Trouble exporting Result List using Batch (ShellExecute)

Hi,

I wish to export my backtest Result list to a csv file using AFL.

I have created a function that creates a Batch file with the Export action:

procedure ExportResultsUsingBatch(outputFile){
	template = 
		"<?xml version=~1.0~ encoding=~ISO-8859-1~?>\n" +
		"<AmiBroker-Batch CompactMode=~0~>\n" +
		"<Step>\n" +
		"<Action>Export</Action>\n" +
		"<Param>" + outputFile + "</Param>\n" +
		"<Param2/>\n" +
		"</Step>\n" +
		"</AmiBroker-Batch>\n";

	xmlContent = StrReplace( template, "~", Chr( 34 ) );

	fh = fopen( "C:/Program Files/AmiBroker/Formulas/Custom/FileExportBatchFile.abb", "w" );
	if( fh )
	{
		fputs( xmlContent, fh );
		fclose( fh );
	}
	else
	{
		Error("Could not open file for writing" );
	}
	
	ShellExecute("runbatch", "C:/Program Files/AmiBroker/Formulas/Custom/FileExportBatchFile.abb", "" );
}

I then run the function in the second part of the backtest:

if( Status("action") == actionPortfolio )
{
    ...  OTHER CODE ...  
	
	ExportResultsUsingBatch("C:/Program Files/AmiBroker/Formulas/Custom/" + "results" + ".csv");
}

My batch file is created correctly and my result list is exported. However, the result list is empty:

I wonder what I might be missing here. Is there perhaps another way to achieve this?

Best regards, Comex

The problem is that you're trying to do things the other way around - completely backwards.

In AmiBroker, the Batch is what controls the Analysis window, not the other way around.

When your AFL reaches the actionPortfolio section, the portfolio backtest is still running. At that point the analysis process has not finished yet, so the Results list has not been finalized. Consequently, when you launch a batch with the Export action from inside the portfolio backtest, there are simply no completed results available to export, which is why you get an empty CSV.

In other words, you should not try to run a batch from within a portfolio backtest. That approach is fundamentally backwards.

The correct workflow is:

  1. A Batch starts and controls the Analysis window.
  2. The batch runs the backtest.
  3. After the backtest has completed and the Results list exists, the batch performs the Export action.

So instead of having the AFL invoke a batch, make the batch invoke the backtest and then export the results as the next batch step. That way the export occurs only after the analysis has finished and the Results list is available.

Thank you for the clarification and the prompt reply!