Your First Backtest
Run a full backtest in the Analysis window, set the date range and settings, and see your equity curve.
- ·From chart to backtest
- ·Backtest settings
- ·Date range & periodicity
- ·Running a backtest
- ·The equity curve
- ·Common setup mistakes
You have written a system, cleaned its signals, added stops, and chosen a position size. Now comes the moment of truth: you press one button and AmiBroker walks through years of history, taking every trade your rules would have taken, and hands you a complete performance report. This is backtesting, and it is the single most useful thing AFL can do.
AmiBroker's backtester is portfolio-level by default: it can simulate a basket of symbols sharing a single equity pool, rank them, and rotate capital between them - not merely test one symbol in isolation.
The wonderful part is that you do not write any new strategy code. The exact same formula you applied to a chart becomes a backtest simply by running it in a different window and pressing a different button. Remember the very first chapter: one formula, four jobs. This is the fourth job.
From chart to backtest
A chart and a backtest run identical AFL - the difference is where you run it. To backtest, you do not Apply the formula to a chart; you load it into the Analysis window.
- Open Analysis -> New Analysis (or the Analysis toolbar button). A window appears with a code pane and a row of buttons: Explore, Scan, Backtest, Optimize.
- Pick the formula to run - either paste your system into the code pane, or use Pick to point at your saved
.aflfile. - Choose what symbols and dates to test (the Filter and range controls, covered below).
- Press Backtest.
That is it. The engine reads your Buy, Sell, Short, Cover arrays, applies your SetPositionSize and SetTradeDelays, simulates every trade, and produces a report.
The chart shows you one symbol with arrows. The backtest trades those same arrows across your chosen symbols and dates and tallies the result. Same code, same signals - the Analysis window just turns the arrows into a profit-and-loss statement.
The Settings dialog
Before the first run, open Settings (the gear/Settings button in the Analysis window). This dialog holds every assumption the simulation makes. The ones that matter most at the start:
- Initial equity - your starting capital. Set it to something realistic, like 10,00,000.
- Periodicity - the bar size the test runs on: Daily, Hourly, 5-minute, and so on. This must match the kind of system you built. A swing system runs on Daily; an intraday system on minutes.
- Commissions - the cost per trade, so the report is honest about brokerage and charges.
- Trade delays / fill prices - how many bars after a signal a fill happens, and at what price.
Here is the habit that saves hours of confusion: anything you set in this dialog can also be set in the AFL with SetOption and SetPositionSize. When a setting lives in the formula, it travels with the file and overrides the dialog. So put your strategy's core assumptions in code, and use the dialog mainly for the date range and periodicity.
If your backtest and your chart disagree about where trades happen, the usual culprit is a mismatch between the dialog and the code - for example, the dialog says "fill at close" while your formula sets BuyPrice = ValueWhen(Buy, Open). Keeping assumptions in the AFL avoids this whole class of confusion.
Date range and periodicity
Two controls decide what slice of history you test:
- Range - the start and end dates. Use the "From-To" or "n recent bars" options in the Analysis window. Test on a span long enough to include different market moods - a bull run, a correction, a sideways drift - so you are not fooled by a system that only works in one regime. Several years of daily data is a sensible minimum for a swing system.
- Periodicity - the timeframe, as above. Set it to match the timeframe your signals were designed for.
A frequent beginner error is testing a daily swing system on a few months of data, getting a flattering result, and trusting it. A handful of trades in one friendly market tells you almost nothing. Widen the range until the system has been tested across conditions it will actually face.
Running the backtest
Let us run a complete, self-contained EMA crossover system - everything from the last four chapters in one block:
_SECTION_BEGIN("EMA Crossover Backtest");
// account assumptions travel with the formula
SetOption("InitialEquity", 1000000);
SetOption("CommissionMode", 2); // flat fee per trade
SetOption("CommissionAmount", 20);
SetPositionSize(75, spsPercentOfEquity);
SetTradeDelays(0, 0, 0, 0); // we delay signals manually below
Fast = EMA(Close, 10);
Slow = EMA(Close, 20);
// clean, non-repainting signals
Buy = Ref(Cross(Fast, Slow), -1);
Sell = Ref(Cross(Slow, Fast), -1);
Buy = ExRem(Buy, Sell);
Sell = ExRem(Sell, Buy);
// honest next-bar-open fills
BuyPrice = ValueWhen(Buy, Open);
SellPrice = ValueWhen(Sell, Open);
// a safety stop in the backtest
ApplyStop(stopTypeLoss, stopModePercent, 2, True);
_SECTION_END();
Load it, set the periodicity to Daily, choose a multi-year range and a symbol like NSE RELIANCE (or a watchlist of stocks), and press Backtest. In a blink the report appears.
The equity curve
The first thing to look at is the equity curve - a line chart of your account balance over the whole test. Open it from the report (Report -> Equity, or the equity tab). It is the most honest single picture of a system:
- A curve that climbs steadily from bottom-left to top-right, without gut-wrenching drops, is what you want.
- A curve that lurches up once and then drifts sideways was carried by a single lucky trade - not a repeatable edge.
- A curve with one terrifying cliff has a drawdown problem, even if it ends higher than it started.
You read the numbers in the next chapter, but the shape of this line tells you in two seconds whether a system is worth deeper study.
Common setup mistakes
Most "broken" backtests are setup errors, not strategy errors. The usual suspects:
- Forgetting
Sell(orCover). With an entry but no exit, the system buys once and holds forever - one trade, a meaningless report. EveryBuyneeds aSell. - Wrong delays. Mixing a manual
Ref(..., -1)withSetTradeDelays(1,1,1,1)double-delays every fill; check you used exactly one delay style. - No position size. Without
SetPositionSize, the result depends on AmiBroker's default and may not reflect your intended risk. - Periodicity mismatch. Running an intraday system on daily bars (or vice-versa) produces nonsense - the bars are not the ones your signals expect.
- Too short a range. A few months and a dozen trades cannot prove an edge.
A backtest is a simulation of the past, not a promise about the future. Even a clean, honest report only says "these rules would have worked on this data". It is education and research, never investment advice - and a system must still be forward-tested in sandbox trading (analyzer mode in OpenAlgo) before it ever risks real money.
Try it yourself
- Run the EMA system on NSE RELIANCE daily over the longest range you have, then on the NIFTY index. Do the equity curves look alike?
- Delete the
Sellline, re-run, and watch the report collapse to a single open trade - proof that exits matter. - Switch periodicity from Daily to Weekly and re-run. Fewer, larger trades or more? Why?
- Open the equity curve and just look at its shape before reading any number. Steady climb, or one lucky jump?
Recap
- A backtest runs the same AFL as your chart - you just load it in the Analysis window and press Backtest.
- The Settings dialog holds initial equity, periodicity, commissions and delays - but settings placed in the AFL travel with the file and override the dialog.
- Range and periodicity decide the slice of history; test across years and match the timeframe to your system.
- The equity curve is the fastest read on a system - look for a steady climb, distrust a single lucky jump or a deep cliff.
- Most failures are setup mistakes: a missing
Sell, double delays, no position size, wrong periodicity, or too short a range.
Next, we open the full backtest report and learn to read every number in it - net profit, CAR, drawdown, win rate, payoff and the red flags that betray a fragile system.