# CUPED in Python: Reduce A/B Test Variance with a Pre-Experiment Covariate

> How to implement CUPED (Controlled-experiment Using Pre-Experiment Data) in Python. Compute theta, adjust the metric, compare confidence intervals before and after, verify with statsmodels OLS, and see how correlation sets the variance reduction.

Source: https://www.pythoncharts.com/ab-testing/cuped-variance-reduction-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: A/B Testing | Tags: ab testing, experimentation, cuped, variance reduction, statsmodels, confidence interval, regression adjustment

CUPED (Controlled-experiment Using Pre-Experiment Data) shrinks the noise in an A/B test by subtracting the part of each user's metric that their pre-experiment behavior already predicts. In Python it's three lines: `theta = np.cov(y, x)[0, 1] / np.var(x, ddof=1)`, then `y_cuped = y - theta * (x - x.mean())`, then run your usual t-test on `y_cuped`. The estimate of the treatment effect stays the same on average, but its confidence interval gets narrower, so you reach a decision with fewer users or less time.

## Quick Example

The data is simulated: weekly minutes watched for 8,000 users, split evenly into control and treatment, with a true treatment effect of +3 minutes. `pre` is each user's viewing in the four weeks before the test and `post` is viewing during it.

```python
import numpy as np
import pandas as pd
from scipy import stats

rng = np.random.default_rng(5)
n = 4000
user_level = rng.gamma(4, 30, 2 * n)                        # stable viewing habit
pre = (user_level + rng.normal(0, 25, 2 * n)).clip(0)        # before the test
group = np.repeat([0, 1], n)                                 # 0 = control, 1 = treatment
post = (user_level + rng.normal(0, 25, 2 * n) + 3.0 * group).clip(0)  # during: +3 min effect
df = pd.DataFrame({"group": group, "pre": pre, "post": post})

# CUPED: remove the part of `post` that `pre` predicts
theta = np.cov(df["post"], df["pre"])[0, 1] / df["pre"].var()
df["post_cuped"] = df["post"] - theta * (df["pre"] - df["pre"].mean())

for col in ["post", "post_cuped"]:
    a, b = df.loc[df["group"] == 1, col], df.loc[df["group"] == 0, col]
    res = stats.ttest_ind(a, b, equal_var=False)
    ci = res.confidence_interval(0.95)
    print(f"{col:11s} lift = {a.mean() - b.mean():+.2f}  "
          f"CI [{ci.low:.2f}, {ci.high:.2f}]  p = {res.pvalue:.2g}")
```

```text
post        lift = +1.16  CI [-1.67, 3.98]  p = 0.42
post_cuped  lift = +3.47  CI [2.02, 4.92]  p = 2.7e-06
```

On this run the raw comparison is inconclusive (the interval runs from -1.67 to +3.98 minutes), while the CUPED-adjusted one clearly detects a positive effect. The CUPED interval is 2.9 minutes wide against 5.7, about half the width. The raw estimate of +1.16 landed below the true +3 purely by chance. That's the problem CUPED addresses: users differ a lot in baseline viewing, and that variation buries the treatment effect.

![Two dot and whisker confidence intervals for the estimated lift in minutes: the raw interval is wide and crosses zero, the CUPED interval is about half as wide and sits entirely above zero](https://www.pythoncharts.com/ab-testing/cuped-variance-reduction-python/images/cuped-ci-comparison.png)

## Why CUPED Works

Most of the variation in `post` has nothing to do with the treatment. Heavy viewers watch a lot in any week, and light viewers watch little. In this data the pre-period and test-period minutes have a correlation of r = 0.86:

![Scatter plot of minutes watched before the test versus minutes watched during it, showing a tight upward linear relationship with a fitted line of slope 0.85](https://www.pythoncharts.com/ab-testing/cuped-variance-reduction-python/images/cuped-pre-post-scatter.png)

The fitted line's slope is `theta` (0.85). CUPED subtracts `theta * (pre - mean(pre))` from each user's `post`. Because `pre` was measured before the experiment, it can't be affected by treatment, so the adjustment doesn't bias the comparison between arms. It only removes baseline differences between users. Centering `pre` at its mean keeps the adjusted metric on the original scale.

How much variance you remove depends on the correlation: the adjusted variance is `(1 - r²)` times the original.

![Line chart of the share of variance remaining after CUPED against the correlation between covariate and metric, falling from 100 percent at r of 0 toward 0 at r of 1, with this test marked at r of 0.86 and 26 percent remaining](https://www.pythoncharts.com/ab-testing/cuped-variance-reduction-python/images/cuped-variance-vs-correlation.png)

At r = 0.86, 26% of the variance remains, and the code confirms it: `df["post_cuped"].var() / df["post"].var()` is 0.263. Confidence interval width scales with the standard deviation, so the width drops to `sqrt(0.263)`, or 51% of the original. The picture for weaker covariates is much less dramatic. At r = 0.3 you keep 91% of the variance, and at r = 0.5, 75%.

## Does CUPED Give the Same Answer as Regression?

Yes, nearly. CUPED is equivalent to regressing the metric on the treatment flag plus the pre-experiment covariate (ANCOVA). With statsmodels:

```python
import statsmodels.formula.api as smf

ols = smf.ols("post ~ group + pre", df).fit()
ols.params["group"], ols.conf_int().loc["group"].tolist()
# (3.474, [2.025, 4.923])
```

The coefficient on `group` is 3.474 against CUPED's 3.473, with an interval of [2.03, 4.92] against [2.02, 4.92]. The regression is handy when you want to add several covariates at once, such as pre-period spend and tenure, or when you want robust standard errors with `.fit(cov_type="HC3")`. CUPED's single-covariate form is easy to explain and to run in a data warehouse or a dashboard.

## How Often Does CUPED Detect a Real Effect?

One simulation can flatter either method, so this repeats the experiment 500 times with the same +3 minute effect, a fresh sample each time, and counts how often each analysis reaches p < 0.05:

| Analysis | Share of runs that detect the effect |
|---|---|
| Raw metric | 52.6% |
| CUPED-adjusted | 98.4% |

CUPED turns a coin-flip test into a reliable one on identical data. The practical use is the other direction too: for a fixed power target you need fewer users, roughly `(1 - r²)` times as many.

## Rules for Choosing the Covariate

- **Measure it before the experiment starts.** Anything collected after assignment can be influenced by the treatment, and adjusting for it biases the estimate.
- **Use the same metric from a prior period when you can.** Pre-period minutes predict test-period minutes better than almost anything else. A different but correlated metric (such as pre-period sessions) works, with a lower r.
- **Fit theta on both arms pooled.** That's what the example does. Estimating it separately per arm adds noise and complexity.
- **Handle users with no history.** New users have no pre-period data. Fill with the mean (their adjustment is then zero) or fit CUPED only where the covariate exists, and say so when reporting.
- **Don't expect miracles for new products.** With r near zero there's nothing to remove, and CUPED returns about the same interval as the raw test.

## When to Use CUPED

| Situation | Use CUPED? |
|---|---|
| Metric is stable per user (time spent, spend, sessions) | Yes, r is usually 0.5 to 0.9 |
| Binary conversion where most users are new | Little gain, r is small |
| Long-running test, covariate from the same period | No, the covariate must predate assignment |
| Several useful pre-period features | Use the regression form with several covariates |

## Similar Topics

- [CUPAC in Python: Use a Machine Learning Model to Reduce A/B Test Variance](https://www.pythoncharts.com/ab-testing/cupac-ml-variance-reduction-python/)- [A/B Test Analysis in Python: Conversion Rate and Revenue](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/)
- [Confidence Interval Bands in Seaborn](https://www.pythoncharts.com/seaborn/seaborn-confidence-interval-bands/)
- [Matplotlib Scatter Plots](https://www.pythoncharts.com/matplotlib/matplotlib-scatterplot/)
- [Ratio Metrics in A/B Tests: The Delta Method in Python](https://www.pythoncharts.com/ab-testing/ratio-metrics-delta-method-python/)
- [A/B Testing in Python: A Guide from Sample Size to Sequential Tests](https://www.pythoncharts.com/ab-testing/ab-testing-python-guide/)
