Run Backtest via Python and save results to variable/array


#1

Hi. I have been using the javascript method to execute my backtests and then store the results to a csv file. Now I'm looking for a mechanism to run the backtest, but then store the results to a variable or array of some sort.

I use the following Python code:

import win32com.client, time

ab = win32com.client.Dispatch("Broker.Application")
time.sleep(3)
NewA = ab.analysisDocs.open( "C:\\path\\file.apx" )
time.sleep(3)
NewA.Run( 2 )
time.sleep(3)
#NewA.Export("C:\\path\\file1.csv")
a = NewA.Export
print (a)
ab.Quit()

When I print this into the IDLE I get the following feedback - <bound method Export of <COMObject >>

My question I guess is whether it is possible to store the results to a variable or array so I print it to the IDLE?

Thanks


#2

@davidp13

the Export() method only returns one or zero. You can surely print that but I doubt that it is what you wanted.

Directly from the AnalysisDoc section of the AmiBroker's OLE Automation Object Model:

Export( pszFileName, whatToExport) method allows to export analysis result list to either .HTML or .CSV file. Returns 1 on success (successful export) or 0 on failure (for example if analysis window is busy).

By the way, instead of unneeded (and/or arbitrary) time.sleep calls you should use the IsBusy property as in the jScript example.

Something along these lines:

from win32com.client import Dispatch
import time

AB = Dispatch("Broker.Application")
AB.Visible = True # will display the AmiBroker UI
try: 
	NewA = AB.AnalysisDocs.Open( "C:\\path\\file.apx" )
	if NewA:
		NewA.Run( 2 ) # 1 is exploration - 2 backtest
		while NewA.IsBusy:
			time.sleep(1)

		export_ok = NewA.Export( "C:\\path\\file1.csv" )
		NewA.Close()
		
		print ('AmiBroker Analysis Export result {}'.format( export_ok ))
		
except Exception as e:
	print("AmiBroker EXCEPTION:")
	print(e)

Since the result of the analysis is saved to a file (.csv or .html) you can add some extra lines to your script to directly read the file content (parsing, extracting text from HTML, etc.) and display it as you prefer.


#3

Thanks very much for the feedback and decent code.