# Build an A/B Test Calculator App in Streamlit

> Build an A/B test calculator in Streamlit with statsmodels: sample size per group, test duration, a two-proportion z-test, a confidence interval chart, a sample ratio mismatch check and shareable URLs.

Source: https://www.pythoncharts.com/streamlit/streamlit-ab-test-calculator/ | Published: 2026-11-26 | Author: Alex Scott | Category: Streamlit | Tags: streamlit, ab testing, sample size, statsmodels, st.number_input

This Streamlit app calculates the sample size for an A/B test with `statsmodels`' `NormalIndPower`, then analyzes the finished test with `proportions_ztest` and a confidence interval. It handles conversion rates (a yes or no outcome per user) and fits in one file. The code was tested with Streamlit 1.67 and statsmodels 0.14.

## Quick Example

Install the packages with `pip install streamlit statsmodels`, save this as `app.py` and run `streamlit run app.py`.

```python
import altair as alt
import numpy as np
import pandas as pd
import streamlit as st
from scipy import stats
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import (confint_proportions_2indep,
                                          proportion_effectsize, proportions_ztest)

def users_per_group(baseline, target, alpha, power):
    effect = abs(proportion_effectsize(target, baseline))
    n = NormalIndPower().solve_power(effect_size=effect, alpha=alpha, power=power, ratio=1.0)
    return int(np.ceil(n))

st.title("A/B Test Calculator")
alpha = st.sidebar.selectbox("Significance level", [0.01, 0.05, 0.10], index=1)
plan, analyze = st.tabs(["Plan a test", "Analyze results"])

with plan:
    left, middle, right = st.columns(3)
    baseline = left.number_input("Baseline rate (%)", 0.1, 90.0, 8.0, 0.5,
                                 key="baseline", bind="query-params") / 100
    lift = middle.number_input("Smallest lift (points)", 0.1, 9.0, 1.0, 0.1,
                               key="lift", bind="query-params") / 100
    daily = right.number_input("Users per day", 1, value=2000, step=100,
                               key="daily", bind="query-params")
    power = st.segmented_control("Power", [0.8, 0.9], default=0.8, required=True,
                                 format_func=lambda p: f"{p:.0%}")

    n = users_per_group(baseline, baseline + lift, alpha, power)
    first, second, third = st.columns(3, border=True)
    first.metric("Users per group", f"{n:,}")
    second.metric("Total users", f"{2 * n:,}")
    third.metric("Days to run", f"{int(np.ceil(2 * n / daily))}")

    lifts = np.linspace(0.6, 2.0, 29) * lift
    lifts = lifts[baseline + lifts < 1]  # a rate can't reach 100%
    curve = pd.DataFrame({
        "Lift (points)": lifts * 100,
        "Users per group": [users_per_group(baseline, baseline + d, alpha, power) for d in lifts],
    })
    st.subheader("Smaller lifts cost far more users")
    st.line_chart(curve, x="Lift (points)", y="Users per group", color="#5f3dc4")

with analyze:
    control, variant = st.columns(2, border=True)
    with control:
        st.subheader("Control")
        n_a = st.number_input("Users", 1, value=12200, key="users_a", bind="query-params")
        x_a = st.number_input("Conversions", 0, value=976, key="conv_a", bind="query-params")
    with variant:
        st.subheader("Variant")
        n_b = st.number_input("Users", 1, value=12180, key="users_b", bind="query-params")
        x_b = st.number_input("Conversions", 0, value=1096, key="conv_b", bind="query-params")

    if x_a > n_a or x_b > n_b:
        st.error("Conversions can't be higher than users.")
    elif x_a + x_b in (0, n_a + n_b):
        st.error("The test needs both converters and non-converters.")
    else:
        rate_a, rate_b = x_a / n_a, x_b / n_b
        p_value = proportions_ztest([x_b, x_a], [n_b, n_a])[1]
        low, high = confint_proportions_2indep(x_b, n_b, x_a, n_a, method="wald",
                                               alpha=alpha)

        first, second, third = st.columns(3)
        first.metric("Control rate", f"{rate_a:.2%}")
        second.metric("Variant rate", f"{rate_b:.2%}",
                      f"{(rate_b - rate_a) * 100:+.2f} points")
        third.metric("p-value", f"{p_value:.4f}")

        if stats.chisquare([n_a, n_b]).pvalue < 0.001:
            st.error("Sample ratio mismatch: the groups aren't split 50/50. "
                     "Fix that before trusting the result.")
        elif p_value < alpha:
            winner = "Variant" if rate_b > rate_a else "Control"
            st.success(f"{winner} converts better, and the difference is significant.")
        else:
            st.info("No significant difference. The interval shows what is still plausible.")

        result = pd.DataFrame({"label": ["Variant minus control"], "diff": [(rate_b - rate_a) * 100],
                               "low": [low * 100], "high": [high * 100]})
        base = alt.Chart(result).encode(y=alt.Y("label:N", axis=None))
        interval = base.mark_rule(strokeWidth=4, color="#0b7285").encode(
            x=alt.X("low:Q", title="Variant minus control (percentage points)"), x2="high:Q")
        point = base.mark_circle(size=220, color="#0b7285", opacity=1).encode(x="diff:Q")
        zero = alt.Chart(pd.DataFrame({"x": [0]})).mark_rule(strokeDash=[5, 4]).encode(x="x:Q")
        st.altair_chart((zero + interval + point).properties(height=120))
        st.caption(f"{1 - alpha:.0%} confidence interval: {low * 100:.2f} to {high * 100:.2f} points")
```

![Streamlit A/B test calculator planning tab showing 12,199 users per group, 24,398 total users, 13 days to run and a curve of users needed against lift](https://www.pythoncharts.com/streamlit/streamlit-ab-test-calculator/images/streamlit-ab-test-calculator.png)

With an 8% baseline, a one point lift, a 5% significance level and 80% power, the app asks for 12,199 users per group, or 13 days at 2,000 users a day. The significance level is set in the sidebar and applies to both tabs.

## How Does the Calculator Find the Sample Size?

`proportion_effectsize` turns the two conversion rates into Cohen's h, and `NormalIndPower().solve_power` returns the users needed in each group. The inputs matter in this order:

| Input | Effect on sample size |
|---|---|
| Smallest lift worth detecting | Halving it needs roughly four times the users |
| Baseline rate | For a fixed absolute lift, rates near 50% need the most users |
| Power | Going from 80% to 90% adds about a third |
| Significance level | A stricter level, such as 1%, needs more users |

Pick the lift from what would change your decision, not from what you hope to see. The [sample size and power tutorial](https://www.pythoncharts.com/ab-testing/ab-test-sample-size-power-python/) goes through each of these.

## Analyze the Finished Test

The second tab takes users and conversions for both groups:

![Results tab showing control at 8.00 percent, variant at 9.00 percent, a p-value below 0.01 and a confidence interval to the right of zero](https://www.pythoncharts.com/streamlit/streamlit-ab-test-calculator/images/streamlit-ab-test-calculator-results.png)

The default numbers give a one point difference with an interval of 0.30 to 1.70 points. The app runs three checks:

1. **Sample ratio mismatch.** A chi-square test compares the group sizes with a 50/50 split. A p-value below 0.001 points to a broken assignment or logging problem, so the app shows an error instead of a winner. See the [SRM check](https://www.pythoncharts.com/ab-testing/ab-test-srm-check-python/).
2. **Significance.** `proportions_ztest` gives the two-sided p-value.
3. **Size of the effect.** `confint_proportions_2indep` gives the range of differences consistent with the data, drawn as an Altair chart with a dashed line at zero.

## Share a Calculation With a Link

`bind="query-params"` ties a widget to the page URL, using its `key` as the parameter name. Changing an input updates the address bar, and opening that address fills the inputs:

```text
http://localhost:8501/?baseline=12&lift=2&daily=500
```

Inputs left at their defaults stay out of the URL. Invalid values in the address are ignored.

## Limits of This Calculator

- **It assumes one look at the data.** Checking the p-value daily and stopping when it dips below 0.05 raises the false positive rate. Use a [sequential test](https://www.pythoncharts.com/ab-testing/ab-test-peeking-sequential-testing-python/) if you need to stop early.
- **It compares one variant on one metric.** More of either calls for a [multiple testing correction](https://www.pythoncharts.com/ab-testing/ab-test-multiple-testing-python/).
- **It doesn't handle revenue.** Averages such as revenue per user need a t-test or bootstrap, shown in [A/B test analysis](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/).
- **Round run time up to whole weeks** so weekdays and weekends are both represented.

## Similar Topics

- [Streamlit Tutorials: A Guide from First App to Deployment](https://www.pythoncharts.com/streamlit/streamlit-python-guide/)
- [A/B Testing in Python: A Guide from Sample Size to Sequential Tests](https://www.pythoncharts.com/ab-testing/ab-testing-python-guide/)
- [How to Deploy a Streamlit App](https://www.pythoncharts.com/streamlit/deploy-streamlit-app/)
