Algorithm Search⌘K

Algorithmcore

Two-stage least squares

Also called 2SLS, TSLS.

First regress the treatment on the instruments, then regress the outcome on the fitted treatment. It is the standard instrumental variables estimator.

Time
Θ(n l^2 + l^3) worst · best
Space
Θ(n k + l^2) extra
Where
k = the number of regressors; l = the number of instruments, l ≥ k; n = the number of units
Properties
consistent with valid strong instrumentsdeterministicequals ols when instruments are regressorsequals wald ratio with one binary instrumentexact in rational arithmetic
Origin
Henri Theil, Robert L. Basmann, John Denis Sargan, 1953

Two-stage least squares (2SLS) estimates the coefficients of a linear model y=Xβ+εy = X\beta + \varepsilon in which some regressors are correlated with the error, using instruments ZZ that are correlated with the regressors but not with the error. The first stage regresses each column of XX on the instruments and keeps the fitted values X^\hat X; this keeps only the part of the regressors that the instruments explain, which is uncorrelated with the error. The second stage regresses yy on X^\hat X. In one formula, b=(X⊤PZX)−1X⊤PZyb = (X^\top P_ZX)^{-1}X^\top P_Zy with PZP_Z the projection on the instruments. It is the standard estimator for instrumental variables: with one binary instrument it is the Wald ratio, with as many instruments as regressors it is the simple instrumental variables formula, and when every regressor is its own instrument it is ordinary least squares. The residuals for the standard errors must be computed with the original XX, not with X^\hat X.

In plain words

We want the effect of a treatment, say years of schooling, on an outcome, say earnings, but the people who got more schooling differ in ways we cannot measure, so a plain regression mixes the effect with those differences. Suppose something else, such as the quarter of the year a person was born, pushes schooling up or down a little for reasons that have nothing to do with earnings.

The first stage asks how much of each person's schooling that push predicts. The second stage relates earnings to that predicted schooling only. Since the predicted part came from the push alone, and the push is unrelated to the hidden differences, the second stage measures the effect of schooling itself. The price is precision: the predicted part varies much less than schooling does, so the estimate is noisier than a plain regression.

The problem

Identification. The structural equation is yi=xi⊤β+εiy_i = x_i^\top\beta + \varepsilon_i, where xix_i has kk entries: a constant, exogenous covariates wiw_i and endogenous regressors did_i (the treatments). The instrument vector ziz_i has l≥kl \ge k entries: the constant, wiw_i, and the excluded instruments. The assumptions are

  • exogeneity: E[ziεi]=0\mathbb{E}[z_i\varepsilon_i] = 0, which contains both the exclusion restriction (the excluded instruments do not enter the equation for yy) and the independence of the instruments from the unobserved causes of yy;
  • relevance: E[zizi⊤]\mathbb{E}[z_iz_i^\top] is invertible and E[zixi⊤]\mathbb{E}[z_ix_i^\top] has rank kk, so the instruments move every endogenous regressor.

Then β\beta is the unique solution of E[zi(yi−xi⊤β)]=0\mathbb{E}[z_i(y_i - x_i^\top\beta)] = 0 in the column space selected by the rank condition, and with l>kl > k the ll moment conditions overidentify it. Relevance is testable with the first-stage regression. Exogeneity is not testable when l=kl = k; with l>kl > k only the consistency of the extra conditions with the others can be tested (Sargan's test), assuming at least kk of them are valid. The linear equation with a constant β\beta is itself an assumption: if the effect varies across units, 2SLS with one binary instrument estimates the local average treatment effect of the compliers, not an average over everyone.

Estimation. The input is yy (nn-vector), XX (n×kn \times k) and ZZ (n×ln \times l). The output is bb, the residuals u=y−Xbu = y - Xb, the homoskedastic variance σ^2(X^⊤X^)−1\hat\sigma^2(\hat X^\top\hat X)^{-1} with σ^2=u⊤u/(n−k)\hat\sigma^2 = u^\top u/(n - k), and the heteroscedasticity-consistent (HC0) sandwich. 2SLS is consistent under the two assumptions and asymptotically normal under finite fourth moments. It is biased in finite samples, toward OLS, and the bias and the size distortion of its tt tests are large when the instruments are weak. The first-stage FF statistic of the excluded instruments is the usual diagnostic: Staiger and Stock (1997) suggested F>10F > 10 as a rule of thumb for one endogenous regressor, and Stock and Yogo (2005) give critical values.

The algorithm

  1. TSLS(y, X, Z) ▷ X is n × k, Z is n × l, l ≥ k
  2. 1Π ← solve (ZᵀZ) Π = ZᵀX ▷ first stage: one regression per column of X
  3. 2X̂ ← Z Π ▷ fitted regressors; exogenous columns are reproduced exactly
  4. 3b ← solve (X̂ᵀX) b = X̂ᵀy ▷ second stage; X̂ᵀX = X̂ᵀX̂
  5. 4u ← y - X b ▷ residuals with the ORIGINAL X
  6. 5σ² ← uᵀu / (n - k)
  7. 6V ← σ² (X̂ᵀX̂)⁻¹; V_HC0 ← (X̂ᵀX̂)⁻¹ (Σ_i u_i² x̂_i x̂_iᵀ) (X̂ᵀX̂)⁻¹
  8. 7return (b, V, V_HC0)

The columns of XX that are also columns of ZZ (the constant and the exogenous covariates) are fitted exactly in line L1, so only the endogenous columns change in X^\hat X. Line L3 can be read as the regression of yy on X^\hat X, which is where the name comes from; but the residual variance of that regression uses y−X^by - \hat Xb, which is wrong, and that is why line L4 goes back to XX. In floating point, solve the least squares problems by QR rather than by forming Z⊤ZZ^\top Z, which squares the condition number.

Example

Eight units. The instrument zz is a random encouragement, dd is whether the unit took the treatment, and yy is the outcome.

zz dd yy
0 0, 0, 0, 1 1, 2, 3, 6
1 1, 1, 1, 0 5, 6, 4, 2

First stage. dˉ=1/4\bar d = 1/4 when z=0z = 0 and 3/43/4 when z=1z = 1, so d^=1/4+z/2\hat d = 1/4 + z/2: the encouragement raises the treatment rate by 1/21/2.

Second stage. yˉ=3\bar y = 3 when z=0z = 0 and 17/417/4 when z=1z = 1. The regression of yy on (1,d^)(1, \hat d) gives b=(19/8,5/2)b = (19/8, 5/2). The slope is the Wald ratio (17/4−3)/(3/4−1/4)=(5/4)/(1/2)=5/2(17/4 - 3)/(3/4 - 1/4) = (5/4)/(1/2) = 5/2, as it must be with one binary instrument. OLS of yy on (1,d)(1, d) gives slope 21/4−2=13/421/4 - 2 = 13/4: the units that took the treatment against the encouragement differ from the rest.

Standard errors. The residuals u=y−19/8−52du = y - 19/8 - \frac52 d are (−11,−3,5,9,1,9,−7,−3)/8(-11, -3, 5, 9, 1, 9, -7, -3)/8, so u⊤u=47/8u^\top u = 47/8 and σ^2=47/48\hat\sigma^2 = 47/48. The centred sum of squares of d^\hat d is 8⋅(1/4)2=1/28 \cdot (1/4)^2 = 1/2, so the variance of the slope is 4748⋅2=47/24\frac{47}{48} \cdot 2 = 47/24 and its standard error is 1.40; the HC0 standard error is 47/32=1.21\sqrt{47/32} = 1.21. The residuals of the literal second regression, y−19/8−52d^y - 19/8 - \frac52\hat d, are −2,−1,0,3-2, -1, 0, 3 and 3/4,7/4,−1/4,−9/43/4, 7/4, -1/4, -9/4, with sum of squares 91/491/4; a program run on d^\hat d would report a standard error of 91/12=2.75\sqrt{91/12} = 2.75, twice too large here, and in other data too small.

Simulation. y=1+d+uy = 1 + d + u, d=0.5(z1+z2+z3)+vd = 0.5(z_1 + z_2 + z_3) + v with three standard normal instruments and corr⁡(u,v)=0.6\operatorname{corr}(u, v) = 0.6, so OLS tends to 1+0.6/1.75=1.3431 + 0.6/1.75 = 1.343. Over 300 samples of n=200n = 200, measured:

design 2SLS mean 2SLS SD OLS mean 95% HC0 coverage Sargan rejects at 5% median first-stage FF
strong instruments 1.006 0.085 1.344 0.94 0.06 50.4
weak, π=0.05\pi = 0.05 each 1.388 0.623 1.604 0.82 0.03 1.2
first instrument invalid 1.327 0.091 1.483 0.05 1.00 50.2

With weak instruments 2SLS moves toward OLS and its intervals undercover. With one instrument that has a direct effect of 0.5 on yy, the estimate is badly biased, and Sargan's test catches it every time, because the other two instruments are valid and disagree with it.

Correctness

The full proofs are in the correctness proof. The key facts:

  • Projection form. X^=PZX\hat X = P_ZX, and since PZP_Z is symmetric and idempotent, X^⊤X=X^⊤X^=X⊤PZX\hat X^\top X = \hat X^\top\hat X = X^\top P_ZX. So line L3 computes b=(X⊤PZX)−1X⊤PZyb = (X^\top P_ZX)^{-1}X^\top P_Zy, which is also the regression of yy on X^\hat X.
  • Just-identified. With l=kl = k, b=(Z⊤X)−1Z⊤yb = (Z^\top X)^{-1}Z^\top y, the simple instrumental variables formula.
  • One binary instrument. With X=[1,d]X = [1, d] and Z=[1,z]Z = [1, z], the equations Z⊤(y−Xb)=0Z^\top(y - Xb) = 0 say the residuals sum to 0 in each instrument group, so yˉ1=a+bddˉ1\bar y_1 = a + b_d\bar d_1 and yˉ0=a+bddˉ0\bar y_0 = a + b_d\bar d_0, and bdb_d is the Wald ratio. The tests check this exactly on 200 random data sets.
  • No endogeneity. With Z=XZ = X, X^=X\hat X = X and 2SLS is OLS, with White's sandwich.
  • Consistency. b−β=(X⊤PZX)−1X⊤PZεb - \beta = (X^\top P_ZX)^{-1}X^\top P_Z\varepsilon, and with Z⊤ε/n→0Z^\top\varepsilon/n \to 0 and the rank condition, the law of large numbers and continuous mapping give b→βb \to \beta. OLS tends to β+Qxx−1E[xiεi]\beta + Q_{xx}^{-1}\mathbb{E}[x_i\varepsilon_i] instead.

Proved: the algebra above and consistency. Cited: asymptotic normality, the validity of the variance estimates, and the χl−k2\chi^2_{l - k} law of Sargan's statistic (Sargan 1958). The simulation numbers are measured.

Proof: Two-stage least squares computes the projection formula, reduces to the Wald ratio with one binary instrument, and is consistent under valid instrumentsfull

Let yy be an nn-vector, XX an n×kn \times k matrix and ZZ an n×ln \times l matrix with l≥kl \ge k. Assume Z⊤ZZ^\top Z is invertible and write P=Z(Z⊤Z)−1Z⊤P = Z(Z^\top Z)^{-1}Z^\top, the orthogonal projection on the column span of ZZ. PP is symmetric and P2=PP^2 = P. TSLS computes Π=(Z⊤Z)−1Z⊤X\Pi = (Z^\top Z)^{-1}Z^\top X (line L1), X^=ZΠ\hat X = Z\Pi (line L2) and solves X^⊤X b=X^⊤y\hat X^\top X\,b = \hat X^\top y (line L3).

Lemma 1 (the projection form). X^=PX\hat X = PX, X^⊤X=X^⊤X^=X⊤PX\hat X^\top X = \hat X^\top\hat X = X^\top PX and X^⊤y=X⊤Py\hat X^\top y = X^\top Py. So if X⊤PXX^\top PX is invertible,

b=(X⊤PX)−1X⊤Py,b = (X^\top PX)^{-1}X^\top Py,

and bb is also the least squares coefficient of yy on X^\hat X.

Proof. X^=Z(Z⊤Z)−1Z⊤X=PX\hat X = Z(Z^\top Z)^{-1}Z^\top X = PX. Then X^⊤X=X⊤P⊤X=X⊤PX\hat X^\top X = X^\top P^\top X = X^\top PX and X^⊤X^=X⊤P⊤PX=X⊤PX\hat X^\top\hat X = X^\top P^\top PX = X^\top PX, using P⊤=PP^\top = P and P2=PP^2 = P. Also X^⊤y=X⊤Py\hat X^\top y = X^\top Py. The least squares coefficient of yy on X^\hat X solves X^⊤X^ c=X^⊤y\hat X^\top\hat X\,c = \hat X^\top y, the same system as line L3. □\square

Theorem 2 (just-identified). If l=kl = k and Z⊤XZ^\top X is invertible, then b=(Z⊤X)−1Z⊤yb = (Z^\top X)^{-1}Z^\top y.

Proof. X⊤PX=(X⊤Z)(Z⊤Z)−1(Z⊤X)X^\top PX = (X^\top Z)(Z^\top Z)^{-1}(Z^\top X) is a product of three invertible k×kk \times k matrices, with inverse (Z⊤X)−1(Z⊤Z)(X⊤Z)−1(Z^\top X)^{-1}(Z^\top Z)(X^\top Z)^{-1}. Multiplying by X⊤Py=(X⊤Z)(Z⊤Z)−1Z⊤yX^\top Py = (X^\top Z)(Z^\top Z)^{-1}Z^\top y gives (Z⊤X)−1Z⊤y(Z^\top X)^{-1}Z^\top y. □\square

Theorem 3 (no endogeneity). If Z=XZ = X (every regressor is its own instrument) and X⊤XX^\top X is invertible, bb is the OLS coefficient and X^=X\hat X = X; the HC0 variance of line L6 is then White's OLS sandwich.

Proof. PX=XPX = X when the columns of XX span the space of PP. Then X^=X\hat X = X, and lines L3 and L6 become the OLS normal equations and the OLS sandwich. □\square

Theorem 4 (the Wald ratio). Let X=[1,d]X = [\mathbf 1, d] and Z=[1,z]Z = [\mathbf 1, z] with z∈{0,1}z \in \{0, 1\}, both values present. Write yˉ1,dˉ1\bar y_1, \bar d_1 for the means over the units with z=1z = 1 and yˉ0,dˉ0\bar y_0, \bar d_0 for z=0z = 0. If dˉ1≠dˉ0\bar d_1 \ne \bar d_0, then the 2SLS slope is

bd=yˉ1−yˉ0dˉ1−dˉ0,b_d = \frac{\bar y_1 - \bar y_0}{\bar d_1 - \bar d_0},

and the intercept is yˉ−bddˉ\bar y - b_d\bar d.

Proof. The model is just-identified, and Z⊤XZ^\top X is invertible: its determinant is n∑izidi−∑izi∑idi=nn1(dˉ1−dˉ)=n1n0(dˉ1−dˉ0)≠0n\sum_i z_id_i - \sum_i z_i\sum_i d_i = n n_1(\bar d_1 - \bar d) = n_1n_0(\bar d_1 - \bar d_0) \ne 0, with n1,n0n_1, n_0 the group sizes. By Theorem 2, b=(a,bd)b = (a, b_d) solves Z⊤(y−Xb)=0Z^\top(y - Xb) = 0, that is, ∑i(yi−a−bddi)=0\sum_i(y_i - a - b_dd_i) = 0 and ∑zi=1(yi−a−bddi)=0\sum_{z_i = 1}(y_i - a - b_dd_i) = 0. Subtracting, the residuals also sum to 0 over z=0z = 0. Dividing by the group sizes, yˉ1=a+bddˉ1\bar y_1 = a + b_d\bar d_1 and yˉ0=a+bddˉ0\bar y_0 = a + b_d\bar d_0. Subtracting gives bdb_d, and the first equation gives aa. □\square

Lemma 5 (which residuals). The residuals of line L4, u=y−Xbu = y - Xb, and the residuals of the literal second regression, u~=y−X^b\tilde u = y - \hat Xb, differ by (X−X^)b=(I−P)Xb(X - \hat X)b = (I - P)Xb. In general u~⊤u~≠u⊤u\tilde u^\top\tilde u \ne u^\top u.

Proof. Subtract. For a concrete case, the example on the page has u⊤u=47/8u^\top u = 47/8 and u~⊤u~=91/4\tilde u^\top\tilde u = 91/4. □\square

Under the model y=Xβ+εy = X\beta + \varepsilon, uu estimates ε\varepsilon, while u~=ε+(X−X^)β+X^(β−b)\tilde u = \varepsilon + (X - \hat X)\beta + \hat X(\beta - b) contains the first-stage error (I−P)Xβ(I - P)X\beta. That is why a regression program run on X^\hat X gives the right bb and the wrong standard errors.

Consistency

Theorem 6. Let the rows (yi,xi,zi)(y_i, x_i, z_i) be independent and identically distributed with finite second moments, yi=xi⊤β+εiy_i = x_i^\top\beta + \varepsilon_i, and assume

  • exogeneity of the instruments: E[ziεi]=0\mathbb{E}[z_i\varepsilon_i] = 0;
  • rank: Qzz=E[zizi⊤]Q_{zz} = \mathbb{E}[z_iz_i^\top] is invertible and Qzx=E[zixi⊤]Q_{zx} = \mathbb{E}[z_ix_i^\top] has rank kk.

Then b→βb \to \beta in probability.

Proof. Substituting y=Xβ+εy = X\beta + \varepsilon in Lemma 1,

b−β=(X⊤Zn(Z⊤Zn)−1Z⊤Xn)−1X⊤Zn(Z⊤Zn)−1Z⊤εn.b - \beta = \Big(\tfrac{X^\top Z}{n}\big(\tfrac{Z^\top Z}{n}\big)^{-1}\tfrac{Z^\top X}{n}\Big)^{-1}\tfrac{X^\top Z}{n}\big(\tfrac{Z^\top Z}{n}\big)^{-1}\tfrac{Z^\top\varepsilon}{n}.

By the law of large numbers Z⊤Z/n→QzzZ^\top Z/n \to Q_{zz}, Z⊤X/n→QzxZ^\top X/n \to Q_{zx} and Z⊤ε/n→E[ziεi]=0Z^\top\varepsilon/n \to \mathbb{E}[z_i\varepsilon_i] = 0. The matrix Qzx⊤Qzz−1QzxQ_{zx}^\top Q_{zz}^{-1}Q_{zx} is invertible, because Qzz−1Q_{zz}^{-1} is positive definite and QzxQ_{zx} has full column rank. Matrix inversion and multiplication are continuous at these limits, so by the continuous mapping theorem b−β→(Qzx⊤Qzz−1Qzx)−1Qzx⊤Qzz−1⋅0=0b - \beta \to (Q_{zx}^\top Q_{zz}^{-1}Q_{zx})^{-1}Q_{zx}^\top Q_{zz}^{-1}\cdot 0 = 0. □\square

OLS, by the same argument with Z=XZ = X, tends to β+Qxx−1E[xiεi]\beta + Q_{xx}^{-1}\mathbb{E}[x_i\varepsilon_i], which differs from β\beta when a regressor is correlated with the error. With one endogenous regressor dd, ε=u\varepsilon = u, d=z⊤π+vd = z^\top\pi + v and the simulation of the tests, the OLS limit is β+Cov⁡(d,u)/Var⁡(d)=1+0.6/1.75≈1.343\beta + \operatorname{Cov}(d, u)/\operatorname{Var}(d) = 1 + 0.6/1.75 \approx 1.343.

What is not proved here

The asymptotic normality n(b−β)→N(0,V)\sqrt n(b - \beta) \to N(0, V), the validity of the homoskedastic variance σ2(X⊤PX)−1\sigma^2(X^\top PX)^{-1} and of the HC0 sandwich, and the χl−k2\chi^2_{l - k} limit of Sargan's statistic under valid instruments and homoskedastic errors are cited from Sargan (1958) and the textbook treatment in Angrist and Pischke (2009). Theorem 6 needs a rank condition that holds in the limit; when the instruments are weak, QzxQ_{zx} is close to rank-deficient, and the normal approximation fails in samples of any practical size (Staiger and Stock 1997). The simulation numbers on the page are measured.

Complexity

Forming Z⊤ZZ^\top Z costs Θ(nl2)\Theta(nl^2) and Z⊤XZ^\top X costs Θ(nlk)\Theta(nlk); solving for Π\Pi costs Θ(l3+l2k)\Theta(l^3 + l^2k); X^\hat X costs Θ(nlk)\Theta(nlk); the second stage costs Θ(nk2+k3)\Theta(nk^2 + k^3). Since k≤lk \le l, the total is Θ(nl2+l3)\Theta(nl^2 + l^3), the cost of one least squares fit on the instruments. The space is Θ(nk)\Theta(nk) for X^\hat X and Θ(l2)\Theta(l^2) for the cross products; a streaming version that keeps only Z⊤ZZ^\top Z, Z⊤XZ^\top X, Z⊤yZ^\top y, X⊤XX^\top X, X⊤yX^\top y and y⊤yy^\top y needs Θ(l2)\Theta(l^2) space and one pass, and gets u⊤u=y⊤y−2b⊤X⊤y+b⊤X⊤Xbu^\top u = y^\top y - 2b^\top X^\top y + b^\top X^\top Xb without the residuals (but not the HC0 sandwich).

Properties

  • GMM with a fixed weight. 2SLS minimizes (y−Xb)⊤Z(Z⊤Z)−1Z⊤(y−Xb)(y - Xb)^\top Z(Z^\top Z)^{-1}Z^\top(y - Xb), the generalized method of moments criterion with weight (Z⊤Z)−1(Z^\top Z)^{-1}. That weight is optimal under homoskedastic errors; with heteroskedastic errors, two-step GMM is more efficient when l>kl > k.
  • Biased toward OLS. A common approximation puts the bias of 2SLS at about the OLS bias times 1/(F+1)1/(F + 1), where FF is the population first-stage FF statistic of the excluded instruments; adding weak instruments lowers FF and makes it worse (Bound, Jaeger and Baker 1995; Staiger and Stock 1997). In the weak design of the simulation, F≈0.5F \approx 0.5 predicts a bias of 0.604/1.5≈0.400.604/1.5 \approx 0.40, and the measured bias was 0.39.
  • No finite moments when just-identified. With one instrument per endogenous regressor, the 2SLS estimate has no finite mean; its distribution has heavy tails. The median is still a useful summary.
  • Invariant to the choice of instruments within a span. Only the column span of ZZ matters, since bb depends on ZZ only through PZP_Z.
  • Exact in rational arithmetic. All steps are rational operations, so with fraction inputs the code gives the exact bb, which the tests use.

Variants and improvements

  • Limited information maximum likelihood (LIML). Anderson and Rubin (1949) derived the maximum likelihood estimator of one equation with normal errors. It is approximately median-unbiased and behaves much better than 2SLS with many or weak instruments. Fuller's modification gives it finite moments.
  • k-class estimators. OLS (κ=0\kappa = 0), 2SLS (κ=1\kappa = 1) and LIML (κ=κ^LIML\kappa = \hat\kappa_{\text{LIML}}) are members of one family b(κ)=(X⊤(I−κMZ)X)−1X⊤(I−κMZ)yb(\kappa) = (X^\top(I - \kappa M_Z)X)^{-1}X^\top(I - \kappa M_Z)y with MZ=I−PZM_Z = I - P_Z.
  • Two-step efficient GMM. Use the 2SLS residuals to estimate S=1n∑iui2zizi⊤S = \frac1n\sum_i u_i^2z_iz_i^\top, then minimize with weight S−1S^{-1}. The Hansen JJ statistic replaces Sargan's test under heteroskedasticity.
  • Cluster-robust variance. With grouped data, replace the HC0 meat by sums over clusters, as in cluster-robust standard errors.
  • Weak-instrument-robust inference. The Anderson-Rubin test, described on the instrumental variables page, has the right size whatever the strength of the instruments.
  • Control function. Add the first-stage residual v^\hat v as a regressor in the outcome equation. In the linear model the coefficient on dd equals the 2SLS estimate, and the tt test on v^\hat v is a test of endogeneity (the Durbin-Wu-Hausman test).

When to use it

Use 2SLS when a regressor of interest is correlated with the error, through omitted variables, measurement error or simultaneity, and you have instruments that you can defend as excluded from the outcome equation and as unrelated to the hidden causes. Examples are random encouragements, lotteries, rules that set eligibility, and the physical or institutional quirks used in natural experiments. Report the first-stage FF; if it is small, prefer LIML or the Anderson-Rubin test. If the regressors are exogenous, use OLS: 2SLS then only adds variance. For errors in variables with a second independent measurement, the second measurement is a natural instrument.

Pitfalls

  • Doing the two stages by hand. The point estimate is right, the standard errors are not, because the residuals of the second regression use X^\hat X. Use a routine that computes u=y−Xbu = y - Xb.
  • Leaving the exogenous covariates out of the first stage. Every exogenous regressor of the outcome equation must also be in ZZ. If a covariate is in the second stage but not in the first, the first-stage fits are not orthogonal to it, and the estimate is inconsistent in general.
  • Nonlinear first stages. Plugging fitted values from a probit or logit first stage into a linear second stage ("forbidden regression") is not 2SLS and is not consistent unless the nonlinear model is exactly right. Use the fitted probabilities as an instrument instead.
  • Weak instruments. A first-stage FF of 2 can give an estimate close to OLS with a small standard error and a confident but wrong interval, as in the simulation, where the coverage was 0.82.
  • Many instruments. Adding instruments raises the first-stage R2R^2 by chance and pulls 2SLS toward OLS. Angrist and Krueger (1991) used up to 180 interactions of quarter of birth; Bound, Jaeger and Baker (1995) showed that random instruments reproduced their estimates.
  • Reading Sargan's test as a proof of validity. The test has power only if some instruments are valid and the invalid ones pull in a different direction. If all instruments share the same bias, it does not reject.
  • Constant effects. With heterogeneous effects, different instruments identify different local effects, so Sargan's test can reject even if every instrument satisfies the exclusion restriction.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

stdist.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
two_stage_least_squares.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-stage-least-squares/. The authors are listed in prov/2XMPJR.jsonl.

"""Two-stage least squares (2SLS) for the linear model y = X b + u with instruments Z.

X is n x k (a constant column, exogenous regressors and endogenous regressors) and
Z is n x l with l >= k (the constant, the exogenous regressors and the excluded
instruments). The estimate is

    b = (X' P_Z X)^(-1) X' P_Z y,   P_Z = Z (Z'Z)^(-1) Z'.

It is computed as two least squares fits: X_hat = Z (Z'Z)^(-1) Z'X, then
b = (X_hat' X)^(-1) X_hat' y, which equals the regression of y on X_hat because
X_hat' X = X_hat' X_hat. The residuals use the original X, not X_hat.

Matrices are lists of rows. All functions are exact for Fraction inputs, except
the p-values, which come from stdist.
"""

from collections.abc import Sequence
from typing import NamedTuple

from stdist import chi2_sf, f_sf


class TSLSResult(NamedTuple):
    coef: list  # b, one entry per column of X
    resid: list  # u = y - X b, with the original X
    sigma2: object  # u'u / (n - k)
    cov: list  # sigma2 (X_hat' X_hat)^(-1), the variance under homoskedastic errors
    cov_hc0: list  # the sandwich (X_hat' X_hat)^(-1) (sum u_i^2 xh_i xh_i') (X_hat' X_hat)^(-1)
    first_stage: list  # Pi = (Z'Z)^(-1) Z'X, l x k
    x_hat: list  # Z Pi, n x k


def transpose(a):
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def crossprod(a, b):
    """a' b for matrices with the same number of rows."""
    return matmul(transpose(a), b)


def solve(a: list[list], b: list[list]) -> list[list]:
    """Solve a x = b for a square a and a matrix b, by Gaussian elimination with partial pivoting."""
    k = len(a)
    m = [list(ra) + list(rb) for ra, rb in zip(a, b)]
    w = len(m[0])
    for c in range(k):
        p = max(range(c, k), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix: the instruments or regressors are collinear")
        m[c], m[p] = m[p], m[c]
        for r in range(k):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                for j in range(c, w):
                    m[r][j] -= f * m[c][j]
    return [[m[r][j] / m[r][r] for j in range(k, w)] for r in range(k)]


def inverse(a):
    k = len(a)
    one = a[0][0] * 0 + 1
    return solve(a, [[one if i == j else one - one for j in range(k)] for i in range(k)])


def column(v):
    return [[x] for x in v]


def tsls(y: Sequence, x: list[list], z: list[list]) -> TSLSResult:
    """2SLS fit. Cost: Theta(n l^2 + l^3) for the first stage and Theta(n k^2 + k^3) for the second."""
    n, k, l = len(y), len(x[0]), len(z[0])
    if len(x) != n or len(z) != n:
        raise ValueError("y, X and Z need the same number of rows")
    if l < k:
        raise ValueError("under-identified: fewer instruments than regressors")
    if n <= k:
        raise ValueError("need more units than regressors")
    pi = solve(crossprod(z, z), crossprod(z, x))  # @line L1
    xh = matmul(z, pi)  # @line L2
    a = crossprod(xh, x)  # @line L3
    b = [r[0] for r in solve(a, crossprod(xh, column(y)))]
    u = [yi - sum(xij * bj for xij, bj in zip(row, b)) for yi, row in zip(y, x)]  # @line L4
    s2 = sum(ui * ui for ui in u) / (n - k)  # @line L5
    bread = inverse(crossprod(xh, xh))
    cov = [[s2 * v for v in row] for row in bread]
    meat = [[sum(ui * ui * r[i] * r[j] for ui, r in zip(u, xh)) for j in range(k)] for i in range(k)]  # @line L6
    hc0 = matmul(matmul(bread, meat), bread)
    return TSLSResult(b, u, s2, cov, hc0, pi, xh)  # @line L7


def ols(y: Sequence, x: list[list]) -> list:
    """Least squares coefficients of y on the columns of x."""
    return [r[0] for r in solve(crossprod(x, x), crossprod(x, column(y)))]


def sargan(res: TSLSResult, z: list[list]) -> tuple[object, int, float]:
    """Sargan's overidentification statistic n R^2 from the regression of the 2SLS residuals on Z.

    Returns (statistic, degrees of freedom l - k, p-value from chi-square). The R^2 is centred,
    so Z must contain a constant column. Valid with homoskedastic errors.
    """
    n, k, l = len(res.resid), len(res.coef), len(z[0])
    if l == k:
        raise ValueError("just-identified: there is nothing to test")
    u = res.resid
    g = ols(u, z)
    fit = [sum(zij * gj for zij, gj in zip(row, g)) for row in z]
    ubar = sum(u) / n
    tss = sum((ui - ubar) ** 2 for ui in u)
    ess = sum((fi - ubar) ** 2 for fi in fit)
    stat = n * ess / tss
    return stat, l - k, chi2_sf(float(stat), l - k)


def first_stage_f(d: Sequence, z_exog: list[list], z_excl: list[list]) -> tuple[object, int, int, float]:
    """F statistic for the excluded instruments in the regression of one endogenous regressor d
    on (z_exog, z_excl). Returns (F, q, n - l, p-value) with q the number of excluded instruments."""
    n = len(d)
    full = [a + b for a, b in zip(z_exog, z_excl)]
    l, q = len(full[0]), len(z_excl[0])

    def rss(cols):
        g = ols(d, cols)
        return sum((di - sum(c * gj for c, gj in zip(row, g))) ** 2 for di, row in zip(d, cols))

    ru, rr = rss(full), rss(z_exog)
    f = ((rr - ru) / q) / (ru / (n - l))
    return f, q, n - l, f_sf(float(f), q, n - l)
test_two_stage_least_squares.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-stage-least-squares/. The authors are listed in prov/2XMPJR.jsonl.

import math
import random
import statistics
from fractions import Fraction as Fr

import pytest

from two_stage_least_squares import crossprod, column, first_stage_f, inverse, matmul, ols, sargan, solve, tsls

ONE = Fr(1)


def test_worked_example():
    z = [0, 0, 0, 0, 1, 1, 1, 1]
    d = [0, 0, 0, 1, 1, 1, 1, 0]
    y = [1, 2, 3, 6, 5, 6, 4, 2]
    x = [[ONE, Fr(v)] for v in d]
    zz = [[ONE, Fr(v)] for v in z]
    r = tsls([Fr(v) for v in y], x, zz)
    assert r.coef == [Fr(19, 8), Fr(5, 2)]
    assert r.first_stage == [[1, Fr(1, 4)], [0, Fr(1, 2)]]
    assert r.resid == [Fr(v, 8) for v in (-11, -3, 5, 9, 1, 9, -7, -3)]
    assert r.sigma2 == Fr(47, 48)
    assert r.cov[1][1] == Fr(47, 24) and r.cov_hc0[1][1] == Fr(47, 32)
    assert ols([Fr(v) for v in y], x) == [Fr(2), Fr(13, 4)]


def wald(y, d, z):
    y1 = [a for a, b in zip(y, z) if b == 1]
    y0 = [a for a, b in zip(y, z) if b == 0]
    d1 = [a for a, b in zip(d, z) if b == 1]
    d0 = [a for a, b in zip(d, z) if b == 0]
    return (sum(y1) / len(y1) - sum(y0) / len(y0)) / (sum(d1) / len(d1) - sum(d0) / len(d0))


def test_binary_instrument_equals_wald_ratio_exactly():
    rng = random.Random(1)
    done = 0
    while done < 200:
        n = rng.randint(4, 12)
        z = [i % 2 for i in range(n)]
        rng.shuffle(z)
        d = [Fr(rng.randint(0, 1)) for _ in range(n)]
        y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
        try:
            target = wald(y, d, z)
        except ZeroDivisionError:
            continue
        r = tsls(y, [[ONE, v] for v in d], [[ONE, Fr(v)] for v in z])
        assert r.coef[1] == target
        assert r.coef[0] == sum(y) / n - target * sum(d) / n
        done += 1


def random_design(rng, n, k_exog, k_endog, l_excl):
    exog = [[ONE] + [Fr(rng.randint(-5, 5)) for _ in range(k_exog)] for _ in range(n)]
    excl = [[Fr(rng.randint(-5, 5)) for _ in range(l_excl)] for _ in range(n)]
    endog = [[sum(e) + sum(z) + Fr(rng.randint(-3, 3)) for _ in range(k_endog)] for e, z in zip(exog, excl)]
    x = [a + b for a, b in zip(exog, endog)]
    z = [a + b for a, b in zip(exog, excl)]
    y = [Fr(rng.randint(-20, 20)) for _ in range(n)]
    return y, x, z, exog, excl


def test_equals_the_two_literal_stages():
    """Regressing y on the first-stage fitted values gives the same b, but the residual variance of
    that second regression is not the 2SLS one (it uses X_hat instead of X)."""
    rng = random.Random(2)
    differ = 0
    for _ in range(60):
        y, x, z, _, _ = random_design(rng, rng.randint(8, 14), 1, 1, 2)
        try:
            r = tsls(y, x, z)
        except ValueError:
            continue
        xh = [[sum(zij * pj for zij, pj in zip(zr, col)) for col in zip(*solve(crossprod(z, z), crossprod(z, x)))] for zr in z]
        assert ols(y, xh) == r.coef
        naive = [yi - sum(a * b for a, b in zip(row, r.coef)) for yi, row in zip(y, xh)]
        differ += sum(v * v for v in naive) != sum(v * v for v in r.resid)
    assert differ > 50


def test_just_identified_is_the_simple_iv_formula():
    rng = random.Random(3)
    for _ in range(60):
        y, x, z, _, _ = random_design(rng, rng.randint(6, 12), 1, 2, 2)
        try:
            r = tsls(y, x, z)
            direct = [v[0] for v in solve(crossprod(z, x), crossprod(z, column(y)))]
        except ValueError:
            continue
        assert r.coef == direct


def test_instruments_equal_to_regressors_give_ols():
    rng = random.Random(4)
    for _ in range(60):
        n = rng.randint(5, 12)
        x = [[ONE] + [Fr(rng.randint(-6, 6)) for _ in range(2)] for _ in range(n)]
        y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
        try:
            r = tsls(y, x, x)
            b = ols(y, x)
        except ValueError:
            continue
        assert r.coef == b
        # White's HC0 for OLS, computed directly
        bread = inverse(crossprod(x, x))
        u = [yi - sum(a * c for a, c in zip(row, b)) for yi, row in zip(y, x)]
        meat = [[sum(ui * ui * row[i] * row[j] for ui, row in zip(u, x)) for j in range(3)] for i in range(3)]
        assert r.cov_hc0 == matmul(matmul(bread, meat), bread)


def test_first_stage_f_with_one_instrument_is_t_squared():
    rng = random.Random(5)
    for _ in range(40):
        y, x, z, exog, excl = random_design(rng, rng.randint(7, 12), 1, 1, 1)
        d = [row[-1] for row in x]
        try:
            f, q, df, _ = first_stage_f(d, exog, excl)
            r = tsls(d, z, z)  # OLS of d on Z, with its homoskedastic variance
        except (ValueError, ZeroDivisionError):
            continue
        assert q == 1 and f == r.coef[-1] ** 2 / r.cov[-1][-1]


def simulate(rng, n, beta, pi, rho, invalid=0.0):
    """y = 1 + beta d + u, d = z' pi + v, corr(u, v) = rho, three N(0, 1) instruments.
    invalid adds that multiple of the first instrument to y (a direct effect)."""
    y, x, z = [], [], []
    for _ in range(n):
        zi = [rng.gauss(0, 1) for _ in range(3)]
        e1, e2 = rng.gauss(0, 1), rng.gauss(0, 1)
        u = e1
        v = rho * e1 + math.sqrt(1 - rho * rho) * e2
        d = sum(p * a for p, a in zip(pi, zi)) + v
        y.append(1 + beta * d + u + invalid * zi[0])
        x.append([1.0, d])
        z.append([1.0] + zi)
    return y, x, z


def test_consistent_where_ols_is_biased_and_sargan_size():
    """r = 300 samples of n = 200 (seed 2026), beta = 1, first stage pi = (0.5, 0.5, 0.5), rho = 0.6.
    OLS has limit 1 + 0.6/1.75 = 1.343. 2SLS mean within 4 SE + 0.02 of 1; HC0 interval coverage at
    least 0.90; Sargan rejection rate at 5% within 0.05 +- 4 SE (SE = 0.0126)."""
    rng = random.Random(2026)
    r_, est, olss, rej, cover = 300, [], [], 0, 0
    for _ in range(r_):
        y, x, z = simulate(rng, 200, 1.0, (0.5, 0.5, 0.5), 0.6)
        res = tsls(y, x, z)
        est.append(res.coef[1])
        olss.append(ols(y, x)[1])
        se = math.sqrt(res.cov_hc0[1][1])
        cover += abs(res.coef[1] - 1) <= 1.96 * se
        rej += sargan(res, z)[2] < 0.05
    assert abs(statistics.mean(est) - 1) < 4 * statistics.stdev(est) / math.sqrt(r_) + 0.02
    assert abs(statistics.mean(olss) - 1.343) < 0.02
    assert cover / r_ >= 0.90
    assert abs(rej / r_ - 0.05) < 4 * math.sqrt(0.05 * 0.95 / r_)


def test_sargan_detects_an_invalid_instrument():
    rng = random.Random(7)
    rej = 0
    for _ in range(100):
        y, x, z = simulate(rng, 200, 1.0, (0.5, 0.5, 0.5), 0.6, invalid=0.5)
        rej += sargan(tsls(y, x, z), z)[2] < 0.05
    assert rej >= 80


def test_input_checks():
    x = [[ONE, Fr(i)] for i in range(5)]
    with pytest.raises(ValueError):
        tsls([ONE] * 5, x, [[ONE]] * 5)  # fewer instruments than regressors
    with pytest.raises(ValueError):
        tsls([ONE] * 5, x, [[ONE, ONE]] * 5)  # the instrument is constant: Z'Z is singular
    with pytest.raises(ValueError):
        sargan(tsls([Fr(i * i) for i in range(5)], x, x), x)

History

Theil (1953), in a memorandum of the Netherlands Central Planning Bureau, and Basmann (1957) proposed two-stage least squares independently, as a way to estimate one equation of a system of simultaneous equations without the full maximum likelihood of the Cowles Commission. Anderson and Rubin (1949) had already given the limited information maximum likelihood estimator and the test that bears their names. Sargan (1958) set out the general instrumental variables estimator, of which 2SLS is the efficient case under homoskedasticity, and the test of overidentifying restrictions. In the 1990s the method became the main tool of the "natural experiments" of labour economics, and the problems with weak instruments found by Bound, Jaeger and Baker (1995) and Staiger and Stock (1997) led to the first-stage diagnostics and the robust tests used today.

References

  1. Henri Theil, Repeated least squares applied to complete equation systems, Central Planning Bureau, 1953, the whole memorandum (the two-stage method; cited here from later accounts, not seen)
  2. R. L. Basmann, A generalized classical method of linear estimation of coefficients in a structural equation, Econometrica 25(1), 1957, the article starting on p. 77 (the estimator for one structural equation)
  3. J. D. Sargan, The estimation of economic relationships using instrumental variables, Econometrica 26(3), 1958, the article starting on p. 393 (the general instrumental variables estimator, its large-sample theory and the test of the extra instruments)
  4. Douglas Staiger and James H. Stock, Instrumental variables regression with weak instruments, Econometrica 65(3), 1997, the article starting on p. 557 (weak-instrument asymptotics, bias toward OLS, the first-stage F rule)
  5. James H. Stock and Motohiro Yogo, Testing for weak instruments in linear IV regression, in Identification and Inference for Econometric Models, Cambridge University Press, 2005, pp. 80 to 108 (critical values of the first-stage F statistic for given bias or size distortion)
  6. John Bound, David A. Jaeger and Regina M. Baker, Problems with instrumental variables estimation when the correlation between the instruments and the endogenous explanatory variable is weak, Journal of the American Statistical Association 90(430), 1995, pp. 443 to 450 (bias toward OLS with weak instruments, and the quarter of birth estimates reproduced with random instruments)
  7. Joshua D. Angrist and Jörn-Steffen Pischke, Mostly Harmless Econometrics, Princeton University Press, 2009, Chapter 4, Instrumental Variables in Action (2SLS, the Wald estimator, standard errors and weak instruments; general locator, the section numbers were not checked)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example