Quant notes · 03 · interactive

Backtest errors and controls

A backtest applies a trading rule to past prices using, on each day, only information available on that day, and deducts transaction costs. This page builds one on a six-day example, then presents four sources of error (look-ahead, omitted costs, selection among trials, aggregation over regimes), the controls for each, and their implementation in the project backtester. Labs use simulated series.

All series on this page are simulated so the "true" answer is known. Nothing here is market data or a performance claim.

1 · Structure of a backtest

Each column uses only the columns to its left, and each row is one day. Read left to right: price → return → signal → position → turnover → cost → gross → net → equity. Two columns carry all the honesty. Position is yesterday's signal, because you decide at the close and hold from the next day. Cost is charged every time the position changes.

Lab A · Six days by hand

the project's worked example

The six prices and the signal are the ones in the project's Code Walkthrough. Change a price, click a signal to cycle it through +1 / −1 / 0, or change the cost, and watch every column to the right recompute. The highlighted column is the one-bar lag.

Reset
DayPriceReturnSignalPositionTurnoverCostGrossNetEquity
1.0064equity after day 6 (growth of $1)
0.30%total paid in costs
1long-to-short flips (each costs double)
Read the table.Day 2's signal says +1, but the position on day 2 is still 0: the decision is made at day 2's close and held from day 3. On day 4 the signal flips to −1 while the position is still +1, so the model is long on a day it has decided to go short; the short is held from day 5. A flip from +1 to −1 is a turnover of 2 (close the long, open the short), so it costs twice a plain entry. With 10 bps costs the walkthrough's equity ends at 1.0064; set costs to 0 and it ends at 1.0094.
positiont = targett−1

The one line that makes the backtest honest. The target computed from day t−1's close is the position held during day t. In pandas it is target.shift(1).

nett = positiont · rt − |Δpositiont| · c − |positiont| · carrybars per year

Today's profit is the position held times today's return, minus a cost on every change of position, minus a daily slice of the financing or funding for holding it. Equity is the running product of (1 + net).

2 · Error 1: look-ahead

Look-ahead bias is the most common and the most flattering error. Delete the lag and the position on day t is computed from day t's own close, so the rule is trading on a price it has not seen yet. The lab below runs the same rule twice on a market that has no trend at all, so an honest rule should make nothing.

Lab B · The same rule, with and without the lag

simulated · no edge in the data
cheating: position uses today's closehonest: position is yesterday's decision
–cheating Sharpe (annualised)
–honest Sharpe
–cheating total profit
–honest total profit
What you are seeing.The market here is a pure random walk with the trend dial at zero: there is nothing to find. The honest line wanders around zero, as it should. The cheating line climbs steadily with a Sharpe ratio no real strategy has, because with a one-day lookback it is literally "buy on days the price went up", decided after the price went up. Try lookback 1 for the purest version. This is the bug that every backtest skeleton on the four "Quantitative Finance Essentials" slides had, and why the project's backtester tests that position == signal.shift(1) on every run.

3 · Error 2: omitted costs

Every change of position pays the spread and slippage, and holding a position overnight pays financing (a CFD on gold) or funding (a bitcoin perpetual). A rule that trades often can be profitable before costs and a steady loser after them. The project's starting assumptions are about 5 bps per trade on bitcoin spot and about 3 bps on gold, plus carry.

Lab C · Gross versus net

simulated · trending market
gross: before costs and carrynet: what you would have kept
–turnover per year (units traded)
–cost drag per year
–carry drag per year
–net Sharpe
What to try.Lookback 5 at 10 bps: high turnover, the gap between the lines widens every month. Now set costs to 30 bps, three times the estimate: the repo rules say every robustness check includes double and triple costs, and this is why. A rule that survives 3× costs is slow enough to be real. Then try lookback 100: fewer trades, smaller gap, slower reaction. Cost is the reason the plan's models are daily and not minute-by-minute.

4 · Error 3: selection among trials

This one is subtler because nothing in the code is wrong. Test twenty variations of a rule on the same data and one of them will look good by luck. Report only that one and you have a backtest that is "worthless, regardless of how excellent the reported performance might be" (Bailey and López de Prado 2014). The question an honest report must answer is: how many things did you try?

Lab D · The best of N coin tosses

simulated · no edge in the data

Each trial is a strategy that flips a coin every day to decide long or short, on a market with no trend. Every one of them has a true Sharpe of zero. The chart shows the Sharpe ratio each trial happened to get over about two years; the orange bar is the best one, the one you would be tempted to report.

–best Sharpe found (pure luck)
–expected best, from the formula
–noise in one Sharpe estimate over this sample
–median Sharpe (the truth is 0)
E[max SR] ≈ σSR · [ (1 − γ) Z−1(1 − 1N) + γ Z−1(1 − 1N · e) ]

The expected best Sharpe among N skill-less trials (Bailey and López de Prado 2014, with γ ≈ 0.5772 the Euler–Mascheroni constant and Z−1 the inverse normal). It grows like √(2 ln N): slowly, but it never stops. σSR is how noisy one Sharpe estimate is on your sample length; over two years of daily data it is about 0.7, so the best of 20 coin tosses is expected to show a Sharpe near 1.3, and the best of 300 near 2.1. The Deflated Sharpe Ratio turns this around: given N, how likely is it that your observed Sharpe beats what luck alone would have produced?

A concrete rule from the sources.Pseudo-Mathematics and Financial Charlatanism works out the backtest length you need so that the best of N skill-less trials does not reach a Sharpe of 1 in sample. Their worked figure: with five years of data, try no more than about 45 independent configurations. López de Prado (2018) adds that it typically takes about 20 iterations of the test-and-tweak loop to discover a false strategy at the standard 5% significance level. The project's answer is the research log: every test is one line, kept whether it failed or not, so N is always known.

5 · Error 4: aggregation over regimes

A full-history Sharpe of 0.8 can hide a rule that made everything in 2020–21 and lost in every other year. The defences are cheap: the yearly table (each year's return and worst drawdown), and keeping a period of data the rule never saw while it was designed. The project's walk_forward does the second one mechanically. Click a stage.

And the caveat on the caveat.Walk-forward is not a licence to iterate. López de Prado (2018), pitfall 9: a walk-forward tests a single historical path, which can still be overfit, and "it does not matter if the backtest is a walk-forward out-of-sample": repeating the test-and-tweak loop on the same data will still produce a false discovery. Walk-forward answers "would this parameter choice have been made in time?". It does not answer "how many rules did you throw away first?". Only the log answers that.

6 · Error sources and controls

The four above plus three that are specific to this project's data. Click each for the check that catches it.

In this project

How backtest.py spells each defence.The lag: pos = target.shift(1).fillna(0.0), applied once to the whole target, which already contains the signal and the volatility scaling. Costs: turnover = pos.diff().abs() and cost = turnover * cost_bps / 1e4, so a +1 to −1 flip is charged as 2. Carry: pos.abs() * carry_annual / bars_per_year, with 365 bars because the daily table has one row per calendar day. Closed days: pos.where(tradable).ffill() freezes gold's position over the weekend, the fix for the week-1 bug that had the model paying the spread twice a week. Sizing: vol_target / realised_vol, an EWMA with span 30, clipped at a leverage of 2. Multiple tries: walk_forward() picks parameters on a training window and keeps only the forward slice; notes/research_log.md keeps the count. Two of the twenty tests are the ones to remember: buy-and-hold with zero costs must reproduce the asset's return exactly, and the position column must equal the shifted signal on every day.

7 · Implementation

# the whole backtester in nine lines (no vol sizing, no closed-day mask)
ret      = px.pct_change().fillna(0.0)
sig      = signal.reindex(px.index).fillna(0.0)      # +1, -1, 0 or a fraction
pos      = sig.shift(1).fillna(0.0)                  # the lag: held during t = decided at t-1
turnover = pos.diff().abs().fillna(pos.abs())
cost     = turnover * cost_bps / 1e4
carry    = pos.abs() * carry_annual / 365
net      = pos * ret - cost - carry
equity   = (1 + net).cumprod()
sharpe   = net.mean() * 365 / (net.std() * 365 ** 0.5)

# the two sanity tests that catch most bugs
assert (pos == sig.shift(1).fillna(0.0)).all()      # no look-ahead
# buy-and-hold with cost_bps=0, carry=0: equity.iloc[-1] == px.iloc[-1] / px.iloc[0]

8 · Terminology

Each entry: the technical definition first, then the same idea in everyday words in the orange strip.

backtesta historical simulation of a rule, using at each step only information available at that step, net of costs.replaying the past with your rule, honestly, to see what it would have done.
in-sample / out-of-samplethe data used to design the rule / data it never saw during design.the part of history you studied, and the part you kept hidden from yourself for a fair test.
look-ahead biasusing information that was not yet available at decision time.letting the test read tomorrow's newspaper.
turnoverthe absolute change in position per day; per year, the sum.how much buying and selling the rule does. Every unit of it costs money.
bpsbasis points: 1 bp = 0.01%.a hundredth of a percent. 10 bps on a $10,000 trade is $10.
carrythe cost (or income) of holding a position overnight: financing on a CFD, funding on a perpetual.rent for keeping the position open.
Sharpe ratiomean return over its standard deviation, annualised.profit per unit of bumpiness. Noisy: over two years of daily data one estimate is easily ±0.7 off.
multiple testingthe inflation of the best result when many hypotheses are tested on the same data.try enough things and one looks great by accident.
Deflated Sharpe Ratiothe probability that the true Sharpe exceeds the level luck alone would produce, given the number of trials and the non-normality of returns.your Sharpe, discounted for how many tries it took and how fat-tailed the returns are.
walk-forwardselecting parameters on a training window, testing on the next window, sliding, and keeping only the test slices.pretend you are at each point in the past, choose with only what you had, then see what happened next.
yearly tableeach calendar year's net return and maximum drawdown.did it work most years, or in one lucky year?

Sources

Bailey & López de PradoD. Bailey, M. López de Prado, "The Deflated Sharpe Ratio: Correcting for Selection Bias, Backtest Overfitting and Non-Normality", Journal of Portfolio Management (2014). The expected-maximum formula in Lab D; "the most important piece of information missing from virtually all backtests … is the number of trials attempted".
Bailey, Borwein, López de Prado & Zhu"Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance", Notices of the AMS 61:5 (2014). In-sample versus out-of-sample; Minimum Backtest Length and the five-years / 45-trials figure.
Bailey, Borwein, López de Prado & Zhu"The Probability of Backtest Overfitting", Journal of Computational Finance (2015). The combinatorial method for estimating how likely a chosen configuration is to underperform out of sample.
Harvey & LiuC. Harvey, Y. Liu, "Backtesting", Journal of Portfolio Management 42:1 (2015). The 50% haircut rule of thumb and why the correct haircut is non-linear: marginal Sharpe ratios are penalised heavily, very high ones only moderately.
López de PradoM. López de Prado, "The 10 Reasons Most Machine Learning Funds Fail" (2018). Pitfall 2 (research through backtesting, "about 20 iterations"), pitfall 9 (walk-forward tests a single path) and pitfall 10 (backtest overfitting).
Project notesThe Code Walkthrough doc (backtest.py, the six-day worked example, the tests) and notes/research_log.md in xau-btc-models.

All charts on this page are generated from simulated series inside the page; no market data is used. Part of quant-notes. See also 01 · Time-series momentum (the rule being tested) and 02 · Volatility estimation by EWMA (the volatility that sizes it).