Difference-in-Differences in Python: Parallel Trends Plot and Regression

Estimate a treatment effect with difference-in-differences in Python: plot parallel trends, run the regression in statsmodels, and draw an event-study chart.

Difference-in-differences (DiD) estimates the effect of something you couldn't randomize, like a program that launched in some stores but not others. In Python it is one regression: smf.ols("y ~ treated * post", ...) from statsmodels, where the coefficient on treated:post is the effect. The chart that earns your trust in that number is the parallel-trends plot.

Quick Example

This builds 60 stores with 12 weeks of sales before a loyalty program and 8 weeks after. Only 20 stores got the program. The data is simulated with a true effect of +5 ($1,000s per week).

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
n_stores, weeks = 60, np.arange(-12, 8)
store = np.repeat(np.arange(n_stores), len(weeks))
week = np.tile(weeks, n_stores)
treated = (store < 20).astype(int)
store_level = rng.normal(50, 6, n_stores) + 8 * (np.arange(n_stores) < 20)  # treated stores are bigger
trend = 0.4 * week + 3 * np.sin(week / 3)                                    # shared trend and seasonality
effect = 5.0 * treated * (week >= 0)                                         # true effect: +5
sales = store_level[store] + trend + effect + rng.normal(0, 3, len(store))
df = pd.DataFrame({"store": store, "week": week, "treated": treated,
                   "post": (week >= 0).astype(int), "sales": sales})

did = smf.ols("sales ~ treated * post", data=df).fit(
    cov_type="cluster", cov_kwds={"groups": df["store"]}
)
print(did.params["treated:post"])
print(did.conf_int().loc["treated:post"].values)

The estimate is about 5.13, with a 95% confidence interval of roughly 4.37 to 5.88, which covers the true +5. The next sections explain why the plain comparisons get this wrong and how to check the assumption behind it.

DiD assumes that without the program, treated and control stores would have moved in parallel. You can't test that directly, but you can look at the periods before the launch. Average the outcome by week and group, then plot both lines:

import matplotlib.pyplot as plt

avg = df.groupby(["week", "treated"])["sales"].mean().unstack()
fig, ax = plt.subplots(figsize=(8, 4.6))
ax.plot(avg.index, avg[0], color="#1c7ed6", marker="o", ms=4, label="Control stores")
ax.plot(avg.index, avg[1], color="#d9480f", marker="o", ms=4, label="Treated stores")
ax.axvline(-0.5, color="#868e96", ls=":")
ax.set(xlabel="Week relative to launch", ylabel="Average weekly sales ($1,000s)",
       title="Treated and control stores move together before the launch")
ax.legend(frameon=False, loc="upper left")
plt.show()

Line chart of average weekly sales for treated and control stores over 20 weeks, moving together before the launch line and separating afterward

The treated stores sit about 7 higher the whole time, which is fine. DiD doesn't need equal levels, only the same changes. Both lines dip and recover together before week 0, and then the treated line pulls away. If the lines had been diverging before the launch, the estimate would be picking up that existing drift.

Why Not Just Compare Before and After, or Treated and Control?

Each simple comparison fails in a different way:

  • Treated stores, after minus before: 12.4. This includes the upward trend that every store had, program or not.
  • Treated vs control, after launch only: 12.2. This includes the fact that treated stores were already bigger.

DiD subtracts both problems: the change in the treated group minus the change in the control group. The treated * post formula expands to treated + post + treated:post, and the interaction is that double difference.

print(did.summary().tables[1])
                   coef    std err          z      P>|z|      [0.025      0.975]
--------------------------------------------------------------------------------
Intercept       46.8043      0.694     67.471      0.000      45.445      48.164
treated          7.1206      1.381      5.156      0.000       4.414       9.828
post             7.2477      0.245     29.618      0.000       6.768       7.727
treated:post     5.1279      0.385     13.336      0.000       4.374       5.882
================================================================================

Reading the rows:

  • Intercept is the control stores' average before the launch.
  • treated is the head start the treated stores already had (7.1).
  • post is the change every store experienced (7.2).
  • treated:post is the extra change in treated stores, which is the effect (5.1).

Draw the Counterfactual

The "double difference" is easier to believe as a picture. Take the treated group's starting point and move it by the control group's change. That dashed line is what the treated stores would have done without the program, and the gap to the real line is the DiD estimate.

means = df.groupby(["treated", "post"])["sales"].mean().unstack()
pre_t, post_t = means.loc[1, 0], means.loc[1, 1]
pre_c, post_c = means.loc[0, 0], means.loc[0, 1]
counterfactual = pre_t + (post_c - pre_c)

fig, ax = plt.subplots(figsize=(7, 4.6))
ax.plot([0, 1], [pre_c, post_c], color="#1c7ed6", marker="o", lw=2, label="Control")
ax.plot([0, 1], [pre_t, post_t], color="#d9480f", marker="o", lw=2, label="Treated")
ax.plot([0, 1], [pre_t, counterfactual], color="#d9480f", ls="--", marker="o",
        mfc="white", label="Treated, if no program")
ax.annotate("", xy=(1.03, post_t), xytext=(1.03, counterfactual),
            arrowprops=dict(arrowstyle="<->"))
ax.set_xticks([0, 1], ["Before (12 weeks)", "After (8 weeks)"])
ax.legend(frameon=False, loc="upper left")
plt.show()

Two-point line chart of treated and control stores before and after launch, with a dashed counterfactual line for the treated group and an arrow showing the DiD effect of about 5

This two-point version uses the average of each period. The arrow's length equals the treated:post coefficient, 5.1 here, because the regression and the hand calculation are the same arithmetic.

Why Cluster the Standard Errors by Store?

Each store appears 20 times, and a store's weekly sales are correlated with each other. Treating them as 1,200 independent rows makes the confidence interval too narrow. cov_type="cluster" with cov_kwds={"groups": df["store"]} groups the errors by store. Cluster by whatever unit was assigned to treatment: stores, regions, or users.

With few clusters (roughly under 30 treated and control combined), cluster-robust standard errors get unreliable too. In that case look at a wild cluster bootstrap or a permutation test rather than trusting the printed interval.

An event study replaces the single post dummy with one coefficient per week, each measuring the treated-minus-control gap relative to a reference week (here week -1). The pre-launch coefficients should hover around zero, and the post-launch ones show how the effect evolves.

ref = -1
es = smf.ols(
    f"sales ~ treated + C(week, Treatment(reference={ref}))"
    f" + treated:C(week, Treatment(reference={ref}))",
    data=df,
).fit(cov_type="cluster", cov_kwds={"groups": df["store"]})

rows = []
for name in es.params.index:
    if name.startswith("treated:C(week"):
        wk = int(name.split("T.")[1].split("]")[0])
        lo, hi = es.conf_int().loc[name]
        rows.append((wk, es.params[name], lo, hi))
rows.append((ref, 0, 0, 0))
ev = pd.DataFrame(rows, columns=["week", "coef", "lo", "hi"]).sort_values("week")

fig, ax = plt.subplots(figsize=(8, 4.4))
ax.axhline(0, color="#868e96", lw=1)
ax.axvline(-0.5, color="#868e96", ls=":")
ax.errorbar(ev["week"], ev["coef"],
            yerr=[ev["coef"] - ev["lo"], ev["hi"] - ev["coef"]],
            fmt="o", color="#d9480f", ecolor="#f4a582", capsize=3)
ax.set(xlabel="Week relative to launch (week -1 is the reference)",
       ylabel="Treated minus control ($1,000s)")
plt.show()

Event-study chart of treated-minus-control sales gap by week, with coefficients near zero before the launch and roughly 5 to 6 afterward

All 12 pre-launch confidence intervals include zero, and the post-launch coefficients sit between about 4.7 and 6.5 with no sign of fading. That is the picture you want in a write-up: flat before, a step at the launch.

Passing the pre-trend check doesn't prove parallel trends held after the launch. It only means there's no visible evidence against it, and with wide intervals a real pre-trend can still hide. Treat it as a screen, not a proof.

When to Use DiD

Situation Method
You randomized the treatment A/B test analysis
One treated group, one control group, before and after data Difference-in-differences
Treatment rolled out to different units at different times Event-study / staggered DiD estimators (plain two-way fixed effects can be biased)
Only one treated unit and many possible controls Synthetic control

Practical Tips

  • Pick the control group before you look at the result. Choosing controls that make the lines look parallel after seeing the effect is a way to fool yourself.
  • Use enough pre-periods. One week before the launch can't show a trend. Ten or more can.
  • Watch for other changes at the launch date. DiD removes shared trends, but a price change that hits only the treated stores in the same week looks like the program.
  • Plot first, regress second. The regression returns a number whether or not the assumption holds. The plot is where you'd notice.
  • This post uses statsmodels 0.14.6 and a simultaneous launch. For staggered rollouts, do not reuse the treated * post model as is.

Similar Topics