fX Engineers Explore the community
Project Quant EngineeringData Science

A 120-line backtester, and the four ways it lied to me

I wrote the simplest possible backtester to understand what one does. It reported a Sharpe ratio of 1.9. Every point of it was a bug.

· Python · NumPy · pandas

The problem

I wanted to understand what a backtester actually does, so I wrote one instead of installing one. The strategy did not matter - I used a plain moving-average crossover, the “hello world” of trading strategies, on daily equity data.

The first working version reported an annualised Sharpe ratio of 1.9. For context, that would be a genuinely excellent result for a systematic strategy, produced in an evening by someone who had been studying finance for six weeks. That number was the most useful thing the project produced, because it was obviously too good and forced me to find out why.

The theory

A backtest tries to answer one counterfactual: if I had run this rule in the past, what would have happened? Every bug in a backtest is a violation of the same principle - the simulation used information that would not have been available at the moment of the decision.

That is the whole of it. Lookahead bias, survivorship bias, in-sample optimisation and unmodelled costs are four different ways of leaking the future or the winners into the past.

The architecture

Deliberately minimal, so that any error would be mine and visible:

data.py        load prices, align on a business-day index
signal.py      prices -> desired position, in {-1, 0, 1}
engine.py      positions + returns -> equity curve
metrics.py     equity curve -> CAGR, Sharpe, max drawdown

No classes, no event loop, no vectorbt. Roughly 120 lines. The full version is in the repo.

The build

The core is genuinely small:

import numpy as np
import pandas as pd

def crossover_signal(price: pd.Series, fast: int = 20, slow: int = 100) -> pd.Series:
    """+1 when the fast average is above the slow one, else 0."""
    fast_ma = price.rolling(fast).mean()
    slow_ma = price.rolling(slow).mean()
    return (fast_ma > slow_ma).astype(int)

def backtest(price: pd.Series, signal: pd.Series, cost_bps: float = 0.0) -> pd.Series:
    returns = price.pct_change().fillna(0.0)

    # The single most important line in the file: act on yesterday's signal.
    position = signal.shift(1).fillna(0.0)

    turnover = position.diff().abs().fillna(0.0)
    costs = turnover * cost_bps / 10_000
    strategy_returns = position * returns - costs
    return (1 + strategy_returns).cumprod()

The results

Three versions of the same strategy, on the same data:

VersionSharpeCAGRMax drawdown
First attempt (buggy)1.9024.1%−11%
Bugs fixed, no costs0.447.2%−34%
Bugs fixed, 5bps costs0.315.1%−36%
Buy and hold, same period0.529.0%−34%

The honest version underperforms doing nothing. That is the normal result for a moving-average crossover, and getting to it was the point.

The failure modes

1. Lookahead by one bar. My first version used position = signal rather than signal.shift(1). The signal on day tt is computed from the close of day tt - so trading at that same close means trading on information from the instant you traded. One missing .shift(1) was worth about 0.9 of Sharpe. It is the most common bug in this entire domain and it produces beautiful results.

2. Survivorship bias. I built the universe from a list of companies currently in the index, then pulled ten years of history for them. Every company that was dropped, delisted or went bankrupt was silently excluded - I had backtested a portfolio selected for having survived. Fixing this needs point-in-time constituent data, which is not free, and that finding is itself worth knowing.

3. Parameter mining. I tried 20/100, then 10/50, then 50/200, and kept the best. With 15 combinations on one price series, the best one looks good by construction. The fix is choosing the parameters before looking, or accepting that the reported number is an in-sample maximum and not an estimate of anything.

4. Costs and fills assumed away. Zero commission, zero spread, and an assumption that I get filled at the exact closing price. At 5bps round-trip the strategy loses another 0.13 of Sharpe. High-turnover strategies die entirely at this step, which is why turnover is a first-class number and not an afterthought.

What I learned

  • A backtest is a measurement instrument, and an uncalibrated instrument reads whatever you want. The default failure mode is optimistic, always.
  • Suspicion should scale with the result. A Sharpe above 1 from a simple rule on daily data means look for the bug, not celebrate.
  • Write the honest version first. Costs and the one-bar delay should be in the engine from line one, not added later - by then you are emotionally attached to the number.
  • The bugs are more educational than the strategy. I learned more from four failure modes than I would have from a working crossover.

Next on this: replacing the single train/test split with walk-forward evaluation, which is the subject of the note on random splits.