Module contents
Lesson 6 of 28Advanced 110 min

Generalized method of moments, overidentification and weak instruments

Unify OLS, IV, 2SLS and likelihood through GMM; derive efficient weighting and Hansen's J, then study weak instruments, effective F and Anderson-Rubin inference.

After this lesson you can

  • Derive GMM asymptotic variance and prove optimality of W = S⁻¹.
  • Express OLS, IV, 2SLS and likelihood as moment methods and implement two-step GMM.
  • Apply J and explain why it cannot validate instruments sharing a common bias.
  • Diagnose weak instruments using first-stage F, effective F and appropriate critical values.
  • Construct Anderson-Rubin confidence sets by test inversion and explain unbounded sets.

Before you start

When there are extra conditions

In the two-stage least squares lesson, several instruments yield several restrictions for one parameter. If each instrument must be orthogonal to error, what can you do when sample restrictions cannot all be zero simultaneously? Find the parameter making them jointly close to zero. The choice of what “close” means determines how information is combined and how much uncertainty results.

The same question arises in finance. If a stochastic discount factor mt+1(θ)m_{t+1}(\theta) prices gross return Rt+1R_{t+1} and ztz_t is available at decision time, a candidate restriction is E[zt{mt+1(θ)Rt+1−1}]=0E[z_t\{m_{t+1}(\theta)R_{t+1}-1\}]=0. There is one condition per chosen instrument, asset and period. Its validity depends on the economic model and available information, not the algorithm’s name. Euler-equation moments are developed in Hansen and Singleton.

The GMM criterion

Let gi(θ)∈Rqg_i(\theta)\in\mathbb R^q be moment conditions for parameter θ∈Rp\theta\in\mathbb R^p, with q≥pq\ge p, and gˉn(θ)=n−1∑igi(θ)\bar g_n(\theta)=n^{-1}\sum_i g_i(\theta). The generalized method of moments minimizes

θ^=arg⁡min⁡θ∈Θgˉn(θ)⊤Wngˉn(θ),\hat\theta=\arg\min_{\theta\in\Theta} \bar g_n(\theta)^\top W_n\bar g_n(\theta),

with symmetric positive-definite WnW_n. If there are as many independent conditions as parameters and they can be solved exactly, the minimum is zero and does not depend on weight. With more conditions than parameters, the sample vector generally cannot be zero and weight matters. A positive-definite matrix assigns importance to combinations of discrepancies; it does not make invalid conditions reliable.

Consistency requires a unique population criterion minimum at θ0\theta_0, uniform convergence, regularity and an estimator actually approximating the global minimum. Global identification requires no other θ\theta satisfy the same restrictions. Locally, matrix G=E[∂gi(θ0)/∂θ⊤]G=E[\partial g_i(\theta_0)/\partial\theta^\top] must have full column rank; that alone does not rule out distant solutions. Dependent data additionally require stationarity and dependence conditions permitting an appropriate law of large numbers and central limit theorem.

InteractiveThe GMM criterion landscape

The surface is n[Q(θ)−Q(θ̂)] for four moments and two parameters. Height is scaled per view; horizontal position is relative to the minimum, which changes with weight and shift.

θ₂θ₁
  • Criterion contour
  • Confidence region
0.361.00−0.17−0.81θ₁θ₂

The blue contour satisfies Δ(nQ)=5.991; the dashed ellipse uses the estimator’s sandwich covariance for the chosen weight. They coincide for S⁻¹. This is a 95% region for the parameter targeted by that estimator in this Gaussian model; if moments are shifted, that parameter can differ from the structural one.

Model: Yᵢ=Aθ₀+δ+εᵢ, θ₀=(0.7; −0.4), A has rows (1,0), (0,1), (1,1), (1,−1), εᵢ∼N(0,S), S=diag(1; 4; 9; 16). Means of 200 NumPy-generated samples use seed 270601 and stay fixed when controls change. Q(θ)=(Aθ−Ȳ)ᵀW(Aθ−Ȳ). The alternative weight is diag(1; 2; 0.5; 1.5); S⁻¹ is known, not estimated.

J is always computed by minimizing with S⁻¹ even when another weight is shown, and compared with χ² on 2 degrees of freedom under valid moments. A transverse shift can raise J; aligned δ=A(1,0) moves the minimum without changing J. Failure to reject never proves moment validity. Reference: Hansen (1982), GMM and overidentifying restrictions.

Weight matrix
Moment shift
θ̂₁0.685
θ̂₂−0.492
Minimum nQ for chosen weight0.128
J with S⁻¹0.128
J p-value, χ²(2)0.9379
Change weight and violation to compare the minimum, test and confidence region.

The next cell regenerates the sample underlying the landscape and checks three weights and shifts. The optimal weight uses the generator’s known covariance.

[ ]Regenerate the GMM landscapeBrowser
import numpy as np
from scipy.stats import chi2

# Cada observación es vectorial Y_i=Aθ₀+δ+ε_i, con ε_i~N(0,S).
# El momento muestral es ḡ(θ)=Aθ−Ȳ. La misma muestra se mantiene al
# activar un desplazamiento, por lo que se observa su efecto sin cambiar ruido.
n=200
A=np.array([[1.,0.],[0.,1.],[1.,1.],[1.,-1.]])
theta0=np.array([.7,-.4])
S=np.diag([1.,4.,9.,16.])
rng=np.random.default_rng(270601)
noise=rng.normal(size=(n,4))@np.linalg.cholesky(S).T
mean_base=A@theta0+noise.mean(axis=0)
weights={'identidad':np.eye(4),'otro peso':np.diag([1.,2.,.5,1.5]),'óptimo':np.linalg.inv(S)}

def fit(b,W):
    curvature=A.T@W@A
    theta=np.linalg.solve(curvature,A.T@W@b)
    residual=A@theta-b
    criterion=residual@W@residual
    return theta,criterion,curvature

for name,shift in [('sin desplazamiento',np.zeros(4)),
                   ('violación transversal',np.array([0.,0.,0.,2.])),
                   ('sesgo alineado',A@np.array([1.,0.]))]:
    b=mean_base+shift
    print('\n',name,'media observada:',b)
    for weight,W in weights.items():
        theta,q,H=fit(b,W)
        j=n*q if weight=='óptimo' else None
        print(weight,'theta:',theta,'criterio:',q,'J óptimo:',j,
              'p:',chi2.sf(j,2) if j is not None else None,'curvatura:',H.tolist())
        assert np.allclose(A.T@W@(A@theta-b),0,atol=1e-12)
    optimum=fit(b,weights['óptimo'])
    # Δ(nQ)=n(θ−θhat)'(A'WA)(θ−θhat), exacto para el peso fijo.
    candidate=optimum[0]+np.array([.1,-.2])
    residual=A@candidate-b
    delta=n*(residual@weights['óptimo']@residual-optimum[1])
    expected=n*(candidate-optimum[0])@optimum[2]@(candidate-optimum[0])
    assert np.isclose(delta,expected)

theta_before,q_before,_=fit(mean_base,weights['óptimo'])
theta_shift,q_shift,_=fit(mean_base+A@np.array([1.,0.]),weights['óptimo'])
assert np.allclose(theta_shift-theta_before,[1.,0.])
assert np.isclose(q_shift,q_before)
print('\nInvariante exacta: desplazamiento alineado incrementa β₁ en 1 sin alterar J.')
print('χ² crítico al 95 %, df=2:',chi2.ppf(.95,2))

Variance and efficient weight

Suppose n gˉn(θ0)⇒N(0,S)\sqrt n\,\bar g_n(\theta_0)\Rightarrow N(0,S), Wn→pWW_n\to_p W, positive-definite SS and WW and full-column-rank GG. Expanding first-order conditions gives

n(θ^−θ0)=−(G⊤WG)−1G⊤Wn gˉn(θ0)+op(1).\sqrt n(\hat\theta-\theta_0) =-(G^\top WG)^{-1}G^\top W\sqrt n\,\bar g_n(\theta_0)+o_p(1).

Thus the asymptotic covariance of n(θ^−θ0)\sqrt n(\hat\theta-\theta_0) is

V(W)=(G⊤WG)−1G⊤WSWG(G⊤WG)−1.V(W)=(G^\top WG)^{-1}G^\top WSWG(G^\top WG)^{-1}.

Approximate covariance of θ^\hat\theta is V(W)/nV(W)/n. If observations are independent, S=Var⁡(gi)S=\operatorname{Var}(g_i); with temporal dependence it is long-run covariance, not merely contemporaneous variance. The efficient weight is W=S−1W=S^{-1} and yields V∗=(G⊤S−1G)−1V_*=(G^\top S^{-1}G)^{-1}.

To prove optimality, define AW=(G⊤WG)−1G⊤WA_W=(G^\top WG)^{-1}G^\top W and A∗=(G⊤S−1G)−1G⊤S−1A_*=(G^\top S^{-1}G)^{-1}G^\top S^{-1}. Both matrices satisfy AWG=A∗G=IA_WG=A_*G=I. If D=AW−A∗D=A_W-A_*, then DG=0DG=0 and cross terms of (A∗+D)S(A∗+D)⊤(A_*+D)S(A_*+D)^\top vanish because A∗S=(G⊤S−1G)−1G⊤A_*S=(G^\top S^{-1}G)^{-1}G^\top. Thus,

V(W)−V∗=DSD⊤⪰0.V(W)-V_*=DSD^\top\succeq0.

The inequality is matrix-valued: no regular linear combination of the considered moments has lower asymptotic variance with another admissible fixed weight. It does not compare models with different moments or correct false restrictions.

Two stages, iteration and dependence

Since SS generally depends on θ0\theta_0, first estimate with an initial weight and calculate S^\hat S at the result. The second stage minimizes with S^−1\hat S^{-1} fixed. You can repeatedly update S^\hat S and the estimator to a tolerance, or use continuous updating, which recalculates the weight as the candidate changes during minimization. These are different algorithms in finite samples; numerical convergence and invertibility of S^\hat S must be checked.

For temporal data, define Γ^h=n−1∑t=h+1n(gt−gˉ)(gt−h−gˉ)⊤\hat\Gamma_h=n^{-1}\sum_{t=h+1}^n(g_t-\bar g)(g_{t-h}-\bar g)^\top. A Newey-West HAC estimator with Bartlett window uses

S^=Γ^0+∑h=1L(1−hL+1)(Γ^h+Γ^h⊤).\hat S=\hat\Gamma_0+\sum_{h=1}^{L} \left(1-\frac{h}{L+1}\right)(\hat\Gamma_h+\hat\Gamma_h^\top).

Bandwidth LL controls the bias-variability trade-off; consistency requires an appropriate choice and dependence conditions. Cluster adjustments require another estimate of SS. Inverting a nearly singular matrix amplifies numerical errors: report the issue rather than hide it.

In stationary series, dependence over time explains why SS accumulates autocovariances. In simulation-model calibration, observed moments can be compared with Monte Carlo approximations; simulation uncertainty adds to parameter identification and must be included in analysis.

OLS, IV, 2SLS and maximum likelihood

OLS solves n−1X⊤(y−Xβ)=0n^{-1}X^\top(y-X\beta)=0; exactly identified IV replaces XX with ZZ. Both are method-of-moments conditions. With more instruments, gi(β)=zi(yi−xi⊤β)g_i(\beta)=z_i(y_i-x_i^\top\beta) and Wn=(Z⊤Z/n)−1W_n=(Z^\top Z/n)^{-1} yield exactly 2SLS:

arg⁡min⁡βgˉ⊤Wngˉ=(X⊤PZX)−1X⊤PZy.\arg\min_\beta \bar g^\top W_n\bar g =(X^\top P_ZX)^{-1}X^\top P_Zy.

Under conditional homoskedasticity E[ui2∣zi]=σ2E[u_i^2\mid z_i]=\sigma^2, S=σ2E[zizi⊤]S=\sigma^2E[z_iz_i^\top] and that weight is proportional to the efficient one. Under general heteroskedasticity it need not be. An interior differentiable likelihood maximum satisfies score moment ∑i∂log⁡f(yi;θ)/∂θ=0\sum_i\partial\log f(y_i;\theta)/\partial\theta=0; multiple roots, boundary solutions or a misspecified model require further analysis. The lab checks these equivalences in a simulated system and compares library implementations.

What J can detect

With q>pq>p, valid moments, strong identification, regularity and a consistent estimate of S−1S^{-1}, the Hansen J test evaluates remaining discrepancy:

J=n gˉn(θ^)⊤S^−1gˉn(θ^)→dχq−p2.J=n\,\bar g_n(\hat\theta)^\top\hat S^{-1}\bar g_n(\hat\theta) \xrightarrow{d}\chi^2_{q-p}.

Exogenous controls entering both regressors and instruments are counted in both and add no net degrees of freedom. Rejection questions the set of restrictions and maintained model; it does not itself identify which instrument fails. Failure to reject can reflect low power or a violation absorbed as a parameter shift. For example, if y=(β+c)x+εy=(\beta+c)x+\varepsilon and E[zε]=0E[z\varepsilon]=0, all moments are compatible with β+c\beta+c even if the causal target were β\beta: restrictions cannot reveal that common shift alone. Nor is it valid to calculate a minimum with arbitrary weight and automatically assign the efficient J distribution. Original theory is in Hansen.

To derive degrees of freedom, whiten moments: h=S−1/2n gˉn(θ0)⇒N(0,Iq)h=S^{-1/2}\sqrt n\,\bar g_n(\theta_0)\Rightarrow N(0,I_q). Near θ0\theta_0, minimizing with efficient weight removes the projection of hh onto columns of S−1/2GS^{-1/2}G. Remaining discrepancy is asymptotically ∥(I−P)h∥2\|(I-P)h\|^2, with PP an orthogonal projector of rank pp. The complement has rank q−pq-p, yielding chi-square. This calculation requires the same efficient weight, or a consistent one, for both estimation and criterion evaluation.

The weak first-stage problem

Weak instruments explain little relevant regressor variation after removing controls. In usual asymptotics the population relationship stays fixed as nn increases; a local-to-zero approximation makes it decrease as 1/n1/\sqrt n. In that regime the IV distribution can be highly asymmetric and conventional normal intervals can undercover. With several instruments, 2SLS can shift toward OLS in common situations, but this is not a universal theorem and should not be summarized with a mean that may not exist.

Table 1 of Bound, Jaeger and Baker studies birth quarter for 329,509 men born between 1930 and 1939. One specification with three instruments reports F=13,486F=13{,}486 and IV coefficient 0.142; another with 28 reports F=1,613F=1{,}613 and coefficient 0.060. The specifications also differ in age controls, so the difference cannot be attributed solely to instrument count. The example shows why a huge sample does not guarantee an informative first stage.

InteractiveWhen the instrument weakens

Each curve counts the fraction of 600 replicates in each interval; the vertical line marks the true effect, 1. Values outside the window do not disappear from the experiment: OLS 0, 2SLS 4.

84.9 %0−1.00.01.02.03.5Coefficient estimate
  • OLS
  • 2SLS

In each replicate, three normal columns are centered and orthonormalized into Q. Generate independent centered standard normals v and ε, u=0.8v+0.6ε, x=√λq₁+v and y=x+u. There is a constant, 120 observations and three excluded instruments. Strength λ is conditional concentration in this construction; the same disturbances are used as the slider moves.

Wald coverage uses the classical structural standard error and normal quantile. AR tests the true value with F on 3 and 116 degrees of freedom and is exact under this normal homoskedastic model, including λ=0. Each proportion has Monte Carlo uncertainty: near 95% the standard error is about 0.9 percentage points. These results describe the experiment, not a guarantee for heteroskedastic or dependent data.

5
270602
OLS median1.771
2SLS median1.229
Nominal 95% Wald coverage80.3 %
Nominal 95% AR coverage96.2 %
Mean first-stage F2.59
Change strength and compare distributions and coverage in a reproducible experiment.

Simulation coverage proportions have Monte Carlo uncertainty. In the figure, the same set of perturbations compares strengths; this does not mean all samples give the same OLS versus 2SLS ordering. LIML may perform better than 2SLS in bias under weak or many instruments, but does not fix invalid instruments or guarantee reliable Wald intervals.

Diagnosis: F is not a certificate

For a first stage with controls and kk excluded instruments, classical F tests that their coefficients are zero. Stock-Yogo tables concern homoskedastic assumptions and specific relative-bias or size-distortion criteria, with design-dependent critical values. The informal rule of exceeding 10 does not guarantee every estimator or interval is reliable.

For example, table 5.2 of Stock and Yogo gives 22.30 for one endogenous regressor, three excluded instruments and a maximum 10% size criterion for a nominal 5% Wald test under their homoskedastic framework. The last replicate below gives classical F of 7.66, below 22.30: by that criterion weak instruments are not rejected. This diagnoses that sample under the table’s assumptions; do not apply that critical value to effective F or interpret the result as exclusion proof.

With one endogenous regressor, Montiel Olea and Pflueger propose effective F and suitable critical values for certain bias criteria under heteroskedasticity, temporal dependence or clustering. In the independent case with instruments residualized and orthonormalized in QQ, one HC0 version uses

Fef=∥Q⊤x~∥2tr⁡{Q⊤diag⁡(v^i2)Q}.F_{\mathrm{ef}}= \frac{\|Q^\top\tilde x\|^2} {\operatorname{tr}\{Q^\top\operatorname{diag}(\hat v_i^2)Q\}}.

Here x~\tilde x and instruments are residualized against the same controls, and v^\hat v is the full first-stage residual. For series or groups replace covariance with the corresponding HAC or cluster version. Effective F is generally not robust Wald divided by instrument count and cannot simply be compared with homoskedastic Stock-Yogo tables. Choosing a method after a diagnostic based on its result can also distort inference.

Anderson-Rubin: test without dividing by the first stage

Weak-instrument-robust inference can avoid the IV ratio. To test β=β0\beta=\beta_0, form y−β0xy-\beta_0x and test whether excluded instruments help explain it after controls. If β0\beta_0 is correct and instruments valid, the transformed outcome contains structural error and controls, without needing a strong estimated first stage. If the error vector is normal with covariance σ2I\sigma^2I conditional on appropriately ranked instruments and controls, the exclusion F has an exact distribution with design degrees of freedom. Heteroskedasticity or dependence requires a robust version and its asymptotic assumptions.

Inverting the test retains every β0\beta_0 value not rejected. The set can be a bounded interval, two rays, the entire line or even empty in some designs. A plot over a finite window does not prove the set ends at its edges: analyze the full inequality.

InteractiveInvert a test to obtain an interval

For each candidate regress Y − β₀X on a constant and Z. The AR test checks whether the coefficient on Z is zero. The dashed line is the 5% critical value; failure to reject does not prove β₀ is true.

  • AR statistic
  • 5% critical value
  • Candidate

The horizontal axis shows candidate β₀ and the vertical axis the F statistic. Shading indicates non-rejected values in the visible window. The plot shows β₀ only from −6 to 6 and clips F above 10. That grid is not used to determine endpoints.

Complete non-rejection set: [0.618, 1.426].

Solve the quadratic inequality (zᵀ(y−β₀x))² ≤ c(zᵀz)‖M₍₁,z₎(y−β₀x)‖²/118 over the entire line, with centered z, x and y and c = F₁,₁₁₈;₀,₉₅. Depending on coefficients the set may be bounded, two rays or the whole line. Displayed endpoints are rounded.

Reproducible model: n = 120; Z, V and E are independent standard normals; X = πZ + V, U = 0.65V + √(1−0.65²)E and Y = 1 + X + U. Correlation between X and U introduces endogeneity; Z is exogenous and satisfies exclusion by construction. With π = 0 there is no population relevance. Under the true null U is homoskedastic normal and independent of Z, so this F reference is exact in finite samples. Heteroskedasticity requires different calibration.

0.45
1.00
AR statistic F(1,118)0.257
5% critical value3.921
Decision on β₀Not rejected
First-stage F25.778
True β1.0
Seed270601
Sweep candidates and observe which values survive the AR test.

Lab: GMM engine

The class receives a function returning a row of moments per observation. First it reproduces 2SLS and statsmodels.sandbox.IVGMM; then estimates a synthetic Euler example and compares with generic statsmodels GMM. Run the cells in order: the second reuses the first’s class.

[ ]GMM engine, two stages and iterationBrowser
"""GMM genérico: ponderación fija, dos etapas, iteración y S HAC.

Cada fila de moments(theta) es g_i(theta). La matriz usada para estimar
se conserva para calcular el criterio, incluido J. HC0/HAC sin correcciones.
"""
import numpy as np
from scipy.optimize import minimize
from scipy.stats import chi2
from statsmodels.sandbox.regression.gmm import IVGMM


def covariance_moments(g, lags=0):
    g = np.asarray(g, dtype=float)
    n = len(g)
    if g.ndim != 2 or not 0 <= lags < n or not np.isfinite(g).all():
        raise ValueError('Momentos o rezagos inválidos')
    centered = g - g.mean(axis=0)
    S = centered.T @ centered / n
    for lag in range(1, lags + 1):
        cross = centered[lag:].T @ centered[:-lag] / n
        S += (1 - lag / (lags + 1)) * (cross + cross.T)
    return (S + S.T) / 2


class GMM:
    def __init__(self, moments, start, weight=None, lags=0):
        self.moments = moments
        self.start = np.asarray(start, dtype=float)
        self.g = np.asarray(moments(self.start), dtype=float)
        if self.g.ndim != 2 or len(self.g) <= len(self.start):
            raise ValueError('Dimensión de momentos inválida')
        self.n, self.q = self.g.shape
        self.p = len(self.start)
        if self.q < self.p:
            raise ValueError('Modelo subidentificado')
        self.weight = np.eye(self.q) if weight is None else np.asarray(weight, float)
        self.lags = lags

    def mean(self, theta):
        return np.mean(self.moments(theta), axis=0)

    def objective(self, theta, W):
        m = self.mean(theta)
        return float(m @ W @ m)

    def fit(self, updates=1, tolerance=1e-8):
        # updates=0: matriz inicial; updates=1: dos etapas; mayor: iterado.
        theta = self.start.copy()
        W = self.weight.copy()
        converged = False
        for step in range(updates + 1):
            result = minimize(self.objective, theta, args=(W,), method='BFGS',
                              options={'gtol': 1e-9, 'maxiter': 250})
            if not result.success and np.linalg.norm(result.jac) > 1e-6:
                raise RuntimeError('No convergió el optimizador: ' + result.message)
            updated = result.x
            converged = np.linalg.norm(updated - theta) < tolerance
            theta = updated
            if step == updates or (step > 0 and converged):
                break
            S = covariance_moments(self.moments(theta), self.lags)
            if np.linalg.matrix_rank(S) < self.q:
                raise ValueError('Covarianza de momentos singular')
            W = np.linalg.inv(S)
        h = 1e-5
        G = np.column_stack([(self.mean(theta + h * np.eye(self.p)[j]) -
                              self.mean(theta - h * np.eye(self.p)[j])) / (2*h)
                             for j in range(self.p)])
        if np.linalg.matrix_rank(G) < self.p:
            raise ValueError('Jacobiano sin rango local')
        S = covariance_moments(self.moments(theta), self.lags)
        bread = np.linalg.inv(G.T @ W @ G)
        covariance = bread @ (G.T @ W @ S @ W @ G) @ bread / self.n
        J = self.n * self.objective(theta, W)
        # El p de Hansen necesita W eficiente, identificación fuerte y validez.
        pvalue = chi2.sf(J, self.q-self.p) if self.q > self.p and step > 0 else np.nan
        return theta, covariance, J, pvalue, step, converged


rng = np.random.default_rng(270601)
n = 1200
z = rng.normal(size=(n, 3))
error = rng.normal(size=n) * (0.8 + 0.2*z[:, 0]**2)
x = 0.7*z[:, 0] + 0.5*z[:, 1] + 0.7*error + rng.normal(size=n)
y = 0.8 + 1.4*x + error
X = np.column_stack((np.ones(n), x))
Z = np.column_stack((np.ones(n), z))
W0 = np.linalg.inv(Z.T @ Z / n)
moments = lambda theta: Z * (y - X @ theta)[:, None]
model = GMM(moments, np.zeros(2), weight=W0)
first = model.fit(updates=0)
Qz, _ = np.linalg.qr(Z, mode='reduced')
Xhat = Qz @ (Qz.T @ X)
tsls = np.linalg.solve(Xhat.T @ Xhat, Xhat.T @ y)
reference = IVGMM(y, X, Z).fitgmm(np.zeros(2), weights=W0,
                                   optim_args={'disp': False, 'gtol': 1e-9})
assert np.allclose(first[0], tsls, atol=1e-5)
assert np.allclose(first[0], reference, atol=1e-5)
second = model.fit(updates=1)
iterated = model.fit(updates=12)
print('MC2E propia / GMM primera etapa / statsmodels:', tsls, first[0], reference)
print('GMM dos etapas, EE HC0, J y p:', second[0], np.sqrt(np.diag(second[1])), second[2:4])
print('GMM iterado, actualizaciones y convergencia:', iterated[0], iterated[4:])
print('J usa la ponderación empleada al estimar; sus p requieren identificación fuerte.')

The next cell generates positive returns with a power-utility discount factor. Data are independent by construction; HAC with three lags illustrates the calculation and does not claim empirical dependence.

[ ]Synthetic Euler equation with GMM and HACBrowser
"""Euler sintético, continuación de la celda que define GMM.

El instrumento es observado antes del rendimiento. El generador impone
E[epsilon|z]=0 y R>0; no pretende reproducir datos financieros reales.
"""
import numpy as np
from statsmodels.sandbox.regression.gmm import GMM as StatsmodelsGMM

rng_euler = np.random.default_rng(270602)
n_euler = 2500
signal = rng_euler.normal(size=n_euler)
growth = 0.03 + 0.025*signal + 0.035*rng_euler.normal(size=n_euler)
delta_true, gamma_true = .96, 2.0
epsilon = rng_euler.uniform(-.12, .12, size=n_euler)
returns = np.exp(gamma_true*growth)*(1+epsilon)/delta_true
instruments = np.column_stack((np.ones(n_euler), signal, signal**2-1))

def euler_moments(theta):
    delta, gamma = theta
    errors = delta*np.exp(-gamma*growth)*returns - 1
    return instruments * errors[:, None]

euler_model = GMM(euler_moments, [0.9, 1.0], lags=3)
first_est = euler_model.fit(updates=0)[0]
euler_weight = np.linalg.inv(covariance_moments(euler_moments(first_est), 3))
est, cov, j, p, updates, conv = euler_model.fit(updates=1)

class EulerStatsmodels(StatsmodelsGMM):
    def momcond(self, theta):
        return self.instrument*(theta[0]*np.exp(-theta[1]*self.exog[:, 0])*self.endog-1)[:, None]

euler_reference = EulerStatsmodels(returns, growth[:, None], instruments,
                                  k_moms=3, k_params=2)
reference_est = euler_reference.fitgmm(first_est, weights=euler_weight,
                                       optim_args={'disp': False, 'gtol': 1e-9})
assert np.all(returns > 0)
assert np.isfinite(est).all() and np.linalg.matrix_rank(cov) == 2
assert np.allclose(est, reference_est, atol=1e-5)
print('Euler verdadero y estimado:', [delta_true, gamma_true], est)
print('Mismos momentos y ponderación, statsmodels GMM:', reference_est)
print('EE HAC Bartlett L=3:', np.sqrt(np.diag(cov)))
print('J eficiente y p chi2(1):', j, p)
print('Euler: datos sintéticos; momento válido por construcción y serie independiente.')

Lab: weak instruments

The experiment compares medians and coverage, not means that may not exist. Retain functions defined in the first cell to run the next two. Monte Carlo errors show uncertainty of each coverage. Exact AR validity here comes from homoskedastic normality and independent instruments, not merely the name AR.

[ ]2SLS, LIML and coverageBrowser
"""Instrumentos débiles, diagnóstico y cobertura en un modelo explícito.

Un regresor endógeno, tres instrumentos excluidos y constante. Los shocks
son normales correlacionados y homocedásticos. AR usa F exacta bajo H0.
"""
import numpy as np
from scipy.linalg import eigh
from scipy.stats import f, t


def fit_one(y, x, z):
    n, k = z.shape
    yc, xc = y-y.mean(), x-x.mean()
    zc = z-z.mean(axis=0)
    q, _ = np.linalg.qr(zc, mode='reduced')
    xp, yp = q.T @ xc, q.T @ yc
    xhat = q @ xp
    beta = float(xp @ yp / (xp @ xp))
    residual = yc-beta*xc
    variance = float(residual @ residual / (n-2) / (xp @ xp))
    first_resid = xc-xhat
    first_f = float((xp@xp/k) / (first_resid@first_resid/(n-k-1)))
    # Covarianza HC0 de los coeficientes sobre Q: tr(Q' diag(v²) Q).
    denom = float(np.sum(q*q*first_resid[:, None]**2))
    effective_f = float(xp @ xp / denom)
    # M_W: centrar. M_Z: centrar y quitar el espacio de instrumentos.
    Y = np.column_stack((yc, xc))
    projected = q.T @ Y
    left = Y.T @ Y
    right = left - projected.T @ projected
    kappa = float(eigh(left, right, eigvals_only=True)[0])
    mx, my = xc-xhat, yc-q@yp
    denominator = float(xc@xc-kappa*(mx@mx))
    liml = float((xc@yc-kappa*(mx@my))/denominator)
    return beta, np.sqrt(variance), liml, first_f, effective_f, q


def ar_pvalue(y, x, q, beta0):
    # Contrasta instrumentos en regresión de y−beta0*x sobre constante y Z.
    n, k = q.shape
    r = y-beta0*x
    r = r-r.mean()
    projection = q.T @ r
    residual = r-q@projection
    statistic = (projection@projection/k)/(residual@residual/(n-k-1))
    return float(f.sf(statistic, k, n-k-1))


rng = np.random.default_rng(270603)
n, k, repetitions = 300, 3, 240
beta_true, corr = 1.0, .8
critical = t.ppf(.975, n-2)
for concentration in (0.0, 5.0, 30.0):
    rows = []
    for _ in range(repetitions):
        z = rng.normal(size=(n, k))
        u, e = rng.normal(size=(2, n))
        v = corr*u + np.sqrt(1-corr*corr)*e
        # ||pi||² n = concentración porque E[z z'] = I y Var(v)=1.
        x = z[:, 0]*np.sqrt(concentration/n) + v
        y = beta_true*x+u
        ols = np.cov(x, y, ddof=0)[0, 1]/np.var(x)
        iv, se, liml, first_f, effective_f, q = fit_one(y, x, z)
        wald = abs(iv-beta_true) <= critical*se
        ar = ar_pvalue(y, x, q, beta_true) >= .05
        rows.append([ols, iv, liml, first_f, effective_f, wald, ar])
    a = np.asarray(rows)
    cover_wald, cover_ar = a[:, 5:].mean(axis=0)
    mc_wald = np.sqrt(cover_wald*(1-cover_wald)/repetitions)
    mc_ar = np.sqrt(cover_ar*(1-cover_ar)/repetitions)
    print('Concentración:', concentration, 'réplicas:', repetitions)
    print('Medianas OLS, MC2E, LIML, F clásico, F efectivo:', np.median(a[:, :5], axis=0))
    print('Cobertura Wald / AR y error Monte Carlo:', cover_wald, mc_wald, cover_ar, mc_ar)
print('Última réplica, concentración 30, F clásico y crítico Stock-Yogo:',
      first_f, 22.30)
print('Solo este diseño normal homocedástico: AR es exacto al fijar beta verdadero.')
print('LIML y MC2E no poseen necesariamente media finita; se comparan medianas.')

Heteroskedasticity in the next example separates three diagnostics; none proves exclusion. Its effective F is based on HC0 covariance and is not interpreted with a generic threshold.

[ ]Effective F versus classical FBrowser
"""Tres estadísticas de primera etapa bajo heterocedasticidad simulada.

Continúa la celda weak_iv_simulation.py. No se comparan con umbrales ajenos.
"""
import numpy as np

rng_hetero = np.random.default_rng(270606)
n_hetero, k_hetero = 1000, 3
z_hetero = rng_hetero.normal(size=(n_hetero, k_hetero))
v_hetero = rng_hetero.normal(size=n_hetero)*(.3+1.2*z_hetero[:, 0]**2)
x_hetero = .45*z_hetero[:, 0] + v_hetero
y_hetero = x_hetero + .4*v_hetero + rng_hetero.normal(size=n_hetero)
_, _, _, f_classic, f_effective, q_hetero = fit_one(y_hetero, x_hetero, z_hetero)
xc_hetero = x_hetero-x_hetero.mean()
pi_q = q_hetero.T@xc_hetero
residual_hetero = xc_hetero-q_hetero@pi_q
cov_q = (q_hetero*residual_hetero[:, None]).T@(q_hetero*residual_hetero[:, None])
f_robust = float(pi_q@np.linalg.solve(cov_q, pi_q)/k_hetero)
print('F clásico, Wald robusto/k y F efectivo HC0:', f_classic, f_robust, f_effective)
print('El F efectivo usa tr(cov_q), no la inversa de cov_q; las tres magnitudes no son equivalentes.')

Analytic inversion also identifies tails. It then checks decisions on a grid as an independent verification of the inequality.

[ ]Invert Anderson-RubinBrowser
"""Región AR mediante inversión exacta de F, continuación de la celda anterior."""
import numpy as np
from scipy.stats import f


def anderson_rubin_region(y, x, z, alpha=.05):
    n, k = z.shape
    q, _ = np.linalg.qr(z-z.mean(axis=0), mode='reduced')
    yc, xc = y-y.mean(), x-x.mean()
    py, px = q.T@yc, q.T@xc
    ry, rx = yc-q@py, xc-q@px
    cutoff = f.ppf(1-alpha, k, n-k-1)
    scale = cutoff/(n-k-1)
    # La región aceptada cumple a*beta0² + b*beta0 + c <= 0.
    a = float(px@px/k-scale*(rx@rx))
    b = float(-2*py@px/k+2*scale*(ry@rx))
    c = float(py@py/k-scale*(ry@ry))
    disc = b*b-4*a*c
    tol = 1e-12
    if abs(a) < tol:
        if abs(b) < tol:
            result = 'toda la recta' if c <= 0 else 'vacío'
        else:
            root = -c/b
            result = f'(-inf, {root:.4f}]' if b > 0 else f'[{root:.4f}, inf)'
    elif disc < 0:
        result = 'toda la recta' if a < 0 else 'vacío'
    else:
        roots = np.sort([(-b-np.sqrt(disc))/(2*a), (-b+np.sqrt(disc))/(2*a)])
        lo, hi = roots
        result = f'[{lo:.4f}, {hi:.4f}]' if a > 0 else f'(-inf, {lo:.4f}] unión [{hi:.4f}, inf)'
    return result, (a, b, c), q


rng_ar = np.random.default_rng(270605)
n_ar, k_ar = 300, 3
z_ar = rng_ar.normal(size=(n_ar, k_ar))
u_ar, e_ar = rng_ar.normal(size=(2, n_ar))
v_ar = .8*u_ar+.6*e_ar
for concentration_ar in (0.0, 30.0):
    x_ar = z_ar[:, 0]*np.sqrt(concentration_ar/n_ar)+v_ar
    y_ar = 1+x_ar+u_ar
    region, (a, b, c), q_ar = anderson_rubin_region(y_ar, x_ar, z_ar)
    for candidate in np.linspace(-20, 20, 121):
        inequality = (a*candidate**2+b*candidate+c <= 0)
        assert inequality == (ar_pvalue(y_ar, x_ar, q_ar, candidate) >= .05)
    print('Concentración, región AR:', concentration_ar, region)
print('La inversión analítica determina colas; una rejilla acotada no lo hace.')

Exercises

ProofOptimality of the weight
Prove: Let S and W be symmetric positive definite and G have full column rank. Show weight S⁻¹ minimizes asymptotic covariance among admissible weights.
0
Compare linear operators A mapping moments to parameter shifts.

Step 1 of 3. What do A_W=(GᵀWG)⁻¹GᵀW and A_*=(GᵀS⁻¹G)⁻¹GᵀS⁻¹ satisfy?

Proof2SLS as GMM
Prove: With full-rank Z and invertible XᵀP_ZX, show moments gᵢ=zᵢ(yᵢ−xᵢᵀβ) with W=(ZᵀZ/n)⁻¹ yield 2SLS. Explain homoskedastic efficiency.
0
Substitute sample mean moments into the quadratic criterion.

Step 1 of 3. Apart from a positive factor that does not change the minimum, what is the criterion?

NumericOveridentification p-value
There are three excluded instruments and one endogenous regressor; controls appear in both matrices. Under efficient J assumptions, what is the p-value if J=7.2? Give four decimal places.
QuizWeak first stage and J
With a weak first stage you do not reject J. What conclusion is justified?
QuizInformative first stage and nonsignificant J
The first stage is informative and J does not reject. What can you say?
QuizJ rejects
In an overidentified model with strong identification and appropriate variance, J rejects the restrictions. What conclusion is defensible?
QuizF under heteroskedasticity
The first stage is heteroskedastic and classical F appears high. What is the strongest next step?
CodeInvert Anderson-Rubin on a grid
Implement anderson_rubin_ci(y, x, Z, grid, alpha=.05). y and x are vectors of length n; Z contains only the q excluded instruments, without a constant; grid is a vector of candidates for the coefficient of x. Return a Boolean vector with the same size and order as grid: True if the joint two-sided AR test does not reject that candidate at level alpha. For each candidate β₀, regress y−β₀ x on a constant and instruments and jointly test that the q slopes are zero using the classical F statistic. Reject nonfinite inputs, incompatible dimensions, an empty grid, a level outside (0,1), instruments lacking rank after removing the constant, insufficient residual degrees of freedom or zero residual variance. The constant is the only exogenous control in this version; with other controls residualize y, x and Z against them and adjust degrees of freedom. Exact F coverage in the simulation assumes exogenous instruments and, conditional on them, iid normal structural errors with common positive variance. It does not assume a strong first stage: tests include an irrelevant instrument. Under heteroskedasticity or dependence this classical F calibration is not generally valid. The result classifies only supplied points: a finite grid does not prove the full set bounded or reconstruct all its components.
import numpy as np
from scipy.stats import f


def anderson_rubin_ci(y, x, Z, grid, alpha=.05):
  """Devuelve un booleano por candidato, True si AR no rechaza."""
  pass
Shift+Enter to run

Test reference values are regenerated with the statsmodels joint F test:

[ ]Independent reference for the AR exerciseBrowser
"""Referencia de los tests: F conjunta calculada con statsmodels."""
import numpy as np
import statsmodels.api as sm
from scipy.stats import f

rng_reference = np.random.default_rng(270607)
n_reference = 30
z_reference = rng_reference.normal(size=(n_reference, 2))
u_reference = rng_reference.normal(size=n_reference)
x_reference = (.8*z_reference[:, 0]-.3*z_reference[:, 1]+.7*u_reference+
               rng_reference.normal(size=n_reference))
y_reference = 1+1.2*x_reference+u_reference
grid_reference = np.array([-2., 0., .5, 1., 1.5, 2., 3., 5.])
regressors_reference = sm.add_constant(z_reference)
f_reference = np.array([sm.OLS(y_reference-b*x_reference, regressors_reference).fit().fvalue
                        for b in grid_reference])
critical_reference = f.ppf(.95, 2, n_reference-3)
print('Candidatos:', grid_reference)
print('F AR de statsmodels:', f_reference)
print('Crítico F(2,27), 95 %:', critical_reference)
print('No rechaza:', f_reference <= critical_reference)
[ ]Check Hansen and the simulation critical valueBrowser
from scipy.stats import chi2, f, norm
import numpy as np
J, instruments, endogenous = 7.2, 3, 1
print('J, grados de libertad y valor p:', J, instruments-endogenous,
      chi2.sf(J, instruments-endogenous))
print('Cuantil F(3,116), 95 %:', f.ppf(.95, 3, 116))
print('Cuantil F(1,118), 95 %:', f.ppf(.95, 1, 118))
print('Cuantil normal bilateral, 97,5 %:', norm.ppf(.975))
print('Error Monte Carlo, 95 % de cobertura y 600 réplicas, en puntos:',
      100*np.sqrt(.95*.05/600))