# Event Study Plot in Python for Staggered Difference-in-Differences

> Draw an event-study plot for staggered difference-in-differences in Python with statsmodels, compare it with a clean-comparison estimator, and see how two-way fixed effects creates fake pre-trends when effects grow over time.

Source: https://www.pythoncharts.com/causal-inference/event-study-staggered-did-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: Causal Inference | Tags: causal inference, difference in differences, event study, staggered adoption, two-way fixed effects, parallel trends, statsmodels

An event-study plot shows the treatment effect at each period relative to when a unit was treated: the points before time 0 test parallel trends, and the points after show how the effect builds. For a single launch date, a regression with relative-time dummies in `statsmodels` produces it. When units are treated at different times (a staggered rollout) and the effect changes with exposure, the two-way fixed effects (TWFE) version gets distorted. The fix is to compare each cohort only with clean controls, as shown below. The code targets statsmodels 0.14.

## Quick Example

A retailer rolls out a feature to stores in three waves (months 8, 12 and 16), and 40% of stores never get it. The effect grows with exposure and is larger in later waves. This builds the data, estimates the effect at each month relative to launch using only never-treated stores as controls, and draws the plot. It runs without downloads.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(77)
n_units, n_periods = 400, 24
cohort_of = rng.choice([8, 12, 16, 0], size=n_units, p=[0.2, 0.2, 0.2, 0.4])   # 0 = never treated
unit_fe = rng.normal(0, 3, n_units)
time_fe = np.linspace(0, 4, n_periods)

rows = []
for i in range(n_units):
    g = cohort_of[i]
    for t in range(n_periods):
        k = t - g if g else np.nan                          # event time
        effect = 0.0
        if g and k >= 0:
            effect = min(1.0 + 1.0 * k, 9.0) * {8: 0.4, 12: 1.0, 16: 1.6}[g]
        y = 50 + unit_fe[i] + time_fe[t] + effect + rng.normal(0, 1.5)
        rows.append((i, t, g, k, effect, y))
df = pd.DataFrame(rows, columns=["unit", "t", "cohort", "k", "true_effect", "y"])

# Clean comparisons: each cohort vs never-treated stores, relative to the month before launch
wide = df.pivot(index="unit", columns="t", values="y")
never = wide.loc[cohort_of == 0]
res = []
for g in [8, 12, 16]:
    treated = wide.loc[cohort_of == g]
    for k in range(-6, 9):
        t = g + k
        if k == -1 or t < 0 or t >= n_periods:
            continue
        d_t = treated[t] - treated[g - 1]
        d_c = never[t] - never[g - 1]
        res.append((g, k, d_t.mean() - d_c.mean(), d_t.var() / len(d_t) + d_c.var() / len(d_c), len(d_t)))
cs = pd.DataFrame(res, columns=["cohort", "k", "att", "var", "n"])

est = []
for k, x in cs.groupby("k"):
    w = x["n"] / x["n"].sum()
    est.append((k, np.sum(w * x["att"]), np.sqrt(np.sum(w**2 * x["var"]))))
clean = pd.DataFrame(est, columns=["k", "est", "se"])
clean = pd.concat([clean, pd.DataFrame({"k": [-1], "est": [0.0], "se": [0.0]})]).sort_values("k")

fig, ax = plt.subplots(figsize=(7.5, 4.3))
ax.axhline(0, color="#999", lw=1)
ax.axvline(-0.5, color="#999", ls="--", lw=1)
ax.errorbar(clean["k"], clean["est"], yerr=1.96 * clean["se"], fmt="o-", color="#2f6690", capsize=3)
ax.set_xlabel("Months relative to launch (event time 0 = first treated month)")
ax.set_ylabel("Effect on sales, vs month -1")
plt.show()
```

![Event-study plot: estimates near zero from month -6 to -1, then rising from 0.8 at launch to about 7.5 at month 7](https://www.pythoncharts.com/causal-inference/event-study-staggered-did-python/images/event-study-plot.png)

The pre-launch points sit around zero (between -0.08 and 0.13, with intervals that include zero), which supports parallel trends. After launch the effect grows from 0.81 in month 0 to 7.54 in month 7. The month before launch (event time -1) is the reference and is fixed at zero by construction.

## What Does the Staggered Design Look Like?

![Average sales over 24 months for stores launched in month 8, 12 and 16 and for never-treated stores; each launched group climbs above the never-treated line after its launch month](https://www.pythoncharts.com/causal-inference/event-study-staggered-did-python/images/event-study-design.png)

Each wave bends away from the never-treated line at its own launch date. A pre/post comparison or a single treated dummy would mix waves that are at different stages of exposure.

## Why Does Two-Way Fixed Effects Give a Wrong Event Study?

The standard approach is one regression with a dummy for each event time, plus unit and period fixed effects:

```python
import statsmodels.formula.api as smf

ks = [k for k in range(-6, 9) if k != -1]
names = {k: (f"m{abs(k)}" if k < 0 else f"p{k}") for k in ks}
for k, name in names.items():
    df[name] = (df["k"] == k).astype(int)
df[names[-6]] = (df["k"] <= -6).astype(int)      # bin the far lead
df[names[8]] = (df["k"] >= 8).astype(int)        # bin the far lag

twfe = smf.ols("y ~ " + " + ".join(names.values()) + " + C(unit) + C(t)", df).fit(
    cov_type="cluster", cov_kwds={"groups": df["unit"]})
tw = pd.DataFrame({"k": ks, "est": [twfe.params[n] for n in names.values()],
                   "se": [twfe.bse[n] for n in names.values()]})
print(tw.round(2).iloc[[0, 1, 2, 5, 11, 13]])
```

With staggered timing, the already-treated waves act as controls for later waves, and their growing effects get subtracted out as if they were trends. The result:

![True average effect compared with two-way fixed effects estimates and clean-comparison estimates; the fixed effects estimates show negative pre-launch values and fall below the truth after launch](https://www.pythoncharts.com/causal-inference/event-study-staggered-did-python/images/event-study-twfe-vs-clean.png)

| Event time | True average effect | TWFE | Clean comparison |
|---|---|---|---|
| -6 | 0 | -1.39 | -0.07 |
| -3 | 0 | -0.45 | -0.08 |
| 7 | 7.63 | 7.08 | 7.54 |
| 8 | 6.40 | 5.20 | 6.76 |

TWFE shows negative "pre-trends" of up to -1.39 even though there are none, and it understates the late effects. An analyst reading the TWFE plot could wrongly conclude that parallel trends fails, or that the effect fades at month 8. The clean comparison stays close to zero before launch and tracks the true effect afterward. The numbers are from this single seeded simulation.

## Which Estimator Should I Use?

| Estimator | Idea | When to use |
|---|---|---|
| TWFE event study | One regression, relative-time dummies | A single launch date, or effects that are constant over time |
| Clean never-treated comparison (above) | Each cohort vs never-treated, then average | You have never-treated units |
| Not-yet-treated comparison | Use units not yet treated as controls | Everyone is eventually treated |
| Packaged estimators | Callaway-Sant'Anna, Sun-Abraham, imputation estimators | You want standard errors, covariates and tested code |

The clean estimator above is a simplified version of the Callaway-Sant'Anna idea with no covariates. The standard errors treat cohorts as independent and ignore correlation across event times. Use a maintained package for published work. Python packages exist for these estimators, but I did not run any here, so check their current documentation.

## Practical Tips

- Always omit one reference period, usually -1, and say so on the plot.
- Bin the far ends of the window, as above, instead of leaving them out.
- Pre-period points near zero do not prove parallel trends, since power can be low. Report the intervals.
- Plot the raw cohort averages first so readers can see the design.
- With a single treated cohort and a clear control group, the plain [difference-in-differences regression](https://www.pythoncharts.com/causal-inference/difference-in-differences-python/) is enough.

## Similar Topics

- [Difference-in-Differences in Python: Parallel Trends Plot and Regression](https://www.pythoncharts.com/causal-inference/difference-in-differences-python/)
- [Synthetic Control in Python: Build the Counterfactual and Run Placebo Tests](https://www.pythoncharts.com/causal-inference/synthetic-control-python/)
- [Causal Inference in Python: How to Choose a Method](https://www.pythoncharts.com/causal-inference/causal-inference-python-guide/)
