Module contents
Stage 4 of 9Advanced 100 min

Instrumental variables and the return to schooling

Use Card's college-proximity data to estimate returns to education with instrumental variables. Implement matrix 2SLS, simulate weak-instrument behavior, construct Anderson-Rubin sets, and examine local-effect interpretation.

After this lesson you can

  • Implement 2SLS with appropriate standard errors and compare with OLS.
  • Demonstrate weak-instrument bias toward OLS and poor coverage by simulation.
  • Construct Anderson-Rubin confidence regions by test inversion.
  • Interpret local treatment effects and characterize compliers under stated assumptions.

Before you start

A different source of variation

How much do wages change with additional education? Comparing people with different years of study mixes that change with prior differences in skills, family environment, and opportunities. An instrumental variable seeks education variation independent of those omitted causes that affects wages through no other route. A variable cannot qualify merely because it predicts education.

Card studied proximity to a college as a source of variation. The instrument nearc4 indicates proximity to a four-year institution in 1966; treatment is years of education and outcome is log hourly wage in 1976. The historical data concern men in the NLS Young Men cohort. Results of this exploratory analysis do not necessarily generalize to women, other cohorts, or current policies.

Relevance requires the instrument to change education after adjusting for covariates. Independence requires proximity, conditional on those variables, to be independent of relevant potential outcomes and treatments. Exclusion requires proximity to affect wages only through education. This is debatable: a nearby area may offer different jobs, networks, or family conditions. Controlling for region and observed characteristics may help, but does not prove exclusion or absence of selection. A strong instrument can be invalid.

Two projections, one uncertainty

With exogenous controls XX, treatment DD, and excluded instrument ZZ, define A=[X,D]A=[X,D], Q=[X,Z]Q=[X,Z], and PQ=Q(Q⊤Q)−1Q⊤P_Q=Q(Q^\top Q)^{-1}Q^\top. The two-stage least squares estimator is

β^=(A⊤PQA)−1A⊤PQY.\hat\beta=(A^\top P_Q A)^{-1}A^\top P_QY.

All regressors are projected onto the instrument space and the outcome is fitted on that projection. In code use least squares or factorizations rather than building an n×nn\times n projection matrix unnecessarily. Here the first stage fits education using controls and proximity. The second uses predicted variation, but its structural residuals are Y−Aβ^Y-A\hat\beta, not Y−PQAβ^Y-P_QA\hat\beta.

For HC0, write A^=PQA\hat A=P_QA and u^i=Yi−Aiβ^\hat u_i=Y_i-A_i\hat\beta. The sandwich matrix is (A^⊤A^)−1[∑iA^iA^i⊤u^i2](A^⊤A^)−1(\hat A^\top\hat A)^{-1}[\sum_i \hat A_i\hat A_i^\top\hat u_i^2](\hat A^\top\hat A)^{-1}. Fitting OLS on predicted values and taking its usual standard error uses different residuals and does not automatically provide correct 2SLS uncertainty. HC0 permits heteroskedasticity asymptotically under regularity conditions; it does not fix a weak or invalid instrument.

Weakness and sets that can be infinite

Weak-instrument inference is difficult because dividing by a small first stage yields unstable estimates and can impair the Wald interval’s normal approximation. The first-stage F statistic diagnoses strength, not exclusion; a value above 10 alone does not guarantee validity in all settings, especially with multiple instruments or heteroskedasticity. Andrews, Stock, and Sun detail these limitations.

InteractiveDistributions and coverage as the instrument weakens

2SLS: distribution of estimates, true effect 1

OLS: distribution of estimates

There are 287 2SLS estimates outside the axis; they remain in calculations and the JSON. At zero strength the population is not identified, and the estimator can have extreme tails: the median avoids summarizing them with an unstable mean.

Mean first-stage F2.94
Median 2SLS1.15
Median OLS1.90
Wald coverage87.8 %
Anderson-Rubin coverage94.8 %
Gaussian simulations with true effect 1; the plot clips its axis, not the replicates used for coverage and medians.

Each replicate generates independent standard normals Z,V,EZ,V,E, centers ZZ within the sample, and calculates D=πZ+VD=\pi Z+V and Y=D+UY=D+U, with U=ρV+1−ρ2EU=\rho V+\sqrt{1-\rho^2}E. Regressions include an intercept. The true structural effect is 1; ρ\rho controls endogeneity and π\pi strength. Each combination uses 2,000 samples of 300 observations and seed 401. With π=0.08\pi=0.08 and ρ=0.9\rho=0.9, the mean classical F is 2.94: that does not mean every replicate has F below 5. Observed HC0 Wald coverage was 87.85%, versus 94.75% for Anderson-Rubin inversion at the true value. Approximate Monte Carlo errors are 0.73 and 0.50 percentage points respectively. When π=0\pi=0, the population does not identify the coefficient and the ratio distribution has very long tails; we show median and count outside the axis rather than a potentially unstable mean.

To test H0:β=bH_0:\beta=b, Anderson-Rubin regresses Y−bDY-bD on XX and ZZ and tests whether the coefficient of ZZ is zero. The confidence region contains values of bb not rejected. The classical tt test is exact under homoskedastic normal errors and instrument independence, even with a weak first stage; it is not automatically exact under heteroskedasticity or false exclusion. Robust versions require appropriate variance and calibration. The set can be an interval, two rays, the whole line, or, in more general settings, empty. A finite grid shows only its range: acceptance at an endpoint does not prove the set ends there. The lab also calculates exact quadratic inversion for one instrument under its homoskedastic model. See the review of AR sets.

Which population does the effect describe?

In the binary case Z,D∈{0,1}Z,D\in\{0,1\}, with independent instrument, exclusion, relevance, and monotonicity D(1)≥D(0)D(1)\ge D(0), compliers are those who would receive treatment with Z=1Z=1 and not with Z=0Z=0. The Wald ratio identifies their local average effect, as Imbens and Angrist explain. We do not observe both potential treatments for each individual, so cannot identify every complier from the table alone. Under those assumptions, the complier proportion can be identified from the first stage and covariate distributions characterized by appropriate contrasts; that does not mean all treated people are compliers.

For example, if instrument independence is unconditional and XX is a pre-treatment characteristic, the mean of XX among compliers is [E(XD∣Z=1)−E(XD∣Z=0)]/[E(D∣Z=1)−E(D∣Z=0)][E(XD\mid Z=1)-E(XD\mid Z=0)]/[E(D\mid Z=1)-E(D\mid Z=0)]. The numerator subtracts those who would receive treatment under both values of ZZ, leaving the compliers’ contribution; the denominator is their proportion under monotonicity. With only conditional independence, appropriate adjustments and weights are needed. No formula identifies a specific person’s complier status.

In Card, education is measured in years and can take more than two values. Do not directly label the coefficient as the binary LATE above. Under additional monotonicity, independence, and exclusion assumptions it can be interpreted as a weighted average of marginal effects of induced schooling changes, with weights and population depending on the instrument and specification. The estimate does not imply the average effect of an extra year for the whole population or directly identify each person whose schooling changed.

Card’s sample under this specification

We use the Card file distributed by linearmodels 7.0, with 3,010 rows. Original data and materials are on Card’s page. We fit an intercept, age, age squared, race indicator, 1966 metropolitan area, and eight 1966 regional indicators; the ninth reference region is omitted. These are choices of this unweighted exploratory example. Potential experience calculated from education is not used as though automatically an exogenous pre-treatment covariate.

ResultEstimate
Adjusted OLS, log wage per year0.0375
2SLS with proximity, log wage per year0.1019
2SLS HC0 standard error0.0394
95% normal Wald interval[0.0246, 0.1793]
95% classical AR set[0.0294, 0.2138]
Classical first-stage F16.52

The first stage estimates 0.465 more years of education for proximity, conditional on controls. The log coefficient is approximately 10.2% per year for small changes; the exact exponential transformation of 0.1019 gives approximately 10.7%. This is this lesson’s specification, not a transcription of Card’s published table. The displayed AR interval uses the normal homoskedastic model, while Wald uses HC0; these are distinct choices and neither validates the instrument. Wage-sample selection and specification must be discussed before extrapolating.

Laboratory

With Python 3.12 install python -m pip install "numpy==2.2.6" "scipy==1.15.3" "pandas==2.3.3" "linearmodels==7.0". The cell implements projections and HC0, compares coefficients and errors with linearmodels, inverts the AR test, analyzes Card, and runs simulations. The Card file included in linearmodels 7.0 is card.csv.bz2 with SHA-256 10181955c6486c2b7c05c0f48e374c34f0990f58a6a8c51d68a01cd21a92d61a. Results depend on this version and stated selection.

Download iv.py, test_iv.py, and experiments.py into the same directory. The complete results contain each simulated estimate and versions; at interval endpoints, null represents negative infinity on the left or positive infinity on the right. Run python test_iv.py and then python experiments.py --out results.json --reps 2000. The program does not overwrite the result.

[ ]2SLS, Anderson-Rubin, and CardLocal GPU
"""2SLS, errores HC0 y conjuntos Anderson-Rubin para un instrumento."""
import numpy as np
from scipy.stats import t as student_t

def _check(y,d,z,X):
    y,d,z=map(lambda a:np.asarray(a,float).reshape(-1),(y,d,z));X=np.asarray(X,float)
    if X.ndim!=2 or any(len(a)!=len(y) for a in (d,z,X)) or len(y)<=X.shape[1]+1:raise ValueError('Dimensiones incompatibles')
    if not all(np.isfinite(a).all() for a in (y,d,z,X)):raise ValueError('Datos no finitos')
    if np.linalg.matrix_rank(np.column_stack((X,z)))<X.shape[1]+1:raise ValueError('Instrumentos colineales')
    return y,d,z,X

def iv2sls(y,d,z,X):
    y,d,z,X=_check(y,d,z,X)
    design=np.column_stack((X,d));instruments=np.column_stack((X,z))
    [email protected](instruments,design,rcond=None)[0]
    bread=fitted.T@fitted
    if np.linalg.matrix_rank(bread)<bread.shape[0]:raise ValueError('Instrumento no identifica la muestra')
    beta=np.linalg.solve(bread,fitted.T@y)
    resid=y-design@beta
    influence=np.linalg.solve(bread,(fitted*resid[:,None]).T)
    [email protected]
    return beta,np.sqrt(np.maximum(0,np.diag(vcov)))

def residual(a,X):return [email protected](X,a,rcond=None)[0]

def ar_test(y,d,z,X,beta,alpha=.05):
    y,d,z,X=_check(y,d,z,X)
    if not 0<alpha<1:raise ValueError('alpha fuera de rango')
    w=residual(y-beta*d,X);zr=residual(z,X);zz=zr@zr
    error=w-zr*(zr@w)/zz;df=len(y)-X.shape[1]-1
    variance=(error@error)/df
    if variance<=0:raise ValueError('Varianza residual nula: test t no definido')
    stat=abs(zr@w)/np.sqrt(zz*variance)
    return bool(stat<=student_t.ppf(1-alpha/2,df)),float(stat)

def anderson_rubin_grid(y,d,z,X,grid,alpha=.05):
    grid=np.asarray(grid,float)
    if grid.ndim!=1 or not np.isfinite(grid).all():raise ValueError('Rejilla no válida')
    return np.array([ar_test(y,d,z,X,b,alpha)[0] for b in grid])

def ar_set(y,d,z,X,alpha=.05):
    """Inversión analítica homocedástica: lista de intervalos, extremos infinitos."""
    y,d,z,X=_check(y,d,z,X)
    if not 0<alpha<1:raise ValueError('alpha fuera de rango')
    zr=residual(z,X);yr=residual(y,X);dr=residual(d,X)
    zz=zr@zr;zy=zr@yr;zd=zr@dr;df=len(y)-X.shape[1]-1
    ey=yr-zr*zy/zz;ed=dr-zr*zd/zz
    c=student_t.ppf(1-alpha/2,df)**2*zz/df
    a=zd*zd-c*(ed@ed);b=-2*zy*zd+2*c*(ey@ed);q=zy*zy-c*(ey@ey)
    if abs(a)<1e-12:
        if abs(b)<1e-12:return [(-np.inf,np.inf)] if q<=0 else []
        root=-q/b;return [(-np.inf,root)] if b>0 else [(root,np.inf)]
    disc=b*b-4*a*q
    if disc<0:return [(-np.inf,np.inf)] if a<0 else []
    r1,r2=sorted(((-b-np.sqrt(disc))/(2*a),(-b+np.sqrt(disc))/(2*a)))
    return [(r1,r2)] if a>0 else [(-np.inf,r1),(r2,np.inf)]

"""Contraste de HC0, proyección y pruebas AR dentro/fuera de raíces."""
import numpy as np
from linearmodels.iv import IV2SLS

rng=np.random.default_rng(402);n=500
x=np.column_stack((np.ones(n),rng.normal(size=n)))
z=rng.normal(size=n);u=rng.normal(size=n);d=.6*z+.3*x[:,1]+u
y=2*d+.4*x[:,1]+.7*u+rng.normal(size=n)
b,se=iv2sls(y,d,z,x)
reference=IV2SLS(y,x,d,z).fit(cov_type='robust',debiased=False)
assert np.allclose(b,reference.params.to_numpy(),rtol=1e-9,atol=1e-9)
assert np.allclose(se,reference.std_errors.to_numpy(),rtol=1e-9,atol=1e-9)
grid=np.linspace(-8,8,1001);accepted=anderson_rubin_grid(y,d,z,x,grid)
intervals=ar_set(y,d,z,x)
for point,actual in zip(grid,accepted):
    expected=any(lo<=point<=hi for lo,hi in intervals)
    assert expected==actual,(point,intervals)
assert ar_test(y,d,z,x,2)[0]
for seed in range(30):
    rng=np.random.default_rng(seed);n=60;x=np.ones((n,1));z=rng.normal(size=n)
    d=.05*z+rng.normal(size=n);y=2*d+rng.normal(size=n)
    intervals=ar_set(y,d,z,x)
    accepted=anderson_rubin_grid(y,d,z,x,grid[::20])
    for point,actual in zip(grid[::20],accepted):
        assert any(lo<=point<=hi for lo,hi in intervals)==actual,(seed,point,intervals)
print('2SLS y HC0 coinciden con linearmodels; conjunto AR coincide con rejilla')
"""Caso Card y cobertura de instrumentos débiles; semillas y valores guardados."""
import argparse,json,platform
from pathlib import Path
import numpy as np
import pandas as pd
import scipy
import linearmodels
from scipy.stats import t as student_t
from linearmodels.datasets import card
from linearmodels.iv import IV2SLS

def first_stage_f(d,z,X):
    [email protected](X,z,rcond=None)[0]
    [email protected](X,d,rcond=None)[0]
    coef=zr@dr/(zr@zr);err=dr-coef*zr
    df=len(d)-X.shape[1]-1
    return float(coef*coef*(zr@zr)/((err@err)/df)),float(coef)

def card_case():
    frame=card.load();frame['age2']=frame.age**2
    controls=['age','age2','black','smsa66']+[f'reg66{i}' for i in range(1,9)]
    data=frame[['lwage','educ','nearc4']+controls].dropna()
    y=data.lwage.to_numpy(float);d=data.educ.to_numpy(float);z=data.nearc4.to_numpy(float)
    X=np.column_stack((np.ones(len(data)),data[controls].to_numpy(float)))
    beta,se=iv2sls(y,d,z,X);first_f,first_coef=first_stage_f(d,z,X)
    ref=IV2SLS(y,X,d,z).fit(cov_type='robust',debiased=False)
    assert np.allclose(beta,ref.params.to_numpy()) and np.allclose(se,ref.std_errors.to_numpy())
    ols=np.linalg.lstsq(np.column_stack((X,d)),y,rcond=None)[0][-1]
    sets=[[None if not np.isfinite(a) else float(a),None if not np.isfinite(b) else float(b)] for a,b in ar_set(y,d,z,X)]
    return {'n':len(data),'controls':controls,'ols':float(ols),'iv':float(beta[-1]),'se_hc0':float(se[-1]),
            'wald_95':[float(beta[-1]-1.96*se[-1]),float(beta[-1]+1.96*se[-1])],
            'ar_homoskedastic_95':sets,'first_stage_f_classical':first_f,'first_stage_nearc4_coefficient':first_coef}

def simulation(n=300,reps=2000,seed=401):
    rng=np.random.default_rng(seed)
    z=rng.normal(size=(reps,n));v=rng.normal(size=(reps,n));eps=rng.normal(size=(reps,n))
    z-=z.mean(axis=1,keepdims=True);zz=np.sum(z*z,axis=1)
    rows=[];crit=student_t.ppf(.975,n-2)
    for rho in [0.,.5,.9]:
        u=rho*v+np.sqrt(1-rho*rho)*eps
        for strength in [0.,.08,.2,.5]:
            d=strength*z+v;y=d+u
            dc=d-d.mean(axis=1,keepdims=True);yc=y-y.mean(axis=1,keepdims=True)
            zd=np.sum(z*dc,axis=1);zy=np.sum(z*yc,axis=1)
            beta=zy/zd;ols=np.sum(dc*yc,axis=1)/np.sum(dc*dc,axis=1)
            resid=yc-beta[:,None]*dc
            se=np.sqrt(np.sum((z*resid)**2,axis=1))/np.abs(zd)
            wald=np.abs(beta-1)<=1.96*se
            w=yc-dc;coef=np.sum(z*w,axis=1)/zz;err=w-coef[:,None]*z
            tstat=np.abs(coef)*np.sqrt(zz/((err*err).sum(axis=1)/(n-2)))
            ar=tstat<=crit
            first=zd/zz;firsterr=dc-first[:,None]*z
            f=first**2*zz/((firsterr**2).sum(axis=1)/(n-2))
            rows.append({'rho':rho,'strength':strength,'n':n,'reps':reps,'mean_f':float(f.mean()),
                         'median_f':float(np.median(f)),'iv_median':float(np.median(beta)),
                         'ols_median':float(np.median(ols)),'wald_coverage':float(wald.mean()),'ar_coverage':float(ar.mean()),
                         'iv':beta.tolist(),'ols':ols.tolist()})
    return rows


case=card_case()
rows=simulation(reps=2000)
print('Card:',case)
for row in rows:
    if row['rho']==.9 and row['strength'] in (0.,.08,.5):
        print({k:v for k,v in row.items() if k not in ('iv','ols')})
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe Wald ratio
Prove: With one instrument and one endogenous regressor, no controls except an intercept, IV is a ratio of covariances.
0
Use the centered sample moment equation between Z and residual Y − βD.

Step 1 of 2. What equation does the estimator satisfy?

Numeric
The reduced form is 0.2 and the first stage is 0.4. What is the Wald ratio?
Quiz
College proximity also directly changes local employment opportunities affecting wages, even with the same education. Which assumption is threatened?
Quiz
In a hypothetical model, moving a college closer changes wages exclusively by changing years of education. Does that mechanism violate exclusion?
Quiz
A scholarship changes education and also provides money that affects future wages through professional networks, even holding education fixed. Does exclusion hold for the scholarship as an instrument?
Code
Implement anderson_rubin_ci(y, d, z, X, grid): return a list of booleans indicating whether each grid value is accepted by a two-sided homoskedastic t test at 5%. X includes an intercept; there is one excluded instrument, full rank, and n > columns(X)+1. A finite grid does not determine infinite endpoints.
def anderson_rubin_ci(y, d, z, X, grid):
  pass
Shift+Enter to run

Summary

Key idea
An instrument needs a causal defense as well as an informative first stage. Anderson-Rubin protects the test against weakness under its assumptions, and an instrumental effect can describe a local population rather than everyone.