Data analysis · Intermediate · 22 min
Plan an A/B test: metric, sample size and duration
By Padding · Updated 18 Nov 2026
Python 3.15 · statsmodels 0.15.0 · pandas 3.1.1 · NumPy 2.5.5 · SciPy 1.18.1 (checked on python:3.15-slim)
You will write a hypothesis, choose one primary metric and a few guardrails, size the test with a statsmodels power calculation, turn the sample size into whole weeks, and fix it all in a one-page plan before any data arrives.
On this page
Most A/B tests that go wrong were lost before the first visitor arrived. Nobody wrote down which number decides the result, so after two weeks the team reads ten dashboards and picks the one that moved. Nobody worked out how many users the test needed, so it stopped as soon as the graph looked good. Nobody agreed whether "a user" meant a person, a session or a page view, so the two groups were not really separate.
A plan fixes all three before there is any data to be tempted by. In this tutorial you plan one realistic test: an online shop wants to replace its three-step checkout with a single page. You will:
- write the hypothesis and pick one primary metric, plus guardrail metrics that must not get worse
- measure the baseline conversion rate from 28 days of history
- choose the smallest lift worth detecting and compute the sample size with statsmodels
- check that number by simulating 2,000 experiments of that size
- turn the sample size into a whole number of weeks
- decide what gets randomised, and check that the split is even and stable
- render everything into a one-page plan and fingerprint it so nobody can quietly edit it later
Every script reads the files the previous one wrote, so the numbers in the final plan come straight from the calculations.
Step 1 · Create the project and install statsmodels
Make a throwaway folder and a virtual environment, then install statsmodels with the libraries it uses, pinned to the versions this tutorial was written against:
mkdir -p ~/ab-plan-demo
cd ~/ab-plan-demo
python3 -m venv .venv
. .venv/bin/activate
pip install "statsmodels==0.15.0" "pandas==3.1.1" "numpy==2.5.5" "scipy==1.18.1"
python -c "import statsmodels, pandas, numpy, scipy; print(statsmodels.__version__, pandas.__version__, numpy.__version__, scipy.__version__)"The four packages together are several tens of megabytes. On prepaid mobile data, install once on Wi-Fi: pip keeps a cache, so the same versions install offline in later projects.
Check it worked
The last command prints 0.15.0 3.1.1 2.5.5 1.18.1 and your prompt starts with (.venv). In a new terminal later, run cd ~/ab-plan-demo and . .venv/bin/activate again.
Step 2 · Write the hypothesis and choose the metrics
Decisions come first, numbers second. Put them in plan.json so later scripts can read them and nobody has to retype them.
A useful hypothesis has three parts: the change, the outcome you expect, and the reason you expect it. The reason matters because it tells you which guardrails to watch. Here the team believes people on slow mobile connections abandon checkout while each of the three steps loads, so page speed on mobile is a guardrail.
Pick exactly one primary metric. It is the only number that decides ship or no ship. Define it precisely enough that two analysts would compute the same value: who is counted, what counts as success, and in what time window. Then add a small set of guardrail metrics: things the change could damage that the primary metric would not show. Each guardrail gets a limit written now, not after you see the data.
cd ~/ab-plan-demo
cat > plan.json <<'JSON'
{
"experiment": "one-page-checkout-2027-01",
"hypothesis": "If we replace the three-step checkout with a single page, more visitors who open checkout will place an order, because people on slow mobile connections drop out while each step loads.",
"primary_metric": {
"name": "Checkout conversion",
"definition": "share of users who open checkout and place at least one order within 24 hours",
"unit": "user"
},
"guardrails": [
{"name": "average order value", "limit": "must not fall by more than 2%"},
{"name": "payment error rate", "limit": "must not rise by more than 0.5 percentage points"},
{"name": "checkout load time, 75th percentile on mobile", "limit": "must not rise by more than 300 ms"},
{"name": "sample ratio", "limit": "split check p-value must stay above 0.001"}
],
"randomisation_unit": "user: logged-in account ID, or a first-party ID cookie for signed-out visitors",
"eligibility": "every user who opens the checkout page between the start and end dates",
"decision_rule": "Ship B only if checkout conversion is higher with p < 0.05 at the planned end date and no guardrail is breached. Otherwise keep A."
}
JSON
. .venv/bin/activate
python -c "import json; p = json.load(open('plan.json')); print(p['primary_metric']['name'], '|', len(p['guardrails']), 'guardrails')"A few choices in that file are worth copying to your own tests:
- The metric is counted per user, not per session or page view. On patchy mobile data people reload and restart sessions, so a session count would grow with network quality rather than with the checkout design.
- "Within 24 hours" closes the window. Without it, a user who enters the test on the last day has less time to buy than one who entered on the first.
- The sample ratio guardrail is about the test itself: if the groups end up with very different sizes, something in the assignment is broken and no other number can be trusted.
- The decision rule names the end date. Results looked at before then do not count.
Check it worked
The command prints Checkout conversion | 4 guardrails. If you get a JSONDecodeError, a quote or comma in the file is out of place; the error names the line.
Step 3 · Measure the baseline from history
The sample size depends on how often the primary metric happens today. Take it from a recent, ordinary stretch of data: four full weeks is a good default because it covers every weekday four times.
You would export this from your analytics tool. For this tutorial, a short script writes a stand-in file, history.csv, with one row per day: users is the number of people who opened checkout for the first time that day, and buyers is how many of them ordered within 24 hours. Counting first-time users matters: daily counts of all users add up to more than the real number of people, because returning users are counted again on every visit.
cd ~/ab-plan-demo
cat > make_history.py <<'PY'
"""Write history.csv: 28 days of new checkout users and buyers, standing in for an analytics export."""
import numpy as np
import pandas as pd
rng = np.random.default_rng(2026)
days = pd.date_range("2026-10-05", periods=28, freq="D") # Monday 5 October to Sunday 1 November
weekday_shape = np.array([1.05, 1.00, 1.00, 1.02, 1.10, 0.88, 0.80]) # Monday to Sunday
users = rng.poisson(5_200 * weekday_shape[days.day_of_week])
buyers = rng.binomial(users, 0.041)
pd.DataFrame({"date": days.date, "users": users, "buyers": buyers}).to_csv("history.csv", index=False)
print(f"wrote {len(days)} days, {users.sum():,} users, {buyers.sum():,} buyers")
PY
cat > baseline.py <<'PY'
"""Baseline conversion rate and daily traffic from history.csv."""
import pandas as pd
history = pd.read_csv("history.csv", parse_dates=["date"])
rate = history["buyers"].sum() / history["users"].sum()
daily_rate = history["buyers"] / history["users"]
by_weekday = history.groupby(history["date"].dt.day_name(), sort=False)["users"].mean()
print(f"days: {len(history)} ({history['date'].min():%a %d %b} to {history['date'].max():%a %d %b})")
print(f"baseline conversion: {rate:.4f}")
print(f"mean users per day: {history['users'].mean():,.0f}")
print(f"quietest weekday: {by_weekday.idxmin()} ({by_weekday.min():,.0f})")
print(f"daily rate range: {daily_rate.min():.4f} to {daily_rate.max():.4f}")
PY
. .venv/bin/activate
python make_history.py
python baseline.pyThe baseline is the total of buyers divided by the total of users, not the average of the 28 daily rates: a quiet Sunday should not count as much as a busy Friday.
Check it worked
You should see wrote 28 days, 142,542 users, 5,751 buyers, then baseline conversion: 0.0403, mean users per day: 5,091 and Sunday as the quietest weekday. These match exactly with NumPy 2.5.5; other versions may draw slightly different numbers. Note the daily rate range, roughly 3.5% to 4.6%: day-to-day noise alone moves the rate by more than the lift you are about to look for, which is why one good day proves nothing.
Step 4 · Choose the minimum effect and compute the sample size
The minimum detectable effect (MDE) is the smallest lift you would act on. It is a business decision, not a statistical one: if building and maintaining the one-page checkout only pays off at +10% relative, there is no point sizing the test to find +2%. A smaller MDE needs many more users, roughly four times as many each time you halve it.
Three more settings go into the calculation:
- Significance level (alpha), 0.05: the chance of declaring a winner when the change does nothing.
- Power, 0.80: the chance of detecting the lift if it really is as large as the MDE. At 0.80 you accept missing a real +10% lift one time in five.
- Two-sided: you test for harm as well as benefit.
statsmodels does this in two calls. proportion_effectsize turns the two conversion rates into Cohen's h, a standardised effect size for proportions. NormalIndPower().solve_power then solves for whichever input you leave out; here that is the number of users in the first group, with ratio=1.0 meaning the second group is the same size.
cd ~/ab-plan-demo
cat > power.py <<'PY'
"""Users needed per group to detect a relative lift in conversion rate."""
import json
import math
import pandas as pd
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
ALPHA = 0.05 # chance of a false positive we accept
POWER = 0.80 # chance of detecting the lift if it is real
MDE_RELATIVE = 0.10 # smallest lift worth shipping: +10% relative
history = pd.read_csv("history.csv")
baseline = round(history["buyers"].sum() / history["users"].sum(), 4)
analysis = NormalIndPower()
def per_group(lift):
target = baseline * (1 + lift)
effect = proportion_effectsize(target, baseline) # Cohen's h
n = analysis.solve_power(effect_size=effect, alpha=ALPHA, power=POWER,
ratio=1.0, alternative="two-sided")
return target, effect, math.ceil(n)
target, effect, n = per_group(MDE_RELATIVE)
print(f"baseline {baseline:.4f} -> target {target:.5f} (+{MDE_RELATIVE:.0%} relative)")
print(f"Cohen's h: {effect:.4f}")
print(f"users per group: {n:,}")
print(f"users in total: {2 * n:,}")
print()
print("lift target per group")
for lift in (0.05, 0.10, 0.15, 0.20):
t, _, k = per_group(lift)
print(f"{lift:>4.0%} {t:.5f} {k:>10,}")
with open("sizing.json", "w") as f:
json.dump({"baseline": baseline, "target": round(target, 5), "mde_relative": MDE_RELATIVE,
"alpha": ALPHA, "power": POWER, "per_group": n}, f, indent=2)
print("\nsaved sizing.json")
PY
. .venv/bin/activate
python power.pymath.ceil rounds up: you cannot recruit 0.3 of a person, and rounding down would leave the test slightly short of 80% power. The baseline is rounded to four decimal places so the plan quotes the same number the calculation used.
Check it worked
The script prints users per group: 39,148 and users in total: 78,296, then a table:
lift target per group
5% 0.04232 153,085
10% 0.04433 39,148
15% 0.04634 17,784
20% 0.04836 10,217Read the table before you move on. Halving the MDE from 10% to 5% needs almost four times the users. If your traffic cannot reach the 10% row in a reasonable time, the honest answer is a bigger, bolder change, not a smaller MDE.
Step 5 · Check the number by simulating experiments
A formula is easier to trust once you have watched it work. Pretend the one-page checkout really lifts conversion by exactly 10%, run 2,000 fake experiments with 39,148 users per group, and count how often a standard two-proportion z-test calls it significant. If the sample size is right, that share should be close to 80%. Then run 2,000 experiments where both groups get the old checkout (an A/A test): about 5% should come out significant by chance, which is alpha doing its job.
cd ~/ab-plan-demo
cat > simulate.py <<'PY'
"""Check the sample size by running 2,000 pretend experiments of that size."""
import json
import numpy as np
from statsmodels.stats.proportion import proportions_ztest
sizing = json.load(open("sizing.json"))
BASELINE, TARGET, N, RUNS = sizing["baseline"], sizing["target"], sizing["per_group"], 2_000
rng = np.random.default_rng(7)
def share_significant(rate_b):
control = rng.binomial(N, BASELINE, size=RUNS)
variant = rng.binomial(N, rate_b, size=RUNS)
hits = 0
for c, v in zip(control, variant):
_, p = proportions_ztest([v, c], [N, N], alternative="two-sided")
hits += p < sizing["alpha"]
return hits / RUNS
print(f"real +10% lift, share significant: {share_significant(TARGET):.3f}")
print(f"no lift (A/A), share significant: {share_significant(BASELINE):.3f}")
PY
. .venv/bin/activate
python simulate.pyThe z-test here is the kind of test you will run at the end, and it is not the same calculation as the arcsine-based Cohen's h. Agreement between the two is the point: the plan's number holds up under the analysis you intend to do.
Check it worked
You should see something like real +10% lift, share significant: 0.796 and no lift (A/A), share significant: 0.053. With 2,000 runs, anything from about 0.78 to 0.82 for the first line and 0.04 to 0.06 for the second is consistent with 80% power and 5% alpha. Try changing N to sizing["per_group"] // 2 and run it again: the first share drops to roughly half, which is what an underpowered test looks like.
Step 6 · Turn the sample size into whole weeks
Divide the users you need by the users you get, then round up to whole weeks. Behaviour on a Saturday is not behaviour on a Tuesday, so a test that runs Monday to Thursday measures a different population from one that covers the weekend. Whole weeks give every weekday equal weight in both groups. Plan on your quietest full week, so a slow week does not leave you short.
Two more limits belong here. Not every test can take all of your traffic, so the script takes the share of eligible users in the test as an optional argument. And set a ceiling: beyond about six weeks, people clear cookies, switch phones and come back as new users, and seasonal events creep in. If the plan needs longer, change the plan rather than the ceiling.
cd ~/ab-plan-demo
cat > duration.py <<'PY'
"""Turn the sample size into whole weeks of traffic."""
import datetime as dt
import json
import math
import sys
import pandas as pd
SHARE_IN_TEST = float(sys.argv[1]) if len(sys.argv) > 1 else 1.0 # share of eligible users in the test
START = dt.date(2027, 1, 11) # a Monday clear of sales and holidays
MAX_WEEKS = 6 # longer than this and the plan needs a bigger MDE
sizing = json.load(open("sizing.json"))
history = pd.read_csv("history.csv", parse_dates=["date"])
weekly = history.groupby(history["date"].dt.to_period("W-SUN"))["users"].sum()
per_week = weekly.min() * SHARE_IN_TEST # plan on the quietest full week
needed = 2 * sizing["per_group"]
weeks = max(1, math.ceil(needed / per_week))
end = START + dt.timedelta(weeks=weeks) - dt.timedelta(days=1)
print(f"quietest week: {weekly.min():,} users")
print(f"users needed: {needed:,}")
print(f"raw weeks: {needed / per_week:.2f} -> run for {weeks} whole weeks")
print(f"dates: {START:%a %d %b %Y} to {end:%a %d %b %Y}")
if weeks > MAX_WEEKS:
print(f"warning: {weeks} weeks is over the {MAX_WEEKS}-week limit; raise the MDE or the share in test")
with open("duration.json", "w") as f:
json.dump({"share_in_test": SHARE_IN_TEST, "weeks": weeks, "start": START.isoformat(),
"end": end.isoformat(), "users_needed": needed}, f, indent=2)
PY
. .venv/bin/activate
python duration.py 0.3
python duration.pyThe first run shows the problem with sending only 30% of users into the test: 8 weeks, over the limit. The second run, with every eligible user in the test, needs 2.2 weeks and becomes 3. The start date is a Monday in January on purpose: a test running over a big sale or a public holiday measures shoppers who behave unlike your usual ones. Pick dates clear of your own market's sales seasons, school terms and holidays.
Check it worked
The second run prints run for 3 whole weeks and dates: Mon 11 Jan 2027 to Sun 31 Jan 2027. Open duration.json and check share_in_test is 1.0: the last run is the one saved, and the plan reads this file.
Step 7 · Decide what gets randomised and check the split
The randomisation unit is the thing that gets put into group A or B. It must match the unit of the primary metric, which is the user. If you randomised page views instead, one person could see the old checkout, reload, and see the new one; their single purchase would then belong to both groups.
A common way to assign users is to hash their ID together with the experiment's name. The same user always gets the same group, on every server and every visit, with nothing to store. Including the experiment name means a user who is in group B of this test is not always in group B of the next one.
cd ~/ab-plan-demo
cat > assign.py <<'PY'
"""Assign each user to a group by hashing their ID with the experiment's name."""
import hashlib
from collections import Counter
from scipy.stats import chisquare
EXPERIMENT = "one-page-checkout-2027-01"
def group(user_id: str) -> str:
digest = hashlib.sha256(f"{EXPERIMENT}:{user_id}".encode()).hexdigest()
bucket = int(digest[:8], 16) % 10_000 # 0 to 9,999
return "B" if bucket < 5_000 else "A"
if __name__ == "__main__":
users = [f"user-{i:06d}" for i in range(100_000)]
counts = Counter(group(u) for u in users)
same = all(group(u) == group(u) for u in users[:1_000])
_, p = chisquare([counts["A"], counts["B"]])
print(f"A: {counts['A']:,} B: {counts['B']:,}")
print(f"same user, same group every time: {same}")
print(f"split check p-value: {p:.3f}")
print(f"user-000042 is in group {group('user-000042')}")
PY
. .venv/bin/activate
python assign.pyThe split check is a chi-square test of the two counts against an even 50/50. During the real test you run the same check on the users who actually arrived in each group. That is the sample ratio guardrail from plan.json: a p-value below 0.001 means the split is broken (a redirect that loses some users, a bot filter applied to one group) and the results should not be read until it is fixed.
Signed-out visitors are the weak spot. Someone who clears cookies or moves from a phone to a laptop gets a new ID and may land in the other group. Asking users to log in for checkout, or counting logged-in users only, keeps the groups cleaner; write down which you chose.
Check it worked
You should see A: 49,906 B: 50,094, same user, same group every time: True and a split check p-value of 0.552, far above 0.001. Change EXPERIMENT to another name and run it again: user-000042 may switch group, and the counts change, but stay close to 50,000 each.
Step 8 · Write and freeze the one-page plan
Now combine the decisions from plan.json with the numbers from sizing.json and duration.json into plan.md. The script refuses to write a plan whose metric is not counted per user, or that has no guardrails or too many to watch.
cd ~/ab-plan-demo
cat > plan.py <<'PY'
"""Combine the decisions and the numbers into a one-page plan, then fingerprint it."""
import hashlib
import json
plan = json.load(open("plan.json"))
sizing = json.load(open("sizing.json"))
duration = json.load(open("duration.json"))
assert plan["primary_metric"]["unit"] == "user", "the metric must be counted per randomisation unit"
assert 1 <= len(plan["guardrails"]) <= 5, "pick between one and five guardrails"
guardrails = "\n".join(f"- {g['name']}: {g['limit']}" for g in plan["guardrails"])
text = f"""# Test plan: {plan['experiment']}
## Hypothesis
{plan['hypothesis']}
## Primary metric
{plan['primary_metric']['name']}: {plan['primary_metric']['definition']}.
## Guardrail metrics
{guardrails}
## Size
- Baseline: {sizing['baseline']:.2%} (last 28 days)
- Smallest lift worth detecting: +{sizing['mde_relative']:.0%} relative, to {sizing['target']:.2%}
- Significance level {sizing['alpha']}, power {sizing['power']:.0%}, two-sided
- Users per group: {sizing['per_group']:,} ({duration['users_needed']:,} in total)
## Duration
- {duration['weeks']} whole weeks, {duration['start']} to {duration['end']}
- Share of eligible users in the test: {duration['share_in_test']:.0%}, split 50/50
## Who is in the test
- Randomisation unit: {plan['randomisation_unit']}
- Eligible: {plan['eligibility']}
## Decision rule
{plan['decision_rule']}
No early stopping and no extra metrics added after the start date.
"""
with open("plan.md", "w") as f:
f.write(text)
print(f"plan.md: {len(text.splitlines())} lines")
print("sha256:", hashlib.sha256(text.encode()).hexdigest())
PY
. .venv/bin/activate
python plan.py
sha256sum plan.mdOn macOS, use shasum -a 256 plan.md instead of sha256sum.
The hash is the freezing step. Paste plan.md and its hash into your team's ticket or chat before the test starts. At the end, anyone can hash the plan again: if one word changed (a new metric, a shorter duration, a different MDE), the hash no longer matches, and the change shows. Commit the project folder to version control as well, so the scripts that produced the numbers stay with the plan.
If several people read the plan in different languages, translate the prose but keep the metric names and limits exactly as written, so there is only one definition to argue about.
Check it worked
The script prints plan.md: 31 lines and a 64-character hash, and sha256sum plan.md prints the same hash. Open plan.md: it fits on one screen, and every number in it (4.03%, 4.43%, 39,148 users per group, 3 weeks from 2027-01-11 to 2027-01-31) matches what the earlier steps printed.
When you are done, delete the project with rm -rf ~/ab-plan-demo.
Next steps
- Analyse an A/B test without peeking or p-hacking takes a finished test, runs the sample ratio check and the primary metric test, and reads the result against a plan like this one.
- Calculate and explain confidence intervals the right way shows how to report the size of a lift, not only whether it passed 0.05.
- Use analytics to decide what to research helps you find the drop-off worth testing in the first place.
- Understand probability distributions by simulating them explains the binomial draws behind the simulation step.
Part of these paths
Related tutorials
- Analyse an A/B test without peeking or p-hackingYou will check an experiment for sample ratio mismatch, read its main metric once with a confidence interval, see by simulation why daily peeking and extra metrics produce false wins, and write a decision that states its uncertainty.
- Calculate and explain confidence intervals the right wayYou will compute a t interval for a mean, a Wilson interval for a proportion and a bootstrap interval for a median in Python, prove by simulation that about 95 in 100 intervals catch the true value, and write the results up in sentences that say what a confidence interval does and does not mean.
- Use analytics to decide what to research nextYou will turn a booking flow's funnel and event data into two or three research questions, each tied to a specific number, a specific group of people and a method that can answer it.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials