Instrumental variables and two-stage least squares
Study instrumental relevance, exogeneity and exclusion; derive Wald and 2SLS with robust variance; examine endogeneity tests and control functions; and replicate the Card college-proximity example.
After this lesson you can
- State and justify instrumental assumptions and critique proposed instruments in applications.
- Derive IV, Wald and 2SLS estimators and their asymptotic variance, including robust variance.
- Implement 2SLS with correct standard errors and explain why manual second-stage errors are incorrect.
- Test endogeneity with Durbin-Wu-Hausman and estimate using a control function.
- Replicate Card's analysis and discuss the plausibility of exclusion.
Before you start
Variation that separates causes
You want to estimate the effect of one more year of education on wages. Chosen education can depend on ability, family resources and expectations that also affect wages. Adding observations alone does not remove that endogeneity. Now imagine some people grow up near a university and others do not. Proximity could change the cost of studying. If proximity affected wages only through education and were independent of unobserved wage determinants, it would provide another source of variation.
The conditional wording matters: a university may also be near more prosperous labor markets. The question is not whether proximity predicts education, but whether it isolates education variation satisfying defensible causal restrictions. Similarly, in product work a technically staggered rollout could instrument adoption if timing does not reflect expected outcomes and does not change outcomes through other channels such as simultaneous infrastructure improvements. Each assumption needs an argument about mechanism and population.
Three requirements for an instrument
Let . A candidate is an instrumental variable for when, after including exogenous controls , it satisfies:
- Relevance: contributes linear variation to after removing . With one instrument and one endogenous regressor, partial covariance must be nonzero.
- Exogeneity: the instrument shares no unadjusted causes with structural error; in the linear model this is expressed by , alongside . It can be formulated conditionally if assumptions justify it.
- Exclusion: changing does not alter by a direct or alternative route outside , holding relevant factors fixed. This is a mechanism restriction, not a property first-stage correlation can prove.
An estimated first stage informs relevance with sampling uncertainty. Independence from unobserved causes and exclusion require institutional knowledge, temporal order and analysis of alternative channels. With one excluded instrument for one endogenous regressor, no overidentification test proves its validity. With additional instruments, a joint-restriction test can detect incompatibility under assumptions but does not prove every instrument valid. Correlation with observed covariates can warn of a problem; its absence also does not prove independence from the unobserved.
First stage, reduced form and Wald
In a simple regression with intercept, moments and imply, if ,
If is binary and both groups have positive probability, each covariance is times the corresponding mean difference. Thus the Wald estimator divides the outcome jump by the treatment jump:
The first stage and reduced form answer different questions: how much changes with and how much changes with . With controls use appropriately partialled differences or regressions, not necessarily raw differences. A small denominator amplifies variation in both jumps; if zero, the ratio is undefined.
If and are reduced form and first stage, the delta method uses gradient and estimates
This local approximation can be very misleading when the first stage is not clearly separated from zero. Inverting the test of , as in the Fieller set or weak-instrument-robust methods, permits unbounded or disconnected sets. That geometry reflects lack of information, not an error fixed by truncating the interval.
With binary treatment and heterogeneous effects, the ratio is not automatically the whole population’s average effect. Under independent instrument assignment, exclusion, relevance and monotonicity it identifies the average effect among those changing treatment when the instrument changes: local effect LATE. This interpretation requires those additional assumptions; Imbens and Angrist develop them formally.
Two stages, several instruments
Stack the endogenous regressor and all controls, including the constant, in ; stack excluded instruments and those same controls in . If has full rank, define . Two-stage least squares is
First project each column of onto instrument space; then regress on projected columns. Since is symmetric and idempotent, and . The formula requires to have full rank. Including only excluded instruments in and forgetting exogenous controls changes the estimator and breaks the described projection. In statsmodels, the instrument argument must also include controls.
The same expression is exactly identified IV using as instrument matrix: , since . Among linear combinations of available instruments, projection is the efficient choice in the usual homoskedastic linear framework; that does not make it optimal under every heteroskedastic or nonlinear model.
The figure shows one endogenous column without controls in a three-dimensional space chosen to display the geometry. In a real sample vectors have as many coordinates as observations and there may be several columns. Projection is linear: first fitting a probit and using its probabilities as if they were the 2SLS first stage generally does not preserve these identities. A nonlinear control function can be valid under its own model but is not automatically equivalent to 2SLS.
Variance: residuals must be structural
Suppose iid observations, suitable finite moments, , invertible and full-column-rank . Then
Factor means the approximate covariance of is . The sample robust version, without degrees-of-freedom correction, can be calculated as
Manual regression of on gives the same coefficients, but its ordinary residual is , not structural residual . Its usual OLS standard errors are therefore not 2SLS errors. Under homoskedasticity, classical covariance is , with . Robust HC0 permits heteroskedasticity independent across observations; it does not replace adjustment for clustering or temporal dependence.
To see where the sandwich comes from, substitute into the estimator and define and . Exactly,
By the law of large numbers, and converge to and ; moment converges to zero, giving consistency. The central limit theorem applied to gives covariance for the final scaled term. Premultiplying and postmultiplying by the matrix limits yields . The argument needs rank identification, sufficient moments and regularity for both convergences; a nonzero sample correlation is insufficient.
These equations turn condition into moment restrictions, extending the method of moments. Forbidden paths can be represented in directed graphs with latent causes, although the graph is the researcher’s assumption. Offline RL also faces learning from confounded recorded decisions: a possible instrument requires its own relevance and exclusion argument and does not automatically validate policy evaluation.
Weak instruments and endogeneity tests
When the relevant projection of is small, the estimator is unstable and the conventional normal approximation may be poor. In certain many- or weak-instrument regimes, finite-sample 2SLS bias often points toward OLS; this is not a universal identity and a ratio may have no finite expectation. Informal rule does not guarantee validity or reliable inference under arbitrary heteroskedasticity or instrument count. Staiger and Stock analyze weak-instrument asymptotics.
The Durbin-Wu-Hausman test asks whether a regressor can be treated as exogenous under instrument validity and the test’s assumptions. In a linear model with one endogenous variable, fit the first stage of on and add residual to the structural equation. A test of its coefficient examines endogeneity within that control-function model. With several endogenous regressors, test corresponding residuals jointly.
In the classical homoskedastic case IV can also be compared with OLS using a Hausman form based on covariance differences. That subtraction assumes, among other things, relative OLS efficiency under the null; with heteroskedasticity it is not a general robust formula and may be indefinite. The residual test with robust variance also requires valid instruments and an appropriate model. Failure to reject does not prove exogeneity, and rejection does not identify which instrumental assumption failed.
Card: proximity to a university
Card’s study uses geographic variation in university proximity to study returns to education. The wooldridge card dataset contains proximity to a four-year college in 1966 and education and wages in 1976. The lab calculates OLS, first stage, reduced form and 2SLS on a common sample; results correspond exactly to the stated specification and should not be conflated with all paper tables.
In that unweighted specification, the cell obtains 3010 observations: the OLS education coefficient is 0.0747 and IV is 0.1315. The partial first stage is 0.3199 years and reduced form 0.0421 log-wage units; their ratio gives the IV estimate. HC0 standard error of the IV coefficient is 0.0540 versus 0.0036 in OLS. The first stage gives classical F of 13.26 and robust Wald of 14.21 with one degree of freedom. These reproducible results belong to this sample and controls; they do not prove instrument validity or guarantee reliable inference.
Exclusion is debatable: places with universities can differ in job opportunities and family composition. The dataset documents proximity correlation with IQ in the subsample with observed IQ; failing to find significance after controls does not prove independence from omitted determinants. Moreover, experience is defined as age minus education minus six and some covariates are measured in 1976: including them reflects a particular specification and can alter causal interpretation. If IV exceeds OLS, heterogeneous returns are one possible interpretation under suitable assumptions; selection, sampling error or instrument violations can also matter. The sign of the difference alone does not distinguish these explanations.
Lab: 2SLS and control function
The first simulation allows heteroskedastic errors and compares 2SLS with the statsmodels sandbox. The second is homoskedastic to illustrate classical Hausman. Instruments are valid by construction. The implementation’s coefficient and HC0 covariance were also checked locally against linearmodels; the experiment can be repeated with a different seed.
"""MC2E, errores robustos, Wald y contraste de endogeneidad simulados."""
import numpy as np
import statsmodels.api as sm
from scipy.stats import chi2
from statsmodels.sandbox.regression.gmm import IV2SLS
def tsls(y,X,Z):
"""Proyección QR, residuos estructurales, covarianzas clásica y HC0."""
y=np.asarray(y,float); X=np.asarray(X,float); Z=np.asarray(Z,float)
if X.ndim!=2 or Z.ndim!=2 or y.ndim!=1 or X.shape[0]!=len(y) or Z.shape[0]!=len(y):
raise ValueError('Formas incompatibles')
n,k=X.shape
if n<=k or Z.shape[1]<k or not all(np.isfinite(a).all() for a in (y,X,Z)):
raise ValueError('Dimensiones o valores inválidos')
if np.linalg.matrix_rank(Z)<Z.shape[1]: raise ValueError('Instrumentos colineales')
Qz,_=np.linalg.qr(Z,mode='reduced')
Xhat=Qz@(Qz.T@X)
if np.linalg.matrix_rank(Xhat)<k: raise ValueError('No se identifica el modelo')
Q,R=np.linalg.qr(Xhat,mode='reduced')
beta=np.linalg.solve(R,Q.T@y)
invR=np.linalg.solve(R,np.eye(k)); bread=invR@invR.T
structural=y-X@beta
classic=bread*(structural@structural)/(n-k)
score=Xhat*structural[:,None]
robust=bread@(score.T@score)@bread
return beta,classic,robust,structural,Xhat
rng=np.random.default_rng(270501)
n=1200
z1=rng.normal(size=n); z2=rng.normal(size=n); control=rng.normal(size=n)
epsilon=rng.normal(size=n)*(0.7+0.3*z1*z1)
x=.8*z1+.5*z2+.7*control+.8*epsilon+rng.normal(size=n)
y=1+1.5*x+.4*control+epsilon
X=np.column_stack((np.ones(n),control,x))
Z=np.column_stack((np.ones(n),control,z1,z2))
beta,classic,hc0,structural,Xhat=tsls(y,X,Z)
reference=IV2SLS(y,X,Z).fit()
assert np.allclose(beta,reference.params,rtol=1e-10,atol=1e-10)
assert np.allclose(classic,reference.cov_params(),rtol=1e-10,atol=1e-10)
manual=sm.OLS(y,Xhat).fit()
assert np.allclose(beta,manual.params)
print('beta real, OLS y 2SLS:',1.5,sm.OLS(y,X).fit().params[-1],beta[-1])
print('Comparación clásica propia / statsmodels sandbox:',np.sqrt(np.diag(classic)),reference.bse)
print('EE de beta_x: clásico IV, HC0 IV y OLS ingenua sobre X ajustada:',
np.sqrt(classic[-1,-1]),np.sqrt(hc0[-1,-1]),manual.bse[-1])
print('La segunda etapa OLS obtiene beta igual, pero usa residuos y varianza distintos.')
# Un instrumento binario: con intercepto, IV es la razón de saltos.
binary=(rng.uniform(size=n)<.5).astype(float)
x_b=.8*binary+rng.normal(size=n)
y_b=1+1.5*x_b+rng.normal(size=n)
X_b=np.column_stack((np.ones(n),x_b)); Z_b=np.column_stack((np.ones(n),binary))
wald=(y_b[binary==1].mean()-y_b[binary==0].mean())/(x_b[binary==1].mean()-x_b[binary==0].mean())
assert np.allclose(wald,tsls(y_b,X_b,Z_b)[0][-1])
print('Wald con Z binario y MC2E:',wald,tsls(y_b,X_b,Z_b)[0][-1])
# Mundo separado homocedástico: función de control lineal y Hausman clásico.
# Los instrumentos son válidos por construcción. Una prueba no confirma su validez.
u=rng.normal(size=n)
xh=.8*z1+.5*z2+.7*control+.8*u+rng.normal(size=n)
yh=1+1.5*xh+.4*control+u
Xh=np.column_stack((np.ones(n),control,xh))
first=sm.OLS(xh,Z).fit()
control_fit=sm.OLS(yh,np.column_stack((Xh,first.resid))).fit()
iv,_,_,uiv,_=tsls(yh,Xh,Z)
ols=sm.OLS(yh,Xh).fit()
Qz,_=np.linalg.qr(Z,mode='reduced'); Xproj=Qz@(Qz.T@Xh)
iv_bread=np.linalg.inv(Xproj.T@Xproj)
ols_bread=np.linalg.inv(Xh.T@Xh)
# Bajo H0 homocedástica OLS es eficiente; se usa la misma escala consistente.
s2=float(ols.resid@ols.resid/(n-Xh.shape[1]))
variance_difference=s2*(iv_bread[-1,-1]-ols_bread[-1,-1])
if variance_difference<=0: raise ValueError('Varianza Hausman no positiva')
hausman=(iv[-1]-ols.params[-1])**2/variance_difference
print('Primera etapa: coeficientes y F conjunto de instrumentos excluidos:',first.params,
float(first.f_test('x2=0,x3=0').fvalue))
print('Función de control: coef. residual, t clásico, p:',control_fit.params[-1],control_fit.tvalues[-1],control_fit.pvalues[-1])
print('Hausman clásico un coeficiente: estadístico y p chi2(1):',hausman,chi2.sf(hausman,1))
print('Hausman de diferencia usa homocedasticidad y eficiencia OLS bajo H0; no restar covarianzas robustas sin más.')Local lab: Card data
Install wooldridge, linearmodels, NumPy, pandas, SciPy and statsmodels locally. An unweighted specification uses controls indicated in code, identical in first stage, reduced form and outcome. linearmodels compares both coefficients and the entire custom HC0 matrix.
"""Análisis reproducible del conjunto card con linearmodels y wooldridge.
Requiere numpy, pandas, scipy, statsmodels, wooldridge y linearmodels.
Es una especificación didáctica del conjunto, no una réplica idéntica de una
tabla concreta de Card: los controles y el tratamiento de pesos importan.
"""
import numpy as np
import statsmodels.api as sm
from linearmodels.iv import IV2SLS
import wooldridge as woo
# Regiones 662..669; la 661 es la categoría omitida. No se usan pesos muestrales.
controls=['exper','expersq','black','south','smsa','smsa66',
'reg662','reg663','reg664','reg665','reg666','reg667','reg668','reg669']
columns=['lwage','educ','nearc4',*controls]
d=woo.data('card')[columns].dropna().copy()
if not np.isfinite(d.to_numpy(dtype=float)).all(): raise ValueError('Valores no finitos')
y=d['lwage'].to_numpy(dtype=float)
C=sm.add_constant(d[controls],has_constant='add').to_numpy(dtype=float)
education=d['educ'].to_numpy(dtype=float)
excluded=d['nearc4'].to_numpy(dtype=float)
X=np.column_stack((C,education))
Z=np.column_stack((C,excluded))
if np.linalg.matrix_rank(X)!=X.shape[1] or np.linalg.matrix_rank(Z)!=Z.shape[1]:
raise ValueError('Diseño sin rango completo')
Qz,_=np.linalg.qr(Z,mode='reduced')
Xhat=Qz@(Qz.T@X)
Q,R=np.linalg.qr(Xhat,mode='reduced')
beta=np.linalg.solve(R,Q.T@y)
u=y-X@beta
invR=np.linalg.solve(R,np.eye(X.shape[1]))
bread=invR@invR.T
scores=Xhat*u[:,None]
cov_hc0=bread@(scores.T@scores)@bread
reference=IV2SLS(y,C,education[:,None],excluded[:,None]).fit(cov_type='robust',debiased=False)
assert np.allclose(beta,reference.params.to_numpy(),rtol=1e-8,atol=1e-8)
assert np.allclose(cov_hc0,reference.cov.to_numpy(),rtol=1e-7,atol=1e-8)
ols=sm.OLS(y,X).fit(cov_type='HC0')
first=sm.OLS(education,Z).fit()
first_robust=first.get_robustcov_results(cov_type='HC0')
reduced=sm.OLS(y,Z).fit()
reduced_robust=reduced.get_robustcov_results(cov_type='HC0')
first_jump=float(first.params[-1]); reduced_jump=float(reduced.params[-1])
wald=reduced_jump/first_jump
assert np.isclose(wald,beta[-1],atol=1e-9,rtol=1e-9)
print('Card, muestra:',len(d),'cercanía nearc4=1:',int(excluded.sum()),'controles:',controls)
print('OLS educación y EE HC0:',ols.params[-1],ols.bse[-1])
print('Primera etapa nearc4, EE HC0, F clásico, Wald robusto chi2(1):',first_jump,
first_robust.bse[-1],first.tvalues[-1]**2,(first_jump/first_robust.bse[-1])**2)
print('Forma reducida nearc4 y EE HC0:',reduced_jump,reduced_robust.bse[-1])
print('Cociente parcial, 2SLS propio, linearmodels, EE HC0:',wald,beta[-1],reference.params.iloc[-1],np.sqrt(cov_hc0[-1,-1]))
print('Cercanía puede reflejar condiciones locales o familiares. IQ observado en una submuestra no valida por sí solo exclusión o independencia.')
print('exper=edad-educación-6 y algunos controles corresponden a 1976: su interpretación causal requiere cuidado.')
print('No se usan pesos; primera etapa y cociente dependen de muestra y especificación, y una F aislada no garantiza instrumento fuerte.')npm run lab and open the connection link.Exercises
Step 1 of 3. What is sample covariance with denominator n?
Step 1 of 3. Which random term governs the difference after multiplication by √n?
The following questions raise specific risks, not definitive verdicts on design validity. Rain has been used to study growth and conflict (Miguel and Satyanath); college proximity for education and wages (Card); birth quarter and draft lotteries for education and labor outcomes (Angrist and Krueger, Angrist and Krueger); and lagged prices for insurance demand (Maestas, Schroeder and Goldman).
import numpy as np
def tsls(y, X, Z):
"""Devuelve (coeficientes, covarianza HC0 de 2SLS)."""
passThe next local cell regenerates complete test references with linearmodels without creating files. Use the same dependencies as the local lab.
"""Genera referencias numéricas con linearmodels 7.1, cov_type robust sin corrección."""
import json
import numpy as np
from linearmodels.iv import IV2SLS
def design(seed,n,k):
rng=np.random.default_rng(seed)
z=rng.normal(size=(n,3))
w=rng.normal(size=n)
u=rng.normal(size=n)*(.8+.3*z[:,0]**2)
x1=.7*z[:,0]+.4*z[:,1]+.3*w+.7*u+rng.normal(size=n)
x2=-.2*z[:,0]+.4*z[:,1]+.8*z[:,2]-.2*w+.5*u+rng.normal(size=n)
endog=np.column_stack((x1,x2))[:,:k]
exog=np.column_stack((np.ones(n),w))
beta=np.array([1.5,-.7])[:k]
y=1+.5*w+endog@beta+u
return y,exog,endog,z
reference=[]
for seed,n,k in [(270510,240,1),(270511,360,2)]:
y,exog,endog,z=design(seed,n,k)
fit=IV2SLS(y,exog,endog,z).fit(cov_type='robust',debiased=False)
item={'seed':seed,'n':n,'endogenous':k,'beta':fit.params.to_numpy().tolist(),'cov_hc0':fit.cov.to_numpy().tolist()}
reference.append(item)
print(json.dumps(item,ensure_ascii=False))npm run lab and open the connection link.import numpy as np
a,b=.06,.4
va,vb,cab=.0004,.0025,.0002
variance=va/b**2+a**2*vb/b**4-2*a*cab/b**3
print('Wald:',a/b,'varianza delta:',variance,'error estándar:',np.sqrt(variance))