# Geo-Lift Testing in Python with Synthetic Control

> A geo-lift test in Python using scipy nnls: compare test markets with a synthetic control, estimate incremental sales and iROAS, and plot placebo results and power curves.

Source: https://www.pythoncharts.com/causal-inference/geo-lift-test-python/ | Published: 2026-11-27 | Author: Alex Scott | Category: Causal Inference | Tags: causal inference, geo experiment, geo-lift, synthetic control, power analysis, campaign measurement, scipy

A geo-lift test measures advertising by running it in some regions and comparing
their sales with what the other regions suggest would have happened anyway. In
Python, you can build that comparison with `scipy.optimize.nnls()`: find
non-negative weights on the untouched markets that reproduce the test markets
before the campaign, then apply them during the campaign. This post uses SciPy
1.18, pandas 3.0 and Matplotlib 3.11.

## Quick Example

A retailer sells in 30 markets and runs extra video ads in five of them for the
last 8 of 112 weeks. The data is simulated with a true lift of 8%.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import nnls

rng = np.random.default_rng(181)

# Sample data: weekly sales ($ thousands) with shared trends and seasonality
weeks = pd.date_range("2024-07-01", periods=112, freq="W-MON")
t = np.arange(len(weeks))
factors = np.vstack([
    np.sin(2 * np.pi * t / 52), np.cos(2 * np.pi * t / 52),
    rng.normal(0, 1, len(t)).cumsum() * 0.15, rng.normal(0, 0.5, len(t)),
])
loadings = rng.uniform(0, 1, (30, 4)) * [0.12, 0.08, 0.06, 0.04]
size = rng.lognormal(np.log(100), 0.6, 30)
noise = rng.normal(0, 0.035, (30, len(t)))
values = size[:, None] * (1 + loadings @ factors + noise)
sales = pd.DataFrame(values.T, index=weeks,
                     columns=[f"M{i:02d}" for i in range(1, 31)])

test_markets = ["M03", "M08", "M14", "M21", "M27"]
start = 104                                        # first campaign week
sales.loc[weeks[start:], test_markets] *= 1.08     # the true 8% lift

treated = sales[test_markets].sum(axis=1)
donors = sales.drop(columns=test_markets)

def synthetic(first_test_week):
    """Fit weights on the weeks before the test and apply them to every week."""
    weights, _ = nnls(donors.iloc[:first_test_week].to_numpy(),
                      treated.iloc[:first_test_week].to_numpy())
    return donors @ weights

control = synthetic(start)
gap = treated - control
lift = gap.iloc[start:].sum() / control.iloc[start:].sum()

fig, ax = plt.subplots(figsize=(9, 4.5))
recent = slice(weeks[start - 40], None)
ax.plot(treated[recent], color="#d35400", lw=2, label="Test markets")
ax.plot(control[recent], color="#34495e", lw=2, ls="--",
        label="Synthetic control")
ax.axvspan(weeks[start], weeks[-1], color="#f6d5b8", alpha=0.5,
           label="Campaign")
ax.set_title(f"Estimated lift during the campaign: {lift:.1%}")
ax.set_ylabel("Weekly sales ($ thousands)")
ax.legend(loc="upper left")
fig.autofmt_xdate()
plt.show()
```

![Weekly sales of the test markets and their synthetic control, tracking closely until the shaded campaign weeks, where the test markets run above](https://www.pythoncharts.com/causal-inference/geo-lift-test-python/images/geo-lift-synthetic-control.png)

Before the campaign the two lines differ by about 1.5% in a typical week. During
it, the test markets run 9.9% above the synthetic control, against a true lift
of 8%.

## Why not compare before and after?

```python
before_after = treated.iloc[start:].mean() / treated.iloc[start - 8:start].mean() - 1
change = lambda s: s.iloc[start:].mean() / s.iloc[:start].mean()
did = change(treated) / change(donors.sum(axis=1)) - 1

print(f"before vs after:           {before_after:.1%}")
print(f"difference-in-differences: {did:.1%}")
print(f"synthetic control:         {lift:.1%}")
```

```text
before vs after:           20.5%
difference-in-differences: 10.6%
synthetic control:         9.9%
```

The before/after number credits the ads with a seasonal rise. A ratio-style
[difference-in-differences](https://www.pythoncharts.com/causal-inference/difference-in-differences-python/)
removes changes shared by all markets. Synthetic control goes further by
weighting the markets that have moved most like the test group.

## Incremental sales and iROAS

Incremental return on ad spend (iROAS) is the extra sales divided by the extra
spend. Suppose the campaign cost $150,000.

```python
spend = 150                                       # $ thousands
incremental = gap.iloc[start:].sum()
print(f"incremental sales: ${incremental:,.0f}k, iROAS: {incremental / spend:.1f}")

fig, ax = plt.subplots(figsize=(8, 4))
running = gap.iloc[start:].cumsum()
ax.bar(range(1, 9), running, color="#d35400")
ax.axhline(spend, color="#34495e", ls="--", label="Ad spend ($150k)")
ax.set_xlabel("Campaign week")
ax.set_ylabel("Cumulative extra sales ($ thousands)")
ax.legend()
plt.show()
```

```text
incremental sales: $530k, iROAS: 3.5
```

![Bar chart of cumulative incremental sales growing over eight campaign weeks and passing the dashed ad spend line](https://www.pythoncharts.com/causal-inference/geo-lift-test-python/images/geo-lift-cumulative.png)

The true lift in this simulation is worth about $437k, an iROAS of 2.9, so the
estimate is on the generous side. This is revenue. For a profit decision, multiply by your margin.

## Is the lift bigger than normal noise?

Run the same analysis on 8-week windows where nothing happened. Each placebo
fits on earlier weeks only, so it measures real forecasting error.

```python
def placebo_lifts(length, earliest=52):
    results = []
    for first in range(earliest, start - length + 1):
        fake = synthetic(first)
        window = slice(first, first + length)
        results.append(treated.iloc[window].sum() / fake.iloc[window].sum() - 1)
    return np.array(results)

placebos = placebo_lifts(8)
low_q, high_q = np.quantile(placebos, [0.025, 0.975])
low, high = (1 + lift) / (1 + high_q) - 1, (1 + lift) / (1 + low_q) - 1
print(f"{len(placebos)} placebo windows, largest absolute lift "
      f"{np.abs(placebos).max():.1%}")
print(f"approximate 95% range for the campaign lift: {low:.1%} to {high:.1%}")

fig, ax = plt.subplots(figsize=(8, 4))
ax.hist(placebos * 100, bins=15, color="#9aa7b4", edgecolor="white",
        label="Placebo windows")
ax.axvline(lift * 100, color="#d35400", lw=3, label="Campaign")
ax.set_xlabel("Estimated lift (%)")
ax.set_ylabel("Windows")
ax.legend()
plt.show()
```

```text
45 placebo windows, largest absolute lift 2.2%
approximate 95% range for the campaign lift: 7.8% to 11.9%
```

![Histogram of placebo lifts clustered within about two percent of zero, with the campaign estimate far to the right](https://www.pythoncharts.com/causal-inference/geo-lift-test-python/images/geo-lift-placebo.png)

The campaign is far outside anything the placebo windows produced. Overlapping
windows share weeks, so 45 windows carry much less information than 45
independent tests. Treat the range as approximate.

## How long should the test run, and how big a lift can it detect?

Run this *before* the campaign. Add a pretend lift to each placebo window and
count how often it clears the 95th percentile of the no-lift results.

```python
lifts = np.arange(0, 0.0601, 0.005)

fig, ax = plt.subplots(figsize=(8, 4.5))
for length, color in [(2, "#c0b3a5"), (4, "#8e7cc3"), (8, "#d35400")]:
    null = placebo_lifts(length)
    threshold = np.quantile(null, 0.95)
    power = [np.mean((1 + null) * (1 + x) - 1 > threshold) for x in lifts]
    ax.plot(lifts * 100, power, "o-", color=color, label=f"{length} weeks")
ax.axhline(0.8, color="#555555", ls=":", label="80% power")
ax.set_xlabel("True lift (%)")
ax.set_ylabel("Chance of detecting it")
ax.legend()
plt.show()
```

![Power curves for two, four and eight week tests, with longer tests detecting smaller lifts](https://www.pythoncharts.com/causal-inference/geo-lift-test-python/images/geo-lift-power.png)

With these markets, 80% power needs a true lift of about 4% for a 2-week test,
3.5% for 4 weeks and 3% for 8 weeks. If you expect the ads to add 1%, this
design is unlikely to show it, so spend more per market, add markets or don't
run the test. The threshold allows about a 5% false positive rate in a one-sided
test.

## Which markets should be in the test?

Choose markets whose combined sales the others can predict well. Score candidate
groups with placebo error, using only data from before the campaign:

```python
def placebo_error(markets, length=8):
    y = sales[markets].sum(axis=1).to_numpy()
    X = sales.drop(columns=markets).to_numpy()
    errors = []
    for first in range(52, start - length + 1, 4):
        w, _ = nnls(X[:first], y[:first])
        window = slice(first, first + length)
        errors.append(y[window].sum() / (X[window] @ w).sum() - 1)
    return np.sqrt(np.mean(np.square(errors)))

pick = np.random.default_rng(0)
candidates = [sorted(pick.choice(sales.columns, 5, replace=False).tolist())
              for _ in range(200)]
scores = np.array([placebo_error(c) for c in candidates])
best = candidates[scores.argmin()]
print(f"typical error: {np.median(scores):.2%}")
print(f"best group:    {scores.min():.2%} {best}")
print(f"worst group:   {scores.max():.2%}")
```

```text
typical error: 1.05%
best group:    0.38% ['M07', 'M14', 'M18', 'M24', 'M26']
worst group:   1.95%
```

The group with the lowest score may be partly lucky, so confirm it on weeks you
didn't use for choosing. In practice also rule out markets with local promotions
or ads that spill across borders. Randomly assigning markets among those that
qualify protects against picking places that were about to grow.

## Geo-lift or another design?

| Situation | Design |
|---|---|
| You can randomize individual users | [A/B test](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/) |
| Ads can only be targeted by region, a few test markets | Geo-lift with synthetic control |
| Many regions you can randomize | [Cluster-randomized experiment](https://www.pythoncharts.com/ab-testing/switchback-cluster-randomized-experiments-python/) |
| One region, one past launch | [Synthetic control](https://www.pythoncharts.com/causal-inference/synthetic-control-python/) or [CausalImpact](https://www.pythoncharts.com/causal-inference/causalimpact-python/) |
| All regions, all channels at once, no experiment | [Marketing mix modeling](https://www.pythoncharts.com/causal-inference/marketing-mix-model-python/) |

## Practical tips

- Fix the markets, dates, metric and analysis before the campaign starts.
- Keep a year or more of weekly history, so the fit sees a full season.
- Weights fitted by `nnls` don't have to sum to 1, which lets small donors match a large test group. Classic synthetic control adds that constraint.
- With many donors and few weeks, a perfect pre-period fit is a sign of overfitting. Trust the placebo error, not the fit.
- Watch the weeks after the campaign too. Sales pulled forward show up as a dip.

## Similar Topics

- [Synthetic Control in Python](https://www.pythoncharts.com/causal-inference/synthetic-control-python/)
- [CausalImpact in Python](https://www.pythoncharts.com/causal-inference/causalimpact-python/)
- [Switchback and Cluster-Randomized Experiments](https://www.pythoncharts.com/ab-testing/switchback-cluster-randomized-experiments-python/)
