Deflated Sharpe Ratio in Python: Correcting Backtest Sharpe for Selection Bias

This guide is based on the original paper, a published reference formula, and a reproducible simulation; we did not trade it live.
Selection Bias: Why the Best of N Noise Strategies Looks Skilled
Selecting the best of N backtests inflates the Sharpe you report, even when every strategy is pure noise. The expected maximum of N zero-skill Sharpe ratios rises with N and with their cross-trial variance, per Bailey and López de Prado (2014). The short simulation below makes that visible with 100 zero-mean strategies over 252 daily returns.
import numpy as np
rng = np.random.default_rng(21)
returns = rng.normal(0, 0.01, size=(100, 252)) # true Sharpe of every strategy is zero
sharpes = returns.mean(axis=1) / returns.std(axis=1, ddof=1) # daily Sharpe
print(f"{'N':>6} {'max daily SR':>13} {'annualized':>11}")
for n in [1, 10, 100]:
print(f"{n:>6} {sharpes[:n].max():>13.4f} {sharpes[:n].max() * np.sqrt(252):>11.3f}")
Output from running this code (numpy 2.5.4, seed 21):
N max daily SR annualized
1 -0.1150 -1.825
10 0.1890 3.000
100 0.1890 3.000
The maximum can only stay flat or rise as N grows, because each larger pool contains the smaller one. Here the best of the first 10 already equals the best of 100, so the two rows tie. That is one seed, not a law: the expected-maximum formula describes the average behavior across draws, not every draw. Every strategy in this pool has a true Sharpe of zero, so the 3.00 annualized figure is a selected maximum, not evidence of skill.
The Deflated Sharpe Ratio, Term by Term
The Deflated Sharpe Ratio (DSR) is a Probabilistic Sharpe Ratio whose rejection threshold is raised to the expected maximum Sharpe across your trials. The formulas below are the ones from Bailey and López de Prado (2014), as rendered on python.financial. The PDF’s text extraction garbled its equation glyphs, so treat that page as the readable reference for the formulas.
SR0 = sqrt(V[SR]) · [ (1 − γ) · Φ⁻¹(1 − 1/N) + γ · Φ⁻¹(1 − 1/(N·e)) ]
DSR = Φ( (SR_hat − SR0) · sqrt(T − 1) / sqrt(1 − skew·SR_hat + ((kurtosis − 1)/4) · SR_hat²) )
- SR_hat: the estimated Sharpe of the strategy you selected, in per-period units.
- SR0: the threshold, the Sharpe the best of N zero-skill trials would be expected to reach.
- V[SR]: the cross-trial variance of the Sharpe estimates. Wider experimentation raises it and raises SR0.
- N: the number of trials that influenced your selection.
- γ: the Euler–Mascheroni constant, about 0.5772.
- Φ and Φ⁻¹: the standard normal CDF and its inverse.
- T: the number of return observations.
- skew and kurtosis: sample skewness and Pearson kurtosis of the selected strategy’s returns. A normal distribution has kurtosis 3, not 0.
The approximation is undefined for N = 1. Treating N = 1 as SR0 = 0 is a convention, not an output of the formula.
Units rule: SR_hat, SR0, and V[SR] must all be in the same per-period units. Never plug an annualized Sharpe into a formula whose variance and moments were computed from daily values. Keep everything daily in code and annualize only for display, using √252.
Counting N Honestly
N must count every trial that influenced the selection: parameter settings, features, assets, time windows, and manual revisions made after you looked at results. Correlated variants do not count as N independent trials.
Two caveats. First, 100 near-duplicate configurations that differ in one correlated parameter carry far less information than 100 independent ideas. Second, Appendix 3 of the Bailey and López de Prado paper discusses estimating the effective number of independent trials from the average correlation between them, and mentions an entropy-based alternative. The paper calls the number of trials attempted the most important piece of information missing from most published backtests, so log trials as you run them.
From-Scratch Implementation: SR0, DSR, and Sensitivity
The script below uses numpy and scipy only. It simulates the same 100 zero-skill strategies, selects the best, computes SR0 and DSR, then varies the moments and sample length while holding the Sharpe fixed. Every printed value in this section comes from running this exact file. It reproduces identically on rerun with the same seed.
import numpy as np
from scipy import stats
EULER_GAMMA = np.euler_gamma # 0.5772...
def expected_max_sharpe(sr_var, n_trials):
"""SR0: expected maximum Sharpe of n_trials zero-skill trials. Per-period units in and out."""
if n_trials <= 1:
return 0.0 # convention: the formula is undefined for N = 1
z1 = stats.norm.ppf(1 - 1 / n_trials)
z2 = stats.norm.ppf(1 - 1 / (n_trials * np.e))
return np.sqrt(sr_var) * ((1 - EULER_GAMMA) * z1 + EULER_GAMMA * z2)
def dsr(sr_hat, sr0, t_obs, skew, kurt):
"""Deflated Sharpe Ratio. kurt is Pearson kurtosis (normal = 3)."""
denom = np.sqrt(1 - skew * sr_hat + ((kurt - 1) / 4) * sr_hat**2)
return stats.norm.cdf((sr_hat - sr0) * np.sqrt(t_obs - 1) / denom)
rng = np.random.default_rng(21)
T, n_strats, noise_sd = 252, 100, 0.01
returns = rng.normal(0, noise_sd, size=(n_strats, T))
sharpes = returns.mean(axis=1) / returns.std(axis=1, ddof=1) # daily Sharpe per strategy
best = int(np.argmax(sharpes))
sr_hat = sharpes[best]
sr_var = np.var(sharpes, ddof=1)
sr0 = expected_max_sharpe(sr_var, n_strats)
r = returns[best]
skew = stats.skew(r, bias=False)
kurt = stats.kurtosis(r, fisher=False, bias=False)
print(f"best daily SR : {sr_hat:.4f} (annualized {sr_hat*np.sqrt(252):.3f})")
print(f"SR0 daily : {sr0:.4f} (annualized {sr0*np.sqrt(252):.3f})")
print(f"cross-trial V[SR] : {sr_var:.6f}")
print(f"skew / kurtosis : {skew:.3f} / {kurt:.3f}")
print(f"DSR : {dsr(sr_hat, sr0, T, skew, kurt):.3f}")
print("Same best Sharpe and threshold, different moments (scenario inputs):")
print(f"normal-ish returns : {dsr(sr_hat, sr0, T, 0.0, 3.0):.3f}")
print(f"fat-tailed, skewed : {dsr(sr_hat, sr0, T, -0.80, 6.00):.3f}")
print("Same best Sharpe and threshold, sample length T:")
print(f"T = 252 : {dsr(sr_hat, sr0, 252, skew, kurt):.3f}")
print(f"T = 2520 : {dsr(sr_hat, sr0, 2520, skew, kurt):.3f}")
Output from running this code:
best daily SR : 0.1890 (annualized 3.000)
SR0 daily : 0.1703 (annualized 2.703)
cross-trial V[SR] : 0.004528
skew / kurtosis : 0.122 / 2.810
DSR : 0.617
Same best Sharpe and threshold, different moments (scenario inputs):
normal-ish returns : 0.615
fat-tailed, skewed : 0.607
Same best Sharpe and threshold, sample length T:
T = 252 : 0.617
T = 2520 : 0.827
The best of 100 noise strategies posts an annualized Sharpe of 3.00; deflation cuts the verdict to DSR 0.617. That is a long way from the 0.95 level that corresponds to a one-sided 5% convention under the model, so the selected strategy is not distinguishable from luck at this sample size. DSR prices the selection; it does not manufacture skill.
Non-Normal Returns: Skew and Kurtosis in the Denominator
Skewness and kurtosis enter the DSR denominator because they change the standard error of the Sharpe estimate. The script’s scenario rows hold SR_hat and SR0 fixed and change only the moments. Normal-ish returns give 0.615, and fat-tailed, negatively skewed returns give 0.607.
The gap is small at this Sharpe level. In the denominator, the kurtosis term scales with SR_hat² and the skew term scales linearly with SR_hat, so the penalty grows as the observed Sharpe grows, which is the regime where overfit backtests tend to sit. The scenario inputs are what-if values, not measured from the data.
Sample Length: Why DSR Grows With √(T − 1)
The numerator scales with √(T − 1), so a longer sample of the same Sharpe earns more credit. In the script, moving from 252 to 2,520 observations lifts DSR from 0.617 to 0.827 at the same SR_hat and threshold.
That assumes the per-period Sharpe holds over ten times the data. Regimes change, and a longer backtest can span a different market. Treat T as a statistical lever, not a guarantee of stability.
What the Deflated Sharpe Ratio Is Not
- Not the probability of skill. DSR is a normal-CDF transform of a standardized gap between your Sharpe and a luck-adjusted threshold. It lies between zero and one, but it is not P(strategy has skill).
- Not the probability of profit. Nothing in the formula says the strategy will make money out of sample.
- Not assumption-free. The output inherits your recorded N, your V[SR] estimate, and the distributional assumptions in the standard error. If you did not log trials as you ran them, N is understated, SR0 is too low, and DSR is overstated.
Inputs That Invalidate DSR
Deflation addresses selection bias, multiple testing, and non-normality. It does not repair data errors. Lookahead bias inflates SR_hat by using information unavailable at decision time. Survivorship bias inflates it by dropping instruments that failed. Ignored transaction costs inflate it and distort the skew and kurtosis of the net return series. Overlapping or strongly autocorrelated returns make T effectively smaller than it looks.
DSR corrects the inference about a clean backtest run across many trials. It does not fix a dirty one.
Related Guides on QuantBrainAI
DSR is one layer of a defense stack. Pair it with our guides on how to detect backtest overfitting in Python for complementary tests beyond a single Sharpe statistic, Sortino ratio in Python for a downside-focused risk measure, and walk-forward analysis methodology, which provides out-of-sample validation that complements DSR’s correction.
The Bottom Line
A backtest Sharpe is a selected maximum. In our seed-21 simulation, the best of 100 zero-skill strategies reached an annualized Sharpe of 3.00, and the Deflated Sharpe Ratio reduced that to 0.617 at 252 observations. The DSR from Bailey and López de Prado (2014) prices selection by raising the bar to the expected maximum across your recorded trials, then adjusts for sample length, skew, and Pearson kurtosis. Count every trial that influenced selection, keep every Sharpe input in per-period units, and treat DSR as one layer of a defense stack, not a verdict.
FAQ
What is a good Deflated Sharpe Ratio?
DSR is a probability under the model, so higher is better, and values near 0.95 correspond to a one-sided 5% convention. In the simulation above, the selected strategy scored 0.617, which is not significant at that level. The number depends on N, V[SR], and the sample length you recorded.
How many trials should I count?
Count every candidate that influenced the selection, including parameter settings you later discarded, features you tested informally, and each manual revision after seeing results. Correlated near-duplicates count for less than independent trials, so log trials as you run them.
Does DSR prove a strategy works?
No. DSR corrects the Sharpe for selection bias and non-normality under stated assumptions. It does not test out-of-sample performance, costs, or data quality, and it is not the probability that the strategy is profitable.
How This Guide Was Built
This guide implements SR0 and DSR from scratch with numpy and scipy, following the formulas from Bailey and López de Prado (2014) as rendered on python.financial. The paper is also indexed on SSRN (Journal of Portfolio Management 40(5), 94–107). Every printed number comes from running the exact code shown, using numpy 2.5.4, scipy 1.18.1, and seed 21. We did not run a live backtest or trade any strategy.
← Back to all posts

