To find the sample size for an A/B test in Python, convert your baseline and target conversion rates to an effect size with proportion_effectsize, then call NormalIndPower().solve_power(...) from statsmodels, leaving nobs1 out so it solves for it. For a revenue-style metric, use TTestIndPower with Cohen's d. The code below targets statsmodels 0.14.
Quick Example
A product has an 8% conversion rate and you want to detect a lift to 9% (one percentage point) with the usual 5% significance level and 80% power:
import numpy as np
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
baseline, target = 0.08, 0.09
effect = proportion_effectsize(target, baseline) # Cohen's h
n_per_group = NormalIndPower().solve_power(effect_size=effect, alpha=0.05,
power=0.8, ratio=1.0)
print(f"Cohen's h = {effect:.4f}")
print(f"users per group: {int(np.ceil(n_per_group)):,}")
That prints Cohen's h of 0.0359 and 12,199 users per group, so about 24,400 in total. solve_power solves for whichever of effect_size, nobs1, alpha, and power you leave as None. nobs1 is the size of the first group, and ratio is the second group's size divided by the first (1.0 for an even split).
What Do Power, Alpha, and Minimum Detectable Effect Mean?
Four numbers are tied together, and fixing three gives you the fourth:
- Alpha (significance level): the false positive rate you accept when there is no real effect. 0.05 is the default.
- Power: the chance of detecting the effect when it is real. 0.8 is the usual target, so you accept missing a real lift one time in five.
- Effect size / minimum detectable effect (MDE): the smallest lift worth detecting. Choose it from the business, not from what your traffic can detect. If a 0.2 pp lift would not change a decision, don't size the test for it.
- Sample size: the thing you usually solve for.
Power is a property of the design you pick before the test runs. Computing it afterward from the observed effect ("post-hoc power") only restates the p-value and adds nothing.
Plot Power Curves for Different Lifts
A power curve shows how power grows with sample size. power() takes the same arguments as solve_power, with nobs1 filled in and power left out, and it accepts an array of sample sizes:
import matplotlib.pyplot as plt
power_model = NormalIndPower()
ns = np.arange(500, 40001, 250)
fig, ax = plt.subplots(figsize=(7.5, 4.8))
colors = ["#0ea5e9", "#7c3aed", "#e11d48", "#f59e0b"]
for lift, color in zip([0.005, 0.01, 0.015, 0.02], colors):
h = proportion_effectsize(baseline + lift, baseline)
pw = power_model.power(effect_size=h, nobs1=ns, alpha=0.05, ratio=1.0)
ax.plot(ns, pw, color=color, lw=2,
label=f"+{lift * 100:.1f} pp ({lift / baseline:.1%} relative)")
ax.axhline(0.8, color="#64748b", ls="--", lw=1)
ax.text(40000, 0.81, "80% power", ha="right", va="bottom", color="#475569")
ax.set(xlabel="Users per group", ylabel="Power", ylim=(0, 1.02),
title="Power vs sample size (baseline conversion 8%, alpha 0.05)")
ax.xaxis.set_major_formatter(lambda v, _: f"{v / 1000:.0f}k")
ax.legend(loc="lower right", title="True lift")

A 2 pp lift crosses 80% power at about 3,200 users per group, a 1 pp lift at about 12,200, and a 0.5 pp lift is still under 75% at 40,000 users per group. Halving the effect you want to detect roughly quadruples the sample you need, because required sample size scales with one over the effect squared.
NormalIndPower().plot_power(...) draws a similar chart in one call if you don't need to style it.
How Does Sample Size Change with the Baseline Rate?
The same relative lift is cheaper to detect on a higher-baseline metric, because a 10% lift on a 20% rate is a bigger absolute difference than a 10% lift on a 2% rate. This sweeps relative lift for three baselines on a log axis:
fig, ax = plt.subplots(figsize=(7.5, 4.8))
rel_lifts = np.linspace(0.04, 0.30, 60)
for base, color in zip([0.02, 0.08, 0.20], ["#7c3aed", "#0ea5e9", "#f59e0b"]):
sizes = [NormalIndPower().solve_power(proportion_effectsize(base * (1 + rl), base),
alpha=0.05, power=0.8) for rl in rel_lifts]
ax.plot(rel_lifts * 100, sizes, color=color, lw=2, label=f"baseline {base:.0%}")
ax.set_yscale("log")
ax.set(xlabel="Minimum detectable effect (relative lift, %)",
ylabel="Users per group (log scale)",
title="Smaller effects and lower baselines need far more users")
ax.yaxis.set_major_formatter(lambda v, _: f"{v:,.0f}")
ax.legend()

For a 10% relative lift at 80% power, a 2% baseline needs about 78,000 users per group, an 8% baseline needs about 18,000, and a 20% baseline needs about 6,300. If your traffic can't reach the number, the choices are to accept a larger MDE, run longer, or reduce variance (below).
Cross-Check the Answer with a Simulation
To confirm the formula, simulate the experiment many times at the planned sample size and count how often the test rejects:
from statsmodels.stats.proportion import proportions_ztest
rng = np.random.default_rng(5)
n = int(np.ceil(n_per_group))
runs = 2000
hits = 0
for _ in range(runs):
a = rng.binomial(n, baseline)
b = rng.binomial(n, target)
_, p = proportions_ztest([b, a], [n, n])
hits += p < 0.05
print("simulated power:", hits / runs)
This prints 0.791 for 2,000 runs, close to the 0.80 target (the simulation itself has a standard error of about 0.009). Simulating is also the practical route when your metric or test isn't covered by a closed-form power function.
Sample Size for a Revenue or Mean Metric
For a continuous metric, use TTestIndPower with the effect size as Cohen's d: the difference you want to detect divided by the metric's standard deviation. Take the standard deviation from historical data.
from statsmodels.stats.power import TTestIndPower
sd = 40.0 # std dev of revenue per user, from past data
mde = 2.0 # smallest lift worth detecting, in dollars
d = mde / sd
n_t = TTestIndPower().solve_power(effect_size=d, alpha=0.05, power=0.8)
print(f"d = {d:.3f}, users per group: {int(np.ceil(n_t)):,}")
Detecting a $2 lift when revenue per user has a $40 standard deviation (d = 0.05) takes 6,281 users per group. Heavy-tailed metrics like revenue have large standard deviations, so they usually need far more users than conversion rates.
Reduce the Sample Size with Variance Reduction
Variance enters the effect size through the denominator, so anything that shrinks it cuts the sample. If a pre-experiment covariate has correlation rho with the metric, CUPED shrinks the variance by a factor of 1 - rho**2:
rho = 0.6
n_cuped = TTestIndPower().solve_power(effect_size=mde / (sd * np.sqrt(1 - rho**2)),
alpha=0.05, power=0.8)
print(f"with CUPED (rho={rho}): {int(np.ceil(n_cuped)):,} users per group")
A correlation of 0.6 cuts the requirement from 6,281 to 4,020 users per group, about 36% fewer.
Can I Use statsmodels' Proportion Functions Directly?
Yes. samplesize_proportions_2indep_onetail takes the absolute difference and the baseline instead of Cohen's h, and despite the name it defaults to alternative="two-sided":
from statsmodels.stats.proportion import samplesize_proportions_2indep_onetail
n = samplesize_proportions_2indep_onetail(diff=0.01, prop2=0.08, power=0.8)
print(f"{n:,.0f}")
It returns about 12,208 per group. That is within 0.1% of the Cohen's h answer, because the two use slightly different variance approximations. Either is fine for planning. Its counterpart power_proportions_2indep(diff, prop2, nobs1) returns power for a given sample size.
Which Power Function Should I Use?
| Metric | Function | Effect size input |
|---|---|---|
| Conversion rate, click-through | NormalIndPower + proportion_effectsize |
Cohen's h from two proportions |
| Conversion rate, absolute difference | samplesize_proportions_2indep_onetail |
Difference and baseline rate |
| Revenue, time on page, order value | TTestIndPower |
Cohen's d (difference / std dev) |
| Anything unusual (ratios, heavy tails) | Simulation | Draw data like yours and run your analysis |
Practical Tips
- Fix the sample size before the test starts, and stick to it. Stopping as soon as p crosses 0.05 inflates false positives well beyond 5%. If you need to look early, use a sequential method designed for it.
- Size to the smallest effect you'd act on, then check whether traffic allows it. Reverse-engineering the MDE from the traffic you have is fine, but say so.
- Convert users to days. Divide total users by daily eligible traffic, then round up to whole weeks so every weekday is covered equally.
- Remember the two-sided default.
alternative="two-sided"needs more users than a one-sided test. Use one-sided only if a negative result would never change your decision. - Adjust for multiple metrics or variants. Run the calculation with
alphadivided by the number of comparisons (Bonferroni) if you will test several variants against control.