Difference-in-Differences Across Provinces
Ontario listed Renavex four months before Quebec. For those four months, Quebec is a natural comparison: same drugs, same guidelines, the same national shocks, no Renavex. Difference-in-differences (DiD) compares Ontario's change with Quebec's change, so anything that moved both provinces cancels. The price is an assumption: without the listing, the two provinces would have moved in parallel. Today you estimate DiD by hand and with two-way fixed effects, test the parallel-trends assumption with an event study and placebos, handle inference with only 11 regions, and see what happens when the "control" province gets treated too.
By the end of today you can
- compute a 2 × 2 DiD by hand and as a two-way fixed effects regression
- plot pre-trends, run an event study and placebo tests, and report them
- cluster standard errors by the unit of policy and use the wild cluster bootstrap with few clusters
- make sure the control group stays untreated for the whole comparison
- present estimates under different trend assumptions when parallel trends is doubtful
Today's 5.5-hour plan
In this lesson
32.1 The comparison province (40 min)
"""Day 32.1-32.2: Ontario vs Quebec before October 2025 - do SGLT2 starts move in parallel?"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import matplotlib # noqa: E402
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.policy import load_panel, province_series # noqa: E402
p = load_panel()
on, qc = province_series(p, "ON"), province_series(p, "QC")
w = (on.t <= 60)
fig, ax = plt.subplots(figsize=(8, 3.6))
ax.plot(on.month[w], on.sglt2_rate[w], color="#4f9cf9", lw=1.5, label="Ontario")
ax.plot(qc.month[w], qc.sglt2_rate[w], color="#e93d82", lw=1.5, label="Quebec")
ax.plot(on.month[w], (on.sglt2_rate - qc.sglt2_rate)[w], color="#8b8d98", lw=1.2, ls=":", label="difference")
ax.axvline(on.month[57], color="black", lw=0.8, ls="--")
ax.set_ylabel("SGLT2 starts per 1,000 per month")
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, fontsize=8)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day32_parallel_trends.png"), dpi=150)
pre = p[p.t < 57].assign(on=lambda x: (x.province == "ON").astype(int))
m = smf.wls("sglt2_rate ~ on:t + C(region) + C(t)", pre, weights=pre.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": pre.region.factorize()[0]})
print(f"pre-period (Jan 2021-Sep 2025): Ontario minus Quebec trend {m.params['on:t']:+.4f} per month "
f"(95% CI {m.conf_int().loc['on:t', 0]:+.4f} to {m.conf_int().loc['on:t', 1]:+.4f})")
gap = (on.sglt2_rate - qc.sglt2_rate)
print(f"Ontario - Quebec gap: 2021 {gap[on.t < 12].mean():.2f}, 2023 {gap[(on.t >= 24) & (on.t < 36)].mean():.2f}, "
f"Jan-Sep 2025 {gap[(on.t >= 48) & (on.t < 57)].mean():.2f}, Oct 2025-Jan 2026 {gap[(on.t >= 57) & (on.t <= 60)].mean():.2f}")
print("wrote figures/day32_parallel_trends.png")
pre-period (Jan 2021-Sep 2025): Ontario minus Quebec trend -0.0070 per month (95% CI -0.0155 to +0.0015)
Ontario - Quebec gap: 2021 0.63, 2023 0.58, Jan-Sep 2025 0.36, Oct 2025-Jan 2026 -0.22
wrote figures/day32_parallel_trends.png

The two provinces move together month to month: the same seasonal dips, the same growth. But the gap between them narrows, from 0.63 starts per 1,000 in 2021 to 0.36 in 2025, a differential trend of −0.007 per month (95% CI −0.016 to +0.002). It is not statistically significant, but it is there, and over a few years it adds up. Then, after the listing, the gap turns negative (−0.22). How much of that last move is the listing, and how much is the narrowing continuing?
32.2 DiD by hand and by regression (40 min)
def did_2x2(p, y, treated, control, pre, post):
"""(mean y in treated regions at post - at pre) - (the same in control regions); regions weighted equally."""
m = p.pivot_table(index="t", columns="region", values=y)
return float((m.loc[post, treated] - m.loc[pre, treated]).mean() - (m.loc[post, control] - m.loc[pre, control]).mean())
"""Day 32.3: difference-in-differences - by hand (2x2 means) and as a two-way fixed effects regression."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import statsmodels.formula.api as smf # noqa: E402
from corridor.policy import load_panel, province_series # noqa: E402
p = load_panel()
w = p[p.t <= 60].reset_index(drop=True) # until Quebec lists (February 2026)
w["D"] = ((w.province == "ON") & (w.t >= 57)).astype(int)
on, qc = province_series(p, "ON"), province_series(p, "QC")
a = lambda s, lo, hi: s.sglt2_rate[(s.t >= lo) & (s.t <= hi)].mean() # noqa: E731
pre_on, post_on, pre_qc, post_qc = a(on, 45, 56), a(on, 57, 60), a(qc, 45, 56), a(qc, 57, 60)
print("2 x 2 (12 months before vs the 4 months after; SGLT2 starts per 1,000 per month):")
print(f" Ontario {pre_on:.2f} -> {post_on:.2f} change {post_on - pre_on:+.2f}")
print(f" Quebec {pre_qc:.2f} -> {post_qc:.2f} change {post_qc - pre_qc:+.2f}")
print(f" difference-in-differences {post_on - pre_on - (post_qc - pre_qc):+.2f}")
m = smf.wls("sglt2_rate ~ D + C(region) + C(t)", w, weights=w.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": w.region.factorize()[0]})
lo, hi = m.conf_int().loc["D"]
print(f"\ntwo-way fixed effects (11 regions x 61 months, weighted by people with diabetes, SEs clustered by region):")
print(f" {m.params.D:+.3f} (95% CI {lo:+.3f} to {hi:+.3f})")
w["on"] = (w.province == "ON").astype(int)
m2 = smf.wls("sglt2_rate ~ D + on:t + C(region) + C(t)", w, weights=w.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": w.region.factorize()[0]})
lo, hi = m2.conf_int().loc["D"]
print(f" + an Ontario-specific linear trend: {m2.params.D:+.3f} (95% CI {lo:+.3f} to {hi:+.3f}); "
f"trend {m2.params['on:t']:+.4f} per month")
2 x 2 (12 months before vs the 4 months after; SGLT2 starts per 1,000 per month):
Ontario 5.75 -> 5.28 change -0.47
Quebec 5.42 -> 5.50 change +0.08
difference-in-differences -0.55
two-way fixed effects (11 regions x 61 months, weighted by people with diabetes, SEs clustered by region):
-0.792 (95% CI -1.116 to -0.468)
+ an Ontario-specific linear trend: -0.586 (95% CI -1.017 to -0.155); trend -0.0069 per month
In the 2 × 2, Ontario fell by 0.47 and Quebec rose by 0.08, so the difference-in-differences is −0.55. The regression version, with region and month fixed effects on all 61 months, gives −0.79. They differ because the regression compares the four post months with the whole pre-period (2021–2025), and over that span the narrowing gap accumulates. Adding an Ontario-specific linear trend absorbs the narrowing and gives −0.59 (95% CI −1.02 to −0.15).
Which is right? Each makes a different assumption about the counterfactual: parallel levels after removing fixed effects, or parallel deviations from province-specific trends. The event study shows which assumption fits the data.
32.3 Event study (45 min)
An event study replaces the single "post" indicator with one indicator per month relative to the listing, with the month before (September 2025) as the reference. The leads (months before) test parallel trends; the lags show how the effect unfolds.
"""Day 32.4: an event study - Ontario minus Quebec, month by month, relative to September 2025."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import matplotlib # noqa: E402
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.policy import load_panel # noqa: E402
p = load_panel()
w = p[p.t <= 60].reset_index(drop=True)
rel = np.where(w.province == "ON", np.clip(w.t - 57, -13, 3), -1) # bin 13+ months before; -1 is the reference
for k in range(-13, 4):
if k != -1:
w[f"e{k + 13}"] = (rel == k).astype(int)
terms = [f"e{k + 13}" for k in range(-13, 4) if k != -1]
m = smf.wls("sglt2_rate ~ " + " + ".join(terms) + " + C(region) + C(t)", w, weights=w.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": w.region.factorize()[0]})
ks = [k for k in range(-13, 4) if k != -1]
est = np.array([m.params[f"e{k + 13}"] for k in ks])
ci = np.array([m.conf_int().loc[f"e{k + 13}"].to_numpy() for k in ks])
print(f"{'month vs Sep 2025':>18}{'estimate':>10} 95% CI")
for k, e, c in zip(ks, est, ci):
print(f"{('<= ' if k == -13 else '') + str(k):>18}{e:>+10.2f} {c[0]:+.2f} to {c[1]:+.2f}")
lead = est[np.array(ks) < -1]
print(f"\nleads (months -13 to -2): mean {lead.mean():+.2f}, {int((lead > 0).sum())} of {len(lead)} positive; "
f"lags (0 to 3): mean {est[np.array(ks) >= 0].mean():+.2f}")
fig, ax = plt.subplots(figsize=(7.5, 3.6))
ax.errorbar(ks, est, yerr=[est - ci[:, 0], ci[:, 1] - est], fmt="o", color="#22b8cf", ecolor="#8b8d98", ms=4)
ax.plot([-1], [0], "o", color="black", ms=4)
ax.axhline(0, color="black", lw=0.8)
ax.axvline(-0.5, color="#8b8d98", lw=0.8, ls="--")
ax.set_xlabel("months relative to the Ontario listing (October 2025 = 0; -13 = 13 or more before)")
ax.set_ylabel("Ontario - Quebec, starts per 1,000")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day32_event_study.png"), dpi=150)
print("wrote figures/day32_event_study.png")
month vs Sep 2025 estimate 95% CI
<= -13 +0.54 -0.27 to +1.36
-12 +0.08 -0.90 to +1.06
-11 +0.25 -0.91 to +1.40
-10 +0.14 -0.87 to +1.14
-9 +0.27 -0.69 to +1.24
-8 +0.66 -0.21 to +1.52
-7 -0.10 -1.01 to +0.82
-6 +0.60 -0.24 to +1.45
-5 +0.25 -0.39 to +0.88
-4 +0.40 -0.14 to +0.94
-3 +0.37 -0.62 to +1.37
-2 -0.09 -0.72 to +0.53
0 -0.43 -1.36 to +0.51
1 -0.40 -1.51 to +0.71
2 -0.32 -1.17 to +0.53
3 -0.12 -1.31 to +1.07
leads (months -13 to -2): mean +0.28, 10 of 12 positive; lags (0 to 3): mean -0.32
wrote figures/day32_event_study.png

Ten of the twelve leads are positive (mean +0.28): in the year before listing, Ontario sat above where September 2025 put it. September was a low month for Ontario relative to Quebec, and the gap had been shrinking. The lags (mean −0.32) are relative to that low month, so they are smaller than the static DiD's −0.79. With one reference month, event studies are noisy, but they show what the single coefficient hides.
Try it (15 min). Run placebo DiDs on pre-listing data only, pretending Ontario listed in October 2023 or October 2024. A design with parallel trends should give placebo effects near zero.
Solution
"""Day 32 try it: a placebo - pretend Ontario listed in October 2024 and use only data before the real listing."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import statsmodels.formula.api as smf # noqa: E402
from corridor.policy import load_panel # noqa: E402
p = load_panel()
for fake in (33, 45): # October 2023, October 2024
d = p[p.t < 57].reset_index(drop=True).assign(D=lambda x: ((x.province == "ON") & (x.t >= fake)).astype(int))
m = smf.wls("sglt2_rate ~ D + C(region) + C(t)", d, weights=d.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": d.region.factorize()[0]})
lo, hi = m.conf_int().loc["D"]
print(f"placebo listing {d.month[d.t == fake].iloc[0]:%B %Y}: {m.params.D:+.3f} (95% CI {lo:+.3f} to {hi:+.3f})")
placebo listing October 2023: -0.252 (95% CI -0.518 to +0.014)
placebo listing October 2024: -0.309 (95% CI -0.708 to +0.089)
Both placebos are negative (−0.25 and −0.31), with intervals that only just include zero. Ontario's "effect" when nothing happened is the narrowing trend again. A placebo that is a third the size of your estimate is a warning; report it.
32.4 Eleven clusters (40 min)
Region-months are not independent: a region's shocks persist (Day 31's autocorrelation), so standard errors must be clustered by region. With 11 regions and 5 treated, even clustered standard errors are unreliable: the cluster-robust variance needs many clusters. The wild cluster bootstrap keeps each region's residuals together, flips their sign with random weights (Webb's six-point distribution, designed for few clusters), and imposes the null hypothesis when generating the bootstrap samples.
def _wls_cr1(x, y, w, cl, k=1):
"""WLS coefficient k and its CR1 cluster-robust standard error."""
sw = np.sqrt(w)
xw, yw = x * sw[:, None], y * sw
bread = np.linalg.pinv(xw.T @ xw)
b = bread @ xw.T @ yw
u = yw - xw @ b
g = np.unique(cl)
meat = sum(np.outer(s, s) for s in (xw[cl == c].T @ u[cl == c] for c in g))
n, kx, G = len(y), np.linalg.matrix_rank(xw), len(g)
v = bread @ meat @ bread * G / (G - 1) * (n - 1) / (n - kx)
return b[k], float(np.sqrt(v[k, k]))
def wild_cluster_bootstrap(p, y, d, w, cluster, reps=999, seed=2026):
"""Wild cluster bootstrap-t (null imposed, Webb six-point weights) for the coefficient on d in a weighted
two-way fixed effects regression. Returns (estimate, CR1 SE, CR1 p-value, bootstrap p-value)."""
from scipy import stats
rng = np.random.default_rng(seed)
x, yv, wv = fe_design(p, d), p[y].to_numpy(float), np.asarray(w, float)
cl = p[cluster].to_numpy()
b, se = _wls_cr1(x, yv, wv, cl)
xr = np.delete(x, 1, axis=1) # the model with the effect set to 0
sw = np.sqrt(wv)
br = np.linalg.lstsq(xr * sw[:, None], yv * sw, rcond=None)[0]
fit, res = xr @ br, yv - xr @ br
groups = np.unique(cl)
idx = np.searchsorted(groups, cl)
webb = np.array([-np.sqrt(1.5), -1, -np.sqrt(0.5), np.sqrt(0.5), 1, np.sqrt(1.5)])
tstar = []
for _ in range(reps):
v = rng.choice(webb, len(groups))[idx]
bs, ss = _wls_cr1(x, fit + v * res, wv, cl)
tstar.append(bs / ss)
G = len(groups)
return float(b), se, float(2 * stats.t.sf(abs(b / se), G - 1)), float(np.mean(np.abs(tstar) >= abs(b / se)))
"""Day 32.5: inference with 11 clusters (5 treated) - classical, clustered, and the wild cluster bootstrap."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import statsmodels.formula.api as smf # noqa: E402
from corridor.policy import load_panel, wild_cluster_bootstrap # noqa: E402
p = load_panel()
w = p[p.t <= 60].reset_index(drop=True)
w["D"] = ((w.province == "ON") & (w.t >= 57)).astype(int)
f = "sglt2_rate ~ D + C(region) + C(t)"
iid = smf.wls(f, w, weights=w.people_with_diabetes).fit()
print(f"estimate {iid.params.D:+.3f}")
print(f" classical SE (every region-month independent): {iid.bse.D:.3f}, p = {iid.pvalues.D:.4f}")
b, se, p_cr1, p_wild = wild_cluster_bootstrap(w, "sglt2_rate", "D", w.people_with_diabetes, "region", reps=999)
print(f" clustered by region (CR1, t with 10 df): {se:.3f}, p = {p_cr1:.4f}")
print(f" wild cluster bootstrap-t (Webb weights, 999): p = {p_wild:.3f}")
estimate -0.792
classical SE (every region-month independent): 0.122, p = 0.0000
clustered by region (CR1, t with 10 df): 0.165, p = 0.0007
wild cluster bootstrap-t (Webb weights, 999): p = 0.003
Ignoring clustering gives p < 0.0001; clustering, 0.0007; the wild bootstrap, 0.003. Here the conclusion survives, but with fewer treated clusters (one province vs one province, for example) the differences are often the difference between "significant" and not. Bertrand, Duflo and Mullainathan showed in 2004 that DiD studies ignoring serial correlation reject a true null far too often.
Check it in R (fixest, the standard tool for fixed effects):
# Day 32: the DiD and event study in R with fixest (clustered by region).
suppressPackageStartupMessages({ library(fixest) })
p <- read.csv("data/drug_utilization_monthly.csv")
p$t <- (as.integer(substr(p$month, 1, 4)) - 2021) * 12 + as.integer(substr(p$month, 6, 7)) - 1
p$rate <- 1000 * p$sglt2_starts / p$people_with_diabetes
w <- subset(p, t <= 60)
w$D <- as.integer(w$province == "ON" & w$t >= 57)
m <- feols(rate ~ D | region + t, data = w, weights = ~people_with_diabetes, cluster = ~region)
print(round(coeftable(m), 4))
w$rel <- ifelse(w$province == "ON", pmax(w$t - 57, -13), -1000)
es <- feols(rate ~ i(rel, ref = c(-1, -1000)) | region + t, data = w, weights = ~people_with_diabetes, cluster = ~region)
ct <- coeftable(es)
print(round(ct[grepl("::(-6|-3|-2|0|1|2|3)$", rownames(ct)), 1:2], 3))
Estimate Std. Error t value Pr(>|t|)
D -0.7921 0.1641 -4.8272 7e-04
attr(,"vcov_type")
[1] "Clustered (region)"
Estimate Std. Error
rel::-6 0.602 0.427
rel::-3 0.373 0.502
rel::-2 -0.095 0.316
rel::0 -0.426 0.473
rel::1 -0.401 0.561
rel::2 -0.320 0.430
rel::3 -0.121 0.601
32.5 Truth check (30 min)
"""Day 32 truth check: the DiD and the event study against the generator."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.policy import load_panel, truth_panel # noqa: E402
p = load_panel()
tr = truth_panel().merge(p[["region", "month", "t", "people_with_diabetes", "province"]], on=["region", "month"])
o = tr[(tr.province == "ON") & (tr.t >= 57) & (tr.t <= 60)]
w = o.people_with_diabetes
print(f"true effect in Ontario, Oct 2025-Jan 2026: {((o.sglt2_rate - o.sglt2_rate_no_listing) * w).sum() / w.sum():+.3f}")
by = ((o.sglt2_rate - o.sglt2_rate_no_listing) * w).groupby(o.t).sum() / w.groupby(o.t).sum()
print("by month: " + ", ".join(f"{k - 57}: {v:+.2f}" for k, v in by.items()))
cf = {}
for prov in ("ON", "QC"):
q = tr[tr.province == prov]
wq = q.people_with_diabetes
cf[prov] = (q.sglt2_rate_no_listing * wq).groupby(q.t).sum() / wq.groupby(q.t).sum()
gap = cf["ON"] - cf["QC"]
print(f"\nwithout any listing, Ontario - Quebec would have been: Oct 2024-Sep 2025 {gap.loc[45:56].mean():.2f}, "
f"Oct 2025-Jan 2026 {gap.loc[57:60].mean():.2f} (change {gap.loc[57:60].mean() - gap.loc[45:56].mean():+.2f})")
true effect in Ontario, Oct 2025-Jan 2026: -0.373
by month: 0: -0.20, 1: -0.35, 2: -0.44, 3: -0.51
without any listing, Ontario - Quebec would have been: Oct 2024-Sep 2025 0.37, Oct 2025-Jan 2026 0.15 (change -0.21)
The true effect over the four months is −0.37, growing from −0.20 to −0.51 as Renavex uptake ramps up. The static DiD (−0.79) is twice too large. The truth check shows why: without any listing, the Ontario–Quebec gap would have shrunk by 0.21 over the same months. Parallel trends fails, partly because of the gradual convergence the event study and placebos detected, and partly because of the Ontario-specific shock Day 31 found.
The trend-adjusted DiD (−0.59, CI −1.02 to −0.15) and the short-window 2 × 2 (−0.55) are closer, and the trend-adjusted interval covers the truth. The event study's lags (mean −0.32) are closest, but they rest on a single reference month. No version is free of assumptions. The honest report shows the event study, the placebos, and the estimate with and without the trend.
Why it matters at work: "Ontario vs Quebec" (or province vs province) comparisons are everywhere in Canadian health policy research, because provinces make different decisions at different times. A reviewer's first question is always the parallel-trends plot. The second is how many clusters you have.
Where you'll meet this: evaluations of provincial pharmacare changes (OHIP+, Quebec's drug insurance reforms); ICES and CIHI interprovincial comparisons; CDA-AMC's real-world evidence on listing decisions
32.6 A control that gets treated (20 min)
Bug of the day. "Use all the data": keep Quebec as the control through December 2027.
"""Day 32 bug of the day: 'use all the data' - keep Quebec as the control after it lists Renavex too."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import statsmodels.formula.api as smf # noqa: E402
from corridor.policy import load_panel # noqa: E402
p = load_panel()
for label, d in (("Jan 2021-Jan 2026 (Quebec untreated)", p[p.t <= 60]), ("Jan 2021-Dec 2027 (all data)", p)):
d = d.reset_index(drop=True).assign(D=lambda x: ((x.province == "ON") & (x.t >= 57)).astype(int))
m = smf.wls("sglt2_rate ~ D + C(region) + C(t)", d, weights=d.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": d.region.factorize()[0]})
print(f"{label:<40}{m.params.D:+.3f} post months for Ontario: {int(d.D.sum() / 5)}")
Jan 2021-Jan 2026 (Quebec untreated) -0.792 post months for Ontario: 4
Jan 2021-Dec 2027 (all data) -0.415 post months for Ontario: 27
After February 2026, Quebec has Renavex too, and its SGLT2 initiation falls for the same reason Ontario's did. Using it as the control subtracts part of the effect from itself. The estimate shrinks to −0.42, while the truth for Ontario over those 27 months is −0.84 (Day 31's truth check). A control must be untreated for the whole comparison. When everyone is eventually treated at different times, the problem becomes staggered adoption: tomorrow.
32.7 Mini-project: the brief's numbers (45 min)
Put the designs side by side for a one-paragraph brief, docs/did_listing.csv:
"""Day 32 mini-project: the numbers for a one-paragraph policy brief, in one table (docs/did_listing.csv)."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import pandas as pd # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.policy import its, its_average_effect, load_panel, province_series, wild_cluster_bootstrap # noqa: E402
p = load_panel()
w = p[p.t <= 60].reset_index(drop=True)
w["D"] = ((w.province == "ON") & (w.t >= 57)).astype(int)
m = smf.wls("sglt2_rate ~ D + C(region) + C(t)", w, weights=w.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": w.region.factorize()[0]})
_, _, _, p_wild = wild_cluster_bootstrap(w, "sglt2_rate", "D", w.people_with_diabetes, "region", reps=999)
w["on"] = (w.province == "ON").astype(int)
m2 = smf.wls("sglt2_rate ~ D + on:t + C(region) + C(t)", w, weights=w.people_with_diabetes).fit(
cov_type="cluster", cov_kwds={"groups": w.region.factorize()[0]})
fit, d = its(province_series(p, "ON"), "sglt2_rate", 57)
its4 = its_average_effect(fit, d, 4)
base = province_series(p, "ON").sglt2_rate[(d.t >= 45) & (d.t <= 56)].mean()
rows = [{"design": "ITS, Ontario alone (GLS AR(1))", "months": "Oct 2025-Jan 2026", "effect": its4[0],
"ci_low": its4[1], "ci_high": its4[2], "p": None},
{"design": "DiD, Ontario vs Quebec (TWFE, clustered)", "months": "Oct 2025-Jan 2026", "effect": m.params.D,
"ci_low": m.conf_int().loc["D", 0], "ci_high": m.conf_int().loc["D", 1], "p": p_wild},
{"design": "DiD + Ontario-specific trend", "months": "Oct 2025-Jan 2026", "effect": m2.params.D,
"ci_low": m2.conf_int().loc["D", 0], "ci_high": m2.conf_int().loc["D", 1], "p": m2.pvalues.D}]
t = pd.DataFrame(rows).round(3)
t["percent_of_baseline"] = (100 * t.effect / base).round(1)
t.to_csv(os.path.join(ROOT, "docs", "did_listing.csv"), index=False)
print(f"Ontario baseline (Oct 2024-Sep 2025): {base:.2f} SGLT2 starts per 1,000 per month")
print(t.to_string(index=False))
Ontario baseline (Oct 2024-Sep 2025): 5.75 SGLT2 starts per 1,000 per month
design months effect ci_low ci_high p percent_of_baseline
ITS, Ontario alone (GLS AR(1)) Oct 2025-Jan 2026 -0.722 -0.968 -0.475 NaN -12.6
DiD, Ontario vs Quebec (TWFE, clustered) Oct 2025-Jan 2026 -0.792 -1.116 -0.468 0.003 -13.8
DiD + Ontario-specific trend Oct 2025-Jan 2026 -0.586 -1.017 -0.155 0.008 -10.2
Write the paragraph: in the four months after listing, Ontario's SGLT2 initiation fell by about 10–14% relative to Quebec. Then add the caveats: the provinces' trends were converging before the listing, so the larger estimates are likely too large; and four months is too short to see the full substitution.
32.8 Save your work
python -m pytest -q
git add .
git commit -m "Day 32: difference-in-differences, Ontario vs Quebec"
Day 32 checklist
- I can compute a 2 × 2 DiD by hand and as a two-way fixed effects regression
- I plot pre-trends, run an event study and placebo tests, and report them
- I cluster standard errors by the unit of policy and use the wild cluster bootstrap with few clusters
- I make sure the control group stays untreated for the whole comparison
- I present estimates under different trend assumptions when parallel trends is doubtful
Bloc français (30 min)
Thème : la méthode des doubles différences.
L'Ontario a inscrit le Renavex quatre mois avant le Québec. La méthode des doubles différences compare la variation observée en Ontario à celle du Québec pendant ces quatre mois. Elle suppose que, sans l'inscription, les deux provinces auraient évolué en parallèle. Une étude d'événements et des tests placebo permettent de vérifier cette hypothèse.
| Français | English |
|---|---|
| la méthode des doubles différences | difference-in-differences |
| le groupe témoin | the control group |
| l'hypothèse de tendances parallèles | the parallel trends assumption |
| l'étude d'événements | the event study |
| le test placebo | the placebo test |
| les effets fixes | fixed effects |
| la grappe | the cluster |
| l'erreur type robuste par grappe | the cluster-robust standard error |
| le bootstrap sauvage par grappe | the wild cluster bootstrap |
| le groupe témoin contaminé | the contaminated control group |
| la convergence | convergence |
| l'écart entre les provinces | the gap between provinces |
Exercices
- Translate: "The gap between Ontario and Quebec was narrowing before the listing."
- Translate: « Après février 2026, le Québec n'est plus un groupe témoin valide. »
- In three French sentences, explain why 11 regions are not enough for ordinary clustered standard errors.
Réponses
- L'écart entre l'Ontario et le Québec se réduisait avant l'inscription.
- "After February 2026, Quebec is no longer a valid control group."
- Example: Les erreurs types robustes par grappe reposent sur un grand nombre de grappes. Avec 11 régions, dont 5 traitées, elles sont trop petites. Le bootstrap sauvage par grappe donne des valeurs p plus fiables.