Most A/B testing statistics guides hand you a formula and a calculator link. The formula is usually fine. What breaks experiments is everything around it: checking the dashboard every morning, reading ten metrics at once, a logging bug that quietly drops users from one arm, and a metric so noisy that the test needs twice the traffic you have.
This post rebuilds the statistics of AB testing in Python and then attacks each piece with simulation. Every claim gets a few thousand synthetic experiments where we know the truth, so you can see the real false positive rate instead of trusting the nominal one.
What we will build and check:
- A sample size calculator for conversion rates, compared with statsmodels and with simulated power.
- A two-proportion z-test with a confidence interval, matched against statsmodels.
- The peeking problem: 5,000 A/A tests checked daily, and two fixes (alpha spending and an always-valid mSPRT).
- Multiple metrics: Bonferroni vs Holm.
- A sample ratio mismatch (SRM) check that catches a bug which manufactured a “significant” lift.
- CUPED variance reduction on synthetic revenue data.
Versions: Python 3.13, numpy 2.5.4, scipy 1.18.1, statsmodels 0.15.0, pytest 9.2.0. Every script uses a fixed seed, and every output block below is pasted from a real run.
What is A/B testing, in statistical terms?
An A/B test is a randomized controlled experiment: users are randomly split between a control (A) and a variant (B), and you compare a metric between the groups. Randomization is what lets you read the difference as an effect of the change, not of who happened to see it. Statistics then answers one narrow question: how surprised should we be by the observed difference if the change did nothing?
That question has a fixed error budget. With a 5% significance level, a test that runs exactly as planned will call a winner in about 5% of experiments where nothing changed. Every shortcut below spends more of that budget without telling you. The table maps each step to the mistake it guards against.

Flow of an A/B test from design to decision: power analysis and MDE before launch, a fixed horizon or sequential boundary while running, then SRM check, z-test, multiple-testing correction and CUPED at readout, with what each step protects against
Project setup
code/
abstats.py # helpers: sample size, z-test, mSPRT, SRM, CUPED
01_sample_size.py ... 06_cuped.py
tests/test_abstats.py
requirements.txt
run_all.sh # runs every script, saves out_*.txt, runs pytest
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
./run_all.sh
All helpers live in one small module. It is short enough to read in one go:
Spoiler on dev.to: abstats.py (full file)
"""Small, dependency-light helpers for A/B testing statistics."""
import numpy as np
from scipy import stats
def sample_size_two_proportions(p1, p2, alpha=0.05, power=0.80):
"""Users per arm for a two-sided two-proportion z-test (classic formula)."""
z_a = stats.norm.ppf(1 - alpha / 2)
z_b = stats.norm.ppf(power)
p_bar = (p1 + p2) / 2
num = (z_a * np.sqrt(2 * p_bar * (1 - p_bar))
+ z_b * np.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2
return int(np.ceil(num / (p2 - p1) ** 2))
def two_proportion_ztest(conv_a, n_a, conv_b, n_b):
"""Pooled z-test for B vs A. Returns (z, two-sided p, diff, 95% CI)."""
p_a, p_b = conv_a / n_a, conv_b / n_b
p_pool = (conv_a + conv_b) / (n_a + n_b)
se_pool = np.sqrt(p_pool * (1 - p_pool) * (1 / n_a + 1 / n_b))
z = (p_b - p_a) / se_pool
p_value = 2 * stats.norm.sf(np.abs(z))
# CI uses the unpooled standard error (no null assumed)
se = np.sqrt(p_a * (1 - p_a) / n_a + p_b * (1 - p_b) / n_b)
diff = p_b - p_a
ci = (diff - 1.96 * se, diff + 1.96 * se)
return z, p_value, diff, ci
def msprt_lambda(diff, var, tau2):
"""Mixture likelihood ratio with a N(0, tau^2) mixing prior on the effect.
diff: observed difference in means, var: its variance (V_n).
Closed form of the Gaussian integral in Johari et al. (eq. 10).
"""
return np.sqrt(var / (var + tau2)) * np.exp(
tau2 * diff ** 2 / (2 * var * (var + tau2)))
def srm_check(n_a, n_b, expected_ratio=0.5):
"""Chi-square goodness-of-fit test for sample ratio mismatch."""
total = n_a + n_b
expected = [total * expected_ratio, total * (1 - expected_ratio)]
return stats.chisquare([n_a, n_b], f_exp=expected)
def cuped_adjust(y, x):
"""Return CUPED-adjusted metric y - theta * (x - mean(x)) and theta."""
theta = np.cov(y, x, ddof=1)[0, 1] / np.var(x, ddof=1)
return y - theta * (x - x.mean()), theta
Step 1. A/B testing sample size calculator: power and MDE
A sample size calculation needs four inputs: the baseline conversion rate, the minimum detectable effect (MDE), the significance level alpha and the power (the chance of detecting the effect if it is really there). Here the baseline is 5%, and we want to detect a +10% relative lift, so 5.0% to 5.5%, with alpha = 0.05 two-sided and 80% power.
The classic formula for two proportions combines the null-hypothesis variance (pooled rate) with the alternative-hypothesis variance:
n = ( z(1-alpha/2) * sqrt(2 * p_bar * (1 - p_bar))
+ z(power) * sqrt(p1 * (1 - p1) + p2 * (1 - p2)) )^2 / (p2 - p1)^2
statsmodels takes another route. proportion_effectsize converts the two rates into an arcsine-transformed effect size, 2 * (arcsin(sqrt(p1)) - arcsin(sqrt(p2))) (often called Cohen’s h), and NormalIndPower.solve_power solves for nobs1, the size of the first sample. Two different approximations should land close together. Then we check the answer the only way that does not rely on either approximation: simulate 4,000 experiments with a true 10% lift at that sample size and count how many reach p < 0.05.
"""Sample size for an A/B test: formula vs statsmodels vs simulation."""
import numpy as np
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
from abstats import sample_size_two_proportions, two_proportion_ztest
BASELINE = 0.05 # 5% conversion rate today
MDE_REL = 0.10 # smallest lift worth detecting: +10% relative
TARGET = BASELINE * (1 + MDE_REL) # 5.5%
n_formula = sample_size_two_proportions(BASELINE, TARGET)
h = proportion_effectsize(TARGET, BASELINE) # Cohen's h (arcsine)
n_sm = NormalIndPower().solve_power(effect_size=h, alpha=0.05,
power=0.80, ratio=1.0,
alternative="two-sided")
print(f"baseline={BASELINE:.1%} target={TARGET:.2%} MDE=+{MDE_REL:.0%} relative")
print(f"classic formula : {n_formula:,} users per arm")
print(f"statsmodels (h={h:.4f}): {int(np.ceil(n_sm)):,} users per arm")
# Does the formula deliver 80% power? Simulate 4,000 experiments.
rng = np.random.default_rng(42)
SIMS = 4_000
n = n_formula
conv_a = rng.binomial(n, BASELINE, SIMS)
conv_b = rng.binomial(n, TARGET, SIMS)
_, pvals, _, _ = two_proportion_ztest(conv_a, n, conv_b, n) # vectorized
print(f"simulated power at n={n:,}: {np.mean(pvals < 0.05):.1%} "
f"({SIMS:,} simulated experiments)")
# How the MDE drives the bill
print("\nrelative MDE -> users per arm")
for mde in (0.02, 0.05, 0.10, 0.20):
n_mde = sample_size_two_proportions(BASELINE, BASELINE * (1 + mde))
print(f" +{mde:.0%}".ljust(8) + f"{n_mde:>10,}")
baseline=5.0% target=5.50% MDE=+10% relative
classic formula : 31,234 users per arm
statsmodels (h=0.0224): 31,218 users per arm
simulated power at n=31,234: 80.0% (4,000 simulated experiments)
relative MDE -> users per arm
+2% 752,703
+5% 122,124
+10% 31,234
+20% 8,158
The two methods differ by 16 users out of 31 thousand, and the simulated power comes out at 80.0%. So the formula does what it says.
The more useful part is the bottom table. Required traffic grows with the inverse square of the effect: halving the MDE from 10% to 5% roughly quadruples the sample (31,234 to 122,124 per arm), and a 2% lift needs about 750 thousand users per arm. Choosing an MDE is a business decision (“what is the smallest lift worth shipping?”). If your traffic cannot reach it in reasonable time, test a bolder change or reduce variance (see CUPED below).
Step 2. Read the result with a two-proportion z-test
The test runs to the planned 31,234 users per arm. We simulate one outcome where the true rates are 5.0% and 5.5%, then compute a pooled z-statistic, a two-sided p-value and a 95% confidence interval for the difference. The interval uses the unpooled standard error, because it does not assume the null is true.
"""Read one finished A/B test with a two-proportion z-test."""
import numpy as np
from statsmodels.stats.proportion import (confint_proportions_2indep,
proportions_ztest)
from abstats import two_proportion_ztest
rng = np.random.default_rng(7)
N = 31_234 # per arm, from 01_sample_size.py
conv_a = int(rng.binomial(N, 0.050)) # control, true rate 5.0%
conv_b = int(rng.binomial(N, 0.055)) # variant, true rate 5.5%
z, p, diff, ci = two_proportion_ztest(conv_a, N, conv_b, N)
print(f"A: {conv_a}/{N} = {conv_a / N:.3%} B: {conv_b}/{N} = {conv_b / N:.3%}")
print(f"hand-rolled : z={z:.3f} p={p:.4f} diff={diff * 100:+.3f} pp "
f"95% CI [{ci[0] * 100:+.3f}, {ci[1] * 100:+.3f}] pp")
z_sm, p_sm = proportions_ztest([conv_b, conv_a], [N, N])
lo, hi = confint_proportions_2indep(conv_b, N, conv_a, N, method="wald")
print(f"statsmodels : z={z_sm:.3f} p={p_sm:.4f} "
f"95% CI [{lo * 100:+.3f}, {hi * 100:+.3f}] pp")
print(f"relative lift: {diff / (conv_a / N):+.1%}")
A: 1557/31234 = 4.985% B: 1678/31234 = 5.372%
hand-rolled : z=2.185 p=0.0289 diff=+0.387 pp 95% CI [+0.040, +0.735] pp
statsmodels : z=2.185 p=0.0289 95% CI [+0.040, +0.735] pp
relative lift: +7.8%
Our hand-rolled function matches proportions_ztest and confint_proportions_2indep(method="wald") to the printed precision, and a unit test pins that.
Two things in this output deserve attention. First, the observed lift is +7.8%, while the true lift we simulated is +10%. That is ordinary sampling noise, and the interval reflects it: anything from about +0.04 to +0.74 percentage points is consistent with the data. Report the interval, not only the point estimate. Second, with 80% power, one in five experiments with this exact true effect would miss it, so a non-significant result is not proof of no effect.
Step 3. The peeking problem, simulated
The p-value from Step 2 is valid for one look at a sample size fixed in advance. Real teams open the dashboard daily and stop when it turns green. To see what that does, simulate 5,000 A/A tests: both arms convert at exactly 5%, 1,200 users per arm per day, for 28 days. Any “winner” is a false positive by construction.
"""The peeking problem: A/A tests checked every day, and two fixes."""
import numpy as np
from scipy import stats
from abstats import msprt_lambda, two_proportion_ztest
rng = np.random.default_rng(2024)
SIMS, DAYS, PER_DAY, P0, ALPHA = 5_000, 28, 1_200, 0.05, 0.05
def run(p_b):
"""Cumulative daily (conv_a, conv_b, n) for SIMS experiments."""
daily_a = rng.binomial(PER_DAY, P0, (SIMS, DAYS))
daily_b = rng.binomial(PER_DAY, p_b, (SIMS, DAYS))
n = PER_DAY * np.arange(1, DAYS + 1)
return daily_a.cumsum(axis=1), daily_b.cumsum(axis=1), n
def first_hit(mask):
"""Day index (1-based) of first True per row, or 0 if never."""
hit = mask.any(axis=1)
return np.where(hit, mask.argmax(axis=1) + 1, 0)
# ---- 1. A/A test: both arms convert at 5%. Any "win" is a false positive.
ca, cb, n = run(P0)
_, p, _, _ = two_proportion_ztest(ca, n, cb, n)
print(f"A/A tests: {SIMS:,} experiments, {DAYS} days, {PER_DAY:,} users/arm/day")
print("look every N days, stop at the first p < 0.05:")
for every in (28, 14, 7, 4, 2, 1):
looks = p[:, every - 1::every]
print(f" every {every:>2} days ({looks.shape[1]:>2} looks): false positive rate "
f"{np.mean((looks < ALPHA).any(axis=1)):.1%}")
A/A tests: 5,000 experiments, 28 days, 1,200 users/arm/day
look every N days, stop at the first p < 0.05:
every 28 days ( 1 looks): false positive rate 5.1%
every 14 days ( 2 looks): false positive rate 8.4%
every 7 days ( 4 looks): false positive rate 12.7%
every 4 days ( 7 looks): false positive rate 16.0%
every 2 days (14 looks): false positive rate 21.4%
every 1 days (28 looks): false positive rate 26.3%
One look at day 28 gives 5.1%, as advertised. Looking weekly and stopping at the first p < 0.05 gives 12.7%. Looking daily gives 26.3%, more than five times the nominal rate, from a procedure that “only” checks a dashboard once a day. The test statistic wanders over time, and every look is another chance for it to cross the line. Johari, Pekelis and Walsh show that with unlimited continuous monitoring the type I error of this procedure can reach 100%. Evan Miller’s well-known essay makes the same point with a small example: checking a do-nothing change after every visitor, up to 150 observations, produces a false positive rate of 26.1%.

Line chart of the false positive rate in 5,000 simulated A/A tests against the number of interim looks: 5.1% with one look, 8.4% with 2, 12.7% with 4, 16.0% with 7, 21.4% with 14 and 26.3% with 28 daily looks, compared with the 5% nominal level
Step 4. Fixing peeking: fixed horizon, alpha spending, mSPRT
There are three honest options.
Fixed horizon. Compute the sample size, run to it, look once. It is the simplest and the most powerful for a given sample size. You can still watch guardrail metrics for outages, as long as nobody stops the test for a good-looking primary metric.
Group sequential design with alpha spending. Plan a small number of interim looks and split the 5% error budget across them. Lan and DeMets (1983) defined spending functions that say how much alpha may be used up by information fraction t. The O’Brien-Fleming-type function 2 - 2 * Phi(z(1-alpha/2) / sqrt(t)) spends almost nothing early and most of the budget at the end. We compute the four weekly boundaries by Monte Carlo on the joint distribution of the cumulative z-statistics.
Always-valid inference (mSPRT). If you want to look after every user, use a test built for it. The mixture sequential probability ratio test from Johari et al. compares the likelihood of the data under “effect drawn from a prior N(0, tau^2)” against “no effect”. For a difference of means with variance V, their Gaussian approximation has a closed form, sqrt(V / (V + tau^2)) * exp(tau^2 * d^2 / (2 * V * (V + tau^2))), which is msprt_lambda() in abstats.py. Under the null this ratio is a martingale, so it reaches 1 / alpha with probability at most alpha no matter how often you check. The always-valid p-value is the running minimum of 1 / Lambda.
# ---- 2. Fix A: mSPRT (always-valid p-values, Johari et al.)
TAU2 = (0.005) ** 2 # prior scale on the effect: our 0.5 pp MDE
def msprt_reject(ca, cb, n):
pa, pb = ca / n, cb / n
var = pa * (1 - pa) / n + pb * (1 - pb) / n # plug-in V_n
lam = msprt_lambda(pb - pa, var, TAU2)
p_always = np.minimum.accumulate(np.minimum(1.0, 1 / lam), axis=1)
return p_always < ALPHA
print(f"mSPRT, checked daily : false positive rate "
f"{np.mean(msprt_reject(ca, cb, n).any(axis=1)):.1%}")
# ---- 3. Fix B: O'Brien-Fleming-type alpha spending, 4 weekly looks
t = np.array([0.25, 0.5, 0.75, 1.0]) # information fractions
spend = 2 - 2 * stats.norm.cdf(stats.norm.ppf(1 - ALPHA / 2) / np.sqrt(t))
# Boundaries by Monte Carlo on the canonical joint distribution of Z_k
paths = rng.standard_normal((1_000_000, 4)).cumsum(axis=1) / np.sqrt(
np.arange(1, 5))
alive = np.ones(len(paths), bool)
bounds = []
for k in range(4):
target = spend[k] - (spend[k - 1] if k else 0.0) # alpha to spend now
z = np.abs(paths[alive, k])
c = np.quantile(z, 1 - target * len(paths) / alive.sum())
bounds.append(c)
alive[alive] = z < c
bounds = np.array(bounds)
print("OBF spending boundaries |z| >= " + ", ".join(f"{b:.2f}" for b in bounds))
zw, _, _, _ = two_proportion_ztest(ca[:, 6::7], n[6::7], cb[:, 6::7], n[6::7])
print(f"alpha spending, 4 looks : false positive rate "
f"{np.mean((np.abs(zw) >= bounds).any(axis=1)):.1%}")
# ---- 4. Same designs when B really is +10% better (5.0% -> 5.5%)
ca, cb, n = run(P0 * 1.10)
z, p, _, _ = two_proportion_ztest(ca, n, cb, n)
fixed = p[:, -1] < ALPHA
ms = first_hit(msprt_reject(ca, cb, n))
zw = z[:, 6::7]
obf = first_hit(np.abs(zw) >= bounds) * 7
print(f"\nA/B tests with a real +10% lift ({SIMS:,} experiments)")
print(f"fixed horizon, day {DAYS} : power {fixed.mean():.1%}")
print(f"mSPRT daily : power {(ms > 0).mean():.1%}, "
f"median stop day {np.median(ms[ms > 0]):.0f}")
print(f"alpha spending weekly : power {(obf > 0).mean():.1%}, "
f"median stop day {np.median(obf[obf > 0]):.0f}")
mSPRT, checked daily : false positive rate 1.3%
OBF spending boundaries |z| >= 3.92, 2.78, 2.30, 2.05
alpha spending, 4 looks : false positive rate 5.2%
A/B tests with a real +10% lift (5,000 experiments)
fixed horizon, day 28 : power 82.2%
mSPRT daily : power 52.6%, median stop day 17
alpha spending weekly : power 81.4%, median stop day 21

Comparison cards for three designs run on the same simulated traffic: fixed horizon with 5.1% false positives and 82.2% power at day 28, O’Brien-Fleming alpha spending with 4 weekly looks at 5.2% and 81.4% power with median stop on day 21, and mSPRT checked daily at 1.3% and 52.6% power with median stop on day 17
Both fixes bring the false positive rate back to 5% or below. The trade-offs are what matter:
Alpha spending keeps almost all of the fixed-horizon power (81.4% vs 82.2%) and stops a typical winning test on day 21 instead of 28. The first boundary is |z| >= 3.92, so only a huge effect can stop the test in week one. The cost is planning: the look schedule is part of the design.
mSPRT lets you look every day with no schedule at all, but within the same 28 days it detects the real lift in only 52.6% of experiments, and it is conservative under the null (1.3%). The median detection happens on day 17. You pay for unlimited flexibility with power at any fixed sample size. The choice of tau matters: I swept it over 0.0025, 0.005, 0.01 and 0.02, and the MDE-sized value of 0.005 (0.5 pp) gave the best power of the four.
If your team will look anyway, make one of these the dashboard default. “Please do not peek” does not survive a launch week.
Step 5. Multiple metrics: Bonferroni vs Holm
A typical experiment reports conversion, revenue, clicks, retention and a couple of engagement metrics. Each one gets its own 5% chance of a false win. With five independent metrics that is 1 - 0.95^5, about 22.6%; correlated metrics are a bit lower. The simulation draws z-statistics for five metrics with pairwise correlation 0.3 directly from their multivariate normal distribution, which is equivalent to simulating 20,000 users per arm and much faster.
"""Five metrics per experiment: family-wise error with and without correction."""
import numpy as np
from scipy import stats
from statsmodels.stats.multitest import multipletests
rng = np.random.default_rng(11)
SIMS, N, K = 20_000, 20_000, 5 # experiments, users per arm, metrics
# Metrics are moderately correlated (rho=0.3), as clicks/carts/orders usually are
cov = 0.3 * np.ones((K, K)) + 0.7 * np.eye(K)
def pvalues(effect_sd):
"""Two-sided z-test p-values for K metrics in SIMS experiments.
With N users per arm, the vector of z-statistics is multivariate normal
with mean effect * sqrt(N/2) and the metrics' correlation matrix, so we
sample it directly instead of simulating 40,000 users per experiment.
"""
z = rng.multivariate_normal(effect_sd * np.sqrt(N / 2), cov, size=SIMS)
return 2 * stats.norm.sf(np.abs(z))
def reject(p, method, alpha=0.05):
"""Vectorized over rows; matches statsmodels.multipletests (see test)."""
k = p.shape[1]
if method == "none":
return p < alpha
if method == "bonferroni":
return p < alpha / k
# Holm: sort p-values, compare the i-th smallest with alpha / (k - i),
# stop at the first failure
order = np.argsort(p, axis=1)
p_sorted = np.take_along_axis(p, order, axis=1)
passed = np.cumprod(p_sorted <= alpha / (k - np.arange(k)), axis=1).astype(bool)
rej = np.empty_like(passed)
np.put_along_axis(rej, order, passed, axis=1)
return rej
p_null = pvalues(np.zeros(K))
for row in p_null[:200]: # sanity check vs statsmodels
assert (reject(row[None], "holm")[0] == multipletests(row, 0.05, "holm")[0]).all()
print(f"{SIMS:,} experiments x {K} metrics, no real effect anywhere")
for m in ("none", "bonferroni", "holm"):
print(f" {m:<10} P(at least one false win) = "
f"{reject(p_null, m).any(axis=1).mean():.1%}")
eff = np.array([0.03, 0.03, 0, 0, 0]) # two metrics move 0.03 SD
p_alt = pvalues(eff)
print("\n2 of 5 metrics truly move by 0.03 SD")
for m in ("none", "bonferroni", "holm"):
rej = reject(p_alt, m)
print(f" {m:<10} power per real metric = {rej[:, :2].mean():.1%} "
f"P(false win on a null metric) = {rej[:, 2:].any(axis=1).mean():.1%}")
20,000 experiments x 5 metrics, no real effect anywhere
none P(at least one false win) = 21.2%
bonferroni P(at least one false win) = 4.6%
holm P(at least one false win) = 4.6%
2 of 5 metrics truly move by 0.03 SD
none power per real metric = 84.9% P(false win on a null metric) = 13.4%
bonferroni power per real metric = 66.5% P(false win on a null metric) = 2.8%
holm power per real metric = 68.4% P(false win on a null metric) = 3.9%
Uncorrected, 21.2% of experiments where nothing changed report at least one winning metric. Bonferroni (test each metric at 0.05 / 5) and Holm both bring this to 4.6%.
Holm is the step-down version: sort the p-values, compare the smallest with alpha/5, the next with alpha/4 and so on, and stop at the first failure. When every null is true, it rejects something exactly when Bonferroni does, so the two family-wise rates match. Once some metrics really move, Holm rejects at least as much as Bonferroni and is uniformly more powerful: 68.4% vs 66.5% per real metric here, while keeping false wins on the null metrics under 5%. Both control the family-wise error rate without assumptions about dependence, so Holm is the default to reach for. A cleaner alternative is to name one primary metric before launch and treat the rest as guardrails or exploration.
Step 6. Sample ratio mismatch check
Before you read any metric, check that the arms got the share of users you configured. A sample ratio mismatch (SRM) means something between assignment and logging treats the arms differently, and the comparison is no longer randomized. Fabijan et al. report that about 6% of experiments at Microsoft showed an SRM.
The simulation assigns 200,000 users 50/50 with no real treatment effect. Then it adds a realistic bug: the variant page fails on some slow devices, those users never send an exposure event, and they happen to have lower purchase intent.
"""Sample ratio mismatch: a buggy variant that loses some users fakes a win."""
import numpy as np
from abstats import srm_check, two_proportion_ztest
rng = np.random.default_rng(5)
USERS = 200_000
arm = rng.integers(0, 2, USERS) # 50/50 assignment
intent = rng.random(USERS) # hidden purchase intent
converted = rng.random(USERS) < 0.10 * intent # ~5% overall, no real effect
# Bug: the variant's new page crashes on slow devices, and those users
# (who also have lower intent) never fire the exposure event.
slow = (intent < 0.3) & (rng.random(USERS) < 0.25)
logged = ~((arm == 1) & slow)
n_a, n_b = int(((arm == 0) & logged).sum()), int(((arm == 1) & logged).sum())
c_a = int(converted[(arm == 0) & logged].sum())
c_b = int(converted[(arm == 1) & logged].sum())
_, p, diff, _ = two_proportion_ztest(c_a, n_a, c_b, n_b)
print(f"logged users A={n_a:,} B={n_b:,} ({n_b / (n_a + n_b):.2%} in B)")
print(f"conversion A={c_a / n_a:.3%} B={c_b / n_b:.3%} "
f"relative lift {diff / (c_a / n_a):+.1%} p={p:.4f}")
chi2, p_srm = srm_check(n_a, n_b)
print(f"SRM check chi2={chi2:.2f} p={p_srm:.2e} "
f"-> {'STOP: sample ratio mismatch' if p_srm < 0.0005 else 'ok'}")
# Healthy assignment for comparison: same users, nothing dropped
h_a, h_b = int((arm == 0).sum()), int((arm == 1).sum())
chi2, p_ok = srm_check(h_a, h_b)
print(f"no bug A={h_a:,} B={h_b:,} chi2={chi2:.2f} p={p_ok:.3f}")
logged users A=100,083 B=92,443 (48.02% in B)
conversion A=4.922% B=5.292% relative lift +7.5% p=0.0002
SRM check chi2=303.18 p=6.69e-68 -> STOP: sample ratio mismatch
no bug A=100,083 B=99,917 chi2=0.14 p=0.710
The bug produces a +7.5% lift with p = 0.0002, entirely from who got counted. The split is 48.02% instead of 50%, small enough to slip past someone eyeballing a dashboard, yet the chi-square test gives p = 6.7e-68. With 100 thousand users per arm, a two-point imbalance is not noise.
scipy.stats.chisquare runs Pearson’s goodness-of-fit test. Pass expected counts in f_exp that sum to the observed total, otherwise the default sum_check raises. Microsoft’s experimentation team uses a conservative threshold of p < 0.0005 to flag SRM, which is why the script uses it. When SRM fires, do not “adjust” the result. Find the cause (redirects, bot filtering, crashes, late triggers) and rerun.
Step 7. CUPED: same power with fewer users
Revenue per user is noisy, so revenue tests need a lot of traffic. CUPED (Deng, Xu, Kohavi and Walker, WSDM 2013) uses data from before the experiment to remove predictable variance. For each user, take the metric Y during the test and a covariate X, usually the same metric in a pre-period, and compute:
Y_cuped = Y - theta * (X - mean(X)), theta = cov(Y, X) / var(X)
The mean does not change, and the variance shrinks by a factor of rho^2, where rho is the correlation between X and Y. The covariate must not be affected by the treatment; pre-experiment data satisfies this by construction. Use one theta for both arms, estimated on the pooled data.
The synthetic data gives each user a gamma-distributed spend rate, and draws revenue for four weeks before the test and during it. The variant has a true +3% revenue lift.
"""CUPED: use pre-experiment revenue to shrink variance of revenue per user."""
import numpy as np
from scipy import stats
from abstats import cuped_adjust
rng = np.random.default_rng(99)
N, LIFT = 20_000, 0.03 # users per arm, true +3% revenue
def make_users(n, lift):
spend_rate = rng.gamma(0.6, 30.0, n) # each user's typical spend
pre = rng.gamma(2.0, spend_rate / 2.0) # revenue in 4 weeks BEFORE test
post = rng.gamma(2.0, spend_rate * (1 + lift) / 2.0) # revenue DURING test
return pre, post
def analyse(pre_a, y_a, pre_b, y_b):
"""Welch t-test on raw and CUPED-adjusted revenue; theta from pooled data."""
y = np.concatenate([y_a, y_b])
x = np.concatenate([pre_a, pre_b])
y_adj, theta = cuped_adjust(y, x)
raw = stats.ttest_ind(y_b, y_a, equal_var=False)
adj = stats.ttest_ind(y_adj[N:], y_adj[:N], equal_var=False)
return raw, adj, theta, y, y_adj
pre_a, y_a = make_users(N, 0.0)
pre_b, y_b = make_users(N, LIFT)
raw, adj, theta, y, y_adj = analyse(pre_a, y_a, pre_b, y_b)
rho = np.corrcoef(y, np.concatenate([pre_a, pre_b]))[0, 1]
print(f"corr(pre, post) = {rho:.3f} theta = {theta:.3f}")
print(f"variance: raw {y.var():.1f} CUPED {y_adj.var():.1f} "
f"-> {1 - y_adj.var() / y.var():.1%} lower (theory: rho^2 = {rho ** 2:.1%})")
print(f"mean diff raw {y_b.mean() - y_a.mean():+.3f} p={raw.pvalue:.4f}")
print(f"mean diff CUPED {y_adj[N:].mean() - y_adj[:N].mean():+.3f} p={adj.pvalue:.4f}")
# Power over many experiments, and the A/A false positive rate
SIMS = 1_000
hits = {"raw": 0, "cuped": 0}
aa_false = {"raw": 0, "cuped": 0}
for _ in range(SIMS):
for lift, store in ((LIFT, hits), (0.0, aa_false)):
pa, ya = make_users(N, 0.0)
pb, yb = make_users(N, lift)
r, a, *_ = analyse(pa, ya, pb, yb)
store["raw"] += r.pvalue < 0.05
store["cuped"] += a.pvalue < 0.05
print(f"\n{SIMS:,} experiments, {N:,} users/arm, true lift +{LIFT:.0%}")
print(f"power raw {hits['raw'] / SIMS:.1%} CUPED {hits['cuped'] / SIMS:.1%}")
print(f"A/A false + raw {aa_false['raw'] / SIMS:.1%} CUPED {aa_false['cuped'] / SIMS:.1%}")
print(f"same power with CUPED needs ~{1 - rho ** 2:.0%} of the users")
corr(pre, post) = 0.550 theta = 0.551
variance: raw 995.9 CUPED 694.7 -> 30.2% lower (theory: rho^2 = 30.2%)
mean diff raw +0.810 p=0.0102
mean diff CUPED +0.743 p=0.0048
1,000 experiments, 20,000 users/arm, true lift +3%
power raw 37.8% CUPED 54.1%
A/A false + raw 4.8% CUPED 5.4%
same power with CUPED needs ~70% of the users
The pre/post correlation is 0.55, so CUPED removes 30.2% of the variance, exactly the rho^2 the theory predicts. Across 1,000 experiments, power rises from 37.8% to 54.1% at the same 20,000 users per arm. Put the other way, CUPED reaches a given power with about 70% of the users. The A/A rows (4.8% and 5.4% from 1,000 runs, within simulation noise of 5%) show the adjustment does not inflate false positives. Deng et al. report about 50% variance reduction on Bing metrics; how much you get depends entirely on how well past behavior predicts the test metric. New users have no pre-period. The paper’s suggestion is to set their missing covariate to a constant and add a second covariate that flags whether the user had pre-period data at all.

CUPED on synthetic revenue: variance of revenue per user drops from 995.9 to 694.7 (30.2% lower, equal to rho squared with rho = 0.55), and power over 1,000 experiments rises from 37.8% to 54.1% at 20,000 users per arm
Tests that pin the claims
Simulation outputs are easy to fool yourself with, so the key claims are also unit tests: the sample size equals 31,234, the z-test matches statsmodels, msprt_lambda() equals the numerical integral of the Gaussian mixture, daily peeking exceeds 20% false positives while mSPRT stays under 5%, the SRM check flags the buggy split and passes the clean one, Holm never rejects less than Bonferroni, and CUPED variance reduction equals rho^2.
Spoiler on dev.to: tests/test_abstats.py
"""Pin the claims the article makes about each helper."""
import sys
from pathlib import Path
import numpy as np
import pytest
from scipy import stats
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.proportion import proportions_ztest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from abstats import (cuped_adjust, msprt_lambda, sample_size_two_proportions, # noqa: E402
srm_check, two_proportion_ztest)
def test_sample_size_matches_textbook_value():
# 5% -> 5.5%, alpha=0.05 two-sided, 80% power
assert sample_size_two_proportions(0.05, 0.055) == 31_234
def test_ztest_matches_statsmodels():
z, p, _, _ = two_proportion_ztest(1557, 31_234, 1678, 31_234)
z_sm, p_sm = proportions_ztest([1678, 1557], [31_234, 31_234])
assert z == pytest.approx(z_sm) and p == pytest.approx(p_sm)
def test_msprt_lambda_is_gaussian_mixture_ratio():
# Closed form equals the integral of N(theta,V)/N(0,V) over N(0,tau^2)
d, v, tau2 = 0.004, 2e-6, 0.005 ** 2
th = np.linspace(-0.05, 0.05, 200_001)
integrand = (stats.norm.pdf(d, th, np.sqrt(v)) / stats.norm.pdf(d, 0, np.sqrt(v))
* stats.norm.pdf(th, 0, np.sqrt(tau2)))
assert msprt_lambda(d, v, tau2) == pytest.approx(np.trapezoid(integrand, th), rel=1e-6)
def test_msprt_controls_type_one_error_under_daily_peeking():
rng = np.random.default_rng(0)
n = 1_200 * np.arange(1, 29)
ca = rng.binomial(1_200, 0.05, (3_000, 28)).cumsum(1)
cb = rng.binomial(1_200, 0.05, (3_000, 28)).cumsum(1)
pa, pb = ca / n, cb / n
lam = msprt_lambda(pb - pa, pa * (1 - pa) / n + pb * (1 - pb) / n, 0.005 ** 2)
assert (lam >= 20).any(axis=1).mean() <= 0.05
def test_naive_daily_peeking_inflates_false_positives():
rng = np.random.default_rng(1)
n = 1_200 * np.arange(1, 29)
ca = rng.binomial(1_200, 0.05, (3_000, 28)).cumsum(1)
cb = rng.binomial(1_200, 0.05, (3_000, 28)).cumsum(1)
_, p, _, _ = two_proportion_ztest(ca, n, cb, n)
assert (p < 0.05).any(axis=1).mean() > 0.20
def test_srm_flags_small_imbalance_at_scale():
assert srm_check(100_083, 92_443).pvalue < 1e-10
assert srm_check(100_083, 99_917).pvalue > 0.05
def test_holm_never_rejects_less_than_bonferroni():
rng = np.random.default_rng(3)
for _ in range(500):
p = rng.random(5) ** 3
bonf = multipletests(p, 0.05, "bonferroni")[0]
holm = multipletests(p, 0.05, "holm")[0]
assert (holm >= bonf).all()
def test_cuped_variance_reduction_equals_rho_squared():
rng = np.random.default_rng(4)
x = rng.normal(size=200_000)
y = 0.7 * x + rng.normal(size=200_000)
y_adj, _ = cuped_adjust(y, x)
rho = np.corrcoef(x, y)[0, 1]
assert 1 - y_adj.var() / y.var() == pytest.approx(rho ** 2, abs=1e-3)
assert y_adj.mean() == pytest.approx(y.mean()) # mean is unchanged
$ python -m pytest -q tests
........ [100%]
8 passed
Gotchas I hit while writing this
proportions_ztest is not vectorized across experiments. Passing 4,000 experiments as a 2 x 4,000 array raised NotImplementedError: more than two samples are not implemented yet. The fix was a small NumPy version of the pooled z-test, with a unit test proving it matches statsmodels on a single case.
Calling multipletests in a Python loop was the slowest part. On a busy two-core sandbox, a row-by-row loop over 20,000 experiments did not finish within two minutes. A vectorized Holm (argsort, cumulative product, scatter back) with an assertion against multipletests on 200 rows replaced it.
The observed lift is not the true lift. In Step 2 the truth was +10% and the readout said +7.8%. Across many tests, the ones that win are biased upward.
mSPRT needs a prior scale. tau is a tuning parameter, not a detail. Set it near the effect size you care about and check power by simulation before you ship it to a dashboard.
CUPED’s theta must be shared. Deng et al. state that the same theta has to be used for control and treatment for the adjusted difference to be unbiased, so estimate it once on the pooled data.
Checklist for your next experiment
- Pick one primary metric and an MDE that is worth shipping.
- Compute the sample size, then verify power by simulating a few thousand experiments.
- Decide how you will look: once, on a spending schedule, or with an always-valid test.
- Run an SRM chi-square check before reading any metric.
- Report the effect with a confidence interval, not only a p-value.
- Correct secondary metrics with Holm, or label them exploratory.
- Add CUPED if you have pre-period data for the metric.
- Run A/A tests on your own pipeline from time to time; the share of “winners” should be close to alpha.
Wrapping up
The formulas behind A/B testing statistics are decades old and fit in a few lines of Python. What a simulation adds is a way to check your whole procedure, including the human parts like peeking, against a world where you know the answer. If your process cannot keep A/A tests at about 5% false wins, the numbers it reports for real tests are not what they claim to be.
How does your team handle peeking: fixed horizon, a spending schedule, or always-valid p-values in the dashboard?

Top comments (0)