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 from moment conditions . It chooses the that makes the sample average as close to zero as possible in the quadratic form . With it is the method of moments; with more conditions than parameters it combines them, and the weight , the inverse covariance of the moments, gives the smallest asymptotic variance. The surplus conditions also give a test of the model, Hansen's 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 are iid, or stationary and ergodic (Hansen's setting), and is known, with at the true .
- Identification: holds only at , and the Jacobian has rank . Then is necessary.
- The moment covariance is finite and nonsingular. For dependent data, is the long-run covariance .
- The model need not give a full likelihood. Only the conditions are assumed, which is why the method is common in economics.
The template
GMM(x_1, ..., x_n, θ_0)- 1
choose MOMENT-FUNCTION g(x, θ) ∈ R^q, q ≥ k ▷ hole: E g(X, θ_0) = 0 at the truth - 2
ḡ(θ) ← (1/n) Σ_i g(x_i, θ) - 3
W ← FIRST-WEIGHT ▷ hole: identity, or (Z'Z/n)^-1 for IV - 4
θ_1 ← MINIMIZE ḡ(θ)' W ḡ(θ) from θ_0 ▷ hole: closed form or Gauss-Newton - 5
S ← (1/n) Σ_i (g(x_i, θ_1) - ḡ(θ_1)) (g(x_i, θ_1) - ḡ(θ_1))' ▷ hole: long-run S for time series - 6
θ̂ ← MINIMIZE ḡ(θ)' S^-1 ḡ(θ) from θ_1 - 7
G ← ∂ḡ/∂θ at θ̂ - 8
V ← (G' S^-1 G)^-1 / n ▷ estimated covariance of θ̂ - 9
J ← n ḡ(θ̂)' S^-1 ḡ(θ̂) ▷ compare with chi-squared, q - k df - 10
return θ̂, 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 (line L5). The estimate in line L5 is centered and has divisor ; the uncentered version has the same limit when the conditions hold. For moments that are linear in , each minimization has a closed form. Otherwise Gauss-Newton steps 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, in probability, uniformly on a compact , under a dominance condition. So the objective converges to , which is zero only at by identification. The minimizer of a uniformly convergent objective converges to the unique minimizer of the limit, so in probability. This is proved (Hansen 1982; Hayashi, Chapter 7) for any fixed positive definite and for an estimated that converges to one.
The asymptotic law. The first-order condition is with . Expand and solve:
The central limit theorem gives in distribution, and Slutsky's theorem gives
This sandwich has the same form as for an M-estimator.
Why is optimal. Write and . Both satisfy , so . Hence
which is positive semidefinite. The left side is the sandwich minus , so no weight does better than , which gives the variance of line L8. This is proved. Line L5 needs a first, consistent estimate because depends on ; replacing by a consistent estimate does not change the limit.
The test. If all conditions hold and , then in distribution (Hansen 1982). The degrees of freedom are used to fit . A large says that some condition is false, but not which one. With , always and there is nothing to test.
Classic examples
The method of moments. With and a solution of , the objective is zero there for every , so GMM is the method of moments and the weight does not matter. For it gives and the variance with divisor . The covariance is the delta method result.
Linear instrumental variables. For with instruments and , take . The conditions are linear in , and
With this is two-stage least squares; with it is ordinary least squares. Under heteroscedastic errors, the second step with (centered as in line L5) is more efficient than 2SLS, and the estimate of line L8 is robust in the same way as heteroscedasticity-consistent standard errors. A small exact case, with and :
| 3 | 6 | 4 | 9 | 2 | 8 | 5 | 11 | 7 | |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 1 | 4 | 0 | 3 | 2 | 5 | 3 | |
| 0 | 1 | 1 | 2 | 0 | 2 | 0 | 3 | 1 | |
| 1 | 1 | 0 | 1 | 0 | 0 | 2 | 2 | 1 |
OLS gives . The first step with gives , the same as the two literal stages of 2SLS, in exact arithmetic. The second step gives with standard errors and , and on 1 degree of freedom, . With the chi-squared reference is a rough guide only.
Poisson with two conditions. For Poisson counts, and , so with , . The population quantities are and with entries , and . The first column of is , so and . Efficient GMM reaches the Cramér-Rao bound of , and the second condition adds no precision but makes the 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 at level 0.05 was 0.594 for (500 data sets) and 1.0 for (500 data sets).
Euler equations. Hansen and Singleton (1982) estimated the discount factor and risk aversion of a consumer from . Any variable known at time gives an unconditional condition , so lagged variables serve as instruments and there is no need to model the law of consumption.
Estimating equations. With , the conditions 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 stops changing. The limit law is the same as for two steps.
- Continuously updated GMM. Minimize with recomputed at each (Hansen, Heaton and Yaron, 1996). It does not depend on a first step and is invariant to nonsingular linear transformations of .
- Long-run covariance. For time series, 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 has no formula, estimate it by simulation at each , with the same random draws for every .
- 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 is correlated with , and this biases the second step (Altonji and Segal, 1996). In the Poisson example with the data , where and the variance with divisor is , the first step with gave and the second step gave , with . The sample mean, which is the efficient estimate under the model, is 3. With few observations, report the first step too.
- The test over-rejects at moderate . Measured for the Poisson example with true Poisson data, nominal level 0.05: for the rejection rate was 0.106 at and 0.074 at (1000 data sets each), and 0.070 at (300 data sets). For the rates were 0.088, 0.074 and 0.043. The chi-squared limit is proved; its accuracy at a given is only measured.
- Weak identification. When is close to rank deficient, as with instruments that hardly move , the normal limit is a poor guide, is biased toward OLS and Wald intervals undercover.
- Too many conditions. Many weak conditions make 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 , the estimate changes when one condition is multiplied by a constant. The efficient objective is invariant to for a fixed and nonsingular , but two-step estimates still change through the first step.
- A small does not confirm the model. tests only the surplus conditions. If the conditions used for identification are false, is inconsistent and can still be small.
- Singular . Redundant conditions, such as the same instrument twice, make 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.
# 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
- Show that when and has a solution, GMM gives that solution for every positive definite , and that . Answer. The objective is a positive definite quadratic form in , so it is at least 0 and equals 0 exactly where . The minimum is therefore the root, whatever is, and .
- For and , show that the GMM estimate is with . Answer. . Setting the gradient of to zero gives . The scale does not change the minimizer.
- Prove that the two-step objective is unchanged when is replaced by with nonsingular and is computed from the new moments at the same point. Answer. The new is and the new is , so the form is .
- In the Poisson example with , find the asymptotic variance of and show it exceeds for every . Answer. With , the entries of are , and . So and . The variance is .
- Show that efficient GMM with the score functions as conditions has the asymptotic covariance . Answer. , and by the information identity, so .
References
- 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)
- 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)
- Fumio Hayashi, Econometrics, Princeton University Press, 2000, Chapter 3 (single-equation GMM, efficient weighting, the J statistic) and Chapter 7 (extremum estimators, nonlinear GMM)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag A39F7K Edit this page History Report an error Markdown