Module contents
Lesson 27 of 30Advanced 110 min

Honest backtesting II: Sharpe ratio statistics and the deflated Sharpe ratio

Treat Sharpe as a noisy estimator: derive standard errors under normality, higher moments and dependence; study probabilistic and deflated Sharpe, minimum track record, expected maxima, effective trials and haircuts.

After this lesson you can

  • Derive estimated Sharpe standard error using the delta method under normality, higher moments and autocorrelation.
  • Calculate probabilistic Sharpe and minimum track-record length for a given confidence.
  • Derive and approximate the expected maximum Sharpe across independent skill-free trials.
  • Estimate an effective trial count from correlated strategies using clustering.
  • Calculate deflated Sharpe and a Harvey-Liu haircut and check calibration by simulation.

Before you start

An estimated ratio

A strategy’s Sharpe is mean excess return over the reference rate divided by its standard deviation. Sample version S^=rˉ/s\widehat S=\bar r/s is random: three years with annualized Sharpe 1 do not by themselves identify a true Sharpe of 1. Returns, frequency, risk-free rate and costs must use the same clock. Lo studies the estimator’s distribution and time aggregation.

The Sharpe standard error measures sampling uncertainty under a model. With normal i.i.d. returns, positive variance and TT observations, the delta method gives

Var⁡(S^)≈1+S2/2T.\operatorname{Var}(\widehat S)\approx \frac{1+S^2/2}{T}.

To derive it, use (rˉ,v^)(\bar r,\widehat v) and f(μ,v)=μ/vf(\mu,v)=\mu/\sqrt v. Under normality, T(rˉ−μ)\sqrt T(\bar r-\mu) has variance σ2\sigma^2, T(v^−σ2)\sqrt T(\widehat v-\sigma^2) has variance 2σ42\sigma^4 and their asymptotic covariance is zero. Gradient (1/σ,−μ/(2σ3))(1/\sigma,-\mu/(2\sigma^3)) yields 1+S2/21+S^2/2. Replacing SS with the estimate gives an estimated standard error, not one exact in small samples.

With independence and finite moments through fourth order, the moment correction is

se⁡(S^)≈1−γ3S+(γ4−1)S2/4T,\operatorname{se}(\widehat S)\approx \sqrt{\frac{1-\gamma_3 S+(\gamma_4-1)S^2/4}{T}},

where γ3\gamma_3 is skewness and γ4\gamma_4 ordinary kurtosis, equal to 3 under normality, not excess kurtosis. Negative skewness can increase uncertainty for positive Sharpe, but its effect depends on SS. These moments are also noisy in finite samples. With autocorrelation or heteroskedasticity, inserting marginal moments is insufficient: a HAC estimate of the long-run variance of influence function ψt=(rt−μ)/σ−S((rt−μ)2−σ2)/(2σ2)\psi_t=(r_t-\mu)/\sigma - S((r_t-\mu)^2-\sigma^2)/(2\sigma^2) incorporates temporal covariances. Bandwidth is another choice.

That influence function also follows from the delta method. The change in mean contributes (rt−μ)/σ(r_t-\mu)/\sigma; the change in variance contributes the second term. Long-run variance sums contemporaneous variance of ψ\psi and its autocovariances. If the series is i.i.d., autocovariances vanish and expanding the square recovers the skewness and kurtosis correction. With dependent returns, estimating return autocorrelation alone may be insufficient because estimated variance also enters.

A normal 95% interval uses S^±1.96 se⁡^\widehat S\pm1.96\,\widehat{\operatorname{se}}. Its frequentist interpretation concerns procedure coverage across repetitions, not a 95% probability assigned to the fixed parameter after observing an interval. Very heavy tails, regime changes and short series can give different coverage. A block bootstrap preserves some local dependence, but also needs assumptions and a length choice.

InteractiveSharpe uncertainty

Hypothetical asymptotic normal distribution of the estimator around the given true Sharpe. The process is described by its specified moments with no simulated returns. Observations are assumed independent.

Annual Sharpe: −3.0 to 3.0

The displayed value is a frequentist probability under the specified process with fixed true Sharpe. An extreme tail can invalidate the normal approximation.

1.0
756
−1.0
5
Approximate annual standard error0.596
95% normal interval−0.17 to 2.17
Approximate P(estimated SR > 0)0.953
A normal approximation with hypothetical parameters; no returns are generated.

Usual annualization S^anual=252S^diario\widehat S_{\rm anual}=\sqrt{252}\widehat S_{\rm diario} and the same factor applied to its standard error are valid conventions for sums of uncorrelated returns and stable volatility. With autocorrelation, variance of a sum of qq periods is qγ0+2∑k=1q−1(q−k)γkq\gamma_0+2\sum_{k=1}^{q-1}(q-k)\gamma_k; scaling by q\sqrt q can fail. Do not replace TT with years if the formula’s Sharpe is daily.

For example, if daily return is positively autocorrelated, variance of the sum can exceed qq times daily variance and the sum’s Sharpe can be lower than the value obtained with q\sqrt q. Sign and size depend on all included autocovariances, not just the first. Aggregating compounded returns adds another difference: the sum approximates small simple returns.

Probability and length

The probabilistic Sharpe compares the estimator with threshold S∗S^\ast:

PSR⁡(S∗)=Φ((S^−S∗)T−11−γ^3S^+(γ^4−1)S^2/4).\operatorname{PSR}(S^\ast)= \Phi\left(\frac{(\widehat S-S^\ast)\sqrt{T-1}} {\sqrt{1-\widehat\gamma_3\widehat S+(\widehat\gamma_4-1)\widehat S^2/4}}\right).

This measure is based on a normal sampling approximation, not a posterior probability of skill. All Sharpes must use the frequency of the TT observations. For S^>S∗\widehat S>S^\ast, approximate minimum track-record length reaching PSR 1−α1-\alpha is 1+z1−α2[1−γ3S^+(γ4−1)S^2/4]/(S^−S∗)21+z_{1-\alpha}^2[1-\gamma_3\widehat S+(\gamma_4-1)\widehat S^2/4]/(\widehat S-S^\ast)^2. If the difference is not positive, that one-sided confidence is not achieved by increasing TT with estimated parameters fixed. This does not correct selection or dependence.

The calculated length assumes the observed estimate and moments remain unchanged as more data arrive. It does not predict how many days a changing strategy actually needs. If the threshold was chosen after seeing the result or the log omits attempts, interpretation also changes. A high PSR against zero answers a different comparison from PSR against a positive economic benchmark.

Selecting among many alternatives

The expected maximum Sharpe rises when many rules are tried even if all have true Sharpe zero. If estimators are approximately independent normal variables with deviation σS\sigma_S, their expected maximum is approximately σS[(1−γ)Φ−1(1−1/N)+γΦ−1(1−1/(Ne))]\sigma_S[(1-\gamma)\Phi^{-1}(1-1/N)+\gamma\Phi^{-1}(1-1/(Ne))] for N>1N>1, with γ≈0.5772\gamma\approx0.5772. For N=1N=1 and zero mean it is zero. The main scale for large NN is 2log⁡N\sqrt{2\log N}, although correction terms matter for finite values.

InteractiveThe best of N

Each trial has 126 independent normal returns with true mean zero. The chart shows the first 30 cumulative paths and the winner. Its Sharpe times √126 is compared with the maximum of standard normals as an asymptotic approximation.

126 cumulative returnsRange ±30.0 units

A single realization can differ from the expected maximum. Curves sum standardized returns under assumptions of zero costs and zero skill.

2.00
Simulated trials100
Best Sharpe × √1262.32
Approximate expected normal maximum2.53
The winning path comes from synthetic skill-free series.

The deflated Sharpe of Bailey and López de Prado evaluates PSR against threshold S0S_0 constructed from that expected maximum and dispersion across trials. It is not an adjusted Sharpe expressed in return units, but a score between zero and one. The approximation assumes properties of the trials’ distribution, dependence and variance. The expected maximum is not the maximum’s 95th percentile: thus DSR above 0.95 need not yield exactly 5% family-wise false positives. We check this below.

InteractiveDSR calculator

Convert annual Sharpe and standard deviation to daily units before applying the formula over T days. The threshold assumes zero mean across trials and a representative variance. Set it to zero for N=1.

DSR is PSR against the estimated expected maximum. Its calibration depends on dependence and variance estimation, so it gives neither a skill probability nor an automatic 5% family-wise error guarantee.

1.5
756
100
0.6
−1.0
5
Annual threshold SR₀1.518
Approximate DSR0.488
Vary the search and moments with consistent units.

The effective number of trials aims to summarize dependence among variants. One practical procedure clusters correlated returns and uses the number of groups as a sensitivity, not a mathematical identity. Negative correlations, unequal groups and adaptive searches can prevent one number from reproducing the maximum’s distribution.

The log should include initial configurations, window adjustments, changed costs, universes, seeds and discarded tests, along with dates and datasets. Two identical variants contribute less diversity to the maximum than two independent variants; retaining only the winner prevents reconstructing dependence. A correlation matrix estimated from few observations also has error, and a different tree cut can greatly change group count. Sensitivity to the cut is information, not an argument for retrospectively choosing the highest DSR.

InteractiveCutting a variants tree

Idealized matrix with four groups of 50 variants. Correlation is 0.8 within a group and 0.15 between groups. Each cell represents five variants. Average linkage with distance 1−ρ merges groups at heights 0.2 and 0.85.

G1G2G3G401Correlation: within 0.8 / between 0.15

Independence between groups still needs evidence. The result changes with the distance, linkage, and cut. Check it against a joint simulation or bootstrap.

0.50
Variants200
Groups at the cut4
DSR if N = groups0.924
The four blocks are an idealized correlation structure.

The Sharpe haircut expresses how much an estimate is reduced after adjusting significance for multiple trials. Harvey and Liu provide implementations and variants of their procedure. Below we calculate a Bonferroni illustration, conservative under valid p-values; we do not present it as a complete reproduction of their simulations. Comparing two Sharpes observed in the same periods should preserve dependence between strategies; Ledoit and Wolf propose robust bootstrap inference.

Lab: errors, PSR and selection

These functions use simple excess returns per period. The HAC function calculates influence covariances with Bartlett weights; length and bandwidth must be reported. Annualization is the stated daily convention, not an autocorrelation correction.

[ ]Sharpe statisticsBrowser
import numpy as np
from scipy.stats import norm, skew, kurtosis
def sharpe(x):
    x=np.asarray(x,float)
    if len(x)<4 or np.std(x,ddof=1)==0: raise ValueError('Serie insuficiente o constante')
    return np.mean(x)/np.std(x,ddof=1)
def momentos(x):
    return float(skew(x,bias=False)),float(kurtosis(x,fisher=False,bias=False))
def se_momentos(x):
    s=sharpe(x); g3,g4=momentos(x); v=1-g3*s+(g4-1)*s*s/4
    if v<=0: raise ValueError('Varianza aproximada no positiva')
    return np.sqrt(v/len(x))
def se_normal(x):
    s=sharpe(x); return np.sqrt((1+s*s/2)/len(x))
def se_hac(x,L):
    x=np.asarray(x,float); T=len(x); mu=x.mean(); sd=x.std(ddof=0); s=mu/sd
    if not (0<=L<T) or sd==0: raise ValueError('Banda o varianza inválida')
    u=(x-mu)/sd-s*((x-mu)**2/sd**2-1)/2; u=u-u.mean()
    v=u@u/T
    for k in range(1,L+1): v+=2*(1-k/(L+1))*(u[k:]@u[:-k]/T)
    return np.sqrt(max(v,0)/T)
def psr(x,base=0):
    s=sharpe(x); g3,g4=momentos(x); v=1-g3*s+(g4-1)*s*s/4
    if v<=0: raise ValueError('Varianza aproximada no positiva')
    return norm.cdf((s-base)*np.sqrt(len(x)-1)/np.sqrt(v))
def min_historia(s,base,g3,g4,conf=.95):
    if s<=base: return np.inf
    return 1+norm.ppf(conf)**2*(1-g3*s+(g4-1)*s*s/4)/(s-base)**2
def max_esperado(n,sd):
    if n<1 or sd<0: raise ValueError('Parámetros inválidos')
    if n==1: return 0.
    gamma=.5772156649
    return sd*((1-gamma)*norm.ppf(1-1/n)+gamma*norm.ppf(1-1/(n*np.e)))
def deflated_sharpe(returns_best,sharpe_trials):
    trials=np.asarray(sharpe_trials,float)
    if len(trials)==0: raise ValueError('Faltan ensayos')
    sd=np.std(trials,ddof=1) if len(trials)>1 else 0.
    return psr(returns_best,max_esperado(len(trials),sd))
print('Sharpe anual 1, tres años, PSR normal frente a cero:',
      norm.cdf((1/np.sqrt(252))*np.sqrt(755)/np.sqrt(1+(1/np.sqrt(252))**2/2)))
print('Máximo normal esperado para N=100:',max_esperado(100,1))

Estimated DSR treats trials as independent and takes their observed cross-sectional deviation as a proxy for null dispersion. If trials have different skills, that dispersion is not solely noise. For one test the null threshold is zero; variance across a single observation is not estimated.

[ ]Coverage under normality, tails and dependenceBrowser
rng=np.random.default_rng(282701); B=800; T=252; L=10
def panel_simulado(kind):
    if kind=='normal': return rng.normal(size=(T,B))
    if kind=='t5': return rng.standard_t(5,size=(T,B))
    z=rng.normal(size=(T,B)); x=np.zeros((T,B))
    if kind=='garch':
        h=np.ones(B)
        for t in range(T):
            x[t]=np.sqrt(h)*z[t]
            h=.05+.1*x[t]**2+.85*h
        return x
    for t in range(1,T): x[t]=.5*x[t-1]+z[t]
    return x
for kind in ('normal','t5','ar1','garch'):
    x=panel_simulado(kind); mu=x.mean(axis=0); sd=x.std(axis=0,ddof=1); s=mu/sd
    g3=skew(x,axis=0,bias=False); g4=kurtosis(x,axis=0,fisher=False,bias=False)
    en=np.sqrt((1+s*s/2)/T); em=np.sqrt((1-g3*s+(g4-1)*s*s/4)/T)
    sigma=x.std(axis=0,ddof=0); sr0=mu/sigma; z=(x-mu)/sigma
    u=z-sr0*(z*z-1)/2; u-=u.mean(axis=0)
    v=np.mean(u*u,axis=0)
    for k in range(1,L+1): v+=2*(1-k/(L+1))*np.sum(u[k:]*u[:-k],axis=0)/T
    eh=np.sqrt(np.maximum(v,0)/T)
    cover_normal=np.mean(np.abs(s)<=1.96*en); cover_mom=np.mean(np.abs(s)<=1.96*em); cover_hac=np.mean(np.abs(s)<=1.96*eh)
    print(kind,'| cobertura normal/momentos/HAC:',
          cover_normal,cover_mom,cover_hac,'| réplicas:',B,'| banda HAC:',L)

True Sharpe is zero in all four generators. The t series with five degrees of freedom has finite fourth moment but not finite fifth absolute moment; kurtosis estimates can be unstable. GARCH has clustered conditional variance and starts at unconditional variance; AR(1) starts at zero and has a transient. Finite-bandwidth HAC is also approximate. Monte Carlo coverage has uncertainty: with 800 replicates, near 95% its standard error is approximately 0.8 percentage points.

[ ]Is DSR > 0.95 calibrated?Browser
rng=np.random.default_rng(282702); B=1200; N=20; T=252
paneles=rng.normal(size=(B,T,N))
sr=paneles.mean(axis=1)/paneles.std(axis=1,ddof=1); elegido=np.argmax(sr,axis=1)
mejores=paneles[np.arange(B),:,elegido]; s=sr[np.arange(B),elegido]
g3=skew(mejores,axis=1,bias=False); g4=kurtosis(mejores,axis=1,fisher=False,bias=False)
umbral=max_esperado(N,1)*sr.std(axis=1,ddof=1)
dsr=norm.cdf((s-umbral)*np.sqrt(T-1)/np.sqrt(1-g3*s+(g4-1)*s*s/4))
maximos=s*np.sqrt(T)
print('N, T, réplicas:',N,T,B,'| DSR > .95:',np.mean(dsr>.95),
      '| máximo con umbral Šidák:',np.mean(maximos>norm.ppf(.95**(1/N))))
print('Máximo observado medio:',np.mean(maximos),'| aproximación:',max_esperado(N,1))

The Šidák threshold uses the maximum’s percentile under independent normals, while DSR uses its expectation as reference and then adds a one-sided margin. Thus the DSR rate can be much lower than 5% here. Cross-sectional variance is estimated from the same trials and Sharpes are finite-sample ratios; the example measures a particular calibration. Positive means can also be planted in some columns and power measured, without confusing the proportion of null selections with an individual posterior probability.

With these seeds the DSR criterion exceeds 0.95 in 1 of 1,200 null repetitions and the Šidák threshold in approximately 5.4%. With two planted alphas, there are 13 acceptances in 600 repetitions and all 13 accepted winners belong to those columns. These counts are from a particular simulation: they do not guarantee that rate in other processes and, with so few acceptances, precision is limited.

An additional check compares the simulated mean maximum with the extreme-value approximation, as the cell does. Reasonable agreement in one generator does not guarantee calibration with correlated trials, skewed distributions or unequal variances. To estimate family-wise error, repeat the complete process including selection and count how often at least one null result exceeds the criterion. Studying power also requires knowing which columns have true alpha; in real data that label is usually unknown.

[ ]Power with planted alphasBrowser
rng=np.random.default_rng(282703); B=600; N=20; T=252; alfa=np.zeros(N); alfa[:2]=.12
aceptados=correctos=0
for _ in range(B):
    panel=rng.normal(size=(T,N))+alfa
    sr=panel.mean(axis=0)/panel.std(axis=0,ddof=1); elegido=np.argmax(sr)
    if deflated_sharpe(panel[:,elegido],sr)>.95:
        aceptados+=1; correctos+=elegido<2
print('Aceptaciones:',aceptados,'| ganadora con alfa plantada:',correctos,'| réplicas:',B)

Lab: reconstructing a log

We reproduce the previous lesson’s three trend windows and carry, with its seed, in one panel. This is a reconstructed subset: it does not contain every signal, pair and PCA variant tried, so calculated DSR does not represent the entire research. Columns are aligned on the same days. A complete log would retain returns of every attempt and subsequent decisions, including discarded variants.

[ ]Four aligned trialsBrowser
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import squareform
rng=np.random.default_rng(282601); T=1260; N=3
carry=np.tile(np.array([.00025,-.0001,.00015]),(T,1))
regimen=np.where((np.arange(T)//126)%2==0,.0006,-.0006)
r=rng.normal(0,.01,(T,N))+regimen[:,None]*np.array([1.,-.4,.7])+carry
r[850:855]-=.035*np.array([1.,.6,.8])
def pesos_trend(r,ventana):
    w=np.zeros_like(r)
    for t in range(ventana,len(r)):
        h=r[t-ventana:t]; vol=np.sqrt(np.mean(h*h,axis=0))
        w[t]=np.sign(h.sum(axis=0))*np.minimum(1.5,.01/np.maximum(vol,.001))/r.shape[1]
    return w
def neto(r,w):
    prev=np.vstack([np.zeros((1,w.shape[1])),w[:-1]])
    return (w*r).sum(axis=1)-.0005*np.abs(w-prev).sum(axis=1)-.02*np.maximum(-w,0).sum(axis=1)/252
wcarry=np.zeros_like(carry); wcarry[1:]=np.sign(carry[:-1])/3
retornos=np.column_stack([neto(r,pesos_trend(r,v)) for v in (21,63,126)]+[neto(r,wcarry)])[126:504]
nombres=['tendencia 21','tendencia 63','tendencia 126','carry']
sr=np.array([sharpe(retornos[:,i]) for i in range(4)]); mejor=int(np.argmax(sr))
corr=np.corrcoef(retornos,rowvar=False); dist=np.clip(1-corr,0,2); np.fill_diagonal(dist,0)
arbol=linkage(squareform(dist,checks=False),method='average')
for corte in (.3,.6,1.):
    grupos=len(np.unique(fcluster(arbol,corte,criterion='distance')))
    s0=max_esperado(grupos,np.std(sr,ddof=1))
    print('Corte:',corte,'| grupos:',grupos,'| DSR si grupos=N:',psr(retornos[:,mejor],s0))
print('Ensayos:',list(zip(nombres,sr*np.sqrt(252))),'| mejor:',nombres[mejor])
print('DSR N=4:',deflated_sharpe(retornos[:,mejor],sr),'| correlaciones:',corr)

The cut uses distance 1−ρ1-\rho and average linkage; it does not guarantee independent groups. Segment 126:504 compares variants, not evaluates a selected one out of sample. Carry uses the previous lesson’s simplified financing and costs. The annual Sharpe shown uses only the scaling convention; PSR/DSR formulas use daily frequency.

In this reconstruction 63-day trend wins with conventional annual Sharpe near 0.255; DSR with four trials is approximately 0.317. Changing the cut to 0.6 or 1 gives three or two groups and increases the calculated score. The partial log and assumptions prevent presenting any of these figures as a definitive conclusion about skill.

[ ]Illustrative haircut and joint bootstrapBrowser
from scipy.stats import norm
T=len(retornos); sb=sr[mejor]; p=min(1.,2*norm.sf(abs(sb)*np.sqrt(T)))
p_aj=min(1.,len(sr)*p)
s_hair=max(0.,norm.isf(p_aj/2)/np.sqrt(T)) if p_aj<1 else 0.
print('p bilateral aproximado:',p,'| Bonferroni:',p_aj,
      '| Sharpe anual original/ajustado:',sb*np.sqrt(252),s_hair*np.sqrt(252))
rng=np.random.default_rng(282704); B=500; longitud=10
a,b=retornos[:,0],retornos[:,1]; diferencia=sharpe(a)-sharpe(b); boot=[]
for _ in range(B):
    inicios=rng.integers(0,T,size=int(np.ceil(T/longitud)))
    idx=np.concatenate([(k+np.arange(longitud))%T for k in inicios])[:T]
    boot.append(sharpe(a[idx])-sharpe(b[idx]))
print('Diferencia diaria 21−63:',diferencia,'| IC bootstrap por bloques:',
      np.quantile(boot,[.025,.975]),'| bloques circulares:',longitud)

The haircut illustration uses a two-sided normal test without HAC and a Bonferroni correction; it does not replicate the full Harvey-Liu algorithm. The bootstrap interval uses common indices to preserve dependence between both strategies and circular blocks to retain local dependence. Coverage depends on stationarity, block length and sample. The difference was chosen here for illustration; if chosen as the most favorable, selection also occurs.

To approximate a robust comparison of two Sharpes, we also calculate HAC variance of the difference between their influence functions and studentize each joint replicate. The idea follows Ledoit and Wolf’s studentized block bootstrap, but bandwidth, block length and number of replicates are teaching choices; their complete block-selection procedure is not reproduced.

[ ]Joint studentized bootstrapBrowser
def influencia(x):
    mu=x.mean(); sd=x.std(ddof=0); s=mu/sd; z=(x-mu)/sd
    u=z-s*(z*z-1)/2
    return u-u.mean()
def error_diferencia(a,b,L=10):
    u=influencia(a)-influencia(b); n=len(u); v=u@u/n
    for k in range(1,L+1): v+=2*(1-k/(L+1))*(u[k:]@u[:-k]/n)
    return np.sqrt(max(v,0)/n)
se=error_diferencia(a,b); estadisticos=[]
rng=np.random.default_rng(282705)
for _ in range(500):
    starts=rng.integers(0,T,size=int(np.ceil(T/longitud)))
    idx=np.concatenate([(k+np.arange(longitud))%T for k in starts])[:T]
    d=sharpe(a[idx])-sharpe(b[idx]); err=error_diferencia(a[idx],b[idx])
    if err>0: estadisticos.append((d-diferencia)/err)
qlo,qhi=np.quantile(estadisticos,[.025,.975])
print('Error HAC:',se,'| IC studentizado:',
      (diferencia-qhi*se,diferencia-qlo*se),'| réplicas válidas:',len(estadisticos))

Exercises

NumericThree years
With estimated annual Sharpe 1, 756 independent normal daily returns and threshold zero, approximately what is PSR? Express the result between 0 and 1.
NumericOne hundred attempts
What is the approximate expected maximum of 100 independent standard normals using the extreme-value formula? Give the result in standard-deviation units.
QuizDelta derivation
For normal i.i.d. returns, what asymptotic variance does √T(estimated S − true S) have?
QuizThe trial archive
Why is counting only finalist strategies dangerous when calculating DSR?
CodeDeflated Sharpe
Implement deflated_sharpe(returns_best, sharpe_trials). Use NumPy and scipy.stats: per-period Sharpe with sample standard deviation, unbiased skewness and ordinary kurtosis, expected normal maximum threshold with zero mean, N=len(sharpe_trials) and sample deviation across trials; use threshold zero for N=1. Apply the PSR formula with T−1. Return a number between 0 and 1.
def deflated_sharpe(returns_best,sharpe_trials):
  raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
A selected Sharpe is a noisy estimator: report its frequency, uncertainty, temporal dependence and complete search alongside any correction.

PSR, DSR, clustering and haircut answer different questions and require assumptions. Calibration simulation and separate evaluation can show when those assumptions fail; no score replaces a decision log.