← All lessons

Rules as code

A backtest is only as honest as the rules a computer can follow. · 7 min

A backtest replays history and trades it by rule. A computer cannot interpret “buy the dip” or “use a sensible stop”. Every decision must be written down so that two people coding the same rule get the same trades.

Predict first

A rule says: buy after an up close, stop 2 ATR below, target 2R, exit after 10 days. On a market with no edge, what will its expectancy be?

Questions every rule must answer

  • When is the signal known? At a close, so orders go in at the next open.
  • What price fills? Market orders pay slippage; a gap through a stop fills at the open, not at the stop.
  • What if stop and target are both inside one candle? A daily candle does not say which came first. Our tests assume the stop (the cautious reading).
  • Can trades overlap? Ours take one at a time.
  • What happens at the end of the data? An open trade is closed at the last close, not dropped.

Backtest a rule

A long-only daily rule on ten years of simulated candles, with the same fills as the chart simulator. Results in R; the equity curve risks 1% per trade.

The rule as steps
  1. At each daily close, check the signal: Up close.
  2. If it fires, buy at the next open (paying slippage).
  3. Stop: 2 × ATR(14) below the order price, measured at the signal close.
  4. Target: 2R above the entry (a resting limit order, no slippage).
  5. Each later day: a gap through the stop fills at the open; then a touch of the stop (checked before the target, the cautious reading) or of the target.
  6. Still open after 10 days: sell at that close.
  7. One trade at a time; the next signal counts only after the exit.

Running the numbers…

Worked example

First trade: signal at the close of day 16. Buy at the next open: 97.95 (including slippage). Stop 94.95, target 103.95.

Risk = 97.95 − 94.95 ≈ 3.00 per share. The trade ran 10 days without touching either level and was sold at the close, 98.58 (time exit): +0.21R after costs.

Common mistake

Letting the target win the tie. When a daily candle spans both your stop and your target, a backtest that assumes the target was hit first turns losers into winners. Unless you have the intraday path, assume the stop. The chart simulator does the same, minute by minute.

Which rule is ambiguous?
Your stop is at 48. The stock closes at 50 and opens the next day at 45. Where does a correct backtest fill the stop?

Closing round

Find the flawed backtest

Three reports on the same ten years. One of them could never be traded as written.

Building a fresh case…

Further reading: Chan, Quantitative Trading, chapter 3 (backtesting).