Estimation error: why Markowitz fails and how to fix it
Study estimation error in portfolio optimization and compare covariance shrinkage, spectral cleaning, resampling and equal weighting against known truth.
After this lesson you can
- Quantify the number of years of data needed to estimate a mean return with useful precision.
- Use spectral decomposition to explain why an optimizer concentrates weight in poorly estimated directions.
- Derive and implement Ledoit-Wolf shrinkage toward a structured target.
- Clean a correlation matrix using Marchenko-Pastur eigenvalue clipping and measure out-of-sample effects.
- Design a known-truth experiment comparing sample Markowitz, GMV, shrinkage, spectral cleaning, resampling and 1/N.
Before you start
- 28Mean-variance optimizationEfficient frontierGlobal minimum variance portfolioTangency portfolioSynthetic market generators with known ground truth
- 04Marchenko-Pastur lawCovariance estimation error
- 05James-Stein estimator and Stein's lemmaNonparametric bootstrapParametric bootstrap
- 02Condition number of a matrix
- 09Conditioning of a problem
The portfolio that looked optimal
In the previous lesson you solved a problem exactly with known means and covariances. In a real market those inputs are estimated. A portfolio optimizing estimated numbers can assign substantial weight to directions that happen to look most attractive by chance. The optimization is correct for its inputs; the mistake is interpreting those inputs as the future distribution.
Estimation-error amplification occurs in two steps. First, among many directions, some happen to have a high sample mean or low sample variance. Then the optimizer rewards those directions and concentrates them in the portfolio. This does not mean every sample necessarily produces an estimated frontier more optimistic than the true one: an estimate can err in either direction. The rigorous claim we will establish is that no budgeted portfolio can have true variance below the true GMV.
The Gaussian model is a one-period approximation for studying moments: it can produce simple returns below −100%, so we do not use it to construct realistic limited-wealth paths. The curves depend on the model and seed; changing the sample can make the estimate optimistic or pessimistic.
The mean is difficult to measure
If annual returns are independent, share a mean and finite variance , and the sample has years, the sample mean has standard error . With temporal dependence, its variance includes autocovariances: , so the simple formula does not always apply. Regime changes add another problem: more history does not guarantee that the estimated mean is the future mean.
For example, if the true annual premium is and volatility is , a standard error of , half the premium, requires years under the assumptions above. This is precision of one standard deviation, not a guarantee of being within that error. The calculation assumes known parameters to design it; it does not provide a way to know them in advance.
Spectrum and sample covariance
In the GMV formula, amplifies small-eigenvalue directions. If , the inverse multiplies the component along each eigenvector by . An abnormally small sample eigenvalue can produce large weights even when true variance in that direction is not small.
With assets and centered observations, the sample covariance has rank at most . If it is singular and the ordinary inverse does not exist. Even with , a ratio close to one can leave an ill-conditioned matrix. A numerical result from solve does not prove that weights are stable.
The Marchenko-Pastur law provides a noise reference for independent observations with identity population covariance and asymptotics with fixed . Its continuous support is ; if there is also point mass at zero. The upper edge is not universal proof that an eigenvalue is signal: true correlations, tails and temporal dependence change the reference.
Shrinkage: trading variance for bias
Ledoit-Wolf shrinkage combines the sample matrix with a structured target :
For deterministic intensity and expected squared Frobenius error, define and . The minimum over of is , provided the denominator is positive. The constrained minimum is obtained by clipping to . That expression is an oracle: it depends on unknown covariance. A practical rule estimates its components from the sample and must account for whether the target is also estimated from it.
A scaled identity preserves trace and pushes eigenvalues toward their mean. Ledoit and Wolf (2004) study that shrinkage toward identity under quadratic loss and a high-dimensional asymptotic regime. A constant-correlation target preserves individual variances and replaces correlations with a common mean; a one-factor model uses covariance explained by the factor plus residual risk. These are different targets and their estimated intensities are not interchangeable. sklearn.covariance.LedoitWolf implements the scaled-identity version, not constant correlation.
The mechanism is a bias-variance tradeoff. At you retain all noisy details of the sample; at you fully accept the target’s bias. If the target is a positive multiple of identity, each sample eigenvalue becomes , where . For this raises eigenvalues below the mean and does not increase the condition number, provided . An incorrect target also distorts real risk directions: regularization does not erase noise alone.
Cleaning the spectrum
Random-matrix cleaning starts with sample correlation, replaces eigenvalues within a reference band by an average and reconstructs the matrix using the same eigenvectors. The diagonal is then renormalized to one and scales are restored with estimated volatilities. This is a heuristic dependent on the null model: a real population direction can lie inside the band and an eigenvalue outside does not by itself prove a stable factor.
Nonlinear shrinkage retains sample eigenvectors but allows their eigenvalues to be treated differently. For a sample orthonormal basis and known truth, the value minimizing Frobenius loss between and a matrix diagonal in that basis is : it follows by minimizing each diagonal term of the loss. It is an oracle because it requires the truth. The analytical version by Ledoit and Wolf (2020) estimates a nonlinear spectral transformation; replacing values by groups or raising small eigenvalues is a simplification, not an implementation of that paper.
Resampling and a naive benchmark
Covariance is not the only uncertain parameter. The tangency direction also uses estimated premiums, and their error can change weights even if covariance is perfectly known. A James-Stein idea is to shrink a mean vector toward a target. In the ideal model with and known , the positive-part estimator toward zero is
At define the estimator as zero. In that model it reduces aggregate quadratic risk relative to ; the factor does not make every component a uniformly better estimate. In portfolios, shrinking toward a common mean or another target requires defining the metric and accounting for different correlations and variances. If the target or variance is estimated, or there is temporal dependence, the spherical-case guarantee does not carry over automatically. Lower mean squared error in means does not necessarily imply a higher Sharpe for a particular portfolio.
The resampled frontier re-estimates portfolios over multiple bootstrap samples and averages their weights for the same criterion. It stabilizes some decisions in certain models, but creates no new information and does not guarantee out-of-sample improvement. Distinguish a parametric bootstrap, which assumes a family, from the nonparametric bootstrap, which resamples observations and requires adaptation under temporal dependence.
The 1/N portfolio assigns equal weight to each asset and estimates neither means nor covariances. It is a demanding benchmark, not a universally optimal portfolio. DeMiguel, Garlappi and Uppal compared 14 models across seven empirical datasets and found none consistently superior to 1/N on the stated metrics. In their calculations and simulations calibrated to the US market, estimated required windows were approximately 3000 months for 25 assets and 6000 for 50. These horizons depend on calibration and are not universal constants.
Lab: estimators against known truth
We generate a monthly Gaussian factor model with 20 assets, three factors and independent idiosyncratic noise. True covariance is because factors have identity covariance and are independent of noise. This truth lets us measure estimator error; it will not be available in real data. For constant-correlation shrinkage we use divisor after centering, as in the authors’ reference implementation. The identity variant compared with sklearn uses divisor .
import numpy as np
from sklearn.covariance import LedoitWolf
rng=np.random.default_rng(280401)
n,t,k=20,160,3
B=rng.normal(0,.012,size=(n,k))
especifica=np.linspace(.012,.026,n)
[email protected]+np.diag(especifica**2)
media=np.linspace(.003,.008,n)
X=media+rng.normal(size=(t,k))@B.T+rng.normal(size=(t,n))*especifica
print('Dimensiones de la muestra:',X.shape)
print('Autovalor mínimo verdadero:',float(np.linalg.eigvalsh(verdad).min()))For constant-correlation shrinkage, intensity must correct for covariation between the sample-built target and the sample itself. We calculate the reference code’s estimates of , and : , with . The target depends on , so the scaled-identity formula is insufficient. If , target and sample coincide and any intensity produces the same matrix; we return zero by convention.
def constante_corr(datos):
Y=np.asarray(datos,dtype=float)
T,N=Y.shape
Y=Y-Y.mean(axis=0)
ne=T-1
S=Y.T@Y/ne
v=np.diag(S)
if T<2 or N<2 or np.any(v<=0):
raise ValueError('Se requieren al menos dos activos con varianza positiva')
escala=np.sqrt(v)
correl=S/np.outer(escala,escala)
rbar=(correl.sum()-N)/(N*(N-1))
F=rbar*np.outer(escala,escala)
np.fill_diagonal(F,v)
pi=(Y**2).T@(Y**2)/ne-S**2
gamma=np.sum((S-F)**2)
theta=(Y**3).T@Y/ne-v[:,None]*S
np.fill_diagonal(theta,0.)
rho=np.trace(pi)+rbar*np.sum((escala[None,:]/escala[:,None])*theta)
delta=0. if gamma<=1e-30 else np.clip((pi.sum()-rho)/(ne*gamma),0.,1.)
return (1-delta)*S+delta*F, float(delta)
cov_cor,delta_cor=constante_corr(X)
cov_identidad=LedoitWolf().fit(X)
print('Intensidad correlación constante:',round(delta_cor,4))
print('Intensidad identidad escalada:',round(float(cov_identidad.shrinkage_),4))The following clipping uses the identity edge as an approximation and rescales to correlation after modifying the spectrum. The median-floor rule is another deliberately simple nonlinear example: do not confuse it with the 2020 analytical estimator. Both rules are evaluated against the generator’s truth.
def limpieza_mp(datos):
Y=np.asarray(datos,dtype=float)
T,N=Y.shape
S=np.cov(Y,rowvar=False,ddof=1)
escala=np.sqrt(np.diag(S))
if np.any(escala<=0): raise ValueError('Varianzas positivas necesarias')
R=S/np.outer(escala,escala)
valores,U=np.linalg.eigh(R)
borde=(1+np.sqrt(N/T))**2
ruido=valores<=borde
nuevos=valores.copy()
if ruido.any(): nuevos[ruido]=valores[ruido].mean()
limpia=(U*nuevos)@U.T
diag=np.sqrt(np.diag(limpia))
limpia=limpia/np.outer(diag,diag)
return limpia*np.outer(escala,escala)
def suelo_espectral(datos):
S=np.cov(datos,rowvar=False,ddof=1)
valores,U=np.linalg.eigh(S)
return (U*np.maximum(valores,np.median(valores)))@U.T
estimadores={'Muestral':np.cov(X,rowvar=False,ddof=1),
'Identidad':cov_identidad.covariance_,
'Correlación constante':cov_cor,
'Recorte MP':limpieza_mp(X),
'Suelo espectral':suelo_espectral(X)}
for nombre,S in estimadores.items():
print(nombre,'error Frobenius',round(float(np.linalg.norm(S-verdad,'fro')),7),
'autovalor mínimo',round(float(np.linalg.eigvalsh(S).min()),8))A single sample does not establish that one method always wins. The intensity minimizing error against truth in that sample is an oracle diagnostic; optimizing it on the same sample and presenting its result as independent evaluation would produce a biased comparison. To choose between methods, repeat the experiment and keep fitting and evaluation samples separate.
In this cell’s seeded run, sample covariance has Frobenius error 0.0013234 and constant-correlation covariance 0.0013544: shrinkage does not improve that loss in this particular sample. MP clipping gives 0.0016744. This is a useful counterexample to the idea that cleaning always helps; neither one sample nor a matrix loss decides which portfolio will perform better. The figures come from the cell’s generator, not historical returns.
To build a resampled frontier rather than just one portfolio, choose nine mean targets and solve each in 20 resamples. Average weights per target and evaluate both ordinary and resampled weight sets with the generator’s true moments. Regularization toward identity is recalculated inside each resample. Each portfolio’s true mean may differ from its sample target: the figure shows that difference rather than imposing it artificially.
import matplotlib.pyplot as plt
def pesos_frontera(means,cov,objetivos):
one=np.ones(len(means))
x,y=np.linalg.solve(cov,np.column_stack((one,means))).T
A,B,C=one@x,one@y,means@y
D=A*C-B*B
if D<=1e-15: raise ValueError('Objetivos de media degenerados')
return np.array([((C-B*m)*x+(A*m-B)*y)/D for m in objetivos])
objetivos=np.linspace(X.mean(axis=0).min(),X.mean(axis=0).max(),9)
ordinarios=pesos_frontera(X.mean(axis=0),LedoitWolf().fit(X).covariance_,objetivos)
rg=np.random.default_rng(280402)
remuestreados=[]
for _ in range(20):
muestra=X[rg.integers(0,len(X),size=len(X))]
remuestreados.append(pesos_frontera(muestra.mean(axis=0),
LedoitWolf().fit(muestra).covariance_,objetivos))
promedio=np.mean(remuestreados,axis=0)
def evaluar_pesos(w):
return np.sqrt(np.einsum('ij,jk,ik->i',w,verdad,w)),w@media
v0,m0=evaluar_pesos(ordinarios)
v1,m1=evaluar_pesos(promedio)
fig,ax=plt.subplots()
ax.plot(v0,m0,'-o',ms=3,label='Ajuste ordinario, evaluación verdadera')
ax.plot(v1,m1,'-o',ms=3,label='Remuestreo, evaluación verdadera')
ax.set_xlabel('Volatilidad verdadera por periodo'); ax.set_ylabel('Media verdadera por periodo')
ax.legend(); plt.show()
print('Pesos remuestreados: máximo error de presupuesto',float(np.max(np.abs(promedio.sum(axis=1)-1))))
print('Objetivos:',len(objetivos),'| remuestras:',len(remuestreados))Lab: tournament with 100 assets
This experiment uses 100 assets and a known stationary factor model. It compares sample tangency, sample GMV, GMV with identity shrinkage, GMV with MP clipping, resampled tangency and 1/N. Each replicate generates two independent training windows and an evaluation window: the first sets weights, the second measures their change and the third calculates observed Sharpe and volatility. Mean-variance utility uses the true mean and variance, not the evaluation observations. The risk-free rate is zero and weights are rebalanced to target each evaluation period.
Execution is local because it includes many 100-asset matrix factorizations and resamples. For each length, 20 replicates and five resamples per portfolio are used: enough to run the full flow and present Monte Carlo uncertainty, but not for a high-precision conclusion. Increase repeticiones and bootstrap to study stability. Independent windows simplify change calculations and do not reproduce a backtest with positions drifting by price. Approximate normal Sharpe intervals require care, especially with extreme weights.
Centered sample covariance is singular for , so those portfolios are marked unavailable. Tangency requires a positive denominator to represent the positive-Sharpe direction with weights summing to one: it is excluded when that fails and the number of valid replicates is shown. Recording a replicate requires both training windows to yield valid weights because their change is also calculated. Methods can therefore have different valid samples. This follows from the protocol and must be considered when comparing.
import numpy as np
from sklearn.covariance import LedoitWolf
N,K=100,3
rng=np.random.default_rng(280410)
cargas=rng.normal(0,.012,size=(N,K))
idio=np.linspace(.025,.045,N)
mu_true=np.linspace(.003,.008,N)
[email protected]+np.diag(idio**2)
gamma=4.
repeticiones=20
bootstrap=5
def muestra(g,T):
return mu_true+g.normal(size=(T,K))@cargas.T+g.normal(size=(T,N))*idio
def limpieza_mp(datos):
T,N=datos.shape
S=np.cov(datos,rowvar=False,ddof=1)
escala=np.sqrt(np.diag(S))
if np.any(escala<=0): raise ValueError('Varianzas positivas necesarias')
R=S/np.outer(escala,escala)
valores,U=np.linalg.eigh(R)
ruido=valores<=(1+np.sqrt(N/T))**2
nuevos=valores.copy()
if ruido.any(): nuevos[ruido]=valores[ruido].mean()
limpia=(U*nuevos)@U.T
diag=np.sqrt(np.diag(limpia))
return limpia/np.outer(diag,diag)*np.outer(escala,escala)
def gmv(cov):
try: u=np.linalg.solve(cov,np.ones(N))
except np.linalg.LinAlgError: return None
d=u.sum()
return u/d if np.isfinite(d) and d>1e-12 else None
def tangente(datos,cov):
try: u=np.linalg.solve(cov,datos.mean(axis=0))
except np.linalg.LinAlgError: return None
d=u.sum()
return u/d if np.isfinite(d) and d>1e-12 else None
def carteras(datos,g):
T=len(datos)
S=np.cov(datos,rowvar=False,ddof=1)
# En T <= N no se usa pseudoinversa como si fuera la GMV ordinaria.
bien=T>N
out={'Tangente muestral':tangente(datos,S) if bien else None,
'GMV muestral':gmv(S) if bien else None,
'GMV identidad':gmv(LedoitWolf().fit(datos).covariance_),
'GMV MP':gmv(limpieza_mp(datos)),
'1/N':np.full(N,1/N)}
# Cada remuestra se regulariza con Ledoit-Wolf; si falla una dirección,
# se excluye el promedio de esa ventana y se informa del recuento final.
remuestras=[]
for _ in range(bootstrap):
res=datos[g.integers(0,T,size=T)]
w=tangente(res,LedoitWolf().fit(res).covariance_)
if w is not None: remuestras.append(w)
out['Tangente remuestreada']=np.mean(remuestras,axis=0) if len(remuestras)==bootstrap else None
return out
for T in (60,120,250,500,1000):
registros={}
for rep in range(repeticiones):
g=np.random.default_rng(280410+T*100+rep)
train1,train2,test=muestra(g,T),muestra(g,T),muestra(g,252)
first,second=carteras(train1,g),carteras(train2,g)
for nombre,w in first.items():
w2=second[nombre]
if w is None or w2 is None: continue
r=test@w
volatilidad=float(r.std(ddof=1))
if volatilidad<=0: continue
sharpe=float(r.mean()/volatilidad*np.sqrt(12))
vol_anual=float(volatilidad*np.sqrt(12))
utilidad=float(mu_true@w-gamma/2*(w@Sigma_true@w))
cambio=float(np.abs(w2-w).sum()/2)
registros.setdefault(nombre,[]).append((sharpe,vol_anual,utilidad,cambio))
print('T =',T)
for nombre in ('Tangente muestral','GMV muestral','GMV identidad','GMV MP','Tangente remuestreada','1/N'):
a=np.asarray(registros.get(nombre,[]))
if len(a)<2:
print(nombre,'| válidas',len(a),'| sin intervalo'); continue
promedio=a.mean(axis=0)
sem=a[:,0].std(ddof=1)/np.sqrt(len(a))
print(f'{nombre}: n={len(a)} S={promedio[0]:.3f} '
f'[{promedio[0]-1.96*sem:.3f},{promedio[0]+1.96*sem:.3f}] '
f'V={promedio[1]:.3f} U={promedio[2]:.5f} C={promedio[3]:.3f}')npm run lab and open the connection link.In the output, S is observed annualized Sharpe, the bracketed interval is its approximate Monte Carlo interval, V is observed annualized volatility, U is monthly utility under the true moments and C is change between target weights. Resampling here includes shrinkage in every resample and averages normalized tangency directions. This is a specific recipe, not a property of every resampled frontier. Nor is it a replication of DeMiguel and colleagues’ experiment: the generator, costs, sizes and evaluation differ. The comparison applies only to this model and stated Monte Carlo size.
For example, in the full run with , sample GMV had mean annualized volatility 0.016 and GMV with MP clipping had 0.012. These averages come from 20 replicates of this specific model using an independent evaluation sample. Comparison with the earlier individual sample shows why the metric matters: cleaning can have higher matrix error in one realization yet lower average portfolio risk in another experiment. The observation neither establishes a universal causal relationship nor validates clipping for data with temporal dependence or changing covariances.
Exercises
Step 1 of 3. What condition does the estimated portfolio share with the true one?
def lw_identity(X):
raise NotImplementedError()Summary
- Means are estimated slowly, and small sample covariance eigenvalues can amplify their own errors.
- The Marchenko-Pastur band is a reference under specific assumptions; cleaning and nonlinear shrinkage are not interchangeable.
- The oracle uses truth unavailable in real data. An experiment separating fitting and evaluation can measure estimation cost without attributing differences to a single cause.