# Ratio Metrics in A/B Tests: The Delta Method in Python

> How to analyze ratio metrics (clicks per session, revenue per visit) in an A/B test in Python. Compute the delta-method standard error with numpy and pandas, compare it with a naive z-test and a user-level bootstrap, and verify the false positive rate with an A/A simulation.

Source: https://www.pythoncharts.com/ab-testing/ratio-metrics-delta-method-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: A/B Testing | Tags: ab testing, experimentation, ratio metrics, delta method, click-through rate, bootstrap, confidence interval, pandas

A ratio metric is one total divided by another, like clicks per session, orders per visit or revenue per active day. If you randomize by user but compute the metric over sessions, the sessions from one user are not independent, so the usual two-proportion z-test understates the standard error. The fix is the delta method: treat each user as the unit and use `Var(R) ≈ (Var(x) + R² Var(y) - 2 R Cov(x, y)) / (n ȳ²)`, where `x` is the numerator per user, `y` is the denominator per user, and `R = x̄ / ȳ`. In the simulated test below, the naive interval is 27% too narrow and has a 15% false positive rate when 5% is the target.

## Quick Example

The data is simulated: one row per user with their session count and click count. Users differ in how often they visit and in how likely they are to click, which is what real engagement data looks like. The treatment raises each user's click propensity by 7% (relative). The naive test pools every session as if it were an independent coin flip. The delta-method test uses one row per user.

```python
import numpy as np
import pandas as pd
from scipy import stats

def make_users(n, rng, lift=0.0):
    """One row per user: sessions and clicks. Users differ a lot in how often they
    visit and in how likely they are to click, so clicks per session varies by user."""
    sessions = 1 + rng.negative_binomial(0.8, 0.1, n)            # heavy-tailed visit counts
    p_user = rng.beta(0.8, 15.0, n)                                # each user's click propensity
    clicks = rng.binomial(sessions, np.clip(p_user * (1 + lift), 0, 1))
    return pd.DataFrame({"sessions": sessions, "clicks": clicks})

def ratio_diff_delta(a, b):
    """Difference in clicks/sessions between two arms, with a delta-method SE."""
    out = []
    for d in (a, b):
        n = len(d)
        mx, my = d.clicks.mean(), d.sessions.mean()
        r = mx / my
        var = (d.clicks.var() + r**2 * d.sessions.var()
               - 2 * r * np.cov(d.clicks, d.sessions)[0, 1]) / (n * my**2)
        out.append((r, var))
    diff = out[0][0] - out[1][0]
    se = np.sqrt(out[0][1] + out[1][1])
    return diff, se

def naive_diff(a, b):
    """Treat every session as an independent Bernoulli trial."""
    p1, p0 = a.clicks.sum() / a.sessions.sum(), b.clicks.sum() / b.sessions.sum()
    n1, n0 = a.sessions.sum(), b.sessions.sum()
    se = np.sqrt(p1 * (1 - p1) / n1 + p0 * (1 - p0) / n0)
    return p1 - p0, se

rng = np.random.default_rng(11)
control = make_users(5000, rng)
treat = make_users(5000, rng, lift=0.07)

for name, fn in [("naive", naive_diff), ("delta", ratio_diff_delta)]:
    diff, se = fn(treat, control)
    p = 2 * stats.norm.sf(abs(diff / se))
    print(f"{name:6s} lift = {diff:+.4f}  SE = {se:.5f}  "
          f"95% CI [{diff - 1.96 * se:.4f}, {diff + 1.96 * se:.4f}]  p = {p:.4f}")
```

```text
naive  lift = +0.0056  SE = 0.00156  95% CI [0.0026, 0.0087]  p = 0.0003
delta  lift = +0.0056  SE = 0.00215  95% CI [0.0014, 0.0098]  p = 0.0087
```

Both methods report the same lift, +0.56 percentage points on a control click-through rate of 5.0%. The difference is the standard error: 0.00215 from the delta method against 0.00156 from the naive test, a ratio of 1.38. The naive p-value is 0.0003, which looks decisive, while the correct one is 0.009. Here both are below 0.05, but a result near the threshold would flip.

![Three horizontal 95 percent confidence intervals for the lift in click-through rate: the naive interval is 0.61 percentage points wide, while the delta method and the bootstrap by user are both 0.84 points wide and reach closer to zero](https://www.pythoncharts.com/ab-testing/ratio-metrics-delta-method-python/images/ratio-ci-comparison.png)

## Why the Naive Test Is Too Confident

The naive test assumes every session is an independent Bernoulli trial with the same click probability. Neither holds. Randomization happened at the user level, and a user's sessions share a click propensity, so a user with 40 sessions contributes 40 correlated observations and counts as 40 independent ones. In this data users average 8.05 sessions, but the median is 5 and the 99th percentile is 39, so a small group of heavy users carries a large share of the sessions.

![Left, a histogram of sessions per user that is heavily right-skewed. Right, a scatter of each user's clicks per session against their session count, showing wide spread in click rate across users](https://www.pythoncharts.com/ab-testing/ratio-metrics-delta-method-python/images/ratio-sessions-per-user.png)

The effective sample size is the number of users, not sessions. The delta method accounts for that: it works from the per-user totals, and the `Cov(x, y)` term captures that users with more sessions also tend to have more clicks.

## How Does the Delta Method Work?

The ratio `R = x̄ / ȳ` is a nonlinear function of two sample means, so there is no direct formula for its variance. The delta method takes a first-order Taylor expansion around the true means, which turns the ratio into a linear combination of `x̄` and `ȳ` whose variance is easy to write down:

```text
Var(R) ≈ (Var(x) + R² · Var(y) − 2 · R · Cov(x, y)) / (n · ȳ²)
```

`ratio_diff_delta()` above computes this for each arm with `d.clicks.var()`, `d.sessions.var()` and `np.cov()`, then adds the two arm variances (the arms are independent) and takes the square root for the difference's standard error. `n` is the number of users, and everything is computed from one row per user.

The approximation is good when `ȳ` is far from zero relative to its own noise, which holds for sessions per user over thousands of users. It gets shaky with tiny samples or a denominator that is often zero (such as revenue per purchase when few users buy).

## Does a Bootstrap Agree?

Yes. Resampling users (not sessions) with replacement and recomputing the pooled ratio each time gives almost the same interval:

```python
brng = np.random.default_rng(1)
boot = []
for _ in range(2000):
    a = treat.iloc[brng.integers(0, len(treat), len(treat))]
    b = control.iloc[brng.integers(0, len(control), len(control))]
    boot.append(a.clicks.sum() / a.sessions.sum() - b.clicks.sum() / b.sessions.sum())

np.percentile(boot, [2.5, 97.5]).round(4), np.std(boot, ddof=1).round(5)
# (array([0.0013, 0.0097]), 0.00215)
```

The bootstrap standard deviation is 0.00215, the same as the delta method's, and its interval [0.0013, 0.0097] is within a few thousandths of the delta interval [0.0014, 0.0098]. The bootstrap needs no formula and works for any ratio, at the cost of 2,000 passes over the data. See the [bootstrap confidence interval post](https://www.pythoncharts.com/ab-testing/bootstrap-confidence-interval-python/) for the general version. The delta method is a closed-form shortcut, so it is the one to run inside a dashboard or on every metric of every experiment.

## How Bad Is the Naive Test in an A/A Test?

An A/A test, with no real difference between arms, shows the damage directly. A valid test should reject at the 5% level in 5% of runs, and the p-values should be uniform. This simulation runs 2,000 A/A tests with 1,500 users per arm:

```python
sim_rng = np.random.default_rng(2026)
p_naive, p_delta = [], []
for _ in range(2000):
    a, b = make_users(1500, sim_rng), make_users(1500, sim_rng)
    for fn, store in [(naive_diff, p_naive), (ratio_diff_delta, p_delta)]:
        diff, se = fn(a, b)
        store.append(2 * stats.norm.sf(abs(diff / se)))

(np.array(p_naive) < 0.05).mean(), (np.array(p_delta) < 0.05).mean()
# (0.151, 0.047)
```

The naive test declares a winner in 15.1% of A/A tests, three times the intended rate, and its p-values pile up near zero. The delta-method test rejects in 4.7% of them, with a flat histogram.

![Two histograms of p-values from 2,000 A/A tests: the naive test has a tall spike near zero with 15.1 percent of p-values below 0.05, while the delta method histogram is flat with 4.7 percent below 0.05](https://www.pythoncharts.com/ab-testing/ratio-metrics-delta-method-python/images/ratio-aa-pvalues.png)

The size of the problem depends on how unevenly users contribute and how much click rates differ between users. If every user had exactly the same number of sessions and click rate, the naive test would be fine.

## Ratio of Totals or Average of User Ratios?

These are different metrics and they give different numbers. `clicks.sum() / sessions.sum()` weights each user by their sessions, so heavy users count more. The mean of per-user ratios weights every user equally:

```python
pooled = treat.clicks.sum() / treat.sessions.sum()
per_user = (treat.clicks / treat.sessions).mean()
pooled, per_user
# (0.0557, 0.0580)
```

On the treatment arm, the pooled CTR is 5.57% and the average user's CTR is 5.80%. Neither is wrong, but pick one before the test and say which. The per-user average is a plain mean, so a regular t-test works and no delta method is needed, but it is noisier when many users have one or two sessions, and it ignores how much each user is actually engaged. Use the ratio of totals when the business question is "what fraction of sessions end in a click," and the per-user average when it is "does the typical user click more."

| Situation | Method |
|---|---|
| Randomized by user, metric is total over total | Delta method (or bootstrap by user) |
| Randomized by session or request | The naive z-test is valid |
| Want the typical user's rate | Per-user ratio, then a t-test |
| Small samples or a sparse denominator | Bootstrap by user |
| Want a relative lift with an interval | Delta method on the ratio of ratios, or bootstrap the relative lift |

## Practical Tips

- **Match the analysis unit to the randomization unit.** Randomize by user, analyze by user. That one rule fixes most of the problem.
- **Keep one row per user.** `groupby("user_id")[["clicks", "sessions"]].sum()` turns event logs into the table the delta method needs.
- **Check with an A/A test first.** If your pipeline rejects far more than 5% of the time, a unit mismatch like this is a likely cause.
- **Combine with variance reduction.** CUPED applies to the linearized metric or to the numerator and denominator separately. See the [CUPED post](https://www.pythoncharts.com/ab-testing/cuped-variance-reduction-python/).
- **Use a robust fallback.** When the denominator can be zero for many users, or a few users dominate, bootstrap by user.

## Similar Topics

- [A/B Test Analysis in Python: Conversion Rate and Revenue](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/) covers the simple per-user metrics this post extends.
- [Bootstrap Confidence Intervals in Python for A/B Tests](https://www.pythoncharts.com/ab-testing/bootstrap-confidence-interval-python/) is the general resampling approach.
- [Switchback and Cluster-Randomized Experiments in Python](https://www.pythoncharts.com/ab-testing/switchback-cluster-randomized-experiments-python/) has the same "wrong unit" problem one level up.
