# Multi-Armed Bandit in Python: Thompson Sampling vs A/B Testing

> A multi-armed bandit tutorial in Python: Thompson sampling with Beta posteriors, epsilon-greedy and a fixed split compared by cumulative regret, traffic allocation over time, and when a bandit is the wrong tool.

Source: https://www.pythoncharts.com/ab-testing/multi-armed-bandit-thompson-sampling-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: A/B Testing | Tags: ab testing, experimentation, multi-armed bandit, thompson sampling, regret, epsilon-greedy, bayesian, numpy

A multi-armed bandit shifts traffic toward the better variants while the experiment is still running, instead of holding a fixed split until the end. The simplest good algorithm is Thompson sampling: for each visitor, draw one random conversion rate from each variant's Beta posterior and show the variant with the highest draw. In NumPy that is `np.argmax(rng.beta(1 + wins, 1 + trials - wins))`. This post compares it with a fixed split and epsilon-greedy using regret, the conversions you lose by not always showing the best variant.

## Quick Example

Four landing-page variants convert at 10%, 11%, 12% and 14%. The code runs 200 independent experiments of 20,000 visitors under three policies and plots the average cumulative regret (expected conversions lost compared with always showing the best variant).

```python
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(88)
true_p = np.array([0.100, 0.110, 0.120, 0.140])   # true conversion rate of each variant
best = true_p.max()
K, T, RUNS = len(true_p), 20_000, 200

def simulate(policy, runs=RUNS, T=T, eps=0.1):
    """Run `runs` experiments of `T` visitors. Returns choices (runs, T) and final wins/trials."""
    wins = np.zeros((runs, K))
    trials = np.zeros((runs, K))
    choices = np.empty((runs, T), dtype=np.int8)
    rows = np.arange(runs)
    for t in range(T):
        if policy == "uniform":
            arm = rng.integers(0, K, runs)
        elif policy == "epsilon":
            greedy = np.argmax(wins / np.maximum(trials, 1), axis=1)
            explore = rng.random(runs) < eps
            arm = np.where(explore, rng.integers(0, K, runs), greedy)
        else:  # Thompson sampling: one draw from each Beta posterior, play the largest
            arm = np.argmax(rng.beta(1 + wins, 1 + trials - wins), axis=1)
        reward = rng.random(runs) < true_p[arm]
        wins[rows, arm] += reward
        trials[rows, arm] += 1
        choices[:, t] = arm
    return choices, wins, trials

results = {name: simulate(name) for name in ["uniform", "epsilon", "thompson"]}
labels = {"uniform": "Fixed equal split (classic A/B/n)", "epsilon": "Epsilon-greedy (eps=0.1)", "thompson": "Thompson sampling"}
colors = {"uniform": "#8a8f98", "epsilon": "#e9a23b", "thompson": "#1b6ca8"}

regret = {k: np.cumsum(best - true_p[v[0]], axis=1) for k, v in results.items()}
for k, r in regret.items():
    print(f"{k:9s} final regret: mean {r[:, -1].mean():.0f}, 10th-90th percentile {np.percentile(r[:, -1], 10):.0f}-{np.percentile(r[:, -1], 90):.0f}")

fig, ax = plt.subplots(figsize=(8, 4.6))
t = np.arange(1, T + 1)
for k, r in regret.items():
    ax.plot(t, r.mean(axis=0), color=colors[k], lw=2.2, label=labels[k])
    ax.fill_between(t, np.percentile(r, 10, axis=0), np.percentile(r, 90, axis=0), color=colors[k], alpha=0.15)
ax.set_xlabel("Visitors")
ax.set_ylabel("Cumulative regret (expected lost conversions)")
ax.set_title("Thompson sampling loses far fewer conversions than a fixed split")
ax.legend(loc="upper left")
fig.tight_layout()
```

![Line chart of cumulative regret over 20,000 visitors. The fixed equal split rises in a straight line to about 450. Epsilon-greedy ends near 123 with a wide band. Thompson sampling flattens out near 72 with a narrow band](https://www.pythoncharts.com/ab-testing/multi-armed-bandit-thompson-sampling-python/images/bandit-regret.png)

Average final regret was 450 for the fixed split, 123 for epsilon-greedy and 72 for Thompson sampling. The fixed split's regret is a straight line because it keeps sending 75% of traffic to inferior variants forever. Over the 20,000 visitors, Thompson sampling produced about 2,728 conversions per experiment against 2,350 for the fixed split, roughly 16% more.

Epsilon-greedy's shaded band is wide (10th to 90th percentile: 50 to 305). It commits to whichever variant looks best early, and sometimes an unlucky early streak locks it onto the wrong one.

## How Does Thompson Sampling Work?

Each variant gets a Beta(1 + wins, 1 + losses) distribution describing what you currently believe its conversion rate is. This is the same Beta-Binomial model used in the [Bayesian A/B test](https://www.pythoncharts.com/ab-testing/bayesian-ab-test-python/) post. For every visitor:

1. Draw one sample from each variant's posterior.
2. Show the variant with the largest sample.
3. Observe convert or not, and add it to that variant's wins or losses.

A variant with a wide posterior (little data) sometimes produces a high draw and gets traffic, which is the exploration. A variant with a posterior firmly below the leader almost never wins a draw, so it fades out. There is no exploration parameter to tune. In production this is a small stateful piece of code, with the counts stored somewhere durable:

```python
def choose_variant(wins, trials, rng):
    return int(np.argmax(rng.beta(1 + wins, 1 + trials - wins)))

def record(wins, trials, arm, converted):
    trials[arm] += 1
    wins[arm] += converted
```

## How Does Traffic Allocation Change Over Time?

The allocation chart is the easiest way to see the difference between the two adaptive policies. It shows the share of visitors each variant received, averaged over the 200 runs, in bins of 500 visitors.

```python
bin_w = 500
arm_cols = ["#b8c4d0", "#8fb7d6", "#4f8fc0", "#1b4f8a"]
fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), sharey=True)
for ax, k in zip(axes, ["epsilon", "thompson"]):
    ch = results[k][0]
    share = np.array([[np.mean(ch[:, i:i + bin_w] == a) for i in range(0, T, bin_w)] for a in range(K)])
    ax.stackplot(np.arange(0, T, bin_w) + bin_w / 2, share, colors=arm_cols,
                 labels=[f"Variant {c} ({p:.0%})" for c, p in zip("ABCD", true_p)])
    ax.set_title(labels[k])
    ax.set_xlabel("Visitors")
    ax.set_xlim(bin_w / 2, T - bin_w / 2)
    ax.set_ylim(0, 1)
axes[0].set_ylabel("Share of traffic")
handles, labs = axes[1].get_legend_handles_labels()
fig.legend(handles, labs, loc="lower center", ncol=4, fontsize=9, frameon=False)
fig.tight_layout(rect=(0, 0.07, 1, 1))
```

![Two stacked area charts of traffic share by variant over time. Both give variant D a growing share. Thompson sampling reaches about 96 percent for D by the end, epsilon-greedy about 87 percent](https://www.pythoncharts.com/ab-testing/multi-armed-bandit-thompson-sampling-python/images/bandit-traffic-share.png)

By the last 500 visitors Thompson sampling sent 96.1% of traffic to the best variant (D), against 87.0% for epsilon-greedy. Epsilon-greedy never drops below its floor: with `eps=0.1`, 10% of visitors are shown a random variant for the whole experiment, including ones it already knows are worse.

## What Do the Posteriors Look Like as the Experiment Runs?

This follows a single Thompson run. After 200 visitors the curves overlap and every variant is plausible. By 2,000 variant D has collected 1,760 visitors and its posterior is narrow, while the others have a few dozen to a hundred.

```python
from scipy import stats

r1 = np.random.default_rng(3)
wins, trials = np.zeros(K), np.zeros(K)
snap = {200: None, 2000: None, 20000: None}
for i in range(1, T + 1):
    arm = int(np.argmax(r1.beta(1 + wins, 1 + trials - wins)))
    wins[arm] += r1.random() < true_p[arm]
    trials[arm] += 1
    if i in snap:
        snap[i] = (wins.copy(), trials.copy())

xs = np.linspace(0.03, 0.22, 500)
fig, axes = plt.subplots(1, 3, figsize=(11, 3.6), sharex=True)
for ax, (n_seen, (w, tr)) in zip(axes, snap.items()):
    for a in range(K):
        ax.plot(xs, stats.beta.pdf(xs, 1 + w[a], 1 + tr[a] - w[a]), color=arm_cols[a] if a < 3 else "#d1495b", lw=2,
                label=f"{'ABCD'[a]} (n={int(tr[a]):,})")
    ax.axvline(true_p[3], color="#d1495b", ls=":", lw=1)
    ax.set_title(f"After {n_seen:,} visitors")
    ax.set_xlabel("Conversion rate")
    ax.set_yticks([])
    ax.legend(fontsize=8, loc="upper right")
fig.tight_layout()
```

![Three panels of Beta posterior curves for four variants after 200, 2,000 and 20,000 visitors. The best variant's curve becomes very narrow around its true rate of 14 percent, while the other variants stay wide](https://www.pythoncharts.com/ab-testing/multi-armed-bandit-thompson-sampling-python/images/bandit-posteriors.png)

By 20,000 visitors variant D had 18,382 of the visitors and a very tight posterior around its true 14% (dotted line). Variants A and B, which saw 175 and 235 visitors, are still wide, and in this run A's posterior sits around 6% when its true rate is 10% (10 conversions in 175 trials was an unlucky streak). The bandit stopped caring because it had no reason to keep testing a variant that looked clearly worse. That is the right trade for earning conversions and the wrong one for learning exact rates.

## What Does a Bandit Cost You in Measurement?

Adaptive allocation gives up precision on the variants you stop showing. Comparing the two best variants (C at 12% and D at 14%) at the end of each run:

| Policy | Median visitors on C | Median visitors on D | Typical standard error of D minus C |
|---|---|---|---|
| Fixed equal split | 5,000 | 5,000 | 0.0067 |
| Thompson sampling | 1,260 | 17,642 | 0.0095 |

The standard errors use the true rates in the variance formula, so they are approximate, but the direction is clear: the bandit's estimate of the D vs C gap is about 40% noisier, because C got about a quarter of the visitors it would have had in the fixed split. If you need a precise, defensible effect size, a fixed-allocation test is better. See [A/B test sample size](https://www.pythoncharts.com/ab-testing/ab-test-sample-size-power-python/) for planning one.

## Bandit vs A/B Test: When to Use Which

| Situation | Better choice |
|---|---|
| The value is short-lived (a promo banner, a headline for a news story) and you want most traffic on the winner quickly | Bandit |
| Many variants, with traffic cost to testing each one | Bandit |
| You need an unbiased effect estimate to decide on a launch or report to stakeholders | A/B test |
| The metric is slow to arrive (retention after 30 days) | A/B test, because bandits need fast feedback to adapt |
| The effect may change over the week (weekday vs weekend) | A/B test, or a bandit with a time-aware model |

## Practical Tips

- Thompson sampling with a `Beta(1, 1)` prior is a good default for conversion-style (0 or 1) rewards. For continuous rewards like revenue, use a different posterior, such as a Normal or a model that handles skew.
- Keep a small floor of traffic on every variant (for example, clip each arm's probability to at least 2%) if you may want to analyze the results later.
- Delayed conversions break the loop. Update the counts in batches (hourly or daily) rather than per visitor, which also makes the system simpler to run.
- Watch for seasonality. A variant that wins on weekdays can lose on weekends, and a bandit that has already stopped exploring will not notice.
- These numbers come from one seeded simulation with specific conversion rates. The size of the gap between policies depends on how far apart the true rates are.

## Similar Topics

- [Bayesian A/B Testing in Python](https://www.pythoncharts.com/ab-testing/bayesian-ab-test-python/)
- [A/B Test Peeking and Sequential Testing in Python](https://www.pythoncharts.com/ab-testing/ab-test-peeking-sequential-testing-python/)
- [A/B Test Sample Size and Power in Python](https://www.pythoncharts.com/ab-testing/ab-test-sample-size-power-python/)
- [A/B Testing in Python: A Guide](https://www.pythoncharts.com/ab-testing/ab-testing-python-guide/)
