Synthetic Control
When one province adopts a policy and the others don't, which province is Ontario's comparison? None of them on its own. A synthetic control builds one: a weighted average of other provinces whose history matches Ontario's before the policy. After the policy, the gap between Ontario and its synthetic twin is the estimated effect. Today you build a synthetic Ontario to evaluate CGM coverage, test the result with placebos, and learn the method's two classic mistakes.
By the end of today you can
- build a synthetic control with non-negative weights summing to 1, fitted on pre-policy data only
- check the pre-period fit before reading the post-period gap
- exclude donors exposed to the same or a similar policy
- use placebos in space and report the rank, knowing the smallest p-value possible
- report leave-one-out donor sensitivity
Today's 5.5-hour plan
In this lesson
34.1 Ten provinces (30 min)
def load_provinces():
"""Quarterly ED visits for glycemic emergencies per 1,000 adults with diabetes, wide: quarters x provinces."""
import duckdb
d = duckdb.sql(f"SELECT * FROM read_csv('{DATA}/provincial_diabetes_quarterly.csv')").df()
d["rate"] = 1000 * d.glycemic_ed_visits / d.adults_with_diabetes
w = d.pivot(index="quarter", columns="province", values="rate")
return w.sort_index()
"""Day 34.1: ED visits for glycemic emergencies per 1,000 adults with diabetes, ten provinces, 2016-2027."""
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
from corridor.db import ROOT # noqa: E402
from corridor.quasi import load_provinces # noqa: E402
w = load_provinces()
print(f"{w.shape[1]} provinces x {w.shape[0]} quarters ({w.index[0]} to {w.index[-1]})")
print(w.loc[["2016Q1", "2019Q4", "2020Q3", "2023Q4", "2027Q4"]].round(2).to_string())
fig, ax = plt.subplots(figsize=(8.5, 4))
x = range(len(w))
for c in w.columns:
ax.plot(x, w[c], color="#4f9cf9" if c == "ON" else "#8b8d98", lw=2 if c == "ON" else 0.8, alpha=1 if c == "ON" else 0.6)
ax.annotate(c, (len(w) - 1, w[c].iloc[-1]), fontsize=7, xytext=(3, 0), textcoords="offset points")
ax.axvline(list(w.index).index("2024Q1") - 0.5, color="black", lw=0.8, ls="--")
ax.set_xticks(range(0, len(w), 8))
ax.set_xticklabels(w.index[::8])
ax.set_ylabel("glycemic ED visits per 1,000 per quarter")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day34_provinces.png"), dpi=150)
print("wrote figures/day34_provinces.png")
10 provinces x 48 quarters (2016Q1 to 2027Q4)
province AB BC MB NB NL NS ON PE QC SK
quarter
2016Q1 3.84 5.30 6.19 5.36 4.45 6.49 5.52 4.33 4.21 5.09
2019Q4 3.47 5.04 5.42 4.16 4.65 5.47 5.00 4.73 3.25 4.20
2020Q3 2.19 3.77 3.69 3.52 3.08 4.22 3.67 2.47 2.03 3.22
2023Q4 3.21 4.17 4.91 4.41 4.25 5.31 4.51 3.73 3.17 3.99
2027Q4 3.15 3.71 4.04 4.59 3.43 4.77 3.48 3.20 3.16 3.11
wrote figures/day34_provinces.png

All provinces share a slow decline as care improves, a five-year cycle, seasonality, and a deep dip in 2020 when people stayed away from emergency departments. Their levels differ: Nova Scotia and Manitoba are high, Alberta and Quebec low. Ontario is in the middle, so a mix of provinces can match it. That is the condition synthetic control needs: the treated unit must be inside the range of the donors, not at the edge.
34.2 Building a synthetic Ontario (50 min)
Choose non-negative weights that sum to 1, so that the weighted average of donor provinces tracks Ontario as closely as possible over 2016–2023. The constraints keep the synthetic control an interpolation of real provinces, never an extrapolation (Abadie, Diamond and Hainmueller, 2010).
def synth_weights(y1_pre, y0_pre):
"""Donor weights w >= 0, sum(w) = 1, minimizing the pre-period squared gap between the treated series
and the weighted donors (outcomes as predictors)."""
from scipy.optimize import minimize
k = y0_pre.shape[1]
obj = lambda w: np.sum((y1_pre - y0_pre @ w) ** 2) # noqa: E731
r = minimize(obj, np.full(k, 1 / k), method="SLSQP", bounds=[(0, 1)] * k,
constraints=[{"type": "eq", "fun": lambda w: w.sum() - 1}], options={"ftol": 1e-12, "maxiter": 500})
return r.x
def synth(wide, treated, start, donors=None):
"""Fit a synthetic control for `treated` using quarters before `start` (a label such as '2024Q1').
Returns a dict: weights (Series), synthetic (Series), gap (Series), pre/post RMSPE."""
donors = [c for c in wide.columns if c != treated] if donors is None else donors
pre = wide.index < start
w = synth_weights(wide.loc[pre, treated].to_numpy(), wide.loc[pre, donors].to_numpy())
syn = pd.Series(wide[donors].to_numpy() @ w, index=wide.index)
gap = wide[treated] - syn
rmspe = lambda g: float(np.sqrt(np.mean(g ** 2))) # noqa: E731
return {"weights": pd.Series(w, index=donors), "synthetic": syn, "gap": gap,
"pre_rmspe": rmspe(gap[pre]), "post_rmspe": rmspe(gap[~pre])}
"""Day 34.2-34.3: a synthetic Ontario from the other provinces, fitted on 2016-2023, compared after 2024 Q1.
Saskatchewan covered CGMs itself from 2025 Q3, so it is not a valid donor."""
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
from corridor.db import ROOT # noqa: E402
from corridor.quasi import load_provinces, synth # noqa: E402
w = load_provinces()
donors = [c for c in w.columns if c not in ("ON", "SK")]
r = synth(w, "ON", "2024Q1", donors)
print("donor weights:")
print(" " + " ".join(f"{k} {v:.3f}" for k, v in r["weights"].sort_values(ascending=False).items() if v > 0.001))
print(f"pre-period fit: RMSPE {r['pre_rmspe']:.3f} visits per 1,000 (Ontario's pre-period mean {w.ON[w.index < '2024Q1'].mean():.2f})")
post = r["gap"][w.index >= "2024Q1"]
syn_post = r["synthetic"][w.index >= "2024Q1"]
print(f"\nOntario minus synthetic Ontario, 2024 Q1-2027 Q4: mean {post.mean():+.3f} ({100 * post.mean() / syn_post.mean():+.1f}%)")
for y in ("2024", "2025", "2026", "2027"):
g = r["gap"][r["gap"].index.str.startswith(y)]
print(f" {y}: {g.mean():+.3f}")
fig, ax = plt.subplots(figsize=(8.5, 3.8))
x = range(len(w))
ax.plot(x, w.ON, color="#4f9cf9", lw=1.8, label="Ontario")
ax.plot(x, r["synthetic"], color="#22b8cf", lw=1.4, ls="--", label="synthetic Ontario")
ax.axvline(list(w.index).index("2024Q1") - 0.5, color="black", lw=0.8)
ax.set_xticks(range(0, len(w), 8))
ax.set_xticklabels(w.index[::8])
ax.set_ylabel("glycemic ED visits per 1,000")
ax.legend(frameon=False, fontsize=8)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day34_synthetic.png"), dpi=150)
print("wrote figures/day34_synthetic.png")
donor weights:
BC 0.582 NS 0.210 QC 0.107 MB 0.094 PE 0.007
pre-period fit: RMSPE 0.112 visits per 1,000 (Ontario's pre-period mean 4.74)
Ontario minus synthetic Ontario, 2024 Q1-2027 Q4: mean -0.407 (-9.9%)
2024: -0.261
2025: -0.476
2026: -0.450
2027: -0.441
wrote figures/day34_synthetic.png
Synthetic Ontario is 58% British Columbia, 21% Nova Scotia, 11% Quebec, 9% Manitoba and a trace of PEI. Saskatchewan is excluded from the donor pool because it adopted the same policy in 2025 Q3: a donor must stay untreated for the whole post-period, the same rule as Day 32's control province. The pre-period fit is close (RMSPE 0.11 visits per 1,000, against a level of 4.7).
34.3 Reading the gap (30 min)

After 2024 Q1, Ontario falls below its synthetic twin: −0.26 visits per 1,000 per quarter in 2024, about −0.45 in 2025–2027, a 10% reduction over the four years. The effect builds over the first year as people get CGMs and learn to use them, then holds.
Two things make this credible: the close pre-period fit over 32 quarters, including the 2020 shock (the synthetic Ontario dips as Ontario did), and the fact that the gap opens at the policy date and not before.
34.4 Placebo inference (45 min)
With one treated unit, there is no sampling distribution to lean on. The standard alternative is placebos in space: pretend each donor was treated in 2024 Q1, build its synthetic control from the remaining donors, and see how unusual Ontario's gap is. The statistic is the ratio of post-period to pre-period RMSPE, which rewards large gaps after the policy and penalizes poor fits before it.
"""Day 34.4: inference by placebos - every donor gets its own synthetic control; is Ontario's gap unusual?"""
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
from corridor.db import ROOT # noqa: E402
from corridor.quasi import load_provinces, placebo_in_space, synth # noqa: E402
w = load_provinces()
donors = [c for c in w.columns if c not in ("ON", "SK")]
ratio, p = placebo_in_space(w, "ON", "2024Q1", donors)
print("post/pre RMSPE ratio (how much worse the fit gets after 2024 Q1):")
print(" " + " ".join(f"{k} {v:.2f}" for k, v in ratio.items()))
print(f"Ontario ranks {list(ratio.index).index('ON') + 1} of {len(ratio)}: permutation p-value {p:.3f} (the smallest possible is {1 / len(ratio):.3f})")
fig, ax = plt.subplots(figsize=(8.5, 3.8))
x = range(len(w))
for u in ratio.index:
g = synth(w, u, "2024Q1", [d for d in donors if d != u])["gap"]
ax.plot(x, g, color="#4f9cf9" if u == "ON" else "#8b8d98", lw=2 if u == "ON" else 0.7, alpha=1 if u == "ON" else 0.6)
ax.axhline(0, color="black", lw=0.6)
ax.axvline(list(w.index).index("2024Q1") - 0.5, color="black", lw=0.8, ls="--")
ax.set_xticks(range(0, len(w), 8))
ax.set_xticklabels(w.index[::8])
ax.set_ylabel("actual - synthetic")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day34_placebos.png"), dpi=150)
print("wrote figures/day34_placebos.png")
post/pre RMSPE ratio (how much worse the fit gets after 2024 Q1):
ON 3.79 BC 1.79 NB 1.58 NL 1.50 NS 1.42 MB 1.26 QC 1.12 PE 0.96 AB 0.26
Ontario ranks 1 of 9: permutation p-value 0.111 (the smallest possible is 0.111)
wrote figures/day34_placebos.png

Ontario's ratio (3.8) is the largest of 9, so the permutation p-value is 1/9 = 0.11: the smallest value nine units can produce. With few comparison units, synthetic control cannot reach p < 0.05 at all. Report the rank and the figure, not just the p-value: Ontario's gap is clearly larger than every placebo's.
Why it matters at work: provincial policies are the classic synthetic control setting: one province changes coverage, pricing or a program, and the others form the donor pool. CIHI's provincial data and NPDUIS make the panels available, and CDA-AMC and provincial ministries increasingly see synthetic control analyses in evaluations.
Where you'll meet this: evaluations of provincial drug coverage changes, tobacco and alcohol policies, pharmacare pilots; the
Synth,tidysynthandaugsynthR packages
Check it in R with Synth (pre-period outcomes as predictors, as in Python):
# Day 34: the synthetic Ontario with the Synth package (outcomes in every pre-period quarter as predictors).
suppressPackageStartupMessages({ library(Synth) })
d <- read.csv("data/provincial_diabetes_quarterly.csv")
d$rate <- 1000 * d$glycemic_ed_visits / d$adults_with_diabetes
d <- subset(d, province != "SK")
d$id <- as.integer(factor(d$province))
d$time <- (as.integer(substr(d$quarter, 1, 4)) - 2016) * 4 + as.integer(substr(d$quarter, 6, 6))
on <- unique(d$id[d$province == "ON"])
pre <- 1:32
dp <- dataprep(foo = d, dependent = "rate", unit.variable = "id", time.variable = "time", unit.names.variable = "province",
treatment.identifier = on, controls.identifier = setdiff(unique(d$id), on),
time.predictors.prior = pre, time.optimize.ssr = pre, time.plot = 1:48,
special.predictors = lapply(pre, function(t) list("rate", t, "mean")))
s <- invisible(capture.output(fit <- synth(dp, method = "BFGS")))
w <- round(fit$solution.w[, 1], 3)
# label each weight by matching its donor column to the province with the same series
names(w) <- sapply(seq_len(ncol(dp$Y0plot)), function(j)
unique(d$province[d$time == 1 & abs(d$rate - dp$Y0plot[1, j]) < 1e-9]))
print(w[w > 0.001])
gap <- dp$Y1plot - dp$Y0plot %*% fit$solution.w
cat(sprintf("effect 2024-27: %+.3f per 1,000 per quarter\n", mean(gap[33:48])))
BC MB NS PE QC
0.582 0.094 0.210 0.007 0.107
effect 2024-27: -0.407 per 1,000 per quarter
Same weights, same effect. One practical warning: Synth's weight vector does not reliably carry donor names in its row names, so the check labels each weight by matching its donor series.
34.5 Truth check (30 min)
"""Day 34 truth check: the synthetic control's gap against the generator's effect of CGM coverage."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
from corridor.quasi import load_provinces, synth # noqa: E402
from corridor.truth import TRUTH # noqa: E402
w = load_provinces()
r = synth(w, "ON", "2024Q1", [c for c in w.columns if c not in ("ON", "SK")])
t = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/cgm_policy_truth.csv') WHERE province = 'ON'").df().set_index("quarter")
true = t.rate_per_1000 - t.rate_no_cgm_policy
print(f"{'period':<10}{'synthetic control':>19}{'truth':>8}")
for lab, sel in (("2024", "2024"), ("2025", "2025"), ("2026", "2026"), ("2027", "2027"), ("2024-27", "20")):
m = (w.index >= "2024Q1") & w.index.str.startswith(sel)
print(f"{lab:<10}{r['gap'][m].mean():>+19.3f}{true[m].mean():>+8.3f}")
pre = w.index < "2024Q1"
print(f"\npre-period: synthetic Ontario vs Ontario's true no-policy rate, RMSE "
f"{((r['synthetic'][pre] - t.rate_no_cgm_policy[pre]) ** 2).mean() ** 0.5:.3f}")
period synthetic control truth
2024 -0.261 -0.280
2025 -0.476 -0.440
2026 -0.450 -0.467
2027 -0.441 -0.465
2024-27 -0.407 -0.413
pre-period: synthetic Ontario vs Ontario's true no-policy rate, RMSE 0.101
The synthetic control recovers the effect year by year (−0.41 against a true −0.41 over 2024–2027). In the generator, Ontario's rates are a mix of British Columbia, Saskatchewan and Nova Scotia. With Saskatchewan excluded, the method rebuilt Ontario from other provinces whose histories carry the same pattern. That is the point: the weights need not be the "true" mix, only a mix that reproduces Ontario's untreated path.
Try it (15 min). How much does the result depend on which provinces are in the pool? Leave out each weighted donor in turn, then add Saskatchewan back.
Solution
"""Day 34 try it: how sensitive is the result to the donor pool? Leave out one donor at a time, and add Saskatchewan."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.quasi import load_provinces, synth # noqa: E402
w = load_provinces()
donors = [c for c in w.columns if c not in ("ON", "SK")]
base = synth(w, "ON", "2024Q1", donors)
post = w.index >= "2024Q1"
print(f"{'donor pool':<26}{'pre RMSPE':>10}{'effect 2024-27':>16}{'effect 2026-27':>16}")
show = lambda lab, r: print(f"{lab:<26}{r['pre_rmspe']:>10.3f}{r['gap'][post].mean():>+16.3f}" # noqa: E731
f"{r['gap'][w.index >= '2026Q1'].mean():>+16.3f}")
show("all valid donors", base)
for d in base["weights"][base["weights"] > 0.01].index:
show(f"without {d}", synth(w, "ON", "2024Q1", [x for x in donors if x != d]))
show("with SK (treated 2025 Q3)", synth(w, "ON", "2024Q1", donors + ["SK"]))
donor pool pre RMSPE effect 2024-27 effect 2026-27
all valid donors 0.112 -0.407 -0.445
without BC 0.162 -0.567 -0.724
without MB 0.115 -0.431 -0.475
without NS 0.134 -0.348 -0.367
without QC 0.116 -0.435 -0.475
with SK (treated 2025 Q3) 0.112 -0.407 -0.445
Dropping British Columbia, the largest donor, worsens the pre-period fit (0.16) and inflates the effect (−0.57). Every other omission keeps the effect between −0.35 and −0.44. Adding Saskatchewan changes nothing here, because it receives no weight; with a different history it could pull the post-period estimate towards zero. A leave-one-out table belongs in every synthetic control report.
34.6 Fitting on everything (20 min)
Bug of the day. "Why throw away 2024–2027? Fit the weights on all quarters."
"""Day 34 bug of the day: fit the donor weights on all quarters, 'to use all the information'."""
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.quasi import load_provinces, synth_weights # noqa: E402
w = load_provinces()
donors = [c for c in w.columns if c not in ("ON", "SK")]
post = w.index >= "2024Q1"
for label, rows in (("fitted on 2016-2023 only", ~post), ("fitted on 2016-2027 (all quarters)", np.ones(len(w), bool))):
wt = synth_weights(w.ON[rows].to_numpy(), w.loc[rows, donors].to_numpy())
gap = w.ON[post] - w.loc[post, donors].to_numpy() @ wt
print(f"{label:<36} effect 2024-27: {gap.mean():+.3f} weights: " +
", ".join(f"{d} {v:.2f}" for d, v in zip(donors, wt) if v > 0.01))
fitted on 2016-2023 only effect 2024-27: -0.407 weights: BC 0.58, MB 0.09, NS 0.21, QC 0.11
fitted on 2016-2027 (all quarters) effect 2024-27: -0.227 weights: BC 0.66, MB 0.24, QC 0.09
Fitting on the post-period asks the weights to make the gap small after the policy too, and they oblige: the estimated effect shrinks by 45%, to −0.23. The weights must be chosen using only data the policy could not have affected. The same rule applies to predictors: no covariate measured after the policy.
34.7 Mini-project: the evaluation summary (55 min)
Turn the gap into numbers a ministry reads: effect per year, and ED visits avoided (gap × Ontario's adults with diabetes), saved to docs/cgm_synthetic_control.csv.
"""Day 34 mini-project: the numbers for the evaluation summary - effect per year, visits avoided, placebo p."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
import pandas as pd # noqa: E402
from corridor.db import DATA, ROOT # noqa: E402
from corridor.quasi import load_provinces, placebo_in_space, synth # noqa: E402
w = load_provinces()
donors = [c for c in w.columns if c not in ("ON", "SK")]
r = synth(w, "ON", "2024Q1", donors)
_, p = placebo_in_space(w, "ON", "2024Q1", donors)
n = duckdb.sql(f"SELECT quarter, adults_with_diabetes FROM read_csv('{DATA}/provincial_diabetes_quarterly.csv') "
"WHERE province = 'ON'").df().set_index("quarter").adults_with_diabetes
rows = []
for y in ("2024", "2025", "2026", "2027"):
m = w.index.str.startswith(y)
gap = r["gap"][m]
rows.append({"year": y, "rate_ontario": round(w.ON[m].mean(), 3), "rate_synthetic": round(r["synthetic"][m].mean(), 3),
"difference_per_1000_per_quarter": round(gap.mean(), 3),
"visits_avoided": round(float(-(gap * n[m] / 1000).sum()))})
t = pd.DataFrame(rows)
t.to_csv(os.path.join(ROOT, "docs", "cgm_synthetic_control.csv"), index=False)
print(t.to_string(index=False))
print(f"\ntotal visits avoided 2024-2027: about {t.visits_avoided.sum():,.0f}; placebo p-value {p:.2f} "
f"({len(donors) + 1} units)")
year rate_ontario rate_synthetic difference_per_1000_per_quarter visits_avoided
2024 4.061 4.322 -0.261 1459
2025 3.804 4.280 -0.476 2666
2026 3.536 3.986 -0.450 2519
2027 3.425 3.865 -0.441 2468
total visits avoided 2024-2027: about 9,112; placebo p-value 0.11 (9 units)
About 9,100 ED visits for glycemic emergencies avoided in four years. Multiplied by a cost per visit (Module 5), that becomes the offset in a CGM budget impact analysis. Write the summary with the placebo rank and the leave-one-out range, not the p-value alone.
34.8 Save your work
python -m pytest -q
git add .
git commit -m "Day 34: synthetic control for Ontario's CGM coverage"
Day 34 checklist
- I build a synthetic control with non-negative weights summing to 1, fitted on pre-policy data only
- I check the pre-period fit before reading the post-period gap
- I exclude donors exposed to the same or a similar policy
- I use placebos in space and report the rank, knowing the smallest p-value possible
- I report leave-one-out donor sensitivity
Bloc français (30 min)
Thème : la méthode du contrôle synthétique.
Quand une seule province adopte une politique, on construit un Ontario synthétique à partir des autres provinces. Les poids sont choisis pour reproduire l'évolution de l'Ontario avant la politique. Après 2024, l'écart entre l'Ontario et son jumeau synthétique mesure l'effet de la couverture des glucomètres en continu. Les tests placebo indiquent si cet écart est inhabituel.
| Français | English |
|---|---|
| le contrôle synthétique | the synthetic control |
| le bassin de donneurs | the donor pool |
| la pondération | the weighting |
| l'ajustement avant l'intervention | the pre-intervention fit |
| l'écart | the gap |
| le test placebo dans l'espace | the in-space placebo test |
| le rang | the rank |
| le glucomètre en continu | the continuous glucose monitor |
| l'urgence glycémique | the glycemic emergency |
| les visites à l'urgence évitées | emergency visits avoided |
| la robustesse | robustness |
| l'interpolation | interpolation |
Exercices
- Translate: "Saskatchewan cannot be a donor because it adopted the same policy."
- Translate: « Les poids ne doivent utiliser que les données antérieures à la politique. »
- In three French sentences, explain why the placebo p-value cannot fall below 0.11 here.
Réponses
- La Saskatchewan ne peut pas être une donneuse, car elle a adopté la même politique.
- "The weights must use only data from before the policy."
- Example: Il y a neuf unités : l'Ontario et huit provinces donneuses. La valeur p est le rang de l'Ontario divisé par neuf. Même au premier rang, elle ne peut pas être inférieure à 1/9, soit 0,11.