Module contents
Lesson 5 of 28Core 105 min

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 Y=βX+W⊤γ+uY=\beta X+W^\top\gamma+u. A candidate ZZ is an instrumental variable for XX when, after including exogenous controls WW, it satisfies:

  1. Relevance: ZZ contributes linear variation to XX after removing WW. With one instrument and one endogenous regressor, partial covariance must be nonzero.
  2. Exogeneity: the instrument shares no unadjusted causes with structural error; in the linear model this is expressed by E[Zu]=0E[Zu]=0, alongside E[Wu]=0E[Wu]=0. It can be formulated conditionally if assumptions justify it.
  3. Exclusion: changing ZZ does not alter YY by a direct or alternative route outside XX, 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.

InteractiveThe path an instrument leaves open

U affects both X and Y and biases OLS. Use the toggles to add a direct path from Z to Y and a common cause of Z and Y. Added arrows appear in orange.

ZXYUunobserved confounder

The vertical mark indicates structural effect β = 1. Strong bars use the sample; lighter bars are population limits of the same generator.

Sample OLS
1.361
Population OLS
1.351
Sample IV
0.963
Population IV
1.000
  • OLS
  • IV

Reproducible generator of 3000 observations: Z₀, U, V and ε are independent standard normals; Z = Z₀ + κU, X = 0.8Z + 0.8U + V, Y = X + U + δZ + ε. Toggles set κ and δ to 0 or 0.6. The button changes the seed; otherwise all four states share the same underlying shocks.

IV computes Covₙ(Z,Y)/Covₙ(Z,X) with an intercept. In the population Cov(Z,X) = 0.8(1+κ²)+0.8κ, positive in these states, so the first stage exists. The IV limit is 1 + [δ(1+κ²)+κ]/Cov(Z,X). Here a direct path violates exclusion and U → Z violates instrument independence from the confounder.

The diagram and equations define a simulated experiment; they do not prove a real instrument satisfies exclusion or exogeneity. The sample estimate’s difference from its limit changes with the seed; even a valid instrument can yield a value other than 1 in a finite sample.

Structural effect β1.00
Sample OLS1.361
Sample IV0.963
Sample first stage0.742
Observations3000
Seed270501
Separately activate the direct path and common cause of instrument and outcome.

First stage, reduced form and Wald

In a simple regression with intercept, moments E[Y−α−βX]=0E[Y-\alpha-\beta X]=0 and E[Z(Y−α−βX)]=0E[Z(Y-\alpha-\beta X)]=0 imply, if Cov⁡(Z,X)≠0\operatorname{Cov}(Z,X)\ne0,

βIV=Cov⁡(Z,Y)Cov⁡(Z,X).\beta_{\mathrm{IV}}= \frac{\operatorname{Cov}(Z,Y)}{\operatorname{Cov}(Z,X)}.

If ZZ is binary and both groups have positive probability, each covariance is p(1−p)p(1-p) times the corresponding mean difference. Thus the Wald estimator divides the outcome jump by the treatment jump:

β^W=YˉZ=1−YˉZ=0XˉZ=1−XˉZ=0=forma reducida^primera etapa^.\hat\beta_W= \frac{\bar Y_{Z=1}-\bar Y_{Z=0}}{\bar X_{Z=1}-\bar X_{Z=0}} =\frac{\widehat{\text{forma reducida}}}{\widehat{\text{primera etapa}}}.

The first stage and reduced form answer different questions: how much XX changes with ZZ and how much YY changes with ZZ. 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.

InteractiveA ratio of two jumps

Two groups of 50 observations: X=πZ+V and Y=X+0.8V+ε, with standard normal V and ε independent of Z and each other. The structural slope is 1. The same disturbances remain when π changes; the observed first stage can differ from π by chance.

First stage: means of X

Z=0Z=1−0.730.96

Means Z=0 and Z=1: −0.266 and 0.465. Each bar is an individual 95% t interval.

Reduced form: means of Y

Z=0Z=1−1.691.29

Means Z=0 and Z=1: −0.808 and 0.421. Each bar is an individual 95% t interval.

95% Fieller set for the ratio: [0.95, 2.31].

The 95% t interval for the difference in X means excludes zero; that alone does not guarantee that a strong-instrument approximation is adequate.

Fieller inverts the two-sided t test of ΔY−bΔX for each b; here it is exact under normality and common group variance. The set may consist of two rays or the entire real line. If ΔX is zero Wald is undefined; near zero it can be huge. Mean bars are not intervals for the ratio.

In this generator Z is independent of disturbances and affects Y only through X. These conditions are imposed in simulation; observing a first stage does not establish exclusion or exogeneity in real data.

0.50
1
Sample first stage ΔX0.731
Sample reduced form ΔY1.229
Wald ΔY/ΔX1.681
Reduce the first stage and observe the jumps and confidence set for the ratio.

If a^\hat a and b^\hat b are reduced form and first stage, the delta method uses gradient (1/b,−a/b2)(1/b,-a/b^2) and estimates

Var⁡^(a^/b^)=V^ab^2+a^2V^bb^4−2a^C^abb^3.\widehat{\operatorname{Var}}(\hat a/\hat b) =\frac{\widehat V_a}{\hat b^2} +\frac{\hat a^2\widehat V_b}{\hat b^4} -\frac{2\hat a\widehat C_{ab}}{\hat b^3}.

This local approximation can be very misleading when the first stage is not clearly separated from zero. Inverting the test of a−θb=0a-\theta b=0, 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 XX; stack excluded instruments and those same controls in ZZ. If ZZ has full rank, define PZ=Z(Z⊤Z)−1Z⊤P_Z=Z(Z^\top Z)^{-1}Z^\top. Two-stage least squares is

X^=PZX,β^2SLS=(X⊤PZX)−1X⊤PZy.\hat X=P_ZX,\qquad \hat\beta_{2SLS}=(X^\top P_ZX)^{-1}X^\top P_Zy.

First project each column of XX onto instrument space; then regress yy on projected columns. Since PZP_Z is symmetric and idempotent, X^⊤X^=X⊤PZX\hat X^\top\hat X=X^\top P_ZX and X^⊤y=X⊤PZy\hat X^\top y=X^\top P_Zy. The formula requires X⊤PZXX^\top P_ZX to have full rank. Including only excluded instruments in ZZ 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 X^\hat X as instrument matrix: β^=(X^⊤X)−1X^⊤y\hat\beta=(\hat X^\top X)^{-1}\hat X^\top y, since X^⊤X=X⊤PZX\hat X^\top X=X^\top P_ZX. 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.

Interactive2SLS in two projections

Each arrow is a vector in observation space. The plane is the instrument space; the coordinates are an explicit construction, not a data sample.

  • original x
  • original y
  • Projection of x
  • Projection of y onto projected x
  • Instrument plane

Here x=(s; 0; 1.2), y=(1.4; 1.1; 1), and the instrument plane is z=0. For positive s, projected x is (s; 0; 0), final projection is (1.4; 0; 0), and slope is 1.4/s. Vector y remains fixed when s changes: this illustrates geometric sensitivity, not an estimator simulation or coverage demonstration.

1.2
First stage: project x
Norm of projected x1.20
2SLS coefficient1.167
Project the regressor vector onto the instrument plane and then the outcome onto its projection.

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, E[ziui]=0E[z_i u_i]=0, invertible W=E[zizi⊤]W=E[z_i z_i^\top] and full-column-rank Q=E[zixi⊤]Q=E[z_i x_i^\top]. Then

n(β^2SLS−β)→dN(0,V),V=A−1Q⊤W−1ΩW−1QA−1,\sqrt n(\hat\beta_{2SLS}-\beta) \xrightarrow{d}N(0,V),\qquad V=A^{-1}Q^\top W^{-1}\Omega W^{-1}Q A^{-1}, A=Q⊤W−1Q,Ω=E[zizi⊤ui2].A=Q^\top W^{-1}Q,\qquad \Omega=E[z_i z_i^\top u_i^2].

Factor n\sqrt n means the approximate covariance of β^\hat\beta is V/nV/n. The sample robust version, without degrees-of-freedom correction, can be calculated as

Var⁡^HC0(β^)=(X⊤PZX)−1(∑ix^ix^i⊤u^i2)(X⊤PZX)−1,u^i=yi−xi⊤β^.\widehat{\operatorname{Var}}_{\mathrm{HC0}}(\hat\beta) =(X^\top P_ZX)^{-1} \left(\sum_i \hat x_i\hat x_i^\top \hat u_i^2\right) (X^\top P_ZX)^{-1},\quad \hat u_i=y_i-x_i^\top\hat\beta.

Manual regression of yy on X^\hat X gives the same coefficients, but its ordinary residual is y−X^β^y-\hat X\hat\beta, not structural residual y−Xβ^y-X\hat\beta. Its usual OLS standard errors are therefore not 2SLS errors. Under homoskedasticity, classical covariance is σ^2(X⊤PZX)−1\hat\sigma^2(X^\top P_ZX)^{-1}, with σ^2=∑iu^i2/(n−k)\hat\sigma^2=\sum_i\hat u_i^2/(n-k). 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 y=Xβ+uy=X\beta+u into the estimator and define Qn=Z⊤X/nQ_n=Z^\top X/n and Wn=Z⊤Z/nW_n=Z^\top Z/n. Exactly,

n(β^−β)=(Qn⊤Wn−1Qn)−1Qn⊤Wn−1Z⊤un.\sqrt n(\hat\beta-\beta) =(Q_n^\top W_n^{-1}Q_n)^{-1}Q_n^\top W_n^{-1} \frac{Z^\top u}{\sqrt n}.

By the law of large numbers, QnQ_n and WnW_n converge to QQ and WW; moment Z⊤u/nZ^\top u/n converges to zero, giving consistency. The central limit theorem applied to ziuiz_i u_i gives covariance Ω\Omega for the final scaled term. Premultiplying and postmultiplying by the matrix limits yields VV. The argument needs rank identification, sufficient moments and regularity for both convergences; a nonzero sample correlation is insufficient.

These equations turn condition E[zu]=0E[zu]=0 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 XX 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 F>10F>10 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 XX on ZZ and add residual v^\hat v 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.

[ ]2SLS, errors and endogeneityBrowser
"""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)); [email protected]
    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([email protected]/(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.

[ ]College proximity and wagesLocal GPU
"""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]))
[email protected]
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.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofFrom covariances to jumps
Prove: With intercept, binary Z and sample proportion p between zero and one, show the IV estimator is the ratio of group mean differences in Y and X.
0
Write sample covariance of Z with a variable A using group means.

Step 1 of 3. What is sample covariance with denominator n?

ProofConsistency and robust variance
Prove: For iid observations with sufficient moments and finite E[‖zu‖²], E[zu]=0, invertible W=E[zzᵀ] and full-column-rank Q=E[zxᵀ], justify consistency and derive 2SLS asymptotic variance.
0
Start from the exact β̂−β expression and apply the law of large numbers and central limit theorem.

Step 1 of 3. Which random term governs the difference after multiplication by √n?

NumericRatio of jumps
The estimated reduced form is 0.06 and first stage is 0.4. What is the Wald ratio?
NumericRatio uncertainty
For jumps 0.06 and 0.4, estimated variances are 0.0004 and 0.0025 and estimated covariance is 0.0002. What is the ratio's delta-method standard error? Give four decimal places.

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).

QuizRain, growth and conflict
You want to use rain to instrument growth and study conflict. Which observation most directly threatens exclusion?
QuizProximity and wages
You use childhood college proximity to instrument education and explain wages. What is the most direct threat?
QuizQuarter of birth
If you use birth quarter as an education instrument to explain wages, what risk should you discuss?
QuizDraft lottery
Consider random draft priority as an education instrument to explain wages. Which path deserves most attention?
QuizLagged price
In studying demand for Medigap policies, the 2001 price has been used to instrument the 2004 price. Which assumption can fail if demand shocks persist?
CodeImplement 2SLS with robust covariance
Implement tsls(y, X, Z), returning coefficients and HC0 covariance. Include exogenous X controls in Z. Reject nonfinite data, incompatible shapes, collinear columns and designs lacking identified rank. Both test designs are overidentified and their references are generated by the following local cell with linearmodels.
import numpy as np

def tsls(y, X, Z):
  """Devuelve (coeficientes, covarianza HC0 de 2SLS)."""
  pass
Shift+Enter to run

The next local cell regenerates complete test references with linearmodels without creating files. Use the same dependencies as the local lab.

[ ]Regenerate exercise references with linearmodelsLocal GPU
"""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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Check the numerical Wald exampleBrowser
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))