# A/B Test Analysis in Python: Conversion Rate and Revenue

> How to analyze an A/B test in Python with statsmodels and SciPy. Run a two-proportion z-test on conversion rate, a Welch t-test on revenue per user, compute confidence intervals for the lift, and plot the results.

Source: https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: A/B Testing | Tags: ab testing, experimentation, statsmodels, scipy, confidence interval, hypothesis testing, conversion rate

To analyze an A/B test in Python, use `proportions_ztest` from statsmodels for a conversion rate (a yes/no metric) and `scipy.stats.ttest_ind(..., equal_var=False)` for a continuous metric like revenue per user. Report the lift with a confidence interval, not just a p-value. This post runs both tests on one simulated checkout experiment and plots the result. The code uses statsmodels 0.14 and SciPy 1.18.

## Quick Example

The data is simulated: 10,000 users per arm, a checkout redesign that nudges the conversion rate from about 11% to 12.6%, and order values drawn from a skewed (lognormal) distribution. Users who don't convert have revenue of 0.

```python
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.proportion import confint_proportions_2indep, proportions_ztest

rng = np.random.default_rng(2024)
n = 10_000
group = np.repeat(["control", "treatment"], n)
converted = np.concatenate([rng.random(n) < 0.110, rng.random(n) < 0.126])
order_value = rng.lognormal(mean=3.7, sigma=0.6, size=2 * n).round(2)
df = pd.DataFrame({
    "group": group,
    "converted": converted.astype(int),
    "revenue": np.where(converted, order_value, 0.0),
})
ctrl = df[df["group"] == "control"]
trt = df[df["group"] == "treatment"]

# Conversion rate: two-proportion z-test
counts = np.array([trt["converted"].sum(), ctrl["converted"].sum()])
nobs = np.array([len(trt), len(ctrl)])
z, p_conv = proportions_ztest(counts, nobs)
diff_lo, diff_hi = confint_proportions_2indep(counts[0], nobs[0], counts[1], nobs[1],
                                              method="wald")
print(f"conversion: {ctrl['converted'].mean():.2%} -> {trt['converted'].mean():.2%}, "
      f"diff CI [{diff_lo:.2%}, {diff_hi:.2%}], p = {p_conv:.4f}")

# Revenue per user: Welch's t-test
res = stats.ttest_ind(trt["revenue"], ctrl["revenue"], equal_var=False)
ci = res.confidence_interval(0.95)
print(f"revenue/user: ${ctrl['revenue'].mean():.2f} -> ${trt['revenue'].mean():.2f}, "
      f"diff CI [${ci.low:.2f}, ${ci.high:.2f}], p = {res.pvalue:.4f}")
```

The output:

```text
conversion: 10.95% -> 12.20%, diff CI [0.36%, 2.14%], p = 0.0057
revenue/user: $5.23 -> $5.96, diff CI [$0.21, $1.25], p = 0.0057
```

Both metrics improved and both intervals exclude zero. Conversion rose by 1.25 percentage points (an 11.4% relative lift) and revenue per user by $0.73 (14.0%). The two p-values are both 0.0057 by coincidence of this seed, not because the tests are related.

![Dot and whisker chart of relative lift with 95% confidence intervals: conversion rate up 11.4 percent and revenue per user up 14.0 percent, both intervals entirely to the right of zero](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/images/ab-test-lift-ci.png)

## Check the Split First (Sample Ratio Mismatch)

Before looking at results, confirm users were split the way you intended. A chi-square test on the arm sizes catches broken randomization or logging problems:

```python
from scipy import stats

stats.chisquare([len(ctrl), len(trt)]).pvalue   # 1.0 for an exact 10,000 / 10,000 split
```

For an intended 50/50 split, a p-value below about 0.001 means something is wrong and the results shouldn't be trusted. For a different split (say 90/10), pass `f_exp=` with the expected counts.

## Conversion Rate: Two-Proportion Z-Test

`proportions_ztest(count, nobs)` takes the number of successes and the number of users in each arm. The first entry is treated as the one being tested against the second, so the order you pass matters for the sign of `z`, not for the p-value.

The test answers "is the difference bigger than noise?" The confidence interval answers "how big is it?" `confint_proportions_2indep` gives an interval for the difference in rates (treatment minus control). Here that's 0.36 to 2.14 percentage points. The example passes `method="wald"`, the textbook normal approximation, which is fine at these sample sizes. The function's default, `"newcomb"`, holds up better for small samples or rates near 0% or 100%, so leave `method` out when in doubt.

To show each arm's rate with its own error bars, Wilson intervals from `proportion_confint(..., method="wilson")` behave better than the normal approximation near 0% or 100%:

```python
import matplotlib.pyplot as plt
from statsmodels.stats.proportion import proportion_confint

fig, ax = plt.subplots(figsize=(6, 4.5))
for i, (name, sub, color) in enumerate([("Control", ctrl, "#64748b"), ("Treatment", trt, "#0f766e")]):
    k, m = sub["converted"].sum(), len(sub)
    lo, hi = proportion_confint(k, m, alpha=0.05, method="wilson")
    rate = k / m
    ax.bar(i, rate, color=color, width=0.55)
    ax.errorbar(i, rate, yerr=[[rate - lo], [hi - rate]], color="#1e293b", capsize=6, lw=1.8)
    ax.text(i, hi + 0.0015, f"{rate:.1%}", ha="center", fontsize=11, fontweight="bold")
ax.set_xticks([0, 1], ["Control", "Treatment"])
ax.set(ylabel="Conversion rate", title="Conversion rate with 95% Wilson intervals")
```

![Bar chart of conversion rate for control at 10.9 percent and treatment at 12.2 percent, each with a 95 percent Wilson confidence interval whiskers](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/images/ab-test-conversion-rate.png)

The bars' intervals touch (control's upper end and treatment's lower end are both near 11.6%), yet the test is significant. Overlapping per-arm intervals don't mean "no difference." The interval for the difference is the one to read.

## Revenue per User: Welch's T-Test

For a continuous metric, compare means with `ttest_ind(..., equal_var=False)`. That's Welch's version, which doesn't assume both arms have the same variance, and it's a safer default than the classic t-test. SciPy returns an object with `.pvalue` and a `.confidence_interval()` method for the difference in means.

Revenue per user has two quirks. About 88% of users spend nothing, and purchasers' order values are right-skewed:

![Overlapping histograms of order values for control and treatment purchasers, both right-skewed with most orders between 20 and 60 dollars and a long tail past 150](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/images/ab-test-order-values.png)

With thousands of users per arm, the t-test on the mean still behaves, because the sample mean is approximately normal even when the data isn't. With a few hundred users or very heavy tails, a bootstrap interval is safer. Don't drop the zeros to analyze only purchasers. That compares a different population in each arm and hides the conversion effect you're testing.

Among purchasers, order value barely moved: the mean was $47.78 in control and $48.88 in treatment. Most of the revenue gain here comes from more people buying, not bigger orders.

## Plot the Lift with Confidence Intervals

Express both metrics as relative lift (the difference divided by the control value) so they share an axis:

```python
p_c, p_t = ctrl["converted"].mean(), trt["converted"].mean()
m_c, m_t = ctrl["revenue"].mean(), trt["revenue"].mean()
metrics = {
    "Conversion rate": ((p_t - p_c) / p_c, diff_lo / p_c, diff_hi / p_c, p_conv),
    "Revenue per user": ((m_t - m_c) / m_c, ci.low / m_c, ci.high / m_c, res.pvalue),
}

fig, ax = plt.subplots(figsize=(7, 3.2))
for i, (name, (lift, lo, hi, p)) in enumerate(metrics.items()):
    color = "#0f766e" if lo > 0 else "#94a3b8"
    ax.errorbar(lift, i, xerr=[[lift - lo], [hi - lift]], fmt="o", color=color,
                capsize=5, lw=2, ms=8)
    ax.text(hi + 0.01, i, f"{lift:+.1%}  (p = {p:.3f})", va="center", fontsize=10)
ax.axvline(0, color="#1e293b", lw=1, ls="--")
ax.set_yticks([0, 1], list(metrics))
ax.set(xlabel="Relative lift vs control (95% CI)", title="Treatment effect by metric")
```

Dividing the interval's endpoints by the control mean is a quick approximation that treats the control mean as fixed. It's fine for reporting. For a precise interval on the ratio, use the delta method or a bootstrap. A dot and whisker chart like this scales well: add one row per metric and the same layout becomes a results dashboard.

## Which Test Should I Use?

| Metric type | Example | Test |
|---|---|---|
| Yes/no per user | Conversion, click-through, signup | `proportions_ztest` (or `scipy.stats.fisher_exact` for very small counts) |
| Continuous per user | Revenue per user, time on page | `ttest_ind(equal_var=False)` |
| Heavy-tailed, small samples | Revenue with whales | Bootstrap confidence interval |
| Counts per user | Sessions, purchases | Welch t-test on the mean, or a Poisson model |

## Practical Tips

- **Decide the sample size up front.** Stopping the moment p dips under 0.05 inflates false positives. Fix the duration, or use a sequential method built for peeking.
- **Pick one primary metric before launch.** If you test ten metrics, expect about one to be "significant" at 0.05 by chance alone.
- **Report the interval.** "Lift of 11.4%, 95% CI 3.3% to 19.5%" tells a decision-maker more than "p = 0.006".
- **Significant isn't important.** A tiny lift can be statistically significant with enough users. Compare the interval to the smallest change that matters to the business.

## Similar Topics

- [How to Plot a ROC Curve and Calculate AUC in Python](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/)
- [Confidence Interval Bands in Seaborn](https://www.pythoncharts.com/seaborn/seaborn-confidence-interval-bands/)
- [Matplotlib Grouped Bar Charts](https://www.pythoncharts.com/matplotlib/grouped-bar-charts-matplotlib/)
- [A/B Testing in Python: A Guide from Sample Size to Sequential Tests](https://www.pythoncharts.com/ab-testing/ab-testing-python-guide/)
