Module contents
Stage 8 of 9Research 110 min

Backtest overfitting and multiple testing

Add a registry of evaluated configurations and tools that account for search: the deflated Sharpe ratio, probability of backtest overfitting, and White and Hansen data-snooping tests with stationary bootstrap. Explore a thousand noise strategies in a controlled experiment.

After this lesson you can

  • Automatically record each trial with its configuration and return series.
  • Calculate the deflated Sharpe ratio using an effective number of trials.
  • Estimate the probability of backtest overfitting using combinatorial symmetric cross-validation.
  • Apply Reality Check and SPA with stationary bootstrap to a family of strategies.

Before you start

The best of many trials

If enough rules with no edge are tested, some will have a high Sharpe by chance. Choosing one after observing all curves introduces selection that a p-value calculated as if it were the only trial does not reflect. For independent standard normals, the maximum grows approximately as 2log⁡N\sqrt{2\log N}; the approximation improves for large NN and does not exactly describe every correlated family.

InteractiveThe best of N useless strategies

Daily normal returns with zero mean, 1% volatility, and a common factor at the selected correlation. All series use the same seed; the highest Sharpe is selected. There are no costs or skill.

Winner's wealth, sampled every 21 days: minimum 1.00, maximum 2.13. The effective number is the heuristic 1 + (N−1)(1−ρ) = 80.2; it is not a validated estimate.

The expected maximum uses a normal approximation and observed cross-sectional dispersion; DSR uses zero skewness and kurtosis three. Correlation and selection can invalidate this approximation; compare with the joint simulation in the lab.

2.0
5
0.2
Trials100
Best annual Sharpe1.06
Approximate expected maximum1.01
Approximate DSR0.542
The selection and curve come from synthetic normally distributed returns with zero mean.

The interactive shows a family of simulated series with a common component. The observed cross-sectional dispersion and heuristic effective-number formula are approximations; they do not turn correlated trials into independent tests. The displayed DSR uses normal moments and is not a joint p-value. Changing years, correlation, and quantity changes the selection, but one seed does not estimate its full distribution.

A trials registry stores each executed configuration, aligned returns, seed, data and code versions, costs, and date. Discarded variants count too. If only finalists are recorded, no later correction can reconstruct forgotten searches. The lab stores the complete matrix in NPZ and a JSON manifest with configuration per column and the file’s SHA-256; it identifies what ran, but cannot know about attempts outside it.

The run_trials function iterates over the supplied configurations and records the matrix when the batch finishes. In the example, each configuration identifies an already generated synthetic column; in an application the callback is replaced with an engine run for that configuration. The registry is not transactional: if the process fails before writing, the batch is not recorded. A persistent research implementation should record the start, success or error of each trial, effective parameters, versioned code and data, and recover interrupted runs without overwriting previous ones.

The hash establishes which bytes were saved. It does not establish that the strategy is causal or that the registry includes every human attempt. The matrix requires common dates and a defined benchmark; columns with different periods should not be compared by silently filling missing observations. A repeat to debug a failure must also be distinguished from a new trial that could have influenced selection.

Similar strategies do not correspond to an equal number of independent trials. One sensitivity analysis uses hierarchical clustering with distance 2(1−ρ)\sqrt{2(1-\rho)} and a correlation threshold; another uses the participation ratio (tr⁡R)2/tr⁡(R2)(\operatorname{tr}R)^2/\operatorname{tr}(R^2). Both summarize dependence rather than the true number of selection opportunities. Estimating correlations from a finite sample also reduces effective rank even when the generating series are independent.

Deflated Sharpe

The deflated Sharpe ratio compares the selected Sharpe to an expected maximum under a null approximation, adjusting for skewness and kurtosis. With per-period Sharpe ss, threshold s0s_0, TT observations, skewness γ3\gamma_3, and ordinary kurtosis γ4\gamma_4:

DSR=Φ ⁣((s−s0)T−11−γ3s+(γ4−1)s2/4).DSR=\Phi\!\left(\frac{(s-s_0)\sqrt{T-1}} {\sqrt{1-\gamma_3s+(\gamma_4-1)s^2/4}}\right).

The threshold is approximated using normal quantiles for NN independent trials and an estimated cross-sectional standard deviation. Units must match: if Sharpe is annualized using 252 days, divide it by 252\sqrt{252} before using daily returns in the formula, and divide the variance across trials by 252. Bailey and López de Prado develop this approximation and a numerical example.

The threshold is an expected maximum, not its 95th percentile. A DSR above 0.95 is therefore not automatically a global 5% level test. The formula does not by itself correct for autocorrelation, forgotten trials, or a wrong effective-number estimate. If strategies have different means, cross-sectional dispersion contains signal as well as noise. Report sensitivity to NN, moments, and the reference family, and use joint tests for a global hypothesis.

The published exercise example starts with annual Sharpe 2.5, 250 observations per year, 100 trials, annual variance across trials 0.5, 1250 observations, skewness −3, and kurtosis 10. Daily conversion gives an approximate threshold of 0.1132 and DSR 0.9004. High negative skewness and kurtosis increase estimation uncertainty. The result depends on the example’s assumptions and does not turn that value into a portfolio’s probability of economic success.

PBO and joint tests

The probability of backtest overfitting using CSCV divides history into an even number of blocks. For each choice of half, it selects the variant with the highest mean in those blocks and computes its rank in the complementary blocks. PBO is the fraction of partitions in which the winner falls below the out-of-sample median. This implementation uses the mean, average ranks for ties, and six blocks; it does not estimate an individual probability of future loss. Bailey and colleagues propose the CSCV framework.

The 20 partitions with six blocks overlap and are not 20 independent samples. CSCV may also train on blocks later than other test blocks. It complements a causal walk-forward and reserved final test. A low PBO does not prove that a strategy is profitable after costs or survives a regime change.

Rank is computed within the same family in each complement. A strategy may be above the median even if all lose money, or below it even if profitable in absolute terms. The procedure addresses the relative stability of selection. A tie receives the average rank so incidental column order does not decide the result. Choosing another metric or changing block size changes the question and must be recorded.

Joint search tests compare all strategies with a benchmark. White’s Reality Check uses the maximum of means; Hansen’s SPA studentizes and adjusts centering of clearly inferior alternatives. The stationary bootstrap resamples the same time indices for all columns, preserving some temporal and cross-sectional dependence. Our SPA variant uses one centering rule and fixed bootstrap scale; other implementations may differ.

With 199 replicates, the smallest reported p with +1+1 correction is 0.005. Changing mean block length or increasing replicates allows sensitivity analysis. A global rejection says at least one variant may outperform the benchmark under the test’s assumptions; by itself it identifies neither which one nor future stability. Failure to reject does not prove that every strategy lacks an edge.

The stationary bootstrap starts at a random index and at each step continues to the next circular index or restarts with probability 1/L1/L, where LL is mean block length. Resampling a whole matrix with the same indices preserves shocks shared across strategies; resampling each column separately would destroy that structure. Validity still depends on stationarity and a reasonable block length.

Local laboratory

Download p01trials.py, p01trials_lab.py, and test_p01trials.py. You need NumPy, SciPy, and pytest. The lab creates two families of 1000 daily normal series over 2520 days: one pure noise and another with a planted mean in the first column, annual population Sharpe 1.5. Returns are not real prices and exclude costs. P01_TRIAL_ROOT controls where matrices and manifests are saved.

[ ]Register and adjust for a thousand variantsLocal GPU
import os,sys
from pathlib import Path
import pytest
lib=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (lib/'p01trials.py').exists(): raise FileNotFoundError('Descarga los módulos en P01_LIB_DIR')
sys.path.insert(0,str(lib))
from p01trials_lab import experiment
os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD']='1'
status=pytest.main([str(lib/'test_p01trials.py'),'-q','-p','no:cacheprovider'])
assert status==0
experiment()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With this seed, the best noise series has annual Sharpe 0.979, DSR 0.452 using effective rank 716, and 0.413 using all 1000 trials. Clustering at the specified threshold produces 1000 groups. PBO is 0.20, Reality Check gives p = 0.625, and SPA p = 0.500. PBO is not forced to 0.5: this is one matrix with only 20 dependent partitions. Effective rank 716 does not imply 716 independent generators either: here we know 1000 were generated, and finite-sample bias in the summary matters.

With a planted signal, column 0 wins with observed Sharpe 2.257, DSR 0.9999, PBO 0, and both p = 0.005. Observed Sharpe differs from the population value of 1.5 because of noise; the minimum p reflects the resolution of 199 replicates. These are controlled demonstrations, not power estimates or detection guarantees. The manifest retains every column; the hash identifies the file produced by that run.

Exercises

NumericApproximate expected maximum
For 100 independent annual Sharpes with zero mean and approximate standard deviation 1/√10, the expected maximum of standard normals is 2.5306. What is the approximate annual expected maximum?
CodeReproduce the published example
Implement deflated_sharpe(sr,n_trials,var_trials,skew,kurt,T). All Sharpes and their variance have the same frequency; kurt is ordinary kurtosis. Use the Bailey-López de Prado expected normal maximum and DSR formula.
import numpy as np
from scipy.stats import norm
def deflated_sharpe(sr,n_trials,var_trials,skew,kurt,T):
  raise NotImplementedError()
Shift+Enter to run
QuizThree hundred trials
After 300 configurations, the best has nominal p 0.002. What should be reported?
ProofGrowth of the maximum
Prove: Sketch why the maximum of N independent standard normals grows on the scale √(2 log N).
The proof will appear here as you work.

Step 1 of 2. What is the probability that every variable is below x?

What to remember

Key idea
A correction can consider only the family that was recorded and the assumptions actually checked.