This is Module 5 of the Data Analyst to Data Scientist path. Module 4 taught you to report an estimate with its uncertainty. Experiments add the thing analysis alone can’t give you: evidence that a change caused a difference. They’re also easy to get wrong in ways that produce confident, false answers. This module covers the three mistakes that do the most damage, each with a script.
You’ll build: a sample-size function, a check that your traffic split worked, and a simulation that shows what stopping a test early does to your error rate.
You need: Python 3. Everything uses the standard library.
1. Before the test: decide the size
A test needs three decisions written down before it starts: the primary metric (one), the smallest lift worth detecting (a smaller real lift wouldn’t pay for the change), and from those, the sample size. Save this as sample_size.py:
# How many visitors does each version need? Two-sided test, 5% significance, 80% power.
from math import ceil, sqrt
from statistics import NormalDist
def visitors_per_group(baseline: float, lift: float, alpha: float = 0.05, power: float = 0.80) -> int:
"""baseline: current conversion rate (0.04 = 4%); lift: smallest absolute change worth detecting (0.01 = 1 point)."""
p1, p2 = baseline, baseline + lift
z_a, z_b = NormalDist().inv_cdf(1 - alpha / 2), NormalDist().inv_cdf(power)
p_bar = (p1 + p2) / 2
n = (z_a * sqrt(2 * p_bar * (1 - p_bar)) + z_b * sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2 / lift ** 2
return ceil(n)
for lift in (0.02, 0.01, 0.005):
print(f"4% baseline, detect +{lift * 100:.1f} points: {visitors_per_group(0.04, lift):,} visitors per version")
4% baseline, detect +2.0 points: 1,863 visitors per version
4% baseline, detect +1.0 points: 6,745 visitors per version
4% baseline, detect +0.5 points: 25,551 visitors per version
Halving the lift you want to detect roughly quadruples the visitors you need. If your site gets 1,000 visitors a day, a test for a 0.5-point lift takes about seven weeks, which is often the answer to “why don’t we test everything?”. The free A/B Test Sample Size Calculator on Analytics Hack does the same arithmetic in a browser; it uses a slightly different approximation, and its answers here are within 1% of these.
2. At the start: check the split
If you designed a 50/50 split, the two groups should come out close to 50/50. When they don’t, something in the setup is broken: a redirect that loses some visitors, a bot filter that applies to one version, a bug that crashes one variant on some browsers. This is called a sample ratio mismatch (SRM), and it biases results in ways no analysis can fix. Microsoft’s experimentation team reports that about 6% of its A/B tests have one, and every test there must pass an SRM check before its results are shown. Save this as srm_check.py:
# Sample ratio mismatch: did the split come out the way you designed it? Check BEFORE reading any result.
from statistics import NormalDist
def srm_p_value(n_a: int, n_b: int, share_a: float = 0.5) -> float:
"""Chi-square goodness-of-fit test with one degree of freedom, written with the normal distribution."""
total = n_a + n_b
exp_a, exp_b = total * share_a, total * (1 - share_a)
chi2 = (n_a - exp_a) ** 2 / exp_a + (n_b - exp_b) ** 2 / exp_b
return 2 * (1 - NormalDist().cdf(chi2 ** 0.5))
for n_a, n_b in [(5_000, 4_950), (5_000, 4_600)]:
p = srm_p_value(n_a, n_b)
verdict = "split looks fine" if p >= 0.001 else "MISMATCH: find the cause before reading results"
print(f"A {n_a:,} vs B {n_b:,}: p = {p:.2g} -> {verdict}")
A 5,000 vs B 4,950: p = 0.62 -> split looks fine
A 5,000 vs B 4,600: p = 4.5e-05 -> MISMATCH: find the cause before reading results
The ratio alone can mislead, so use a statistical test, as Microsoft’s team advises: 4,600 out of 9,600 is only 48%, yet with this many visitors a gap that size is very unlikely to be chance. We use a strict threshold (0.001) so that the check rarely raises a false alarm.
3. During the test: don’t stop at the first “significant” result
Most testing tools show a live p-value. It’s tempting to stop the moment it drops below 0.05. Evan Miller’s classic note, How Not To Run an A/B Test, explains why that’s a mistake: every look is another chance for noise to cross the line. Save this as peeking.py, which simulates 2,000 tests where B is identical to A, so every “winner” is false:
# Why you shouldn't stop a test the first time it looks significant: simulate tests where B is identical to A.
import random
from math import sqrt
from statistics import NormalDist
def p_value(conv_a, n_a, conv_b, n_b):
p_pool = (conv_a + conv_b) / (n_a + n_b)
se = sqrt(p_pool * (1 - p_pool) * (1 / n_a + 1 / n_b))
if se == 0:
return 1.0
z = (conv_b / n_b - conv_a / n_a) / se
return 2 * (1 - NormalDist().cdf(abs(z)))
random.seed(5)
RATE, DAILY, DAYS, TESTS = 0.04, 500, 20, 2_000 # both versions convert at 4%; 500 visitors each per day
stopped_early = fixed_end = 0
for _ in range(TESTS):
ca = cb = n = 0
peeked_significant = False
for day in range(DAYS):
ca += sum(random.random() < RATE for _ in range(DAILY))
cb += sum(random.random() < RATE for _ in range(DAILY))
n += DAILY
if p_value(ca, n, cb, n) < 0.05:
peeked_significant = True # a peeker would stop here and declare a winner
stopped_early += peeked_significant
fixed_end += p_value(ca, n, cb, n) < 0.05 # one look, at the planned end
print(f"false winners, checking once at the end: {fixed_end / TESTS:.1%}")
print(f"false winners, checking every day: {stopped_early / TESTS:.1%}")
false winners, checking once at the end: 4.9%
false winners, checking every day: 25.1%
Checked once, at the planned end, the test is wrong about 5% of the time, as designed. Checked every day for 20 days and stopped at the first significant reading, it declares a false winner a quarter of the time. Miller’s own worst case, checking after every observation, gives 26.1%. His advice is the simplest fix: “Decide on a sample size in advance and wait until the experiment is over.” Looking is fine; stopping early is the problem. (Methods built for continuous monitoring, such as sequential tests, exist, but they need to be chosen before the test starts.)
4. At the end: read the result with its interval
When the planned sample is reached, compute the difference and its 95% confidence interval. The path overview has a short ab_test.py for this. Its example, 4.0% against 4.9% on 5,000 visitors each, is significant (p = 0.029), but the interval runs from +0.09 to +1.71 points. If a 0.1-point lift wouldn’t pay for the change, the test hasn’t settled the decision. Report both numbers.
A pre-registration checklist
Write this down before the test starts, and share it:
- The one primary metric, and how it’s calculated.
- The smallest lift worth detecting, and why.
- The sample size per version, and the date you expect to reach it.
- The SRM check you’ll run first.
- The decision rule: what result leads to shipping, and what doesn’t.
Project
Design an experiment for a real change your team is considering. Fill in the checklist, run sample_size.py with your own baseline and lift, and check the duration against your traffic. If it’s too long, say what you’d change: a bigger lift, a metric closer to the change, or more traffic.
Next: Module 6: Predictive Modelling, Judged by What Errors Cost.