Bayesian A/B Testing in Python: Beta-Binomial Posteriors and P(B > A)

Run a Bayesian A/B test on conversion rates in Python with SciPy. Build Beta posteriors, compute the probability that B beats A, a credible interval for the lift, and the expected loss of each decision.

For a conversion-rate A/B test, the Bayesian version needs only scipy.stats.beta. Start each variant with a Beta(1, 1) prior, add its conversions and non-conversions to get the posterior Beta(1 + conversions, 1 + non_conversions), then draw samples from both posteriors and compare them. The share of draws where B is higher is P(B > A), and the draws of B - A give a credible interval for the difference. No PyMC or MCMC is needed, because the Beta prior and binomial data combine in closed form.

Quick Example

The test below has 6,000 users per arm: control converts 330 (5.5%), the variant 372 (6.2%). It runs without downloads.

import numpy as np
from scipy import stats

n_a, x_a = 6000, 330   # control: users, conversions
n_b, x_b = 6000, 372   # variant

# Beta(1, 1) prior = uniform; posterior is Beta(1 + conversions, 1 + non-conversions)
post_a = stats.beta(1 + x_a, 1 + n_a - x_a)
post_b = stats.beta(1 + x_b, 1 + n_b - x_b)

rng = np.random.default_rng(31)
draws_a = post_a.rvs(200_000, random_state=rng)
draws_b = post_b.rvs(200_000, random_state=rng)

diff = draws_b - draws_a
lift = draws_b / draws_a - 1
lo, hi = np.percentile(diff, [2.5, 97.5])

print("P(B > A):", round((draws_b > draws_a).mean(), 3))
print("Difference, mean:", round(diff.mean() * 100, 2), "pp; 95% credible interval:",
      round(lo * 100, 2), "to", round(hi * 100, 2), "pp")
print("Relative lift, median:", round(np.median(lift) * 100, 1), "%; 95% interval:",
      np.round(np.percentile(lift, [2.5, 97.5]) * 100, 1))

The output:

  • P(B > A) is 0.949.
  • The difference in conversion rate averages 0.70 percentage points, with a 95% credible interval of -0.14 to 1.54 pp.
  • The relative lift has a median of 12.7%, with a 95% interval of -2.3% to 30.2%.

Two overlapping bell curves for the conversion rate posteriors, control centered near 5.5% and variant near 6.2%, with moderate overlap

Each curve is what the data says about that variant's true conversion rate. The curves overlap, which is why the answer isn't certain. Comparing paired draws from the two posteriors turns the overlap into a single probability.

How the Beta-Binomial Model Works

A conversion is a yes/no outcome, so the number of conversions out of n users follows a binomial distribution with an unknown rate p. The Beta distribution is a conjugate prior for that rate: if the prior is Beta(a, b) and you observe x conversions out of n, the posterior is exactly Beta(a + x, b + n - x).

Beta(1, 1) is the flat prior: every rate from 0 to 1 is equally plausible before seeing data. Its two parameters add one pseudo-conversion and one pseudo-non-conversion to the counts, so it is overwhelmed by real data almost immediately.

Because the posterior is a known distribution, you can ask post_a.mean(), post_a.interval(0.95) or post_a.ppf(0.025) directly. Sampling is only needed for questions that combine the two variants, such as the difference or ratio.

Read the Posterior of the Difference

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 4))
ax.hist(diff * 100, bins=120, color="#0d9488", alpha=0.85)
ax.axvline(0, color="black", lw=1.5)
ax.axvline(lo * 100, color="#f59e0b", ls="--")
ax.axvline(hi * 100, color="#f59e0b", ls="--", label="95% credible interval")
ax.set(xlabel="B minus A (percentage points)", ylabel="Posterior draws")
ax.legend()

Left: histogram of posterior draws of B minus A, mostly right of zero with a 95% credible interval from -0.14 to 1.54 percentage points. Right: a falling curve of the probability that the true relative lift exceeds each threshold, crossing 50% near 12.7%

The left panel is the posterior of B - A. Most of the mass is right of zero, but the lower edge of the interval is slightly below it. The right panel answers a more useful question than "is it above zero": the probability that the true lift is at least X%. Here that is 83% for a lift of at least 5%, and 50% at about 13%. A Bayesian result can be read straight off this curve against whatever lift the business cares about.

Expected Loss: What You Give Up by Choosing Wrong

P(B > A) ignores how big the mistake could be. Expected loss averages the cost of each decision across the posterior, in conversion-rate points:

loss_ship_b = np.maximum(draws_a - draws_b, 0).mean()   # B shipped, A was better
loss_keep_a = np.maximum(draws_b - draws_a, 0).mean()   # A kept, B was better
print(round(loss_ship_b * 100, 4), "pp lost if you ship B")
print(round(loss_keep_a * 100, 4), "pp lost if you keep A")

Shipping B has an expected loss of 0.009 pp, and keeping A has one of 0.708 pp. Even in the 5% of worlds where B is worse, it is only slightly worse. A common rule is to ship the variant when its expected loss drops under a "threshold of caring" fixed in advance, such as 0.1 pp.

Bayesian vs Frequentist Results on the Same Data

Running the usual two-proportion z-test on the same counts with statsmodels gives p = 0.102, and its 95% confidence interval for the difference is -0.14 to 1.54 pp. That is almost identical to the credible interval above (-0.14 to 1.54 pp). With a flat prior and this much data the numbers agree, and the difference is in how they are phrased:

Frequentist Bayesian
Headline number p = 0.102 P(B > A) = 94.9%
Interval means If the test were repeated, 95% of such intervals would contain the true value Given the data and prior, there is a 95% chance the true value is in it
Answers "how likely is B better?" No Yes
Decision rule Reject at p < 0.05 Probability or expected-loss threshold you choose

P(B > A) is not a p-value, though with a flat prior it lines up with a one-sided one. Here P(B > A) of 94.9% goes with a one-sided p of about 0.051, which is the two-sided 0.102 halved. For the frequentist workflow, see A/B Test Analysis in Python.

How Much Does the Prior Matter?

An informative prior pulls estimates toward what you already believe about the conversion rate. This example uses Beta(5.5, 94.5), a 5.5% rate worth 100 users of evidence, against the flat prior, on a small test (400 per arm, 22 vs 31 conversions) and on the large one.

Two panels of relative lift posteriors under a flat and an informative prior; on the small test the informative prior shrinks the lift and cuts off the right tail, on the large test the two curves are identical

With 400 users per arm, the flat prior gives a median relative lift of 39.7% (95% interval -16% to 138%), and the informative prior pulls that to 33.1% (-17% to 117%) and cuts the heavy right tail. P(B > A) moves from 0.90 to 0.88. With 6,000 per arm the two priors give the same answer (median lift 12.8% vs 12.6%, P(B > A) 0.949 vs 0.948). The data dominates once the sample is large, so the prior only matters in small tests.

Use informative priors when you have solid history, for example past tests on the same page, and say what you used. If you can't justify one, use Beta(1, 1).

Peeking Still Has a Cost

A popular claim is that Bayesian tests let you stop whenever you like. The posterior is a valid summary of the data at any moment, but a decision rule that says "stop as soon as P(B > A) crosses 95%" is still a stopping rule with error rates. In a simulation of 2,000 A/A tests (both arms at 5.5%, so no real difference), checking every 500 users up to 10,000 per arm and stopping if P(B > A) went above 95% or below 5%, 43% of the runs ended with a "winner". Fix the sample size or the stopping rule in advance, and size the test with a power analysis.

Practical Tips

  • Use random_state=rng and 100,000+ draws. Tail probabilities such as P(lift > 20%) need many draws to be stable. The rvs calls are cheap.
  • Report the lift curve or an interval, not only P(B > A). 95% on a 0.01 pp improvement is not worth shipping.
  • Conjugacy only covers simple metrics. This closed form works for conversion rates. For revenue per user, ratio metrics or hierarchical models you need PyMC or a bootstrap: see Bootstrap Confidence Intervals for A/B Tests.
  • Several variants: draw from each posterior and take the argmax per draw to get P(each variant is best).

Similar Topics