Automate an Amibroker Backtest
By Dave Mabe
One of the many nice things about Amibroker is its developer-friendly attitude.
A great example of that is the fact that you can automate backtests (or explorations) from a scripting interface.
This allows you to create scheduled tasks to run backtests or open several analysis windows exactly as you'd like each day.
Here's some Python code that does the following:
Connects to an already started Amibroker instance
Opens an APX file (an Analysis window you've saved previously)
Runs a backtest (same as clicking the Backtest button manually in the program)
Saves the results to a CSV file
Closes the Analysis window
To simply open the APX file instead of running a backtest, comment out the line with the call to Run and the remaining lines in that function.
import argparse
import sys
import time
import win32com.client
BACKTEST_ACTION = 2
def main():
parser = argparse.ArgumentParser(description="Run AmiBroker backtest and export CSV")
parser.add_argument("apx_file", help="Path to .apx analysis project file")
parser.add_argument("--output", "-o", help="Output CSV path (default: same name as APX)")
args = parser.parse_args()
from pathlib import Path
apx_path = Path(args.apx_file).resolve()
if not apx_path.exists():
print(f"ERROR: APX file not found: {apx_path}", file=sys.stderr)
sys.exit(1)
output = args.output or str(apx_path.with_suffix(".csv"))
ami = win32com.client.Dispatch("Broker.Application")
analysis = ami.AnalysisDocs.Open(str(apx_path))
analysis.Run(BACKTEST_ACTION)
while analysis.IsBusy:
time.sleep(1.0)
analysis.Export(output)
analysis.Close()
print(f"Results saved to: {output}")
if __name__ == "__main__":
main()For information on all functions available via this interface, check out the documentation.
-Dave
P.S. Why is every other trader printing money while you’re stuck? Close the gap with MabeKit.