Algorithm Search⌘K

Techniqueadvanced

Generalized method of moments

Also called Hansen's generalized method of moments.

Hansen's estimator that minimizes a weighted quadratic form in sample moment conditions. With the optimal weight matrix it is efficient among such estimators.

The generalized method of moments (GMM) estimates a parameter θ∈Rk\theta \in \mathbb{R}^k from q≥kq \ge k moment conditions E[g(X,θ0)]=0\mathbb{E}[g(X, \theta_0)] = 0. It chooses the θ\theta that makes the sample average gˉ(θ)\bar g(\theta) as close to zero as possible in the quadratic form gˉ(θ)TWgˉ(θ)\bar g(\theta)^{\mathsf T} W \bar g(\theta). With q=kq = k it is the method of moments; with more conditions than parameters it combines them, and the weight W=S−1W = S^{-1}, the inverse covariance of the moments, gives the smallest asymptotic variance. The surplus conditions also give a test of the model, Hansen's JJ test. Linear instrumental variables, two-stage least squares, ordinary least squares and maximum likelihood are special cases.

In plain words

A model often tells you several averages that should be zero at the true parameter, more averages than there are unknowns. With real data you cannot make all of them zero at once. So you choose the parameter that makes them as small as possible together.

How much each average counts is a choice. A good rule gives less weight to averages that are noisy and accounts for averages that move together. With that rule the answer is as precise as these averages permit.

The leftover misfit is useful too. If the model is right, the averages should be close to zero at the best parameter, and the size of the misfit has a known reference law. A misfit that is too large says that some of the conditions are false.

When it applies

  • The data X1,…,XnX_1, \ldots, X_n are iid, or stationary and ergodic (Hansen's setting), and g(x,θ)∈Rqg(x, \theta) \in \mathbb{R}^q is known, with E[g(X,θ0)]=0\mathbb{E}[g(X, \theta_0)] = 0 at the true θ0\theta_0.
  • Identification: E[g(X,θ)]=0\mathbb{E}[g(X, \theta)] = 0 holds only at θ=θ0\theta = \theta_0, and the q×kq \times k Jacobian G=E[∂g(X,θ0)/∂θ]G = \mathbb{E}[\partial g(X, \theta_0)/\partial\theta] has rank kk. Then q≥kq \ge k is necessary.
  • The moment covariance S=Var⁡[g(X,θ0)]S = \operatorname{Var}[g(X, \theta_0)] is finite and nonsingular. For dependent data, SS is the long-run covariance ∑hCov⁡(gt,gt+h)\sum_{h} \operatorname{Cov}(g_t, g_{t+h}).
  • The model need not give a full likelihood. Only the conditions are assumed, which is why the method is common in economics.

The template

  1. GMM(x_1, ..., x_n, θ_0)
  2. 1choose MOMENT-FUNCTION g(x, θ) ∈ R^q, q ≥ k ▷ hole: E g(X, θ_0) = 0 at the truth
  3. 2ḡ(θ) ← (1/n) Σ_i g(x_i, θ)
  4. 3W ← FIRST-WEIGHT ▷ hole: identity, or (Z'Z/n)^-1 for IV
  5. 4θ_1 ← MINIMIZE ḡ(θ)' W ḡ(θ) from θ_0 ▷ hole: closed form or Gauss-Newton
  6. 5S ← (1/n) Σ_i (g(x_i, θ_1) - ḡ(θ_1)) (g(x_i, θ_1) - ḡ(θ_1))' ▷ hole: long-run S for time series
  7. 6θ̂ ← MINIMIZE ḡ(θ)' S^-1 ḡ(θ) from θ_1
  8. 7G ← ∂ḡ/∂θ at θ̂
  9. 8V ← (G' S^-1 G)^-1 / n ▷ estimated covariance of θ̂
  10. 9J ← n ḡ(θ̂)' S^-1 ḡ(θ̂) ▷ compare with chi-squared, q - k df
  11. 10return θ̂, V, J

The holes are the moment conditions (line L1), the first weight (line L3), the minimizer (lines L4 and L6) and the estimate of SS (line L5). The estimate in line L5 is centered and has divisor nn; the uncentered version 1n∑igigiT\frac1n\sum_i g_i g_i^{\mathsf T} has the same limit when the conditions hold. For moments that are linear in θ\theta, each minimization has a closed form. Otherwise Gauss-Newton steps δ=−(GTWG)−1GTWgˉ\delta = -(G^{\mathsf T} W G)^{-1} G^{\mathsf T} W \bar g with step halving work well, and for linear moments they reach the minimum in one step.

Why it is consistent. By a uniform law of large numbers, gˉ(θ)→E[g(X,θ)]\bar g(\theta) \to \mathbb{E}[g(X, \theta)] in probability, uniformly on a compact Θ\Theta, under a dominance condition. So the objective converges to E[g]TW E[g]\mathbb{E}[g]^{\mathsf T} W \,\mathbb{E}[g], which is zero only at θ0\theta_0 by identification. The minimizer of a uniformly convergent objective converges to the unique minimizer of the limit, so θ^→θ0\hat\theta \to \theta_0 in probability. This is proved (Hansen 1982; Hayashi, Chapter 7) for any fixed positive definite WW and for an estimated WW that converges to one.

The asymptotic law. The first-order condition is Gn(θ^)TWgˉ(θ^)=0G_n(\hat\theta)^{\mathsf T} W \bar g(\hat\theta) = 0 with Gn=∂gˉ/∂θG_n = \partial\bar g/\partial\theta. Expand gˉ(θ^)=gˉ(θ0)+Gn(θ~)(θ^−θ0)\bar g(\hat\theta) = \bar g(\theta_0) + G_n(\tilde\theta)(\hat\theta - \theta_0) and solve:

n(θ^−θ0)=−(GnTWGn)−1GnTWn gˉ(θ0)+op(1).\sqrt n(\hat\theta - \theta_0) = -(G_n^{\mathsf T} W G_n)^{-1} G_n^{\mathsf T} W \sqrt n\, \bar g(\theta_0) + o_p(1).

The central limit theorem gives n gˉ(θ0)→N(0,S)\sqrt n\,\bar g(\theta_0) \to N(0, S) in distribution, and Slutsky's theorem gives

n(θ^−θ0)→N(0,  (GTWG)−1GTWSWG(GTWG)−1)in distribution.\sqrt n(\hat\theta - \theta_0) \to N\big(0,\; (G^{\mathsf T}WG)^{-1} G^{\mathsf T} W S W G (G^{\mathsf T}WG)^{-1}\big) \quad \text{in distribution}.

This sandwich has the same form as for an M-estimator.

Why W=S−1W = S^{-1} is optimal. Write A=(GTWG)−1GTWA = (G^{\mathsf T}WG)^{-1}G^{\mathsf T}W and B=(GTS−1G)−1GTS−1B = (G^{\mathsf T}S^{-1}G)^{-1}G^{\mathsf T}S^{-1}. Both satisfy AG=BG=IkAG = BG = I_k, so ASBT=AG(GTS−1G)−1=(GTS−1G)−1=BSBTASB^{\mathsf T} = AG(G^{\mathsf T}S^{-1}G)^{-1} = (G^{\mathsf T}S^{-1}G)^{-1} = BSB^{\mathsf T}. Hence

ASAT−BSBT=(A−B) S (A−B)T,ASA^{\mathsf T} - BSB^{\mathsf T} = (A - B)\,S\,(A - B)^{\mathsf T},

which is positive semidefinite. The left side is the sandwich minus (GTS−1G)−1(G^{\mathsf T}S^{-1}G)^{-1}, so no weight does better than S−1S^{-1}, which gives the variance (GTS−1G)−1(G^{\mathsf T}S^{-1}G)^{-1} of line L8. This is proved. Line L5 needs a first, consistent estimate because SS depends on θ0\theta_0; replacing SS by a consistent estimate does not change the limit.

The JJ test. If all qq conditions hold and q>kq > k, then J=n gˉ(θ^)TS^−1gˉ(θ^)→χq−k2J = n\,\bar g(\hat\theta)^{\mathsf T} \hat S^{-1} \bar g(\hat\theta) \to \chi^2_{q-k} in distribution (Hansen 1982). The kk degrees of freedom are used to fit θ\theta. A large JJ says that some condition is false, but not which one. With q=kq = k, J=0J = 0 always and there is nothing to test.

Classic examples

The method of moments. With q=kq = k and a solution of gˉ(θ)=0\bar g(\theta) = 0, the objective is zero there for every WW, so GMM is the method of moments and the weight does not matter. For g(x,θ)=(x−μ,  x2−σ2−μ2)g(x, \theta) = (x - \mu,\; x^2 - \sigma^2 - \mu^2) it gives xˉ\bar x and the variance with divisor nn. The covariance (GTS−1G)−1=G−1SG−T(G^{\mathsf T}S^{-1}G)^{-1} = G^{-1}SG^{-\mathsf T} is the delta method result.

Linear instrumental variables. For y=xTβ+uy = x^{\mathsf T}\beta + u with instruments z∈Rqz \in \mathbb{R}^q and E[zu]=0\mathbb{E}[z u] = 0, take g=z(y−xTβ)g = z(y - x^{\mathsf T}\beta). The conditions are linear in β\beta, and

β^(W)=(XTZWZTX)−1XTZWZTy.\hat\beta(W) = (X^{\mathsf T}Z W Z^{\mathsf T}X)^{-1} X^{\mathsf T}Z W Z^{\mathsf T}y.

With W=(ZTZ/n)−1W = (Z^{\mathsf T}Z/n)^{-1} this is two-stage least squares; with z=xz = x it is ordinary least squares. Under heteroscedastic errors, the second step with S^=1n∑iu^i2ziziT\hat S = \frac1n\sum_i \hat u_i^2 z_i z_i^{\mathsf T} (centered as in line L5) is more efficient than 2SLS, and the estimate VV of line L8 is robust in the same way as heteroscedasticity-consistent standard errors. A small exact case, with x=(1,x1)x = (1, x_1) and z=(1,z1,z2)z = (1, z_1, z_2):

yy 3 6 4 9 2 8 5 11 7
x1x_1 1 2 1 4 0 3 2 5 3
z1z_1 0 1 1 2 0 2 0 3 1
z2z_2 1 1 0 1 0 0 2 2 1

OLS gives (1.8333,1.8333)(1.8333, 1.8333). The first step with W=(ZTZ/n)−1W = (Z^{\mathsf T}Z/n)^{-1} gives (863/486,301/162)≈(1.7757,1.8580)(863/486, 301/162) \approx (1.7757, 1.8580), the same as the two literal stages of 2SLS, in exact arithmetic. The second step gives (1.9434,1.7874)(1.9434, 1.7874) with standard errors 0.2280.228 and 0.0500.050, and J=5.546J = 5.546 on 1 degree of freedom, p=0.019p = 0.019. With n=9n = 9 the chi-squared reference is a rough guide only.

Poisson with two conditions. For Poisson(λ)(\lambda) counts, EX=λ\mathbb{E}X = \lambda and EX2=λ+λ2\mathbb{E}X^2 = \lambda + \lambda^2, so g=(x−λ,  x2−λ−λ2)g = (x - \lambda,\; x^2 - \lambda - \lambda^2) with q=2q = 2, k=1k = 1. The population quantities are G=−(1,1+2λ)TG = -(1, 1 + 2\lambda)^{\mathsf T} and SS with entries λ\lambda, 2λ2+λ2\lambda^2 + \lambda and 4λ3+6λ2+λ4\lambda^3 + 6\lambda^2 + \lambda. The first column of SS is Se1=λ(1,1+2λ)T=−λGS e_1 = \lambda(1, 1 + 2\lambda)^{\mathsf T} = -\lambda G, so S−1G=−e1/λS^{-1}G = -e_1/\lambda and (GTS−1G)−1=λ(G^{\mathsf T}S^{-1}G)^{-1} = \lambda. Efficient GMM reaches the Cramér-Rao bound λ/n\lambda/n of Xˉ\bar X, and the second condition adds no precision but makes the JJ test a test of equidispersion. For negative binomial counts with mean 3 and variance 6 (a Poisson law with a Gamma(3, 1) mean), the measured rejection rate of JJ at level 0.05 was 0.594 for n=50n = 50 (500 data sets) and 1.0 for n=200n = 200 (500 data sets).

Euler equations. Hansen and Singleton (1982) estimated the discount factor β\beta and risk aversion γ\gamma of a consumer from E[β(ct+1/ct)−γrt+1−1∣It]=0\mathbb{E}[\beta (c_{t+1}/c_t)^{-\gamma} r_{t+1} - 1 \mid \mathcal I_t] = 0. Any variable ztz_t known at time tt gives an unconditional condition E[(β(ct+1/ct)−γrt+1−1)zt]=0\mathbb{E}[(\beta (c_{t+1}/c_t)^{-\gamma} r_{t+1} - 1) z_t] = 0, so lagged variables serve as instruments and there is no need to model the law of consumption.

Estimating equations. With q=kq = k, the conditions 1n∑iψ(xi,θ)=0\frac1n\sum_i \psi(x_i, \theta) = 0 of an M-estimator, of generalized estimating equations and the score equations of maximum likelihood are exactly identified GMM, and the GMM sandwich is their robust covariance.

Variations

  • Iterated GMM. Repeat lines L5 and L6 until θ^\hat\theta stops changing. The limit law is the same as for two steps.
  • Continuously updated GMM. Minimize gˉ(θ)TS^(θ)−1gˉ(θ)\bar g(\theta)^{\mathsf T} \hat S(\theta)^{-1} \bar g(\theta) with SS recomputed at each θ\theta (Hansen, Heaton and Yaron, 1996). It does not depend on a first step and is invariant to nonsingular linear transformations of gg.
  • Long-run covariance. For time series, SS in line L5 is a kernel estimate of the long-run covariance, such as the Newey-West estimate, which is positive semidefinite by construction.
  • Generalized empirical likelihood. Empirical likelihood and its relatives reweight the data so that the conditions hold exactly. They have the same first-order limit as efficient GMM and a smaller higher-order bias.
  • Simulated moments. When E[g(X,θ)]\mathbb{E}[g(X, \theta)] has no formula, estimate it by simulation at each θ\theta, with the same random draws for every θ\theta.
  • Orthogonal moments. Moment functions whose derivative with respect to a nuisance part is zero let a machine learning estimate of that part enter without first-order effect, as in double machine learning.

Pitfalls

  • Small-sample bias of the two-step estimate. The estimated weight S^−1\hat S^{-1} is correlated with gˉ\bar g, and this biases the second step (Altonji and Segal, 1996). In the Poisson example with the data (0,0,1,1,2,3,3,5,7,8)(0, 0, 1, 1, 2, 3, 3, 5, 7, 8), where xˉ=3\bar x = 3 and the variance with divisor nn is 7.27.2, the first step with W=IW = I gave 3.5483.548 and the second step gave 1.8021.802, with J=2.98J = 2.98. The sample mean, which is the efficient estimate under the model, is 3. With few observations, report the first step too.
  • The JJ test over-rejects at moderate nn. Measured for the Poisson example with true Poisson data, nominal level 0.05: for λ=3\lambda = 3 the rejection rate was 0.106 at n=50n = 50 and 0.074 at n=200n = 200 (1000 data sets each), and 0.070 at n=1000n = 1000 (300 data sets). For λ=1\lambda = 1 the rates were 0.088, 0.074 and 0.043. The chi-squared limit is proved; its accuracy at a given nn is only measured.
  • Weak identification. When GG is close to rank deficient, as with instruments that hardly move xx, the normal limit is a poor guide, θ^\hat\theta is biased toward OLS and Wald intervals undercover.
  • Too many conditions. Many weak conditions make S^\hat S hard to estimate and increase the bias. More conditions can only help in the limit; in finite samples they can hurt.
  • Scaling with a fixed weight. With W=IW = I, the estimate changes when one condition is multiplied by a constant. The efficient objective gˉTS^−1gˉ\bar g^{\mathsf T}\hat S^{-1}\bar g is invariant to g↦Agg \mapsto Ag for a fixed θ\theta and nonsingular AA, but two-step estimates still change through the first step.
  • A small JJ does not confirm the model. JJ tests only the surplus conditions. If the kk conditions used for identification are false, θ^\hat\theta is inconsistent and JJ can still be small.
  • Singular S^\hat S. Redundant conditions, such as the same instrument twice, make S^\hat S singular. Remove them before line L5.

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.

generalized_method_of_moments.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-method-of-moments/. The authors are listed in prov/A39F7K.jsonl.

from collections.abc import Callable, Sequence
from typing import Any, NamedTuple

from stdist import chi2_sf

Vector = list
Matrix = list
MomentFn = Callable[[Any, Vector], Vector]
JacobianFn = Callable[[Any, Vector], Matrix]


def solve(a: Matrix, b: Vector) -> Vector:
    """Solve a x = b by Gaussian elimination with partial pivoting.

    Works for float and Fraction entries. Precondition: a is square and
    nonsingular. Cost: O(k^3) for a k x k matrix.
    """
    k = len(a)
    m = [list(row) + [b[i]] for i, row in enumerate(a)]
    for c in range(k):
        p = max(range(c, k), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ZeroDivisionError("singular matrix")
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, k):
            f = m[r][c] / m[c][c]
            if f != 0:
                for j in range(c, k + 1):
                    m[r][j] = m[r][j] - f * m[c][j]
    x = [0] * k
    for r in range(k - 1, -1, -1):
        s = m[r][k]
        for j in range(r + 1, k):
            s = s - m[r][j] * x[j]
        x[r] = s / m[r][r]
    return x


def inverse(a: Matrix) -> Matrix:
    """Return the inverse of a nonsingular square matrix, column by column."""
    k = len(a)
    cols = [solve(a, [1 if i == j else 0 for i in range(k)]) for j in range(k)]
    return [[cols[j][i] for j in range(k)] for i in range(k)]


def _matmul(a: Matrix, b: Matrix) -> Matrix:
    return [[sum(a[i][t] * b[t][j] for t in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]


def _t(a: Matrix) -> Matrix:
    return [list(col) for col in zip(*a)]


def _matvec(a: Matrix, v: Vector) -> Vector:
    return [sum(r[j] * v[j] for j in range(len(v))) for r in a]


def sample_moments(g: MomentFn, data: Sequence, theta: Vector) -> tuple[Vector, list]:
    """Return g-bar(theta) = (1/n) sum g(x_i, theta) and the rows g(x_i, theta). Cost O(n q)."""
    rows = [g(x, theta) for x in data]
    n = len(rows)
    q = len(rows[0])
    return [sum(r[j] for r in rows) / n for j in range(q)], rows  # @line L2


def mean_jacobian(dg: JacobianFn | None, g: MomentFn, data: Sequence, theta: Vector, h: float = 1e-6) -> Matrix:
    """Return G = d g-bar / d theta (q x k). Central differences when dg is None."""
    n = len(data)
    if dg is not None:
        mats = [dg(x, theta) for x in data]
        q, k = len(mats[0]), len(mats[0][0])
        return [[sum(m[i][j] for m in mats) / n for j in range(k)] for i in range(q)]
    k = len(theta)
    cols = []
    for j in range(k):
        up = list(theta)
        dn = list(theta)
        up[j] += h
        dn[j] -= h
        gu, _ = sample_moments(g, data, up)
        gd, _ = sample_moments(g, data, dn)
        cols.append([(a - b) / (2 * h) for a, b in zip(gu, gd)])
    return _t(cols)


def moment_covariance(rows: list, gbar: Vector) -> Matrix:
    """Centered S = (1/n) sum (g_i - g-bar)(g_i - g-bar)'. Divisor n. Cost O(n q^2)."""
    n = len(rows)
    q = len(gbar)
    return [[sum((r[i] - gbar[i]) * (r[j] - gbar[j]) for r in rows) / n for j in range(q)] for i in range(q)]


def objective(g: MomentFn, data: Sequence, theta: Vector, w: Matrix) -> float:
    """Q(theta) = g-bar' W g-bar."""
    gb, _ = sample_moments(g, data, theta)
    return sum(gb[i] * w[i][j] * gb[j] for i in range(len(gb)) for j in range(len(gb)))


def minimize_gmm(
    g: MomentFn,
    data: Sequence,
    theta0: Sequence,
    w: Matrix,
    dg: JacobianFn | None = None,
    tol: float = 1e-14,
    max_iter: int = 100,
    min_step: float = 2.0 ** -30,
) -> tuple[Vector, int, bool]:
    """Minimize g-bar' W g-bar by Gauss-Newton steps with step halving.

    W must be symmetric positive definite and G'WG nonsingular. The step is
    delta = -(G'WG)^-1 G'W g-bar. Stops when the decrement -b'delta <= tol.
    For moments linear in theta one exact step reaches the minimum.
    Cost per step: O(n q k) for G plus O(k^3).
    """
    theta = list(theta0)
    for t in range(max_iter):
        gb, _ = sample_moments(g, data, theta)
        big_g = mean_jacobian(dg, g, data, theta)
        gtw = _matmul(_t(big_g), w)
        a = _matmul(gtw, big_g)
        b = _matvec(gtw, gb)
        delta = [-v for v in solve(a, b)]
        dec = -sum(bi * di for bi, di in zip(b, delta))
        if dec <= tol:
            return theta, t, True
        q_old = sum(gb[i] * w[i][j] * gb[j] for i in range(len(gb)) for j in range(len(gb)))
        s = 1
        new = [ti + di for ti, di in zip(theta, delta)]
        q_new = objective(g, data, new, w)
        while q_new > q_old and s > min_step:
            s = s / 2
            new = [ti + s * di for ti, di in zip(theta, delta)]
            q_new = objective(g, data, new, w)
        if q_new > q_old:
            return theta, t, False
        theta = new
    return theta, max_iter, False


def efficient_cov(big_g: Matrix, s: Matrix, n: int) -> Matrix:
    """(G' S^-1 G)^-1 / n, the covariance of efficient GMM."""
    gts = _matmul(_t(big_g), inverse(s))
    v = inverse(_matmul(gts, big_g))
    return [[e / n for e in row] for row in v]


def sandwich_cov(big_g: Matrix, w: Matrix, s: Matrix, n: int) -> Matrix:
    """(G'WG)^-1 G'W S W G (G'WG)^-1 / n, the covariance for a fixed weight W."""
    gtw = _matmul(_t(big_g), w)
    bread = inverse(_matmul(gtw, big_g))
    meat = _matmul(_matmul(gtw, s), _t(gtw))
    v = _matmul(_matmul(bread, meat), bread)
    return [[e / n for e in row] for row in v]


class GMMResult(NamedTuple):
    theta: list        # two-step estimate
    cov: list          # (G' S^-1 G)^-1 / n at theta, S from the first step
    j_stat: float      # n g-bar' S^-1 g-bar at theta
    df: int            # q - k
    p_value: float     # chi-squared(q - k) upper tail of j_stat; 1.0 when df = 0
    first_step: list   # estimate with the first weight
    weight: list       # S^-1, the second-step weight
    converged: bool


def gmm(
    g: MomentFn,
    data: Sequence,
    theta0: Sequence,
    dg: JacobianFn | None = None,
    w1: Matrix | None = None,
    tol: float = 1e-14,
    max_iter: int = 100,
) -> GMMResult:
    """Two-step efficient GMM with Hansen's J test of the overidentifying conditions.

    g(x, theta) returns the q moment functions of one observation, with
    E g(X, theta_0) = 0 at the true theta_0 and q >= k = len(theta0). The data
    are iid. dg(x, theta) is the q x k derivative; None uses central
    differences. w1 is the first-step weight (identity when None).
    S is centered with divisor n. Cost: O(n q (q + k)) per Gauss-Newton step.
    """
    data = list(data)  # @line L1
    n = len(data)
    q = len(g(data[0], list(theta0)))
    k = len(theta0)
    if q < k:
        raise ValueError("need at least as many moment conditions as parameters")
    w = w1 if w1 is not None else [[1 if i == j else 0 for j in range(q)] for i in range(q)]  # @line L3
    th1, _, ok1 = minimize_gmm(g, data, theta0, w, dg, tol, max_iter)  # @line L4
    gb1, rows1 = sample_moments(g, data, th1)
    s = moment_covariance(rows1, gb1)  # @line L5
    w2 = inverse(s)
    th, _, ok2 = minimize_gmm(g, data, th1, w2, dg, tol, max_iter)  # @line L6
    big_g = mean_jacobian(dg, g, data, th)  # @line L7
    cov = efficient_cov(big_g, s, n)  # @line L8
    gb, _ = sample_moments(g, data, th)
    j = n * sum(gb[a] * w2[a][b] * gb[b] for a in range(q) for b in range(q))  # @line L9
    df = q - k
    p = chi2_sf(float(j), df) if df > 0 else 1.0
    return GMMResult(th, cov, j, df, p, th1, w2, ok1 and ok2)  # @line L10
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_generalized_method_of_moments.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-method-of-moments/. The authors are listed in prov/A39F7K.jsonl.

import math
import random
from fractions import Fraction

from generalized_method_of_moments import (
    efficient_cov,
    gmm,
    inverse,
    mean_jacobian,
    objective,
    sandwich_cov,
    solve,
)


def poisson(rng: random.Random, m: float) -> int:
    u, k, pk = rng.random(), 0, math.exp(-m)
    cum = pk
    while u > cum:
        k += 1
        pk *= m / k
        cum += pk
    return k


def pois_g(x, t):
    lam = t[0]
    return [x - lam, x * x - lam - lam * lam]


def pois_dg(x, t):
    return [[-1], [-1 - 2 * t[0]]]


def ols(x, y):
    p = len(x[0])
    xtx = [[sum(r[i] * r[j] for r in x) for j in range(p)] for i in range(p)]
    xty = [sum(r[i] * yi for r, yi in zip(x, y)) for i in range(p)]
    return solve(xtx, xty)


def test_exactly_identified_is_method_of_moments():
    rng = random.Random(1)
    xs = [rng.gauss(5, 2) for _ in range(60)]

    def g(x, t):
        return [x - t[0], x * x - t[1] - t[0] * t[0]]

    def dg(x, t):
        return [[-1.0, 0.0], [-2.0 * t[0], -1.0]]

    res = gmm(g, xs, [0.0, 1.0], dg)
    n = len(xs)
    mean = sum(xs) / n
    var_n = sum((x - mean) ** 2 for x in xs) / n  # divisor n
    assert abs(res.theta[0] - mean) < 1e-10 and abs(res.theta[1] - var_n) < 1e-9
    assert res.df == 0 and res.p_value == 1.0 and res.j_stat < 1e-15
    assert res.converged


def iv_data():
    # y = 1 + 2 x + u, x endogenous, two instruments plus the constant
    rows = [
        (3, 1, 0, 1), (6, 2, 1, 1), (4, 1, 1, 0), (9, 4, 2, 1),
        (2, 0, 0, 0), (8, 3, 2, 0), (5, 2, 0, 2), (11, 5, 3, 2), (7, 3, 1, 1),
    ]
    y = [Fraction(r[0]) for r in rows]
    x = [[Fraction(1), Fraction(r[1])] for r in rows]
    z = [[Fraction(1), Fraction(r[2]), Fraction(r[3])] for r in rows]
    return y, x, z


def test_linear_iv_first_step_is_two_stage_least_squares_exact():
    y, x, z = iv_data()
    n = len(y)
    data = list(zip(y, x, z))

    def g(d, b):
        yi, xi, zi = d
        e = yi - xi[0] * b[0] - xi[1] * b[1]
        return [zj * e for zj in zi]

    def dg(d, b):
        _, xi, zi = d
        return [[-zj * xk for xk in xi] for zj in zi]

    zz = [[sum(r[i] * r[j] for r in z) / n for j in range(3)] for i in range(3)]
    res = gmm(g, data, [Fraction(0), Fraction(0)], dg, w1=inverse(zz), tol=0)
    # reference: the two literal stages
    xhat_cols = []
    for col in range(2):
        c = ols(z, [xi[col] for xi in x])
        xhat_cols.append([sum(zi[j] * c[j] for j in range(3)) for zi in z])
    xhat = [list(r) for r in zip(*xhat_cols)]
    assert res.first_step == ols(xhat, y)
    # second step: closed form (X'Z S^-1 Z'X)^-1 X'Z S^-1 Z'y with S from the first step
    b1 = res.first_step
    rows = [[zj * (yi - xi[0] * b1[0] - xi[1] * b1[1]) for zj in zi] for yi, xi, zi in data]
    gb = [sum(r[j] for r in rows) / n for j in range(3)]
    s = [[sum((r[i] - gb[i]) * (r[j] - gb[j]) for r in rows) / n for j in range(3)] for i in range(3)]
    si = inverse(s)
    xz = [[sum(xi[a] * zi[j] for xi, zi in zip(x, z)) for j in range(3)] for a in range(2)]
    zy = [sum(zi[j] * yi for zi, yi in zip(z, y)) for j in range(3)]
    m = [[sum(xz[a][i] * si[i][j] * xz[b][j] for i in range(3) for j in range(3)) for b in range(2)] for a in range(2)]
    r = [sum(xz[a][i] * si[i][j] * zy[j] for i in range(3) for j in range(3)) for a in range(2)]
    assert res.theta == solve(m, r)
    assert res.df == 1 and res.j_stat >= 0


def test_poisson_two_moments_against_grid_search():
    rng = random.Random(3)
    xs = [poisson(rng, 3.0) for _ in range(150)]
    res = gmm(pois_g, xs, [1.0], pois_dg)
    w = res.weight
    c = sum(xs) / len(xs)
    best = min((objective(pois_g, xs, [c - 1 + i / 10000], w), c - 1 + i / 10000) for i in range(20001))
    h = 1e-4
    best = min((objective(pois_g, xs, [best[1] - h + i * h / 5000], w), best[1] - h + i * h / 5000) for i in range(10001))
    assert abs(res.theta[0] - best[1]) < 1e-7
    assert objective(pois_g, xs, res.theta, w) <= best[0] + 1e-15
    assert abs(res.j_stat - len(xs) * objective(pois_g, xs, res.theta, w)) < 1e-9


def test_numeric_jacobian_matches_analytic():
    rng = random.Random(4)
    xs = [poisson(rng, 2.0) for _ in range(50)]
    a = mean_jacobian(pois_dg, pois_g, xs, [2.3])
    b = mean_jacobian(None, pois_g, xs, [2.3])
    assert all(abs(u[0] - v[0]) < 1e-7 for u, v in zip(a, b))
    r1 = gmm(pois_g, xs, [1.0], pois_dg)
    r2 = gmm(pois_g, xs, [1.0])
    assert abs(r1.theta[0] - r2.theta[0]) < 1e-8


def test_poisson_efficient_variance_is_cramer_rao_exact():
    # Population G and S for the two Poisson moments; efficient GMM reaches lambda / n.
    lam, n = Fraction(5, 2), 40
    big_g = [[Fraction(-1)], [-1 - 2 * lam]]
    s = [[lam, 2 * lam * lam + lam], [2 * lam * lam + lam, 4 * lam ** 3 + 6 * lam * lam + lam]]
    assert efficient_cov(big_g, s, n) == [[lam / n]]
    ident = [[Fraction(1), Fraction(0)], [Fraction(0), Fraction(1)]]
    assert sandwich_cov(big_g, ident, s, n)[0][0] > lam / n
    assert sandwich_cov(big_g, inverse(s), s, n) == [[lam / n]]


def test_sandwich_minus_efficient_is_positive_semidefinite_exact():
    rng = random.Random(5)
    for _ in range(30):
        big_g = [[Fraction(rng.randint(-4, 4)) for _ in range(2)] for _ in range(4)]
        a = [[Fraction(rng.randint(-3, 3)) for _ in range(4)] for _ in range(4)]
        b = [[Fraction(rng.randint(-3, 3)) for _ in range(4)] for _ in range(4)]
        s = [[sum(a[i][t] * a[j][t] for t in range(4)) + (i == j) for j in range(4)] for i in range(4)]
        w = [[sum(b[i][t] * b[j][t] for t in range(4)) + (i == j) for j in range(4)] for i in range(4)]
        gtg = [[sum(big_g[t][i] * big_g[t][j] for t in range(4)) for j in range(2)] for i in range(2)]
        if gtg[0][0] * gtg[1][1] - gtg[0][1] ** 2 == 0:
            continue
        d = sandwich_cov(big_g, w, s, 1)
        e = efficient_cov(big_g, s, 1)
        m = [[d[i][j] - e[i][j] for j in range(2)] for i in range(2)]
        assert m[0][0] >= 0 and m[1][1] >= 0 and m[0][0] * m[1][1] - m[0][1] * m[1][0] >= 0


def test_j_test_size_and_power_measured():
    # Measured, not proved: rejection rate of the J test at level 0.05.
    # At n = 200 the test over-rejects a little (about 0.07 in 1000 runs),
    # so the bound is wide: it checks the chi-squared scale, not exact size.
    r, n = 300, 200
    rng = random.Random(6)
    rej = 0
    for _ in range(r):
        xs = [poisson(rng, 3.0) for _ in range(n)]
        rej += gmm(pois_g, xs, [sum(xs) / n], pois_dg).p_value < 0.05
    size = rej / r
    assert 0.02 < size < 0.05 + 4 * math.sqrt(0.05 * 0.95 / r)
    # negative binomial with mean 3 and variance 6: the second condition fails
    rej = 0
    for _ in range(100):
        xs = [poisson(rng, rng.gammavariate(3.0, 1.0)) for _ in range(n)]
        rej += gmm(pois_g, xs, [sum(xs) / n], pois_dg).p_value < 0.05
    assert rej / 100 > 0.8

Exercises

  1. Show that when q=kq = k and gˉ(θ)=0\bar g(\theta) = 0 has a solution, GMM gives that solution for every positive definite WW, and that J=0J = 0. Answer. The objective is a positive definite quadratic form in gˉ\bar g, so it is at least 0 and equals 0 exactly where gˉ=0\bar g = 0. The minimum is therefore the root, whatever WW is, and J=n⋅0=0J = n \cdot 0 = 0.
  2. For g=z(y−xTβ)g = z(y - x^{\mathsf T}\beta) and W=(ZTZ)−1W = (Z^{\mathsf T}Z)^{-1}, show that the GMM estimate is (XTPZX)−1XTPZy(X^{\mathsf T}P_ZX)^{-1}X^{\mathsf T}P_Zy with PZ=Z(ZTZ)−1ZTP_Z = Z(Z^{\mathsf T}Z)^{-1}Z^{\mathsf T}. Answer. gˉ=ZT(y−Xβ)/n\bar g = Z^{\mathsf T}(y - X\beta)/n. Setting the gradient of (y−Xβ)TZ(ZTZ)−1ZT(y−Xβ)(y - X\beta)^{\mathsf T}Z(Z^{\mathsf T}Z)^{-1}Z^{\mathsf T}(y - X\beta) to zero gives XTPZ(y−Xβ)=0X^{\mathsf T}P_Z(y - X\beta) = 0. The scale 1/n21/n^2 does not change the minimizer.
  3. Prove that the two-step objective gˉ(θ)TS^−1gˉ(θ)\bar g(\theta)^{\mathsf T}\hat S^{-1}\bar g(\theta) is unchanged when gg is replaced by AgAg with AA nonsingular and S^\hat S is computed from the new moments at the same point. Answer. The new S^\hat S is AS^ATA\hat SA^{\mathsf T} and the new gˉ\bar g is AgˉA\bar g, so the form is gˉTATA−TS^−1A−1Agˉ=gˉTS^−1gˉ\bar g^{\mathsf T}A^{\mathsf T}A^{-\mathsf T}\hat S^{-1}A^{-1}A\bar g = \bar g^{\mathsf T}\hat S^{-1}\bar g.
  4. In the Poisson example with W=IW = I, find the asymptotic variance of n(λ^−λ)\sqrt n(\hat\lambda - \lambda) and show it exceeds λ\lambda for every λ>0\lambda > 0. Answer. With c=1+2λc = 1 + 2\lambda, the entries of SS are λ\lambda, λc\lambda c and λc2+2λ2\lambda c^2 + 2\lambda^2. So GTG=1+c2G^{\mathsf T}G = 1 + c^2 and GTSG=λ+2λc2+c2(λc2+2λ2)=λ(1+c2)2+2λ2c2G^{\mathsf T}SG = \lambda + 2\lambda c^2 + c^2(\lambda c^2 + 2\lambda^2) = \lambda(1 + c^2)^2 + 2\lambda^2c^2. The variance is GTSG/(GTG)2=λ+2λ2c2/(1+c2)2>λG^{\mathsf T}SG/(G^{\mathsf T}G)^2 = \lambda + 2\lambda^2c^2/(1 + c^2)^2 > \lambda.
  5. Show that efficient GMM with the kk score functions u(x,θ)u(x, \theta) as conditions has the asymptotic covariance I(θ)−1I(\theta)^{-1}. Answer. q=kq = k, S=Var⁡u=I(θ)S = \operatorname{Var}u = I(\theta) and G=E[∂u/∂θ]=−I(θ)G = \mathbb{E}[\partial u/\partial\theta] = -I(\theta) by the information identity, so (GTS−1G)−1=(II−1I)−1=I(θ)−1(G^{\mathsf T}S^{-1}G)^{-1} = (I I^{-1} I)^{-1} = I(\theta)^{-1}.

References

  1. Lars Peter Hansen, Large sample properties of generalized method of moments estimators, Econometrica 50(4), 1982, pp. 1029 to 1054 (consistency, asymptotic normality, the optimal weight matrix and the test of overidentifying restrictions, for stationary ergodic data)
  2. Lars Peter Hansen and Kenneth J. Singleton, Generalized instrumental variables estimation of nonlinear rational expectations models, Econometrica 50(5), 1982, pp. 1269 to 1286 (the consumption Euler equation estimated from its conditional moment restrictions)
  3. Fumio Hayashi, Econometrics, Princeton University Press, 2000, Chapter 3 (single-equation GMM, efficient weighting, the J statistic) and Chapter 7 (extremum estimators, nonlinear GMM)
  4. Joseph G. Altonji and Lewis M. Segal, Small-sample bias in GMM estimation of covariance structures, Journal of Business and Economic Statistics 14(3), 1996, pp. 353 to 366 (the estimated optimal weight is correlated with the sample moments, which biases two-step estimates)

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)
WritingW2 basic
  • three classic examples