Day 30. Phase 2 Capstone: GMM & Numerical Optimisation
One framework for OLS, IV, 2SLS and MLE: choose moment conditions, minimise a quadratic form, and solve it numerically.
- ●Write OLS, IV and maximum likelihood as method-of-moments estimators.
- ●Set up the GMM objective, derive its first-order condition and the optimal weighting matrix.
- ●Show that 2SLS is GMM with a particular weighting matrix and interpret the J test of over-identifying restrictions.
- ●Run Newton–Raphson by hand for a logit and use numerical derivatives safely.
Theory
Method of moments
Many estimators come from population moment conditions , where is the data and has elements. The method of moments replaces the expectation by a sample average and solves
| Estimator | Moment condition |
|---|---|
| Mean | |
| OLS | |
| IV | |
| MLE | (the score) |
Generalised method of moments (GMM)
With moment conditions (over-identification), they cannot all be set to zero in the sample. GMM minimises a weighted distance from zero:
With and :
- FOC: .
- Asymptotic variance: (another sandwich).
- Optimal weighting gives the smallest variance, : trust precise moments more (compare Day 26's inverse-variance weights).
- J test: under correct specification.
2SLS is GMM with moments and : optimal under homoskedasticity.
Solving it numerically
Most GMM and ML problems have no closed form. Newton–Raphson (Day 25) iterates ; Gauss–Newton approximates the Hessian with first derivatives of . When derivatives are not available analytically, the central difference has error of order , but too small amplifies rounding error; to (relative to ) is a sensible default.
Phase 2 in one table
| Tool | Where it returns |
|---|---|
| Dot products, norms (16) | covariances, matching distances |
| , (17) | every regression |
| Rank (18) | identification, collinearity, fixed effects |
| Inverses, conditioning (19) | IV, weak instruments |
| Projections (20) | residuals, , leverage |
| Eigenvalues (21) | PCA, condition numbers, stability |
| Covariance matrices (22) | SEs of combinations, simulation |
| Derivatives, Taylor (23) | marginal effects, delta method |
| Matrix calculus (24) | first-order conditions |
| Optimisation (25–26) | MLE, weighting, design |
| OLS, FWL, sandwich (27–29) | regression, fixed effects, robust inference |
| GMM (30) | IV, 2SLS, efficient estimation |
Part 1 · Warm-up
Exercise 1 · Exponential by moments
For , . Find the method-of-moments estimator.
Show solution
Set : , the same as the MLE (Day 11).
Exercise 2 · Uniform by moments
For , find the method-of-moments estimator. Is it always sensible?
Show solution
Step 1. .
Step 2. Not always: with data , though an observation equals 7, impossible under the model.
Step 3. (The MLE is .) Moment estimators are consistent but not always efficient or coherent.
Exercise 3 · OLS as a moment estimator
Show that solving the sample analogue of gives OLS.
Show solution
, the normal equations (Day 24).
Exercise 4 · IV as a moment estimator
With as many instruments as regressors, solve .
Show solution
(Day 19, Exercise 15), which requires invertible: instruments must be relevant.
Exercise 5 · Counting
A model has parameters. How many moment conditions are needed for identification, and what does the J test need?
Show solution
At least 2 (order condition; the rank condition requires to have full column rank). The J test needs over-identification: with moments it has degrees of freedom, so .
Part 2 · Proofs
Exercise 6 · The GMM first-order condition
Derive from with symmetric .
Show solution
Step 1. By the chain rule and Day 24's quadratic-form rule, .
Step 2. Set it to zero.
Step 3. With and invertible, this forces : just-identified GMM is method of moments, whatever .
Exercise 7 · 2SLS is GMM
With and , show the GMM estimator is with .
Show solution
Step 1. .
Step 2. The FOC gives .
Step 3. Since (first-stage fitted values) and is idempotent, this is OLS of on : the "two stages".
Exercise 8 · The optimal weighting matrix
Show that with the sandwich simplifies to .
Show solution
Step 1. Substitute : the middle becomes , so the variance is .
Step 2. (That no other does better is a Gauss–Markov-style argument.)
Exercise 9 · Why J has L − K degrees of freedom
Explain intuitively why the J statistic is rather than .
Show solution
Step 1. is approximately a vector of independent standard normals, so its squared length would be .
Step 2. But we evaluate at , chosen to make small, which uses up directions (a projection, Day 20).
Step 3. The remaining directions are free, and their squared length is .
Exercise 10 · Two moments for doctor visits
Annual doctor visits are modelled as Poisson(), which implies and . A health survey finds and (so the sample variance is 4). Write the GMM objective with and find its minimiser numerically.
Show solution
Step 1. Sample moment conditions: .
Step 2. With : .
Step 3. At the first moment fits exactly but the second does not: . The second moment wants a larger .
Step 4. Minimising numerically (code below): .
Step 5. With the optimal , the noisy second moment gets little weight and returns to .
Answer: about 3.14 with and 3.00 with optimal weights. Variance (4) above the mean (3) is overdispersion (Day 4); in a large sample the J test would flag it.
Part 3 · Applied
Exercise 11 · Newton–Raphson for training take-up
30% of eligible workers enrol in a training programme. Fit an intercept-only logit for enrolment. Starting from , do two Newton steps and compare with the exact MLE .
Show solution
Step 1. Per worker, the score is and the Hessian is , where . Newton step: .
Step 2. From : , so .
Step 3. From : and , so .
Step 4. Exact: .
Answer: two steps reach three decimals: Newton's quadratic convergence.
Exercise 12 · Two instruments disagree
Two valid-looking instruments give Wald estimates 2.0 (SE 0.3) and 3.0 (SE 0.3). Would an over-identification test reject? What are the possible explanations?
Show solution
Step 1. Difference between the two estimates: .
Step 2. SE of the difference, ignoring correlation between them: .
Step 3. , so an over-identification (J) test would likely reject.
Step 4. Two explanations: one instrument is invalid; or both are valid but effects are heterogeneous and each identifies a LATE for different compliers (Day 63).
Answer: likely rejection, but the J test cannot tell the two explanations apart.
Exercise 13 · Pooling two evaluations is GMM
Two independent RCTs of the same microcredit programme estimate its effect on business profits: with variance and with variance . Treat as moment conditions with . Show that GMM gives the inverse-variance average.
Show solution
Step 1. Objective: .
Step 2. FOC: .
Step 3. Collect terms in : .
Answer:
Day 8's pooled estimator. Here , the optimal choice.
Exercise 14 · A numerical demand elasticity
A demand model is too complicated to differentiate by hand, so you compute derivatives numerically. Test the method on a case with a known answer: at (true derivative ). Use central differences with , and . Which step is best?
Show solution
Step 1. Truncation error of the central difference is about : roughly at , and about at .
Step 2. Rounding error is about (machine precision ≈ ) × : negligible at , but about at , because subtracts two almost equal numbers.
Step 3. The code confirms errors of , and .
Answer: . Too large a step is biased; too small a step is swamped by rounding.
Exercise 15 · From Phase 2 to Phase 3
Name the Phase 2 tool you would use for each task: (a) check whether a treatment dummy is collinear with fixed effects; (b) compute the SE of the sum of three event-study coefficients; (c) estimate an effect controlling for 50 covariates and explain what "controlling" does; (d) get valid SEs when treatment is assigned by school; (e) estimate a model with more instruments than endogenous regressors.
Show solution
Step 1. (a) Is treatment in the span of the fixed effects? → rank (Day 18).
Step 2. (b) Variance of a sum of coefficients → (Day 22).
Step 3. (c) Many controls and what "controlling" does → OLS and FWL (Days 27–28).
Step 4. (d) Treatment assigned by school → cluster-robust sandwich at the school level (Day 29).
Step 5. (e) More instruments than endogenous regressors → GMM/2SLS with a J test (Day 30).
Verify in Python
import numpy as np
from scipy import optimize
Q = lambda l: (3 - l)**2 + (13 - l - l**2)**2
lam_I = optimize.minimize_scalar(Q, bounds=(0.1, 10), method="bounded").x
print(f"GMM with W = I: lambda = {lam_I:.4f}")
# Optimal W for Poisson moments at lambda = 3: S = Var(X, X^2)
l = 3.0
EX, EX2, EX3, EX4 = l, l + l**2, l**3 + 3 * l**2 + l, l**4 + 6 * l**3 + 7 * l**2 + l
S = np.array([[EX2 - EX**2, EX3 - EX * EX2], [EX3 - EX * EX2, EX4 - EX2**2]])
W = np.linalg.inv(S)
Qopt = lambda l: (g := np.array([3 - l, 13 - l - l**2])) @ W @ g
print(f"GMM with optimal W: lambda = {optimize.minimize_scalar(Qopt, bounds=(0.1, 10), method='bounded').x:.4f}")
# Newton-Raphson for an intercept-only logit with ybar = 0.3
b = 0.0
for step in range(4):
p = 1 / (1 + np.exp(-b)); b = b + (0.3 - p) / (p * (1 - p)); print(f"step {step + 1}: {b:.6f}")
print("exact:", round(np.log(0.3 / 0.7), 6))
for h in (1e-1, 1e-5, 1e-12):
print(f"h={h:g}: error {abs((np.exp(1 + h) - np.exp(1 - h)) / (2 * h) - np.e):.2e}")
Key takeaways
- OLS, IV, 2SLS and MLE are all method-of-moments estimators; GMM handles extra moments by weighting.
- Optimal weighting trusts precise moments more; the J test checks whether over-identifying moments agree.
- Newton's method converges fast near the optimum; numerical derivatives need a sensible step size.
Simulation Lab: GMM with Two Moments
Open full screen →Estimate a Poisson rate from two moments, compare identity and optimal weighting, and watch the J test catch overdispersion.
Two moments for one parameter: E[X] = λ and E[X²] = λ + λ². With W = I the noisy second moment pulls the estimate; with the optimal W = Ŝ⁻¹ it is down-weighted. When the data are overdispersed the two moments disagree and the J test rejects. Curves are rescaled to share an axis.