Panel data: fixed effects, random effects and dynamic panels
Use repeated observations to study fixed, first-difference and random effects, Hausman and Mundlak diagnostics, clustered panel inference, Nickell bias and dynamic-panel GMM.
After this lesson you can
- Derive the within estimator by FWL and prove equivalence to LSDV.
- Compare within and first differences under error structures and strict exogeneity.
- Derive random effects as FGLS with quasi-demeaning and parameter θ.
- Compare fixed and random effects using Hausman and clustered Mundlak tests.
- Demonstrate Nickell bias and implement Arellano-Bond estimation in a simulated dynamic panel.
Before you start
- 27Generalized least squaresCluster-robust inferenceOmitted variable biasGeneralized method of momentsFrisch-Waugh-Lovell theoremDurbin-Wu-Hausman testMeasurement error and attenuation bias
- 00Split-apply-combine (groupby)pandas indexes and automatic alignment
- 14Partial pooling and shrinkageBayesian hierarchical model
Comparing a unit with itself
You want to measure whether adopting static analysis reduces failures per repository. Adopting repositories may already differ: perhaps they have better practices or more experienced teams. Comparing them at one time mixes those differences with the change of interest. Observing each repository across periods lets you separate its constant level and ask how failures vary when tool use changes.
That does not resolve all causality. A process improvement may coincide with adoption, or adoption may respond to earlier failures. A panel removes certain constant factors under an explicit model; it does not turn an observed change into a randomized intervention.
Write for unit and period . Unobserved individual heterogeneity remains constant, while may change over time. Fixed effects allow correlation between and the path of ; random effects restrict that relationship and also use differences between units.
Within, indicators and FWL
Subtracting each unit’s time mean,
The within fixed-effects estimator regresses on . In matrix form, if contains one indicator per unit and ,
Equality with LSDV, regression of on and indicators, is an exact application of Frisch-Waugh-Lovell: removes projection onto indicators from both sides. It requires rank of . A regressor constant within each unit disappears even if it differs across units; its separate coefficient is not identified with these fixed effects. For observations, units and independent varying regressors, classical variance uses degrees of freedom if individual intercepts are estimated.
A common sufficient condition is strict exogeneity: for each , in addition to within variation and regularity. It is stronger than requiring zero contemporaneous correlation. If a failure shock drives adoption in later periods, means of and error may relate after centering. Fixed effects also do not remove a common cause that changes over time.
First differences and measurement error
First differences remove the same :
With two observations per unit, the same sample and equivalent specification, within and differences give exactly the same slopes: the two within residuals are differences with opposite signs divided by two. With more periods transformations weight different temporal combinations and need not coincide. Relative efficiency depends on structure of : if is iid, has negative covariance between adjacent differences; other patterns can favor differences. Using iid standard errors on differences is not automatically correct.
If has measurement error, differencing can remove persistent signal and increase relative noise. Bias direction and magnitude depend on variances, autocorrelations and relationships with structural error: no universal rule holds without additional assumptions.
Random effects as GLS
In a balanced panel, suppose has variance , variance , idiosyncratic errors are uncorrelated across periods and orthogonal to the individual effect. Within-unit covariance is
If is also uncorrelated with the entire regressor path and idiosyncratic error satisfies relevant exogeneity, random effects apply GLS to this matrix. For usual GLS efficiency, composite covariance must have the stated form conditional on regressors too, not just unconditionally. GLS quasi-demeaning uses
Transforming the constant too and fitting OLS gives GLS if variances are known; estimated variances give FGLS. If , and pooled is recovered. With and finite variances, ; it approaches within as a limit. In an unbalanced panel the factor depends on . The connection with a hierarchical model helps explain partial pooling, but an RE point estimator and Bayesian posterior distribution are different objects.
The cell checks slopes of the deterministic panel using independent regressions, including at control extremes.
import numpy as np
def slopes(T, variance_a, variance_u):
q=np.array([-1.,-.5,0.,.5,1.])
v=np.linspace(-1.,1.,T)
x=q[:,None]+.6*v[None,:]
y=1-x+2*q[:,None]
theta=1-np.sqrt(variance_u/(variance_u+T*variance_a))
xq=x-theta*x.mean(axis=1,keepdims=True)
yq=y-theta*y.mean(axis=1,keepdims=True)
def regression(a,b):
A=np.column_stack((np.ones(a.size),a.ravel()))
return np.linalg.lstsq(A,b.ravel(),rcond=None)[0][1]
pooled=regression(x,y)
re=regression(xq,yq)
within=regression(x-x.mean(axis=1,keepdims=True),y-y.mean(axis=1,keepdims=True))
sw=np.sum((x-x.mean(axis=1,keepdims=True))**2)
sb=T*np.sum((x.mean(axis=1)-x.mean())**2)
analytic=(-sw+(1-theta)**2*sb)/(sw+(1-theta)**2*sb)
assert np.allclose(re,analytic)
assert np.isclose(within,-1.)
return theta,pooled,re,within
for T in (2,5,10):
for sa,su in ((0.,1.),(1.,1.),(4.,.2)):
print('T, varianzas, θ y pendientes:',T,sa,su,*slopes(T,sa,su))For one regressor and intercept, RE slope is a sum-of-squares-weighted average of within and between slopes, with between weight proportional to . This scalar interpretation does not mean every multiple-regression coefficient moves monotonically between endpoints. Interactive variances are working assumptions, not estimates from its synthetic panel.
Hausman, Mundlak and dependence
The classical Hausman test compares FE and RE under the null that both are consistent and RE efficient in the maintained model. Their covariance difference can be nonpositive in finite samples, and naive subtraction of robust or clustered matrices is generally not a valid test. A nonsignificant result does not prove independence of and regressors. The original formulation is by Hausman.
A Mundlak correlated-random-effects alternative writes and adds unit means. The specification retains and strict exogeneity of idiosyncratic error given history and effect. A joint test of with clustered covariance assesses that restriction within the chosen conditional-mean form. It detects neither every form of dependence nor proves causality. See Mundlak.
For common shocks, include unit and period effects, accounting for redundant categories and rank. Clustering by unit permits arbitrary within-unit dependence under independence between groups and sufficiently many groups. Clustering by period addresses another pattern; two-way covariance combines both and subtracts their intersection contribution. With few groups the asymptotic approximation can be fragile. See clustered inference before interpreting a p-value.
In pandas, an entity-period index helps retain observation alignment while grouping and differencing. In finance you will also encounter Fama-MacBeth regressions on panel returns: their average of cross-sectional regressions is a different construction and not automatically equivalent to FE.
Dynamic panels and Nickell
In , unit demeaning makes relate to : means include future observations depending on current shocks. FE is therefore biased even if original innovations are independent. Nickell bias persists with and fixed ; increasing only the number of units does not fix it.
Approximation is first-order for a specific regime and assumptions, not an exact identity for every . For an exact limit derivation in a stationary case, take regression pairs , and iid innovations of variance . Assume independent units and stationary initialization conditional on , independent of future innovations. Then, with and ,
The law of large numbers across units gives if the denominator is positive. The first sum appears because affect later values of included in its mean; the second subtracts autocovariances of the mean of . There are observed states for those pairs: changing this convention changes indices. The original source is Nickell.
Lags as instruments
Differencing gives , but contains and is endogenous relative to . Under its conditions, Anderson-Hsiao uses a sufficiently lagged level as instrument. Arellano-Bond collects moments such as
These moments require restrictions on initial conditions and serial correlation, not merely an old lag. Differenced iid errors have first-order correlation by construction; second-order correlation in differences is a relevant diagnostic of failures of usual conditions, not a validity certificate. Many instruments can overfit and weaken tests: limit lags and compare a collapsed matrix. Arellano and Bond develop estimation and tests.
In two stages, the moment matrix is estimated and naive asymptotic standard errors can be unreliable in finite samples. The lab compares estimates but does not calculate the Windmeijer correction or AR(2) or Hansen tests; do not present those quantities as checked.
Lab: Grunfeld
In the GLS lesson you worked with three Grunfeld firms; here the full statsmodels dataset is used, with 11 firms and 20 years per firm. Slopes are descriptive. The first cell calculates all estimators and Mundlak with CR1; the second compares with maximum-likelihood MixedLM, whose variances need not match Swamy-Arora.
With 220 observations in this specification, within obtains approximate slopes 0.110 for value and 0.310 for capital; RE obtains 0.109 and 0.308. Classical Hausman gives and the clustered Mundlak-means test gives . These are not identical versions of one test, and with only 11 firms the cluster reference is especially uncertain. The statsmodels-distributed dataset documents provenance and variables.
"""Panel de Grunfeld: pooled, within, primeras diferencias, between y RE.
Swamy-Arora para un panel equilibrado con constante. No interpreta las
pendientes como causales. La celda usa los datos incluidos en statsmodels.
"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.stats import chi2
panel = sm.datasets.grunfeld.load_pandas().data.copy()
panel = panel.sort_values(['firm', 'year']).reset_index(drop=True)
if panel.duplicated(['firm', 'year']).any():
raise ValueError('Cada entidad y año debe aparecer una sola vez')
counts = panel.groupby('firm', sort=True).size()
if counts.nunique() != 1:
raise ValueError('Esta implementación de Swamy-Arora exige panel equilibrado')
groups = panel['firm'].to_numpy()
variables = ['value', 'capital']
G, T, N = len(counts), int(counts.iloc[0]), len(panel)
y = panel['invest'].to_numpy(float)
X = np.column_stack((np.ones(N), panel[variables].to_numpy(float)))
labels, group = np.unique(groups, return_inverse=True)
def entity_means(values, group):
values = np.asarray(values)
return np.stack([values[group == g].mean(axis=0) for g in np.unique(group)])
def cluster_cov(X, residual, group, df_residual):
# CR1 para G clústeres: corrección explícita G/(G−1)*(N−1)/df.
Q, R = np.linalg.qr(X, mode='reduced')
invr = np.linalg.solve(R, np.eye(R.shape[0]))
bread = [email protected]
scores = np.vstack([X[group == g].T@residual[group == g] for g in np.unique(group)])
ngroups = len(np.unique(group))
return (ngroups/(ngroups-1)*(len(residual)-1)/df_residual)*bread@(scores.T@scores)@bread
ymean, xmean = entity_means(y, group), entity_means(X, group)
yc, xc = y-ymean[group], X[:, 1:]-xmean[group, 1:]
k = xc.shape[1]
beta_within = np.linalg.lstsq(xc, yc, rcond=None)[0]
within_resid = yc-xc@beta_within
df_within = N-G-k
sigma_e = float(within_resid@within_resid/df_within)
cov_fe = sigma_e*np.linalg.inv(xc.T@xc)
cov_fe_cluster = cluster_cov(xc, within_resid, group, df_within)
beta_pooled = np.linalg.lstsq(X, y, rcond=None)[0]
beta_between = np.linalg.lstsq(xmean, ymean, rcond=None)[0]
between_resid = ymean-xmean@beta_between
sigma_a = max(0.,float(between_resid@between_resid/(G-X.shape[1])-sigma_e/T))
theta = 1-np.sqrt(sigma_e/(sigma_e+T*sigma_a))
ystar = y-theta*ymean[group]
Xstar = X-theta*xmean[group]
beta_re = np.linalg.lstsq(Xstar, ystar, rcond=None)[0]
resid_re = ystar-Xstar@beta_re
cov_re = (resid_re@resid_re/(N-X.shape[1]))*np.linalg.inv(Xstar.T@Xstar)
# LSDV incluye una dummy para cada empresa y omite el intercepto común.
dummies = np.eye(G)[group]
lsdv = np.column_stack((dummies, X[:, 1:]))
beta_lsdv = np.linalg.lstsq(lsdv, y, rcond=None)[0][-k:]
assert np.allclose(beta_lsdv, beta_within, atol=1e-9)
# Orden cronológico, una diferencia por entidad desde la segunda observación.
delta_y = panel.groupby('firm', sort=False)['invest'].diff().to_numpy()
delta_x = panel.groupby('firm', sort=False)[variables].diff().to_numpy()
mask = np.isfinite(delta_y)
beta_fd = np.linalg.lstsq(delta_x[mask], delta_y[mask], rcond=None)[0]
# Hausman clásico solo si la diferencia estimada es positiva definida.
diff = beta_within-beta_re[1:]
Vdiff = (cov_fe-cov_re[1:, 1:]); Vdiff = (Vdiff+Vdiff.T)/2
eig = np.linalg.eigvalsh(Vdiff)
if np.min(eig) > 0:
hausman = float([email protected](Vdiff, diff))
print('Hausman clásico, chi2(2) y p:', hausman, chi2.sf(hausman, k))
else:
print('Hausman clásico indefinido: diferencia de covarianzas no positiva:', eig)
# Mundlak: medias de covariables como términos adicionales y CR1 agrupado.
XM = np.column_stack((X, xmean[group, 1:]))
bm = np.linalg.lstsq(XM, y, rcond=None)[0]
um = y-XM@bm
vm = cluster_cov(XM, um, group, N-XM.shape[1])
eta = bm[-k:]
Veta = vm[-k:, -k:]
wald = float([email protected](Veta, eta))
print('Grunfeld: observaciones, empresas y años por empresa:', N, G, T)
print('Pooled / within / LSDV / diferencias / between:', beta_pooled, beta_within, beta_lsdv, beta_fd, beta_between)
print('Swamy-Arora: varianzas idiosincrática y efecto, theta:', sigma_e, sigma_a, theta)
print('RE cuasi-centrado:', beta_re)
print('EE within por empresa (CR1):', np.sqrt(np.diag(cov_fe_cluster)))
print('Mundlak: coeficientes de medias, Wald agrupado chi2(2) y p:', eta, wald, chi2.sf(wald, k))
print('Solo 11 empresas: las referencias asintóticas agrupadas son frágiles.')"""Contraste con MixedLM; ejecuta antes la celda de Grunfeld."""
import warnings
import numpy as np
import statsmodels.api as sm
with warnings.catch_warnings(record=True) as observed:
warnings.simplefilter('always')
fit = sm.MixedLM(y, X, groups=groups).fit(reml=False, method='lbfgs', maxiter=200, disp=False)
if not fit.converged:
raise RuntimeError('MixedLM no converge')
print('MixedLM ML, intercepto y pendientes:', fit.fe_params)
print('Varianzas efecto / error y convergencia:', np.asarray(fit.cov_re)[0, 0], fit.scale, fit.converged)
print('Avisos:', [str(w.message) for w in observed])
print('ML y Swamy-Arora estiman componentes de varianza de manera distinta.')For a second comparison, run this cell locally with NumPy, pandas, statsmodels and linearmodels installed. It reloads data and therefore does not depend on working files or browser session.
import numpy as np
import statsmodels.api as sm
from linearmodels.panel import PanelOLS, RandomEffects, FirstDifferenceOLS, BetweenOLS
d=sm.datasets.grunfeld.load_pandas().data.sort_values(['firm','year'])
d=d.set_index(['firm','year'])
d['const']=1.
y_lm=d['invest']
X_lm=d[['const','value','capital']]
fe_lm=PanelOLS(y_lm,X_lm,entity_effects=True).fit()
re_lm=RandomEffects(y_lm,X_lm).fit()
fd_lm=FirstDifferenceOLS(y_lm,X_lm[['value','capital']]).fit()
between_lm=BetweenOLS(y_lm,X_lm).fit()
print('PanelOLS within:',fe_lm.params.to_numpy())
print('RandomEffects y theta:',re_lm.params.to_numpy(),re_lm.theta.iloc[0,0])
print('Primeras diferencias:',fd_lm.params.to_numpy())
print('Between:',between_lm.params.to_numpy())npm run lab and open the connection link.Lab: dynamic panel
The simulated panel starts in the stationary distribution conditional on individual effect. First calculate within, Anderson-Hsiao and one- and two-step Arellano-Bond and compare with statsmodels; then examine T and instrument proliferation. Run cells in order. The code takes T as the number of observed states, so within uses T−1 equations.
"""Panel AR(1) y GMM en diferencias; datos simulados por construcción.
El primer dato de cada unidad viene de la distribución estacionaria
condicional a su efecto fijo. No hay constantes temporales ni regresores
adicionales. Los shocks son independientes por unidad y periodo.
"""
import numpy as np
from statsmodels.sandbox.regression.gmm import GMM as StatsGMM
def simulate_dynamic(n, periods, rho, rng):
if n < 2 or periods < 3 or abs(rho) >= 1:
raise ValueError('Se requieren n >= 2, T >= 3 y |rho| < 1')
a = rng.normal(size=n)
y = np.empty((n, periods))
y[:, 0] = a/(1-rho) + rng.normal(size=n)/np.sqrt(1-rho*rho)
shocks = rng.normal(size=(n, periods-1))
for t in range(1, periods):
y[:, t] = rho*y[:, t-1] + a + shocks[:, t-1]
return y
def within_dynamic(y):
x, outcome = y[:, :-1], y[:, 1:]
x = x-x.mean(axis=1, keepdims=True)
outcome = outcome-outcome.mean(axis=1, keepdims=True)
return float(np.sum(x*outcome)/np.sum(x*x))
def instruments_dynamic(y, max_lag, collapsed=True):
"""Filas por unidad, columnas temporales y momentos por instrumento.
En la ecuación del periodo t se permite y[t-lag] para lag >= 2.
Colapsar suma, en una misma columna, los momentos de igual rezago.
Sin colapsar hay una columna distinta por pareja (t, lag).
"""
n, periods = y.shape
if not 2 <= max_lag < periods:
raise ValueError('max_lag debe estar entre 2 y T-1')
m = periods-2
keys = list(range(2, max_lag+1)) if collapsed else [
(t, lag) for t in range(2, periods)
for lag in range(2, min(max_lag, t)+1)]
index = {key: j for j, key in enumerate(keys)}
z = np.zeros((n, m, len(keys)))
for t in range(2, periods):
for lag in range(2, min(max_lag, t)+1):
key = lag if collapsed else (t, lag)
z[:, t-2, index[key]] = y[:, t-lag]
x = y[:, 1:-1]-y[:, :-2]
outcome = y[:, 2:]-y[:, 1:-1]
return outcome, x, z
def dynamic_gmm(y, max_lag, collapsed=True):
"""GMM lineal de una y dos etapas con momentos agregados por unidad.
La ponderación inicial usa H = D D' para shocks homocedásticos sin
correlación serial. La segunda usa la covarianza empírica de momentos
de la primera etapa, sin corrección de Windmeijer ni inferencia aquí.
"""
outcome, x, z = instruments_dynamic(y, max_lag, collapsed)
n, m, q = z.shape
if q >= n:
raise ValueError('Demasiados momentos para la covarianza de n unidades')
H = 2*np.eye(m)-np.eye(m, k=1)-np.eye(m, k=-1)
S0 = np.einsum('imq,mr,irk->qk', z, H, z)/n
zx = np.einsum('imq,im->q', z, x)/n
zy = np.einsum('imq,im->q', z, outcome)/n
def solve_with(S):
if np.linalg.matrix_rank(S) < q:
raise ValueError('Matriz de ponderación singular')
sx = np.linalg.solve(S, zx)
sy = np.linalg.solve(S, zy)
if abs(float(zx@sx)) < 1e-12:
raise ValueError('Primera etapa sin rango')
return float(zx@sy/(zx@sx))
first = solve_with(S0)
g = np.einsum('imq,im->iq', z, outcome-first*x)
g = g-g.mean(axis=0)
S1 = g.T@g/n
second = solve_with(S1)
return first, second, z, S0, S1
rng_dynamic = np.random.default_rng(270701)
rho_true, n_dynamic, T_dynamic = .6, 500, 8
y_dynamic = simulate_dynamic(n_dynamic, T_dynamic, rho_true, rng_dynamic)
ah, ah_two, _, _, _ = dynamic_gmm(y_dynamic, max_lag=2, collapsed=True)
first, second, Z, S0, S1 = dynamic_gmm(y_dynamic, max_lag=4, collapsed=True)
print('rho verdadero y within:', rho_true, within_dynamic(y_dynamic))
print('Anderson-Hsiao, una y dos etapas:', ah, ah_two)
print('Arellano-Bond colapsado, una y dos etapas, q:', first, second, Z.shape[2])
# Implementación independiente de las mismas condiciones de momento y pesos.
dy_ref, dx_ref, z_ref = instruments_dynamic(y_dynamic, 4, True)
class DynamicStats(StatsGMM):
def momcond(self, params):
return np.einsum('imq,im->iq', z_ref, dy_ref-params[0]*dx_ref)
reference = DynamicStats(np.zeros(n_dynamic), np.ones((n_dynamic, 1)),
np.ones((n_dynamic, Z.shape[2])),
k_moms=Z.shape[2], k_params=1)
for estimate, S in ((first, S0), (second, S1)):
ref = reference.fitgmm(np.array([.3]), weights=np.linalg.inv(S),
optim_method='nm',
optim_args={'disp': False, 'xtol': 1e-9, 'ftol': 1e-12})
assert np.allclose(estimate, ref[0], atol=2e-5)
print('GMM propia / statsmodels:', estimate, ref[0])
assert np.allclose(ah, ah_two)
print('AH usa un único instrumento y está exactamente identificado.')"""La misma distribución condicional para varios T.
T cuenta todos los datos de y, incluido el dato inicial; el estimador usa
T-1 ecuaciones. Es una simulación de una muestra por T, no una prueba.
"""
rng_nickell = np.random.default_rng(270702)
for T_nickell in (6, 12, 30):
panel_nickell = simulate_dynamic(5000, T_nickell, .6, rng_nickell)
value_nickell = within_dynamic(panel_nickell)
print('T observado, ecuaciones, within, error frente a rho:',
T_nickell, T_nickell-1, value_nickell, value_nickell-.6)
print('El sesgo se atenúa al crecer T en este diseño; la muestra sigue siendo finita.')"""Comparación Monte Carlo de instrumentos colapsados y sin colapsar.
Los pares usan exactamente el mismo panel en cada réplica. Esto ilustra
el diseño fijado y no demuestra que más instrumentos siempre sesguen.
"""
rng_many = np.random.default_rng(270703)
N_many, T_many, R_many, rho_many = 100, 8, 60, .6
results_many = []
for repetition in range(R_many):
panel_many = simulate_dynamic(N_many, T_many, rho_many, rng_many)
one_c, two_c, z_c, _, _ = dynamic_gmm(panel_many, T_many-1, True)
one_u, two_u, z_u, _, _ = dynamic_gmm(panel_many, T_many-1, False)
results_many.append([one_c, two_c, one_u, two_u])
results_many = np.asarray(results_many)
print('N, T, réplicas, rho:', N_many, T_many, R_many, rho_many)
print('Número de instrumentos colapsados / sin colapsar:', z_c.shape[2], z_u.shape[2])
print('Medias: una y dos etapas colapsado, una y dos sin colapsar:', results_many.mean(axis=0))
print('Sesgos Monte Carlo:', results_many.mean(axis=0)-rho_many)
print('Error Monte Carlo de las medias:', results_many.std(axis=0, ddof=1)/np.sqrt(R_many))
paired = results_many[:, 2:4]-results_many[:, :2]
print('Diferencia apareada sin colapsar menos colapsado, etapas 1 y 2:', paired.mean(axis=0))
print('Error Monte Carlo de las diferencias apareadas:', paired.std(axis=0, ddof=1)/np.sqrt(R_many))
print('Diagnósticos AR(2), Hansen y corrección de Windmeijer no se calculan en este ejemplo.')The following definition reproduces the previous lesson’s engine so this page runs independently. Panel moments are aggregated by unit, preserving temporal dependence within each unit.
"""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
"""Reutiliza GMM definido en la celda «Motor GMM» de m27-l06.
Primero ejecuta esa celda vigente y la celda que define dynamic_gmm.
Cada fila de momentos corresponde a una unidad completa y conserva las
dependencias temporales dentro de ella. No se aplica HAC entre unidades.
"""
dy_panel, dx_panel, z_panel = instruments_dynamic(y_dynamic, 4, True)
def moments_panel(theta):
return np.einsum('imq,im->iq', z_panel, dy_panel-theta[0]*dx_panel)
model_panel = GMM(moments_panel, [0.3], weight=np.linalg.inv(S0), lags=0)
first_panel = model_panel.fit(updates=0)
second_panel = model_panel.fit(updates=1)
assert np.allclose(first_panel[0][0], first, atol=2e-5)
assert np.allclose(second_panel[0][0], second, atol=2e-5)
print('AB etapa 1: forma lineal / motor de m27-l06:', first, first_panel[0][0])
print('AB etapa 2: forma lineal / motor de m27-l06:', second, second_panel[0][0])
print('El motor estima S con momentos centrados por unidad, como dynamic_gmm.')
print('La covarianza de dos etapas es asintótica y no incluye Windmeijer.')Exercises
Step 1 of 3. What does M_D do to a variable observed in a balanced panel?
Step 1 of 5. Which ratio determines the shift from ρ?
import numpy as np
import pandas as pd
def random_effects(df, y, X, entity):
passThis local cell independently reproduces test references with linearmodels:
import numpy as np
import pandas as pd
from linearmodels.panel import RandomEffects
def fixture(kind):
rng=np.random.default_rng(270707)
G,T=24,5
index=pd.MultiIndex.from_product([range(G),range(T)],names=['entity','time'])
x=rng.normal(size=(G,T,2))
u=rng.normal(scale=.6,size=(G,T))
if kind=='positive':
effects=rng.normal(scale=1.2,size=G)[:,None]
else:
effects=np.zeros((G,1)); u=u-u.mean(axis=1,keepdims=True)
y=1.5+.7*x[:,:,0]-.3*x[:,:,1]+effects+u
return pd.DataFrame({'const':1.,'x1':x[:,:,0].ravel(),'x2':x[:,:,1].ravel(),'y':y.ravel()},index=index)
for kind in ('positive','truncated'):
df=fixture(kind)
ref=RandomEffects(df.y,df[['const','x1','x2']]).fit()
print(kind,'beta',ref.params.to_numpy().tolist(),'theta',float(ref.theta.iloc[0,0]),'decomp',ref.variance_decomposition.to_dict())npm run lab and open the connection link.import numpy as np
theta_example=1-np.sqrt(1/(1+5*2))
rho,T=.6,4
numerator=-sum((T-1-k)*rho**k for k in range(T-1))/T
denominator=((T-1)-(2/T)*sum((T-k)*rho**k for k in range(1,T)))/(1-rho**2)
print('theta con varianzas 2 y 1, T=5:',theta_example)
print('Nickell: rho, T pares, numerador, denominador, límite within:',
rho,T,numerator,denominator,rho+numerator/denominator)