TExcelTAD
Home › Statistics › Statistics Mini Project

Statistics Mini Project

In this project you'll analyse an A/B test from start to finish, the way a data analyst at an online shop would. It brings together most of the course: study design, descriptive statistics, charts, confidence intervals, hypothesis tests, chi-square tests, effect sizes, multiple-testing caution and power analysis.

The story

An online tea shop wants to know whether a redesigned checkout page (variant B) sells better than the current page (variant A). For two weeks, every visitor who reached the checkout was randomly assigned to A or B. For each visitor we record:

  • variant: A or B,
  • device: mobile or desktop,
  • converted: whether the visitor completed the purchase,
  • revenue: the order value in euros (0 if no purchase).

Before looking at any data, the team wrote down its plan (pre-registration, see Statistical Pitfalls):

Item Decision
Primary metric conversion rate
Hypotheses H₀: p_B = p_A vs. H₁: p_B ≠ p_A (two-tailed)
Significance level α = 0.05
Secondary metric revenue per visitor
Sample size about 4,000 visitors, fixed in advance (no peeking)

Real data would come from the shop's logs. Here we simulate it with a seeded generator so everyone gets the same numbers. The same eleven lines at the top of each step rebuild the dataset, so every step runs on its own.

Step 1: Load and inspect the data

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(50)
n = 4000
users = pd.DataFrame({
    "variant": rng.choice(["A", "B"], size=n),
    "device": rng.choice(["mobile", "desktop"], size=n, p=[0.6, 0.4]),
})
base = np.where(users["device"] == "mobile", 0.08, 0.12)
lift = np.where(users["variant"] == "B", 0.025, 0.0)          # the "truth" we pretend not to know
users["converted"] = rng.random(n) < base + lift
users["revenue"] = np.where(users["converted"], rng.gamma(4, 12, n).round(2), 0.0)

print(users.head(8))
print()
print("rows:", len(users))
print("missing values:", int(users.isna().sum().sum()))
print(users.dtypes)
  variant   device  converted  revenue
0       B   mobile      False     0.00
1       B   mobile      False     0.00
2       B   mobile      False     0.00
3       B   mobile       True    18.35
4       B  desktop      False     0.00
5       B  desktop      False     0.00
6       A  desktop      False     0.00
7       B   mobile      False     0.00

rows: 4000
missing values: 0
variant       object
device        object
converted       bool
revenue      float64
dtype: object

Four variables: two nominal (variant, device), one binary (converted) and one ratio-level quantitative (revenue). No missing values.

Step 2: Sanity checks before any test

Did the randomisation split the traffic evenly?

A sample ratio mismatch (for example, 55/45 when 50/50 was intended) signals a bug in the assignment and would invalidate the test. A chi-square goodness-of-fit test checks the split:

python · try it yourself
import numpy as np
import pandas as pd
from scipy import stats

rng = np.random.default_rng(50)
n = 4000
users = pd.DataFrame({
    "variant": rng.choice(["A", "B"], size=n),
    "device": rng.choice(["mobile", "desktop"], size=n, p=[0.6, 0.4]),
})
base = np.where(users["device"] == "mobile", 0.08, 0.12)
lift = np.where(users["variant"] == "B", 0.025, 0.0)
users["converted"] = rng.random(n) < base + lift
users["revenue"] = np.where(users["converted"], rng.gamma(4, 12, n).round(2), 0.0)

counts = users["variant"].value_counts().sort_index()
print(counts.to_string())
srm = stats.chisquare(counts, f_exp=[n / 2, n / 2])
print(f"sample ratio test: chi2 = {srm.statistic:.3f}, p = {srm.pvalue:.3f}")

print()
mix = pd.crosstab(users["variant"], users["device"], normalize="index").round(3)
print(mix)
balance = stats.chi2_contingency(pd.crosstab(users["variant"], users["device"]))
print(f"device balance: p = {balance.pvalue:.3f}")
variant
A    2015
B    1985
sample ratio test: chi2 = 0.225, p = 0.635

device   desktop  mobile
variant
A          0.415   0.585
B          0.403   0.597
device balance: p = 0.446

The split (2,015 vs. 1,985) is well within what chance produces for a fair 50/50 assignment, and the device mix is nearly the same in both groups. Randomisation worked, so any difference in outcomes can be attributed to the page design (see Study Types).

Step 3: Describe the results

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(50)
n = 4000
users = pd.DataFrame({
    "variant": rng.choice(["A", "B"], size=n),
    "device": rng.choice(["mobile", "desktop"], size=n, p=[0.6, 0.4]),
})
base = np.where(users["device"] == "mobile", 0.08, 0.12)
lift = np.where(users["variant"] == "B", 0.025, 0.0)
users["converted"] = rng.random(n) < base + lift
users["revenue"] = np.where(users["converted"], rng.gamma(4, 12, n).round(2), 0.0)

summary = users.groupby("variant").agg(
    visitors=("converted", "size"),
    orders=("converted", "sum"),
    conv_rate=("converted", "mean"),
    revenue_per_visitor=("revenue", "mean"),
)
buyers = users[users["converted"]]
summary["avg_order_value"] = buyers.groupby("variant")["revenue"].mean()
print(summary.round(4))
         visitors  orders  conv_rate  revenue_per_visitor  avg_order_value
variant
A            2015     192     0.0953               4.7408          49.7539
B            1985     238     0.1199               5.9673          49.7692

Variant B converts about 12.0% of visitors versus about 9.5% for A, and earns more per visitor. The average order value of those who do buy is similar, so the extra revenue comes from more buyers, not bigger baskets. Now we must ask whether this difference could be chance.

Step 4: Visualise with confidence intervals

A bar chart of the two conversion rates with 95% Wilson intervals:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.stats.proportion import proportion_confint

rng = np.random.default_rng(50)
n = 4000
users = pd.DataFrame({
    "variant": rng.choice(["A", "B"], size=n),
    "device": rng.choice(["mobile", "desktop"], size=n, p=[0.6, 0.4]),
})
base = np.where(users["device"] == "mobile", 0.08, 0.12)
lift = np.where(users["variant"] == "B", 0.025, 0.0)
users["converted"] = rng.random(n) < base + lift
users["revenue"] = np.where(users["converted"], rng.gamma(4, 12, n).round(2), 0.0)

g = users.groupby("variant")["converted"].agg(["sum", "size"])
rates = g["sum"] / g["size"]
low, high = proportion_confint(g["sum"], g["size"], alpha=0.05, method="wilson")

fig, ax = plt.subplots(figsize=(4.5, 3.5))
ax.bar(rates.index, rates.values, color=["#86b6ef", "#2a78d6"], width=0.5,
       yerr=[rates - low, high - rates], capsize=8, ecolor="#0b0b0b")
ax.set_ylabel("conversion rate")
ax.set_ylim(0, 0.15)
ax.set_title("Checkout conversion (95% CI)")
plt.tight_layout()
plt.show()
for v in rates.index:
    print(f"{v}: {rates[v]:.2%}  (95% CI {low[v]:.2%} to {high[v]:.2%})")
A: 9.53%  (95% CI 8.32% to 10.89%)
B: 11.99%  (95% CI 10.63% to 13.49%)

The intervals barely overlap. Note that overlapping individual intervals do not prove there is no difference; the proper comparison is a test (or interval) for the difference, which comes next.

Step 5: Test the primary metric

A two-proportion z-test compares the conversion rates. Its statistic uses the pooled proportion p̄ (all orders / all visitors) under H₀:

text
z = (p̂_B − p̂_A) / √( p̄(1 − p̄)(1/n_A + 1/n_B) )
python · try it yourself
import math
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep

rng = np.random.default_rng(50)
n = 4000
users = pd.DataFrame({
    "variant": rng.choice(["A", "B"], size=n),
    "device": rng.choice(["mobile", "desktop"], size=n, p=[0.6, 0.4]),
})
base = np.where(users["device"] == "mobile", 0.08, 0.12)
lift = np.where(users["variant"] == "B", 0.025, 0.0)
users["converted"] = rng.random(n) < base + lift
users["revenue"] = np.where(users["converted"], rng.gamma(4, 12, n).round(2), 0.0)

g = users.groupby("variant")["converted"].agg(["sum", "size"])
xA, nA = int(g.loc["A", "sum"]), int(g.loc["A", "size"])
xB, nB = int(g.loc["B", "sum"]), int(g.loc["B", "size"])

# by hand
pA, pB = xA / nA, xB / nB
pooled = (xA + xB) / (nA + nB)
z = (pB - pA) / math.sqrt(pooled * (1 - pooled) * (1 / nA + 1 / nB))
print(f"by hand:     z = {z:.3f}, p = {2 * stats.norm.sf(abs(z)):.4f}")

# with statsmodels
z2, p2 = proportions_ztest([xB, xA], [nB, nA])
print(f"statsmodels: z = {z2:.3f}, p = {p2:.4f}")

low, high = confint_proportions_2indep(xB, nB, xA, nA, compare="diff", method="newcomb")
print(f"difference B - A = {pB - pA:+.4f}, 95% CI ({low:+.4f}, {high:+.4f})")
print(f"relative lift = {(pB - pA) / pA:+.1%}")
by hand:     z = 2.513, p = 0.0120
statsmodels: z = 2.513, p = 0.0120
difference B - A = +0.0246, 95% CI (+0.0054, +0.0439)
relative lift = +25.8%

p ≈ 0.012 < 0.05: we reject H₀. The 95% interval for the difference lies entirely above 0. B raises conversion by roughly 2.5 percentage points, but the true lift could plausibly be anywhere from about half a point to about four and a half points.

Step 6: The secondary metric, revenue per visitor

Revenue per visitor is extremely skewed: about 90% of the values are 0. The Welch t-test still works here thanks to the Central Limit Theorem (n ≈ 2,000 per group), but let's double-check with a bootstrap confidence interval, which resamples the data instead of relying on a formula:

python · try it yourself
import numpy as np
import pandas as pd
from scipy import stats

rng = np.random.default_rng(50)
n = 4000
users = pd.DataFrame({
    "variant": rng.choice(["A", "B"], size=n),
    "device": rng.choice(["mobile", "desktop"], size=n, p=[0.6, 0.4]),
})
base = np.where(users["device"] == "mobile", 0.08, 0.12)
lift = np.where(users["variant"] == "B", 0.025, 0.0)
users["converted"] = rng.random(n) < base + lift
users["revenue"] = np.where(users["converted"], rng.gamma(4, 12, n).round(2), 0.0)

a = users.loc[users["variant"] == "A", "revenue"].to_numpy()
b = users.loc[users["variant"] == "B", "revenue"].to_numpy()
print(f"share of zero revenue: A {np.mean(a == 0):.1%}, B {np.mean(b == 0):.1%}")

welch = stats.ttest_ind(b, a, equal_var=False)
print(f"Welch t = {welch.statistic:.3f}, p = {welch.pvalue:.4f}")

boot = np.random.default_rng(1)
diffs = [boot.choice(b, b.size).mean() - boot.choice(a, a.size).mean() for _ in range(5000)]
low, high = np.percentile(diffs, [2.5, 97.5])
print(f"difference in revenue per visitor = {b.mean() - a.mean():+.2f} EUR")
print(f"bootstrap 95% CI: ({low:+.2f}, {high:+.2f}) EUR")
share of zero revenue: A 90.5%, B 88.0%
Welch t = 2.232, p = 0.0257
difference in revenue per visitor = +1.23 EUR
bootstrap 95% CI: (+0.13, +2.31) EUR

Both methods agree: B earns more per visitor, and the bootstrap interval excludes 0. Because revenue was a secondary metric, we report it as supporting evidence rather than as a second headline result.

Step 7: Segments, with care

Managers always ask "does it work on mobile and desktop?". Segment results are useful, but they are exploratory: every extra test adds a chance of a false positive, and each segment has less data, hence less power.

python · try it yourself
import numpy as np
import pandas as pd
from statsmodels.stats.proportion import proportions_ztest

rng = np.random.default_rng(50)
n = 4000
users = pd.DataFrame({
    "variant": rng.choice(["A", "B"], size=n),
    "device": rng.choice(["mobile", "desktop"], size=n, p=[0.6, 0.4]),
})
base = np.where(users["device"] == "mobile", 0.08, 0.12)
lift = np.where(users["variant"] == "B", 0.025, 0.0)
users["converted"] = rng.random(n) < base + lift
users["revenue"] = np.where(users["converted"], rng.gamma(4, 12, n).round(2), 0.0)

for device, seg in users.groupby("device"):
    g = seg.groupby("variant")["converted"].agg(["sum", "size"])
    rate = g["sum"] / g["size"]
    z, p = proportions_ztest(g.loc[["B", "A"], "sum"], g.loc[["B", "A"], "size"])
    print(f"{device:8s} A={rate['A']:.2%} (n={g.loc['A', 'size']})  "
          f"B={rate['B']:.2%} (n={g.loc['B', 'size']})  p={p:.3f}")
desktop  A=10.63% (n=837)  B=14.12% (n=800)  p=0.032
mobile   A=8.74% (n=1178)  B=10.55% (n=1185)  p=0.137

Both segments move in the same direction as the overall result. The desktop test happens to fall below 0.05 and the mobile test doesn't, but that is not evidence that B "only works on desktop": each segment has about half the data, hence much less power, and the two lifts are compatible with each other. Declaring a segment winner from exploratory splits like this would be a classic pitfall. If the team really cares about devices, it should plan a test of the device × variant interaction in advance.

Step 8: Was the test big enough?

Power analysis answers how many visitors were needed to detect a given lift. Using the effect we observed (9.5% → 12.0%) and two alternatives, at α = 0.05 and 80% power:

python · try it yourself
import math
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize

analysis = NormalIndPower()
for p_new in [0.110, 0.120, 0.130]:
    h = proportion_effectsize(p_new, 0.095)            # Cohen's h for two proportions
    n_per_group = analysis.solve_power(effect_size=h, alpha=0.05, power=0.80)
    print(f"9.5% -> {p_new:.1%}: need {math.ceil(n_per_group):5d} visitors per variant")

h = proportion_effectsize(0.120, 0.095)
print(f"power with 2000 per group for 9.5% -> 12.0%: {analysis.power(h, nobs1=2000, alpha=0.05):.2f}")
9.5% -> 11.0%: need  6411 visitors per variant
9.5% -> 12.0%: need  2403 visitors per variant
9.5% -> 13.0%: need  1273 visitors per variant
power with 2000 per group for 9.5% -> 12.0%: 0.72

With about 2,000 visitors per variant the test had roughly 72% power for a 2.5-point lift: slightly under the usual 80% target (about 2,400 per variant would have reached it). We were somewhat lucky to detect the effect, and a lift of only 1.5 points would have needed more than three times as many visitors. In the next test, the team should plan the sample size with this calculation before starting.

Step 9: The report

Result. In a randomised test with 4,000 checkout visitors, the redesigned checkout (B) converted 12.0% of visitors versus 9.5% for the current page (A), a difference of +2.5 percentage points (95% CI +0.5 to +4.4; two-proportion z-test, p = 0.012). Revenue per visitor rose by about 1.23 EUR (bootstrap 95% CI +0.13 to +2.31 EUR). Traffic was split evenly (sample-ratio check p ≈ 0.64) and both devices showed the same direction of effect.

Recommendation. Roll out variant B. Monitor conversion after launch, since the plausible lift ranges from small to substantial.

Ideas to extend the project

  1. Change lift to 0.0 in the data generator and rerun every step: how often would you "find" an effect? (Try a few different seeds.)
  2. Add a third variant C and compare all three with a chi-square test, followed by pairwise tests with a Holm correction.
  3. Simulate "peeking" after every 500 visitors and measure how much the false-positive rate grows.
  4. Replace the bootstrap with stats.mannwhitneyu and discuss what that test actually compares.

Test yourself

Why was a chi-square test run on the number of visitors in A and B before analysing conversions?

  1. To test whether B converts better
  2. To detect a sample ratio mismatch, which would point to a broken randomisation
  3. Because chi-square is required before every z-test
  4. To compute revenue per visitor

The 95% CI for the difference in conversion (B − A) is (+0.5, +4.4) percentage points. Which statement is correct?

  1. B is certainly 2.5 points better
  2. The data are consistent with a lift anywhere from about 0.5 to 4.4 points; 0 is not plausible at the 95% level
  3. There is a 95% chance that the lift is exactly 2.5 points
  4. The test was not significant

The mobile segment alone gives p = 0.14. What is the right interpretation?

  1. B does not work on mobile
  2. The segment has less data, so its test has less power; the direction agrees with the overall result
  3. The overall result is wrong
  4. We should only launch B on desktop