A/B tests in Python: sample size, significance and lift, step by step
TL;DR
Difficulty: Intermediate
An A/B test in Python is a handful of calls. The judgement around them is the work.
- Set the lift worth having in money first, then compute visitors per arm, and run the function backwards to see what the test you can afford is able to detect.
- Report the lift with its interval from confint_proportions_2indep(compare="ratio"): the nine day test's plus 32% runs from minus 11% to plus 96%.
- Read a factorial with one regression and plus and minus one coding. The default coding turns the anchor that helps next to proof into an anchor that hurts.
- Check the split with a chi square before reading anything.
- Daily peeking turns 5% false winners into 28%, and a small test that wins reports a true 15% lift as 26% or more.
My Marketing Analytics chapter on testing explains sample size, lift and full factorial designs on an invented SaaS called Workbench. This chapter builds all of it in Python with statsmodels, SciPy and NumPy, reproduces its numbers exactly, and adds what the code makes visible: an honest interval on the lift, the coding trap in factorial regressions, and why a small test that wins overstates its win.
The nine day test, now in code
Workbench is the invented Rails SaaS for joiners, plumbers and electricians, run from Cork at workbench.example, that carries the Marketing Analytics chapter on testing. Its founders once shipped a new pricing page headline because a dashboard said "plus 32% trial signups" after nine days: 41 trials from 1,050 visitors on the old page, 54 from 1,050 on the new one. Two months later the trial rate was exactly where it had been.
Why that happened, and the whole discipline that stops it, is explained in Statistical testing: sample size, lift and full factorial designs. Read it for the concepts. This chapter builds every piece of it in Python, line by line: the lift worth detecting, the sample size, the two proportion z test, an honest interval on the lift, the two by two by two factorial on Workbench's pricing page analysed with a regression, the peeking problem shown by simulation, and the checks that make a result trustworthy. The factorial data is generated so that it reproduces the counts in that chapter exactly, so every number you get here matches a number you read there.
You need the basics from descriptive statistics for marketers in Python, where intervals for a proportion first appear, and the formula interface from statistical models in Python with statsmodels and scikit learn. If grouping a table is new, group by and pivot tables in pandas covers it.
If you only read one section
For the person who commissions tests and will never run the code, four things matter, and the first is the one most teams miss.
A winner from a small test overstates the lift. In the simulations below, Workbench's variant truly lifts trials by 15%. With 6,000 visitors per arm the test finds it only 37% of the time, and when it does, the average lift it reports is 26%. If the team checks the dashboard daily and stops at the first green day, the median reported lift is 34%. The bigger the reported win from a small test, the more of it is luck. A forecast built on that number will disappoint, and nobody will know why.
Decide the smallest lift worth having before the test, in money. For Workbench, a 15% lift on the pricing page is worth about €5,200 of lifetime revenue for every month the better page runs. That is what justifies 17,944 visitors per arm, about 18 months of its traffic. One function call turns that business number into a sample size, and the same call run backwards tells you what a test of the size you can afford is able to see.
Ask for the interval on the relative lift, not the p value. The nine day test's "plus 32%" has a 95% interval from minus 11% to plus 96%. That range is the true state of knowledge, and it fits on one line of a memo.
Test the pieces of a page together. A two by two by two factorial on 6,000 visitors measures three changes for the price of one, and in Workbench's data it finds that a price anchor hurts on its own and helps a lot next to customer proof. A regression reads that in one line, provided the factors are coded the right way. Coded the default way, the same regression tells you the anchor hurts, full stop.
Before you start: the versions this chapter uses
This chapter is written for Python 3.14, released in October 2025, with pandas 3.0.5, NumPy 2.5, statsmodels 0.14.6 and SciPy 1.18, the versions current in August 2026.1 If you set up your environment as described in why Python for data analysis, and how to set it up, install them with:
pip install "pandas>=3.0.5" "numpy>=2.5" "statsmodels>=0.14.6" "scipy>=1.18"
Wes McKinney's Python for Data Analysis, third edition, introduces statsmodels and its formula interface in chapter 12, written against pandas 1.4.2 The formula interface is unchanged in statsmodels 0.14, and the book does not cover the testing and power functions in statsmodels.stats, which this chapter leans on. pandas 3.0, released in January 2026, made text columns a dedicated string data type by default and made copy on write the only behaviour, so a filtered table always acts like a copy.3 You will see the string type in the output below, and the code adds columns with assign rather than writing into a slice.
Example: checking your versions
import sys
import numpy as np
import pandas as pd
import scipy
import statsmodels
print(sys.version.split()[0], pd.__version__, np.__version__,
statsmodels.__version__, scipy.__version__)
# 3.14.x 3.0.5 2.5.1 0.14.6 1.18.0
Run every block in this chapter in order, in one notebook. Later blocks use names that earlier ones define.
Step one: read the nine day test the way it should have been read
Start where the Workbench founders went wrong. They had two counts and two denominators, and they read the ratio of the rates: 54 out of 1,050 is 5.14%, 41 out of 1,050 is 3.90%, and 5.14 divided by 3.90 is 1.32. That ratio is the observed lift. What they skipped is the question every test has to answer: how surprised should I be by a gap this size if the headline did nothing?
The two proportion z test answers it. It compares the gap with the gap that random variation alone would produce, using the pooled rate of both arms:
where and are the observed rates of the old and new page, and their trial counts, and their visitors, and the pooled rate if nothing differs. With the Workbench numbers, , the standard error is points, and . The logic of probabilities and standard errors is in Foundations: probability.
Example: the z test and the interval on the difference
In statsmodels the test is proportions_ztest, which takes the counts and the visitors as lists, and uses the pooled variance by default.4 The interval on the difference comes from confint_proportions_2indep. I pass method="wald" here so the numbers match the Marketing Analytics chapter, which uses the textbook formula.
from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep
# new headline first, old headline second
trials = [54, 41]
visitors = [1050, 1050]
z, p = proportions_ztest(trials, visitors)
print(f"z = {z:.2f}, p = {p:.2f}")
# z = 1.37, p = 0.17
low, high = confint_proportions_2indep(54, 1050, 41, 1050, method="wald")
print(f"difference: {low:+.2%} to {high:+.2%}")
# difference: -0.54% to +3.02%
The p value of 0.17 says that a gap this size turns up about one time in six when the two pages are identical. The interval says the new headline's true effect is somewhere between a loss of 0.54 points and a gain of 3.02 points. Both readings say the same thing: the test could not tell the headline from nothing. The significance and error margins article covers how to read both.
Step two: put the interval on the lift itself
Here is the first thing the Python version adds. A manager does not think in percentage points of a 4% rate. She thinks in "plus 32%". So give her the interval on that number, the relative lift, rather than on the absolute difference.
You cannot get it by dividing the ends of the difference interval by the baseline, because the baseline is itself an estimate with its own noise. The right tool is an interval for the ratio of the two rates, the risk ratio , and lift is that ratio minus one. confint_proportions_2indep computes it with compare="ratio".5
Example: "plus 32%" becomes "minus 11% to plus 96%"
low_r, high_r = confint_proportions_2indep(54, 1050, 41, 1050, compare="ratio", method="log")
print(f"lift: {low_r - 1:+.0%} to {high_r - 1:+.0%}")
# lift: -11% to +96%
The log method builds the interval on the log of the ratio and transforms it back, which is why it is lopsided: 32% sits much closer to the lower end than to the upper. That asymmetry is honest. Ratios of small counts are skewed, and an interval that pretends otherwise would understate the chance of a big disappointment.
My view: put this line, the lift with its interval, at the top of every test report, and drop the p value to a footnote. "Plus 32%, anywhere from minus 11% to plus 96%" stops a headline rewrite on its own. Nobody reorganises a website on a coin flip once they can see it is one.
A note on defaults, because they bite. If you call confint_proportions_2indep without a method, statsmodels 0.14.6 uses Newcombe's method for a difference and an adjusted log method for a ratio, both of which a review of the available intervals recommends over the textbook Wald formula for small counts.56 The docstring warns that defaults may change between versions. Write the method into the call every time, so the number in your report does not quietly change when someone upgrades.
Step three: the lift worth detecting is a business number
A test is designed backwards from a decision. Before any visitor is randomised, someone has to say how big a lift would change what the business does. That number is the minimum detectable effect, and the Marketing Analytics chapter makes the case for setting it in money. Here it is as a few lines of Python, so that it lives in the same notebook as the sample size it drives.
Example: what each lift is worth to Workbench
Workbench's pricing page gets 2,000 visitors a month, 4% start a trial, a quarter of trials become paying customers at €79 a month, and a customer stays about 22 months.
visitors_per_month = 2_000
trial_rate = 0.04
paid_share = 0.25
price_per_month = 79
months_kept = 22
value_per_customer = price_per_month * months_kept # €1,738
for lift in [0.05, 0.10, 0.15, 0.25]:
extra_trials = visitors_per_month * trial_rate * lift
extra_value = extra_trials * paid_share * value_per_customer
print(f"lift {lift:.0%}: {extra_trials:.0f} extra trials, "
f"€{extra_value:,.0f} of lifetime revenue per month")
# lift 5%: 4 extra trials, €1,738 of lifetime revenue per month
# lift 10%: 8 extra trials, €3,476 of lifetime revenue per month
# lift 15%: 12 extra trials, €5,214 of lifetime revenue per month
# lift 25%: 20 extra trials, €8,690 of lifetime revenue per month
The founders decided that 15%, about €5,200 a month, is the smallest lift worth a redesign and a test. That decision, written down with its reasoning, is the most important line in the test plan. Everything else in this chapter follows from it.
Step four: the sample size, three ways
For two conversion rates, the visitors needed in each arm to detect a gap with a two sided test at level and power are (derivation in Foundations: sample size):
where is the number of visitors per arm, the baseline rate, the rate you want to be able to detect, their average, the standard normal point for a two sided 5% test and the point for 80% power. For Workbench, , , , and the formula gives visitors per arm.
Example: the formula as a function
from math import ceil
from scipy.stats import norm
def visitors_per_arm(p_a, lift, alpha=0.05, power=0.80):
"""Visitors needed in each arm to detect a relative lift on baseline p_a."""
p_b = p_a * (1 + lift)
p_bar = (p_a + p_b) / 2
z_sum = norm.ppf(1 - alpha / 2) + norm.ppf(power)
return ceil(2 * z_sum**2 * p_bar * (1 - p_bar) / (p_b - p_a) ** 2)
print(visitors_per_arm(0.04, 0.15))
# 17944
This is the same formula as the Marketing Analytics chapter and how much data you actually need, so the numbers match to the visitor. statsmodels offers two built in routes to the same question, and they give slightly different answers. That is worth seeing once, because a colleague using a different route will get a different number and someone will ask why.
Example: the two statsmodels routes
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import (proportion_effectsize,
samplesize_proportions_2indep_onetail)
p_a, p_b = 0.04, 0.046
# route 1: Cohen's h and the generic power solver
h = proportion_effectsize(p_b, p_a)
n1 = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.80)
# route 2: the function written for two proportions
# careful: diff is the ABSOLUTE difference, prop2 the control rate
n2 = samplesize_proportions_2indep_onetail(diff=p_b - p_a, prop2=p_a, power=0.80)
print(ceil(n1), ceil(n2))
# 17923 17943
Route 1 converts the two rates into Cohen's h, a difference of arcsine square roots, , and hands it to a generic solver for normal tests.7 Route 2 uses the variance of each rate under the null and the alternative separately.8 Three methods, three answers, 21 visitors apart out of nearly 18,000. None of them is wrong. Pick one, name it in the plan, and stop there.
The difference that does matter is a trap in route 2. Its diff argument is the absolute gap in rates, 0.006, not the relative lift, 0.15. Pass 0.15 by mistake and the function cheerfully returns 70 visitors per arm, a test you could finish before lunch. The comment in the code above is there for that reason.
Step five: what a test you can afford is able to see
The sample size question usually arrives the other way round: given the traffic a page actually gets, what can a test learn? Turn the function around. Given the visitors per arm, find the smallest lift that gives 80% power. There is no neat closed form for the relative lift, so let SciPy's root finder do it: brentq finds where a function crosses zero between two bounds.9
Example: the smallest lift each test could reliably detect
from scipy.optimize import brentq
def smallest_lift(p_a, n, alpha=0.05, power=0.80):
"""The smallest relative lift that n visitors per arm can reliably detect."""
return brentq(lambda lift: visitors_per_arm(p_a, lift, alpha, power) - n, 0.001, 10)
for n in [1_050, 1_500, 3_000, 17_944]:
print(f"{n:>6,} per arm: {smallest_lift(0.04, n):.0%}")
# 1,050 per arm: 69%
# 1,500 per arm: 56%
# 3,000 per arm: 39%
# 17,944 per arm: 15%
The nine day test, at 1,050 per arm, could only reliably see a 69% lift. Nobody expects a headline to lift trials by 69%, so the test was never able to answer its own question. Put this number in every test plan next to the sample size, under the heading "what this test cannot see". It is the most useful sentence a founder can read before agreeing to a test.
Step six: a sample size table for your own baselines
With the function in hand, the table from the Marketing Analytics chapter is one DataFrame. Change the baselines to your own funnel steps and print it for the next planning meeting.
Example: the table, and how long each cell takes
baselines = [0.01, 0.02, 0.04, 0.08, 0.15]
lifts = [0.05, 0.10, 0.15, 0.25, 0.50]
table = pd.DataFrame(
[[visitors_per_arm(b, l) for l in lifts] for b in baselines],
index=[f"{b:.0%}" for b in baselines],
columns=[f"{l:.0%} lift" for l in lifts],
)
print(table)
# 5% lift 10% lift 15% lift 25% lift 50% lift
# 1% 637012 163096 74195 27939 7751
# 2% 315208 80683 36694 13811 3827
# 4% 154306 39476 17944 6747 1865
# 8% 73855 18873 8569 3215 883
# 15% 36311 9258 4194 1566 426
months = 2 * table / visitors_per_month # two arms share the page's traffic
print(months.loc["4%"].round(1))
# 5% lift 154.3
# 10% lift 39.5
# 15% lift 17.9
# 25% lift 6.7
# 50% lift 1.9
At Workbench's baseline, a 15% lift takes 17.9 months of pricing page traffic and a 25% lift takes 6.7. Anything under 10% is a decade or more. The arithmetic is the argument for testing bold changes high in the funnel, where rates are larger, rather than small tweaks at the bottom.
Step seven: generate the Workbench factorial
Now the main experiment. Workbench tests three things on its pricing page at once, each at two levels: the headline (the current feature headline or an outcome headline), a price anchor (the monthly price alone, or next to the crossed out cost of the three tools it replaces) and proof (nothing, or customer logos with a quote from a joiner in Galway). Every combination is a cell, two times two times two makes eight, and every visitor is randomised into one of them. That is a full factorial design.10
What makes it affordable is that each main effect uses every visitor: the headline comparison is the four cells with the outcome headline against the four with the feature headline, 3,000 against 3,000. Three questions for the price of one.
Example: one row per visitor, reproducing the chapter's counts
Real test data arrives as one row per visitor with the cell they saw and whether they converted. So build it that way. The counts per cell are the ones in the Marketing Analytics chapter, 750 visitors each, and the random generator only shuffles who converted, so the totals reproduce exactly.
rng = np.random.default_rng(24)
cells = pd.DataFrame({
"headline": ["feature"] * 4 + ["outcome"] * 4,
"anchor": ["none", "none", "anchor", "anchor"] * 2,
"proof": ["none", "logos"] * 4,
"visitors": 750,
"trials": [30, 36, 25, 50, 34, 40, 29, 54],
})
parts = []
for cell in cells.itertuples():
trial = np.zeros(cell.visitors, dtype=int)
trial[: cell.trials] = 1 # exactly this many trials in the cell
rng.shuffle(trial)
parts.append(pd.DataFrame({
"headline": cell.headline,
"anchor": cell.anchor,
"proof": cell.proof,
"trial": trial,
}))
visits = pd.concat(parts, ignore_index=True)
visits = visits.sample(frac=1, random_state=24).reset_index(drop=True)
print(visits.shape)
print(visits.head(3))
print(visits.dtypes)
# (6000, 4)
# headline anchor proof trial
# 0 outcome anchor logos 0
# 1 feature anchor none 0
# 2 outcome anchor logos 0
# headline str
# anchor str
# proof str
# trial int64
The str data type on the three text columns is pandas 3.0's new default for text. In pandas 2 they would have shown as object.
Step eight: check the split before you look at a single rate
Before reading any result, check that randomisation did what it promised. If you planned equal cells, the counts should be close to equal, and how close is a question a chi square test answers: it compares the observed counts per cell with the expected ones. Kohavi, Tang and Xu call a failure here a sample ratio mismatch and treat it as the first check on any experiment, because a broken split means some visitors were routed by something other than chance, and then every comparison is suspect.11
Example: the split, healthy and broken
from scipy.stats import chisquare
counts = visits.groupby(["headline", "anchor", "proof"]).size()
print(chisquare(counts).pvalue)
# 1.0
broken = counts.copy()
broken.iloc[0] = 640 # one cell short by 110 visitors
print(f"{chisquare(broken).pvalue:.4f}")
# 0.0448
chisquare assumes equal expected counts when you pass only the observed ones.12 The generated data is perfectly balanced, so p is 1. With one cell at 640, p drops to 0.045. That does not prove a bug, but the split is the one place in a test where randomisation promises an exact answer, so I treat a small p here as a reason to read the assignment code before reading any rate. The usual culprits: a variant that loads more slowly so impatient visitors never get counted, a redirect that loses tracking, or bots that hit one URL.
Step nine: the cell table and the main effects
With the split checked, summarise. One group by gives the cell table from the Marketing Analytics chapter.
Example: rates per cell
summary = (
visits.groupby(["headline", "anchor", "proof"])["trial"]
.agg(visitors="size", trials="sum", rate="mean")
)
print(summary.round(4))
# visitors trials rate
# headline anchor proof
# feature anchor logos 750 50 0.0667
# none 750 25 0.0333
# none logos 750 36 0.0480
# none 750 30 0.0400
# outcome anchor logos 750 54 0.0720
# none 750 29 0.0387
# none logos 750 40 0.0533
# none 750 34 0.0453
pandas sorts the levels alphabetically, so "anchor" comes before "none". The pattern is the one the earlier chapter describes: the anchor without proof is the lowest cell in each headline group, the anchor with proof the highest.
The main effect of a factor is the average rate of the four cells where it is on, minus the average of the four where it is off. Since all cells are the same size, that is the same as splitting all 6,000 visitors by the one factor and comparing the halves, which is a plain two proportion test.
Example: three z tests from one loop
on_level = {"headline": "outcome", "anchor": "anchor", "proof": "logos"}
rows = []
for factor, on in on_level.items():
is_on = visits[factor].eq(on)
x_on, n_on = visits.loc[is_on, "trial"].sum(), is_on.sum()
x_off, n_off = visits.loc[~is_on, "trial"].sum(), (~is_on).sum()
z, p = proportions_ztest([x_on, x_off], [n_on, n_off])
low, high = confint_proportions_2indep(x_on, n_on, x_off, n_off, method="wald")
rows.append({"factor": factor, "off": x_off / n_off, "on": x_on / n_on,
"diff_pts": 100 * (x_on / n_on - x_off / n_off),
"z": z, "p": p, "low_pts": 100 * low, "high_pts": 100 * high})
main = pd.DataFrame(rows).set_index("factor")
print(main.round(4))
# off on diff_pts z p low_pts high_pts
# factor
# headline 0.0470 0.0523 0.5333 0.9508 0.3417 -0.5660 1.6327
# anchor 0.0467 0.0527 0.6000 1.0696 0.2848 -0.4993 1.6993
# proof 0.0393 0.0600 2.0667 3.6842 0.0002 0.9685 3.1649
These are the figures in the Marketing Analytics chapter's main effects table to the second decimal. Proof is the only clear effect, 2.07 points with an interval from 0.97 to 3.16. The headline and the anchor both have intervals that include zero, which at 3,000 per side means "this test cannot tell", not "this does nothing": step five says 3,000 per arm can only reliably see a 39% lift.
Step ten: the factorial as a regression
The loop works, but it hides the interaction, and the interaction is why you ran a factorial. A regression gives you every main effect and every interaction in one fit, with standard errors, from the same visitor table.
The model is a linear probability model: ordinary least squares on a 0 or 1 outcome, so each coefficient is a change in the conversion rate.
where is 1 if visitor started a trial and 0 otherwise, , and are the headline, anchor and proof of the visitor's cell coded as plus one for "on" and minus one for "off", is the average rate across all eight cells, each is half the effect of its factor (because moving from minus one to plus one is two steps), and is the part of the outcome the model does not explain. The coding is the whole trick, and the next step shows what happens without it. Each coefficient is an expected change in the rate (Foundations: expected value). Because the outcome is 0 or 1, the error variance differs between cells, so I ask for robust standard errors with cov_type="HC1".
Example: the full model, every effect at once
import statsmodels.formula.api as smf
coded = visits.assign(
H=np.where(visits["headline"].eq("outcome"), 1, -1),
A=np.where(visits["anchor"].eq("anchor"), 1, -1),
P=np.where(visits["proof"].eq("logos"), 1, -1),
)
full = smf.ols("trial ~ H * A * P", data=coded).fit(cov_type="HC1")
print((2 * 100 * full.params).round(2)) # effects in percentage points
# Intercept 9.93
# H 0.53
# A 0.60
# H:A 0.00
# P 2.07
# H:P 0.00
# A:P 1.27
# H:A:P 0.00
H * A * P in a formula expands to all three factors, all three two way interactions and the three way interaction. Doubling the coefficients turns them into effects in the units of the earlier chapter: 0.53, 0.60 and 2.07 points for the main effects, exactly the loop's results, and 1.27 points for the anchor by proof interaction, exactly the "interaction column applied to the cell rates" in the Marketing Analytics chapter. (The doubled intercept means nothing. The intercept itself, 4.97%, is the average rate.) The headline interacts with nothing, so the smaller model drops those terms.
Example: the model worth reporting
model = smf.ols("trial ~ H + A * P", data=coded).fit(cov_type="HC1")
print(model.summary().tables[1])
# ==============================================================================
# coef std err z P>|z| [0.025 0.975]
# ------------------------------------------------------------------------------
# Intercept 0.0497 0.003 17.731 0.000 0.044 0.055
# H 0.0027 0.003 0.952 0.341 -0.003 0.008
# A 0.0030 0.003 1.071 0.284 -0.002 0.008
# P 0.0103 0.003 3.689 0.000 0.005 0.016
# A:P 0.0063 0.003 2.261 0.024 0.001 0.012
# ==============================================================================
Read the A:P row. The anchor by proof interaction has and , the same as the difference of differences in the earlier chapter. The main effect of the anchor, , says the anchor barely matters. The interaction says it matters a lot, in opposite directions, depending on whether proof is on the page.
Step eleven: the coding trap that reverses the story
Here is the trap that the default settings set for you. Pass the text columns straight into the formula and statsmodels, through the Patsy formula language, uses treatment coding: one level of each factor becomes the reference, and every other level is a 0 or 1 dummy.13 With an interaction in the model, the coefficient on the anchor then means "the effect of the anchor when proof is at its reference level". That is not a main effect. It is one slice of the data.
Example: the same data, the default coding
trap = smf.ols("trial ~ C(headline) + C(anchor, Treatment('none')) * C(proof, Treatment('none'))",
data=visits).fit(cov_type="HC1")
print((100 * trap.params).round(2))
# Intercept 4.00
# C(headline)[T.outcome] 0.53
# C(anchor, Treatment('none'))[T.anchor] -0.67
# C(proof, Treatment('none'))[T.logos] 0.80
# C(anchor, Treatment('none'))[T.anchor]:C(proof, Treatment('none'))[T.logos] 2.53
The anchor coefficient is now minus 0.67 points: the anchor's effect on pages without proof. Proof shows plus 0.80 points: its effect on pages without the anchor. A reader who skims this table sees "the anchor hurts, proof barely helps", the exact opposite of what the factorial found. The interaction, 2.53 points, is the full difference of differences rather than half of it.
Nothing in the model is wrong. Both codings fit the same eight cell rates perfectly. What changes is what each coefficient means, and a table that does not say which coding it used cannot be read. My rule: in a two level factorial, always code plus one and minus one. The coefficients are then half the main effects, every column is orthogonal to every other, and dropping a term does not change the others. With treatment coding none of that holds.
Step twelve: read the interaction, and draw it
The regression gives you the interaction as one coefficient. A founder needs it as two numbers. So compute the effect of the anchor separately with and without proof, pooled over both headlines, 1,500 visitors per group.
Example: the anchor in each condition
pooled = visits.groupby(["anchor", "proof"])["trial"].mean()
with_proof = pooled["anchor", "logos"] - pooled["none", "logos"]
without_proof = pooled["anchor", "none"] - pooled["none", "none"]
interaction = with_proof - without_proof
se = np.sqrt((pooled * (1 - pooled) / 1_500).sum())
print(f"anchor without proof {without_proof:+.2%}, with proof {with_proof:+.2%}")
print(f"difference of differences {interaction:.2%}, z = {interaction / se:.2f}, "
f"p = {2 * norm.sf(interaction / se):.3f}")
# anchor without proof -0.67%, with proof +1.87%
# difference of differences 2.53%, z = 2.26, p = 0.024
Without proof, the anchor takes the rate from 4.27% to 3.60%. With proof, it takes it from 5.07% to 6.93%. The standard error of the difference of differences is the square root of summed over the four pooled groups, 1.12 points, and it is twice the standard error of a main effect. That is why an interaction as large as a main effect needs four times the visitors to detect, a point how much data you actually need makes for two by two tests.
When you chart an interaction for a decision, label the two gaps on the chart itself, minus 0.67 and plus 1.87, so the reader does not have to subtract bar heights. Words on charts covers how to do that without clutter.
Example: does the interaction survive a logistic model?
A linear probability model measures effects in percentage points. A logistic regression, the model from logistic regression, lift charts and basket analysis in Python, measures them in log odds. For main effects the two usually agree on direction. For interactions they can disagree, because an interaction on one scale is not the same as an interaction on the other.14
logit = smf.logit("trial ~ H + A * P", data=coded).fit(disp=0)
print(logit.pvalues.round(3))
# Intercept 0.000
# H 0.341
# A 0.521
# P 0.000
# A:P 0.037
The interaction is still there, at rather than 0.024. My view: for a test whose decision is "which page earns more trials", report the linear model, because percentage points are the unit the business uses and the factorial's balance makes it well behaved. Run the logistic version as a check, and if the two disagree about whether an interaction exists, treat the interaction as unconfirmed. Here they agree. At between 0.02 and 0.04, it is real enough to ship the anchor with proof and to confirm it with a second test on the new page, not strong enough to build a pricing philosophy on.
Step thirteen: peeking, shown by simulation
The most common way honest teams fool themselves is by watching the dashboard and stopping when it turns green.15 The test statistic wanders as data arrives, and each look is another chance for it to wander across 1.96. A simulation makes this concrete and costs half a second if you write it with arrays instead of loops, the way NumPy explained recommends.
The setup: 40,000 A/A tests, where both arms truly convert at 4%, each running 30 days with 200 visitors per arm per day. For every test and every day, compute the running z statistic. Then count how often it crosses 1.96 under different reading habits.
Example: 40,000 A/A tests in one array
sim = np.random.default_rng(7)
n_tests, days, per_day, rate = 40_000, 30, 200, 0.04
def z_paths(rate_a, rate_b):
"""Running z statistic after each day, one row per simulated test."""
a = sim.binomial(per_day, rate_a, size=(n_tests, days)).cumsum(axis=1)
b = sim.binomial(per_day, rate_b, size=(n_tests, days)).cumsum(axis=1)
n = per_day * np.arange(1, days + 1)
pooled = (a + b) / (2 * n)
se = np.sqrt(pooled * (1 - pooled) * 2 / n)
with np.errstate(divide="ignore", invalid="ignore"):
z = np.where(se > 0, (b / n - a / n) / se, 0.0)
return z, a / n, b / n
z, _, _ = z_paths(rate, rate) # A/A: both arms truly 4%
crossed = np.abs(z) > 1.96
print(f"read once at day 30: {crossed[:, -1].mean():.1%}")
print(f"every third day: {crossed[:, 2::3].any(axis=1).mean():.1%}")
print(f"every day: {crossed.any(axis=1).mean():.1%}")
# read once at day 30: 5.2%
# every third day: 19.6%
# every day: 28.1%
binomial(200, 0.04) draws a whole day's conversions in one number, cumsum turns days into running totals, and each row of z is one test's path. Read once at the end, about 5% of identical pairs produce a false winner, which is what a 5% test promises. Read every third day, nearly one in five. Read daily, more than one in four. These match the figures in the Marketing Analytics chapter.
Example: false winners by number of looks
looks = {1: [29], 2: [14, 29], 5: [5, 11, 17, 23, 29],
10: list(range(2, 30, 3)), 30: list(range(30))}
by_looks = pd.Series({k: crossed[:, v].any(axis=1).mean() for k, v in looks.items()})
print(by_looks.round(3))
# 1 0.052
# 2 0.084
# 5 0.144
# 10 0.196
# 30 0.281
Step fourteen: if you must look, raise the bar
There are two honest cures. Fix the sample size in advance and read once, the right default for most small business tests. Or use a sequential design that is built for repeated looks. The classic version, from Pocock, uses one stricter threshold at every look, chosen so that the overall false positive rate stays at 5%.16 Modern tools often use always valid p values, which allow looking at any time.17 If your tool does either, fine, as long as you know which. You can also calibrate a simple Pocock style threshold for your own look schedule with the simulation you already have.
Example: the threshold for daily looks
Take each A/A test's largest absolute z across all 30 days. The 95th percentile of those maxima is the bar that only 5% of no difference tests ever cross.
threshold = np.quantile(np.abs(z).max(axis=1), 0.95)
print(f"daily looks need |z| > {threshold:.2f}")
print(f"false winners with that bar: {(np.abs(z) > threshold).any(axis=1).mean():.1%}")
# daily looks need |z| > 2.73
# false winners with that bar: 5.0%
A daily look needs , not 1.96. The price is power: a stricter bar needs more visitors to detect the same lift. There is no free look. This threshold is calibrated to this traffic and this schedule by simulation, which makes it a sound internal rule. For anything with legal or medical stakes, use a published method and its software.
Step fifteen: the winner's curse
Peeking inflates false winners. It also inflates true winners, and this is the part tutorials skip. When a test is too small for the lift it is chasing, it only reaches significance on the days when chance has pushed the observed lift well above the true one. So the winners you ship carry an exaggerated lift, and the forecast built on them falls short. Gelman and Carlin call this a type M error, M for magnitude.18
Example: a real 15% lift, reported as 26% and 34%
Run the same simulation with a real difference: the variant converts at 4.6%, a true lift of 15%, and the test is 6,000 visitors per arm, a third of what step four asked for.
z1, pa1, pb1 = z_paths(0.04, 0.046) # the variant truly lifts by 15%
won = z1 > 1.96
stop_day = np.where(won.any(axis=1), won.argmax(axis=1), -1)
stopped = stop_day >= 0
idx = np.flatnonzero(stopped)
reported = pb1[idx, stop_day[idx]] - pa1[idx, stop_day[idx]]
print(f"declared a winner: {stopped.mean():.0%}, median stop day {np.median(stop_day[idx]) + 1:.0f}")
print(f"median reported lift: {np.median(reported) / 0.04:.0%} (true lift 15%)")
# declared a winner: 56%, median stop day 10
# median reported lift: 34% (true lift 15%)
final_won = z1[:, -1] > 1.96
final_lift = pb1[final_won, -1] / pa1[final_won, -1] - 1
print(f"read once: winner in {final_won.mean():.0%}, mean lift among winners {final_lift.mean():.0%}")
# read once: winner in 37%, mean lift among winners 26%
Read once at day 30, the test finds the real lift only 37% of the time, and the winners it finds report 26% on average. Peek daily and stop on green, and more tests "win", 56%, but the median winner stops on day 10 and reports 34%, more than double the truth. The 32% the Workbench founders celebrated is exactly the kind of number this produces.
This is the strongest argument for the sample size calculation, and it is not the one usually made. A properly powered test is not only less likely to miss a winner. It is the only kind whose winners you can believe at face value. When a small test does win, shrink the forecast: plan on the lower end of the interval, not the point estimate.
Step sixteen: the traps in real test data
Generated data is clean. Real test data comes from a tracking setup, and it breaks in predictable ways. Each of these has quietly flipped a result somewhere.
Visitors in both arms. A visitor who clears cookies, switches device or arrives through a link with a forced variant can be counted in both arms. Their conversion then counts for whichever arm logged it, and the arms are no longer independent. Find them and exclude them, or keep only their first exposure if your assignment is sticky.
The day boundary. Exposure logs are usually in UTC. If you report by day, or cut the test at "midnight", do it in the business's time zone, or a visitor at 11.40pm in June lands on the wrong day. Time series in pandas covers the conversions.
The wrong denominator. Sessions are not visitors. If randomisation is by visitor and you divide by sessions, a variant that brings people back more often looks worse per session while doing better per person. Analyse in the unit you randomised.
Conversions that undo themselves. A trial cancelled within the hour, a test signup by staff, an order refunded the next day. Decide before the test which ones count, and clean them the same way in both arms, as in cleaning data in pandas.
Example: finding crossovers and fixing the day
exposures = pd.DataFrame({
"visitor_id": ["v1", "v2", "v2", "v3", "v4", "v4", "v5"],
"arm": ["A", "B", "B", "A", "A", "B", "B"],
"seen_at": pd.to_datetime([
"2026-06-01 22:15", "2026-06-01 23:40", "2026-06-02 08:05",
"2026-06-02 09:30", "2026-06-02 10:00", "2026-06-03 19:20",
"2026-06-03 23:55"], utc=True),
})
# visitors who saw more than one arm
arms_per_visitor = exposures.groupby("visitor_id")["arm"].nunique()
crossed_over = arms_per_visitor[arms_per_visitor > 1].index
print(list(crossed_over))
# ['v4']
# first exposure per remaining visitor, on the Irish calendar
first_seen = (
exposures[~exposures["visitor_id"].isin(crossed_over)]
.sort_values("seen_at")
.drop_duplicates("visitor_id")
)
first_seen["day_local"] = first_seen["seen_at"].dt.tz_convert("Europe/Dublin").dt.date
print(first_seen)
# visitor_id arm seen_at day_local
# 0 v1 A 2026-06-01 22:15:00+00:00 2026-06-01
# 1 v2 B 2026-06-01 23:40:00+00:00 2026-06-02
# 3 v3 A 2026-06-02 09:30:00+00:00 2026-06-02
# 6 v5 B 2026-06-03 23:55:00+00:00 2026-06-04
Visitor v4 saw both arms and is excluded. Visitor v2 appears twice in the same arm and is counted once. Visitors v2 and v5 arrived just before midnight UTC, which under Irish Standard Time, the summer clock, is already the next day in Cork. On a seven row example this looks fussy. On a real test with a cut at a fixed date and a newsletter sent at 11pm, it decides which arm got the newsletter traffic.
The whole workflow on one page
The protocol from the Marketing Analytics chapter, with the Python call that does each step.
When a test is not worth running at all, the Marketing Analytics chapter and the guide to digital marketing testing methods cover the less expensive instruments.
My view
My view: the sample size calculation is sold as a way to avoid missing winners, and that undersells it. Its real job is to make the winners believable. Every simulation in this chapter points the same way. An underpowered test that "wins" reports a lift that is mostly luck, and a team that ships on it then spends months wondering where the promised trials went. If the traffic cannot carry the test, the honest outputs are "change the lever", "test something bolder" or "decide on judgment and say so". Never "run it anyway and see".
The second part of my view is about code over tools. Testing tools are grand for splitting traffic. For reading results, a notebook with fifteen lines of statsmodels beats any dashboard, because every default is visible: the interval method, the coding, the robust errors, the number of looks. When a result matters, someone will ask how it was computed, and "the tool said so" is not an answer.
And for factorials specifically: code plus one and minus one, always. It is a one line assign, and it is the difference between a table that says the anchor works with proof and a table that says the anchor hurts.
Mistakes worth avoiding
Passing a relative lift where an absolute difference is expected. samplesize_proportions_2indep_onetail wants 0.006, not 0.15. The wrong one returns 70 visitors per arm and nobody blinks.
Leaving the interval method to the default. It can change between statsmodels versions. Write method= every time.
Reading treatment coded coefficients as main effects. With an interaction in the model, they are simple effects at the reference level. Code plus and minus one.
Reading before checking the split. A sample ratio mismatch means the comparison is broken, however good the lift looks.
Peeking without a corrected threshold. Daily looks at 1.96 turn a 5% test into a 28% one. Either read once or raise the bar.
Forecasting from the point estimate of a small winning test. Plan on the lower end of the interval. The winner's curse is real and it always points up.
Analysing sessions when you randomised visitors. The unit of analysis is the unit of randomisation.
For the person who commissions this
You do not need to read the code to judge a test. Ask for these:
| Question | A good answer sounds like |
|---|---|
| Which lift was set as worth detecting, and why? | A percentage with its value in money per month, written before the start |
| How many visitors per arm, and what is the smallest lift the test can see? | Both numbers, with the method named |
| Was the split checked? | Yes, a chi square on the cell counts, before any rate was read |
| How often was the result looked at? | Once, at the planned end, or with a stricter threshold set in advance |
| What is the lift, with its interval? | "Plus 15%, between plus 4% and plus 27%", not "significant" |
| For a factorial: how were the factors coded? | Plus and minus one, with interactions reported in percentage points |
| What goes into the forecast? | The lower end of the interval, not the point estimate |
| What happens if the answer is "no difference"? | A decision written down before the start |
Testing, dashboards and data science are a core part of the work I do for clients, from the test plan to the decision memo: the Data Science page describes how I work, and where the tests run on ad landing pages they sit inside Performance Marketing. My prices are published at transparent pricing, and the code, the accounts and the data stay yours.
Conclusion
An A/B test in Python is a handful of calls: proportions_ztest for the test, confint_proportions_2indep for the interval on the difference and, with compare="ratio", on the lift, a ten line function for the sample size, and brentq to run it backwards. A factorial is one visitor table and one regression with plus and minus one coding, which reads every main effect and the interaction in one fit and reproduces the Workbench results exactly. The hard part is not the code. It is deciding the lift worth having before the start, checking the split, reading once, and refusing to believe a big win from a small test. The simulations show why: peeking turns 5% false winners into 28%, and a true 15% lift found by a small test gets reported as 26% or more.
The next chapter of this series, media mix modelling in Python, takes the question from a single page to the whole budget: what each channel's spend actually does, with adstock and saturation, when you cannot randomise at all.
