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 prices gross return and is available at decision time, a candidate restriction is . 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 be moment conditions for parameter , with , and . The generalized method of moments minimizes
with symmetric positive-definite . 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 , uniform convergence, regularity and an estimator actually approximating the global minimum. Global identification requires no other satisfy the same restrictions. Locally, matrix 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.
The next cell regenerates the sample underlying the landscape and checks three weights and shifts. The optimal weight uses the generator’s known covariance.
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',[email protected]([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([email protected]([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 , , positive-definite and and full-column-rank . Expanding first-order conditions gives
Thus the asymptotic covariance of is
Approximate covariance of is . If observations are independent, ; with temporal dependence it is long-run covariance, not merely contemporaneous variance. The efficient weight is and yields .
To prove optimality, define and . Both matrices satisfy . If , then and cross terms of vanish because . Thus,
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 generally depends on , first estimate with an initial weight and calculate at the result. The second stage minimizes with fixed. You can repeatedly update 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 must be checked.
For temporal data, define . A Newey-West HAC estimator with Bartlett window uses
Bandwidth controls the bias-variability trade-off; consistency requires an appropriate choice and dependence conditions. Cluster adjustments require another estimate of . Inverting a nearly singular matrix amplifies numerical errors: report the issue rather than hide it.
In stationary series, dependence over time explains why 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 ; exactly identified IV replaces with . Both are method-of-moments conditions. With more instruments, and yield exactly 2SLS:
Under conditional homoskedasticity , and that weight is proportional to the efficient one. Under general heteroskedasticity it need not be. An interior differentiable likelihood maximum satisfies score moment ; 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 , valid moments, strong identification, regularity and a consistent estimate of , the Hansen J test evaluates remaining discrepancy:
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 and , all moments are compatible with even if the causal target were : 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: . Near , minimizing with efficient weight removes the projection of onto columns of . Remaining discrepancy is asymptotically , with an orthogonal projector of rank . The complement has rank , 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 increases; a local-to-zero approximation makes it decrease as . 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 and IV coefficient 0.142; another with 28 reports 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.
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 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 , one HC0 version uses
Here and instruments are residualized against the same controls, and 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 , form and test whether excluded instruments help explain it after controls. If 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 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 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.
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 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.
"""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.
"""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.
"""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([email protected](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.
"""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
Step 1 of 3. What do A_W=(GᵀWG)⁻¹GᵀW and A_*=(GᵀS⁻¹G)⁻¹GᵀS⁻¹ satisfy?
Step 1 of 3. Apart from a positive factor that does not change the minimum, what is the criterion?
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."""
passTest reference values are regenerated with the statsmodels joint F test:
"""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)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))