Module contents
Lesson 19 of 28Core 105 min

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.

InteractiveFour means and a counterfactual

The four filled points are observed means. The dashed line projects the control change onto the treated group: its endpoint is the assumed untreated outcome under parallel trends.

17.320.824.3BeforeAfter
  • Observed control
  • Observed treated
  • Untreated treated group under parallel trends
  • Observed DiD

The chosen deviation adds 0.00 to the change the treated group would have had without treatment, relative to the control change. Under this additional assumption, the counterfactual is 18.30 and the modeled effect is DiD minus the deviation. The deviation is not observed in the four means: it cannot be deduced from this graph or a prior trend alone.

Interpreting DiD as ATT requires parallel trends in untreated outcomes, no anticipation and consistency, as well as appropriate comparability. The four means identify the observed difference; they do not verify these assumptions.

23.3
21.2
20.4
22.1
0.0
Control change−2.10
Treated change1.70
Observed DiD3.80
Counterfactual under parallel trends18.30
Effect under the chosen deviation3.80
Move the means and distinguish the parallel counterfactual from a hypothetical deviation.

Identify ATT

Let G=1G=1 be the treated group, t=0t=0 the prior period, and t=1t=1 the later period. Yt(0)Y_t(0) is the potential outcome under no policy; Yt(1)Y_t(1) corresponds to the regime beginning policy in t=1t=1. Thus Y0(1)Y_0(1) can represent possible anticipation before it starts. With consistency and no interference between groups, the estimand is ATT=E[Y1(1)−Y1(0)∣G=1]ATT=E[Y_1(1)-Y_1(0)\mid G=1]. The observed difference-in-differences is

DiD^=(Y‾11−Y‾10)−(Y‾01−Y‾00),\widehat{DiD}=(\overline Y_{11}-\overline Y_{10})-(\overline Y_{01}-\overline Y_{00}),

where the first subscript is group and the second period. In the population, it requires no anticipation E[Y0(1)−Y0(0)∣G=1]=0E[Y_0(1)-Y_0(0)\mid G=1]=0 and parallel trends for untreated outcomes:

E[Y1(0)−Y0(0)∣G=1]=E[Y1(0)−Y0(0)∣G=0].E[Y_1(0)-Y_0(0)\mid G=1] =E[Y_1(0)-Y_0(0)\mid G=0].

To prove identification, add and subtract E[Y1(0)∣G=1]E[Y_1(0)\mid G=1] 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 Y(0)Y(0). 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,

Yit=α+γGi+λPostt+β(GiPostt)+εit,Y_{it}=\alpha+\gamma G_i+\lambda Post_t+\beta(G_i Post_t)+\varepsilon_{it},

the four parameters exactly fit four cell means when all exist. Subtracting the two temporal differences yields β^=DiD^\widehat\beta=\widehat{DiD} 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.

If untreated evolution depends on prior covariates XX, parallelism given X followed by averaging over treated units may be more plausible. For a panel, write ΔY=Y1−Y0\Delta Y=Y_1-Y_0, p(X)=P(G=1∣X)p(X)=P(G=1\mid X), m0(X)=E[ΔY∣G=0,X]m_0(X)=E[\Delta Y\mid G=0,X] and w0=(1−G)p(X)/(1−p(X))w_0=(1-G)p(X)/(1-p(X)). With control support in the treated population, a normalized form of Sant’Anna and Zhao’s doubly robust estimator averages

{GE[G]−w0E[w0]}{ΔY−m0(X)}.\left\{\frac{G}{E[G]}-\frac{w_0}{E[w_0]}\right\} \{\Delta Y-m_0(X)\}.

If m0m_0 is correct, mean control residual is zero given XX and the treated counterfactual change is removed. If pp is correct, weighted controls reproduce the treated distribution of XX and cancel any proposed function m0(X)m_0(X). 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.

InteractiveParallelism depends on scale

Observed control and the treated group’s untreated counterfactual increase by the same amount in levels. The solid treated line also includes the effect; the two observed trajectories are not assumed parallel.

0.47.514.7BeforeAfter
  • Observed control
  • Observed treated
  • Treated without treatment

Explicit model: control 2.0 → 4.0; treated without treatment 10.0 → 12.0; observed treated 10.0 → 13.0. All outcomes are positive, so the logarithm is defined. The additive effect is 1.0.

In logarithms, observed DiD equals the true effect on that scale plus the difference in untreated changes. It can therefore have the opposite sign to the true effect: equal changes in levels do not imply equal changes in logs. In the initial model level DiD is positive and log DiD is negative, although the true log effect is positive.

2.0
10.0
2.0
1.0
Observed DiD in levels1.000
Observed DiD in logarithms−0.431
True effect in levels1.000
True effect in logarithms0.080
Difference in untreated changes in log−0.511
Compare levels and logarithms using the same counterfactual trajectory.

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 t0t_0 and an untreated control group, an event study estimates interactions between group and relative time k=t−t0k=t-t_0:

Yit=αi+λt+∑k≠−1βkGi1{t−t0=k}+εit.Y_{it}=\alpha_i+\lambda_t+\sum_{k\ne -1}\beta_k G_i1\{t-t_0=k\}+\varepsilon_{it}.

Period k=−1k=-1 is the omitted reference. Each coefficient compares the treated–control gap in kk 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.

InteractiveBuild an event study

Each point compares the group gap in that period with the gap in the omitted period. Bars show pointwise 95% normal intervals, not a simultaneous band.

2.50−2.5-3-2-1012Relative time
  • Coefficient and pointwise interval
  • After the intervention

Reproducible panel: 40 independent clusters, 20 per group, observed from t=−3 to t=2; simultaneous treatment from t=0. The outcome has common trend 0.3t, random cluster intercepts and slopes, and AR(1) disturbances. For treated units d(t+1) is added and, from t=0, τ(1+0.4t). Controls adjust d and τ; the fixed seed is 2719.

For each contrast, the sample variance of changes within each group is divided by its 20 clusters and the two are added. This retains temporal dependence within clusters. The normal approximation requires enough independent clusters; with few, intervals may have poor coverage. The omitted point is zero by construction, not evidence of no uncertainty.

0.00
1.0
Reference period
Coefficient at t=01.010
Cluster standard error0.178
Clusters per group20
Change the reference and observe how coefficients and intervals transform.

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.

InteractiveHow much parallelism can break

The colored region contains intervals for the effect at t=0 as a function of the allowed deviation from parallel trends. The vertical line marks the chosen M.

3.40−3.40123Relative magnitude M
  • Conservative intervals
  • Chosen M
  • Zero effect

Assume no anticipation and that the counterfactual gap change from t=−1 to t=0 is at most M times the largest true change among t=−3, −2 and −1. M=0 imposes parallel trends in the first post period. The deviation is an assumption, not something established by pre-treatment data.

The same reproducible event-study panel supplies three contrasts: two pre-period changes and the post-period change, with cluster standard errors. Their normal intervals use quantile 2.394 to distribute the 5% error across three contrasts by Bonferroni. The pre-period bound is the maximum of |estimated change| plus its margin; M times that bound is added to the post-period margin. Under the normal approximation and assumptions above, asymptotic coverage is at least 95%.

This deliberately conservative construction incorporates pre-period uncertainty; it is not HonestDiD output. The procedures of Rambachan y Roth (2023) use the estimated vector and its covariance for inference under trend restrictions. The shown threshold applies only to the interval in this figure.

0.50
0.00
1.0
Conservative 95% interval[0.31, 1.72]
Bound on prior changes0.558
M at zero inclusion1.05
A conservative band incorporates pre- and post-period uncertainty under an explicit restriction.

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.

[ ]did import numpyBrowser
import numpy as np
[ ]did import scipyBrowser
import scipy
[ ]did import specialBrowser
import scipy.special
[ ]did import statsBrowser
from scipy.stats import t as student_t
[ ]did panel setupBrowser
def 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.')
[ ]did panel 2x2Browser
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.')
[ ]did panel eventsBrowser
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.')
[ ]did panel violationBrowser
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.

[ ]drdid 01 modeloBrowser
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.')
[ ]drdid 02 scenariosBrowser
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.')
[ ]drdid 03 bootstrapBrowser
# 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.

[ ]card downloadBrowser
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())
[ ]card panelBrowser
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

ProofIdentification with parallel trends
Prove: In two periods, group G=1G=1 receives the policy only afterward and group G=0G=0 receives it in neither period; both groups have positive probability. Assume consistency, no anticipation, no interference, and parallel mean trends in untreated outcomes. Prove that difference-in-differences of observed means identifies ATT.
The proof will appear here as you work.

Step 1 of 3. What is missing to obtain the average treated effect?

ProofThe table interaction
Prove: A sample has observations in all four cells of group G∈{0,1}G\in\{0,1\} and period T∈{0,1}T\in\{0,1\}. In least-squares regression with intercept, GG, TT and GTG T, prove that the interaction coefficient is difference-in-differences of the four sample means.
The proof will appear here as you work.

Step 1 of 3. How many distinct fitted values does the model allow?

NumericA policy in two regions
Average employment moves from 20.4 to 21.0 in the treated region and from 23.3 to 21.2 in the control region. Calculate difference-in-differences in full-time-equivalent jobs.
CodeEvent study with clustered uncertainty
Implement event_study(df, unit, time, treat_time, y, ref=-1) for a panel with simultaneous adoption and a never-treated group. Column arguments are column names; df is a pandas DataFrame. The treat_time column contains one integer adoption period per treated unit and NaN for every observation of a never-treated unit. All treated units share the adoption period. time contains integer periods; use k = time - treat_time only for treated units. Estimate by least squares a regression including intercept, unit and period fixed effects, and one indicator per relative period observed among treated units except ref. The ref period must exist among treated units. Return a DataFrame indexed by these relative periods in increasing order, with estimate and se columns; omit the reference. Calculate unit-clustered CR1 covariance with factor G/(G-1) * (N-1)/(N-K), where G is the number of units, N the number of valid rows, and K the number of columns in the full-rank design. Do not modify the input DataFrame. Raise ValueError for missing columns, non-finite data or noninteger times, missing identifiers, duplicate unit-periods, treatment inconsistent within a unit, multiple adoption dates, absence of treated or control units, an unobserved reference, insufficient degrees of freedom, or a rank-deficient design. Do not impute missing data or permit reversed treatment. Unit-level errors describe within-unit dependence under the sampling model; if policy is assigned to a region, region may be the relevant level and few clusters require additional methods.
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 NotImplementedError
Shift+Enter to run

In 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]
QuizFour pieces of prior evidence
Assuming correctly calibrated intervals for each study, which plot shows evidence at 5% against the represented zero prior-difference restriction?
QuizAn imprecise pretest
A joint test of prior coefficients does not reject zero. What can you conclude?
QuizMany restaurants, two policies
Policy is assigned to two states and there are hundreds of restaurants. What does clustering by restaurant imply?
QuizThe control changes too
The treated state’s policy directly affects restaurants in the comparison state. What is the problem?
QuizChoose a scale
Counterfactual trends are parallel in positive levels. Must they also be parallel in logarithms?

After attempting the calculation, check it:

[ ]Check the four-means contrastBrowser
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)