Backtesting pitfalls in Python: lookahead bias, overfitting and survivorship
Why most backtests look better than reality: lookahead bias, missing costs, overfitting and survivorship bias, with Python examples of each and how to fix them.
A backtest asks: "if I had followed this rule, what would have happened?" It's the most important tool in quantitative finance, and also the easiest one to fool yourself with. Almost every too-good backtest has one of four problems.
1. Lookahead bias: trading on tomorrow's newspaper
The classic bug: compute a signal from today's close, then earn today's return with it.
# Wrong: positions[i] uses close i, and earns the return that ENDS at close i
strategy = [positions[i] * (closes[i] / closes[i - 1] - 1) for i in range(1, len(closes))]
# Right: positions[i] is known after close i, so it earns close i -> i + 1
strategy = [positions[i] * (closes[i + 1] / closes[i] - 1) for i in range(len(closes) - 1)]It hides in other places too:
- Normalising with the full sample, such as a z-score using the mean of all prices, including future ones.
- Filling missing data with values from later days.
- Fitting a model on the whole history, then "testing" on part of it.
A test catches every variant: changing future prices must not change past positions.
def test_signal_is_causal():
closes = load_closes()
k = 300
changed = closes[: k + 1] + [c * 1.5 for c in closes[k + 1 :]]
assert signal(closes)[: k + 1] == signal(changed)[: k + 1]2. Missing costs
Every trade pays fees and half the bid–ask spread, and large trades move the price. A rough rule:
annual cost drag ≈ trades per year × cost per tradeA strategy that trades 50 times a year at 10 basis points loses about 5% a year before earning anything. Gross backtests overstate every strategy, and high-turnover ones the most. Always compare strategies after costs.
3. Overfitting: the best of a thousand tries
Try enough parameter combinations and one will look brilliant by chance. Picking the maximum of many noisy results is biased upwards, often hugely.
best = max(((f, s) for f in range(2, 60) for s in range(f + 1, 200)),
key=lambda p: growth(backtest(closes, trend(closes, *p))))That's about ten thousand trials on the same data. The defences:
- Train/test split: choose on one period, evaluate once on a later one, parameters frozen.
- Walk-forward analysis: repeatedly fit on a past window and trade the next one, so every result is out-of-sample.
- Fewer parameters with a reason behind them, and an honest count of how many things you tried.
- Show the distribution of results, not just the winner: if hundreds of combinations score nearly as well, the winner is noise.
4. Survivorship bias
Testing on today's index members skips every company that went bankrupt or was removed, and includes every company that joined because it had already done well. The past looks rosier than it was. The fix is a point-in-time universe: the members as they were on each date, delisted ones included.
You can measure the effect yourself: pick the best three stocks of the last two years in hindsight and backtest them from the start. The result looks spectacular, because the selection used the answer.
A checklist before believing a backtest
- Are positions shifted so each signal trades on the next bar?
- Are fees, spreads and turnover included?
- Were the parameters chosen on data the reported result didn't use?
- Was the universe chosen point-in-time?
- Is the Sharpe ratio plausible (below about 2)?
- Does an event-driven run through a broker, with whole shares and cash, roughly agree?
Every item on this list is a module or a project milestone in our Quantitative Programming with Python course, where you'll fix a lookahead bug in a colleague's code, review an overfitted parameter search and build a backtester the risk officer signs off. For the career side, see what a quant developer does.
Questions and answers
- What is lookahead bias in backtesting?
- Using information in a backtest that wasn't available at the time of the decision, most often trading at the same close that a signal was computed from. The fix is to shift positions by one bar so a signal from day i earns the return from day i to day i + 1.
- How do I know if my backtest is overfitted?
- Choose parameters on one period and test them, frozen, on a later one. If the out-of-sample result is far below the in-sample one, or no better than a simple default, the optimisation found noise. Walk-forward analysis repeats this over many windows.
- What is survivorship bias?
- Testing only on assets that still exist today, such as current index members. Companies that failed or were removed are missing, so past performance looks better than it was. Use point-in-time universes that include delisted assets.
- What's a realistic Sharpe ratio for a backtest?
- Sustained Sharpe ratios above 2 are rare, and a backtest above 3 usually has a bug. Check for lookahead, missing costs and overfitting before believing it.
Practise it
Read next
- What is a quant developer? Skills, daily work and how to become one
Quant developers build the data pipelines, backtesters, risk systems and execution tools that trading firms run on. What the role involves, the skills it takes and how to start.
- Big-O in practice: amortised cost, worst cases and memory
What Big-O tells you on the job: the costs of common operations, amortised O(1), inputs that trigger the worst case, memory as a cost, and when to measure instead of guessing.
- Testing with pytest: run, read and write Python tests
How to run pytest, read a failing test, select tests with markers and -k, share setup with fixtures, cover many cases with parametrize, and test exceptions.