…
…
Statistics and Data Analysis Fundamentals · Lesson 42 / 44 · A/B tests and fallacies
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
From April 15 to 28, Bazaar compared the new mobile checkout page (B) with the old one (A): half of the sessions were sent to the new page at random. The product team said "add-to-cart went up on the new page" and released the design to all mobile users on May 1. In this lesson you will analyze the test data from start to finish, step by step, and decide for yourself whether the decision was right.
Since lesson 29 you have worked with the same 1,000 sessions: the shuffle test (29), the bootstrap interval (30), the two-proportion z test (31), power (33), chi-square (34), and the funnel (40) were all applied to this data. In each lesson you looked at one part of the experiment. In this lesson we put the parts together and do the job a product team really has to do: read a test from start to finish and give a reasoned answer to "should we release it?" You will not learn a new statistical test. What is new is the order in which the tests are used, and why.
At the end of the lesson you will fill in the outline below with the Bazaar data yourself. Each row matches one section of the lesson:
| Section | Question | Bazaar's answer (at the end of the lesson) |
|---|---|---|
| Plan | Which metric decides, and what must not get worse? | Primary: purchase rate · guardrail: checkout time |
| Check | Are the groups really random and balanced? | 500 / 500, new visitors 42.6% / 42.8% |
| Primary result | How big is the difference, and could it be chance? | 13% → 8%, p = 0.0099 |
| Guardrail | Did anything get worse? | Checkout time 98.7 → 133.4 sec |
| Funnel | Where does the difference come from? | The step from the checkout page to purchase |
| Decision | Do we release it? | ? |
In lesson 3 you saw why an experiment is strong: if chance decides who goes into which group, the two groups are similar on average in every way except the change. The difference between them is the effect of the change. In digital products this experiment is called an A/B test: A is the old version (the control), B is the new version.
Why do we need one? An experiment measures many numbers: add-to-cart, reaching the checkout page, purchase, checkout time, time on the page, and more. After the test ends, it is tempting to go through these numbers one by one and ask "which one came out in favor of B?" That multiplies the type I error from lesson 33: if you look at twenty metrics, you should expect one of them to look "significant" by chance, even when nothing changed. So a good A/B test writes down four things before it starts.
The primary metric is the one number that decides. It measures the real goal of the work; for Bazaar this is the purchase rate (how many sessions end in a purchase). The guardrail metric is a secondary number that must not get worse. It does not decide on its own, but it has a "veto": if the primary metric improves but the guardrail gets clearly worse, the change is not released as it is. For Bazaar, checkout time is a good guardrail: if checkout gets longer, customers get annoyed, and the price shows up in later purchases. The sample size comes from the power calculation of lesson 33. The duration is at least one full week, preferably two, because weekday and weekend visitors behave differently; a test of only three days measures only the visitors of certain days.
Let's look at Bazaar's sample size with the tool from lesson 33. If the team wanted to catch a change in purchase rate from 13% to 8% (or the other way around), the group size needed is:
import numpy as np from statsmodels.stats.proportion import proportion_effectsize from statsmodels.stats.power import NormalIndPower h = proportion_effectsize(0.13, 0.08) power_calc = NormalIndPower() print("Per group for 80% power:", int(np.ceil(power_calc.solve_power(h, alpha=0.05, power=0.8)))) print("Power with 500 per group:", round(power_calc.power(h, nobs1=500, alpha=0.05), 3))
OutputPer group for 80% power: 583
Power with 500 per group: 0.738For 80% power, 583 sessions per group would be needed. The test ran with 500 per group, so its power is about 74%. In other words, if a real difference of this size exists, the test catches it with a probability of about three in four. This is not a flaw, but it goes in the "limitations" line of the report. Remember the warning from lesson 33: the power calculation is done before collecting data. Power calculated with the observed difference after the test ends gives no new information.
Every number measured in an experiment has a role. Match Bazaar's five numbers with their roles:
In Bazaar's checkout page test, match each number with its role.
For each row, pick its match from the list, then check.
Why do we need one? It is easy to think "if the groups were assigned at random, there is no need to check." But software does the assignment, and software can make mistakes: in one browser version the new page may not open and those users silently fall into A, or the new page may open slowly and some sessions close before they are recorded. Then the groups are no longer random, and the difference between them can be the result of this bug, not of the design. The check takes a minute. If you skip it, the whole analysis is built on a bad foundation.
The randomization check has two questions. The first: does the split match what was expected? In a test planned as a 50/50 split, 500 of 1,000 sessions should go to A and 500 to B. Chance moves this a little, but not much. A deviation from the expected ratio that chance cannot explain is called a sample ratio mismatch (SRM). The binomtest from lesson 31 tests it: "If the chance of falling into B is 0.5 in 1,000 trials, how often does a split this uneven happen?" The second question: are the pre-existing traits similar in the two groups? If a trait that was fixed before the experiment and that the design cannot affect (such as visiting the site for the first time) is clearly different in the two groups, there is a problem with the assignment.
import pandas as pd from scipy import stats s = pd.read_csv("sessions.csv") n_a = int((s["group"] == "A").sum()) n_b = int((s["group"] == "B").sum()) print("A:", n_a, "| B:", n_b) print("Split p:", stats.binomtest(n_b, n_a + n_b, 0.5).pvalue) print("New visitor rate:", s.groupby("group")["new_visitor"].mean().round(3).tolist())
OutputA: 500 | B: 500
Split p: 1.0
New visitor rate: [0.426, 0.428]The split is exactly 500 / 500; p = 1.0, so no split could be more balanced than this. The new visitor rate is 42.6% in A and 42.8% in B: almost the same. The assignment looks sound, so we can move on to the analysis.
But what if the split were 540 / 460? At first glance you might say "a 4 percent deviation, not important." The cell below is this whole step: run it as it is first, then try the made-up numbers.
Try it now· not graded; doesn't affect progress
For 540 / 460, p = 0.0124: if the 50/50 assignment worked correctly, a split this uneven would appear only once in a hundred tests. For 510 / 490, p = 0.548; this much wobble is ordinary. Now make a decision:
In a test the split came out 540 / 460 (binomtest p = 0.012). What do you do?
If the check passes, the plan's main question comes next: did B change the purchase rate? This is the difference between the rates of two independent groups; the two-proportion z test and the difference interval from lesson 31 are made for exactly this job. We keep the direction rule from lesson 29: the difference is always B − A (new minus old). The cell below is this whole step:
Try it now· not graded; doesn't affect progress
In A, 65 of 500 sessions ended in a purchase (13%); in B, 40 did (8%). The difference B − A = −0.05; z = −2.58, two-sided p = 0.0099; the 95% interval for the difference is −0.0884 to −0.012. The whole interval is below zero: the new page seems to have lowered the purchase rate by at least 1.2 and at most 8.8 points. Because this is an experiment, we can say "lowered"; unlike the observational data in lesson 37, the only systematic difference between the groups is the page itself.
You can describe the size of a difference in two ways. The absolute difference is the difference of the two rates: 5 points. The relative difference is that difference divided by the starting rate: what percent of the purchases disappeared? Both appear in reports, and they are easy to mix up. Follow it line by line:
Run the code line by line: see which line runs next, the variable boxes and the output.
a = 65 / 500 b = 40 / 500 absolute = b - a relative = absolute / a print("A:", a, "| B:", b) print("Absolute difference (points):", round(absolute * 100, 1)) print("Relative difference (%):", round(relative * 100, 1))
The absolute difference is −5 points, and the relative difference is −38.5%: of every 13 people who bought in A, about 5 are gone in B. The sentence "purchases fell 5%" is therefore unclear: 5 points or 5 percent? Write both in the report: "purchase rate fell from 13% to 8% (5 points, relative 38.5%)."
The primary result is clear, but it contradicts the product team's sentence: "add-to-cart went up in B." How can both be true at the same time? Let's split the funnel from lesson 40 by group:
import pandas as pd s = pd.read_csv("sessions.csv") print(s.groupby("group")[["added_to_cart", "reached_checkout", "purchased"]].mean().round(3)) checkout = s[s["reached_checkout"] == 1] print("Purchase among those who reached checkout:", checkout.groupby("group")["purchased"].mean().round(3).tolist())
Output added_to_cart reached_checkout purchased
group
A 0.31 0.192 0.13
B 0.36 0.198 0.08
Purchase among those who reached checkout: [0.677, 0.404]The team was right: add-to-cart is a bit higher in B (36% against 31%). But this difference is not significant (p = 0.094, as in lesson 31), and reaching the checkout page is almost the same in the two groups (19.2% and 19.8%). The real split happens at the last step: of those who reach the checkout page, 67.7% buy in A and only 40.4% in B. The new design loses customers at the step that was changed, the checkout page. The mistake "if an upper funnel step goes up, the result goes up too" falls apart here: a small rise in an upper step does not make up for a large loss in a lower step.
Now the guardrail metric. Checkout time is measured only in sessions that reach the checkout page; the difference in means is tested with the Welch t test from lesson 32. The code for this step:
Try it now· not graded; doesn't affect progress
Checkout time averages 98.7 seconds in A and 133.4 seconds in B: B − A = 34.7 seconds, Welch p = 4.9e-14, and the interval for the difference is 26.3 to 43.1 seconds. The guardrail metric got worse too: finishing checkout on the new page takes more than half a minute longer. The funnel and the guardrail tell the same story: the new design made the checkout step harder.
Look at the three metrics side by side. The code keeps the numbers from lesson 31 ready; change the metric and look at the rates and p:
Change the metric: at which step do the two groups really separate?
Pick a value; predict the output first, then look.
1from statsmodels.stats.proportion import proportions_ztest2metric = "added_to_cart"3counts = {"added_to_cart": (155, 180), "reached_checkout": (96, 99), "purchased": (65, 40)}4a, b = counts[metric]5z, p = proportions_ztest([b, a], [500, 500])6print("Metric:", metric)7print("A:", a / 500, "| B:", b / 500)8print("p:", round(p, 4))
Metric: added_to_cart A: 0.31 | B: 0.36 p: 0.0939
Faded lines didn't run with this value. In add-to-cart, B is ahead, but the difference cannot be told apart from chance (p = 0.094). In reaching the checkout page, the two groups are almost the same (p = 0.81). In purchase, A is clearly ahead (p = 0.0099). The third row makes the decision; the first two rows only show where the path splits.
Now we can name the team's mistake. Instead of the primary metric, they looked at a metric from an upper step of the funnel (add-to-cart), and the difference in that metric was not even significant. Most likely no plan was written before the test started, or the plan that was written was not followed. Go back to the start of the test and build the plan yourself:
It is April 1. The product team is planning the new checkout page test and asks you for a recommendation. Which one do you recommend?
Pick an option and see what happens. There are no points; you can try the other options too.
Why does it matter? Waiting two weeks for a test takes patience, and teams look at the dashboard every morning. Looking alone is harmless; the problem is when a look turns into a decision: "p is below 0.05 today, let's finish the test." In Bazaar's test, the cumulative p value went like this, day by day (a two-proportion z test with all sessions up to that day):
| Date | A purchases / sessions | B purchases / sessions | Cumulative p |
|---|---|---|---|
| April 15 | 5 / 38 | 2 / 33 | 0.317 |
| April 17 | 14 / 110 | 7 / 117 | 0.080 |
| April 18 | 17 / 144 | 11 / 156 | 0.157 |
| April 21 | 33 / 252 | 21 / 261 | 0.062 |
| April 24 | 50 / 360 | 31 / 352 | 0.033 |
| April 27 | 63 / 457 | 36 / 466 | 0.003 |
| April 28 | 65 / 500 | 40 / 500 | 0.0099 |
p does not fall along a straight line; it goes up and down. On April 24 it drops below 0.05 for the first time. Because this test has a real effect, it stays below in the following days, and on the last day it is 0.0099. Here, stopping early would have given the same decision. But what happens in a test with no effect at all?
The early-peeking trap is that checking the test every day and stopping on the first day with p < 0.05 pushes the type I error rate far above α. Every look is a separate test, and each has a 5% chance of a false alarm; as the number of looks grows, the chance of "at least one significant-looking day" adds up. In lesson 33 you saw the A/A test: both groups see the same page, and the real difference is zero. Let's run 10,000 experiments in that same world. In each group there are 36 sessions a day, the purchase rate is 10.5% in both groups, and the test lasts 14 days. The team knows the numbers are small in the first two days and does not look; from day 3 on, they look every morning:
import numpy as np from scipy import stats rng = np.random.default_rng(42) runs, daily = 10000, 36 day = np.arange(3, 15) a = rng.binomial(daily, 0.105, size=(runs, 14)).cumsum(axis=1)[:, 2:] b = rng.binomial(daily, 0.105, size=(runs, 14)).cumsum(axis=1)[:, 2:] n = daily * day pooled = (a + b) / (2 * n) se = np.sqrt(pooled * (1 - pooled) * (2 / n)) z = (b / n - a / n) / se p = 2 * stats.norm.sf(np.abs(z)) print("Looking only on day 14:", (p[:, -1] < 0.05).mean()) print("Looking every day from day 3:", (p < 0.05).any(axis=1).mean())
OutputLooking only on day 14: 0.052
Looking every day from day 3: 0.1821The code applies the two-proportion z test from lesson 31 to all 12 looks of 10,000 experiments at once: cumsum gives the cumulative purchase count at the end of each day, pooled is the combined rate, and se is the standard error of the difference. The result: an analyst who looks only on the planned last day gives a false alarm in 5.2% of the experiments with no difference, as α predicts. An analyst who looks every day and stops on the first "significant" day does so in 18.2%. The chance of a false alarm became three and a half times larger, and no calculation mistake was made; the only mistake was choosing the stopping rule based on the data.
The fix is simple: set the sample size and duration beforehand, and wait until that day for the decision. If you really need to look often and decide early, there are sequential testing methods designed for this; they keep the threshold stricter at every look, so the total false alarm rate stays at 5%. We will not go into them in this course.
It is the morning of April 24, and the cumulative p = 0.033. The plan says the test ends on April 28. Should the test end today?
It is time to fill in the report. The randomization is sound (500 / 500, new visitors 42.6% / 42.8%). The primary metric is significantly worse in B: purchase fell from 13% to 8% (p = 0.0099; difference −8.8 to −1.2 points). The guardrail metric also got worse: checkout is 34.7 seconds longer. The funnel shows that the loss is on the checkout page. Decision: B should not have been released. Thinking "we got a significant result, at least we learned something, let's release it anyway" is also a mistake: the decision follows the direction of the primary metric, and here the direction is bad. What was learned is that the new design needs fixing at the checkout step; a fixed version is tested again in a new test.
The design went live on May 1 anyway. Part of the drop in mobile orders comes from this decision. But something else happened on May 1 too: the ads were cut (lesson 41). When two changes happen on the same day, separating how much of the drop comes from each is a new problem; we will return to it in the next lesson.
A good test report starts with what the reader most wants to know and continues with the evidence that supports it. Put the report sections in order:
Put the sections of Bazaar's test report in the order management will read them.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The logic of A/B testing is the same everywhere. A fictional news site is testing two headline styles: the old style is plain statements, the new style is headlines that ask a question. Each style was shown 20,000 times, and the click rate was chosen as the primary metric:
from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep clicks = {"old": 820, "new": 920} n = 20000 z, p = proportions_ztest([clicks["new"], clicks["old"]], [n, n]) low, high = confint_proportions_2indep(clicks["new"], n, clicks["old"], n) print("Click rate old:", clicks["old"] / n, "| new:", clicks["new"] / n) print("Difference (new - old):", round((clicks["new"] - clicks["old"]) / n, 4)) print("z =", round(z, 2), "| p =", round(p, 4)) print("95% interval:", round(low, 4), round(high, 4))
OutputClick rate old: 0.041 | new: 0.046
Difference (new - old): 0.005
z = 2.45 | p = 0.0142
95% interval: 0.001 0.009The click rate rose from 4.1% to 4.6% (p = 0.014; difference 0.1 to 0.9 points). But the site's guardrail metric, reading time, changed too: the time spent on the page by people who opened the story fell from an average of 74 seconds to 61 seconds (Welch p < 0.001 in the team's report). The question headline pulls more people in, but those who come in read the story less; perhaps the headline promises something the story does not give.
On the news site, the click rate rose significantly and reading time fell significantly. Is the new headline style released?
The order for reading an A/B test is the same in every test. First the plan: primary metric, guardrail metric, sample, and duration, all before the data. Then the check: does the split match what was expected, and are the pre-existing traits balanced? If the check fails, the analysis stops. Then the primary metric: difference, interval, and p; the decision comes from this line. Then the guardrail metric: was a cost paid? Then the funnel and subgroups: why is the result like this? These explain, they do not prove. Last, the decision and its reasons. If Bazaar had followed this order, the new checkout page would not have opened on May 1.
Is the purchase difference in the same direction for new and returning visitors?
import pandas as pd s = pd.read_csv("sessions.csv") t = s.pivot_table(index="new_visitor", columns="group", values="purchased", aggfunc="mean").round(3) t["diff"] = (t["B"] - t["A"]).round(3) print(t)
Outputgroup A B diff
new_visitor
0 0.146 0.087 -0.059
1 0.108 0.070 -0.038Among returning visitors (0), A is at 14.6% and B at 8.7%; among new visitors (1), A is at 10.8% and B at 7.0%. A is ahead in both subgroups, so the result does not come from only one type of visitor. A look like this builds trust, but as the number of subgroups grows, it becomes easier for one of them to differ by chance (the multiple-looks warning in section 2). Subgroups are for explaining; the decision is still made from all groups.
The check, the primary result, and the guardrail metric together:
import pandas as pd from scipy import stats from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep s = pd.read_csv("sessions.csv") A, B = s[s[] == ], s[s[] == ] (, stats.binomtest((B), (s), 0.5).pvalue) z, p = proportions_ztest([B[].(), A[].()], [(B), (A)]) low, high = confint_proportions_2indep(B[].(), (B), A[].(), (A)) diff = B[].mean() - A[].mean() (, (diff, 3), , (p, 4), , (low, 3), (high, 3)) ta, tb = A[].dropna(), B[].dropna() r = stats.ttest_ind(tb, ta, equal_var=) (, (tb.mean() - ta.mean(), 1), , f)
Making the decision from a metric at an upper funnel step instead of the primary metric. At Bazaar, add-to-cart rose 5 points (not even significant), and purchase fell 5 points. A rise in an upper step does not make up for a loss in a lower one. Choose the primary metric before the test starts and decide by it; use the funnel steps and subgroups only to explain the result.
binomtest; at Bazaar 500 / 500, p = 1.0; it would have been p = 0.012 with 540 / 460) and the balance of pre-existing traits (new visitors 42.6% / 42.8%). Then come the primary metric (13% → 8%, p = 0.0099), the guardrail metric (+34.7 sec), and the funnel; the funnel and subgroups explain, they do not prove.Next lesson: we will study common analysis fallacies such as Simpson's paradox, survivorship bias, and multiple comparisons, and separate the two changes of May 1 from each other.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputSplit p: 1.0
Purchase B - A: -0.05 | p: 0.0099 | interval: -0.088 -0.012
Checkout time B - A: 34.7 | p: 4.9e-14In the exercises you will collect these lines in a function called ab_report and apply it to other experiments too. Checkout time exists only in sessions that reach the checkout page; dropna() drops the empty values, so both the mean and the Welch test are computed only from those sessions.