Module contents
Lesson 22 of 28Core 105 min

Synthetic control and synthetic difference-in-differences

Synthetic control builds a convex combination of untreated donors to approximate one treated unit’s counterfactual. Study simplex optimization, factor-model justification, placebo inference, augmented control, and synthetic DiD.

After this lesson you can

  • Formulate and solve synthetic control as simplex optimization.
  • Justify the method under a latent factor model and explain prior fit.
  • Use spatial and time placebos and interpret prediction-error ratios.
  • Implement augmented synthetic control and synthetic difference-in-differences.
  • Study California’s Proposition 99 cigarette-sales example.

Before you start

What would have happened without the law?

A country passes a cybersecurity law and no other changes exactly the same rule on the same date. A before–after comparison would attribute any worldwide trend to the law; choosing a single neighbor could introduce persistent differences. Synthetic control seeks a combination of untreated countries whose prior trajectory resembles that of the treated country.

The question remains causal: the constructed trajectory estimates the outcome the treated country would have had without the law. Prior fit makes that counterfactual more plausible under an appropriate model, but does not ensure a later exclusive shock or donor spillover disappears.

InteractiveConstructing California

California passed Proposition 99 in 1988; the post period starts in 1989. Fit only earlier data and observe what happens afterward.

0701401970198019892000Packs per person per yearYear
  • California
  • Ten weighted donors

Whenever you change a weight, the others are redistributed proportionally and still sum to one. Moving a weight down from 100% divides the rest equally.

The button loads the optimum of the quadratic problem for these ten states, computed with SLSQP on 19 annual sales observations from 1970 to 1988. The minimum was checked using optimality conditions. Only prior outcomes are used, so this fit does not reproduce Abadie, Diamond and Hainmueller’s specification with seven predictors and 38 donors.

Public data from synthdid. The post-treatment gap is California minus its combination; causal interpretation requires, among other assumptions, no anticipation and no policy effects on donors.

10.0 %
10.0 %
10.0 %
10.0 %
10.0 %
10.0 %
10.0 %
10.0 %
10.0 %
10.0 %
Pre-treatment RMSE7.12
Pre-treatment minimum for these ten1.70
Average post-treatment gap−29.70
Sum of weights1.000
Adjust weights of ten real donors and compare them with the optimum for that subsample.

A combination inside the simplex

Let i=1i=1 be the treated unit, i=2,…,J+1i=2,\ldots,J+1 donor units, and T0T_0 the last pre-intervention period. The prediction is Y^1t(0)=∑j=2J+1wjYjt\widehat Y_{1t}(0)=\sum_{j=2}^{J+1}w_jY_{jt} and observed post-period gap is Y1t−Y^1t(0)Y_{1t}-\widehat Y_{1t}(0). Weights satisfy wj≥0w_j\ge0 and ∑jwj=1\sum_jw_j=1: classical synthetic control interpolates among donors rather than extrapolating through arbitrary weights.

With prior predictor vector X1X_1, donor predictor matrix X0X_0, and positive-semidefinite diagonal matrix VV, simplex optimization solves

w^(V)∈arg⁡min⁡w≥0, 1⊤w=1(X1−X0w)⊤V(X1−X0w).\widehat w(V)\in\arg\min_{w\ge0,\ \mathbf 1^\top w=1} (X_1-X_0w)^\top V(X_1-X_0w).

Scale variables before comparing their importance. VV can be chosen by an outer optimization measuring prediction error on prior periods held out for validation. The nested choice must use pretreatment information; searching VV after observing the later effect favors selected results. The outer surface can have local minima and inner weights need not be unique. Whether a solution is sparse depends on data and geometry; it is not guaranteed for every panel.

The lab also implements projected descent. To project a vector onto the simplex, sort components, calculate the threshold making positive parts sum to one, and truncate negatives. Projection ensures constraints; here 16,000 iterations use a step based on matrix norm, and the objective is then checked against a quadratic optimizer. That validates this instance, not the fixed budget for every problem.

Why pre-periods matter

A factor model for untreated outcome is

Yit(0)=δt+θt⊤Zi+λt⊤μi+εit,Y_{it}(0)=\delta_t+\theta_t^\top Z_i+\lambda_t^\top\mu_i+\varepsilon_{it},

where ZiZ_i are observed characteristics and μi\mu_i latent loadings. Weights sum to one, so the treated–synthetic difference cancels common component δt\delta_t. If they also balance ZZ and loadings μ\mu, they cancel the systematic factor component in every period.

Without disturbances and with ZZ balanced, exact equality of prior outcomes implies Λpre(μ1−∑jwjμj)=0\Lambda_{\rm pre}(\mu_1-\sum_jw_j\mu_j)=0. If the prior factor matrix has full column rank, loadings are balanced too. With noise, rank alone is insufficient: normalized eigenvalue, factor, and disturbance conditions are needed to control error as pre-period length grows. Even that does not imply a later shock in one realization disappears. The formal argument and conditions are in Abadie, Diamond and Hainmueller (2010).

Good prior fit is relevant empirical evidence, not proof of no bias. Also examine anticipation, composition changes, and donor exposure to intervention. If no convincing combination exists, report that limitation rather than interpreting a poorly fitted curve as a reliable counterfactual.

Placebos and gap rank

Placebo inference reruns the procedure pretending each donor was treated. Compare the actual treated gap with placebo gaps, or use the ratio of post- to pre-period mean squared prediction error, MSPE. Placebos with poor prior fit may produce large gaps without informative comparison; if filtering by that fit, set the rule before inspecting post-period outcomes and report how many remain.

For a statistic where larger values are more extreme, an inclusive rank counts the treated unit and ties:

p^rango=#{i:Si≥Stratado}nuˊmero de unidades comparadas.\widehat p_{\rm rango}= \frac{\#\{i:S_i\ge S_{\rm tratado}\}}{\text{número de unidades comparadas}}.

A reassignment rank has an exact-test interpretation only under an assignment mechanism and selection rule making label exchange justifiable. In an observational study it can be a descriptive comparison without automatically becoming a sampling probability. If prior error is zero, the ratio requires an explicit convention; do not divide without reporting it. RMSPE and MSPE ratios order units identically, but their numeric thresholds differ by a square. A time placebo moves the pretend date earlier and must avoid contaminating its evaluation with the real intervention.

InteractivePlacebo gaps and prior fit

The orange line is the treated unit’s gap; gray lines are placebo reassignments whose pre-treatment RMSPE does not exceed k times that of the treated unit. Each comparison refits weights using its own donors.

2.30−2.30369121517Period
  • Treated
  • Retained placebos
  • After intervention

Simulated model: 11 units, 12 pre and 6 post periods; latent factors, common trend and noise, with seed 2722. Only unit 0 receives an effect of −2 after the cutoff. These are not California data.

Each unit is compared with the convex combination of the other ten minimizing pre-treatment squared error. The ratio divides post-treatment RMSPE by pre-treatment RMSPE; rank counts the treated and retained ratios at least as large, including ties. 1 placebo exceeding the chosen fit threshold are excluded.

The filtered rank is descriptive: changing the filter changes its denominator and does not guarantee an exact test. Without filtering, interpretation as a p-value requires assignment compatible with the null and permutation; unit 0 was fixed by design here. The actually treated unit serves as a donor for other placebos and can contaminate them if an effect exists. See Abadie (2021).

5.0
Retained placebos9 / 10
Treated post/pre ratio14.85
Descriptive rank1 / 10 = 0.100
Change the fit filter and observe which comparisons remain.

Augment and connect to DiD

Augmented synthetic control adds a modeled correction to weighted control:

Y^1taug(0)=∑jwjYjt+m^t(X1)−∑jwjm^t(Xj).\widehat Y_{1t}^{\rm aug}(0) =\sum_jw_jY_{jt} +\widehat m_t(X_1)-\sum_jw_j\widehat m_t(X_j).

For example, ridge can predict outcomes using prior history. The correction attempts to compensate imbalance remaining in XX according to that model. Effective weights can be negative and permit extrapolation; usefulness depends on model fit and assumptions. This is not automatic double robustness against every incorrect model. See Ben-Michael, Feller and Rothstein.

Synthetic difference-in-differences combines donor and prior-period weights. For common adoption, unit weights fit the treated trajectory before treatment allowing an intercept; time weights approximate the control post-period average as a combination of their prior periods, also with an intercept. They are regularized and normalized on their respective simplexes. With ωj\omega_j for controls, λt\lambda_t for prior periods, and uniform post weights, the single-treated-unit estimator is

τ^SDID=(Y‾1,post−∑t≤T0λtY1t)−∑jωj(Y‾j,post−∑t≤T0λtYjt).\widehat\tau_{\rm SDID}= \left(\overline Y_{1,\rm post}-\sum_{t\le T_0}\lambda_tY_{1t}\right) -\sum_j\omega_j\left(\overline Y_{j,\rm post} -\sum_{t\le T_0}\lambda_tY_{jt}\right).

Uniform control and prior-time weights recover DiD. The intercept permits prior series to be parallel with a level difference without requiring exact equality. Regularization and weight choice affect the result; the teaching example declares its parameters rather than presenting them as uniquely possible. See Arkhangelsky and colleagues.

InteractiveUnit and period weights

Above, compare the treated unit with its control; in DiD and SDID the control is shifted by the weighted pre-treatment gap. Below, color shows each observation’s signed coefficient in the final contrast, holding weights fixed.

12.39.2Contrast coefficients by cell015100369121517Period
  • Treated unit
  • Displayed control
  • Positive coefficient
  • Negative coefficient

Unit 0 is treated; 1 to 10 are controls. Intervention starts at t=12. The selected cell coefficient is multiplied by its outcome in the contrast; summing the 198 contributions reproduces the estimate. Unit weight is 1 for treated and ωᵢ for each control; time weight is λₜ before and 1/6 afterward.

DiD uses uniform weights. Synthetic control obtains ω to fit the pre period and averages post-treatment gaps; its direct pre coefficients are zero with weights fixed, although those data were used to learn ω. SDID estimates ω using treated pre outcomes and λ to approximate the controls’ post average. Both fits allow an intercept and penalize the sum of squared weights by 0.05.

Signed contrast coefficients are not the nonnegative weights in SDID regression. Since ω and λ are estimated from the panel, the cell formula describes the contrast with those weights fixed. The panel is simulated, with true effect −2, factors and noise; pre-fit alone does not guarantee a valid counterfactual. See Arkhangelsky y colaboradores.

Estimator
1
0
Estimated effect−1.921
Cell coefficient0.0204
Unit weight0.119
Time weight0.172
Compare contrasts and trajectories of DiD, synthetic control, and SDID.

California and Proposition 99

California approved Proposition 99 in 1988; example data consider treatment from 1989. Abadie, Diamond and Hainmueller study cigarette sales in packs per capita, not smoking prevalence. Their specification also uses economic and demographic predictors as well as prior outcomes. Table 2 publishes rounded weights for Colorado, Connecticut, Montana, Nevada, and Utah of 0.164, 0.069, 0.199, 0.234, and 0.334 respectively.

The lab downloads trajectories and a predictor matrix from SDID authors’ sources. Comparing a trajectory-only estimate with the original paper requires noting that difference; applying published rounded weights checks a curve but does not itself reproduce the original optimization. Sensitivity to donor sample and predictors matters as much as the figure’s appearance.

Lab: build and compare

First build the reproducible panel and compare a simplex optimizer with a custom implementation. Then explore placebos, an augmented correction, and SDID. Values come from the cells and each simulation’s assumptions are stated alongside the code.

Download the public matrix of predictors and outcomes. Published rounded weights check a trajectory; they are not a new optimization.

[ ]cell 01 dataBrowser
import io
import numpy as np
from pyodide.http import pyfetch

# Matriz de los autores de synthdid: 7 predictores y ventas de 1970 a 2000.
url = ('https://raw.githubusercontent.com/synth-inference/synthdid/master/'
       'experiments/california_smoking/data/raw/california_prop99.txt')
response = await pyfetch(url)
if not response.ok:
    raise RuntimeError(f'Descarga fallida: HTTP {response.status}')
matrix = np.loadtxt(io.StringIO(await response.string()))
states = ['Alabama','Arkansas','Colorado','Connecticut','Delaware','Georgia','Idaho',
          'Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Minnesota',
          'Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Mexico',
          'North Carolina','North Dakota','Ohio','Oklahoma','Pennsylvania','Rhode Island',
          'South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia',
          'West Virginia','Wisconsin','Wyoming','California']
assert matrix.shape == (39, 39) and len(states) == 39
assert np.array_equal(matrix[0], [*range(1, 3), *range(4, 40), 3])
X = matrix[1:8]            # siete predictores por estado
Y = matrix[8:]             # años en filas, estados en columnas
years = np.arange(1970, 2001)
before = years <= 1988
assert np.array_equal(Y[years == 1988].reshape(-1), X[4])
assert np.array_equal(Y[years == 1980].reshape(-1), X[5])
assert np.array_equal(Y[years == 1975].reshape(-1), X[6])
print('Años', years[0], years[-1], '| estados', len(states), '| previos', before.sum())
print('California 1975, 1980, 1988 y 2000:',
      np.round(Y[np.isin(years, [1975, 1980, 1988, 2000]), -1], 3))

Implement projection and solve the same problem using SLSQP and projected descent. Comparison values come from this calculation.

[ ]cell 02 simplexBrowser
from scipy.optimize import minimize

def simplex_projection(z):
    """Proyección euclídea, con ceros y suma exactamente uno salvo redondeo."""
    z = np.asarray(z, dtype=float)
    descending = np.sort(z)[::-1]
    offsets = np.cumsum(descending) - 1
    eligible = descending - offsets / np.arange(1, len(z) + 1) > 0
    rho = np.flatnonzero(eligible)[-1]
    return np.maximum(z - offsets[rho] / (rho + 1), 0)

def scm_slsqp(A, b, w0=None):
    """Minimiza ||Aw-b||² sobre el símplex de los donantes."""
    A, b = np.asarray(A, float), np.asarray(b, float)
    n = A.shape[1]
    if w0 is None:
        w0 = np.full(n, 1 / n)
    def objective(w):
        e = A @ w - b
        return float(e @ e)
    def gradient(w):
        return 2 * A.T @ (A @ w - b)
    result = minimize(objective, w0, jac=gradient, method='SLSQP',
                      bounds=[(0, 1)] * n,
                      constraints={'type': 'eq', 'fun': lambda w: w.sum() - 1,
                                   'jac': lambda w: np.ones(n)},
                      options={'ftol': 1e-10, 'maxiter': 1000})
    if not result.success:
        raise RuntimeError(result.message)
    return result.x

def scm_projected(A, b, iterations=16000):
    """Gradiente proyectado acelerado con paso basado en ||A||₂."""
    n = A.shape[1]
    L = 2 * np.linalg.norm(A, 2)**2
    if not np.isfinite(L) or L <= 0:
        raise ValueError('La matriz debe tener variación')
    w = np.full(n, 1 / n)
    momentum = w.copy()
    t = 1.
    for _ in range(iterations):
        new_w = simplex_projection(momentum - (2 / L) * (A.T @ (A @ momentum - b)))
        new_t = (1 + np.sqrt(1 + 4 * t * t)) / 2
        momentum = new_w + ((t - 1) / new_t) * (new_w - w)
        w, t = new_w, new_t
    return w

# La diagonal V inicial da igual peso a cada predictor estandarizado.
scale = X.std(axis=1, ddof=1)
if np.any(scale <= 0):
    raise ValueError('No se puede estandarizar un predictor constante')
Z = X / scale[:, None]
v_equal = np.full(7, 1 / 7)
A = np.sqrt(v_equal)[:, None] * Z[:, :-1]
b = np.sqrt(v_equal) * Z[:, -1]
w_solver = scm_slsqp(A, b)
w_gradient = scm_projected(A, b)
loss_solver = float(np.linalg.norm(A @ w_solver - b)**2)
loss_gradient = float(np.linalg.norm(A @ w_gradient - b)**2)
print('SLSQP: suma, mínimo, objetivo:', w_solver.sum(), w_solver.min(), loss_solver)
print('Proyectado: suma, mínimo, objetivo:', w_gradient.sum(), w_gradient.min(), loss_gradient)
print('Diferencia entre objetivos:', abs(loss_solver - loss_gradient))
assert abs(w_solver.sum() - 1) < 1e-8 and w_solver.min() >= -1e-8
assert abs(w_gradient.sum() - 1) < 1e-8 and w_gradient.min() >= -1e-12
assert abs(loss_solver - loss_gradient) < 1e-5
print('Los pesos pueden no ser únicos; comparamos objetivos y restricciones.')

Select V among eight explicit candidates by error in the prior period. The fit reuses years also present in predictors: this is not independent temporal validation. This restricted search does not claim a continuous optimum or exact reproduction of the paper’s V.

[ ]cell 03 validationBrowser
# Selección anidada acotada: se comparan ocho diagonales prefijadas V.
# Esto NO es la optimización continua completa de V del trabajo original.
candidates = [np.full(7, 1 / 7)]
for j in range(7):
    v = np.full(7, 0.05)
    v[j] = 0.70
    candidates.append(v)
assert all(np.isclose(v.sum(), 1) for v in candidates)

best = None
for index, v in enumerate(candidates):
    weighted_A = np.sqrt(v)[:, None] * Z[:, :-1]
    weighted_b = np.sqrt(v) * Z[:, -1]
    w = scm_slsqp(weighted_A, weighted_b)
    mse = float(np.mean((Y[before, -1] - Y[before, :-1] @ w)**2))
    if best is None or mse < best['mse']:
        best = {'index': index, 'v': v, 'weights': w, 'mse': mse}

w_nested = best['weights']
gap_nested = Y[:, -1] - Y[:, :-1] @ w_nested
print('Diagonal elegida entre ocho candidatas:', best['index'])
print('V elegida:', np.round(best['v'], 3))
print('RMSE previo:', np.sqrt(best['mse']))
print('Pesos > 0,001:', [(states[i], round(float(w), 4)) for i, w in enumerate(w_nested) if w > 0.001])
print('Brecha en 2000:', gap_nested[-1], '| media 1989-2000:', gap_nested[~before].mean())
print('Ajuste propio: ocho V candidatas, no reproducción exacta de la búsqueda continua del paper.')

Now optimize V continuously in a reduced example: predictors are from 1972, 1975, and 1978; 1980–1988 is the selection window. The outer solution is local and that window is not an independent final evaluation.

[ ]Continuous nested optimizationBrowser
# Ejemplo reducido de V continua: tres donantes, tres resultados de 1972,
# 1975 y 1978 como predictores; elegimos V en 1980-1988, antes del tratamiento.
# Ese periodo selecciona V: no es una evaluación final independiente.
chosen = ['Colorado', 'Nevada', 'Utah']
idx = np.array([states.index(name) for name in chosen])
train_years = [1972, 1975, 1978]
train = Y[np.isin(years, train_years)]
train_scale = train[:, np.r_[idx, 38]].std(axis=1, ddof=1)
if np.any(train_scale <= 0):
    raise ValueError('Predictores constantes')
train_z = train / train_scale[:, None]
val = (years >= 1980) & (years <= 1988)
val_y = Y[val, -1]
val_A = Y[val][:, idx]

def loss_for_v(v):
    A = np.sqrt(v)[:, None] * train_z[:, idx]
    b = np.sqrt(v) * train_z[:, -1]
    w = scm_slsqp(A, b)
    return float(np.mean(((val_A @ w - val_y) / 100)**2))

v0 = np.full(3, 1 / 3)
loss0 = loss_for_v(v0)
outer = minimize(loss_for_v, v0, method='SLSQP', bounds=[(0.02, 0.96)] * 3,
                 constraints={'type': 'eq', 'fun': lambda v: v.sum() - 1},
                 options={'ftol': 1e-8, 'maxiter': 40})
if not outer.success:
    raise RuntimeError('La búsqueda exterior no convergió: ' + outer.message)
assert outer.fun <= loss0 + 1e-7
v_local = outer.x
w_local = scm_slsqp(np.sqrt(v_local)[:, None] * train_z[:, idx],
                    np.sqrt(v_local) * train_z[:, -1])
print('V continua local:', np.round(v_local, 6), '| suma:', v_local.sum())
print('RMSE de selección con V uniforme y optimizada:',
      100 * np.sqrt(loss0), 100 * np.sqrt(outer.fun))
print('Donantes activos:', [(chosen[j], round(float(w), 5)) for j, w in enumerate(w_local) if w > 0.001])
print('Selección temporal pretratamiento, sin prueba final independiente; solución local.')

For the following placebos fit prior trajectories. California is not a donor for placebo units, unlike one possible choice in the paper. If pre-MSPE is zero and post-MSPE positive, the ratio is infinite; if both are zero, it is undefined and excluded from rank and denominator. If the treated ratio is undefined, no rank is computed.

[ ]cell 04 placebosBrowser
# Placebos SCM en trayectorias pretratamiento; usa solo donantes no tratados
# en la posintervención, por lo que se excluye California de los placebos.
# La unidad real usa 38 donantes; cada placebo usa los otros 37.
def fit_trajectory(target, donors):
    # El escalado común no cambia el minimizador y mejora el acondicionamiento.
    A = Y[before][:, donors] / 100
    b = Y[before, target] / 100
    w = scm_slsqp(A, b)
    return Y[:, target] - Y[:, donors] @ w

def ratio_mspe(gap):
    pre = float(np.mean(gap[before]**2))
    post = float(np.mean(gap[~before]**2))
    if pre == 0:
        return np.nan if post == 0 else np.inf
    return post / pre

# Un cociente 0/0 es indefinido; con error posterior positivo es infinito.
gap_zero = np.zeros(len(years))
gap_post = gap_zero.copy()
gap_post[~before] = 1
assert np.isnan(ratio_mspe(gap_zero))
assert np.isposinf(ratio_mspe(gap_post))

gap_ca = fit_trajectory(38, np.arange(38))
ratios = [ratio_mspe(gap_ca)]
print('California: RMSE previo', np.sqrt(np.mean(gap_ca[before]**2)),
      '| cociente MSPE posterior/previo', ratios[0])
print('California: brecha 2000', gap_ca[-1], '| media posperiodo', gap_ca[~before].mean())

Calculate the first batch of placebos.

[ ]cell 05 placebos 0 9Browser
for target in range(0, 10):
    donors = np.array([j for j in range(38) if j != target])
    ratios.append(ratio_mspe(fit_trajectory(target, donors)))
print('Placebos completados:', len(ratios) - 1)

Calculate the second batch.

[ ]cell 06 placebos 10 19Browser
for target in range(10, 20):
    donors = np.array([j for j in range(38) if j != target])
    ratios.append(ratio_mspe(fit_trajectory(target, donors)))
print('Placebos completados:', len(ratios) - 1)

Calculate the third batch.

[ ]cell 07 placebos 20 29Browser
for target in range(20, 30):
    donors = np.array([j for j in range(38) if j != target])
    ratios.append(ratio_mspe(fit_trajectory(target, donors)))
print('Placebos completados:', len(ratios) - 1)

Finish placebos and calculate the inclusive rank. Its inferential interpretation depends on design, and specification differs from the original.

[ ]cell 08 placebos 30 37Browser
for target in range(30, 38):
    donors = np.array([j for j in range(38) if j != target])
    ratios.append(ratio_mspe(fit_trajectory(target, donors)))
ratios = np.asarray(ratios)
assert len(ratios) == 39
valid = ~np.isnan(ratios)
if not valid[0]:
    raise ValueError('El cociente de la unidad tratada es indefinido: no hay rango')
rank = int(np.count_nonzero(ratios[valid] >= ratios[0]))
print('Placebos completados:', len(ratios) - 1)
print('Cocientes indefinidos excluidos:', int((~valid).sum()))
print('Rango inclusivo:', rank, 'de', int(valid.sum()), '| proporción', rank / valid.sum())
print('Es una referencia descriptiva; una prueba exacta requiere justificar reasignación y nula apropiadas.')
print('No coincide necesariamente con ADH: usamos trayectoria, no sus predictores y V, y excluimos California de los donantes placebo.')

For a time placebo, pretend treatment occurred in 1980 and evaluate only through 1988, before the real policy. This is a diagnostic, not definitive proof of validity.

[ ]Time placebo before 1989Browser
# Simula una intervención en 1980. Tanto el ajuste como la evaluación
# se limitan a 1970-1988, antes de la intervención real de 1989.
fake_pre = years < 1980
fake_post = (years >= 1980) & (years <= 1988)
fake_A = Y[fake_pre, :-1] / 100
fake_b = Y[fake_pre, -1] / 100
fake_w = scm_slsqp(fake_A, fake_b)
fake_gap = Y[:, -1] - Y[:, :-1] @ fake_w
print('Intervención ficticia: 1980; ajuste 1970-1979; evaluación 1980-1988.')
print('Donantes: los 38 estados sin California; pesos ajustados solo con ventas 1970-1979.')
print('RMSE antes del corte ficticio:', np.sqrt(np.mean(fake_gap[fake_pre]**2)))
print('Brecha media 1980-1988:', fake_gap[fake_post].mean())
print('Una brecha pequeña no demuestra validez causal y una grande señala sensibilidad a examinar.')

Now generate a factor panel with treated level outside the control convex hull. Five post-periods remain fixed as the number of pre-periods varies.

[ ]sdid panelBrowser
import numpy as np

# Panel equilibrado: 12 controles, una tratada, 20 periodos anteriores y 5 posteriores.
# La selección de periodos previos se realiza después de generar todo el panel;
# así se conservan los mismos resultados posteriores entre comparaciones.
rg = np.random.default_rng(272122)
n0, t0, tpost = 12, 20, 5
tiempo = np.arange(t0+tpost)
factor = np.sin(tiempo/4) + .04*tiempo
nivel = np.r_[np.linspace(-2, 1, n0), 3.]
cargas = np.r_[np.linspace(0, 1.5, n0), 1.1]
ruido = rg.normal(0, .15, size=(n0+1,t0+tpost))
Y0 = nivel[:, None] + .03*tiempo[None, :] + cargas[:, None]*factor[None, :] + ruido
efecto = -2.
Y = Y0.copy()
Y[n0:, t0:] += efecto

def panel_con_pre(pre):
    if not isinstance(pre, int) or not 2 <= pre <= t0:
        raise ValueError('El número de periodos previos debe estar entre 2 y t0')
    return np.concatenate((Y[:, t0-pre:t0], Y[:, t0:]), axis=1)

print('Y:', Y.shape, 'controles:', n0, 'tratada: última fila, t0:', t0,
      'periodos posteriores:', tpost, 'efecto:', efecto)

Fit unit and time weights with free intercepts and stated penalty. The estimator uses uniform post-period means.

[ ]sdid functionsBrowser
import numpy as np
from scipy.optimize import minimize

def pesos_simplex(X, y, zeta, intercepto=True):
    """Minimiza ||a+Xw-y||² + m*zeta²||w||², w>=0, sum(w)=1.

    El intercepto a, si se permite, no se penaliza y se elimina analíticamente.
    X tiene m filas (observaciones) y k columnas (pesos).
    """
    X, y = np.asarray(X, float), np.asarray(y, float)
    if X.ndim != 2 or y.shape != (X.shape[0],) or not np.isfinite(X).all() or not np.isfinite(y).all():
        raise ValueError('X e y deben ser finitos y tener dimensiones compatibles')
    m, k = X.shape
    if m < 1 or k < 1 or not np.isfinite(zeta) or zeta < 0:
        raise ValueError('Dimensiones o penalización no válidas')
    Xc = X - X.mean(axis=0) if intercepto else X
    yc = y - y.mean() if intercepto else y
    def objective(w):
        res = Xc @ w - yc
        return float(res @ res + m*zeta**2*(w @ w))
    def grad(w):
        return 2*(Xc.T @ (Xc @ w - yc) + m*zeta**2*w)
    solution = minimize(objective, np.full(k, 1/k), jac=grad, method='SLSQP',
                        bounds=[(0., 1.)]*k,
                        constraints={'type':'eq','fun':lambda w:w.sum()-1,
                                     'jac':lambda w:np.ones(k)},
                        options={'ftol':1e-11,'maxiter':1000})
    if not solution.success or np.min(solution.x) < -1e-8 or abs(solution.x.sum()-1) > 1e-8:
        raise RuntimeError('No se encontró un mínimo factible: '+solution.message)
    w = solution.x
    a = float(np.mean(y-X@w)) if intercepto else 0.
    return w, a, float(objective(w))

def estimador_sdid(Y, n0, t0, zeta_omega=None, zeta_lambda=None):
    """Bloque equilibrado, controles arriba, tratadas abajo; sin covariables."""
    Y = np.asarray(Y, float)
    if Y.ndim != 2 or not np.isfinite(Y).all():
        raise ValueError('Y debe ser una matriz finita')
    n, T = Y.shape
    if not isinstance(n0, int) or not isinstance(t0, int) or not 0 < n0 < n or not 1 < t0 < T:
        raise ValueError('Se requieren controles, tratadas y al menos dos periodos previos')
    n1, t1 = n-n0, T-t0
    sigma = float(np.std(np.diff(Y[:n0,:t0], axis=1), ddof=1))
    if zeta_omega is None:
        zeta_omega = (n1*t1)**.25 * sigma
    if zeta_lambda is None:
        zeta_lambda = 1e-6*sigma
    # El vector de pesos de unidades reproduce la media tratada pre, salvo nivel.
    omega, a_omega, obj_omega = pesos_simplex(Y[:n0,:t0].T,
        Y[n0:,:t0].mean(axis=0), zeta_omega, intercepto=True)
    # Los pesos temporales reproducen la media posterior de cada control, salvo nivel.
    lam, a_lam, obj_lam = pesos_simplex(Y[:n0,:t0],
        Y[:n0,t0:].mean(axis=1), zeta_lambda, intercepto=True)
    gap = Y[n0:,:].mean(axis=0) - omega @ Y[:n0,:]
    tau = float(gap[t0:].mean()-lam @ gap[:t0])
    return {'tau':tau, 'omega':omega, 'lambda':lam,
            'intercepto_unidad':a_omega, 'intercepto_tiempo':a_lam,
            'obj_unidad':obj_omega, 'obj_tiempo':obj_lam,
            'zeta_omega':float(zeta_omega), 'zeta_lambda':float(zeta_lambda),
            'sigma_diferencias':sigma}

def estimador_did(Y,n0,t0):
    gap = Y[n0:,:].mean(axis=0)-Y[:n0,:].mean(axis=0)
    return float(gap[t0:].mean()-gap[:t0].mean())

def estimador_scm(Y,n0,t0):
    # Ajuste convexivo sin intercepto para comparar SC de resultados previos.
    w, _, _ = pesos_simplex(Y[:n0,:t0].T, Y[n0:,:t0].mean(axis=0), 1e-6, False)
    return float(Y[n0:,t0:].mean() - (w @ Y[:n0,t0:]).mean())

Compare the formula with a weighted fixed-effects regression and compare DiD, SCM, and SDID.

[ ]sdid exampleBrowser
def verificar_regresion(Y, n0, t0, omega, lam):
    """Misma DiD ponderada mediante MCO con efectos fijos y tratamiento."""
    n, T = Y.shape
    unitw = np.r_[omega, np.repeat(1/(n-n0), n-n0)]
    timew = np.r_[lam, np.repeat(1/(T-t0), T-t0)]
    ii, tt = np.indices((n, T))
    rows, cols = ii.ravel(), tt.ravel()
    W = ((rows >= n0) & (cols >= t0)).astype(float)
    design = np.column_stack([np.ones(n*T),
        np.eye(n)[rows,1:], np.eye(T)[cols,1:], W])
    weight = np.sqrt((unitw[:, None]*timew[None, :]).ravel())
    beta = np.linalg.lstsq(design*weight[:, None],Y.ravel()*weight,rcond=None)[0]
    return float(beta[-1])

for pre in (5, 10, 20):
    panel = panel_con_pre(pre)
    # Regularización temporal positiva explícita para una solución numéricamente única.
    result = estimador_sdid(panel, n0, pre, zeta_lambda=.05)
    did = estimador_did(panel, n0, pre)
    scm = estimador_scm(panel, n0, pre)
    beta = verificar_regresion(panel, n0, pre, result['omega'], result['lambda'])
    np.testing.assert_allclose(result['tau'], beta, atol=1e-8, rtol=0)
    assert np.all(result['omega']>=-1e-10) and np.isclose(result['omega'].sum(),1)
    assert np.all(result['lambda']>=-1e-10) and np.isclose(result['lambda'].sum(),1)
    print('previos:', pre, 'verdad:', efecto, 'DiD:', round(did,6),
          'SC:', round(scm,6), 'SDID:', round(result['tau'],6),
          'regresión ponderada:', round(beta,6))
    print('zeta unidades/tiempo:', round(result['zeta_omega'],6), result['zeta_lambda'])
    print('pesos de unidad:', np.round(result['omega'],5))
    print('pesos de tiempo:', np.round(result['lambda'],5))

Define augmented synthetic control using ridge; the correction changes effective weights and can make them negative.

[ ]ascm 01 functionsBrowser
import numpy as np

def simplex(v):
    """Proyección euclídea sobre pesos no negativos de suma uno."""
    v = np.asarray(v, dtype=float)
    u = np.sort(v)[::-1]
    q = np.cumsum(u) - 1
    indices = np.arange(1, len(u)+1)
    rho = np.flatnonzero(u-q/indices > 0)[-1]
    return np.maximum(v-q[rho]/(rho+1), 0.)

def pesos_scm(X, y, tol=1e-9, max_iter=5000):
    """X contiene controles × periodos previos; minimiza error en símplex."""
    X, y = np.asarray(X, float), np.asarray(y, float)
    if X.ndim != 2 or y.shape != (X.shape[1],) or X.shape[0] < 2:
        raise ValueError('Dimensiones incompatibles')
    if not np.isfinite(X).all() or not np.isfinite(y).all():
        raise ValueError('Se requieren datos finitos')
    L = float(np.linalg.norm(X, 2)**2)
    if L == 0:
        return np.full(len(X), 1/len(X))
    w = np.full(len(X), 1/len(X))
    # FISTA con comprobación de gradiente proyectado, no solo paso pequeño.
    z = w.copy()
    momentum = 1.
    for _ in range(max_iter):
        wnew = simplex(z - X @ (X.T @ z-y)/L)
        tnew = (1 + np.sqrt(1 + 4*momentum**2))/2
        z = wnew + (momentum-1)/tnew*(wnew-w)
        w, momentum = wnew, tnew
        residual = np.linalg.norm(w-simplex(w-X@(X.T@w-y)/L))
        if residual < tol:
            return w
    raise RuntimeError('El descenso no convergió; revisa escala o iteraciones')

def ascm_ridge(X, y, Z, ridge=1.):
    """SCM aumentado con intercepto ridge sin penalizar; X: controles × pre.

    Z tiene las mismas filas de controles y una columna por periodo posterior.
    Devuelve pronósticos SCM/ASCM y pesos aumentados compartidos por periodos.
    """
    X, y, Z = np.asarray(X, float), np.asarray(y, float), np.asarray(Z, float)
    if Z.ndim != 2 or Z.shape[0] != X.shape[0] or not np.isfinite(Z).all():
        raise ValueError('Z debe contener los resultados posteriores de los controles')
    if not np.isfinite(ridge) or ridge <= 0:
        raise ValueError('La penalización ridge debe ser positiva')
    w = pesos_scm(X, y)
    Xc = X-X.mean(axis=0)
    d = y-X.T@w
    gram = Xc.T@Xc + ridge*np.eye(X.shape[1])
    aug = w + [email protected](gram, d)
    # Forma alternativa: ajuste ridge con intercepto y corrección residual.
    Zc = Z-Z.mean(axis=0)
    beta = np.linalg.solve(gram, Xc.T@Zc)
    ridge_treated = Z.mean(axis=0) + (y-X.mean(axis=0))@beta
    ridge_donors = Z.mean(axis=0) + Xc@beta
    via_residuos = ridge_treated + w@(Z-ridge_donors)
    via_pesos = aug@Z
    np.testing.assert_allclose(via_pesos, via_residuos, atol=1e-9, rtol=0)
    assert np.isclose(w.sum(), 1) and np.isclose(aug.sum(), 1)
    return {'w': w, 'w_aug': aug, 'scm': w@Z, 'ascm': via_pesos,
            'rmse_pre_scm': float(np.sqrt(np.mean(d*d))),
            'rmse_pre_ascm': float(np.sqrt(np.mean((y-X.T@aug)**2)))}

Compare three pre-period lengths in the same sample. It does not follow that correction always improves as periods are added.

[ ]ascm 02 simulationBrowser
# Usa el panel Y y t0 de la celda previa: última fila tratada, resto controles.
# Mantén fijos los cinco resultados posteriores al variar el periodo previo.
for pre in (5, 10, 20):
    X = Y[:-1, t0-pre:t0]
    y = Y[-1, t0-pre:t0]
    Z = Y[:-1, t0:]
    tratado_post = Y[-1, t0:]
    resultado = ascm_ridge(X, y, Z, ridge=1.)
    tau_scm = float(np.mean(tratado_post-resultado['scm']))
    tau_ascm = float(np.mean(tratado_post-resultado['ascm']))
    print('pre:', pre, 'RMSE pre SCM/ASCM:',
          round(resultado['rmse_pre_scm'], 4), round(resultado['rmse_pre_ascm'], 4),
          'efecto SCM/ASCM:', round(tau_scm, 4), round(tau_ascm, 4),
          'mínimo peso aumentado:', round(float(resultado['w_aug'].min()), 4),
          'suma pesos:', round(float(resultado['w_aug'].sum()), 8))
print('Efecto verdadero de esta simulación:', efecto)

Load the optimizer for an independent check.

[ ]ascm 03 import scipyBrowser
from scipy.optimize import minimize

Compare simplex and ridge fits with alternative formulations.

[ ]ascm 03 checkBrowser
# Contraste independiente: SLSQP para el símplex y mínimos cuadrados
# aumentados con intercepto libre para ridge. No comparar pesos cuando
# existen múltiples soluciones óptimas con el mismo objetivo.
for pre in (5, 10, 20):
    X = Y[:-1, t0-pre:t0]
    y = Y[-1, t0-pre:t0]
    Z = Y[:-1, t0:]
    resultado = ascm_ridge(X, y, Z, ridge=1.)
    n, p = X.shape
    objective = lambda w: .5*np.sum((X.T@w-y)**2)
    gradient = lambda w: X@(X.T@w-y)
    ref = minimize(objective, np.ones(n)/n, jac=gradient, method='SLSQP',
                   bounds=[(0.,1.)]*n,
                   constraints={'type':'eq', 'fun':lambda w:w.sum()-1,
                                'jac':lambda w:np.ones(n)},
                   options={'ftol':1e-11, 'maxiter':1000})
    assert ref.success, ref.message
    np.testing.assert_allclose(objective(resultado['w']), objective(ref.x),
                               atol=1e-7, rtol=0)
    # Formulación primal de ridge: mínimos cuadrados con filas artificiales
    # y sin penalizar el intercepto. Respuesta por columnas posteriores.
    D = np.column_stack([np.ones(n), X])
    penalty = np.column_stack([np.zeros(p), np.eye(p)])
    design = np.vstack([D, penalty])
    targets = np.vstack([Z, np.zeros((p, Z.shape[1]))])
    theta = np.linalg.lstsq(design, targets, rcond=None)[0]
    fit_treated = np.r_[1., y]@theta
    fit_donors = D@theta
    pred = fit_treated + resultado['w']@(Z-fit_donors)
    np.testing.assert_allclose(resultado['ascm'], pred, atol=1e-8, rtol=0)
    print('pre:', pre, 'diferencia objetivo SLSQP:',
          f"{objective(resultado['w'])-objective(ref.x):.3g}",
          'máxima diferencia predicción ridge:', f"{np.max(np.abs(pred-resultado['ascm'])):.3g}")
print('Coinciden optimización convexa y las dos formulaciones ridge.')

Exercises

ProofFrom prior fit to loadings
Prove: Assume the undisturbed factor model Yit(0)=δt+θt⊤Zi+λt⊤μiY_{it}(0)=\delta_t+\theta_t^\top Z_i+\lambda_t^\top\mu_i. Weights sum to one, balance ZZ and exactly reproduce prior outcomes. The matrix with rows λt⊤\lambda_t^\top from pre-periods has full column rank. Prove that weights also balance loadings and thus later untreated outcomes.
The proof will appear here as you work.

Step 1 of 3. Which terms cancel when subtracting the weighted combination from the treated unit?

ProofDiD as a special case
Prove: In the single-treated-unit SDID formula, assign uniform weights to controls and prior periods and retain the uniform post-period mean. Prove this gives difference-in-differences.
The proof will appear here as you work.

Step 1 of 3. What does the treated unit’s weighted prior mean produce?

NumericCount ties and treated unit
One treated unit and 38 placebos are compared. Four placebos have a post/pre MSPE ratio at least as large as the treated unit’s, and the others have a smaller ratio. Calculate the inclusive rank, counting the treated unit and ties.
CodeSolve synthetic control
Implement scm_weights(Y0_pre, y1_pre). Y0_pre is a finite numeric matrix with periods in rows and donors in columns; y1_pre is a finite vector with the same number of periods. Return a vector w minimizing the sum of squares ||Y0_pre @ w - y1_pre||² with w >= 0 and sum(w)=1. Raise ValueError for empty matrices, incompatible dimensions, or non-finite values. You may use projected gradient descent: calculate a stable rate and project onto the simplex. If you do not converge, signal failure instead of returning a purported optimum. When several optimal solutions exist, the objective and constraints are evaluated, not one specific weight vector.
import numpy as np

def scm_weights(Y0_pre, y1_pre):
  """Y0_pre tiene periodos en filas y donantes en columnas."""
  raise NotImplementedError
Shift+Enter to run
QuizPoor prior fit
A synthetic state reproduces neither prior levels nor trend of the treated state. What is a prudent conclusion?
QuizAffected donors
The treated country’s policy shifts activity toward candidate donor countries. What is the risk?
QuizFew donors
Only four valid donors exist and the treated unit has the most extreme error ratio among all five. What does inclusive rank permit?
QuizChoosing predictors
You try many V matrices and choose the one producing the largest post-law decline. What is the problem?

After solving the rank exercise, check its arithmetic:

[ ]Inclusive rank exerciseBrowser
placebos_extremos, placebos = 4, 38
rango_ejercicio = (placebos_extremos + 1) / (placebos + 1)
assert abs(rango_ejercicio - 5/39) < 1e-12
print("Rango inclusivo:", rango_ejercicio)