Systems & building

Backtesting & simulation

∞structural
By . Reviewed 22 October 2026. As of 2026: a permanent feature of the market, not an edge that decays.

Toggle look-ahead, survivorship and optimistic fills and watch a fake edge appear. The hardest part of research is not finding an edge. It is not lying to yourself about one.

See it move

Conjure a fake edgetoggle the sinsIX-BACKTEST
Backtest verdictflat / honest
Realityno edge here
dashed = honest backtest

What to notice. Turn on any of the three classic backtest sins and a flat strategy sprouts a beautiful upward equity curve. None of it survives live. The hardest part of research isn't finding an edge; it's not lying to yourself about one.

What is a backtest, and why does it lie so easily?

A backtest replays a strategy over historical data to estimate how it would have performed. It lies easily because nearly every shortcut in the simulation flatters the result in the same direction, toward a higher and smoother return, and because you can keep adjusting the test until it looks good. The discipline is to make the simulation pessimistic and judge it on data you never touched.

A backtest is a story about the past, and you control every detail of the telling. Each convenient assumption ("I'd have been filled", "costs are negligible", "I'd have known by then") nudges the story toward profit. Stack a few and you have a beautiful equity curve that describes nothing real. Most of the common errors bias the result upward, so a backtest's default state is "too good" and your job is to push it back toward reality.

The deepest trap is the process rather than any single error. You tweak, re-run and tweak again, and every adjustment that improves the backtest is a fit to that specific history. By the time it looks great you have overfit it without noticing. Harvey and Liu (2015) is a good starting point on why the number of strategies tried has to be allowed for. Every signal in the strategies section has to survive the checks on this page. In the explorer above, the toy strategy's true edge is exactly zero by construction, so every gain you can produce is an artefact of one of the problems below.

What is look-ahead bias?

Look-ahead bias is using information in a decision that you would not actually have had at that moment, and it is the most common and most damaging backtest error. Using a bar's close to decide a trade within that bar, applying a restated figure as of its event date, or using a statistic computed over the whole sample all let the strategy see the future. The results are spectacular and entirely fictional.

The classic forms are easy to write by accident. You decide today's trade with today's close, which is unknown until the day ends. You use a corporate figure as of its event date when it was published days later. You compute a normalisation (a mean, a standard deviation, a model fit) over the entire dataset and use it at every point in time, so the in-sample statistic leaks the future into the past.

A tiny leak produces an enormous, smooth edge, because the strategy is effectively told the answer. In the explorer above, look-ahead alone lifts the toy strategy's Sharpe from about zero to about three.

The defence is point-in-time, causal evaluation: at every simulated instant tt, the strategy may use only information that was actually observable by then.
decisiont=f(Ft),Ft={information observable up to and including t}\text{decision}_t = f\big(\mathcal{F}_t\big), \qquad \mathcal{F}_t = \{\text{information observable up to and including } t\}

Use point-in-time datasets, lag every value to its real availability, and compute statistics on a rolling or expanding window that never peeks ahead. A faithful market-replay simulation enforces this structurally, because it feeds events in time order and nothing later exists yet.

What is survivorship bias?

Survivorship bias is backtesting only on the instruments that survived to today, silently excluding everything that was delisted, went bankrupt or was acquired. With the failures removed, every strategy looks safer and more profitable than it was, especially one that buys distressed or falling names. Brown, Goetzmann, Ibbotson and Ross (1992) is the classic study of how this distorts performance evidence.

If you study only the companies that exist today you have pre-selected for survival. A "buy the dip" strategy looks brilliant when every name that dipped to zero has been deleted from the data: you never see the ones the dip killed.

It bites hardest on mean-reversion and value strategies that lean toward beaten-down names, and on any equity universe built from current index membership and applied to the past, where former members who were later dropped are simply gone. It also lurks in crypto (dead tokens, defunct venues) and is easy to introduce by accident.

The defence is a point-in-time universe: the instruments that actually existed and traded at each date, including those that later died, with their full price-to-zero history. Survivor-free databases exist for equities; for crypto you must deliberately retain delisted assets. In the explorer above, drop the "dead" symbols and the curve improves; restore them and the losses reappear.

What are unrealistic fills, and why is queue position the heart of it?

Unrealistic fills assume you traded at prices or sizes you would not have got: filling at the mid, always getting the touch, zero slippage, no queue. For passive (limit-order) strategies this is fatal, because whether a resting order fills at all depends on its place in the queue, and assuming it always fills invents the entire edge.

The optimistic-fill family is large. A market order filled at the mid instead of paying the spread. A large order that ignores how it walks the book. A limit order at the touch that always executes. Each ignores a real cost, and the spread you ignored is often the whole strategy: a market-making backtest that fills at mid collects an imaginary spread.

Queue position is the crux for passive strategies. A limit order joins the back of the queue at its price and fills only after enough volume trades through ahead of it. Your fill rate, and which fills you get, depend on where you sat. Assuming you are always filled hands you the good fills and spares you the bad ones, which inverts adverse selection: in reality you tend to be filled just as the market is about to move against you.

Your order fills only once the cumulative volume traded at your price level exceeds the quantity queued ahead of you. A bar backtest cannot represent this quantity at all.
fill  ⟺  ∑(volume traded through your level)  >  Qahead\text{fill} \iff \sum (\text{volume traded through your level}) \;\gt \; Q_{\text{ahead}}

Queue and fill modelling is therefore the hardest and most important part of a microstructure backtest. Cont, Stoikov and Talreja (2010) model the book as a queueing system and compute execution probabilities from it, and the open-source hftbacktest project accounts for limit orders, queue positions and latencies using L2 or L3 tick data. You need arrivals, your position, cancellations ahead of you and the probability of execution, ideally from L3 market-by-order data. The defence is conservative assumptions: you are not filled unless the simulation shows the queue cleared past you; you pay the spread and fees; you model partial fills; and you prefer a market-replay test that rebuilds the actual book over a bar-based one that cannot represent the queue.

Why does latency belong in the backtest?

Because in reality there is a delay between seeing a signal and your order reaching the matching engine, and the market moves in that gap. A backtest that acts instantly on every signal captures opportunities that, by the time your order arrived, were already gone, taken by faster players. Modelling your real latency is part of an honest fill model.

Suppose you see a stale quote and "trade" against it in the backtest at time TT. Your order does not reach the venue until T+ℓT + \ell, where ℓ\ell is your latency, and by then the quote you targeted has probably been updated or taken. The backtest filled you; reality would not have.

This is the backtest face of the latency and colocation story. An instantaneous backtest assumes you are infinitely fast, which silently grants you every latency-arbitrage opportunity. Put in your actual tick-to-trade and most speed-dependent edges vanish for anyone outside the speed tier.

The defence is to delay every decision by a realistic latency before it can act, and to fill only against the book as it was when your order would truly have arrived, something a faithful market-replay simulation does naturally.

What is overfitting, and why is multiple testing now the biggest danger?

Overfitting is tuning a strategy to the noise in your historical sample rather than to a repeatable pattern. The mechanism is multiple testing: try enough variations and the luckiest will look brilliant in-sample by chance. Automated and AI-assisted strategy search now makes trying thousands of variants effortless, which makes this the dominant way backtests lie today.

Flip 1,000 coins ten times each and the best coin will have a great run, not because it is a good coin but because you searched 1,000 of them. Search 1,000 parameter sets and the best in-sample Sharpe is the same illusion: you found the luckiest configuration, not an edge.

The statistics make this precise. The expected maximum of NN noisy results grows with NN, so the more strategies you try, the higher the best in-sample performance you will see even when every true edge is zero. White (2000) built his "Reality Check" for exactly this problem, a test of whether the best of many tried rules really beats a benchmark once data snooping is allowed for. Bailey and López de Prado (2014) offer a more direct correction, the deflated Sharpe ratio, which adjusts the observed Sharpe for the number of trials and the non-normality of returns.

▸ Show the maximum-of-N argument and the deflation optional

Suppose you run NN independent strategies, each with a true Sharpe of zero, and each estimated Sharpe is approximately Gaussian noise with standard deviation σ^SR\hat{\sigma}_{SR} across the trials. The expected best of the NN is not zero; it grows like the maximum of NN standard normals.

E ⁣[max⁡i≤NSR^i]≈σ^SR[(1−γ) Φ−1 ⁣(1−1N)+γ Φ−1 ⁣(1−1Ne)]\mathbb{E}\!\left[\max_{i\le N} \widehat{SR}_i\right] \approx \hat{\sigma}_{SR}\left[(1-\gamma)\,\Phi^{-1}\!\left(1-\tfrac{1}{N}\right) + \gamma\,\Phi^{-1}\!\left(1-\tfrac{1}{N e}\right)\right]

where Φ−1\Phi^{-1} is the inverse normal CDF and γ\gamma is the Euler–Mascheroni constant. This rising threshold is the bar a real edge must clear. The deflated Sharpe ratio turns an observed Sharpe into the probability that the true Sharpe exceeds zero, after accounting for that bar, the number of trials, and the skew and kurtosis of the returns.

DSR^=Φ ⁣((SR^−SR0)T−11−γ^3 SR^+γ^4−14 SR^ 2)\widehat{DSR} = \Phi\!\left(\frac{\big(\widehat{SR} - SR_0\big)\sqrt{T-1}}{\sqrt{1 - \hat{\gamma}_3\,\widehat{SR} + \tfrac{\hat{\gamma}_4 - 1}{4}\,\widehat{SR}^{\,2}}}\right)

Here SR0SR_0 is the inflated benchmark from the maximum-of-N expression above, TT is the number of observations, and γ^3,γ^4\hat{\gamma}_3,\hat{\gamma}_4 are the skewness and kurtosis of the returns. The paper's own numerical example makes it concrete: a strategy with an annualised Sharpe of 2.5 over five years of daily data (T = 1,250) turns out, once the number of trials is counted, to have only about a 90% chance that its true Sharpe exceeds zero, short of the usual 95%. Had the analyst run only 46 trials, the deflated Sharpe would have been 0.9505. Reference: Bailey and López de Prado, "The Deflated Sharpe Ratio" (2014).

Cheap search makes this worse. The thing that used to limit overfitting, the effort of running each test, is gone, so the discipline has to come from method rather than friction (see what AI changes for HFT). Bailey, Borwein, López de Prado and Zhu propose combinatorially symmetric cross-validation to estimate the probability of backtest overfitting, the chance that the in-sample winner underperforms out of sample. The practical defences are concrete. With out-of-sample hold-out, you fit and tune on one period and evaluate once on a period you never touched; touching the hold-out more than once destroys it, because every peek is another test. Walk-forward validation rolls the train and test windows through time so each evaluation is out-of-sample across regimes. Count your trials honestly and deflate the Sharpe for them. And prefer simple, economically motivated strategies with few parameters: there is less to overfit, and a reason it should work beyond "it fit the past".

What is market-replay simulation, and how does it differ from a bar backtest?

Market-replay simulation feeds the recorded message stream (every order, cancel and trade, in time order) through your system exactly as it happened, and matches your orders against the reconstructed book as it evolves. Unlike a bar-by-bar backtest, it can represent the queue, the spread, partial fills and latency, which decide a high-frequency strategy's real P&L.

A bar backtest is the crude tool. With OHLCV bars you assume fills at the open, close or mid, and you cannot see the spread, the queue or intrabar dynamics, so it cannot honestly test any passive or latency-sensitive strategy. It is fine for slow, signal-driven equity strategies and useless for market making.

A market-replay, event-driven simulation replays the recorded tape message by message, rebuilds the book at every instant and injects your orders into it. They take a queue position, wait their turn, fill or not as real volume trades through, and pay real fees, after your real latency. This is the same event-driven design as the live system, so the simulator and production share the strategy code and you test what you will run.

The hard part is whether your order changes the market. The simplest and most conservative assumption is that your orders take liquidity and queue position but do not make others react. Modelling market impact and others' responses is harder and matters more as your size grows (see capacity). That is why the build order puts record-and-replay and the harness before the strategy: the simulator is the instrument that tells you whether anything is real.

What is conformance and exchange certification testing?

Before a venue lets your system trade live, it usually requires conformance testing: you connect to its test environment and prove that your system speaks the protocol correctly, handles every order type and message, and behaves under error and recovery conditions. It validates correctness and safety, where backtesting validates the strategy.

In the EU this is a legal duty on both sides. RTS 7 (Delegated Regulation 2017/584, Article 9) requires trading venues to make members undertake conformance testing before deploying or substantially updating their systems, and to provide a testing environment. The checks cover order submission, modification and cancellation, market-data handling, the cancel-on-disconnect command, market-data feed loss, throttles and recovery. RTS 6 Article 6 puts the matching duty on the investment firm. Rule 15c3-5 and RTS 6 risk-control obligations are covered in building a trading system.

The two tests answer different questions. Backtesting asks whether the strategy makes money; conformance asks whether the system behaves correctly against the real venue. You need both, since a profitable strategy on a non-conformant system is a regulatory and operational problem waiting to happen. For a solo builder, crypto and prediction-market venues ask for far less formal certification than regulated equity and futures exchanges, one more reason they are the accessible starting point, but you still owe yourself the equivalent self-test against the venue's sandbox before risking capital.

Worked example: one strategy with zero edge

Take a toy strategy with a true edge of exactly zero and run it through the explorer above, switching on each problem in turn. Because it provably cannot make money, every gain below is a measured artefact. The figures are illustrative and reproducible from the widget's seed.

The honest configuration (out-of-sample, real fills, costs and latency) reports a Sharpe of about zero and an annual return of roughly zero minus costs. That is the truth. Add look-ahead bias alone and the Sharpe jumps to about three on a large, smooth curve, the strategy seeing the future. Add optimistic fills alone (mid, always filled) and you collect an imaginary spread worth a Sharpe of one to two. Add survivorship alone by dropping the dead names and you get a modest lift, the failures simply deleted. Add overfitting by keeping the best of 200 random parameter sets and the best in-sample curve looks great: the maximum-of-N illusion.

All sins on produces a beautiful in-sample curve at a Sharpe near three. Evaluate that same configuration out-of-sample and it collapses to zero: the cliff. The edge was never there.
SRin-sample, all sins≈3⟶SRout-of-sample≈0SR_{\text{in-sample, all sins}} \approx 3 \qquad\longrightarrow\qquad SR_{\text{out-of-sample}} \approx 0

The out-of-sample column is the only one that means anything. A backtest is guilty until proven innocent on data it has never seen, with realistic fills, costs and latency and an honest count of how many times you tried. The widget lets you produce every row yourself, and the numbers are a fiction you can audit because the true edge is zero by construction.

Sources

  1. Bailey, D. H. and López de Prado, M. (2014). "The Deflated Sharpe Ratio: Correcting for Selection Bias, Backtest Overfitting, and Non-Normality". Journal of Portfolio Management 40(5), 94–107. doi.org
  2. Bailey, D. H., Borwein, J. M., López de Prado, M. and Zhu, Q. J. (2017). "The probability of backtest overfitting". Journal of Computational Finance 20(4). doi.org
  3. White, H. (2000). "A Reality Check for Data Snooping". Econometrica 68(5), 1097–1126. doi.org
  4. Harvey, C. R. and Liu, Y. (2015). "Backtesting". Journal of Portfolio Management 42(1), 13–28. doi.org
  5. Brown, S. J., Goetzmann, W., Ibbotson, R. G. and Ross, S. A. (1992). "Survivorship Bias in Performance Studies". Review of Financial Studies 5(4), 553–580. doi.org
  6. Cont, R., Stoikov, S. and Talreja, R. (2010). "A Stochastic Model for Order Book Dynamics". Operations Research 58(3), 549–563. doi.org
  7. Commission Delegated Regulation (EU) 2017/584 (RTS 7, organisational requirements of trading venues), 14 July 2016. eur-lex.europa.eu
  8. hftbacktest, open-source backtester for limit orders, queue positions and latencies. github.com

Where this fits