Module contents
Lesson 2 of 28Core 100 min

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 XX, residual u^\hat u and B=(X⊤X)−1B=(X^\top X)^{-1}, HC standard errors start from

V^HC=B(∑i=1nxixi⊤wi)B.\widehat V_{\mathrm{HC}}=B\left(\sum_{i=1}^n x_i x_i^\top w_i\right)B.

For HC0, wi=u^i2w_i=\hat u_i^2. HC1 multiplies all weights by n/(n−p)n/(n-p); HC2 uses u^i2/(1−hii)\hat u_i^2/(1-h_{ii}) and HC3 uses u^i2/(1−hii)2\hat u_i^2/(1-h_{ii})^2, where hii=xi⊤Bxih_{ii}=x_i^\top Bx_i. Matrix H=XBX⊤H=XBX^\top is symmetric and idempotent and 0≤hii≤10\le h_{ii}\le1. If hii=1h_{ii}=1, 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 E[u∣X]=0E[u\mid X]=0 and Var⁡(u∣X)=σ2I\operatorname{Var}(u\mid X)=\sigma^2I, u^=(I−H)u\hat u=(I-H)u, so

E[u^i2∣X]=σ2[(I−H)2]ii=σ2(1−hii).E[\hat u_i^2\mid X] =\sigma^2[(I-H)^2]_{ii} =\sigma^2(1-h_{ii}).

HC2 undoes that shrinkage of each squared residual under those specific assumptions. With heteroskedastic and conditionally uncorrelated errors, E[u^i2∣X]=∑j(δij−hij)2σj2E[\hat u_i^2\mid X]=\sum_j(\delta_{ij}-h_{ij})^2\sigma_j^2 and dividing by 1−hii1-h_{ii} does not necessarily recover σi2\sigma_i^2. Under conditional dependence, the general expression is the diagonal of MVar⁡(u∣X)M⊤M\operatorname{Var}(u\mid X)M^\top and also contains cross terms. HC3 relates to leave-one-out differences because the omitted prediction residual is u^i/(1−hii)\hat u_i/(1-h_{ii}) when the reduced fit exists. It guarantees neither exact coverage nor improvement in every sample. See White’s original formulation.

InteractiveOne influential point and four adjustments

The line is refitted to all 14 points whenever you move the highlighted point. The dotted line is its vertical residual.

-1024604812xy

Slope standard errors: each bar uses all residuals and all leverage values, not just those of the highlighted point.

HC0
0.261
HC1
0.282
HC2
0.503
HC3
1.016

Deterministic synthetic model: xᵢ = −1 + i/6 for i = 0,…,12 and yᵢ = 1 + 1.2xᵢ + 0.25 sin(3.1xᵢ) + 0.2 cos(7xᵢ). You control the fourteenth point. No real sample is shown.

HC0 uses eᵢ²; HC1 multiplies it by n/(n−2); HC2 and HC3 divide it by 1−hᵢᵢ and (1−hᵢᵢ)², respectively. With homoskedastic errors and fixed design, E[eᵢ² | X] = σ²(1−hᵢᵢ). These corrections can become very unstable as hᵢᵢ approaches 1.

Greater leverage does not guarantee a smaller residual for every displacement, and HC2 or HC3 do not guarantee corrected bias or coverage in a particular sample. The bars compare uncertainty estimators; they are not the true error.

4.00
12.0
Leverage hᵢᵢ0.764
Point residual1.275
OLS slope2.400
Factor HC24.24
Factor HC317.99
Move the point, observe leverage and compare slope standard errors.

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, nR2nR^2 from an auxiliary regression has asymptotic reference χ2\chi^2 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 χ2\chi^2 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 st=xtu^ts_t=x_t\hat u_t matters, not only that of residuals. Let

Γ^ℓ=1n∑t=ℓ+1nstst−ℓ⊤,Ω^L=Γ^0+∑ℓ=1L(1−ℓL+1)(Γ^ℓ+Γ^ℓ⊤).\widehat\Gamma_\ell=\frac1n\sum_{t=\ell+1}^{n}s_t s_{t-\ell}^\top,\qquad \widehat\Omega_L=\widehat\Gamma_0+ \sum_{\ell=1}^{L}\left(1-\frac{\ell}{L+1}\right) (\widehat\Gamma_\ell+\widehat\Gamma_\ell^\top).

The Newey-West HAC estimator uses Qn−1Ω^LQn−1/nQ_n^{-1}\widehat\Omega_LQ_n^{-1}/n, with Qn=X⊤X/nQ_n=X^\top X/n. 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 xtu^tx_t\hat u_t.

To estimate dependence of unknown length, a common theory grows LL with nn and requires L/n→0L/n\to0, along with moment and dependence conditions. Fixed LL generally does not recover all autocovariances. More lags reduce truncation but can increase estimation noise; do not choose LL 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 ∣ϕ∣<1|\phi|<1, long-run variance, the limit of nVar⁡(uˉ)n\operatorname{Var}(\bar u), is (1+ϕ)/(1−ϕ)(1+\phi)/(1-\phi). For large nn, variance of the mean is approximately that quantity divided by nn. With negative ϕ\phi, ignoring lags can overestimate it; bias has no universal sign. Under the spectral convention with factor 1/(2π)1/(2\pi), long-run variance is 2πf(0)2\pi f(0).

InteractiveThe Newey-West window

A series of 160 observations: blue bars are centered autocovariances; orange bars multiply them by Bartlett weights. Each positive lag contributes twice its orange bar to the long-run estimate.

Lag k

  • Autocovariance
  • Bartlett weighted

Window wₖ=1−k/(L+1) for k≤L and zero afterward; L=0 retains only lag zero.

Generate standard normal u₀ and uₜ=φuₜ₋₁+√(1−φ²)εₜ with independent normal innovations. Thus Var(uₜ)=1 and the long-run variance of the mean is (1+φ)/(1−φ). The first series stays fixed as L changes; changing φ or seed generates new series.

For each of 1000 series calculate the mean and a 95% Wald interval with standard error √(HAC/160); the Wilson interval quantifies uncertainty in simulated coverage. The reference n × Var(mean) has a finite-sample formula distinct from its limit. Short or long windows can bias the estimate or make it variable; the direction depends on dependence and sample.

This is an intercept-only regression, where the score equals the residual. In general regressions Newey–West applies to vectors xₜûₜ, not just residuals, and requires dependence conditions and an appropriate choice of L.

0.6
6
1
Theoretical long-run variance4.000
First series: HAC estimate2.586
Mean HAC across replicates2.791
n × exact variance of mean3.953
Simulated coverage89.2 %
95% Monte Carlo CI87.1 % to 91.0 %
Change autocorrelation and lags to compare estimation and coverage in an explicit AR(1).

Groups and assignment

With groups g=1,…,Gg=1,\ldots,G and grouped scores Sg=∑i∈gxiu^iS_g=\sum_{i\in g}x_i\hat u_i, cluster covariance replaces the meat by ∑gSgSg⊤\sum_g S_gS_g^\top. A common CR1 correction multiplies by G/(G−1)⋅(n−1)/(n−p)G/(G-1)\cdot(n-1)/(n-p). 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:

V^A,B=V^A+V^B−V^A∩B.\widehat V_{A,B}=\widehat V_A+\widehat V_B-\widehat V_{A\cap B}.

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 mm and constant within-group regressor and error correlations, approximate variance factor 1+(m−1)ρxρu1+(m-1)\rho_x\rho_u 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.

InteractiveEffective size depends on design

In 1600 independent simulated samples the true slope is zero. Each dot shows the rejection proportion of a nominal 5% two-sided test; its bar is a 95% Wilson Monte Carlo interval. All three methods use the same samples.

Classical25.0 %; CI [22.9 %, 27.2 %]
HC125.9 %; CI [23.8 %, 28.1 %]
Cluster CR18.7 %; CI [7.4 %, 10.2 %]
0 %30 %

The vertical mark indicates 5%. Classical and HC1 tests use the normal quantile; CR1 uses correction G/(G−1) · (N−1)/(N−2) and t with G−1 degrees of freedom. None guarantees exact size with few groups.

Independent normal components are generated for each group: X=√ρX A+√(1−ρX) a and u=√ρu B+√(1−ρu) b; Y=u. Uppercase letters are shared by the group and lowercase letters individual. Regress Y on a constant and X; the model is exogenous by construction.

The approximate factor 1+(m−1)ρXρu compares slope variances under an ideal balanced design. In finite samples, when estimating the intercept, the exact factor conditional on each X is 1+ρu[Σg(Σi(Xgi−X̄))²/Σgi(Xgi−X̄)²−1]; its mean over replicates is shown. These are variance factors; standard error is multiplied by their square root.

In this balanced model, setting either correlation to zero removes approximate Moulton inflation. This does not imply clustering is irrelevant in other designs or that CR1 always over-rejects: group count, design and simulation randomness matter.

Number of groups G
Observations per group m
0.5
0.1
1
Observations400
Approximate Moulton factor3.45
Mean conditional factor3.16
Simulate clustered samples and compare paired rejection rates with Monte Carlo uncertainty.

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 −1-1 or +1+1 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: ±1/2\pm\sqrt{1/2}, ±1\pm1 and ±3/2\pm\sqrt{3/2}. 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 and clusters from scratchBrowser
"""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.

[ ]HC, HAC and CR1 coverageBrowser
"""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))
    [email protected]
    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.

[ ]Restricted wild cluster bootstrapBrowser
"""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

ProofWhy a residual shrinks
Prove: With fixed full-rank X, E[u|X]=0 and Var(u|X)=σ²I, show E[ûᵢ²|X]=σ²(1−hᵢᵢ).
0
Write the residual vector using residual projector M=I−H.

Step 1 of 3. What matrix is the conditional covariance of û?

NumericClustered variance factor
In the described equicorrelated model, groups have 40 observations, ρₓ=0.4 and ρᵤ=0.2. What approximate factor multiplies variance, not standard error?
QuizTreatment assigned by school
A program is assigned by school and you observe many students in each. What initial inference is most defensible?
QuizFirm panel and macro series
Compare a panel with firm- and year-shared shocks against a single macro time series. Which strategy best respects those dependencies?
QuizHousehold sampling
Independent households are sampled and several members of each interviewed. What is the first check for uncertainty?
CodeCluster standard errors
Implement cluster_se(X,resid,groups) for finite full-rank X with n>p, finite residuals and at least two group labels. Return CR1 standard errors with factor G/(G−1)·(n−1)/(n−p).
import numpy as np

def cluster_se(X,resid,groups):
  pass
Shift+Enter to run
CodeBreusch-Godfrey from residuals
Implement bg_lm(X,y,p) for n observations, p lags and full-rank X whose first column is a constant of ones. Fit OLS, add p lags of its residuals filling the first entries with zeros and return n·R² of the auxiliary regression. Reject invalid shapes and rank.
import numpy as np

def bg_lm(X,y,p):
  pass
Shift+Enter to run
[ ]Simulate the Breusch-Godfrey nullBrowser
import 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.')
[ ]Check the variance factorBrowser
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))