Module contents
Stage 6 of 9Advanced 100 min

Synthetic control and California's tobacco tax

Study California's Proposition 99 by building a synthetic California as a convex combination of other states, estimating the cigarette-sales gap, and examining spatial and temporal placebos. Compare synthetic difference-in-differences and discuss pre-period overfitting.

After this lesson you can

  • Solve synthetic-control weights as a constrained optimization problem.
  • Qualitatively reproduce the published Proposition 99 trajectory and effect.
  • Calculate a placebo permutation rank and the ratio of post- to pre-treatment errors.
  • Implement synthetic DiD and compare its estimates with synthetic control.

Before you start

A counterfactual California

Proposition 99, approved in 1988, introduced a tobacco tax and funded control measures; the analysis treats 1989 as the first post-treatment year. To study cigarette sales per capita, Abadie, Diamond, and Hainmueller compare California with a combination of other states. This is a composite intervention, and the measure is packs sold per capita, not direct observation of each person’s consumption.

A synthetic control chooses nonnegative weights summing to one to reproduce treated-unit characteristics before intervention. If Y0,preY_{0,\mathrm{pre}} has one column per donor and y1,prey_{1,\mathrm{pre}} is the treated trajectory, a simple specification solves

min⁡w≥0,  1⊤w=1∥Y0,prew−y1,pre∥22.\min_{w\ge0,\;\mathbf{1}^{\top}w=1}\|Y_{0,\mathrm{pre}}w-y_{1,\mathrm{pre}}\|_2^2.

The simplex prevents extrapolation outside the donors’ convex hull. It does not guarantee a good combination exists or that its later evolution is the true counterfactual. The original article uses specific predictors and weights; here we fit all 19 prior annual values equally, without those additional predictors. This reproducible choice helps study overlap but does not exactly reproduce published weights or results.

If two donors have very similar trajectories, different weight allocations can produce nearly the same fit. Weights are not probabilities that a state is the true California, and small perturbations can change their allocation. Check sensitivity by leaving out high-weight donors and reserve some prior years for evaluation outside the fitting window. In this example pre-treatment RMSPE is in-sample, not independent temporal validation.

The data come from the original file included by the synthdid authors, pinned to commit eaf905d96bdcd26d7b7386a8afa5f31488ffbfd0 and verified by SHA-256. There are 39 states observed from 1970 to 2000, with 38 possible donors for California. The authors’ preparation code identifies rows and the 1989 start. Donor selection matters: a similar policy or spillover in another state can contaminate the comparison.

InteractiveCalifornia weights and trajectories
  • California
  • Optimized synthetic

The optimizer uses all 38 donor states and fits the 19 prior years. The gap is California minus its synthetic control.

RMSPE before 19891.66
Mean post-treatment gap-19.51
Optimized rank3/39
Historical sales data; placebos and optimal fit were calculated previously using this lesson's specification.

Optimized mode can use all 38 donors; manual mode edits six with relevant weight and normalizes them to sum one. If all manual inputs are zero, six equal weights are used. The placebo view shows results already calculated by the lab; rank is not recalculated from manual weights. The optimizer assigned approximately 39.4% to Utah, 23.2% to Montana, 20.5% to Nevada, 10.9% to Connecticut, 4.5% to New Hampshire, and 1.5% to Colorado.

The root mean squared prediction error before 1989, or RMSPE, was 1.656 packs per capita. The mean gap from 1989 to 2000, California minus control, was -19.514; in 2000 the values were 41.60 and 68.20. These are results of this specification, not a new experimental estimate or a transcription of the article’s figure. Good pre-fit increases comparison plausibility, but an almost perfect fit with many degrees of freedom can memorize noise; reserve prior years for validation and document predictor choice before inspecting post-treatment results.

Placebos across space and time

Placebo inference applies the same rule to each donor as if treated. We compare post-treatment RMSPE divided by pre-treatment RMSPE: a large later gap with poor prior fit can be uninformative. In the symmetric rule, each state uses the other 38 as potential donors. California ranks third of 39: Missouri and Virginia have larger ratios. The rank fraction is 3/39≈0.0773/39\approx0.077, counting ties at least as extreme and the observed state.

That value is not automatically an exact pp: the real intervention was not randomly assigned among states, exchangeability is debatable, and California can contaminate a placebo by acting as a donor after 1989. Excluding California from each placebo’s donors keeps rank 3, but the rule is no longer symmetric and that check is descriptive sensitivity. This specification’s rank is not the first expected in the design; the measured result is retained. Rank depends on windows, predictors, donors, and exclusion rules.

A very small prior RMSPE denominator can yield a large ratio even with a moderate post-treatment gap. Inspect both errors separately and the trajectories rather than ranking states on a single number and discarding other diagnostics. A permutation test would have an assignment interpretation only under exchangeability and an assignment mechanism supporting that comparison.

A temporal placebo uses only 1970 through 1988, places a false intervention in 1980, and fits 1970 through 1979. In this run its mean gap from 1980 to 1988 is -3.37, with prior RMSPE 0.84. This diagnoses that window and does not guarantee that no other changes occurred in 1989. Looking at many cutoffs and choosing the most favorable creates additional selection that must be recorded.

Synthetic control and differences-in-differences

Synthetic DiD combines unit and period weights with a difference of gaps. With weights ω\omega on controls and λ\lambda on prior times, the effect for one treated unit is

τ^=1T1∑t≥T0(Y1t−ω⊤Y0t)−∑t<T0λt(Y1t−ω⊤Y0t).\hat\tau=\frac{1}{T_1}\sum_{t\ge T_0}(Y_{1t}-\omega^\top Y_{0t})-\sum_{t<T_0}\lambda_t(Y_{1t}-\omega^\top Y_{0t}).

Unit weights are chosen to approximate the treated unit before intervention, allowing an intercept and penalizing concentration. Time weights approximate the controls’ post-treatment mean from their prior periods, also with an intercept. Both vectors lie in their simplex. Subtracting the weighted pre-gap permits different levels; it does not correct every differing trend. Arkhangelsky and colleagues describe the construction and conditions.

In this run CVXPY obtains -15.605 packs per capita, and diff-diff returns -15.604 with its Frank-Wolfe algorithm and sparsification. The SDID weight fit permits an intercept: pre-treatment RMSPE without adjusting levels is 24.81, but after the intercept it is 1.73. The library warns of poor pre-fit using its no-intercept level diagnostic; it should not be ignored, although that diagnostic measures a different quantity from the centered objective. The library’s synthetic-control comparison approximates -19.523 with RMSPE 1.662 and warns its optimizer did not converge after 100,000 iterations; the custom convex solution has RMSPE 1.656. Differences are documented without claiming exact equality.

Synthetic DiD can help if a persistent level shift makes exact fit difficult and time weights are defensible. Pure synthetic control can be preferable if a convex combination fits the level well and an interpretable counterfactual trajectory is desired. Neither method automatically determines causal validity, absence of coincident policies, or stability outside the pre-period.

Laboratory

With Python 3.12 install python -m pip install "numpy==2.2.6" "pandas==2.3.3" "scipy==1.15.3" "scikit-learn==1.6.1" "cvxpy==1.9.3" "diff-diff==3.8.0". Download synth.py, test_synth.py, and experiment.py into the same directory. The complete results include trajectories, weights, placebos, versions, and reference warnings. Run python test_synth.py and python experiment.py --data data/california_prop99.txt --out results.json. The second downloads the pinned file, checks its hash, and does not overwrite results. The next cell repeats optimization and comparisons.

[ ]California, placebos, and synthetic DiDLocal GPU
"""Control sintético y SDID convexos con datos primarios versionados."""
import hashlib,urllib.request
from pathlib import Path
import numpy as np
import cvxpy as cp

REVISION='eaf905d96bdcd26d7b7386a8afa5f31488ffbfd0'
URL=f'https://raw.githubusercontent.com/synth-inference/synthdid/{REVISION}/experiments/california_smoking/data/raw/california_prop99.txt'
SHA256='0dd5e2b7cd44c99fa1f67764bb727dd436a4f65c7aee8541a663d0d4122f4014'
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']

def load_data(path):
    path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
    if not path.exists():
        with urllib.request.urlopen(URL,timeout=90) as r:data=r.read()
        if hashlib.sha256(data).hexdigest()!=SHA256:raise ValueError('Hash inesperado')
        path.write_bytes(data)
    if hashlib.sha256(path.read_bytes()).hexdigest()!=SHA256:raise ValueError('Archivo modificado')
    data=np.loadtxt(path)
    if data.shape!=(39,39) or int(data[0,-1])!=3:raise ValueError('Matriz fuente inesperada')
    return np.arange(1970,2001), data[8:,:].T

def simplex_fit(A,b,ridge=0.,intercept=False):
    A,b=np.asarray(A,float),np.asarray(b,float)
    if A.ndim!=2 or b.shape!=(A.shape[0],) or not np.isfinite(A).all() or not np.isfinite(b).all() or ridge<0:
        raise ValueError('Dimensiones o parámetros inválidos')
    w=cp.Variable(A.shape[1]);offset=cp.Variable() if intercept else 0.
    objective=cp.sum_squares(A@w+offset-b)/A.shape[0]+ridge**2*cp.sum_squares(w)
    problem=cp.Problem(cp.Minimize(objective),[w>=0,cp.sum(w)==1])
    problem.solve(solver='CLARABEL')
    if problem.status not in ('optimal','optimal_inaccurate') or w.value is None:raise RuntimeError('Optimización fallida')
    weights=np.maximum(np.asarray(w.value).reshape(-1),0);weights/=weights.sum()
    return weights,float(offset.value) if intercept else 0.

def synth_weights(Y0_pre,y1_pre):return simplex_fit(Y0_pre,y1_pre)[0]

def fit_sc(Y,target,pre=19,excluded=()):
    Y=np.asarray(Y,float);donors=[i for i in range(len(Y)) if i!=target and i not in excluded]
    if pre<2 or pre>=Y.shape[1] or not donors:raise ValueError('Muestra inválida')
    weights=synth_weights(Y[donors,:pre].T,Y[target,:pre]);synthetic=weights@Y[donors]
    gap=Y[target]-synthetic
    before=float(np.sqrt(np.mean(gap[:pre]**2)));after=float(np.sqrt(np.mean(gap[pre:]**2)))
    return {'target':int(target),'donors':donors,'weights':weights,'synthetic':synthetic,'gap':gap,
            'pre_rmspe':before,'post_rmspe':after,'ratio':after/before if before>0 else np.inf,
            'mean_post_gap':float(gap[pre:].mean())}

def fit_sdid(Y,target,pre=19):
    Y=np.asarray(Y,float);donors=[i for i in range(len(Y)) if i!=target]
    controls=Y[donors];treated=Y[target];npost=Y.shape[1]-pre
    noise=float(np.std(np.diff(controls[:,:pre],axis=1),ddof=1))
    zeta_omega=npost**.25*noise;zeta_lambda=1e-6*noise
    omega,offset=simplex_fit(controls[:,:pre].T,treated[:pre],ridge=zeta_omega,intercept=True)
    lam,offset_t=simplex_fit(controls[:,:pre],controls[:,pre:].mean(axis=1),ridge=zeta_lambda,intercept=True)
    delta=treated-omega@controls
    estimate=float(delta[pre:].mean()-delta[:pre]@lam)
    return {'estimate':estimate,'omega':omega,'lambda':lam,'donors':donors,
            'omega_intercept':offset,'lambda_intercept':offset_t,
            'noise':noise,'zeta_omega':zeta_omega,'zeta_lambda':zeta_lambda}

"""Invariantes del símplex y recuperación SDID en datos sin ruido."""
import numpy as np

A=np.array([[0.,1.,2.],[1.,0.,2.],[2.,1.,0.],[0.,2.,1.]])
truth=np.array([.2,.3,.5]);target=A@truth
w=synth_weights(A,target)
assert np.all(w>=-1e-9) and abs(w.sum()-1)<1e-9
assert np.linalg.norm(A@w-target)<1e-5
Y=np.array([[i+2*t for t in range(8)] for i in range(6)],float)
Y[-1,4:]+=3
result=fit_sdid(Y,5,pre=4)
assert abs(result['estimate']-3)<1e-5
assert abs(result['omega'].sum()-1)<1e-8 and abs(result['lambda'].sum()-1)<1e-8
print('Símplex y SDID con efecto conocido pasan')
"""Proposición 99 con placebos, comparadores y fuentes fijadas."""
import argparse,json,platform,warnings
from pathlib import Path
import numpy as np
import pandas as pd
import cvxpy
import diff_diff
from diff_diff import SyntheticControl,SyntheticDiD

def run(path):
    years,Y=load_data(path);cal=fit_sc(Y,38)
    # La regla simétrica incluye California como donante de cada placebo;
    # una sensibilidad alternativa la excluye para evitar contaminación.
    placebos=[fit_sc(Y,i) for i in range(38)]
    excluded_ca=[fit_sc(Y,i,excluded=[38]) for i in range(38)]
    ranks=sorted([{'state':STATES[x['target']],'ratio':float(x['ratio']),
                   'pre_rmspe':x['pre_rmspe'],'mean_post_gap':x['mean_post_gap']} for x in placebos],
                 key=lambda x:-x['ratio'])
    rank=1+sum(x['ratio']>=cal['ratio'] for x in placebos)
    rank_excluded=1+sum(x['ratio']>=cal['ratio'] for x in excluded_ca)
    fake=fit_sc(Y[:,:19],38,pre=10)
    sd=fit_sdid(Y,38)
    long=pd.DataFrame([(STATES[i],int(t),float(Y[i,j]),int(i==38 and t>=1989),int(i==38))
                       for i in range(39) for j,t in enumerate(years)],columns=['state','year','y','treated','group'])
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter('always')
        sc_ref=SyntheticControl(v_method='custom',custom_v=np.ones(19),standardize='none',
                   inner_max_iter=100000,inner_min_decrease=1e-9).fit(long,'y','treated','state','year',
                   treated_unit='California',pre_period_outcomes='all')
        sd_ref=SyntheticDiD(variance_method='placebo',n_bootstrap=10,seed=601).fit(long,'y','group','state','year',
                    post_periods=list(range(1989,2001)))
    assert abs(sd['estimate']-sd_ref.att)<.05
    assert abs(cal['pre_rmspe']-sc_ref.pre_rmspe)<.03
    keep=lambda x:{k:float(x[k]) for k in ('pre_rmspe','post_rmspe','ratio','mean_post_gap')}
    return {'source':{'revision':REVISION,'sha256':SHA256},'years':years.tolist(),
            'states':STATES,'outcomes':Y.tolist(),'california':{**keep(cal),'weights':cal['weights'].tolist(),
            'donors':cal['donors'],'synthetic':cal['synthetic'].tolist(),'gap':cal['gap'].tolist(),
            'rank':int(rank),'n_placebos_including_ca':39,'permutation_rank_fraction':rank/39},
            'placebos':ranks,'rank_excluding_california_from_placebo_donors':int(rank_excluded),
            'time_placebo_1980_1988':keep(fake),
            'sdid':{'estimate':sd['estimate'],'omega':sd['omega'].tolist(),'lambda':sd['lambda'].tolist(),
                    'donors':sd['donors'],'zeta_omega':sd['zeta_omega'],'zeta_lambda':sd['zeta_lambda'],
                    'omega_intercept':sd['omega_intercept'],'lambda_intercept':sd['lambda_intercept']},
            'reference':{'sc_att':float(sc_ref.att),'sc_pre_rmspe':float(sc_ref.pre_rmspe),
                         'sdid_att':float(sd_ref.att),'warnings':[str(x.message) for x in caught]},
            'versions':{'python':platform.python_version(),'numpy':np.__version__,'pandas':pd.__version__,
                        'cvxpy':cvxpy.__version__,'diff_diff':diff_diff.__version__}}


result=run('data/california_prop99.txt')
print('California:',{k:v for k,v in result['california'].items() if k not in ('weights','donors','synthetic','gap')})
print('Placebos mayores:',result['placebos'][:2])
print('Placebo temporal:',result['time_placebo_1980_1988'])
print('SDID:',result['sdid']['estimate'],'referencia:',result['reference'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
In a hypothetical example of 39 states, the treated state has the largest ratio and there are no ties. If rank/39 is used, what value results?
Quiz
A control nearly perfectly reproduces many prior predictors chosen after testing numerous variants. What risk should you examine?
Quiz
When is synthetic DiD worth considering alongside pure synthetic control?
Code
Implement synth_weights(Y0_pre, y1_pre): accept a periods × donors matrix and a periods vector, and return nonnegative weights summing to one that minimize pre-treatment squared error. Use CVXPY and check solver status.
def synth_weights(Y0_pre, y1_pre):
  pass
Shift+Enter to run

Summary

Key idea
Synthetic control builds a convex comparison from prior data; placebos and fit do not remove the need to justify donors and assumptions. Synthetic DiD adds time weights and a difference of gaps.