Heteroskedasticity, autocorrelation and robust standard errors
Construct HC0–HC3, cluster and Newey-West standard errors, study heteroskedasticity and serial-correlation tests, and use design-based clustering and wild cluster bootstrap with few groups.
After this lesson you can
- Derive White's sandwich estimator and HC1, HC2 and HC3 leverage corrections.
- Test heteroskedasticity and serial correlation and interpret results without overclaiming.
- Implement Newey-West errors with Bartlett kernel and choose lag count.
- Calculate one- and two-way cluster errors and choose clustering by sampling or assignment design.
- Apply wild cluster bootstrap with Rademacher weights when groups are few.
Before you start
Many records are not always much information
Imagine a regression of vulnerability remediation times with multiple observations per repository. Two issues in the same repository can share team, processes and priorities. Treating every record as independent can make an interval appear more precise than warranted. The change depends on design, regressor and dependence structure; there is no universal factor.
Heteroskedasticity means conditional error variance changes with regressors. It does not by itself imply the OLS coefficient is inconsistent: if exogeneity, identification and appropriate law-of-large-numbers conditions hold, it can still estimate its target. Nor does it guarantee consistency. With endogeneity or a changed target, changing the covariance matrix does not fix coefficient bias.
Sandwich variance and leverage
In a sample with full-rank design , residual and , HC standard errors start from
For HC0, . HC1 multiplies all weights by ; HC2 uses and HC3 uses , where . Matrix is symmetric and idempotent and . If , HC2 and HC3 are undefined by those formulas.
The intuition is that an extreme point in regressor space can pull the fit toward itself. Its observed residual may be small precisely because the model has rotated toward it, while its position gives it much influence on the slope. In the figure move the point horizontally and vertically: the relationship need not be monotonic in each move. The four bars calculate slope errors, meaning square roots of full variances; HC factors apply to meat contributions before summing.
Why correct? Under and , , so
HC2 undoes that shrinkage of each squared residual under those specific assumptions. With heteroskedastic and conditionally uncorrelated errors, and dividing by does not necessarily recover . Under conditional dependence, the general expression is the diagonal of and also contains cross terms. HC3 relates to leave-one-out differences because the omitted prediction residual is when the reduced fit exists. It guarantees neither exact coverage nor improvement in every sample. See White’s original formulation.
Tests are not filters for robustness
Heteroskedasticity tests ask specific questions about variance structure. Breusch-Pagan relates squared residuals to auxiliary variables; White includes quadratic and cross terms. In common formulations, from an auxiliary regression has asymptotic reference under suitable assumptions and rank. Studentized Breusch-Pagan relaxes normality of the original version but retains its other conditions.
The Breusch-Pagan test is developed as a Lagrange-multiplier test. The specific version, auxiliary regressor set and assumptions should be included in the reported result.
Failure to reject does not prove homoskedasticity: the test can have low power or seek another form of variation. Choosing between classical and robust error only after a pretest changes inference properties. If design makes heteroskedasticity plausible and HC conditions hold, report the robust method and its limits.
In the example cell, variance increases with the absolute value of a regressor. The linear Breusch-Pagan auxiliary regression and expanded White regression need not respond alike: one includes a quadratic function of the regressor and the other, in that specification, only a linear function. The p-values correspond to a simulated sample; they do not establish a universal power hierarchy. If adding many products or categories, check rank and degrees of freedom before using the asymptotic reference.
For serial correlation, Durbin-Watson summarizes successive residual differences, but interpretation depends on the regression and does not replace general diagnosis. Breusch-Godfrey adds residual lags to an auxiliary regression retaining original regressors; under its null and regularity, the LM statistic is compared with with as many degrees of freedom as tested lags. A trend or misspecification can affect diagnosis: a small p-value does not itself identify its cause.
In the statsmodels version included in this browser, the Breusch-Godfrey function adds a constant even when the original model already contains one. This duplication leaves the auxiliary regression rank deficient and, with Pyodide’s numerical implementation, may alter its result. The exercise checks the auxiliary regression with one constant against explicit OLS; it does not assume the convenience function yields exactly the same figure in every version.
Long-run variance and Newey-West
In a time regression dependence of scores matters, not only that of residuals. Let
The Newey-West HAC estimator uses , with . Bartlett weights yield a positive-semidefinite estimate in the standard construction; see Newey and West. Normalization convention and finite corrections may vary between libraries.
The expression comes from expanding variance of a sum of scores: besides individual variances, covariances across dates appear. The window attenuates distant covariances to prevent very noisy estimates dominating the result. The graph uses an intercept-only model, where the score is the residual, to compare with an analytic variance; in a regression with other coefficients use the full vector .
To estimate dependence of unknown length, a common theory grows with and requires , along with moment and dependence conditions. Fixed generally does not recover all autocovariances. More lags reduce truncation but can increase estimation noise; do not choose to obtain significance. Prewhitening fits a model to scores before estimating their covariance and then transforms the result: it can help or introduce sensitivity to that fit.
In the special case of an intercept and stationary AR(1) errors with unit marginal variance and , long-run variance, the limit of , is . For large , variance of the mean is approximately that quantity divided by . With negative , ignoring lags can overestimate it; bias has no universal sign. Under the spectral convention with factor , long-run variance is .
Groups and assignment
With groups and grouped scores , cluster covariance replaces the meat by . A common CR1 correction multiplies by . Its asymptotic justification requires enough independent groups and conditions preventing a few from dominating. Many records within few groups do not equal many independent groups.
For two clustering dimensions use inclusion-exclusion:
Each term may have its own finite correction. The resulting sum may be indefinite in a particular sample; report this rather than hiding it by taking square roots of negative variances. Clustering level is chosen from assignment and sampling, not only observed correlations. Abadie and colleagues distinguish these sources of uncertainty; Cameron and Miller develop cluster inference practice.
In school-level assignment, all students at a school share assigned treatment; counting each student as an independent assignment confuses file size with the number of assigned units. In a panel, a firm-specific shock and another common to all firms in a year suggest considering both axes. These decisions require examining how data were generated and sampled, including number and size of groups and number of treated groups.
The multidimensional extension is studied by Cameron, Gelbach and Miller. When both factors share a cell, correction of that intersection depends on how each term is defined; document the convention before comparing libraries.
In a simplified model with equally sized groups and constant within-group regressor and error correlations, approximate variance factor appears. It is an approximation under that model and regime, not a generally necessary condition for clustering or exact equality in every finite sample. Other dependence patterns, unequal sizes and assignment design can change the conclusion.
Few groups: adjust the test, not promise miracles
With few clusters, CR1 and its reference approximation can over-reject in some designs. CR2 uses group matrix adjustments tied to a working model and is often accompanied by adjusted degrees of freedom; its form requires necessary matrices to be invertible. The restricted wild cluster bootstrap fits the null, multiplies each group’s restricted residuals by a common random weight and recalculates a studentized statistic.
Restricting the fit imposes the hypothesis to be tested before constructing resampled data. Studentizing means recalculating standard error for each bootstrap sample, not dividing every replicate by the original fit’s error. The simulation compares the observed statistic’s absolute value with that null distribution. A nonsignificant result can reflect little information or low power; it does not prove the effect is exactly zero.
With Rademacher weights choose or with equal probability; Webb’s distribution uses six symmetric values. With few groups the set of possible signs is limited and inference also depends on treated-group count, leverage and design. No bootstrap automatically turns a sample with little independent information into exact inference. The lesson compares variants in a reproducible simulation and shows Monte Carlo uncertainty.
The six Webb weights are equally probable: , and . In a two-sided test, specify how ties are counted and whether the p-value is exact weight enumeration or a Monte Carlo approximation. The code uses both cases depending on group count and identifies them in output.
Lab: build and check the sandwich
Calculate four HC variants, Bartlett HAC and clustered covariances from QR. The example compares full matrices with statsmodels under the same conventions; matching code does not prove those assumptions hold in an application. Heteroskedasticity tests use another simulated iid sample, not the clustered panel.
"""HC, HAC y covarianzas por grupos desde QR, contrastadas con statsmodels."""
import numpy as np
import statsmodels.api as sm
from statsmodels.stats.sandwich_covariance import cov_hac, cov_cluster, cov_cluster_2groups
from statsmodels.stats.diagnostic import het_breuschpagan, het_white, acorr_breusch_godfrey
from scipy.stats import chi2
rng = np.random.default_rng(270201)
n, group_size = 360, 20
group = np.repeat(np.arange(n//group_size),group_size)
time_group = np.tile(np.arange(group_size),n//group_size)
x = .6*rng.normal(size=n//group_size)[group] + rng.normal(size=n)
X = np.column_stack([np.ones(n),x])
u = .7*rng.normal(size=n//group_size)[group] + (.4+.3*np.abs(x))*rng.normal(size=n)
y = 1+2*x+u
q,r = np.linalg.qr(X,mode='reduced')
b = np.linalg.solve(r,q.T@y)
e = y-X@b
inv_r = np.linalg.solve(r,np.eye(X.shape[1]))
bread = inv_r@inv_r.T
leverage = np.sum(q*q,axis=1)
if np.any(leverage >= 1-1e-12):
raise ValueError('Apalancamiento demasiado cercano a uno')
def hc(kind):
weights = e*e
if kind == 'HC1': weights *= n/(n-X.shape[1])
if kind == 'HC2': weights /= 1-leverage
if kind == 'HC3': weights /= (1-leverage)**2
return bread@(X.T@(weights[:,None]*X))@bread
fit = sm.OLS(y,X).fit()
print('Coeficientes QR:',b)
for kind in ('HC0','HC1','HC2','HC3'):
ours=hc(kind)
ref=fit.get_robustcov_results(cov_type=kind).cov_params()
assert np.allclose(ours,ref,rtol=1e-10,atol=1e-12)
print(kind,'errores:',np.sqrt(np.diag(ours)))
def clustered(groups):
"""CR1: suma de scores por grupo, con corrección finita explícita."""
_,ids=np.unique(groups,return_inverse=True)
G=ids.max()+1
if G < 2: raise ValueError('Se necesitan al menos dos grupos')
scores=np.zeros((G,X.shape[1]))
np.add.at(scores,ids,X*e[:,None])
factor=G/(G-1)*(n-1)/(n-X.shape[1])
return factor*bread@(scores.T@scores)@bread
def hac(lags):
"""Bartlett con L fijo, sin corrección de grados de libertad."""
if not 0<=lags<n: raise ValueError('Retardos inválidos')
scores=X*e[:,None]
meat=scores.T@scores
for lag in range(1,lags+1):
cross=scores[lag:].T@scores[:-lag]
meat+=(1-lag/(lags+1))*(cross+cross.T)
return bread@meat@bread
one=clustered(group)
two=clustered(time_group)
pairs=np.column_stack([group,time_group])
_,intersection=np.unique(pairs,axis=0,return_inverse=True)
inter=clustered(intersection)
two_way=one+two-inter
reference_two=cov_cluster_2groups(fit,group,time_group,use_correction=True)[0]
assert np.allclose(one,cov_cluster(fit,group,use_correction=True),rtol=1e-10,atol=1e-12)
assert np.allclose(two_way,reference_two,rtol=1e-10,atol=1e-12)
L=int(np.floor(4*(n/100)**(2/9)))
ours_hac=hac(L)
assert np.allclose(ours_hac,cov_hac(fit,nlags=L,use_correction=False),rtol=1e-10,atol=1e-12)
print('CR1 una vía:',np.sqrt(np.diag(one)))
print('CR1 dos vías, diagonal:',np.diag(two_way),'autovalores:',np.linalg.eigvalsh(two_way))
print('HAC Bartlett L:',L,'errores:',np.sqrt(np.diag(ours_hac)))
print('L es una regla de ejemplo fijada antes de ver la significación; cambia según diseño.')
print('Las dos vías pueden producir una matriz indefinida en muestras finitas.')
# La referencia chi-cuadrado de BP/White presupone observaciones adecuadas para
# esos contrastes. Los datos agrupados anteriores no cumplen independencia.
z=rng.normal(size=400)
X_test=sm.add_constant(z)
sigma=.4+.6*np.abs(z)
y_test=1+2*z+sigma*rng.normal(size=400)
fit_test=sm.OLS(y_test,X_test).fit()
bp=het_breuschpagan(fit_test.resid,X_test,robust=True)
white=het_white(fit_test.resid,X_test)
print('Breusch-Pagan studentizado LM y p:',bp[:2])
print('White LM y p:',white[:2])
# Serie temporal independiente del panel anterior.
n_t=400
innovation=rng.normal(size=n_t)
serial=np.zeros(n_t)
for t in range(1,n_t): serial[t]=.6*serial[t-1]+innovation[t]
xt=rng.normal(size=n_t)
fit_time=sm.OLS(1+xt+serial,sm.add_constant(xt)).fit()
bg=acorr_breusch_godfrey(fit_time,nlags=2)
resid_time=fit_time.resid
lags_time=np.zeros((n_t,2))
lags_time[1:,0]=resid_time[:-1]
lags_time[2:,1]=resid_time[:-2]
aux_time=sm.OLS(resid_time,np.column_stack([fit_time.model.exog,lags_time])).fit()
print('BG con auxiliar de rango completo, LM y p:',n_t*aux_time.rsquared,chi2.sf(n_t*aux_time.rsquared,2))
print('Función de conveniencia, que puede duplicar la constante:',bg[:2])
print('Los p-valores son para estos datos simulados y las hipótesis de cada prueba.')The next simulation compares coverage in three different designs: heteroskedastic, temporal and clustered. The same samples are used for all estimators within each design; the reported Monte Carlo error describes each proportion, not the paired difference. HAC uses four lags chosen in advance and CR1 uses blocks of eight observations even in nonclustered cases: this permits comparison but does not justify it as a general method.
"""Cobertura emparejada de variantes HC, HAC y CR1 en tres modelos."""
import numpy as np
from scipy.stats import norm, t
gen=np.random.default_rng(270205)
N,G,M,REPS,L=160,20,8,240,4
critical=norm.ppf(.975)
groups=np.repeat(np.arange(G),M)
names=('HC0','HC1','HC2','HC3','HAC','CR1')
def one_sample(kind):
if kind=='heterocedástico':
x=gen.normal(size=N)
u=x*gen.normal(size=N)
elif kind=='temporal':
x=np.zeros(N); u=np.zeros(N)
x[0]=gen.normal(); u[0]=gen.normal()
for i in range(1,N):
x[i]=.6*x[i-1]+.8*gen.normal()
u[i]=.6*u[i-1]+.8*gen.normal()
else:
x=np.sqrt(.5)*gen.normal(size=G)[groups]+np.sqrt(.5)*gen.normal(size=N)
u=np.sqrt(.5)*gen.normal(size=G)[groups]+np.sqrt(.5)*gen.normal(size=N)
X=np.column_stack([np.ones(N),x])
y=1+x+u
q,r=np.linalg.qr(X,mode='reduced')
invr=np.linalg.solve(r,np.eye(2))
bread=invr@invr.T
beta=np.linalg.solve(r,q.T@y)
resid=y-X@beta
h=np.sum(q*q,axis=1)
scores=X*resid[:,None]
cov=[]
for weight in (np.ones(N),np.full(N,N/(N-2)),1/(1-h),1/(1-h)**2):
cov.append(bread@(scores.T@(weight[:,None]*scores))@bread)
meat=scores.T@scores
for lag in range(1,L+1):
cross=scores[lag:].T@scores[:-lag]
meat+=(1-lag/(L+1))*(cross+cross.T)
cov.append(bread@meat@bread)
grouped=np.zeros((G,2))
np.add.at(grouped,groups,scores)
cov.append((G/(G-1))*((N-1)/(N-2))*bread@(grouped.T@grouped)@bread)
se=np.sqrt([v[1,1] for v in cov])
return np.abs(beta[1]-1)<=se*np.array([critical]*5+[t.ppf(.975,G-1)])
for kind in ('heterocedástico','temporal','agrupado'):
hits=np.array([one_sample(kind) for _ in range(REPS)])
print(kind,'n',N,'réplicas',REPS)
for j,name in enumerate(names):
rate=hits[:,j].mean()
print(name,'cobertura',round(rate,4),'EE Monte Carlo aprox.',round(np.sqrt(rate*(1-rate)/REPS),4))
print('HC y HAC usan referencia normal; CR1 usa t(G−1); estimaciones emparejadas.')
print('Los bloques CR1 en las dos primeras filas son una elección ilustrativa, no una corrección universal.')Lab: restricted bootstrap with few groups
Treatment is assigned by group and the null is true in the generator. Restricted fitting precedes every resample: all members of a group receive the same weight. The code checks the vectorized version against explicit refitting and compares CR1 with Rademacher and Webb for 8, 15 and 50 groups. Intervals quantify outer-replicate variability; finitely many simulated weights add inner uncertainty. These rates belong to this design and are not universal guarantees.
"""Wild cluster bootstrap restringido, con contraste frente a ajuste directo.
El diseño tiene tratamiento asignado por grupo, error con componente común y
observaciones individuales independientes entre grupos. H0: beta_tratamiento=0.
El tamaño se estima con simulaciones independientes; no es garantía universal.
Las celdas se pueden ejecutar en Pyodide con NumPy y SciPy.
"""
import itertools
import math
import numpy as np
from scipy.stats import t as student_t
SEED = 270202
M = 12
RHO = .65
REPS = 200
B = 399
Z = 1.959963984540054
def wilson(k, n):
p=k/n
center=(p+Z*Z/(2*n))/(1+Z*Z/n)
half=Z*math.sqrt(p*(1-p)/n+Z*Z/(4*n*n))/(1+Z*Z/n)
return float(center-half), float(center+half)
def group_matrices(x, y):
"""Regresores y resultados como matrices (G,m); incluye intercepto."""
g,m = x.shape
X = np.stack((np.ones_like(x),x),axis=-1)
A = np.einsum('gmi,gmj->gij',X,X)
total = A.sum(axis=0)
if np.linalg.matrix_rank(total)<2: raise ValueError('Diseño sin rango completo')
inv = np.linalg.inv(total)
beta = inv @ np.einsum('gmi,gm->i',X,y)
resid = y-np.einsum('gmi,i->gm',X,beta)
score = np.einsum('gmi,gm->gi',X,resid)
factor = g/(g-1)*(g*m-1)/(g*m-2)
se = math.sqrt(factor*np.sum((score@inv[:,1])**2))
if se <= 1e-14: raise ValueError('Error estándar degenerado')
return X,A,inv,beta,resid,score,factor,se
def restricted_bootstrap(x, y, weights):
"""Devuelve t observado y t* CR1, imponiendo H0 y misma v por grupo."""
X,A,inv,beta,resid,score,factor,se = group_matrices(x,y)
null_intercept = y.mean()
null_resid = y-null_intercept
c = np.einsum('gmi,gm->gi',X,null_resid)
delta = (weights@c)@inv.T
scores = weights[:,:,None]*c[None,:,:] - np.einsum('gij,bj->bgi',A,delta)
bootstrap_se = np.sqrt(factor*np.sum((scores@inv[:,1])**2,axis=1))
if np.any(bootstrap_se<=1e-14): raise ValueError('t* degenerado')
return beta[1]/se, delta[:,1]/bootstrap_se
def direct_bootstrap(x,y,weights):
"""Referencia deliberadamente lenta que regenera y* y reajusta OLS."""
alpha=y.mean()
residual=y-alpha
observed=group_matrices(x,y)[3][1]/group_matrices(x,y)[7]
values=[]
for v in weights:
y_star=alpha+v[:,None]*residual
parts=group_matrices(x,y_star)
values.append(parts[3][1]/parts[7])
return observed,np.array(values)
def draws(g,rng,distribution):
if distribution=='rademacher' and g==8:
return np.array(list(itertools.product((-1.,1.),repeat=g)))
if distribution=='rademacher':
return rng.choice(np.array([-1.,1.]),size=(B,g))
if distribution=='webb':
choices=np.array([-math.sqrt(1.5),-1.,-math.sqrt(.5),math.sqrt(.5),1.,math.sqrt(1.5)])
return rng.choice(choices,size=(B,g))
raise ValueError('Distribución desconocida')
def data(g,rng):
# Mitad aproximada de grupos tratados, con orden aleatorizado.
treatment=np.r_[np.zeros(g//2),np.ones(g-g//2)]
rng.shuffle(treatment)
x=np.repeat(treatment[:,None],M,axis=1)
group=rng.normal(size=(g,1))
individual=rng.normal(size=(g,M))
y=2+math.sqrt(RHO)*group+math.sqrt(1-RHO)*individual
return x,y
def p_value(tobs,tstar,exact):
# Prueba bilateral, incluye empates; para muestras Monte Carlo usa +1.
count=np.count_nonzero(np.abs(tstar)>=abs(tobs)-1e-12)
return count/len(tstar) if exact else (count+1)/(len(tstar)+1)
# Comprueba cada estadístico, ambos pesos y mismo conjunto de réplicas.
validate_rng=np.random.default_rng(SEED+1)
x,y=data(8,validate_rng)
for distribution in ('rademacher','webb'):
w=draws(8,validate_rng,distribution)[:16]
fast=restricted_bootstrap(x,y,w)
slow=direct_bootstrap(x,y,w)
assert np.allclose(fast[0],slow[0],rtol=1e-10,atol=1e-10)
assert np.allclose(fast[1],slow[1],rtol=1e-10,atol=1e-10)
print('Reajuste directo y vectorizado:',distribution,'máx. diferencia t*',np.max(np.abs(fast[1]-slow[1])))
# Corrientes separadas para datos y pesos: modificar B no altera las muestras.
for g in (8,15,50):
data_rng=np.random.default_rng(SEED+g)
boot_rng=np.random.default_rng(SEED+100+g)
hits={'CR1':0,'Rademacher':0,'Webb':0}
for rep in range(REPS):
x,y=data(g,data_rng)
wr=draws(g,boot_rng,'rademacher')
tobs,tr=restricted_bootstrap(x,y,wr)
ww=draws(g,boot_rng,'webb')
_,tw=restricted_bootstrap(x,y,ww)
hits['CR1'] += abs(tobs)>student_t.ppf(.975,g-1)
hits['Rademacher'] += p_value(tobs,tr,g==8)<.05
hits['Webb'] += p_value(tobs,tw,False)<.05
print('Grupos:',g,'series:',REPS,'observaciones/grupo:',M,'ICC error:',RHO)
for name,k in hits.items():
print(name,'rechazos:',k,'/',REPS,'tasa:',k/REPS,'IC Monte Carlo Wilson 95 %:',wilson(k,REPS))
print('Bootstrap: Rademacher exacto' if g==8 else 'Bootstrap: Rademacher Monte Carlo',
'; Webb Monte Carlo, B=',B,'; α=0,05 bilateral.')
print('Los intervalos Wilson cuantifican solo variación entre simulaciones, no error del bootstrap interior.')
print('CR1 usa t(G−1); el bootstrap restringido usa t* studentizado CR1. Ningún método garantiza tamaño exacto aquí.')Exercises
Step 1 of 3. What matrix is the conditional covariance of û?
import numpy as np
def cluster_se(X,resid,groups):
passimport numpy as np
def bg_lm(X,y,p):
passimport numpy as np
import statsmodels.api as sm
from scipy.stats import chi2
rng_bg=np.random.default_rng(270204)
n_bg, p_bg, replicas_bg = 200, 2, 300
values_bg=[]
for _ in range(replicas_bg):
x_bg=rng_bg.normal(size=n_bg)
X_bg=np.column_stack([np.ones(n_bg),x_bg])
y_bg=1+x_bg+rng_bg.normal(size=n_bg)
fit_bg=sm.OLS(y_bg,X_bg).fit()
resid_bg=fit_bg.resid
lagged_bg=np.zeros((n_bg,p_bg))
for j in range(1,p_bg+1):
lagged_bg[j:,j-1]=resid_bg[:-j]
auxiliary_bg=sm.OLS(resid_bg,np.column_stack([X_bg,lagged_bg])).fit()
values_bg.append(n_bg*auxiliary_bg.rsquared)
values_bg=np.asarray(values_bg)
reject_bg=np.mean(values_bg>chi2.ppf(.95,p_bg))
print('BG bajo nula iid: réplicas, rechazo al 5 %, media LM:',replicas_bg,reject_bg,values_bg.mean())
print('Referencia chi-cuadrado: grados, media y cuantil 95 %:',p_bg,chi2.mean(p_bg),chi2.ppf(.95,p_bg))
print('Incertidumbre Monte Carlo aproximada de la tasa:',np.sqrt(reject_bg*(1-reject_bg)/replicas_bg))
print('La aproximación asintótica no garantiza tamaño exacto con muestras finitas.')import numpy as np
factor = 1+(40-1)*0.4*0.2
print('Factor de varianza y factor de error estándar:',factor,np.sqrt(factor))