Module contents
Lesson 7 of 28Core 115 min

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

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 yit=α+xit⊤β+ai+uity_{it}=\alpha+x_{it}^\top\beta+a_i+u_{it} for unit ii and period tt. Unobserved individual heterogeneity aia_i remains constant, while uitu_{it} may change over time. Fixed effects allow correlation between aia_i and the path of xx; random effects restrict that relationship and also use differences between units.

Within, indicators and FWL

Subtracting each unit’s time mean,

y~it=yit−yˉi,x~it=xit−xˉi,y~it=x~it⊤β+(uit−uˉi).\tilde y_{it}=y_{it}-\bar y_i,\qquad \tilde x_{it}=x_{it}-\bar x_i,\qquad \tilde y_{it}=\tilde x_{it}^\top\beta+(u_{it}-\bar u_i).

The within fixed-effects estimator regresses y~\tilde y on X~\tilde X. In matrix form, if DD contains one indicator per unit and MD=I−D(D⊤D)−1D⊤M_D=I-D(D^\top D)^{-1}D^\top,

β^FE=(X⊤MDX)−1X⊤MDy.\hat\beta_{FE}=(X^\top M_DX)^{-1}X^\top M_Dy.

Equality with LSDV, regression of yy on XX and indicators, is an exact application of Frisch-Waugh-Lovell: MDM_D removes projection onto indicators from both sides. It requires rank of MDXM_DX. A regressor constant within each unit disappears even if it differs across units; its separate coefficient is not identified with these fixed effects. For NN observations, GG units and kk independent varying regressors, classical variance uses N−G−kN-G-k degrees of freedom if GG individual intercepts are estimated.

InteractiveWhat the within estimator sees

Each color is a unit observed over eight periods. Demeaning progressively subtracts its own X and Y means; the visible slope changes with the transformation. Axis scales stay fixed during animation.

  • Unit 1
  • Unit 2
  • Unit 3
  • Unit 4
  • Unit 5
−2.72.81.1−1.1Transformed XTransformed Y

Model: aᵢ takes −2, −1, 0, 1 and 2; Xᵢₜ=κaᵢ+0.35vᵢₜ, Yᵢₜ=aᵢ−0.65Xᵢₜ+0.14εᵢₜ. Normal innovations are reproducible with seed 270701 and centered within each unit. LSDV slope is computed separately with five indicators and no additional intercept: it matches within by FWL.

Association between aᵢ and X can bias pooled regression. Demeaning removes each unit’s constant component, not omitted time-varying causes or measurement error; causal interpretation still requires assumptions about errors.

1.0
0 %
Pooled slope0.305
Within slope−0.586
LSDV slope−0.586
Sample correlation of a and X0.976
Visible cloud slope0.305
Center clouds by unit and compare pooled, within and indicator estimates.

A common sufficient condition is strict exogeneity: E[uit∣xi1,…,xiT,ai]=0E[u_{it}\mid x_{i1},\ldots,x_{iT},a_i]=0 for each tt, 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 xx 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 aia_i:

Δyit=Δxit⊤β+Δuit.\Delta y_{it}=\Delta x_{it}^\top\beta+\Delta u_{it}.

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 uu: if uu is iid, Δu\Delta u has negative covariance between adjacent differences; other patterns can favor differences. Using iid standard errors on differences is not automatically correct.

If xx 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 aia_i has variance σa2\sigma_a^2, uitu_{it} variance σu2>0\sigma_u^2>0, idiosyncratic errors are uncorrelated across periods and orthogonal to the individual effect. Within-unit covariance is

Ωi=σu2IT+σa211⊤.\Omega_i=\sigma_u^2I_T+\sigma_a^2\mathbf1\mathbf1^\top.

If aia_i 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

θ=1−σu2σu2+Tσa2,yit∗=yit−θyˉi,xit∗=xit−θxˉi.\theta=1-\sqrt{\frac{\sigma_u^2}{\sigma_u^2+T\sigma_a^2}}, \quad y^*_{it}=y_{it}-\theta\bar y_i,\quad x^*_{it}=x_{it}-\theta\bar x_i.

Transforming the constant too and fitting OLS gives GLS if variances are known; estimated variances give FGLS. If σa2=0\sigma_a^2=0, θ=0\theta=0 and pooled is recovered. With σu2>0\sigma_u^2>0 and finite variances, θ<1\theta<1; it approaches within as a limit. In an unbalanced panel the factor depends on TiT_i. The connection with a hierarchical model helps explain partial pooling, but an RE point estimator and Bayesian posterior distribution are different objects.

InteractiveRandom effects between pooled and within

The horizontal axis shows x−θx̄ᵢ and the vertical y−θȳᵢ. The solid line fits transformed points with an intercept; dashed lines show pooled and within slopes, anchored at the mean of those same points for comparison.

  • Transformed points
  • Pooled slope
  • Within slope
  • RE fit

Deterministic panel with five units: qᵢ takes −1, −0.5, 0, 0.5 and 1; vₜ spans evenly spaced values from −1 to 1; xᵢₜ=qᵢ+0.6vₜ and yᵢₜ=1−xᵢₜ+2qᵢ. The variance controls are working values for constructing θ, not estimates from this panel.

With an intercept and one regressor, slope is [Swithin,xy+(1−θ)²Sbetween,xy]/[Swithin,xx+(1−θ)²Sbetween,xx]. Setting σₐ²=0 gives θ=0 and pooled OLS; θ approaches 1 as individual variance dominates. This geometry does not prove effects are independent of regressors or that RE is causal.

1.0
1.0
5
Quasi-demeaning θ0.592
Pooled slope0.471
RE slope−0.367
Within slope−1.000
Change assumed variances and number of periods and observe quasi-demeaning.

The cell checks slopes of the deterministic panel using independent regressions, including at control extremes.

[ ]Check quasi-demeaningBrowser
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 (1−θ)2(1-\theta)^2. 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 aia_i and regressors. The original formulation is by Hausman.

A Mundlak correlated-random-effects alternative writes ai=xˉi⊤π+cia_i=\bar x_i^\top\pi+c_i and adds unit means. The specification retains E[ci∣xi1,…,xiT]=0E[c_i\mid x_{i1},\ldots,x_{iT}]=0 and strict exogeneity of idiosyncratic error given history and effect. A joint test of π=0\pi=0 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 yit=ρyi,t−1+ai+uity_{it}=\rho y_{i,t-1}+a_i+u_{it}, unit demeaning makes yi,t−1−yˉi,−1y_{i,t-1}-\bar y_{i,-1} relate to uit−uˉiu_{it}-\bar u_i: means include future observations depending on current shocks. FE is therefore biased even if original innovations are independent. Nickell bias persists with G→∞G\to\infty and fixed TT; increasing only the number of units does not fix it.

Approximation −(1+ρ)/(T−1)-(1+\rho)/(T-1) is first-order for a specific regime and assumptions, not an exact identity for every TT. For an exact limit derivation in a stationary case, take T≥2T\ge2 regression pairs (yt−1,yt)(y_{t-1},y_t), ∣ρ∣<1|\rho|<1 and iid innovations of variance σ2>0\sigma^2>0. Assume independent units and stationary initialization conditional on aia_i, independent of future innovations. Then, with M=IT−11⊤/TM=I_T-\mathbf1\mathbf1^\top/T and xt=yt−1x_t=y_{t-1},

E[x⊤Mu]=−σ2T∑k=0T−2(T−1−k)ρk,E[x^\top Mu]=-\frac{\sigma^2}{T} \sum_{k=0}^{T-2}(T-1-k)\rho^k, E[x⊤Mx]=σ21−ρ2[(T−1)−2T∑k=1T−1(T−k)ρk].E[x^\top Mx]=\frac{\sigma^2}{1-\rho^2} \left[(T-1)-\frac{2}{T}\sum_{k=1}^{T-1}(T-k)\rho^k\right].

The law of large numbers across units gives plim⁡ρ^FE=ρ+E[x⊤Mu]/E[x⊤Mx]\operatorname{plim}\hat\rho_{FE}=\rho+E[x^\top Mu]/E[x^\top Mx] if the denominator is positive. The first sum appears because utu_t affect later values of xx included in its mean; the second subtracts autocovariances of the mean of xx. There are T+1T+1 observed states for those TT pairs: changing this convention changes indices. The original source is Nickell.

InteractiveNickell bias as a function of T and ρ

Monte Carlo bias: mean FE minus ρ. Each cell is an independent simulation with 160 replicates of 80 units. Select a cell to see distributions; greater intensity means larger bias magnitude.

ρ / T
3
4
6
8
12
−0.4
0.0
0.4
0.7
0.9

Curves: fraction of 160 replicates per interval. Dashed line marks ρ. Outside axis [−1.5, 2.0]: FE 0 and GMM 0. GMM replicates unresolved due to numerical singularity: 0; they are reported and excluded from medians.

0.640−1.50.01.02.0Estimate of ρ
  • Fixed effects
  • One-step Arellano–Bond

Simulated model: yᵢₜ = αᵢ + ρyᵢ,ₜ₋₁ + uᵢₜ, with independent standard normal αᵢ and errors. Initialize yᵢ₀ = αᵢ/(1−ρ) + vᵢ/√(1−ρ²), with independent standard normal vᵢ. FE uses t=1,…,T. Each difference at t=2,…,T uses instrument yᵢ,ₜ₋₂, with a column for each period.

One-step GMM uses weight [ΣZᵢᵀHZᵢ]⁻¹, where H has 2 on the diagonal and −1 on adjacent diagonals, the covariance of differenced errors under this model. Independent disturbances ensure population moments, but instruments can be weak with short T or high ρ. Finite-sample variance and tails can be large; these results do not guarantee absence of bias in a particular sample.

T regressions per unit4
True ρ0.7
Mean FE bias−0.481
FE median0.219
GMM median0.599
Select a combination and compare simulated within and difference-GMM distributions.

Lags as instruments

Differencing gives Δyit=ρΔyi,t−1+Δuit\Delta y_{it}=\rho\Delta y_{i,t-1}+\Delta u_{it}, but Δyi,t−1\Delta y_{i,t-1} contains ui,t−1u_{i,t-1} and is endogenous relative to Δuit\Delta u_{it}. Under its conditions, Anderson-Hsiao uses a sufficiently lagged level as instrument. Arellano-Bond collects moments such as

E[yi,t−sΔuit]=0,s≥2.E[y_{i,t-s}\Delta u_{it}]=0,\qquad s\ge2.

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 p=0,138p=0{,}138 and the clustered Mundlak-means test gives p=0,018p=0{,}018. 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 estimators and Mundlak in GrunfeldBrowser
"""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 = invr@invr.T
    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(diff@np.linalg.solve(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(eta@np.linalg.solve(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.')
[ ]Compare with MixedLMBrowser
"""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.

[ ]PanelOLS and RandomEffects with linearmodelsLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Anderson-Hsiao and difference GMMBrowser
"""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.')
[ ]Within as T variesBrowser
"""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.')
[ ]Collapsed and uncollapsed instrumentsBrowser
"""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 engine from the previous lessonBrowser
"""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

[ ]Check Arellano-Bond with the GMM engineBrowser
"""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

ProofWithin and dummies
Prove: With one indicator column per entity and full-rank M_DX, show the X slope in dummy regression equals that estimated on entity-demeaned variables.
0
Use FWL and recall that M_D is a symmetric idempotent projector.

Step 1 of 3. What does M_D do to a variable observed in a balanced panel?

ProofNickell bias with fixed T
Prove: For yₜ=ρyₜ₋₁+a+uₜ, |ρ|<1, iid innovations of variance σ² and stationary start conditional on the effect, derive the within limit as units grow with T regression pairs fixed.
0
Write x=(y₀,…,yₜ₋₁), M=I−11ᵀ/T and decompose β̂−ρ.

Step 1 of 5. Which ratio determines the shift from ρ?

NumericRE quasi-demeaning
In a balanced panel, σₐ²=2, σᵤ²=1 and T=5. What is θ? Give four decimal places.
QuizRepositories with fixed heterogeneity
You want to compare changes within repositories differing in constant technical culture potentially correlated with adoption. Which approach best addresses that initial concern?
QuizRandom effects and levels
You care about variables unchanged over time and can defend independence of individual effect from the entire regressor path. Which approach can use that variation?
QuizTwo periods
A balanced panel has two observations per unit, the same sample and an equivalent specification. How do first differences and within relate?
QuizLagged outcome
In a short panel with lagged outcome, serially uncorrelated original errors and appropriate initial conditions, what strategy deserves evaluation for the dynamic problem?
CodeSwamy-Arora random effects
Implement random_effects(df, y, X, entity) for Swamy-Arora in a balanced panel with an explicit intercept. df is a DataFrame with two-level MultiIndex: the first is named entity and the second represents period. Observations of every entity must share exactly the same periods; reject duplicate or incomplete indices. y names the dependent column, X lists numeric columns whose first column is a constant of ones, and entity names the first level. Calculate within and between residuals, use their degrees of freedom to estimate idiosyncratic and individual variance, truncate the latter at zero, quasi-demean and return a dictionary with beta (in X order), theta, sigma2_a and sigma2_u. Reject nonfinite values, unbalanced panels, designs lacking full total, within or between rank, insufficient degrees of freedom and degenerate idiosyncratic variance. This exercise requires full rank between units and for nonconstant columns within units. An intercept alone is valid too. Test references were calculated with linearmodels 7.1 from the same reproducible samples, but tests use only NumPy and pandas to run in Pyodide. They do not assume MixedLM matches Swamy-Arora.
import numpy as np
import pandas as pd

def random_effects(df, y, X, entity):
  pass
Shift+Enter to run

This local cell independently reproduces test references with linearmodels:

[ ]RE exercise referencesLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Check θ and the Nickell limitBrowser
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)