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
- Model
- Real RAM
- Properties
- consistent with valid strong instrumentsdeterministicequals ols when instruments are regressorsequals wald ratio with one binary instrumentexact in rational arithmetic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Henri Theil, Robert L. Basmann, John Denis Sargan, 1953
Two-stage least squares (2SLS) estimates the coefficients of a linear model in which some regressors are correlated with the error, using instruments that are correlated with the regressors but not with the error. The first stage regresses each column of on the instruments and keeps the fitted values ; this keeps only the part of the regressors that the instruments explain, which is uncorrelated with the error. The second stage regresses on . In one formula, with 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 , not with .
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 , where has entries: a constant, exogenous covariates and endogenous regressors (the treatments). The instrument vector has entries: the constant, , and the excluded instruments. The assumptions are
- exogeneity: , which contains both the exclusion restriction (the excluded instruments do not enter the equation for ) and the independence of the instruments from the unobserved causes of ;
- relevance: is invertible and has rank , so the instruments move every endogenous regressor.
Then is the unique solution of in the column space selected by the rank condition, and with the moment conditions overidentify it. Relevance is testable with the first-stage regression. Exogeneity is not testable when ; with only the consistency of the extra conditions with the others can be tested (Sargan's test), assuming at least of them are valid. The linear equation with a constant 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 (-vector), () and (). The output is , the residuals , the homoskedastic variance with , 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 tests are large when the instruments are weak. The first-stage statistic of the excluded instruments is the usual diagnostic: Staiger and Stock (1997) suggested as a rule of thumb for one endogenous regressor, and Stock and Yogo (2005) give critical values.
The algorithm
TSLS(y, X, Z) ▷ X is n × k, Z is n × l, l ≥ k- 1
Π ← solve (ZᵀZ) Π = ZᵀX ▷ first stage: one regression per column of X - 2
X̂ ← Z Π ▷ fitted regressors; exogenous columns are reproduced exactly - 3
b ← solve (X̂ᵀX) b = X̂ᵀy ▷ second stage; X̂ᵀX = X̂ᵀX̂ - 4
u ← y - X b ▷ residuals with the ORIGINAL X - 5
σ² ← uᵀu / (n - k) - 6
V ← σ² (X̂ᵀX̂)⁻¹; V_HC0 ← (X̂ᵀX̂)⁻¹ (Σ_i u_i² x̂_i x̂_iᵀ) (X̂ᵀX̂)⁻¹ - 7
return (b, V, V_HC0)
The columns of that are also columns of (the constant and the exogenous covariates) are fitted exactly in line L1, so only the endogenous columns change in . Line L3 can be read as the regression of on , which is where the name comes from; but the residual variance of that regression uses , which is wrong, and that is why line L4 goes back to . In floating point, solve the least squares problems by QR rather than by forming , which squares the condition number.
Example
Eight units. The instrument is a random encouragement, is whether the unit took the treatment, and is the outcome.
| 0 | 0, 0, 0, 1 | 1, 2, 3, 6 |
| 1 | 1, 1, 1, 0 | 5, 6, 4, 2 |
First stage. when and when , so : the encouragement raises the treatment rate by .
Second stage. when and when . The regression of on gives . The slope is the Wald ratio , as it must be with one binary instrument. OLS of on gives slope : the units that took the treatment against the encouragement differ from the rest.
Standard errors. The residuals are , so and . The centred sum of squares of is , so the variance of the slope is and its standard error is 1.40; the HC0 standard error is . The residuals of the literal second regression, , are and , with sum of squares ; a program run on would report a standard error of , twice too large here, and in other data too small.
Simulation. , with three standard normal instruments and , so OLS tends to . Over 300 samples of , measured:
| design | 2SLS mean | 2SLS SD | OLS mean | 95% HC0 coverage | Sargan rejects at 5% | median first-stage |
|---|---|---|---|---|---|---|
| strong instruments | 1.006 | 0.085 | 1.344 | 0.94 | 0.06 | 50.4 |
| weak, 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 , 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. , and since is symmetric and idempotent, . So line L3 computes , which is also the regression of on .
- Just-identified. With , , the simple instrumental variables formula.
- One binary instrument. With and , the equations say the residuals sum to 0 in each instrument group, so and , and is the Wald ratio. The tests check this exactly on 200 random data sets.
- No endogeneity. With , and 2SLS is OLS, with White's sandwich.
- Consistency. , and with and the rank condition, the law of large numbers and continuous mapping give . OLS tends to instead.
Proved: the algebra above and consistency. Cited: asymptotic normality, the validity of the variance estimates, and the 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 be an -vector, an matrix and an matrix with . Assume is invertible and write , the orthogonal projection on the column span of . is symmetric and . TSLS computes (line L1), (line L2) and solves (line L3).
Lemma 1 (the projection form). , and . So if is invertible,
and is also the least squares coefficient of on .
Proof. . Then and , using and . Also . The least squares coefficient of on solves , the same system as line L3.
Theorem 2 (just-identified). If and is invertible, then .
Proof. is a product of three invertible matrices, with inverse . Multiplying by gives .
Theorem 3 (no endogeneity). If (every regressor is its own instrument) and is invertible, is the OLS coefficient and ; the HC0 variance of line L6 is then White's OLS sandwich.
Proof. when the columns of span the space of . Then , and lines L3 and L6 become the OLS normal equations and the OLS sandwich.
Theorem 4 (the Wald ratio). Let and with , both values present. Write for the means over the units with and for . If , then the 2SLS slope is
and the intercept is .
Proof. The model is just-identified, and is invertible: its determinant is , with the group sizes. By Theorem 2, solves , that is, and . Subtracting, the residuals also sum to 0 over . Dividing by the group sizes, and . Subtracting gives , and the first equation gives .
Lemma 5 (which residuals). The residuals of line L4, , and the residuals of the literal second regression, , differ by . In general .
Proof. Subtract. For a concrete case, the example on the page has and .
Under the model , estimates , while contains the first-stage error . That is why a regression program run on gives the right and the wrong standard errors.
Consistency
Theorem 6. Let the rows be independent and identically distributed with finite second moments, , and assume
- exogeneity of the instruments: ;
- rank: is invertible and has rank .
Then in probability.
Proof. Substituting in Lemma 1,
By the law of large numbers , and . The matrix is invertible, because is positive definite and has full column rank. Matrix inversion and multiplication are continuous at these limits, so by the continuous mapping theorem .
OLS, by the same argument with , tends to , which differs from when a regressor is correlated with the error. With one endogenous regressor , , and the simulation of the tests, the OLS limit is .
What is not proved here
The asymptotic normality , the validity of the homoskedastic variance and of the HC0 sandwich, and the 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, 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 costs and costs ; solving for costs ; costs ; the second stage costs . Since , the total is , the cost of one least squares fit on the instruments. The space is for and for the cross products; a streaming version that keeps only , , , , and needs space and one pass, and gets without the residuals (but not the HC0 sandwich).
Properties
- GMM with a fixed weight. 2SLS minimizes , the generalized method of moments criterion with weight . That weight is optimal under homoskedastic errors; with heteroskedastic errors, two-step GMM is more efficient when .
- Biased toward OLS. A common approximation puts the bias of 2SLS at about the OLS bias times , where is the population first-stage statistic of the excluded instruments; adding weak instruments lowers and makes it worse (Bound, Jaeger and Baker 1995; Staiger and Stock 1997). In the weak design of the simulation, predicts a bias of , 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 matters, since depends on only through .
- Exact in rational arithmetic. All steps are rational operations, so with fraction inputs the code gives the exact , 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 (), 2SLS () and LIML () are members of one family with .
- Two-step efficient GMM. Use the 2SLS residuals to estimate , then minimize with weight . The Hansen 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 as a regressor in the outcome equation. In the linear model the coefficient on equals the 2SLS estimate, and the test on 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 ; 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 . Use a routine that computes .
- Leaving the exogenous covariates out of the first stage. Every exogenous regressor of the outcome equation must also be in . 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 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 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2XMPJR Edit this page History Report an error Markdown