Staggered difference-in-differences: the TWFE problem and modern estimators
Staggered adoption with heterogeneous effects can make two-way fixed effects compare late-treated units with already-treated controls. Derive Goodman–Bacon and cell weights, then study cohort ATT, interaction-weighted event studies, and imputation.
After this lesson you can
- Derive the Goodman–Bacon decomposition and identify comparisons with already-treated controls.
- Construct an example where TWFE has the opposite sign to all true effects.
- Implement cohort ATT aggregation and imputation from scratch.
- Explain event-study contamination and the Sun–Abraham approach.
- Choose never-treated or not-yet-treated controls and an estimator for the design.
Before you start
The control already received the tool
An organization deploys an AI tool to teams at different dates. Productivity rises after adoption in all teams, but not necessarily at the same rate. A regression with team and period fixed effects can yield a negative coefficient: to evaluate late teams it compares their change with teams that have already used the tool for some time. If the latter’s effect keeps growing, their change does not represent untreated evolution.
With two groups and two periods, the interaction reproduces the difference in changes. Now there are many comparisons and some use treated units as controls. To decide whether an estimate has a causal interpretation, know who is compared with whom and which effect is summarized.
Cohorts, timing, and assumptions
In absorbing staggered adoption, is the first period unit is treated and indicates no treatment during the window. Write for the outcome if treatment starts at and for the untreated outcome throughout the window. For , the cohort-period effect is
Consistency links observed outcomes to the regime followed and no anticipation equates outcomes before under both regimes. A parallel-trends condition compares the mean change in for cohort with eligible controls, perhaps conditional on prior covariates. Not-yet-treated cohorts are controls in only if they do not anticipate and adopt after ; without appropriate controls or extra assumptions that cell is not identified. Relevant support and no interference are also required.
Goodman–Bacon comparisons
The Goodman–Bacon decomposition expresses the TWFE treatment coefficient as an average of two-group, two-time-block DiD contrasts in a balanced panel, without time-varying covariates and with absorbing binary treatment. Consider early cohort , late cohort , and never-treated . Blocks are before , between and , and after . Four types appear:
- Early versus never-treated, before and after .
- Late versus never-treated, before and after .
- Early versus not-yet-treated late, between the prior and middle blocks.
- Late versus already-treated early, between middle and later blocks.
In the last contrast control change includes change in its treatment effect. It can cancel if that effect is constant across blocks, but contaminates the comparison if it evolves. These comparison weights are nonnegative and sum to one. Their values depend on cohort sizes and temporal variation in residualized treatment, not whether the contrast is causally clean. See Goodman-Bacon (2021).
To see the weights’ origin, let be unit proportions and the fractions of periods treated for early and late cohorts. Without covariates and with a balanced panel, unnormalized early-versus-never and late-versus-never weights are and . Early versus not-yet-treated late and late versus already-treated early weights respectively are
The sum of these terms is the variance of residualized against unit and time effects; dividing each term by the sum yields average weights. The identity follows by expanding numerator and denominator of the residualized regression by cohort pairs and separating blocks where relative treatment changes. The next cell computes both these terms and the fixed-effects regression and checks equality with unequal sizes too. With covariates or missing observations, these simplified formulas do not transfer without justifying the corresponding decomposition.
In the lab, three equally sized cohorts are observed in ; adoptions are , and never. All untreated outcomes are zero and early effects are ; the late effect is . The four contrasts in the above order are with weights . Their average is even though all four treated effects are positive. The final comparison subtracts early-effect growth from the late effect.
Another average, different weights
The preceding decomposition differs from expressing the coefficient as a weighted sum of treated-cell effects. Residualize against unit and period fixed effects and denote the residual . By Frisch–Waugh–Lovell,
In the deterministic example, and weights of the four treated cells are . They sum to one, but the final early cell receives negative weight: . Noisy samples also contain a counterfactual term; causal assumptions control its population contribution, not remove it algebraically in each sample. Negative weights on effects are studied by de Chaisemartin and D’Haultfœuille (2020). These are not negative weights on Goodman–Bacon comparisons.
Estimate each ATT first
Callaway and Sant’Anna estimate each through a comparison retaining untreated controls. With panel data, no covariates, and base , a post-period cell estimate is
may be the never-treated group or cohorts not yet treated in , excluding the cohort itself and those anticipating. Each choice requires its own parallel-trends and support conditions. With covariates, the previous lesson’s doubly robust estimator can be applied to each comparison: propensity and counterfactual-change regression are fitted within that cell’s eligible set. Correctness of one nuisance model does not repair anticipation, spillovers, or false conditional parallelism. See Callaway and Sant’Anna (2021).
Make that normalization explicit. Restrict the population to or , write , , and . If , the population mean of the following contrast identifies the cell under causal and support assumptions:
If is correct, control residual has mean zero and the treated part subtracts its counterfactual change. If is correct, weighted controls and treated units have the same distribution of , so any contribution cancels. In a sample replace expectations with means and estimate nuisances; inference has its own regularity conditions. The lab uses nuisances known by construction to isolate this property, not as information available in an application.
Then aggregate with explicit weights. A dynamic effect at horizon averages across cohorts observed at that horizon; a calendar effect fixes ; a cohort effect averages its post-periods; an overall effect combines exposures. If contributing cohorts change with , the curve can change through composition even when individual effects are constant. Compare the same population when the question demands pure dynamics.
Cells share controls and their estimates are correlated. Aggregate uncertainty requires their covariance or a valid joint procedure. The lab applies unit multipliers to the influence vector and calculates a simultaneous band; justification requires enough independent units under the simulated model. If treatment is assigned to regions, clustering and the number of regions are decisive.
Event studies without contamination
The conventional TWFE event study includes an indicator per relative time and an omitted reference. With staggered adoption and heterogeneity, a horizon coefficient can mix effects from other cohorts and horizons. Apparent pretrends may even appear through that mixture. Sun and Abraham propose cohort-by-relative-time interactions aggregated with cohort weights: the interaction-weighted estimator avoids that contamination under its assumptions and eligible controls. Align reference, sample, and cohorts before comparing curves.
The lab builds a second explicit panel to show the difference; pretreatment coefficients are zero in the model, although conventional fitting may show nonzero values. A pretest does not prove future parallel trends, as seen in the single-cohort event study.
Impute the untreated outcome
The Borusyak, Jaravel and Spiess imputation estimator fits the untreated-outcome model using only untreated observations; it predicts that outcome for treated observations and aggregates treated residuals according to the estimand. Fixed effects used in prediction must be identified from untreated data: if no control remains in a period, its time effect is not identified without additional restrictions.
Method efficiency is formulated under the model and error assumptions of the theoretical result, not every dependence pattern. Prior-trend checking is separate from estimation so the estimator is not selected after a pretest. See Borusyak, Jaravel and Spiess (2024).
The methods in this lesson assume absorbing binary adoption. A continuous dose, repeated changes, or treatment reversal require defining effects and controls for those trajectories; changing the indicator in the same regression does not inherit these interpretations.
Lab: decompose, estimate, and aggregate
The following cells generate all data. The first noiseless panel checks identities exactly; reproducible noise is then added to distinguish population equality from sample coincidence. Do not confuse inference with deterministic identities.
First decompose the deterministic panel and compare its coefficient with regression and cell weights.
import numpy as np
def descomponer_bacon(resultados, adopcion, tamanos):
"""Panel equilibrado, tratamiento absorbente binario, sin covariables.
Una fila por cohorte, una columna por periodo; las entradas son medias
de cohorte, y tamanos da el número de unidades de cada cohorte.
La categoría sin tratamiento se representa mediante np.inf.
"""
y = np.asarray(resultados,dtype=float)
cohort = np.asarray(adopcion,dtype=float)
n = np.asarray(tamanos,dtype=float)
if y.ndim != 2 or len(cohort) != len(y) or len(n) != len(y):
raise ValueError('Dimensiones incompatibles')
if not np.isfinite(y).all() or not np.isfinite(n).all() or np.any(n<=0):
raise ValueError('Medias y tamaños deben ser finitos, con tamaños positivos')
T = y.shape[1]
finite = np.isfinite(cohort)
if np.isnan(cohort).any() or np.isneginf(cohort).any() or np.sum(~finite)>1 or len(np.unique(cohort))!=len(cohort):
raise ValueError('Cada cohorte debe ser única, con como máximo una nunca tratada')
if np.any((cohort[finite] < 1)|(cohort[finite]>=T)|(cohort[finite]!=np.floor(cohort[finite]))):
raise ValueError('Cada cohorte tratada necesita periodos antes y después')
treated = np.flatnonzero(finite)
if not len(treated): raise ValueError('Sin cohortes tratadas')
shares = n/n.sum()
D = (np.arange(T)[None,:]>=cohort[:,None]).astype(float)
group_avg = D.mean(axis=1,keepdims=True)
time_avg = np.sum(shares[:,None]*D,axis=0,keepdims=True)
overall = float(np.sum(shares[:,None]*D)/T)
residual = D-group_avg-time_avg+overall
variance = float(np.sum(shares[:,None]*residual**2)/T)
if variance <= 0: raise ValueError('El tratamiento residual no varía')
beta = float(np.sum(shares[:,None]*residual*y)/(T*variance))
exposure = D.mean(axis=1)
rows = []
def did(treated_group,control_group,before,after):
return float((y[treated_group,after].mean()-y[treated_group,before].mean())
-(y[control_group,after].mean()-y[control_group,before].mean()))
never = np.flatnonzero(~finite)
if len(never):
u = never[0]
for k in treated:
t_k = int(cohort[k])
raw = shares[k]*shares[u]*exposure[k]*(1-exposure[k])
rows.append(('tratada vs nunca',int(cohort[k]),'nunca',
did(k,u,slice(0,t_k),slice(t_k,T)),raw/variance))
for i,first in enumerate(treated):
for second in treated[i+1:]:
k,l = (first,second) if cohort[first]<cohort[second] else (second,first)
early,late = int(cohort[k]),int(cohort[l])
mid = slice(early,late)
late_pre = did(k,l,slice(0,early),mid)
early_post = did(l,k,mid,slice(late,T))
delta = exposure[k]-exposure[l]
early_w = shares[k]*shares[l]*delta*(1-exposure[k])/variance
late_w = shares[k]*shares[l]*exposure[l]*delta/variance
rows.append(('temprana vs tardía',early,late,late_pre,early_w))
rows.append(('tardía vs temprana ya tratada',late,early,early_post,late_w))
return beta,rows,residual,D,variance
# Tres cohortes del mismo tamaño; Y(0)=0 en todos los grupos y periodos.
# En las celdas tratadas todos los efectos verdaderos son positivos.
cohortes = np.array([1,3,np.inf])
tamanos = np.array([10,10,10])
Y = np.array([[0,1,1,20],[0,0,0,1],[0,0,0,0]],dtype=float)
twfe,filas,D_resid,D,V = descomponer_bacon(Y,cohortes,tamanos)
print('ATT verdaderos en celdas tratadas:',Y[D==1])
print('Matriz de tratamiento residualizado:')
print(np.round(D_resid,6))
print('Varianza del tratamiento residualizado:',V)
print('Coeficiente TWFE:',twfe)
print('Comparación | cohorte tratada | control | DiD | peso de Bacon')
for kind,treated,control,value,weight in filas:
print(kind,treated,control,round(value,6),round(weight,6))
print('Suma de pesos:',sum(row[4] for row in filas))
print('Suma ponderada de DiD:',sum(row[3]*row[4] for row in filas))
# Los pesos de efectos cohorte-tiempo son diferentes de los pesos Bacon.
shares = tamanos/tamanos.sum()
cell_weights = shares[:,None]*D_resid*D/(D.shape[1]*V)
print('Pesos de ATT por celda tratada:',np.round(cell_weights[D==1],6))
print('Suma de efectos verdaderos ponderados por celda:',np.sum(cell_weights*Y))
# Verificación por OLS completo sobre unidades individuales y tiempo.
unit_cohort = np.repeat(np.arange(len(cohortes)),tamanos)
unit_y = Y[unit_cohort].reshape(-1)
unit_d = D[unit_cohort].reshape(-1)
N,T = len(unit_cohort),Y.shape[1]
unit_fe = np.repeat(np.eye(N),T,axis=0)[:,1:]
time_fe = np.tile(np.eye(T)[:,1:],(N,1))
X = np.column_stack([np.ones(N*T),unit_fe,time_fe,unit_d])
beta_ols = np.linalg.lstsq(X,unit_y,rcond=None)[0][-1]
print('Verificación OLS con efectos fijos de unidad y tiempo:',beta_ols)
assert np.all(Y[D==1]>0)
assert np.isclose(sum(row[4] for row in filas),1)
assert np.isclose(twfe,sum(row[3]*row[4] for row in filas))
assert np.isclose(twfe,beta_ols)
assert np.isclose(twfe,-0.9)
# Otro panel sin covariables, con tamaños desiguales y resultados arbitrarios.
# Verifica la identidad algebraica sin suponer este patrón concreto de efectos.
rng = np.random.default_rng(272020)
test_y = rng.normal(size=(3,4))
test_beta,test_rows,*_ = descomponer_bacon(test_y,cohortes,[4,7,2])
assert np.isclose(test_beta,sum(row[3]*row[4] for row in test_rows))
print('Verificación adicional de la identidad con cohortes desiguales: correcta')Now explicitly change the late-cohort effect and compare the conventional event study with cohort interactions. References and cohorts contributing at each horizon are shown in output.
# Ejecutar después de bacon_example.py: conserva las cohortes y el panel original.
import numpy as np
unit_cohort = np.repeat(np.arange(len(cohortes)),tamanos)
n_units,T = len(unit_cohort),Y.shape[1]
unit_id = np.repeat(np.arange(n_units),T)
time = np.tile(np.arange(T),n_units)
group = np.repeat(cohortes[unit_cohort],T)
treated_group = np.isfinite(group)
relative = np.full(len(group),np.nan)
relative[treated_group] = time[treated_group]-group[treated_group]
base = np.column_stack([np.ones(len(group)),
np.eye(n_units)[unit_id,1:],
np.eye(T)[time,1:]])
# Interacciones de cada cohorte con su tiempo de evento, salvo k=-1.
labels,interactions = [],[]
for adoption in np.sort(np.unique(group[treated_group])):
for k in np.unique(relative[group==adoption]).astype(int):
if k != -1:
labels.append((int(adoption),int(k)))
interactions.append(((group==adoption)&(relative==k)).astype(float))
X_iw = np.column_stack([base]+interactions)
periods = sorted({k for _,k in labels})
X_twfe = np.column_stack([base]+[((relative==k)&treated_group).astype(float) for k in periods])
def comparar_sun_abraham(y_cohortes,nombre):
observed_y = y_cohortes[unit_cohort].reshape(-1)
b_iw,_,rank_iw,_ = np.linalg.lstsq(X_iw,observed_y,rcond=None)
b_twfe,_,rank_twfe,_ = np.linalg.lstsq(X_twfe,observed_y,rcond=None)
if rank_iw != X_iw.shape[1] or rank_twfe != X_twfe.shape[1]:
raise RuntimeError('Diseño sin rango completo')
cohort_effects = dict(zip(labels,b_iw[-len(labels):]))
pooled = dict(zip(periods,b_twfe[-len(periods):]))
iw = {}
print('\nEscenario:',nombre)
print('k | cohortes incluidas | pesos | interacción ponderada | TWFE convencional')
for k in periods:
eligible = [g for g,event in labels if event==k]
counts = np.array([tamanos[np.flatnonzero(cohortes==g)[0]] for g in eligible],float)
weights = counts/counts.sum()
iw[k] = float(sum(w*cohort_effects[(g,k)] for g,w in zip(eligible,weights)))
print(k,eligible,np.round(weights,3),round(iw[k],6),round(float(pooled[k]),6))
# Verificación independiente de cada interacción mediante las cuatro medias.
never = np.flatnonzero(~np.isfinite(cohortes))[0]
for (adoption,k),value in cohort_effects.items():
g = np.flatnonzero(cohortes==adoption)[0]
ref = adoption-1
t = adoption+k
direct = (y_cohortes[g,t]-y_cohortes[g,ref])-(y_cohortes[never,t]-y_cohortes[never,ref])
assert np.isclose(value,direct,atol=1e-10)
return iw,pooled
# En el ejemplo original las dos cohortes tienen el mismo efecto en k=0:
# por eso los dos estudios de eventos coinciden, aunque TWFE estático sea negativo.
iw_original,pooled_original = comparar_sun_abraham(Y,'panel original de Bacon')
assert all(np.isclose(iw_original[k],pooled_original[k]) for k in periods)
assert np.isclose(iw_original[0],1) and np.isclose(iw_original[1],1) and np.isclose(iw_original[2],20)
# Cambia solo el efecto de la cohorte tardía al inicio: 1 -> 1,5.
# Mantiene los demás efectos, el control nunca tratado y las hipótesis del DGP.
Y_heterogeneo = Y.copy()
Y_heterogeneo[np.flatnonzero(cohortes==3)[0],3] = 1.5
iw_heterogeneo,pooled_heterogeneo = comparar_sun_abraham(Y_heterogeneo,'inicio heterogéneo: tardía=1,5')
assert np.isclose(iw_heterogeneo[0],1.25)
assert not np.isclose(iw_heterogeneo[1],pooled_heterogeneo[1])
print('Los coeficientes IW coinciden con DiD frente al grupo nunca tratado.')
print('Cambiar la cohorte disponible modifica la composición del promedio por horizonte.')
print('Este panel determinista ilustra valores puntuales, no errores estándar.')Next build a unit panel using the same example and its known potential outcomes.
import numpy as np
import pandas as pd
# Panel equilibrado: las tres cohortes tienen el mismo tamaño. Coincide con
# el ejemplo didáctico de signo inverso; la nunca tratada tiene G = infinito.
def panel_escalonado(n_por_cohorte=10):
rows=[]
for cohort in (1.,3.,np.inf):
for j in range(n_por_cohorte):
unit=len(rows)//4
for t in range(4):
treated=np.isfinite(cohort) and t>=cohort
if cohort==1 and treated:
effect=(1.,1.,20.)[t-1]
elif cohort==3 and treated:
effect=1.
else:
effect=0.
# Y(0)=0; cambios por tratamiento aparecen solo desde G.
rows.append((unit,t,cohort,effect,0.,effect))
return pd.DataFrame(rows,columns=['unit','time','cohort','y','y0','tau'])
panel=panel_escalonado()
print('Panel:',panel.unit.nunique(),'unidades,',len(panel),'filas; cohortes 1, 3 y nunca.')Estimate cells with both control groups and aggregate only identified cells.
def att_gt(panel,control='never'):
"""ATT(g,t) simple para panel balanceado y sin anticipación."""
if control not in ('never','not_yet'):
raise ValueError('control debe ser never o not_yet')
if panel.duplicated(['unit','time']).any(): raise ValueError('Unidad y tiempo duplicados')
if panel.groupby('unit').cohort.nunique(dropna=False).ne(1).any():
raise ValueError('La cohorte cambia dentro de una unidad')
cohorts=sorted(g for g in panel.cohort.unique() if np.isfinite(g))
times=sorted(panel.time.unique());data=[]
for g in cohorts:
base=g-1
for t in (z for z in times if z>=g):
controls=np.isinf(panel.cohort) if control=='never' else panel.cohort>t
selected=panel[(panel.cohort==g)|controls]
baseline=selected[selected.time==base].set_index('unit')
after=selected[selected.time==t].set_index('unit')
if baseline.index.has_duplicates or after.index.has_duplicates or set(baseline.index)!=set(after.index):
raise ValueError('Se necesita panel balanceado entre base y periodo')
matched=after[['cohort','y','tau']].join(baseline[['y']].rename(columns={'y':'base'}))
treated=matched.cohort==g
if not treated.any(): continue
if (~treated).sum()==0:
data.append((int(g),int(t),np.nan,int(treated.sum()),float(matched.loc[treated,'tau'].mean()),0))
continue
change=matched.y-matched.base
estimate=change[treated].mean()-change[~treated].mean()
data.append((int(g),int(t),float(estimate),int(treated.sum()),
float(matched.loc[treated,'tau'].mean()),int((~treated).sum())))
return pd.DataFrame(data,columns=['g','t','att','n_g','true','n_controls'])
never=att_gt(panel,'never'); notyet=att_gt(panel,'not_yet')
print('ATT(g,t), grupo nunca tratado:')
print(never.to_string(index=False))
print('ATT(g,t), grupo aún no tratado:')
print(notyet.to_string(index=False))
def agrega_att(tabla):
valid=tabla.dropna(subset=['att']).copy()
valid['k']=valid.t-valid.g
def weighted(frame): return np.average(frame.att,weights=frame.n_g)
dynamic={int(k):weighted(s) for k,s in valid.groupby('k')}
cohort={int(g):weighted(s) for g,s in valid.groupby('g')}
calendar={int(t):weighted(s) for t,s in valid.groupby('t')}
return dynamic,cohort,calendar,weighted(valid)
dinamico,por_cohorte,calendario,global_=agrega_att(never)
print('Agregación dinámica:',dinamico,'| por cohorte:',por_cohorte)
print('Agregación por calendario:',calendario,'| global por exposiciones observadas:',global_)
print('Cada agregación usa n_g por celda disponible; las cohortes pueden cambiar con k.')Fit the counterfactual exclusively on untreated observations. Then remove never-treated units to observe support loss.
def imputacion_sin_tratar(panel):
"""Ajusta Y(0)=α_i+λ_t solo con observaciones no tratadas."""
frame=panel.copy()
untreated=(np.isinf(frame.cohort)) | (frame.time<frame.cohort)
supported=set(frame.loc[untreated,'time'].unique())
# No se extrapola a periodos sin ninguna observación no tratada.
usable=frame[frame.time.isin(supported)].copy()
u=(np.isinf(usable.cohort)) | (usable.time<usable.cohort)
# Si una unidad no tiene ninguna observación no tratada, su α_i no se puede
# identificar. Además se comprueba el rango de toda la matriz observada.
if set(usable.unit)!=set(usable.loc[u,'unit']):
raise ValueError('Hay unidades sin observaciones no tratadas')
X=np.column_stack([np.ones(len(usable)),
pd.get_dummies(usable.unit,drop_first=True,dtype=float).to_numpy(),
pd.get_dummies(usable.time,drop_first=True,dtype=float).to_numpy()])
fit=X[u.to_numpy()]
beta,_,rank,_=np.linalg.lstsq(fit,usable.loc[u,'y'].to_numpy(),rcond=None)
if rank!=X.shape[1]: raise ValueError('Efectos fijos no identificados en datos no tratados')
usable['y0_imputado']=X@beta
usable['impacto']=usable.y-usable.y0_imputado
treated=np.isfinite(usable.cohort)&(usable.time>=usable.cohort)
tab=(usable.loc[treated].groupby(['cohort','time'])
.agg(estimate=('impacto','mean'),truth=('tau','mean'),n=('unit','size')))
return tab,sorted(set(frame.time)-supported)
imputed,unsupported=imputacion_sin_tratar(panel)
print('Imputación con efectos fijos ajustados solo sin tratar:')
print(imputed.to_string())
print('Periodos sin soporte:',unsupported)
assert np.allclose(imputed.estimate,imputed.truth,atol=1e-10)
# Sin cohortes nunca tratadas, al llegar la última adopción no quedan controles.
sin_nunca=panel[np.isfinite(panel.cohort)].copy()
sin_controles=att_gt(sin_nunca,'not_yet')
print('Sin nunca tratados, ATT aún no tratados:')
print(sin_controles.to_string(index=False))
imputed_no_never,unsupported=imputacion_sin_tratar(sin_nunca)
print('Imputación sin nunca tratados; periodos no identificados:',unsupported)
print(imputed_no_never.to_string())Add fixed effects and independent noise to see how estimates differ in a sample.
# Repetimos el diseño de tres cohortes con efectos fijos, shocks y ruido.
# La tendencia paralela se cumple en esperanza, no exactamente en cada muestra.
rng=np.random.default_rng(272020)
ruidoso=panel_escalonado(n_por_cohorte=20)
fixed_unit=rng.normal(0,1,ruidoso.unit.nunique())
fixed_time=np.array([0.,.4,-.2,.3])
ruidoso['y0']=fixed_unit[ruidoso.unit.to_numpy()]+fixed_time[ruidoso.time.to_numpy()]+rng.normal(0,.25,len(ruidoso))
ruidoso['y']=ruidoso.y0+ruidoso.tau
print('Comparación en una muestra con ruido, semillas fijadas:')
for grupo in ('never','not_yet'):
out=att_gt(ruidoso,grupo)
print(grupo, 'ATT:',np.round(out.att.to_numpy(),4),
'verdad:',out.true.to_numpy(), 'global:',round(agrega_att(out)[3],4))
imputed,unsupported=imputacion_sin_tratar(ruidoso)
print('Imputación: estimado',np.round(imputed.estimate.to_numpy(),4),
'verdad',imputed.truth.to_numpy(),'periodos sin soporte',unsupported)
print('Son discrepancias de una muestra, no pruebas de insesgadez ni intervalos.')The multiplier bootstrap uses the same shared controls across all cells and produces an approximate simultaneous band.
# Bootstrap multiplicador de grupo-tiempo con controles nunca tratados.
# Las unidades son clústeres independientes y la composición por cohorte es
# fija en este ejemplo. Para dependencia regional se requieren multiplicadores
# por región y suficientes regiones, no por unidad.
tabla=att_gt(ruidoso,'never')
wide=ruidoso.pivot(index='unit',columns='time',values='y').sort_index()
cohort=ruidoso.groupby('unit').cohort.first().reindex(wide.index).to_numpy()
scores=[]
for row in tabla.itertuples(index=False):
dy=(wide[row.t]-wide[row.g-1]).to_numpy()
treat=cohort==row.g; control=np.isinf(cohort)
score=np.zeros(len(wide))
score[treat]=(dy[treat]-dy[treat].mean())/treat.sum()
score[control]=-(dy[control]-dy[control].mean())/control.sum()
scores.append(score)
scores=np.column_stack(scores)
rng_boot=np.random.default_rng(272021)
perturbations=rng_boot.normal(size=(1200,len(wide)))@scores
se=perturbations.std(axis=0,ddof=1)
if np.any(se<=0): raise ValueError('No se puede estandarizar una celda sin variación')
critical=np.quantile(np.max(np.abs(perturbations/se),axis=1),.95)
print('ATT por celda:',np.round(tabla.att.to_numpy(),4),
'EE multiplicador:',np.round(se,4))
print('Banda simultánea 95 %, crítico de máximo:',round(critical,4))
print('Extremos:',np.round(np.column_stack([tabla.att-critical*se,tabla.att+critical*se]),4))
print('Banda asintótica, basada en 1200 multiplicadores; esta ejecución no prueba cobertura.')This separate simulation conditions assignment and trend on X. Compare unconditional DiD with the doubly robust formula, using nuisance models known by construction.
import numpy as np
# Cohortes 1, 2, 3, 4 y nunca; estimamos ATT(2,3), con base 1.
# X es anterior a la adopción. Las probabilidades de cada cohorte dependen de X.
rg = np.random.default_rng(272020)
n = 100_000
x = rg.binomial(1, .5, n)
u = rg.uniform(size=n)
p2 = .15 + .2*x
p3 = p2 + .1
p4 = p3 + .3 - .1*x
# El primer decil corresponde a la cohorte 1, ya tratada antes de la base.
cohort = np.where(u < .1, 1, np.where(u < .1+p2, 2,
np.where(u < .1+p3, 3,
np.where(u < .1+p4, 4, np.inf))))
eligible = (cohort == 2) | (cohort > 3)
x = x[eligible]
g = (cohort[eligible] == 2).astype(float)
# El cambio sin tratar es 2X. La cohorte 2 tiene efecto 1 en t=3.
dy = 2*x + g
# Propensión condicional a pertenecer a la cohorte 2 ENTRE elegibles.
e_true = (.15 + .2*x)/.8
e_wrong = np.full_like(g, g.mean())
m_true = 2*x
m_wrong = np.zeros_like(g)
def dr_att(g, dy, m, e):
if np.any((e <= 0) | (e >= 1)):
raise ValueError('Se requiere solapamiento estricto')
w = (1-g)*e/(1-e)
r = dy-m
return np.mean(g*r)/np.mean(g) - np.mean(w*r)/np.mean(w)
unconditional = dy[g == 1].mean() - dy[g == 0].mean()
print('ATT verdadero:', 1.0, '| DiD incondicional:', round(unconditional, 4))
for nombre, e, m in [
('e y m correctos', e_true, m_true),
('solo e correcto', e_true, m_wrong),
('solo m correcto', e_wrong, m_true),
('ambos incorrectos', e_wrong, m_wrong),
]:
print(nombre, round(dr_att(g, dy, m, e), 4))
print('Controles elegibles: cohortes 4 y nunca; se excluyen 1 y 3.')
print('Los auxiliares correctos son conocidos por construcción; la aproximación con e correcto tiene error Monte Carlo.')Download public data and check cohorts; the treat variable means the county is treated at some point.
import io
import numpy as np
import pandas as pd
from pyodide.http import pyfetch
# Copia que distribuye el proyecto csdid; el paquete did documenta la fuente
# https://bcallaway11.github.io/did/reference/mpdta.html.
url='https://raw.githubusercontent.com/d2cml-ai/csdid/main/data/mpdta.csv'
response=await pyfetch(url)
if not response.ok: raise RuntimeError(f'No se pudo descargar el panel: HTTP {response.status}')
mpdta=pd.read_csv(io.StringIO(await response.string()))
required=['countyreal','year','lemp','first.treat','treat']
assert len(mpdta)==2500 and mpdta.countyreal.nunique()==500
assert not mpdta[required].isna().any().any()
assert not mpdta.duplicated(['countyreal','year']).any()
assert mpdta.groupby('countyreal').size().eq(5).all()
assert (mpdta.groupby('countyreal')['first.treat'].nunique()==1).all()
assert (mpdta.treat==(mpdta['first.treat']>0).astype(int)).all()
cohorts=mpdta.groupby('countyreal')['first.treat'].first().value_counts().sort_index()
print('Panel público: observaciones',len(mpdta),'condados',mpdta.countyreal.nunique(),
'años',int(mpdta.year.min()),'a',int(mpdta.year.max()))
print('Condados por primera adopción (0 = nunca en la muestra):',cohorts.to_dict())
print('lemp es logaritmo del empleo adolescente; treat indica si alguna vez se trata.')In a local Python environment install csdid==0.4.5 and pyfixest==0.60.0. Compare seven post-period ATTs with csdid and the TWFE coefficient with pyfixest, using the same sample and specification. The file does not include state, so this point comparison does not offer state-clustered inference.
"""Contraste reproducible de mpdta: estimaciones puntuales, no inferencia."""
import os
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
os.environ.setdefault("OMP_NUM_THREADS", "1")
import numpy as np
import pandas as pd
import pyfixest as pf
from csdid.att_gt import ATTgt
URL = "https://raw.githubusercontent.com/d2cml-ai/csdid/main/data/mpdta.csv"
df = pd.read_csv(URL).rename(columns={"first.treat": "cohort"})
assert df.shape == (2500, 6)
assert not df.duplicated(["countyreal", "year"]).any()
assert df.groupby("countyreal").year.nunique().eq(5).all()
assert df.groupby("countyreal").cohort.nunique().eq(1).all()
assert df[["countyreal", "year", "cohort", "lemp"]].notna().all().all()
assert (df.treat == (df.cohort > 0)).all()
print("Cohortes:", df.groupby("cohort").countyreal.nunique().to_dict())
wide = df.pivot(index="countyreal", columns="year", values="lemp")
cohort = df.groupby("countyreal").cohort.first().reindex(wide.index)
for control in ("nevertreated", "notyettreated"):
pkg = ATTgt(yname="lemp", gname="cohort", idname="countyreal", tname="year",
data=df, control_group=control, xformla="lemp~1", anticipation=0,
compute_inffunc=False).fit(est_method="reg", base_period="varying", bstrap=False)
result = pd.DataFrame(pkg.did_object)
result = result[result.t >= result.group].copy()
own = []
for g, t in result[["group", "t"]].itertuples(index=False, name=None):
g, t = int(g), int(t)
delta = wide[t] - wide[g - 1]
is_control = cohort.eq(0) if control == "nevertreated" else (cohort.eq(0) | (cohort > t))
own.append(delta[cohort.eq(g)].mean() - delta[is_control].mean())
result["propio"] = own
result["error"] = abs(result.att - result.propio)
print("\nATT(g,t):", control)
print(result[["group", "t", "att", "propio", "error"]].to_string(index=False))
assert result.error.max() < 1e-10
df["D"] = ((df.cohort > 0) & (df.year >= df.cohort)).astype(int)
def within(v):
return v - v.groupby(df.countyreal).transform("mean") - v.groupby(df.year).transform("mean") + v.mean()
yw, dw = within(df.lemp), within(df.D)
own_twfe = np.dot(dw, yw) / np.dot(dw, dw)
fit = pf.feols("lemp ~ D | countyreal + year", data=df)
library_twfe = fit.coef()["D"]
print("\nTWFE propio y pyfixest:", own_twfe, library_twfe)
assert abs(own_twfe - library_twfe) < 1e-10npm run lab and open the connection link.Exercises
Step 1 of 3. Which contrast uses not-yet-treated controls?
Step 1 of 3. What remains after residualizing against fixed effects?
def att_gt(df, unit, time, cohort, y, control='never'):
# Valida panel, forma los cambios y conserva sin estimar las celdas sin controles.
raise NotImplementedErrorCheck the numeric exercise after solving it:
import numpy as np
# Tabla hipotética: tres cohortes, pero la última no llega a k=1 en la ventana.
groups=np.array([2004,2006,2007])
sizes=np.array([20,40,60])
effects=np.array([2.,4.,np.nan])
available=np.isfinite(effects)
weights=sizes[available]/sizes[available].sum()
aggregate=np.dot(weights,effects[available])
assert np.isclose(aggregate,10/3)
print('Cohortes con k=1 observado:',groups[available])
print('Pesos disponibles:',np.round(weights,6),'efecto dinámico:',round(aggregate,6))
print('La tercera cohorte queda fuera: los pesos de cohortes pueden variar por horizonte.')