Synthetic control estimates the effect of something that happened to one unit (a region, a store, a market) by building a counterfactual out of the units it didn't happen to. You find non-negative weights that sum to 1 so that a weighted average of the untouched "donor" units matches the treated unit before the launch, then see how far the treated unit departs from that average afterward. The gap is the effect estimate. The code below uses scipy.optimize.minimize and needs no extra packages.
Quick Example
This simulates weekly sales for one treated region and 24 donor regions over 48 weeks. The treated region gets a launch in week 37 that adds 6 to its sales index. The code finds the donor weights using only the 36 pre-launch weeks.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import minimize
# ---- Simulated panel: 1 treated region + 24 donor regions, 48 weeks ----
rng = np.random.default_rng(66)
n_donors, T, T0 = 24, 48, 36 # first 36 weeks are pre-launch
TRUE_EFFECT = 6.0
t = np.arange(T)
factors = np.column_stack([
0.15 * t + 3 * np.sin(2 * np.pi * t / 26), # trend + seasonality
np.cumsum(rng.normal(0, 0.8, T)), # random-walk shock
])
loadings = rng.normal(1, 0.5, size=(n_donors, 2))
level = rng.normal(100, 12, n_donors)
donors = level[:, None] + loadings @ factors.T + rng.normal(0, 0.8, (n_donors, T))
# the treated region behaves like a mix of a few donors
true_w = np.zeros(n_donors)
true_w[[2, 7, 13, 19]] = [0.4, 0.3, 0.2, 0.1]
treated = true_w @ donors + rng.normal(0, 0.8, T)
treated[T0:] += TRUE_EFFECT
weeks = np.arange(1, T + 1)
cols = [f"region_{i:02d}" for i in range(n_donors)]
panel = pd.DataFrame(donors.T, columns=cols, index=weeks)
panel["treated"] = treated
panel.index.name = "week"
launch_week = T0 + 1 # first treated week
# ---- Fit synthetic control weights ----
def fit_weights(y_pre, X_pre):
"""Non-negative weights summing to 1 that best match y_pre."""
k = X_pre.shape[1]
res = minimize(lambda w: np.sum((y_pre - X_pre @ w) ** 2),
np.full(k, 1 / k), method="SLSQP",
bounds=[(0, 1)] * k,
constraints={"type": "eq", "fun": lambda w: w.sum() - 1})
return res.x
pre = panel.index < launch_week
X = panel[cols].to_numpy()
y = panel["treated"].to_numpy()
w = fit_weights(y[pre], X[pre])
synthetic = X @ w
gap = y - synthetic
print("pre-launch RMSPE:", round(np.sqrt(np.mean(gap[pre] ** 2)), 2))
print("average post-launch gap:", round(gap[~pre].mean(), 2), "(true effect 6.0)")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8.5, 6.4), sharex=True,
gridspec_kw={"height_ratios": [2.2, 1]})
ax1.plot(weeks, y, color="#be123c", lw=2.2, label="Treated region")
ax1.plot(weeks, synthetic, color="#1d4ed8", lw=2.2, ls="--", label="Synthetic control")
ax1.axvline(launch_week - 0.5, color="#64748b", ls=":")
ax1.set(ylabel="Weekly sales index", title="Treated region vs its synthetic control")
ax1.legend(loc="upper left")
ax2.bar(weeks, gap, color=np.where(weeks >= launch_week, "#be123c", "#94a3b8"))
ax2.axhline(0, color="black", lw=0.8)
ax2.axvline(launch_week - 0.5, color="#64748b", ls=":")
ax2.set(xlabel="Week", ylabel="Gap (treated minus synthetic)")
fig.tight_layout()

Before the launch the synthetic line tracks the treated one closely: the pre-launch RMSPE (root mean squared prediction error) is 0.70, and no weekly gap is larger than 1.63. After the launch the treated region goes above its synthetic twin and stays there. The gap ranges from 5.0 to 7.6 over the 12 post-launch weeks and averages 6.21, against the true effect of 6.0 built into the simulation. Summed over the 12 weeks, the launch added about 74.5 index points of sales.
How Synthetic Control Works
A single treated unit has no obvious control group, and any one other region differs from it. Synthetic control sidesteps that by combining many:
- Choose a donor pool of units that didn't get the treatment and shouldn't have been affected by it.
- Find weights
w ≥ 0withsum(w) = 1such thatdonors @ wmatches the treated unit's pre-launch values as closely as possible. - Apply those weights to the donors' post-launch values. That blend is what the treated unit would have done without the launch, under the model's assumptions.
- The effect at each week is
treated - synthetic.
The "non-negative and sums to 1" constraints keep the synthetic unit inside the range of the donors, so it interpolates and never extrapolates. That is the main difference from a plain regression of the treated series on the donors, which can give negative weights and extreme values.
Which Donors Got the Weight?
order = np.argsort(w)[::-1][: (w > 0.01).sum()]
fig, ax = plt.subplots(figsize=(6.5, 3.8))
ax.barh([cols[i] for i in order][::-1], w[order][::-1], color="#0f766e")
ax.set(xlabel="Weight", title="Donor weights in the synthetic control")

Six of the 24 donors get a weight above 0.01, and four carry almost all of it (region_02 at 0.42, region_13 at 0.20, region_07 at 0.17, region_20 at 0.15). The sparsity is typical, since the constraints push weights to a few donors. This is also the main transparency benefit: you can say exactly which regions the comparison is made of, and check that they make sense for the business.
How Do You Know the Gap Isn't Just Noise? Placebo Tests
With one treated unit there is no standard error, so the usual inference is a placebo test in space. Pretend each donor was the treated unit, build a synthetic control for it from the remaining 23 donors, and compute its gap. If the real treated unit's gap is much larger than the placebo gaps, it is unlikely to be chance.
Compare units by the ratio of post-launch to pre-launch RMSPE, which also controls for how well each unit could be fit:
gaps = {"treated": gap}
for j, name in enumerate(cols):
others = [k for k in range(n_donors) if k != j]
wj = fit_weights(X[pre][:, j], X[pre][:, others])
gaps[name] = X[:, j] - X[:, others] @ wj
ratios = {k: np.sqrt(np.mean(g[~pre] ** 2)) / np.sqrt(np.mean(g[pre] ** 2))
for k, g in gaps.items()}
rank = sorted(ratios.values(), reverse=True).index(ratios["treated"]) + 1
print("treated ratio:", round(ratios["treated"], 2),
"| rank", rank, "of", len(ratios), "| p =", round(rank / len(ratios), 3))

The treated region's post/pre RMSPE ratio is 8.97. The highest ratio among the 24 donors is 1.52. The treated unit ranks first of 25, which gives a permutation p-value of 1/25 = 0.04, the smallest value 25 units can give. With few donors that is the resolution limit, so more donors let you test at a stricter level. The left plot leaves out three donors whose pre-launch fit was more than five times worse than the treated unit's. A bad pre-fit makes a placebo gap meaningless, and dropping them is standard practice. The ranking uses all 25 either way.
When Synthetic Control Works, and When It Doesn't
| Check | Why it matters |
|---|---|
| Pre-launch fit is tight | If the synthetic line can't track the treated unit before launch, the post gap tells you nothing. |
| Treated unit sits inside the donors' range | The weights can only interpolate. A unit with a level above every donor can't be matched. |
| No donor was affected by the launch | Spillovers (a campaign in one region lifting its neighbors) bias the counterfactual. |
| Enough pre-launch periods | With 24 donors and 36 weeks the fit is meaningful. With 24 donors and 6 weeks you can match anything by chance. |
| Nothing else changed at the launch | Like any before/after design, a simultaneous shock is indistinguishable from the effect. |
The pre-launch fit is measured on the same weeks the weights were fitted on, so it flatters the method. If the pre-period is short, hold out the last few pre-launch weeks, fit on the earlier ones, and check the fit on the held-out weeks.
Synthetic Control vs Difference-in-Differences
| Synthetic control | Difference-in-differences | |
|---|---|---|
| Treated units | One (or a few) | Many |
| Control group | A weighted blend, chosen to match | All untreated units, equal weight |
| Key assumption | The blend reproduces the treated unit's no-launch path | Parallel trends |
| Inference | Placebo tests | Standard errors |
| Typical use | A launch in one region, a policy in one state | A rollout across many stores or users |
If you have many treated units and a plausible parallel-trends story, difference-in-differences is simpler. If you have one treated unit and no single good control, use synthetic control. When there is no donor pool at all, a before/after comparison with an interrupted time series is the weaker fallback.
Practical Tips
- Match on more than the outcome. Real applications often include predictors such as population or past marketing spend in the weight fit. This post matches on the outcome series only, which is the simplest version.
- Don't tune until the result looks good. Choose the donor pool and pre-period before looking at the post-launch gap.
- Packages exist for the fuller method.
pysynconand CausalPy implement synthetic control with predictor matching and other estimators. I didn't use them for this post, and the SciPy version above is enough to see how the weights work. - Report the pre-fit. Show the pre-launch RMSPE or gap alongside the effect, so readers can judge how much to trust it.