← Back to Blog

Your First Backtest: From Idea to Results

In the last post, we covered what algorithmic trading is and set up a basic environment. Now it's time to do something with it. In this post, you'll write a complete AFL strategy, run it through AmiBroker's backtester, and learn how to read the results without fooling yourself.

We'll keep the strategy dead simple on purpose. The point isn't to build something profitable — it's to learn the process. A trader who understands backtesting mechanics can evaluate any strategy. A trader who skips this step is flying blind.

The Strategy: Bollinger Band Mean Reversion

The idea is straightforward: when price stretches too far from its average, it tends to snap back. Bollinger Bands give us a way to measure "too far" — they plot a moving average with bands at a fixed number of standard deviations above and below.

  • Buy when price closes below the lower band (oversold)
  • Sell when price closes above the upper band (overbought)

This is a classic mean-reversion strategy. It won't work in every market condition — trending markets will punish it — but it's a clean, intuitive starting point.

Writing the AFL

Open AmiBroker's Formula Editor (Analysis → Formula Editor) and type the following:

// Bollinger Band Mean Reversion
// Parameters
period = Param("BB Period", 20, 5, 100, 1);
width  = Param("BB Width", 2, 0.5, 4, 0.1);

// Calculate Bollinger Bands
middle = MA(Close, period);
upper  = middle + width * StDev(Close, period);
lower  = middle - width * StDev(Close, period);

// Trading rules
Buy  = Cross(lower, Close);   // Close drops below lower band
Sell = Cross(Close, upper);   // Close rises above upper band

// Position sizing: invest full equity per trade
SetPositionSize(100, spsPercentOfEquity);

// Plotting
Plot(Close, "Price", colorDefault, styleCandle);
Plot(middle, "Middle", colorGrey50, styleLine);
Plot(upper, "Upper", colorRed, styleDashed);
Plot(lower, "Lower", colorGreen, styleDashed);

Let's break this down line by line.

Param() creates adjustable parameters in AmiBroker's Parameters dialog. Instead of hardcoding values, you can tweak them from the GUI. The BB Period (20) controls how many bars the moving average looks back. The BB Width (2) sets how many standard deviations the bands sit from the middle.

Cross(lower, Close) fires when the lower band goes from being below Close to being above Close — meaning price just dropped through the band. This is our buy signal. The sell signal works in reverse.

SetPositionSize(100, spsPercentOfEquity) tells the backtester to invest 100% of available equity per trade. In a real strategy, you'd size more carefully — but for learning, this keeps things simple.

Running the Backtest

Save the formula, then open the Analysis window (Analysis → New Analysis, or Ctrl+R). Here's the step-by-step:

  1. Click the formula picker (top-left of Analysis window) and select your saved formula.
  2. Set the symbol filter — for a first test, pick a single liquid stock or index. NIFTY 50 is a good choice if you have the data.
  3. Set the date range — pick at least 2-3 years of data. More is generally better, but make sure your data quality is consistent across the range.
  4. Open Settings (the gear icon) and set:
    • Initial equity: 100,000 (or whatever feels realistic)
    • Brokerage/commission: set a per-trade cost (even a small flat fee changes results more than you'd expect)
    • Trade delays: set to 1 bar if you want realistic execution (you see a signal on bar N and execute on bar N+1)
  5. Click Backtest.

Within seconds, you'll get a results table. But the numbers mean nothing if you don't know what you're looking at.

Reading the Results: Metrics That Matter

AmiBroker generates dozens of metrics. Most beginners fixate on net profit and ignore everything else. Here are the ones that actually tell you something useful.

Net Profit & CAR (Compound Annual Return)

Net profit is the total money made or lost. CAR normalizes this to an annual percentage, making it comparable across different test periods. A strategy that made 50% over 5 years (8.4% CAR) is very different from one that made 50% over 1 year.

But net profit alone is meaningless without knowing what you risked to get it.

Maximum Drawdown (MaxDD)

This is the single most important risk metric. Maximum drawdown is the largest peak-to-trough decline in your equity curve — the worst losing streak you would have experienced.

A strategy that returns 25% annually with a 15% max drawdown is vastly better than one that returns 40% with a 60% drawdown. Why? Because a 60% drawdown means you'd have watched your account drop from, say, 10 lakhs to 4 lakhs before recovering. Very few people can sit through that without pulling the plug.

Rule of thumb: expect your live max drawdown to be 1.5-2x worse than your backtest drawdown. If you can't stomach that number, the strategy isn't for you.

CAR/MaxDD Ratio

This is return divided by risk. A ratio above 1.0 means you earned more than your worst drawdown. Above 2.0 is good. Above 3.0 is excellent. This single number tells you more than profit and drawdown separately.

Sharpe Ratio

The Sharpe ratio measures risk-adjusted return — how much return you get per unit of volatility. A Sharpe above 1.0 is decent, above 2.0 is strong. Below 0.5, and you're taking a lot of risk for mediocre returns.

One caution: the Sharpe ratio assumes returns are normally distributed, which they rarely are in trading. It's a useful shorthand, not gospel.

Number of Trades

A strategy with 5 trades over 10 years might show amazing returns, but it's statistically meaningless. You need enough trades to trust the pattern is real. As a rough guide: 30 trades is a bare minimum, 100+ is better, and for short-term strategies, you want several hundred.

Win Rate & Profit Factor

Win rate (percentage of winning trades) is the most overrated metric in trading. A strategy can be profitable with a 30% win rate if winners are much larger than losers. Trend-following strategies routinely win only 35-40% of trades but make money because the average win is 3-5x the average loss.

Profit Factor (gross profits / gross losses) captures this better. A profit factor of 1.0 means break-even. Above 1.5 is solid. Above 2.0 is strong.

The Equity Curve

Click the equity chart button in the Analysis window. This is the most honest view of a strategy. Look for:

  • Smoothness — a jagged, volatile curve means inconsistent performance
  • Flat periods — long stretches with no growth suggest the strategy only works in specific conditions
  • Recent performance — if all the profits came from 5 years ago and the curve has been flat since, the edge may be gone

If the equity curve doesn't look like something you'd be comfortable riding with real money, the numbers don't matter.

The Commission Reality Check

Run the backtest twice: once with zero commissions, once with realistic costs. If adding commissions wipes out most of the profit, the strategy has a very thin edge — and thin edges tend to disappear in live trading.

For Indian markets trading options, costs include brokerage, STT, exchange fees, GST, and the bid-ask spread. The spread alone can be several points on less liquid contracts. When in doubt, overestimate your costs. It's better to reject a strategy that might work than to trade one that doesn't.

What This Backtest Doesn't Tell You

A single backtest on fixed parameters has a critical flaw: you chose those parameters after looking at the results. Maybe you tried period 10 first, saw poor results, then tried 20 and got better numbers. That process — even if subconscious — is data snooping.

A single backtest answers the question: "Would these exact parameters have worked on this exact data?" It does not answer: "Is this strategy robust enough to work going forward?"

For that, you need walk-forward analysis — splitting your data into optimization and validation windows, and testing whether optimized parameters hold up on unseen data. We'll cover this in the next post.

Summary

Here's what you should take away from your first backtest:

  1. Max drawdown matters more than profit — it determines whether you can actually trade the strategy psychologically.
  2. CAR/MaxDD is your best single metric — it captures return relative to risk in one number.
  3. Win rate is misleading — profit factor and average win/loss ratio tell the real story.
  4. Always include commissions — a strategy that only works with zero costs isn't a strategy.
  5. Look at the equity curve — if you wouldn't ride it with real money, the numbers don't matter.
  6. One backtest proves nothing — you need out-of-sample validation to trust any result.

What's Next

You've run a backtest. You know what the numbers mean. But you don't yet know if the results are real or just curve-fitting. The next post covers walk-forward analysis — the most important technique for separating strategies that work from strategies that just look like they work.