# CausalImpact in Python: Estimate a Campaign's Effect with Structural Time Series

> CausalImpact in Python with statsmodels UnobservedComponents: forecast the no-campaign counterfactual from control series, get pointwise and cumulative effects, run a placebo test, and compare with tfcausalimpact.

Source: https://www.pythoncharts.com/causal-inference/causalimpact-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: Causal Inference | Tags: causal inference, causalimpact, structural time series, counterfactual, campaign measurement, placebo test, statsmodels, time series

CausalImpact estimates the effect of something that happened once (a campaign, a launch, a price change) by training a time series model on the period before it, using control series that were not affected, and forecasting what the outcome would have been afterward. The gap between actual and forecast is the estimated effect. Google's original is an R package. In Python, you can build the same model with `statsmodels.tsa.statespace.structural.UnobservedComponents`, as this post does, or use `tfcausalimpact`.

## Quick Example

A marketing campaign starts on day 101 in one region. Two other regions have no campaign and share the same market trend, so their sales act as controls. The code fits a local-level model with the two control series as regressors on the first 100 days only, then forecasts the next 50 days with intervals.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.statespace.structural import UnobservedComponents

rng = np.random.default_rng(52)

# Sample data: daily sales in the campaign region, plus two regions with no campaign
n, n_pre = 150, 100
dates = pd.date_range("2026-01-01", periods=n)
season = 4 * np.sin(2 * np.pi * np.arange(n) / 7)
shared = np.cumsum(rng.normal(0, 1.2, n))                      # common market trend
ctrl_a = 200 + shared + season + rng.normal(0, 2, n)
ctrl_b = 150 + 0.8 * shared + season + rng.normal(0, 2, n)
level = np.cumsum(rng.normal(0, 0.4, n))                       # region-specific drift
effect = np.where(np.arange(n) >= n_pre, 12 * (1 - np.exp(-(np.arange(n) - n_pre + 1) / 5)), 0)   # ramps up to +12 per day
sales = 120 + 0.9 * shared + 0.6 * (ctrl_a - 200) + season + level + effect + rng.normal(0, 2.5, n)
df = pd.DataFrame({"sales": sales, "control_a": ctrl_a, "control_b": ctrl_b}, index=dates)
pre, post = df.iloc[:n_pre], df.iloc[n_pre:]
print("true average effect:", round(float(effect[n_pre:].mean()), 2), " true cumulative effect:", round(float(effect[n_pre:].sum()), 1))

def fit_impact(pre, post, alpha=0.05, reps=2000):
    """Fit on the pre-period only, forecast the post-period, return actual vs predicted and effects."""
    cols = ["control_a", "control_b"]
    model = UnobservedComponents(pre["sales"], level="local level", exog=pre[cols])
    res = model.fit(disp=False)
    pred = res.get_forecast(steps=len(post), exog=post[cols]).summary_frame(alpha=alpha)
    out = pd.DataFrame({"actual": post["sales"], "pred": pred["mean"],
                        "pred_lo": pred["mean_ci_lower"], "pred_hi": pred["mean_ci_upper"]})
    out["effect"] = out.actual - out.pred
    out["effect_lo"] = out.actual - out.pred_hi
    out["effect_hi"] = out.actual - out.pred_lo
    # Cumulative effect intervals need the joint uncertainty, so simulate future paths
    sims = res.simulate(nsimulations=len(post), anchor="end", repetitions=reps, exog=post[cols],
                        random_state=0).to_numpy().reshape(len(post), reps)
    cum = np.cumsum(post["sales"].to_numpy()[:, None] - sims, axis=0)
    out["cum"] = cum.mean(axis=1)
    out["cum_lo"] = np.percentile(cum, 100 * alpha / 2, axis=1)
    out["cum_hi"] = np.percentile(cum, 100 * (1 - alpha / 2), axis=1)
    return res, out

res, imp = fit_impact(pre, post)
print("average effect:", round(imp.effect.mean(), 2))
print(f"cumulative effect: {imp.cum.iloc[-1]:.0f} (95% interval {imp.cum_lo.iloc[-1]:.0f} to {imp.cum_hi.iloc[-1]:.0f})")
print(f"relative effect: {imp.effect.sum() / imp.pred.sum():.1%}")

fig, axes = plt.subplots(3, 1, figsize=(9, 8.2), sharex=True)
ax = axes[0]
ax.plot(df.index, df.sales, color="#1d3557", lw=1.4, label="Observed")
ax.plot(imp.index, imp.pred, color="#e76f51", lw=1.8, ls="--", label="Predicted without campaign")
ax.fill_between(imp.index, imp.pred_lo, imp.pred_hi, color="#e76f51", alpha=0.2)
ax.set_ylabel("Daily sales")
ax.legend(loc="upper left")
ax = axes[1]
ax.plot(imp.index, imp.effect, color="#2a9d8f", lw=1.6)
ax.fill_between(imp.index, imp.effect_lo, imp.effect_hi, color="#2a9d8f", alpha=0.2)
ax.axhline(0, color="black", lw=0.8, ls=":")
ax.set_ylabel("Pointwise effect")
ax = axes[2]
ax.plot(imp.index, imp.cum, color="#7a4ea3", lw=1.8)
ax.fill_between(imp.index, imp.cum_lo, imp.cum_hi, color="#7a4ea3", alpha=0.2)
ax.axhline(0, color="black", lw=0.8, ls=":")
ax.set_ylabel("Cumulative effect")
for a in axes:
    a.axvline(dates[n_pre], color="gray", ls=":", lw=1.2)
axes[0].set_title("Campaign launches on day 101 (dotted line)")
fig.autofmt_xdate()
fig.tight_layout()
```

![Three stacked charts. Top: observed daily sales rising above a dashed predicted line after the campaign start. Middle: pointwise effect rising to about 10 to 15 units per day. Bottom: cumulative effect climbing to about 550 with a widening interval](https://www.pythoncharts.com/causal-inference/causalimpact-python/images/causalimpact-plot.png)

The simulated campaign ramps up to +12 sales per day, which averages +10.92 per day over the 50 days (546 in total). The model's estimate is +10.99 per day, a cumulative effect of 552 with a 95% interval of 374 to 728, and a relative effect of 8.4%. The top chart is the core idea: the dashed line is the model's forecast of sales without the campaign, and the observed line pulls away from it. The interval on the cumulative effect widens over time because forecast uncertainty accumulates.

## How Does CausalImpact Work?

1. **Fit** a structural time series model on the pre-period: a local level (a slowly drifting baseline) plus regression on control series. The controls capture what the outcome does because of the market, the season or anything else shared.
2. **Forecast** the post-period using the controls' post-period values. This is the counterfactual: sales without the campaign.
3. **Subtract** the forecast from the actual values. The difference is the pointwise effect, and its running sum is the cumulative effect.

The model's coefficients show how it used the controls. Here `beta.control_a` is 1.00 (std err 0.14) and `beta.control_b` is 0.39 (std err 0.13). In `UnobservedComponents`, `level="local level"` is a random-walk baseline. Add `seasonal=7` for a weekly cycle if the controls do not already carry it.

Two assumptions matter more than the model details: the controls must **not be affected by the campaign**, and the relationship between target and controls must **stay stable** after the launch. Neither can be tested directly.

## How Do I Check the Estimate with a Placebo Test?

Pretend the campaign started earlier, inside the pre-period, and run the same analysis. A good setup finds no effect. Here the fake launch is on day 71:

```python
pl_pre, pl_post = df.iloc[:70], df.iloc[70:n_pre]
_, pl = fit_impact(pl_pre, pl_post)
print(f"placebo average effect {pl.effect.mean():.2f}, cumulative {pl.cum.iloc[-1]:.0f} "
      f"(95% interval {pl.cum_lo.iloc[-1]:.0f} to {pl.cum_hi.iloc[-1]:.0f})")

fig, ax = plt.subplots(figsize=(8.5, 4.2))
ax.plot(pl.index, pl.effect, color="#2a9d8f", lw=1.6, label="Placebo pointwise effect")
ax.fill_between(pl.index, pl.effect_lo, pl.effect_hi, color="#2a9d8f", alpha=0.2, label="95% interval")
ax.axhline(0, color="black", lw=0.8, ls=":")
ax.set_ylabel("Estimated effect (units per day)")
ax.set_title("Placebo test: no campaign happened here, so the effect should hover around 0")
ax.legend(loc="lower left")
fig.autofmt_xdate()
fig.tight_layout()
```

![Pointwise placebo effect over days 71 to 100 hovering mostly between 0 and 8 units per day, with a wide 95 percent band that mostly but not entirely contains zero](https://www.pythoncharts.com/causal-inference/causalimpact-python/images/causalimpact-placebo.png)

This placebo run did not come out clean: it estimates +3.21 per day, with a cumulative interval of 56 to 137 that excludes zero, even though nothing happened. That is a useful warning, and it is not a one-off. Re-running the whole setup on 120 freshly simulated datasets:

```python
def make(seed):
    r = np.random.default_rng(seed)
    sh = np.cumsum(r.normal(0, 1.2, n))
    se = 4 * np.sin(2 * np.pi * np.arange(n) / 7)
    a = 200 + sh + se + r.normal(0, 2, n)
    b = 150 + 0.8 * sh + se + r.normal(0, 2, n)
    lv = np.cumsum(r.normal(0, 0.4, n))
    ef = np.where(np.arange(n) >= n_pre, 12 * (1 - np.exp(-(np.arange(n) - n_pre + 1) / 5)), 0)
    y = 120 + 0.9 * sh + 0.6 * (a - 200) + se + lv + ef + r.normal(0, 2.5, n)
    return pd.DataFrame({"sales": y, "control_a": a, "control_b": b}, index=dates), ef

covered = false_pos = 0
SEEDS = 120
for seed in range(SEEDS):
    d, ef = make(seed)
    _, real = fit_impact(d.iloc[:n_pre], d.iloc[n_pre:], reps=300)
    covered += real.cum_lo.iloc[-1] <= ef[n_pre:].sum() <= real.cum_hi.iloc[-1]
    _, fake = fit_impact(d.iloc[:70], d.iloc[70:n_pre], reps=300)
    false_pos += not (fake.cum_lo.iloc[-1] <= 0 <= fake.cum_hi.iloc[-1])
print(f"interval covered the true cumulative effect in {covered / SEEDS:.0%} of {SEEDS} datasets (nominal 95%)")
print(f"placebo interval excluded zero in {false_pos / SEEDS:.0%} of {SEEDS} datasets (nominal 5%)")
```

The nominal 95% interval covered the true cumulative effect in 86% of datasets, and the placebo interval excluded zero in 16% instead of 5%. The intervals from this maximum-likelihood fit are too narrow, because they treat the estimated variances and regression coefficients as known. Read them as optimistic, make the placebo test part of the analysis, and trust effects that are large compared with the placebo noise (here, 11 per day against a placebo of about 3).

## Does tfcausalimpact Give the Same Answer?

`tfcausalimpact` is a Python port of Google's package built on TensorFlow Probability (a fully Bayesian model). I ran it on this exact data (the first 100 days as the pre-period) under Python 3.12 with `tfcausalimpact` 0.0.19:

```text
                          Average            Cumulative
Actual                    142.3              7114.93
Prediction (s.d.)         130.28 (0.86)      6513.94 (42.82)
95% CI                    [128.65, 132.01]   [6432.63, 6600.5]

Absolute effect (s.d.)    12.02 (0.86)       600.99 (42.82)
95% CI                    [10.29, 13.65]     [514.44, 682.3]

Relative effect (s.d.)    9.23% (0.66%)      9.23% (0.66%)
95% CI                    [7.9%, 10.47%]     [7.9%, 10.47%]
```

Both land close to the truth of 10.92 per day: 10.99 from the `statsmodels` version and 12.02 from `tfcausalimpact`. The `tfcausalimpact` intervals are much narrower (10.29 to 13.65 per day, and 514 to 682 cumulative) and still contain the true values (10.92 and 546), but only just. I ran each once on this dataset, so this does not show that one is better. The point is that a structural time series model gives similar answers whichever implementation fits it.

Package notes from when I tried them with pandas 3.0 and Python 3.14: the older `pycausalimpact` (0.1.1) failed on `DataFrame.applymap`, and the newer `causalimpact` (0.2.6) failed on `pd.core.dtypes.common.is_datetime_or_timedelta_dtype`, which pandas removed. `tfcausalimpact` worked on Python 3.12 but pulls in TensorFlow, which is a heavy install. These are version snapshots and may have been fixed since.

## CausalImpact vs Other Methods

| Method | Needs | Best when |
|---|---|---|
| CausalImpact (this post) | A long pre-period and control series not affected by the change | One treated unit, many days of history, good controls |
| [Synthetic control](https://www.pythoncharts.com/causal-inference/synthetic-control-python/) | A pool of untreated units | You have many comparable units and want transparent weights |
| [Difference-in-differences](https://www.pythoncharts.com/causal-inference/difference-in-differences-python/) | Treated and untreated groups, parallel trends | Several treated units, short history |
| [Interrupted time series](https://www.pythoncharts.com/causal-inference/interrupted-time-series-python/) | Only the treated series | No controls at all; weakest of the four |

## Practical Tips

- Choose controls before looking at results, and check that the campaign cannot affect them (no spillover or shared marketing budget).
- Keep the pre-period long compared with the post-period. Forecast uncertainty grows with the horizon.
- Always run a placebo test, and consider several placebo dates. This setup's intervals were too narrow, and a placebo test is how you notice.
- Plot the pre-period fit. If the model cannot track the pre-period, its post-period forecast is not a counterfactual.
- Do not add controls just to improve the pre-fit. Too many correlated controls can overfit the pre-period.
- With statsmodels 0.14.6 and NumPy 2.5 you may see a `DeprecationWarning` about setting an array's shape. It comes from inside statsmodels and does not affect the results.
- All numbers come from one seeded simulation with a known effect. Real campaigns are messier.

## Similar Topics

- [Synthetic Control in Python](https://www.pythoncharts.com/causal-inference/synthetic-control-python/)
- [Interrupted Time Series in Python](https://www.pythoncharts.com/causal-inference/interrupted-time-series-python/)
- [Difference-in-Differences in Python](https://www.pythoncharts.com/causal-inference/difference-in-differences-python/)
- [Causal Inference in Python: A Guide](https://www.pythoncharts.com/causal-inference/causal-inference-python-guide/)
