Algorithm Search⌘K

Techniquecore

Instrumental variables estimation

Also called IV estimation, instrumental variable method.

Identifies a causal effect under unmeasured confounding with a variable that moves the treatment but affects the outcome only through it.

Instrumental variables estimation recovers the causal effect of a treatment DD on an outcome YY when unmeasured confounders affect both, so that neither a regression of YY on DD nor any adjustment for measured covariates can remove the bias. It needs a third variable ZZ, the instrument, that moves DD, has no path to YY except through DD, and is as good as randomly assigned. Then the effect of ZZ on YY is the effect of ZZ on DD times the effect of DD on YY, and the effect of DD on YY is the ratio of two estimable effects: β=Cov⁡(Z,Y)/Cov⁡(Z,D)\beta = \operatorname{Cov}(Z, Y)/\operatorname{Cov}(Z, D), which for a binary instrument is the Wald ratio of the differences in means. The technique is the identification argument; two-stage least squares is the estimator that carries it to several instruments and covariates. With effects that vary across units, the ratio is the local average treatment effect of the units the instrument moves. With weak instruments the ratio is badly behaved, and the Anderson-Rubin test gives confidence sets that stay valid.

In plain words

Suppose we want to know whether a training course raises wages, but the people who take it are more motivated, and motivation also raises wages. Comparing takers and non-takers mixes the two. Now suppose the course was advertised by letter to a random half of the people. The letter makes taking the course more likely, and it cannot affect wages by itself.

Compare the two halves. The half that got letters took the course more often, by some amount, and earned more, by some other amount. Because the halves were formed at random, motivation is the same in both, so the extra earnings can only come through the extra course-taking. Dividing the extra earnings by the extra course-taking gives the effect of the course per person who took it because of the letter. The letter is the instrument.

When it applies

The setting is a treatment DD, an outcome YY, and unobserved UU that affects both. The instrument ZZ must satisfy three conditions, written here in potential outcomes Y(d,z)Y(d, z) and D(z)D(z):

  • Relevance. ZZ changes DD: Cov⁡(Z,D)≠0\operatorname{Cov}(Z, D) \ne 0. This is testable with the first-stage regression of DD on ZZ.
  • Exclusion. ZZ affects YY only through DD: Y(d,z)=Y(d)Y(d, z) = Y(d) for all d,zd, z. This is an assumption about the world and cannot be tested from (Z,D,Y)(Z, D, Y) alone with one instrument.
  • Independence. ZZ is as good as randomly assigned: ZZ is independent of (Y(d),D(z))(Y(d), D(z)) for all d,zd, z. It holds by design when ZZ is randomized, and otherwise it is an assumption, often made conditional on covariates XX.

Then two different targets are identified, under two different extra assumptions:

  • Constant effects. If Y=α+βD+εY = \alpha + \beta D + \varepsilon with the same β\beta for every unit and Cov⁡(Z,ε)=0\operatorname{Cov}(Z, \varepsilon) = 0, then Cov⁡(Z,Y)=βCov⁡(Z,D)+Cov⁡(Z,ε)=βCov⁡(Z,D)\operatorname{Cov}(Z, Y) = \beta\operatorname{Cov}(Z, D) + \operatorname{Cov}(Z, \varepsilon) = \beta\operatorname{Cov}(Z, D), and relevance gives β=Cov⁡(Z,Y)/Cov⁡(Z,D)\beta = \operatorname{Cov}(Z, Y)/\operatorname{Cov}(Z, D).
  • Heterogeneous effects with a binary ZZ and DD. If no unit takes the treatment because the instrument is off and refuses it because it is on (monotonicity), the same ratio equals E[Y(1)−Y(0)∣D(1)>D(0)]\mathbb{E}[Y(1) - Y(0) \mid D(1) > D(0)], the average effect among the compliers. The LATE theorem page proves this.

The technique is not needed when the treatment is randomized or when ignorability given measured covariates is credible: then the instrument only adds variance. It does not help when no defensible instrument exists, which is the usual case.

The template

Identification. The estimand is β\beta in the constant effect model or the complier effect under monotonicity. The identification formula is the ratio of the reduced form to the first stage,

β=Cov⁡(Z,Y)Cov⁡(Z,D),for binary Z:β=E[Y∣Z=1]−E[Y∣Z=0]E[D∣Z=1]−E[D∣Z=0].\beta = \frac{\operatorname{Cov}(Z, Y)}{\operatorname{Cov}(Z, D)}, \qquad \text{for binary } Z: \quad \beta = \frac{\mathbb{E}[Y \mid Z = 1] - \mathbb{E}[Y \mid Z = 0]}{\mathbb{E}[D \mid Z = 1] - \mathbb{E}[D \mid Z = 0]}.

The two forms agree for a binary ZZ, because Cov⁡(Z,V)=p(1−p)(E[V∣Z=1]−E[V∣Z=0])\operatorname{Cov}(Z, V) = p(1 - p)(\mathbb{E}[V \mid Z = 1] - \mathbb{E}[V \mid Z = 0]) for any VV, with p=Pr⁡[Z=1]p = \Pr[Z = 1]. The sample versions agree exactly too, which the tests check with fractions.

Estimation. With one instrument and one treatment the steps are below. The holes are the instrument, the covariates (handled by adding them to both regressions, which is 2SLS), and the level α\alpha.

  1. INSTRUMENT-ANALYSIS(Y, D, Z, α) ▷ one treatment, one instrument, n units
  2. 1first stage: slope π̂ of D on (1, Z) and its F statistic F₁
  3. 2reduced form: slope ρ̂ of Y on (1, Z)
  4. 3β̂ ← ρ̂ / π̂ ▷ = s_ZY / s_ZD; the Wald ratio for binary Z
  5. 4residuals Y - ȳ - β̂ (D - d̄); σ̂² ← their sum of squares / (n - 2); se ← σ̂ √s_ZZ / |s_ZD|
  6. 5AR set ← {b : F statistic of Z in the regression of Y - b D on (1, Z) ≤ F_{1, n-2, 1-α}}
  7. 6return (β̂, se, F₁, AR set)

Here sZY=∑i(Zi−zˉ)(Yi−yˉ)s_{ZY} = \sum_i(Z_i - \bar z)(Y_i - \bar y) and so on. The estimate β^\hat\beta is consistent when the three conditions hold and Cov⁡(Z,D)≠0\operatorname{Cov}(Z, D) \ne 0, and β^±t se\hat\beta \pm t\,\mathrm{se} is a valid large-sample interval when the instrument is strong. Both fail together when the instrument is weak.

The Anderson-Rubin set. The Anderson-Rubin (AR) test of Line L5 tests each value bb by asking whether ZZ predicts Y−bDY - bD. Under β=b\beta = b, Y−bD=α+εY - bD = \alpha + \varepsilon does not depend on ZZ, so with normal errors independent of ZZ the statistic

AR(b)=(n−2)rb21−rb2,rb=corr⁡(Z,Y−bD),\mathrm{AR}(b) = (n - 2)\frac{r_b^2}{1 - r_b^2}, \qquad r_b = \operatorname{corr}(Z, Y - bD),

has exactly the F1,n−2F_{1, n - 2} law, whatever the value of Cov⁡(Z,D)\operatorname{Cov}(Z, D). Without normality it is still asymptotically valid. The set of bb not rejected is found in closed form. With c(b)=sZY−b sZDc(b) = s_{ZY} - b\,s_{ZD}, sww(b)=sYY−2b sYD+b2sDDs_{ww}(b) = s_{YY} - 2b\,s_{YD} + b^2s_{DD} and q=F1,n−2,1−αq = F_{1, n - 2, 1 - \alpha}, the condition AR(b)≤q\mathrm{AR}(b) \le q is

c(b)2−κ sZZ sww(b)≤0,κ=qn−2+q,c(b)^2 - \kappa\,s_{ZZ}\,s_{ww}(b) \le 0, \qquad \kappa = \frac{q}{n - 2 + q},

a quadratic inequality in bb with leading coefficient sZD2−κsZZsDDs_{ZD}^2 - \kappa s_{ZZ}s_{DD}. That coefficient is positive exactly when the first-stage statistic F1=(n−2)rZD2/(1−rZD2)F_1 = (n - 2)r_{ZD}^2/(1 - r_{ZD}^2) exceeds qq, since both say rZD2>κr_{ZD}^2 > \kappa. So the set is a bounded interval if and only if the first stage is significant at level α\alpha, and otherwise it is the complement of an interval or the whole line. An unbounded set is the honest answer when the data cannot tell the effect apart from infinity: as b→±∞b \to \pm\infty, AR(b)→F1\mathrm{AR}(b) \to F_1. When it is an interval, it contains β^\hat\beta, where c=0c = 0. This is the test-inversion of test-interval duality, and the shapes are those of Fieller's set for a ratio, for the same reason. The tests check the closed form against a grid of 801 values of bb and check the bounded-if-and-only-if-significant rule.

Worked example. Eight units, the same data as on the 2SLS page:

ZZ DD YY
0 0, 0, 0, 1 1, 2, 3, 6
1 1, 1, 1, 0 5, 6, 4, 2

The centred sums are sZZ=2s_{ZZ} = 2, sZD=1s_{ZD} = 1, sZY=5/2s_{ZY} = 5/2, sDD=2s_{DD} = 2, sYD=13/2s_{YD} = 13/2, sYY=207/8s_{YY} = 207/8. So β^=(5/2)/1=5/2\hat\beta = (5/2)/1 = 5/2, which is also (17/4−3)/(3/4−1/4)(17/4 - 3)/(3/4 - 1/4). The residual sum of squares is 207/8−2⋅52⋅132+254⋅2=47/8207/8 - 2 \cdot \frac52 \cdot \frac{13}{2} + \frac{25}{4} \cdot 2 = 47/8, so σ^2=47/48\hat\sigma^2 = 47/48 and se=47/48⋅2/1=1.40\mathrm{se} = \sqrt{47/48 \cdot 2}/1 = 1.40; the usual 95% interval with t6=2.447t_{6} = 2.447 is (−0.92,5.92)(-0.92, 5.92). But the first stage is weak: rZD2=1/4r_{ZD}^2 = 1/4, so F1=6⋅1/43/4=2F_1 = 6 \cdot \frac{1/4}{3/4} = 2, far below F1,6,0.95=5.99F_{1, 6, 0.95} = 5.99. The 95% Anderson-Rubin set is the whole real line: no value of the effect can be rejected, and the tt interval was false comfort. At level α=0.30\alpha = 0.30, where q=1.27<2q = 1.27 < 2, the set is the interval (−2.51,3.91)(-2.51, 3.91). For b=0b = 0, AR(0)=6⋅(5/2)2/(2⋅207/8−25/4)=75/91\mathrm{AR}(0) = 6 \cdot (5/2)^2/(2 \cdot 207/8 - 25/4) = 75/91.

Simulation. Y=D+εY = D + \varepsilon, D=πZ+vD = \pi Z + v, corr⁡(ε,v)=0.8\operatorname{corr}(\varepsilon, v) = 0.8, n=50n = 50, 2000 samples each, all numbers measured:

first-stage π\pi AR rejects β=1\beta = 1 tt test rejects β=1\beta = 1 AR set bounded median of β^\hat\beta mean of OLS
0.05 0.052 0.121 0.06 1.715 1.800
0.3 0.048 0.090 0.53 1.019 1.734
1.0 0.050 0.046 1.00 1.001 1.400

The AR test keeps its 5% size in every row. With a weak instrument the ratio estimate sits near OLS and the tt test rejects a true value two to three times too often.

Classic examples

  • Supply and demand. Wright (1928), in Appendix B of a book on the tariff on animal and vegetable oils, estimated the elasticities of supply and demand for butter and flaxseed. Price and quantity are set together by both curves, so a regression of one on the other estimates neither. A variable that shifts supply only, such as yield per acre, traces out the demand curve, and one that shifts demand only traces out supply. Stock and Trebbi (2003) describe the history.
  • Quarter of birth and schooling. Angrist and Krueger (1991) noted that compulsory schooling laws let students leave at an age, not at a grade, so those born early in the year can leave with slightly less schooling. Quarter of birth is the instrument for years of schooling in a wage equation. The study is also the standard warning about weak and many instruments (Bound, Jaeger and Baker 1995, on the 2SLS page).
  • Randomized trials with noncompliance. Assignment to treatment is a randomized instrument for the treatment actually received. The ratio of the intention-to-treat effect on the outcome to its effect on uptake is the effect among compliers.
  • Draft lottery. The Vietnam-era draft lottery numbers were random and changed the chance of military service; Angrist used them to estimate the effect of service on later earnings.
  • Mendelian randomization. Genetic variants that affect an exposure, such as a variant that changes alcohol tolerance, are assigned at conception, roughly at random given the parents' genes. The exclusion restriction fails if the variant has other effects (pleiotropy).
  • Measurement error. If DD is measured with error, a second independent measurement of the same quantity is an instrument for the first, and removes the attenuation bias of errors in variables.

Variations

  • Several instruments and covariates. Use two-stage least squares, or efficient GMM with heteroskedastic errors. Extra instruments allow Sargan's test of overidentifying restrictions.
  • Limited information maximum likelihood. Anderson and Rubin (1949): less biased than 2SLS with weak or many instruments; with one instrument it equals the ratio estimate.
  • Weak-instrument-robust tests. With several instruments the AR test loses power because its degrees of freedom grow with the number of instruments; the conditional likelihood ratio test of Moreira and the K test of Kleibergen keep the size with better power.
  • Control function. Add the first-stage residual to the outcome regression. In linear models this equals 2SLS; in nonlinear models it is a different estimator with its own assumptions.
  • Conditional instruments. If ZZ is random only given covariates XX, add XX to both stages, or weight by the instrument propensity score (Abadie's kappa weighting).
  • Fuzzy regression discontinuity. Crossing a cutoff is an instrument for the treatment near the cutoff; the estimate is a ratio of two jumps. See the regression discontinuity page.
  • System identification. Control engineering uses the same idea to estimate a dynamic model from noisy data, with delayed inputs as instruments: see instrumental variable identification.

Pitfalls

  • Defending the exclusion restriction with data. With one instrument it cannot be tested. A balance table of covariates across instrument values supports independence, not exclusion.
  • Weak instruments. A first-stage FF below about 10 makes the ratio biased toward OLS and the tt interval too narrow. Report the first stage and use the AR set.
  • Ignoring heterogeneity. With varying effects, the estimate is the effect for compliers, who may be a small and unusual group. Two valid instruments can give two different answers, and neither is the average effect over everyone.
  • Defiers. If some units do the opposite of what the instrument pushes, the ratio is a difference of complier and defier effects and can even have the wrong sign.
  • Small first stage in a large sample. A significant first stage with a tiny effect on DD means that a tiny direct effect of ZZ on YY (a small violation of exclusion) is divided by a tiny number and becomes a large bias.
  • Reading the reduced form as the effect. The reduced form E[Y∣Z=1]−E[Y∣Z=0]\mathbb{E}[Y \mid Z = 1] - \mathbb{E}[Y \mid Z = 0] is the effect of the instrument (the intention-to-treat effect), not of the treatment; it is smaller by the factor E[D∣Z=1]−E[D∣Z=0]\mathbb{E}[D \mid Z = 1] - \mathbb{E}[D \mid Z = 0].

Code

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.

instrumental_variables_estimation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instrumental-variables-estimation/. The authors are listed in prov/CM6TM9.jsonl.

"""Instrumental variables with one treatment d and one instrument z.

The structural model is y = alpha + beta d + e with z uncorrelated with e. The IV
estimate is the ratio of two regression slopes on z (the reduced form over the first
stage), beta = Cov(z, y) / Cov(z, d); for a binary z it is the Wald ratio.

The Anderson-Rubin (AR) test of beta = b0 regresses y - b0 d on (1, z) and uses the
F statistic of the slope. With normal errors independent of z it is exactly F(1, n - 2)
under the null, whatever the strength of the instrument. Inverting it gives a
confidence set that is an interval, the complement of an open interval, a half-line,
or the whole line.

The point estimates and the statistics are exact for Fraction inputs; the critical
values and p-values come from stdist.
"""

import math
from collections.abc import Sequence
from functools import lru_cache
from typing import NamedTuple

from stdist import f_ppf, f_sf, t_ppf


class Moments(NamedTuple):
    n: int
    szz: object
    szd: object
    szy: object
    sdd: object
    syd: object
    syy: object


class IVResult(NamedTuple):
    beta: object  # the IV estimate
    alpha: object  # the intercept
    se: float  # the homoskedastic standard error
    first_stage_f: object  # F statistic of z in the regression of d on (1, z)
    ar_set: tuple  # the AR confidence set, see ar_set()


def moments(y: Sequence, d: Sequence, z: Sequence) -> Moments:
    """Centred sums of squares and cross products (not divided by n)."""
    n = len(y)
    if len(d) != n or len(z) != n:
        raise ValueError("y, d and z need the same length")
    if n < 3:
        raise ValueError("need at least 3 units")
    my, md, mz = sum(y) / n, sum(d) / n, sum(z) / n
    cy = [v - my for v in y]
    cd = [v - md for v in d]
    cz = [v - mz for v in z]

    def dot(a, b):
        return sum(p * q for p, q in zip(a, b))

    return Moments(n, dot(cz, cz), dot(cz, cd), dot(cz, cy), dot(cd, cd), dot(cy, cd), dot(cy, cy))


def wald_estimate(y: Sequence, d: Sequence, z: Sequence) -> object:
    """(mean y | z = 1 - mean y | z = 0) / (mean d | z = 1 - mean d | z = 0) for a 0/1 instrument."""
    g1 = [i for i, v in enumerate(z) if v == 1]
    g0 = [i for i, v in enumerate(z) if v == 0]
    if not g1 or not g0 or len(g1) + len(g0) != len(z):
        raise ValueError("z must be 0/1 with both values present")
    dy = sum(y[i] for i in g1) / len(g1) - sum(y[i] for i in g0) / len(g0)
    dd = sum(d[i] for i in g1) / len(g1) - sum(d[i] for i in g0) / len(g0)
    if dd == 0:
        raise ZeroDivisionError("the instrument does not move the treatment in this sample")
    return dy / dd


def ar_statistic(m: Moments, b0) -> object:
    """F statistic of the slope of z in the regression of y - b0 d on (1, z)."""
    c = m.szy - b0 * m.szd
    sww = m.syy - 2 * b0 * m.syd + b0 * b0 * m.sdd
    resid = m.szz * sww - c * c  # szz times the residual sum of squares
    if resid == 0:
        return math.inf
    return (m.n - 2) * c * c / resid


@lru_cache(maxsize=256)
def _f_crit(alpha: float, df: int) -> float:
    return f_ppf(1 - alpha, 1, df)


def ar_set(m: Moments, alpha: float = 0.05) -> tuple:
    """{b0 : AR(b0) <= F_(1, n-2, 1-alpha)} as one of
    ("interval", lo, hi), ("complement", lo, hi) meaning (-inf, lo] and [hi, inf),
    ("ray_up", lo) meaning [lo, inf), ("ray_down", hi) meaning (-inf, hi], ("line",), ("empty",)."""
    q = _f_crit(alpha, m.n - 2)
    kappa = q / (m.n - 2 + q)
    szz, szd, szy, sdd, syd, syy = (float(v) for v in m[1:])
    # AR(b) <= q  <=>  (szy - b szd)^2 - kappa szz (syy - 2 b syd + b^2 sdd) <= 0
    a = szd * szd - kappa * szz * sdd
    b = -2 * szy * szd + 2 * kappa * szz * syd
    c = szy * szy - kappa * szz * syy
    if a == 0:
        if b > 0:
            return ("ray_down", -c / b)
        if b < 0:
            return ("ray_up", -c / b)
        return ("line",) if c <= 0 else ("empty",)
    disc = b * b - 4 * a * c
    if a > 0:
        if disc < 0:
            return ("empty",)
        r = math.sqrt(disc)
        lo, hi = sorted(((-b - r) / (2 * a), (-b + r) / (2 * a)))
        return ("interval", lo, hi)
    if disc <= 0:
        return ("line",)
    r = math.sqrt(disc)
    lo, hi = sorted(((-b - r) / (2 * a), (-b + r) / (2 * a)))
    return ("complement", lo, hi)


def in_set(s: tuple, v: float) -> bool:
    kind = s[0]
    if kind == "interval":
        return s[1] <= v <= s[2]
    if kind == "complement":
        return v <= s[1] or v >= s[2]
    if kind == "ray_up":
        return v >= s[1]
    if kind == "ray_down":
        return v <= s[1]
    return kind == "line"


def iv_analysis(y: Sequence, d: Sequence, z: Sequence, alpha: float = 0.05) -> IVResult:
    """The IV estimate, its standard error, the first-stage F and the AR set. Cost: Theta(n)."""
    m = moments(y, d, z)
    if m.szz == 0:
        raise ValueError("the instrument is constant")
    f1 = (m.n - 2) * m.szd * m.szd / (m.szz * m.sdd - m.szd * m.szd) if m.szz * m.sdd != m.szd * m.szd else math.inf  # @line L1
    rf = m.szy / m.szz  # @line L2
    if m.szd == 0:
        raise ZeroDivisionError("the instrument is uncorrelated with the treatment in this sample")
    beta = rf / (m.szd / m.szz)  # @line L3
    n = m.n
    alpha_hat = sum(y) / n - beta * sum(d) / n
    rss = m.syy - 2 * beta * m.syd + beta * beta * m.sdd  # @line L4
    se = math.sqrt(float(rss / (n - 2)) * float(m.szz)) / abs(float(m.szd))
    s = ar_set(m, alpha)  # @line L5
    return IVResult(beta, alpha_hat, se, f1, s)  # @line L6


def wald_interval(res: IVResult, n: int, alpha: float = 0.05) -> tuple[float, float]:
    """beta +- t_(n-2, 1-alpha/2) se, valid only with a strong instrument."""
    t = t_ppf(1 - alpha / 2, n - 2)
    return float(res.beta) - t * res.se, float(res.beta) + t * res.se


def ar_pvalue(m: Moments, b0) -> float:
    return f_sf(float(ar_statistic(m, b0)), 1, m.n - 2)
stdist.py 238 lines
# 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)
test_instrumental_variables_estimation.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instrumental-variables-estimation/. The authors are listed in prov/CM6TM9.jsonl.

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

import pytest

from instrumental_variables_estimation import (
    ar_pvalue,
    ar_set,
    ar_statistic,
    in_set,
    iv_analysis,
    moments,
    wald_estimate,
    wald_interval,
)
from stdist import f_ppf


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]
    yf, df, zf = ([Fr(v) for v in a] for a in (y, d, z))
    r = iv_analysis(yf, df, zf)
    assert r.beta == Fr(5, 2) == wald_estimate(yf, df, zf)
    assert r.alpha == Fr(19, 8)
    assert r.first_stage_f == Fr(2)
    m = moments(yf, df, zf)
    assert ar_statistic(m, Fr(5, 2)) == 0
    assert ar_statistic(m, 0) == Fr(75, 91)
    assert r.ar_set == ("line",)  # F = 2 is below F(1, 6, 0.95) = 5.99: the set is unbounded
    kind, lo, hi = ar_set(m, 0.30)  # F(1, 6, 0.70) = 1.27 < 2: bounded
    assert kind == "interval" and abs(lo + 2.5129) < 1e-4 and abs(hi - 3.9082) < 1e-4


def test_wald_equals_covariance_ratio_exactly():
    rng = random.Random(1)
    done = 0
    while done < 300:
        n = rng.randint(4, 15)
        z = [Fr(rng.randint(0, 1)) for _ in range(n)]
        d = [Fr(rng.randint(0, 3)) for _ in range(n)]
        y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
        try:
            w = wald_estimate(y, d, z)
        except (ValueError, ZeroDivisionError):
            continue
        m = moments(y, d, z)
        assert w == m.szy / m.szd == iv_analysis(y, d, z).beta
        done += 1


def test_ar_set_matches_grid_inversion():
    """The closed-form set agrees with testing every grid point, away from its boundary."""
    rng = random.Random(2)
    kinds = set()
    for trial in range(150):
        n = rng.randint(8, 40)
        pi = rng.choice([0.0, 0.1, 0.3, 1.0, 3.0])
        z = [rng.gauss(0, 1) for _ in range(n)]
        d = [pi * a + rng.gauss(0, 1) for a in z]
        y = [0.5 * b + rng.gauss(0, 1) for b in d]
        m = moments(y, d, z)
        s = ar_set(m, 0.05)
        kinds.add(s[0])
        q = f_ppf(0.95, 1, n - 2)
        ends = [v for v in s[1:]]
        for i in range(-400, 401):
            b0 = i / 20
            if any(abs(b0 - e) < 1e-6 for e in ends):
                continue
            assert (ar_statistic(m, b0) <= q) == in_set(s, b0)
    assert {"interval", "complement", "line"} <= kinds


def test_ar_set_is_bounded_iff_the_first_stage_rejects():
    rng = random.Random(3)
    for _ in range(300):
        n = rng.randint(6, 30)
        pi = rng.choice([0.0, 0.2, 0.5, 2.0])
        z = [rng.gauss(0, 1) for _ in range(n)]
        d = [pi * a + rng.gauss(0, 1) for a in z]
        y = [b + rng.gauss(0, 1) for b in d]
        r = iv_analysis(y, d, z)
        q = f_ppf(0.95, 1, n - 2)
        if abs(r.first_stage_f - q) < 1e-9:
            continue
        assert (r.ar_set[0] == "interval") == (r.first_stage_f > q)
        if r.ar_set[0] == "interval":
            assert r.ar_set[1] <= r.beta <= r.ar_set[2]


def weak_sample(rng, n, pi, rho, beta=1.0):
    z = [rng.gauss(0, 1) for _ in range(n)]
    e = [rng.gauss(0, 1) for _ in range(n)]
    v = [rho * a + math.sqrt(1 - rho * rho) * rng.gauss(0, 1) for a in e]
    d = [pi * a + b for a, b in zip(z, v)]
    y = [beta * a + b for a, b in zip(d, e)]
    return y, d, z


def test_ar_size_under_a_weak_instrument():
    """n = 50, first-stage coefficient 0.05, corr(e, v) = 0.8, r = 2000 (seed 2026). The AR test is exact,
    so its rejection rate is within 0.05 +- 4 SE (SE = 0.0049). The Wald t test is not: it rejects in more
    than 9% of the samples (0.05 + 8 SE; the measured rate is 0.121)."""
    rng = random.Random(2026)
    r, ar_rej, t_rej = 2000, 0, 0
    q = f_ppf(0.95, 1, 48)
    for _ in range(r):
        y, d, z = weak_sample(rng, 50, 0.05, 0.8)
        m = moments(y, d, z)
        ar_rej += ar_statistic(m, 1.0) > q
        res = iv_analysis(y, d, z, alpha=0.05)
        t_rej += abs(res.beta - 1.0) > math.sqrt(q) * res.se  # sqrt(F(1, 48)) is the t(48) critical value
    se = math.sqrt(0.05 * 0.95 / r)
    assert abs(ar_rej / r - 0.05) < 4 * se
    assert t_rej / r > 0.09
    lo, hi = wald_interval(res, 50)
    assert abs(hi - lo - 2 * math.sqrt(q) * res.se) < 1e-9


def test_iv_consistent_where_ols_is_biased():
    """Strong instrument (coefficient 1), corr(e, v) = 0.5, n = 400, r = 300 (seed 5). OLS tends to
    1 + 0.5/2 = 1.25. IV has no finite mean with one instrument, so the median is checked: within
    4 SE + 0.01 of 1, with SE = 1.2533 SD / sqrt(r)."""
    rng = random.Random(5)
    iv, ols = [], []
    for _ in range(300):
        y, d, z = weak_sample(rng, 400, 1.0, 0.5)
        iv.append(iv_analysis(y, d, z).beta)
        m = moments(y, d, z)
        ols.append(m.syd / m.sdd)
    se = 1.2533 * statistics.stdev(iv) / math.sqrt(300)
    assert abs(statistics.median(iv) - 1) < 4 * se + 0.01
    assert abs(statistics.mean(ols) - 1.25) < 0.02


def test_input_checks():
    with pytest.raises(ValueError):
        wald_estimate([1, 2], [0, 1], [2, 0])
    with pytest.raises(ZeroDivisionError):
        wald_estimate([1, 2, 3, 4], [1, 0, 1, 0], [0, 0, 1, 1])
    with pytest.raises(ValueError):
        iv_analysis([1, 2, 3], [1, 2, 3], [1, 1, 1])

Exercises

  1. Show that for a binary ZZ with p=Pr⁡[Z=1]p = \Pr[Z = 1], Cov⁡(Z,V)=p(1−p)(E[V∣Z=1]−E[V∣Z=0])\operatorname{Cov}(Z, V) = p(1 - p)(\mathbb{E}[V \mid Z = 1] - \mathbb{E}[V \mid Z = 0]), and conclude that the covariance ratio is the Wald ratio.
  2. In a trial, 40% of those assigned to treatment take it and 5% of those assigned to control get it anyway. The mean outcome is 12.0 in the assigned group and 11.3 in the control group. What is the ratio estimate, and what does it estimate?
  3. Suppose ZZ has a direct effect γ\gamma on YY, so Y=α+βD+γZ+εY = \alpha + \beta D + \gamma Z + \varepsilon. Show that the ratio tends to β+γVar⁡(Z)/Cov⁡(Z,D)\beta + \gamma\operatorname{Var}(Z)/\operatorname{Cov}(Z, D), and explain why a weak instrument makes a small γ\gamma dangerous.
  4. Show that AR(b)→F1\mathrm{AR}(b) \to F_1 as b→±∞b \to \pm\infty.
  5. Use the code to find the smallest α\alpha at which the AR set of the worked example is bounded. (It is the p-value of the first-stage FF test, Pr⁡[F1,6>2]≈0.207\Pr[F_{1, 6} > 2] \approx 0.207.)

References

  1. Philip G. Wright, The Tariff on Animal and Vegetable Oils, Macmillan, 1928, Appendix B (the first instrumental variables estimates of supply and demand elasticities; cited from Stock and Trebbi 2003)
  2. James H. Stock and Francesco Trebbi, Retrospectives, who invented instrumental variable regression?, Journal of Economic Perspectives 17(3), 2003, pp. 177 to 194 (the history of Wright's Appendix B and of the method)
  3. T. W. Anderson and Herman Rubin, Estimation of the parameters of a single equation in a complete system of stochastic equations, The Annals of Mathematical Statistics 20(1), 1949, pp. 46 to 63 (the limited information estimator and the test of the coefficients that does not depend on the strength of the 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, size distortion of Wald tests)
  5. Joshua D. Angrist and Alan B. Krueger, Does compulsory school attendance affect schooling and earnings?, The Quarterly Journal of Economics 106(4), 1991, pp. 979 to 1014 (quarter of birth as an instrument for schooling)
  6. Guido W. Imbens and Joshua D. Angrist, Identification and estimation of local average treatment effects, Econometrica 62(2), 1994, the article starting on p. 467 (what the ratio identifies when effects vary)
  7. Joshua D. Angrist and Jörn-Steffen Pischke, Mostly Harmless Econometrics, Princeton University Press, 2009, Chapter 4, Instrumental Variables in Action (general locator, the section numbers were not checked)

Where this leads

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises