Multiple Testing in Backtests: Variant Matrix and Corrections
Testing many filter and parameter combinations is legitimate, as long as the evaluation counts every combination you tried. The best of 200 variants looks better than a typical one even if none of them has an edge, and the more variants you test, the better the best one looks. The remedy is a process, not a single statistic: a variant matrix that lists every combination before the run, an evaluation plan written down in advance, data kept back for a final out-of-sample check, and corrections built for exactly this situation, such as White’s Reality Check, Hansen’s test for Superior Predictive Ability (SPA) and the Deflated Sharpe Ratio (DSR). This guide shows how the pieces fit together, includes a tested Python function for the DSR and ends with a checklist. It is about methodology: no test turns a strategy into a promise of returns.
Why does the best of many backtests look too good?
Halbert White described the problem in 2000: data snooping occurs when the same data is used more than once for inference or model selection, and then good results may be due to chance rather than to any merit of the method. In trading research this is practically unavoidable, because there is only one price history. Every filter you switch on, every parameter you vary and every variant you discard reuses that history.
The effect can be quantified. Bailey and López de Prado give an approximation for the expected maximum Sharpe ratio of N independent trials whose true Sharpe ratio is zero. It grows with N and with the variance of the trials’ Sharpe ratios. Worked example, calculated with their formula: if the annualized Sharpe ratios of zero-skill variants scatter with a standard deviation of about 0.71, the best of 10 variants is expected to show an annualized Sharpe ratio of about 1.1, the best of 100 about 1.8, and the best of 1,000 about 2.3. None of these strategies has an edge.
Bailey, Borwein, López de Prado and Zhu turned the same effect into a minimum backtest length in 2014: with only five years of data, no more than 45 independent configurations should be tried, or a strategy with an annualized in-sample Sharpe ratio of 1 is almost guaranteed even though its expected out-of-sample Sharpe ratio is zero. With two years of data, seven configurations are enough for the same result. Their conclusion: a backtest that does not report the number of trials leaves the risk of overfitting impossible to assess.
That is why a single impressive number says little without its context: how many variants were tried, how different they were, and how the winner was chosen. The rest of this guide is about recording that context and correcting for it.
The variant matrix: list every combination before the run
A variant matrix is the complete list of combinations you intend to test, written down before the first run. Its dimensions are the choices you make: filters on or off, parameter values, instruments, timeframes, exit rules and cost assumptions. The number of rows is your first honest count of trials.
Typical example (illustrative, not a recommendation):
| Dimension | Values | Count |
|---|---|---|
| Trend filter | off, on | 2 |
| Lookback of the entry signal | 10, 20 or 50 bars | 3 |
| Stop distance | 1 or 2 times the average true range | 2 |
| Exit | time-based or target-based | 2 |
| Total variants | 2 × 3 × 2 × 2 | 24 |
Each row gets an ID and a log entry when it runs: parameters, code version, data period, cost model, start time, metrics and status. Three rules keep the log honest. Every run is logged, including crashed and discarded ones. A run with changed code or data counts as a new variant, not as a replacement. And variants added after looking at results are marked as such, with the date.
Variants are rarely independent: lookbacks of 20 and 21 bars often produce nearly the same trades. The Deflated Sharpe Ratio paper therefore works with the number of independent trials and explains in an appendix how to estimate it when trials are not independent. Count the raw variants anyway: the effective number is an estimate, the raw count is a fact.
Pre-register the evaluation
Pre-registration means writing down how you will judge the results before you see them. Bailey and López de Prado make the same point about multiple testing: such exercises should be planned in advance, and “investment theory, not computational power” should decide which experiments are worth running.
A one-page evaluation plan, stored with a date in the same repository as the code, should fix at least:
- Hypothesis and benchmark: what the strategy is supposed to exploit, and what it has to beat, for example buy-and-hold or cash.
- Metric: for example the Sharpe ratio after costs, computed on daily returns.
- Cost model: commissions, spread and slippage, set before the run.
- Data periods: the in-sample period, the out-of-sample period and any walk-forward windows, with dates.
- Selection rule: how one variant is chosen, and what happens on ties.
- Correction and threshold: which test, and which p-value or DSR level counts as a pass, decided now and not after the results.
Changing the plan later is allowed. It just has to be documented as a change, with the reason, so that anyone reading the results knows which decisions were made with knowledge of the data.
Out-of-sample and walk-forward: data you use once
The simplest protection is to hold back the most recent part of the history and use it once, for the variant chosen in-sample. The value of that period comes from being untouched. Each time you look at it, adjust something and look again, it becomes part of the search, and the next out-of-sample result is in-sample in disguise.
Walk-forward analysis rolls this idea through time: optimize on one window, test on the next, move on. It shows how a re-optimization rule would have behaved, but every walk-forward setting you try, such as window length or step size, is another variant in the matrix.
Bailey, Borwein, López de Prado and Zhu go further: in their words, standard techniques such as hold-out “tend to be unreliable and inaccurate” for investment backtests. Their alternative, combinatorially symmetric cross-validation (CSCV), works on the matrix of all variants’ returns. It splits the time axis into an even number of blocks, uses every combination of half the blocks as in-sample and the rest as out-of-sample, and measures how often the in-sample winner ranks below the median out-of-sample. That frequency estimates the probability of backtest overfitting (PBO). A high PBO means the in-sample winner tends to do worse than the median variant out-of-sample: the selection mostly picks noise.
Look-ahead errors, where the code uses information that was not yet available, are a separate problem that no statistical correction fixes. The prefix check in the pre-live checklist for AI-built trading bots covers it.
Corrections for many variants: Reality Check, SPA, StepM and DSR
Classical corrections such as Bonferroni divide the significance level by the number of tests. With hundreds of highly correlated variants they become very strict. The methods in the table are built for the typical research situation in trading: many related strategies, one history, one benchmark.
| Method | Question it answers | Input |
|---|---|---|
| White’s Reality Check (2000) | Does the best variant found in the search beat the benchmark, or could its lead be chance? | Performance series of all variants and the benchmark |
| Hansen’s SPA test (2005) | The same question, with studentized statistics and less influence from clearly inferior variants | Same as above |
| Romano and Wolf’s StepM (2005) | Which variants beat the benchmark, with the familywise error rate under control? | Same as above |
| Deflated Sharpe Ratio (2014) | Is the selected Sharpe ratio still convincing after N trials and non-normal returns? | Sharpe ratio, sample length, skewness, kurtosis, number of trials, variance of the trials’ Sharpe ratios |
| PBO via CSCV | How likely is the selection process to pick an overfit variant? | Return matrix of all variants |
In Python, the package arch (version 9.0.0 as of November 2026) implements White’s and Hansen’s test in one class, SPA (also available as RealityCheck), Romano and Wolf’s procedure as StepM, plus the model confidence set MCS. Two details matter in practice. All three take losses, where smaller is better, so a return series has to be passed with a negative sign. And the SPA class reports three p-values, lower, consistent and upper, which differ in how the losses are re-centred; the arch documentation says that in general the consistent p-value should be used. Name the p-value in your evaluation plan, so that you do not pick the most convenient one afterwards. The bootstrap block length needs a deliberate choice as well: write it into the evaluation plan and set it to suit how strongly the returns depend on each other.
For factor research, Harvey, Liu and Zhu derive a rule of thumb from the same reasoning: given hundreds of tested factors, the usual t-ratio above 2.0 is no longer a sensible hurdle, and a newly discovered factor should clear a t-ratio above 3.0.
Deflated Sharpe Ratio in Python: a tested function
The DSR is the probability that the true Sharpe ratio of the selected variant exceeds what the best of N zero-skill trials would be expected to show. The function below implements equations (1) and (2) of Bailey and López de Prado (2014) with the standard library. All inputs are per period, for example daily, and kurtosis is the plain kurtosis, which is 3 for a normal distribution.
# deflated_sharpe.py: Deflated Sharpe Ratio after Bailey and Lopez de Prado (2014).
# Standard library only. All inputs are per period (e.g. daily), not annualized.
import math
from statistics import NormalDist
EULER_GAMMA = 0.5772156649015329
STD_NORMAL = NormalDist()
def expected_max_sharpe(n_trials, var_sharpe):
"""Expected best Sharpe ratio of n_trials independent trials without skill."""
if n_trials < 2 or var_sharpe <= 0:
raise ValueError("need n_trials >= 2 and var_sharpe > 0")
z1 = STD_NORMAL.inv_cdf(1 - 1 / n_trials)
z2 = STD_NORMAL.inv_cdf(1 - 1 / (n_trials * math.e))
return math.sqrt(var_sharpe) * ((1 - EULER_GAMMA) * z1 + EULER_GAMMA * z2)
def deflated_sharpe(sharpe, n_obs, skew, kurt, n_trials, var_sharpe):
"""Probability that the true Sharpe ratio beats the best zero-skill trial.
sharpe Sharpe ratio of the selected variant (per period)
n_obs number of return observations T
skew, kurt skewness and kurtosis of its returns (kurtosis, normal = 3)
n_trials number of independent trials N (estimate it if trials correlate)
var_sharpe variance of the per-period Sharpe ratios across all trials
"""
sr0 = expected_max_sharpe(n_trials, var_sharpe)
var_term = 1 - skew * sharpe + (kurt - 1) / 4 * sharpe ** 2
if var_term <= 0:
raise ValueError("skewness and kurtosis give a non-positive variance term")
z = (sharpe - sr0) * math.sqrt(n_obs - 1) / math.sqrt(var_term)
return STD_NORMAL.cdf(z)
if __name__ == "__main__":
# Example from the paper: annualized Sharpe ratio 2.5 on five years of
# daily returns (250 days a year), annualized variance of the trials'
# Sharpe ratios 0.5, skewness -3, kurtosis 10.
sr, var = 2.5 / math.sqrt(250), 0.5 / 250
for n in (46, 100):
print(f"N={n}: threshold {expected_max_sharpe(n, var):.4f}, "
f"DSR {deflated_sharpe(sr, 1250, -3, 10, n, var):.4f}")Tested with Python 3.9 and 3.12. The demo reproduces the example from the paper: an annualized Sharpe ratio of 2.5 over five years of data reaches a DSR of about 0.90 after 100 trials, which the authors read as only a 90 percent chance that the true Sharpe ratio is above zero, and 0.9505 after 46 trials. The inputs the function needs are exactly what a complete variant log provides: the number of trials and the variance of their Sharpe ratios.
Limits and risks
- Unlogged trials: every correction depends on the count. Variants tried in an earlier project on the same data, ideas rejected by eye and strategies copied from others after they had looked good are trials too, and they are rarely in the log.
- Assumptions: the DSR approximation assumes independent trials and approximately normal Sharpe ratio estimates across trials; the bootstrap tests assume the past is a usable model for the dependence in the data. Regime changes undermine all of them.
- Power: strict corrections also reject real effects, especially with short histories. A failed test means “not shown”, not “proven worthless”.
- Costs and data: no correction repairs wrong cost assumptions, survivorship bias or look-ahead errors. Check those first.
- Trading risk: a variant that passes every test can still lose money live, up to a total loss with leveraged products.
Next steps: a checklist for your next parameter study
- Write the hypothesis and the benchmark in one paragraph.
- Build the variant matrix and count the variants before the first run.
- Write the evaluation plan: metric, cost model, periods, selection rule, correction and threshold.
- Log every run automatically, with code version and status.
- Run the in-sample study and apply the planned corrections: the DSR for the selected variant, SPA or StepM against the benchmark, and PBO if the matrix is large.
- Test the final candidate once on the untouched period.
- Paper-trade the result before any live money, and compare live behaviour with the backtest.
If you want a second opinion on an existing study, a trading system code review includes the backtest methodology: costs, slippage, out-of-sample periods, walk-forward analysis and the number of variants tested.
Frequently asked questions
How many backtest variants are too many?
There is no fixed limit; it depends on the length of the data. Bailey, Borwein, López de Prado and Zhu show that with five years of data, 45 independent zero-skill configurations already produce a best variant with an expected annualized in-sample Sharpe ratio of 1, and with two years of data, seven do. What matters is that the evaluation accounts for every variant: log them all, estimate the effective number of independent trials and apply a correction such as the Deflated Sharpe Ratio or Hansen’s SPA test.
What is White’s Reality Check?
White’s Reality Check, published in Econometrica in 2000, tests the null hypothesis that the best model found in a specification search has no predictive superiority over a benchmark. It bootstraps the performance of all variants together instead of testing the winner alone. Hansen’s SPA test refines the approach, and the Python package arch implements it in its SPA class.
What does a Deflated Sharpe Ratio of 0.95 mean?
Roughly, a 95 percent probability that the true Sharpe ratio of the selected variant is above zero once the number of trials, their variance, the sample length, skewness and kurtosis are taken into account. In the paper’s example, an annualized Sharpe ratio of 2.5 over five years of data reaches only about 0.90 after 100 trials, and 0.95 only if 46 trials had been run.
Is walk-forward testing enough to avoid overfitting?
No. Walk-forward analysis shows how a re-optimization rule would have behaved over time, but every walk-forward configuration you try is another variant. If you test several window lengths or step sizes and keep the best, the same selection bias returns. Treat walk-forward settings as part of the variant matrix and keep a final period untouched for one last check.
Sources and status
- White (2000): A Reality Check for Data Snooping, Econometrica 68(5), 1097–1126 (abstract) — The Econometric Society (retrieved November 19, 2026)
- Hansen (2005): A Test for Superior Predictive Ability, Journal of Business & Economic Statistics 23(4), 365–380 — American Statistical Association / Taylor & Francis (DOI) (retrieved November 19, 2026)
- Romano and Wolf (2005): Stepwise Multiple Testing as Formalized Data Snooping, Econometrica 73(4), 1237–1282 (abstract) — The Econometric Society (retrieved November 19, 2026)
- Bailey and López de Prado (2014): The Deflated Sharpe Ratio, Journal of Portfolio Management 40(5) — David H. Bailey (authors’ version) (retrieved November 19, 2026)
- Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance (Notices of the AMS, May 2014; authors’ version) — Bailey, Borwein, López de Prado, Zhu (retrieved November 19, 2026)
- Bailey, Borwein, López de Prado and Zhu: The Probability of Backtest Overfitting (Journal of Computational Finance) — David H. Bailey (authors’ version) (retrieved November 19, 2026)
- Harvey, Liu and Zhu: … and the Cross-Section of Expected Returns (NBER Working Paper 20592; Review of Financial Studies 29(1), 2016) — National Bureau of Economic Research (retrieved November 19, 2026)
- arch 9.0.0 documentation: Multiple Comparisons (SPA, RealityCheck, StepM, MCS, p-values) — arch (Kevin Sheppard) (retrieved November 19, 2026)
As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.
This article is also available in German: Viele Varianten testen: ohne sich zu täuschen.
Want your backtest methodology checked before you rely on the results? Get in touch — a free intro call clarifies what to review: the variant log, costs, the out-of-sample design and the corrections used. More: Trading system code review and audit.