Difference-in-differences and event studies
Under parallel untreated trends, difference-in-differences identifies the treated effect. Derive the 2×2 regression, event studies, sensitivity to trend violations, and triple differences, and replicate Card and Krueger.
After this lesson you can
- Derive DiD from potential outcomes and explain identification of ATT.
- Show equivalence between 2×2 DiD and the two-way regression, and discuss clustered inference.
- Estimate and plot an event study with dynamic effects and prior trends.
- Assess parallel trends, scale dependence, and sensitivity intervals.
- Replicate Card and Krueger’s minimum-wage study.
Before you start
A decline that also occurred in the control
One region implements a security policy; another does not. Incidents decline in both, perhaps due to a general improvement in tools. Comparing regions afterward mixes policy with preexisting differences; comparing only the treated region’s change attributes all common evolution to policy. Difference-in-differences compares changes and asks what would have happened in the treated region without the policy.
Identify ATT
Let be the treated group, the prior period, and the later period. is the potential outcome under no policy; corresponds to the regime beginning policy in . Thus can represent possible anticipation before it starts. With consistency and no interference between groups, the estimand is . The observed difference-in-differences is
where the first subscript is group and the second period. In the population, it requires no anticipation and parallel trends for untreated outcomes:
To prove identification, add and subtract from the treated group’s change. The first part is ATT; the second is its counterfactual change without policy because there is no anticipation. The control’s observed change equals its untreated change and, by parallel trends, cancels the treated counterfactual. The assumption allows different initial levels but excludes a difference in counterfactual changes.
If the policy indirectly affects the control region, its observed evolution no longer represents . If group composition changes, repeated means also need conditions linking them to the same potential populations. Matching prior trends gives context but does not directly reveal the unobserved later trajectory.
Four means and a regression
In the saturated two-group, two-period regression,
the four parameters exactly fit four cell means when all exist. Subtracting the two temporal differences yields even with unequal cell sizes. The two-way fixed-effects model with individual and time effects yields the same mean-change contrast in a balanced two-period panel under the same sample and weighting; with attrition or different weights it is not automatically an equality of simple means.
The within transformation removes unit fixed components before fitting the rest of the model.
Equal coefficients do not determine their standard errors. Observations within a region may share shocks, and its time series may be autocorrelated. If assignment varies by region, clustered inference must reflect dependence at the relevant level. With only two treated and control regions, many individuals do not justify the conventional many-state-cluster approximation; an appropriate design and inference method for so few groups are needed.
Conditional parallel trends
If untreated evolution depends on prior covariates , parallelism given X followed by averaging over treated units may be more plausible. For a panel, write , , and . With control support in the treated population, a normalized form of Sant’Anna and Zhao’s doubly robust estimator averages
If is correct, mean control residual is zero given and the treated counterfactual change is removed. If is correct, weighted controls reproduce the treated distribution of and cancel any proposed function . Under other assumptions, the point estimator is consistent if either model is correct. This resembles augmented weighting applied to period changes. It does not protect against spillovers or false conditional parallel trends; inference also requires suitable conditions and procedures for nuisance estimation.
Scale is part of the assumption
An equal absolute increase for both groups can be a different proportional increase if starting levels differ. Thus parallel trends in levels do not imply parallel trends in logarithms. The level effect and log-change contrast answer different questions; choosing scale after seeing which is significant does not establish a plausible counterfactual.
Using logarithms requires positive outcomes or an explicit transformation with a different interpretation. Do not add an arbitrary constant without examining its effect on the contrast. The figure distinguishes observed trajectories from the treated counterfactual under parallel levels.
Event studies
With common adoption in and an untreated control group, an event study estimates interactions between group and relative time :
Period is the omitted reference. Each coefficient compares the treated–control gap in with the reference gap. Under no anticipation, unaffected controls, and relevant parallel trends, post-period coefficients describe dynamic effects relative to that reference. Pre-period coefficients describe observed differences before treatment, with uncertainty, and help assess plausibility rather than observe the later counterfactual.
Changing reference subtracts the new base-period gap from each coefficient and transforms its covariance. Shifting points while leaving standard errors unchanged is insufficient. With staggered adoption and heterogeneous effects, a single two-way regression can have a different interpretation; examine who serves as control for each comparison.
A nonsignificant pretest does not prove parallelism: power may be low. The relationship between tests and intervals helps assess deviations compatible with data. Selecting only designs passing that test also changes estimates’ and intervals’ distributions. Similarly, a statistically detectable prior deviation requires questioning the assumption and model, but its relevance for the future counterfactual gap depends on structure and scale; it does not by itself invalidate every possible analysis.
How much deviation can the conclusion tolerate?
Sensitivity to nonparallel trends distinguishes sampling uncertainty from counterfactual uncertainty. Rambachan and Roth restrict how post-period violations can differ from prior changes in the untreated gap. One class bounds changes in its slope; another limits post changes relative to pre changes. Different restrictions yield different identified sets.
The maximum estimated pre-coefficient is not the known true maximum. A valid interval must account for uncertainty in pre and post estimates alongside selected restrictions. Some procedures use their covariance matrix; others, such as a conservative Bonferroni construction, can combine marginal coverage without explicitly knowing it. A plot merely widening an interval by a fixed margin can illustrate sensitivity under that margin, but does not itself reproduce uniformly valid intervals of the general Rambachan–Roth procedure. The breakdown value depends on parameter, horizon, restriction, and inference method.
Triple differences
Triple differences compares two DiD estimators: for example, eligible and ineligible populations in the same regions and periods. Algebraically it subtracts the evolution of their two regional gaps. It can remove a differential regional trend shared by both populations but introduces a new assumption: without treatment, their remaining differential trends must coincide on the chosen scale. Three differences do not automatically remove confounding or spillovers.
Card and Krueger: minimum wage and employment
Card and Krueger compared fast-food restaurants in New Jersey and Pennsylvania before and after New Jersey’s minimum-wage increase. In their table 3, for the available sample, full-time-equivalent employment moved from 20.44 to 21.03 in New Jersey and from 23.33 to 21.17 in Pennsylvania. The table publishes DiD 2.76; subtracting already rounded means gives 2.75. The replication below preserves original values and distinguishes available sample from balanced panel.
Neumark and Wascher used payroll records and obtained an opposite-sign estimate in their sample. Card and Krueger responded using another administrative source and sample: in table 2, panel A, their uncontrolled total-employment DiD is 0.536 with standard error 1.017. It is not the same FTE measure or sample as the original survey. Data and design differences matter; attributing disagreement to one cause requires checking it.
Lab: DiD and event studies
First generate a balanced panel with common adoption and independent units. Autocorrelation is within each unit, so clustering by unit is appropriate in this particular DGP; it does not represent a policy assigned to only two regions. Removed fixed-effect parameters count in the CR1 correction.
import numpy as npimport scipyimport scipy.specialfrom scipy.stats import t as student_tdef panel_did(seed=191901,units_per_group=60,trend_violation=0.):
"""Panel equilibrado; asignación por unidad sin choques comunes de grupo."""
rng=np.random.default_rng(seed)
n=2*units_per_group;periods=5
group=np.r_[np.zeros(units_per_group),np.ones(units_per_group)].astype(int)
unit_effect=rng.normal(size=n)
# Un componente persistente dentro de unidad hace necesaria la agrupación.
err=np.zeros((n,periods));err[:,0]=rng.normal(scale=.8,size=n)
for period in range(1,periods):
err[:,period]=.45*err[:,period-1]+rng.normal(scale=.8,size=n)
times=np.arange(periods)
effects=np.array([0.,0.,0.,1.,2.])
potential=unit_effect[:,None]+.4*times+group[:,None]*(.6+trend_violation*times)+err
observed=potential+group[:,None]*effects
return group,observed,potential,effects
def cluster_ols(y,X,groups,k_total):
"""OLS y CR1 con G grupos; k_total incluye parámetros FE eliminados."""
y,X,groups=np.asarray(y,float),np.asarray(X,float),np.asarray(groups)
n,p=X.shape
if y.shape!=(n,) or groups.shape!=(n,) or np.linalg.matrix_rank(X)<p:
raise ValueError('Diseño sin rango completo o dimensiones incompatibles')
ids=np.unique(groups);G=len(ids)
if G<2 or n<=k_total: raise ValueError('Sin grados de libertad para CR1')
theta=np.linalg.lstsq(X,y,rcond=None)[0]
errors=y-X@theta
gram=np.linalg.inv(X.T@X)
sums=np.stack([(X[groups==g]*errors[groups==g,None]).sum(axis=0) for g in ids])
correction=G/(G-1)*(n-1)/(n-k_total)
covariance=correction*gram@(sums.T@sums)@gram
return theta,covariance
def event_panel(group,Y,ref=2):
"""Un tratamiento común desde tiempo 3; panel equilibrado y un grupo nunca tratado."""
n,T=Y.shape
if len(group)!=n or not 0<=ref<T: raise ValueError('Dimensiones o referencia inválida')
relative=[s for s in range(T) if s!=ref]
# FE de tiempo comunes: se elimina la primera columna como referencia.
timed=np.tile(np.eye(T)[:,1:],(n,1))
# Cada indicador de evento es grupo × tiempo, excepto el de referencia.
# Cada bloque del evento se convierte a columnas por observación.
event=np.stack([np.repeat(group,T)*np.tile((np.arange(T)==s).astype(float),n) for s in relative],axis=1)
raw=np.column_stack((timed,event)).reshape(n,T,-1)
x=(raw-raw.mean(axis=1,keepdims=True)).reshape(n*T,-1)
yy=(Y-Y.mean(axis=1,keepdims=True)).reshape(-1)
units=np.repeat(np.arange(n),T)
beta,cov=cluster_ols(yy,x,units,k_total=n+x.shape[1])
return np.array(relative),beta[T-1:],cov[T-1:,T-1:]
print('Panel simulado: una cohorte tratada a partir del período 3, grupo nunca tratado y unidades independientes.')g,Y,Y0,effects=panel_did()
pre,post=2,3
means=np.array([[Y[g==a,b].mean() for b in (pre,post)] for a in (0,1)])
did=(means[1,1]-means[1,0])-(means[0,1]-means[0,0])
long_y=Y[:,[pre,post]].reshape(-1)
long_t=np.tile([0,1],len(g));long_g=np.repeat(g,2)
design=np.column_stack((np.ones(len(long_y)),long_g,long_t,long_g*long_t))
coef,cov=cluster_ols(long_y,design,np.repeat(np.arange(len(g)),2),k_total=4)
assert np.isclose(did,coef[-1],atol=1e-12)
print('Cuatro medias:',np.round(means,4))
print('DiD por medias:',round(did,5),'interacción OLS:',round(coef[-1],5),
'EE CR1 por unidad:',round(np.sqrt(cov[-1,-1]),5),'efecto verdadero:',effects[post])
print('La agrupación por unidad es apropiada solo bajo el diseño simulado sin choques comunes de grupo.')periods,betas,cov=event_panel(g,Y,ref=2)
crit=student_t.ppf(.975,len(g)-1)
print('Estudio de eventos con referencia tiempo 2; IC t con',len(g)-1,'gl.')
for period,value,se in zip(periods,betas,np.sqrt(np.diag(cov))):
print('tiempo relativo',period-3,'estimación',round(value,4),'IC',np.round([value-crit*se,value+crit*se],4),
'efecto verdadero',round(effects[period]-effects[2],4))
print('Coeficientes previos no significativos no prueban paralelismo posterior.')gv,Yv,Y0v,effectsv=panel_did(seed=191902,trend_violation=.3)
means_v=np.array([[Yv[gv==a,b].mean() for b in (2,3)] for a in (0,1)])
did_v=(means_v[1,1]-means_v[1,0])-(means_v[0,1]-means_v[0,0])
counterfactual=(Y0v[gv==1,3]-Y0v[gv==1,2]).mean()-(Y0v[gv==0,3]-Y0v[gv==0,2]).mean()
print('Con tendencia diferencial: DiD',round(did_v,4),'ATT verdadero',effectsv[3],
'brecha contrafactual de cambios',round(counterfactual,4))
assert np.isclose(did_v,effectsv[3]+counterfactual,atol=1e-12)
print('DiD = ATT + diferencia de cambios contrafactuales; esta última no es observable en datos reales.')Now simulate conditional parallel trends and compare correct and incorrect specifications. Then introduce a deliberate violation; double robustness of nuisance models does not repair that causal assumption. The bootstrap refits both models and applies to i.i.d. units in this simulation.
import numpy as np
def expit(a):
return 1/(1+np.exp(-np.clip(a,-30,30)))
def logit_newton(X,g):
# Solo un modelo de trabajo: sin penalización, con comprobación de convergencia.
b = np.zeros(X.shape[1])
for _ in range(50):
p = expit(X@b)
hess = X.T@((p*(1-p))[:,None]*X)
step = np.linalg.solve(hess,X.T@(g-p))
b += step
if np.max(np.abs(step)) < 1e-9:
return expit(X@b)
raise RuntimeError('La logística no convergió')
def estimar_drdid(x,g,dy,prop_correcta=True,media_correcta=True):
# Los indicadores de corrección se refieren a este DGP conocido, no a
# diagnósticos disponibles en una aplicación observacional.
base = np.ones(len(x))
Xp = np.column_stack((base,x,x*x)) if prop_correcta else base[:,None]
Xm = np.column_stack((base,x,x*x)) if media_correcta else base[:,None]
p = logit_newton(Xp,g)
beta0 = np.linalg.lstsq(Xm[g==0],dy[g==0],rcond=None)[0]
m0 = Xm@beta0
residual = dy-m0
treated = g==1
weight = (1-g)*p/(1-p)
if weight.sum() <= 0 or not np.any(treated):
raise ValueError('No hay solapamiento empírico')
return residual[treated].mean()-np.sum(weight*residual)/weight.sum()
def panel(n,seed,violacion=0.0):
rng = np.random.default_rng(seed)
x = rng.uniform(-1,1,n)
e = expit(-0.25+1.3*x+1.0*(x*x-1/3))
g = rng.binomial(1,e,n)
y0 = 5+0.3*x+rng.normal(0,0.5,n)
delta0 = 0.2+1.2*x+x*x+rng.normal(0,0.8,n)+violacion*g
tau = 2.0
y1 = y0+delta0+tau*g
return x,g,y0,y1,e
print('Modelo: x uniforme en [-1,1]; ATT constante verdadero = 2.')
print('El sesgo de tendencias diferenciales es la desviación fijada en el DGP.')for violation in (0.0,0.6):
x,g,y0,y1,e = panel(40_000,271919,violation)
dy = y1-y0
did_bruto = dy[g==1].mean()-dy[g==0].mean()
print('\nDesviación de tendencia no tratada:',violation)
print('Tratados, rango de propensity verdadero:',int(g.sum()),np.round([e.min(),e.max()],4))
print('DiD bruto:',round(did_bruto,4),'ATT verdadero:',2.0)
for pc,mc in ((True,True),(False,True),(True,False),(False,False)):
value = estimar_drdid(x,g,dy,pc,mc)
print('Propensity correcta:',pc,'| cambio control correcto:',mc,'| DR DiD:',round(value,4))
if violation:
print('Con tendencias violadas, el blanco del ajuste ideal es',2+violation,
'y no el ATT de 2.')
else:
print('Con tendencias paralelas condicionales, el blanco del ajuste ideal es el ATT de 2.')# Bootstrap por unidad i.i.d. en el escenario de tendencias paralelas y
# ambos modelos auxiliares correctos. Cada réplica vuelve a ajustar ambos.
x_b,g_b,y0_b,y1_b,e_b = panel(2500,271920,0)
dy_b = y1_b-y0_b
estimate_b = estimar_drdid(x_b,g_b,dy_b,True,True)
rng_boot = np.random.default_rng(271921)
draws = []
failures = 0
for _ in range(160):
ids = rng_boot.integers(0,len(x_b),len(x_b))
try:
draws.append(estimar_drdid(x_b[ids],g_b[ids],dy_b[ids],True,True))
except (ValueError,RuntimeError,np.linalg.LinAlgError):
failures += 1
if len(draws) != 160:
raise RuntimeError(f'Fallaron {failures} réplicas; no se informa el intervalo')
ci = np.quantile(draws,[0.025,0.975])
print('Estimación DR DiD:',round(estimate_b,4))
print('Bootstrap por unidad: réplicas válidas y fallos:',len(draws),failures)
print('Intervalo percentil 95 % aproximado:',np.round(ci,4))
print('El ATT verdadero es 2; un intervalo aislado no demuestra cobertura.')
print('Con asignación por regiones, se requiere remuestrear clústeres y suficientes clústeres.')Lab: Card and Krueger data
We download a CSV mirror checked row by row in the used columns against Card’s public file. FTE sums full-time workers, managers, and half of part-time workers; permanent closures are treated as zero and temporary ones as missing in the main comparison. A connection is required.
import io
import pandas as pd
from pyodide.http import pyfetch
url='https://kvasilopoulos.github.io/econdata/data/ck1994.csv'
r=await pyfetch(url)
if not r.ok: raise RuntimeError(f'No se pudo descargar: HTTP {r.status}')
restaurantes=pd.read_csv(io.StringIO(await r.string()))
assert restaurantes.shape==(410,46)
assert restaurantes.state.value_counts().to_dict()=={1:331,0:79}
print('Locales originales:',len(restaurantes),'NJ:',(restaurantes.state==1).sum(),
'PA:',(restaurantes.state==0).sum())import numpy as np
import pandas as pd
d=restaurantes.copy()
# El identificador sheet se repite entre estados: la fila es única.
d['id_local']=np.arange(len(d))
d['fte_antes']=d.empft+d.nmgrs+.5*d.emppt
d['fte_despues']=d.empft2+d.nmgrs2+.5*d.emppt2
# Cierres permanentes: 0 FTE; cierres temporales: ausentes, siguiendo tabla 3.
d.loc[d.status2==3,'fte_despues']=0.
for g in (1,0):
r=d[d.state==g]
print('NJ' if g==1 else 'PA','antes n/media:',r.fte_antes.count(),round(r.fte_antes.mean(),6),
'después n/media:',r.fte_despues.count(),round(r.fte_despues.mean(),6))
all_means=d.groupby('state')[['fte_antes','fte_despues']].mean()
did_all=(all_means.loc[1,'fte_despues']-all_means.loc[1,'fte_antes'] -
all_means.loc[0,'fte_despues']+all_means.loc[0,'fte_antes'])
balanced=d.dropna(subset=['fte_antes','fte_despues']).copy()
balanced['change']=balanced.fte_despues-balanced.fte_antes
grouped=balanced.groupby('state').change
diff=grouped.mean(); ns=grouped.count(); var=grouped.var(ddof=1)
did=diff[1]-diff[0]
se=np.sqrt(var[1]/ns[1]+var[0]/ns[0])
print('Todas las observaciones disponibles: DiD',round(did_all,6))
print('Panel equilibrado locales NJ/PA:',int(ns[1]),int(ns[0]),
'cambios:',round(diff[1],6),round(diff[0],6),
'DiD:',round(did,6),'EE emparejado:',round(se,6))
zero_temporary=d.copy()
zero_temporary.loc[zero_temporary.status2.isin([2,4,5]),'fte_despues']=0.
zero_temporary=zero_temporary.dropna(subset=['fte_antes','fte_despues']).copy()
zero_temporary['change']=zero_temporary.fte_despues-zero_temporary.fte_antes
alt=zero_temporary.groupby('state').change.mean()
print('Análisis alternativo, cierres temporales a cero: DiD',round(alt[1]-alt[0],6))
# Los mismos locales observados en ambos tiempos: interacción 2×2 = DiD.
nj=balanced.state.to_numpy(float); n=len(nj)
Y=np.r_[balanced.fte_antes.to_numpy(),balanced.fte_despues.to_numpy()]
post=np.r_[np.zeros(n),np.ones(n)]; state=np.r_[nj,nj]
design=np.column_stack([np.ones(2*n),state,post,state*post])
beta=np.linalg.lstsq(design,Y,rcond=None)[0]
assert np.isclose(beta[-1],did)
print('Coeficiente de la interacción, mismos locales:',round(beta[-1],6))
print('Observación: hay dos estados, no 384 asignaciones independientes de la política.')The matched restaurant difference uses the balanced sample and restaurant-level uncertainty. It does not by itself represent uncertainty for a policy assigned to two states. The alternative closure analysis changes the sample or coding and answers a different data decision.
Exercises
Step 1 of 3. What is missing to obtain the average treated effect?
Step 1 of 3. How many distinct fitted values does the model allow?
def event_study(df, unit, time, treat_time, y, ref=-1):
# Valida el panel y construye efectos fijos e indicadores de evento.
# Agrupa la covarianza por unidad con la corrección CR1 indicada.
raise NotImplementedErrorIn four separate hypothetical studies, each plot shows the 95% interval for one prior difference relative to the reference period. The center mark is zero:
A: 0 [0,3 -------- 0,8]
B: [−0,3 ---- 0 ---- 0,3]
C: [−1,0 ---------------- 0 ---------------- 1,0]
D: [−0,4 ------- 0 -- 0,2]
After attempting the calculation, check it:
import numpy as np
tratado_antes, tratado_despues = 20.4, 21.0
control_antes, control_despues = 23.3, 21.2
did_ejercicio = (tratado_despues-tratado_antes)-(control_despues-control_antes)
assert np.isclose(did_ejercicio, 2.7)
print("Diferencia en diferencias del ejercicio:", did_ejercicio)