Difference-in-differences with staggered adoption
Start with Card and Krueger's minimum-wage case and extend it to multiple periods and staggered adoption. Simulate sign reversal in two-way fixed effects under heterogeneous effects, implement cohort estimation and event studies, and examine parallel-trends sensitivity with honest intervals.
After this lesson you can
- Estimate two-period DiD and its regression version with clustered errors.
- Reproduce the Goodman-Bacon decomposition and TWFE bias with dynamic effects.
- Implement a cohort estimator and aggregate it in an event study.
- Apply honest intervals bounding deviations from parallel trends.
Before you start
Two states and two periods
In April 1992 New Jersey raised the minimum wage from 4.25 to 5.05 dollars per hour; neighboring Pennsylvania kept 4.25 dollars. Card and Krueger compared fast-food restaurants before and after. The unit is the establishment and the outcome is full-time-equivalent employment, counting each part-time worker as half. The contrast asks about relative change in this sample; it does not by itself measure all possible effects on new openings.
Table 3 of the article presents means using all available observations: New Jersey changes from 20.44 to 21.03 and Pennsylvania from 23.33 to 21.17. The difference-in-differences calculated from those rounded figures is equivalent jobs per establishment. The article reports 2.76 from unrounded values and 2.75 using a balanced sample. These are not simulated data, but the four means can come from different sets of establishments across waves.
Interpreting the contrast as an effect requires a version of parallel trends: without the policy change, mean outcome change in New Jersey would have equaled Pennsylvania’s for the studied populations and periods. Anticipation, composition, interference between markets, and other simultaneous policies must also be considered. Good prior fit does not observe the later counterfactual. Errors should be clustered where shocks correlate and policy is assigned; with only two states, a state-clustered error using a many-cluster approximation is unreliable.
In a balanced panel with two groups and periods, regression with unit and period fixed effects and a treated × post interaction gives exactly the same difference-in-differences of means. The lab verifies equality and a unit-clustered error in a synthetic panel with independent units. This does not turn two states into many clusters or reproduce the article’s standard errors.
Staggered adoption and already-treated controls
With many periods, treatment can begin at different times. The two-way fixed-effects or TWFE coefficient mixes cohort comparisons, including those using an already-treated cohort as control for a later one. If the early cohort’s effect continues growing, the second comparison subtracts part of that growth and can be negative even when every true effect is positive.
The uncontrolled Goodman-Bacon decomposition expresses TWFE as a weighted sum of 2×2 comparisons. Those comparison weights are nonnegative and sum to one. Re-expressing the same coefficient as a sum of cohort-time treatment effects can produce negative weights on some effects. These are distinct decompositions; do not call 2×2 weights negative merely because a comparison estimate is negative.
The simulation uses 170 units, eight periods, cohorts of 80 units adopting at and , and 10 never treated. Untreated outcome has an individual intercept, common trend , and normal noise; seed 501. The early effect is after adoption and the late effect is 1. With , true mean effect across treated cells is 8.50, while TWFE estimates -0.760. The cohort estimator gives 8.488 with bootstrap percentile interval [8.360, 8.631] in this sample. All simulated effects are positive; sign reversal does not imply TWFE always fails or describe a minimum-wage result.
The 2×2 weights are 0.079, 0.079, 0.421, and 0.421. The last comparison uses the already-treated early cohort as control and estimates -11.094; as its effect grows, control change absorbs part of the late change. Implicit weights on the early cohort’s effect in periods 6 and 7 are -0.197 each. Weights do not depend on outcomes in this balanced design, but do depend on cohort size and timing.
Cohorts and event study
The staggered-adoption cohort estimator calculates for the cohort adopting at , comparing with and using units never treated or not yet treated in either period. It then aggregates using declared weights. The lab uses the no-covariate case of Callaway and Sant’Anna; covariates require their adjustments and additional assumptions. If no valid controls remain for a pair , do not invent an estimate.
An event study groups effects by relative time . Here is the baseline; for and earlier, prior contrasts use that baseline. The aggregate effect at is 0.929 and at is 2.919; the cohort set changes at longer horizons, so the trajectory also reflects composition. Overall aggregation weights are proportional to each cohort’s unit count in each estimable treated cell, the same target as the true mean 8.50.
We resample complete units within each cohort 199 times with seed 501. For each horizon we calculate standard deviation across replicates and use the 95th percentile of maximum standardized deviations for simultaneous bands over displayed horizons. The figure’s overall interval is percentile-based and should not be confused with those bands. Replicate count and especially the 10 never-treated units limit this illustration’s precision; validity depends on independence across units, design, and bootstrap conditions.
Before does not prove after
A nonsignificant pre-treatment coefficient does not establish parallel trends: power can be low and choosing a specification after inspecting its pretest changes inference. Parallel-trends sensitivity asks which conclusions survive if the relative counterfactual trajectory can deviate within chosen bounds. Rambachan and Roth develop restrictions and confidence sets for that question. These assumptions need justification and are not tests of the missing trend.
To avoid mixing cohorts of different composition, we apply HonestDiD from diff-diff only to the late cohort and 10 never-treated units, with baseline and target . The smoothness restriction bounds the absolute second differences of trend violation by . With , it permits a linear deviation and the nominal 95% FLCI interval is [0.541, 1.051]; with , [0.407, 1.191]; with , [0.162, 1.429]. The package’s full analytical covariance is used rather than the diagonal bootstrap alternative. These simulation results depend on the restriction, inference approximation, and control size; they do not certify parallel trends in Card and Krueger.
Laboratory
In Python 3.12 install python -m pip install "numpy==2.2.6" "scipy==1.15.3" "pandas==2.3.3" "scikit-learn==1.6.1" "statsmodels==0.15.0" "differences==0.3.0" "polars==1.35.2" "diff-diff==3.8.0". The custom implementation uses balanced panels and irreversible adoption without covariates; it compares each cell with differences and the decomposition with diff-diff. Sensitivity analysis uses diff-diff for the smoothness procedure and does not claim to reproduce every option in the authors’ R package.
Download did.py, test_did.py, experiment.py, and widget_data.py into the same directory. The complete results and interactive values record parameters and comparisons. Run python test_did.py and python experiment.py --out results.json --reps 199; the latter does not overwrite results. To regenerate the interactive, python widget_data.py writes a new widget_values.json and does not overwrite an existing one.
"""DiD equilibrado por cohortes; comparaciones y bootstrap por unidad."""
import numpy as np
import pandas as pd
def panel(seed=501,n_early=80,n_late=80,n_never=10,slope=4.):
rng=np.random.default_rng(seed);cohorts=np.r_[np.full(n_early,2),np.full(n_late,6),np.zeros(n_never,dtype=int)]
units=np.arange(len(cohorts));times=np.arange(8);intercepts=rng.normal(0,1,len(units))
out=[]
for i,g in enumerate(cohorts):
for t in times:
treated=int(g>0 and t>=g)
effect=treated*(1+slope*(t-g) if g==2 else 1.)
y0=intercepts[i]+.15*t+rng.normal(0,.5)
out.append((i,t,g,treated,y0+effect,float(effect)))
return pd.DataFrame(out,columns=['id','time','cohort','treated','y','effect'])
def within(panel,column):
return (panel[column]-panel.groupby('id')[column].transform('mean')
-panel.groupby('time')[column].transform('mean')+panel[column].mean()).to_numpy()
def twfe(panel):
d=within(panel,'treated');y=within(panel,'y');den=d@d
if den<=1e-12:raise ValueError('Sin variación residual del tratamiento')
estimate=float(d@y/den);resid=y-estimate*d
cluster=pd.Series(d*resid).groupby(panel.id.to_numpy()).sum().to_numpy()
se=float(np.sqrt(cluster@cluster)/den)
treated=panel.treated.to_numpy()==1
weights=pd.DataFrame({'cohort':panel.cohort,'time':panel.time,'w':np.where(treated,d/den,0.)})
effects=weights.groupby(['cohort','time'],as_index=False).w.sum()
return estimate,se,effects[effects.cohort>0]
def bacon(panel):
"""Descomposición no controlada para panel balanceado y adopción irreversible."""
cohorts=sorted(g for g in panel.cohort.unique() if g>0);has_never=(panel.cohort==0).any()
rows=[]
def add(g1,g2,times,kind):
sub=panel[panel.cohort.isin([g1,g2]) & panel.time.isin(times)].copy().reset_index(drop=True)
d=within(sub,'treated');y=within(sub,'y');variance=float(np.mean(d*d))
if variance<=0:return
rows.append({'treated_cohort':int(g1),'control_cohort':int(g2),'type':kind,
'estimate':float(d@y/(d@d)),'raw_weight':float(len(sub)**2*variance)})
times=sorted(panel.time.unique())
if has_never:
for g in cohorts:add(g,0,times,'tratado vs nunca')
for i,g in enumerate(cohorts):
for h in cohorts[i+1:]:
add(g,h,[t for t in times if t<h],'temprano vs tardío aún no tratado')
add(h,g,[t for t in times if t>=g],'tardío vs temprano ya tratado')
total=sum(r['raw_weight'] for r in rows)
for row in rows:row['weight']=row.pop('raw_weight')/total
return rows
def att_gt(panel,cohort,time):
"""Diferencia de cambios con base g−1 y controles no tratados en ambos periodos."""
base=cohort-1
if time==base:raise ValueError('El periodo base no tiene efecto estimado')
valid=(panel.cohort==0)|(panel.cohort>max(base,time))
ids=panel.loc[valid & (panel.cohort!=cohort),'id'].unique()
treated=panel.loc[panel.cohort==cohort,'id'].unique()
if not len(ids) or not len(treated):raise ValueError('No hay grupo o controles válidos')
w=panel[panel.time.isin([base,time])].pivot(index='id',columns='time',values='y')
change=w[time]-w[base]
return float(change.loc[treated].mean()-change.loc[ids].mean())
def aggregates(panel):
cohorts=sorted(g for g in panel.cohort.unique() if g>0);times=sorted(panel.time.unique())
count=panel.groupby('cohort').id.nunique();cells=[]
for g in cohorts:
for t in times:
if t==g-1:continue
try:estimate=att_gt(panel,g,t)
except ValueError:continue
cells.append({'cohort':int(g),'time':int(t),'event':int(t-g),'n':int(count[g]),'att':estimate})
event={}
for e in sorted(set(c['event'] for c in cells)):
subset=[c for c in cells if c['event']==e]
event[e]=float(np.average([c['att'] for c in subset],weights=[c['n'] for c in subset]))
treated=[c for c in cells if c['event']>=0]
overall=float(np.average([c['att'] for c in treated],weights=[c['n'] for c in treated]))
return cells,event,overall
def bootstrap(panel,reps=199,seed=501):
rng=np.random.default_rng(seed);cohorts=panel.groupby('cohort').id.unique().to_dict()
cells,event,overall=aggregates(panel);events=list(event);draws=[];avgs=[]
byid={int(i):group for i,group in panel.groupby('id')}
for _ in range(reps):
sample=[];newid=0
for ids in cohorts.values():
for i in rng.choice(ids,size=len(ids),replace=True):
piece=byid[int(i)].copy();piece['id']=newid;sample.append(piece);newid+=1
sample=pd.concat(sample,ignore_index=True)
_,ev,avg=aggregates(sample);draws.append([ev[e] for e in events]);avgs.append(avg)
matrix=np.asarray(draws);centres=np.array([event[e] for e in events]);se=matrix.std(axis=0,ddof=1)
valid=se>0;maxstat=np.max(np.abs((matrix[:,valid]-centres[valid])/se[valid]),axis=1)
critical=float(np.quantile(maxstat,.95));result=[]
for i,e in enumerate(events):result.append({'event':int(e),'estimate':event[e],'se':float(se[i]),
'lower':float(event[e]-critical*se[i]),'upper':float(event[e]+critical*se[i])})
return {'cells':cells,'event':result,'overall':overall,
'overall_ci':[float(x) for x in np.quantile(avgs,[.025,.975])],
'critical':critical,'bootstrap_reps':reps,'bootstrap_seed':seed}
"""Equivalencia dos por dos, errores agrupados y descomposición."""
import numpy as np
import statsmodels.formula.api as smf
p=panel();estimate,se,weights=twfe(p);rows=bacon(p)
assert np.isclose(sum(r['weight'] for r in rows),1)
assert all(r['weight']>=0 for r in rows)
assert np.isclose(sum(r['weight']*r['estimate'] for r in rows),estimate)
assert (weights.w<0).any()
q=p[p.cohort.isin([0,6]) & p.time.isin([5,6])].copy()
small_ids=q.groupby('cohort').id.unique().apply(lambda a:a[:8]).explode().astype(int)
q=q[q.id.isin(small_ids)].copy();b,s,_=twfe(q)
assert np.isclose(b,att_gt(q,6,6))
ref=smf.ols('y ~ treated + C(id) + C(time)',data=q).fit(cov_type='cluster',cov_kwds={'groups':q.id,'use_correction':False})
assert np.isclose(b,ref.params['treated']) and np.isclose(s,ref.bse['treated'])
print('2×2, error agrupado y suma Bacon: verificados')
"""Comparación TWFE, cohortes, Bacon y sensibilidad en un panel simulado."""
import argparse,json,platform
from pathlib import Path
import numpy as np
import pandas as pd
import scipy
import differences
import diff_diff
from differences import ATTgt
from diff_diff import BaconDecomposition,CallawaySantAnna,HonestDiD
def run(seed=501,reps=199,slope=4.):
frame=panel(seed=seed,slope=slope);coefficient,se,weights=twfe(frame);decomp=bacon(frame)
assert abs(sum(r['weight']*r['estimate'] for r in decomp)-coefficient)<1e-10
assert all(r['weight']>=0 for r in decomp)
truth=float(frame.loc[frame.treated==1,'effect'].mean())
own=bootstrap(frame,reps=reps,seed=seed)
source=frame.copy();source['cohort']=source.cohort.replace(0,np.nan)
fit=ATTgt(data=source.set_index(['id','time']),cohort_column='cohort',base_period='universal')
reference=fit.fit(formula='y',est_method='reg',control_group='not_yet_treated',progress_bar=False).to_pandas()
diffs=[]
for cell in own['cells']:
actual=float(reference.loc[(cell['cohort'],cell['cohort']-1,cell['time']),('ATTgtElements','','ATT')])
diffs.append(abs(actual-cell['att']))
assert max(diffs)<1e-8
check=BaconDecomposition().fit(frame,'y','id','time','cohort')
assert abs(check.twfe_estimate-coefficient)<1e-8
sample=frame[frame.cohort.isin([0,6])].copy()
cs=CallawaySantAnna(control_group='never_treated',estimation_method='reg',base_period='universal',n_bootstrap=0)
fitted=cs.fit(sample,outcome='y',unit='id',time='time',first_treat='cohort',aggregate='event_study')
sensitivity=[]
for M in (0.,.1,.25):
result=HonestDiD(method='smoothness',M=M,l_vec=np.array([1.,0.])).fit(fitted)
sensitivity.append({'M':M,'ci':[float(result.ci_lb),float(result.ci_ub)],'method':result.ci_method})
return {'seed':seed,'slope':slope,'n_units':int(frame.id.nunique()),'periods':8,'truth_treated_cells':truth,
'twfe':{'estimate':coefficient,'cluster_se_uncorrected':se,'effect_weights':weights.to_dict('records')},
'bacon':decomp,'cohorts':own,'differences_max_abs_error':max(diffs),
'sensitivity':{'cohort':6,'control':'never','event':0,'restrictions':'smoothness, second differences bounded by M',
'intervals':sensitivity},
'versions':{'python':platform.python_version(),'numpy':np.__version__,'pandas':pd.__version__,'scipy':scipy.__version__,
'differences':differences.__version__,'diff_diff':diff_diff.__version__}}
result=run(reps=199)
print('TWFE:',result['twfe']['estimate'],'verdad:',result['truth_treated_cells'])
print('Cohortes:',result['cohorts']['overall'],result['cohorts']['overall_ci'])
print('Bacon:',result['bacon'])
print('Sensibilidad:',result['sensitivity'])npm run lab and open the connection link.Exercises
Step 1 of 2. What happens when the pre-period is subtracted from the post-period for each unit?
def att_gt(panel, g, t):
pass
def aggregate_event(cells):
pass
def simultaneous_bands(estimates, draws):
pass