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
- 28Sharpe ratioTime aggregation and annualizationSynthetic market generators with known ground truthWalk-forward validationMultiple testing in factor discoveryResearch trial logHierarchical Risk Parity
- 05Delta methodAsymptotic normality of the MLEFamilywise error rate control: Bonferroni, Šidák and HolmBenjamini-Hochberg procedure
- 04Order statisticsSkewness and kurtosis
- 12Agglomerative clusteringLinkage criteria
- 26Stylized facts of returns
An estimated ratio
A strategy’s Sharpe is mean excess return over the reference rate divided by its standard deviation. Sample version 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 observations, the delta method gives
To derive it, use and . Under normality, has variance , has variance and their asymptotic covariance is zero. Gradient yields . Replacing 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
where is skewness and ordinary kurtosis, equal to 3 under normality, not excess kurtosis. Negative skewness can increase uncertainty for positive Sharpe, but its effect depends on . 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 incorporates temporal covariances. Bandwidth is another choice.
That influence function also follows from the delta method. The change in mean contributes ; the change in variance contributes the second term. Long-run variance sums contemporaneous variance of 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 . 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.
Usual annualization 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 periods is ; scaling by can fail. Do not replace with years if the formula’s Sharpe is daily.
For example, if daily return is positively autocorrelated, variance of the sum can exceed times daily variance and the sum’s Sharpe can be lower than the value obtained with . 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 :
This measure is based on a normal sampling approximation, not a posterior probability of skill. All Sharpes must use the frequency of the observations. For , approximate minimum track-record length reaching PSR is . If the difference is not positive, that one-sided confidence is not achieved by increasing 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 , their expected maximum is approximately for , with . For and zero mean it is zero. The main scale for large is , although correction terms matter for finite values.
The deflated Sharpe of Bailey and López de Prado evaluates PSR against threshold 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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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
def deflated_sharpe(returns_best,sharpe_trials):
raise NotImplementedError()Key takeaways
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.