Metrics with uncertainty and factor attribution
Build the analysis module: Sharpe and its standard error under non-normality and autocorrelation, drawdowns, historical VaR and Expected Shortfall, and Fama-French factor regression with HAC errors. Combine the results in an automatically generated performance report with block-bootstrap confidence intervals.
After this lesson you can
- Calculate annualized Sharpe and its standard error with Lo's correction and block bootstrap.
- Measure drawdowns, VaR, and Expected Shortfall and quantify their sampling variability.
- Estimate factor alpha with Newey-West errors and interpret factor loadings.
- Generate a reproducible report with metrics, intervals, and subperiod performance.
Before you start
- P01Vectorized backtestTransaction cost model
- 05Nonparametric bootstrapBootstrap percentile and basic intervalsDelta methodBlock bootstrap
- 26Autocorrelation function
- 27Newey-West HAC standard errorsHeteroskedasticity-consistent standard errors (HC0 to HC3)
- 28Sharpe ratioExpected ShortfallTime-series factor regressions
- 00Uncertainty visualizationReproducible publication-quality figures
A number is an estimate
A curve can look convincing and still partly reflect chance in a short sample. Sharpe inference asks how much the ratio of mean excess return to standard deviation might vary. An estimate of 1 does not guarantee a population value of 1 or that the strategy survives costs and regime changes.
For monthly excess returns , the conventional estimator is
The factor describes the Sharpe of the annual sum of returns only when monthly covariances are zero. With autocorrelation, it is a convention for expressing the monthly ratio on an annual scale and must not be confused with the mean-to-standard-deviation ratio of the annual sum. Lo studies inference and annualization under temporal dependence.
For example, two strategies with the same monthly mean and marginal volatility can have different annual risks if one clusters good and bad months while the other alternates signs. The sum’s standard deviation depends on covariances among all months of the year, not just one month’s standard deviation. Both can have the same conventional Sharpe. Before comparing figures, ask for frequency, excess-return definition, treatment of costs, and annualization method.
The figure’s asymmetric mixture transforms the innovation distribution; the AR(1) process introduces dependence while maintaining marginal variance. The probability that a true value of zero appears greater than one uses other means with the same disturbances. It is a simulated frequency for that family, not a universal probability or correction for selecting the best of many strategies.
For a sum of stationary returns with autocovariance , variance is
Thus the Sharpe of the sum is divided by the square root of that variance. Positive autocorrelation usually reduces aggregate Sharpe relative to the naive rule; negative autocorrelation can increase it. The formula uses a simple sum rather than compounding, and estimating eleven monthly autocovariances from a short history can be noisy. No multiplier is reliable for every series.
Uncertainty under dependence
With independent normal returns, observations, and per-period Sharpe , the delta method gives approximately
The formula ignores skewness, tails, and autocorrelation. To incorporate them, the module calculates the influence series of the mean-to-standard-deviation ratio and estimates its long-run variance with Newey-West Bartlett weights. Divide by and multiply by for the variance of conventionally annualized Sharpe. The number of lags is a choice: too few can omit dependence, while many add noise. The approximation requires appropriate moments and stationarity conditions.
The influence series combines two error sources: estimated mean and estimated standard deviation. An extreme observation changes both. Using only the mean’s standard error and treating volatility as known is another approximation that can understate ratio variability. HAC applied to this series does not assume normal returns, but relevant moments and long-run variance must exist and be estimable.
The circular block bootstrap preserves consecutive sample fragments, restarts at random positions, and can wrap from the end to the beginning. We calculate the 2.5th and 97.5th percentiles of replicates. Block size balances preserving dependence against the number of independent fragments; results can be biased with short samples or regime changes. It is not the stationary bootstrap with random-length blocks of Politis and Romano, though both resample dependence.
A 95% interval is a procedure intended to cover the parameter in 95% of repetitions under its assumptions; it does not mean a particular hypothesis has 95% probability. The coverage lab repeats the whole experiment 1000 times with a known true value and shows that nominal coverage is not a guarantee.
Losses, path, and factors
Drawdown and tail risk describe different aspects. Maximum drawdown is the largest decline from a previous equity peak to a trough; recovery is the first later date reaching that peak, if one exists. It depends on return order and the observed period. Historical 95% VaR is the 95th percentile of loss; this implementation’s Expected Shortfall averages losses equal to or above that threshold. With ties it may include more than 5% of observations, a convention that is disclosed.
VaR is a threshold, not a maximum loss. ES describes the observed tail and is also uncertain; with few extreme months, one observation can shift it substantially. The report resamples blocks to obtain intervals for VaR, ES, and drawdown. These represent variation under the resampling scheme, not a prediction of future losses or a guarantee under a changing distribution.
An equity sequence of 100, 120, 90, 110, and 120 has peak 120, trough 90, and maximum drawdown 25%; it recovers the peak at the last observation. Episode duration depends on observation time units. If the last value were 110, the episode would remain unrecovered at the sample end; that absence must not be turned into zero duration. The report returns peak, trough, and recovery indices; for real dates they must be mapped to the calendar, including initial capital.
Tail risk and drawdown answer different questions. Reordering the same returns preserves empirical quantiles but can cluster losses and deepen drawdown. Conversely, adding one extreme observation can substantially change VaR or ES. The report therefore shows both families and their uncertainty rather than compressing risk into one number.
Factor attribution fits a regression of monthly excess return on market, size, value, and momentum:
The intercept is alpha conditional on the model and sample. A positive momentum loading may explain part of the return without establishing independent skill. Newey and West HAC errors adjust uncertainty for heteroskedasticity and dependence up to a chosen lag; they do not eliminate omitted variables, model selection, or factor errors. Multiplying monthly alpha by 12 approximates a sum, not exact compounding.
A momentum loading of 0.9 indicates that, holding other regressors constant in the linear model, a one-unit factor change is associated with an estimated 0.9-unit change in portfolio excess return. Interpretation depends on compatible scales: factors and return here are monthly fractions. Using factors in percent and portfolio return as a fraction would change coefficients by a factor of one hundred. Align dates and subtract the risk-free rate once before interpreting results.
Splitting the sample in two reveals Sharpe differences but does not automatically prove structural change. Each half has less data and greater uncertainty. Choosing cutoffs after seeing the curve also introduces selection. Keep dates, costs, factor versions, and seed with the report so someone else can repeat the calculation.
Reproducible local report
The performance tearsheet combines the curve, Sharpe, intervals, tail, drawdown, subperiods, and regression. Download p01metrics.py, p01metrics_lab.py, and test_p01metrics.py with p01data.py. You need Python with NumPy, pandas, statsmodels, and pytest. The cell downloads or reuses official Kenneth French factors and writes a local HTML file at P01_REPORT_PATH or p01_project/tearsheet.html.
The portfolio is synthetic: it combines those real monthly factors with known coefficients, monthly alpha 0.002, and fixed-seed normal noise. It does not represent a traded portfolio. Displayed capital compounds excess returns, not an account including the risk-free rate. The code prints download hashes to identify versions; French may revise its history and change results.
import os,sys
from pathlib import Path
import pytest
lib=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (lib/'p01metrics.py').exists(): raise FileNotFoundError('Descarga los módulos en P01_LIB_DIR')
sys.path.insert(0,str(lib))
from p01metrics_lab import experiment
os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD']='1'
status=pytest.main([str(lib/'test_p01metrics.py'),'-q','-p','no:cacheprovider'])
assert status==0
experiment()npm run lab and open the connection link.The verified version has 168 months between 2010 and 2023. Conventional Sharpe is 1.073, block confidence interval [0.642, 1.609], and estimated aggregate Sharpe 1.709; the difference reflects estimated autocovariances, not that either is always greater. Fitted alpha is 0.00379 monthly with HAC statistic 2.28, versus 0.002 used to generate the data. VaR and ES at 95% are approximately 7.06% and 10.49%, and maximum drawdown is 25.46% on the excess-return curve. These values are reproducible for this run’s files and seed, not real performance.
Laboratory: coverage under tails and dependence
The following simulation uses Student innovations with five degrees of freedom, AR(1) correlation 0.25, and 360 months per sample after 200 warm-up months. Population conventional Sharpe is . Each sample generates 300 circular-block replicates of 12 months. We compare percentile and five-lag delta-HAC intervals; the target is that conventional Sharpe, not the annual sum’s Sharpe. Monte Carlo error for coverage near 95% with 1000 repetitions is approximately 0.7 percentage points.
import numpy as np
rng=np.random.default_rng(5105)
N=1000; n=360; B=300; block=12; rho=.25; mu=.005; sigma=.04; q=12
truth=np.sqrt(q)*mu/sigma
covered_boot=0; covered_hac=0; widths=[]
for experiment in range(N):
noise=rng.standard_t(5,n+200)*np.sqrt(3/5)
x=np.empty(n+200);x[0]=mu+sigma*noise[0]
for t in range(1,len(x)):
x[t]=mu+rho*(x[t-1]-mu)+sigma*np.sqrt(1-rho*rho)*noise[t]
x=x[200:]
s=np.sqrt(q)*x.mean()/x.std(ddof=1)
starts=rng.integers(0,n,size=(B,(n+block-1)//block))
idx=(starts[:,:,None]+np.arange(block))%n
samples=x[idx.reshape(B,-1)[:,:n]]
boot=np.sqrt(q)*samples.mean(axis=1)/samples.std(axis=1,ddof=1)
lo,hi=np.quantile(boot,[.025,.975])
covered_boot+=lo<=truth<=hi;widths.append(hi-lo)
m=x.mean();v=np.mean((x-m)**2)
psi=(x-m)/np.sqrt(v)-(m/np.sqrt(v))*((x-m)**2-v)/(2*v)
omega=np.dot(psi,psi)/n
for k in range(1,6):
omega+=2*(1-k/6)*np.dot(psi[k:],psi[:-k])/n
se=np.sqrt(q*max(omega,0)/n)
covered_hac+=s-1.96*se<=truth<=s+1.96*se
print('Sharpe verdadero convencional:',round(truth,4),'| experimentos:',N)
print('Cobertura bootstrap circular:',covered_boot,'/',N,'=',round(covered_boot/N,3))
print('Cobertura HAC delta:',covered_hac,'/',N,'=',round(covered_hac/N,3))
print('Ancho medio IC bootstrap:',round(float(np.mean(widths)),3))In the verified local run they cover 939/1000 and 940/1000 respectively, close to the nominal value but not identical. With 120 months and blocks of six, another run with the same basic setup produced 912/1000 and 916/1000: coverage depends on length, blocks, and process. The intervals do not correct bias from choosing a strategy after testing many.
Exercises
Step 1 of 2. What is the gradient of μ/σ with respect to (μ, σ)?
def max_drawdown(equity):
raise NotImplementedError()