A/B test statistical significance tells you whether the difference between two versions of a page is larger than what random variation alone would produce. Most testing tools show a green badge when a test is significant, but they rarely show how that number was computed, what the confidence interval for the lift looks like, or whether the test had enough traffic to detect a realistic effect in the first place. This guide computes significance for a conversion-rate test in Python with statsmodels and SciPy: the two-proportion z-test and its formula, a confidence interval for the difference, the sample size you need before you start, a sample ratio mismatch check that catches broken splits, and the peeking problem that turns many winning tests into false positives. Every script is complete and runs from the command line.

A/B test statistical significance workflow in Python: plan the sample size, check the traffic split for SRM, run a two-proportion z-test, read the confidence interval and decide
Plan the sample size, check the split, then test: the p-value only means something if the first two steps were done.

From my own work: When clients show me a winning test, the first questions I ask are how many visitors per variant it had, whether the split was close to 50/50 and whether someone stopped it the day it turned green. Those three answers decide whether the result is worth shipping far more often than the p-value itself.

What A/B test statistical significance means

In a conversion test you compare two proportions: conversions divided by visitors for control (A) and for the variant (B). The null hypothesis is that both have the same true conversion rate. The p-value is the probability of seeing a difference at least as large as the one you observed if the null hypothesis were true. A p-value below your chosen significance level, usually 0.05, is called statistically significant.

That definition matters because of what it does not say. A p-value of 0.03 is not a 97 percent chance that B is better, and it says nothing about how large the improvement is. The confidence interval for the difference answers the size question, and the sample size plan answers whether you could have detected a meaningful difference at all.

Term Meaning in a conversion test Typical setting
Significance level (alpha) Accepted false positive rate when there is no real difference 0.05
Power (1 minus beta) Chance of detecting the effect if it really exists at the planned size 0.80
Minimum detectable effect (MDE) Smallest lift worth detecting, set before the test Relative lift such as 10 percent
p-value How surprising the data are if A and B are equal Compared with alpha once, at the planned end
Confidence interval Range of plausible values for the true difference 95 percent

Calculate A/B test significance in Python

statsmodels provides the two-proportion z-test as proportions_ztest (statsmodels: proportions_ztest) and a confidence interval for the difference of two independent proportions as confint_proportions_2indep (statsmodels: confint_proportions_2indep). The script below also runs a sample ratio mismatch check with SciPy, which is covered in its own section. Install the libraries in a virtual environment first:

python3 -m venv .venv
. .venv/bin/activate
pip install statsmodels scipy
"""A/B test significance for a conversion-rate experiment.

Usage: python ab_test.py 10000 520 10050 584
       (visitors_a conversions_a visitors_b conversions_b)
"""
import sys

from scipy.stats import chisquare
from statsmodels.stats.proportion import confint_proportions_2indep, proportions_ztest

ALPHA = 0.05


def srm_check(n_a: int, n_b: int, expected_share_a: float = 0.5) -> float:
    total = n_a + n_b
    expected = [total * expected_share_a, total * (1 - expected_share_a)]
    return chisquare([n_a, n_b], f_exp=expected).pvalue


def analyse(n_a: int, x_a: int, n_b: int, x_b: int) -> dict:
    p_a, p_b = x_a / n_a, x_b / n_b
    z, p_value = proportions_ztest(count=[x_b, x_a], nobs=[n_b, n_a], alternative="two-sided")
    low, high = confint_proportions_2indep(
        x_b, n_b, x_a, n_a, method="newcomb", compare="diff", alpha=ALPHA
    )
    return {
        "rate_a": p_a,
        "rate_b": p_b,
        "abs_lift": p_b - p_a,
        "rel_lift": (p_b - p_a) / p_a,
        "z": z,
        "p_value": p_value,
        "ci_low": low,
        "ci_high": high,
        "srm_p": srm_check(n_a, n_b),
    }


if __name__ == "__main__":
    n_a, x_a, n_b, x_b = map(int, sys.argv[1:5])
    r = analyse(n_a, x_a, n_b, x_b)

    if r["srm_p"] < 0.001:
        print(f"WARNING: sample ratio mismatch (p = {r['srm_p']:.2g}). Fix the split before reading results.")

    print(f"Control  : {r['rate_a']:.2%}  ({x_a}/{n_a})")
    print(f"Variant  : {r['rate_b']:.2%}  ({x_b}/{n_b})")
    print(f"Lift     : {r['abs_lift'] * 100:+.2f} pp  ({r['rel_lift']:+.1%} relative)")
    print(f"95% CI   : {r['ci_low'] * 100:+.2f} pp to {r['ci_high'] * 100:+.2f} pp")
    print(f"z = {r['z']:.3f}, p = {r['p_value']:.4f}")
    verdict = "significant" if r["p_value"] < ALPHA else "not significant"
    print(f"Result   : {verdict} at alpha = {ALPHA}")

With a made-up example of 10,000 visitors and 520 conversions for control against 10,050 visitors and 584 conversions for the variant:

$ python ab_test.py 10000 520 10050 584
Control  : 5.20%  (520/10000)
Variant  : 5.81%  (584/10050)
Lift     : +0.61 pp  (+11.7% relative)
95% CI   : -0.02 pp to +1.24 pp
z = 1.896, p = 0.0579
Result   : not significant at alpha = 0.05

An 11.7 percent relative lift sounds like a winner, but the p-value is just above 0.05 and the confidence interval includes zero. The honest summary is that the variant may be better, by anything from roughly nothing to about 1.2 percentage points, and this test cannot tell which. The right response is not to rerun the numbers until they cross the line, but to check whether the test reached its planned sample size.

The two-proportion z-test by hand

The z-test is simple enough to write out, which helps when you need to check a tool’s numbers. It uses the pooled conversion rate under the null hypothesis to estimate the standard error of the difference, as described in the NIST engineering statistics handbook (NIST: comparing two proportions):

from math import sqrt

from scipy.stats import norm


def two_proportion_z(n_a, x_a, n_b, x_b):
    p_a, p_b = x_a / n_a, x_b / n_b
    pooled = (x_a + x_b) / (n_a + n_b)
    se = sqrt(pooled * (1 - pooled) * (1 / n_a + 1 / n_b))
    z = (p_b - p_a) / se
    p_value = 2 * norm.sf(abs(z))      # two-sided
    return z, p_value


print(two_proportion_z(10000, 520, 10050, 584))
# (1.896..., 0.0579...)

The result matches statsmodels. The normal approximation is reliable when each group has a reasonable number of conversions and non-conversions, which is the case for typical website tests. With very small counts, use Fisher’s exact test (scipy.stats.fisher_exact) instead. The confidence interval in the main script uses the Newcombe method rather than the simple Wald interval, because Wald intervals are too narrow when conversion rates are low.

Sample size and minimum detectable effect

Decide the sample size before the test starts. It depends on the baseline conversion rate, the smallest lift you care about, alpha and power. statsmodels solves it with NormalIndPower using Cohen’s h as the effect size (statsmodels: NormalIndPower):

"""Visitors needed per variant for a two-sided test on conversion rate.

Usage: python sample_size.py 0.05 0.10   (baseline rate, relative MDE)
"""
import math
import sys

from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize

baseline = float(sys.argv[1])
relative_mde = float(sys.argv[2])
target = baseline * (1 + relative_mde)

effect = proportion_effectsize(target, baseline)  # Cohen's h
n = NormalIndPower().solve_power(effect_size=effect, alpha=0.05, power=0.8, ratio=1.0, alternative="two-sided")

print(f"Baseline {baseline:.2%} -> target {target:.2%} (Cohen's h = {effect:.4f})")
print(f"Visitors per variant: {math.ceil(n):,}")
print(f"Total visitors:       {math.ceil(n) * 2:,}")

Running it for a few common scenarios at alpha 0.05 and 80 percent power gives:

Baseline rate Relative MDE Visitors per variant
5% 20% (5.0% to 6.0%) 8,143
5% 10% (5.0% to 5.5%) 31,218
2% 10% (2.0% to 2.2%) 80,638

Halving the detectable effect roughly quadruples the required traffic, and lower baseline rates need more visitors for the same relative lift. This is why small sites struggle to test small changes and should test bolder ones, or optimise for a higher-volume step such as clicks to checkout rather than completed orders. The framework in conversion rate optimization without big traffic covers how to prioritise when traffic is limited. Divide the required total by your daily eligible traffic to get the duration, and round up to whole weeks so weekday and weekend behaviour are both represented.

Check for sample ratio mismatch first

If you split traffic 50/50 but one variant received noticeably more visitors than the other, something is broken: a redirect that drops some users, a bot filter applied to one side, a caching layer, or tracking that fails on the variant page. Results from such a test are not trustworthy no matter what the p-value says. A chi-square goodness-of-fit test compares the observed counts with the expected split (SciPy: chisquare). A threshold of p < 0.001 is a common convention, chosen strict on purpose because you run this check on every test:

$ python ab_test.py 10000 520 10600 584
WARNING: sample ratio mismatch (p = 2.9e-05). Fix the split before reading results.
Control  : 5.20%  (520/10000)
Variant  : 5.51%  (584/10600)
...

A difference of 600 visitors on 20,000 looks small, but it is very unlikely under a true 50/50 split. Investigate the assignment and tracking before looking at conversions. If the split is intentionally uneven, pass the planned share to srm_check.

The peeking problem: when to stop a test

A fixed-sample test controls the false positive rate at alpha only if you look at the p-value once, at the planned end. Checking the result every day and stopping as soon as it drops below 0.05 gives chance many opportunities to cross the line, and the real false positive rate ends up far higher than 5 percent. A short simulation shows it on your own machine:

import numpy as np
from statsmodels.stats.proportion import proportions_ztest

rng = np.random.default_rng(1)
RATE, DAILY, DAYS, RUNS = 0.05, 500, 28, 2000   # A and B identical: no real effect

false_wins_peeking = false_wins_fixed = 0
for _ in range(RUNS):
    a = rng.binomial(1, RATE, (DAYS, DAILY)).sum(axis=1).cumsum()
    b = rng.binomial(1, RATE, (DAYS, DAILY)).sum(axis=1).cumsum()
    n = DAILY * np.arange(1, DAYS + 1)
    pvals = [proportions_ztest([b[d], a[d]], [n[d], n[d]])[1] for d in range(DAYS)]
    false_wins_peeking += any(p < 0.05 for p in pvals)   # stop at first "significant" day
    false_wins_fixed += pvals[-1] < 0.05                 # look once at the end

print(f"False positives, daily peeking: {false_wins_peeking / RUNS:.1%}")
print(f"False positives, fixed horizon: {false_wins_fixed / RUNS:.1%}")

Both variants have the same true rate in this simulation, so every win is a false positive. The fixed-horizon share stays close to 5 percent, while the daily-peeking share comes out several times higher. Run it and see the numbers for your own traffic pattern. If you need to monitor tests continuously, use a method designed for it, such as a sequential test with an alpha spending plan, or a tool that implements always-valid inference, instead of repeatedly applying a fixed-sample test.

How to report and act on the result

  • Report the interval, not just the verdict. “Variant B: +0.61 percentage points, 95 percent CI -0.02 to +1.24, p = 0.058” tells the team far more than “not significant”.
  • One primary metric. Decide it before the test. If you test ten metrics at alpha 0.05, one will often look significant by chance; adjust with a Bonferroni or Holm correction (statsmodels.stats.multitest.multipletests) when several metrics matter equally.
  • Check guardrails. A variant that lifts sign-ups but raises refunds or page load time is not a win. Speed regressions in particular change conversion on their own.
  • Segment carefully. Desktop versus mobile splits are useful for understanding, but each segment has less power, so treat segment wins as hypotheses for the next test.
  • Count the right unit. Randomise and count by user, not by page view, or the independence assumption behind the z-test breaks.

Accurate conversion counts are the foundation of all of this. If purchases are tracked in the browser only, ad blockers and consent choices remove some of them unevenly; server-side events, as in the Meta Conversions API guide or server-side analytics in Next.js, make the numbers that feed your test more complete. Fast, stable pages also reduce noise between variants, which is where passing Core Web Vitals on mobile pays off.

A/B test statistical significance checklist

  • Primary metric, alpha, power and MDE written down before the test.
  • Sample size calculated and converted into whole weeks of traffic.
  • Randomisation by user; the same user always sees the same variant.
  • Sample ratio mismatch checked before any conversion numbers are read.
  • Significance tested once at the planned end, or with a proper sequential method.
  • Result reported as lift with a confidence interval and the p-value.
  • Guardrail metrics checked; segment findings treated as new hypotheses.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

How do I calculate statistical significance for an A/B test in Python?

For conversion rates, run a two-proportion z-test with statsmodels.stats.proportion.proportions_ztest, passing conversions and visitors for both variants. Add confint_proportions_2indep for a confidence interval of the difference, and compare the p-value with your planned alpha once the planned sample size is reached.

What p-value means an A/B test is significant?

By convention a p-value below 0.05 is called significant, which corresponds to accepting a 5 percent false positive rate when there is no real difference. The threshold should be chosen before the test, and the p-value should be read once at the planned end.

How many visitors do I need for an A/B test?

It depends on the baseline conversion rate and the smallest lift you want to detect. At a 5 percent baseline, detecting a 10 percent relative lift with 80 percent power needs about 31,000 visitors per variant; detecting a 20 percent lift needs about 8,000.

What is sample ratio mismatch?

It is a significant difference between the planned and the observed traffic split, for example 10,000 versus 10,600 visitors in a 50/50 test. It points to a bug in assignment or tracking, and the test results should not be trusted until it is fixed.

Can I stop an A/B test as soon as it becomes significant?

Not with a standard fixed-sample test. Stopping at the first significant result inflates the false positive rate well above alpha. Either wait for the planned sample size or use a sequential testing method designed for continuous monitoring.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.