Hypothesis Testing Framework
Hypothesis Testing: The Universal Algorithm
Hypothesis testing is a universal algorithm that powers A/B tests, clinical trials, quantitative trading, and nearly every data-driven decision. The core idea is a simple four‑step function: take data → produce a decision. The underlying logic never changes—only the specific formula used in one of the steps changes depending on the type of data.
The Language of Hypothesis Testing
Before diving into the algorithm, four key terms define every hypothesis test:
Null hypothesis (H0): The boring status quo, the default reality that assumes no effect or difference.
Alternative hypothesis (H1): The exciting new theory you want to prove—the presence of an effect or difference.
Alpha (α): The BS threshold—the maximum risk you're willing to take of being wrong (usually set at 0.05).
P‑value (p): The probability of observing data as extreme as yours, assuming the null hypothesis is true.
The universal rule: If p<α, reject H0. If p≥α, fail to reject H0.
The Four‑Step Algorithm
Step 1: Formulate
Define the null hypothesis (H0) and the alternative hypothesis (H1).
Step 2: Calibrate
Set the significance level α (e.g., 0.05). This answers: How much evidence do I need?
Step 3: Compute
Calculate a test statistic that measures how far the observed data is from what H0 predicts. The formula depends on the data type.
Step 4: Decide
Compare the p‑value (derived from the test statistic) with α. If p<α, reject H0; otherwise, fail to reject H0 (the status quo remains).
Example 1: The Rigged Coin (Intuition Built from Scratch)
The Scenario
A friend claims a coin is fair (50 % heads, 50 % tails). You flip it 10 times and get 9 heads and 1 tail. Is your friend cheating, or is this just bad luck?
The Intuitive Logic
Assume the coin is fair (this is H0).
Calculate the probability of getting a result this extreme (9 or 10 heads) purely by chance.
If that probability is very low (below a BS threshold), call BS—reject fairness.
The Math
Probability of exactly 10 heads: (0.5)10≈0.0009766.
Probability of exactly 9 heads: 10×(0.5)10≈0.0097656.
Total probability of 9 or more heads = 0.0009766+0.0097656=0.0107422≈1.07 %.
So the p‑value is 0.0107. With a BS threshold (alpha) of 0.05, 0.0107<0.05. Therefore, reject H0—the coin is rigged.
The Rosetta Stone: Intuition → Formal Terms
Intuitive Idea | Formal Name | Symbol |
|---|---|---|
“Assume the coin is fair” | Null hypothesis | H0 |
“Your friend is cheating” | Alternative hypothesis | H1 |
1.07 % chance | P‑value | p |
5 % BS threshold | Significance level | α |
Key visualization: The outcomes can be plotted on a bar chart. The bars for 9 or 10 heads are tiny tails—this is the rejection region. If the observed outcome falls there, you reject H0.
Implementation in Python
from scipy.stats import binom_test
k = 9 # successes (heads)
n = 10 # total flips
p = 0.5 # null probability
p_value = binom_test(k, n, p, alternative='greater')
print(p_value) # 0.0107421875From Discrete to Continuous Data: The Need for a Universal Yardstick
Coin flips produce discrete data (countable). But business data like revenue, time on site, or weight are continuous—you cannot count them. For continuous data, the Z‑test becomes the standard tool, underpinned by the Central Limit Theorem.
Example 2: The Chip Factory (Z‑Test)
The Setup
A factory produces potato chips; target weight per bag is 100 g. From historical data, the machine’s standard deviation (σ) is 5 g. A sample of 50 bags shows a sample mean (xˉ) of 102 g. Is the machine broken (making heavier bags) or is the 2 g difference just random noise?
The Central Limit Theorem (CLT)
The Central Limit Theorem promises that, regardless of the shape of the population distribution, the distribution of sample means becomes approximately normal (bell‑shaped) for large enough sample sizes. This justifies using a Z‑test.
The Z‑Score Formula
Signal: xˉ−μ (how far from the target)
Noise (standard error): σ/n (how much variation is normal for that sample size)
Applying the Four Steps
Formulate: H0:μ=100 (machine is fine), H1:μ=100 (machine is broken).
Calibrate: α=0.05.
Compute:
Signal = 102−100=2.
Noise = 5/50≈0.707.
Z=2/0.707≈2.83.
Decide: A Z‑score of 2.83 corresponds to a p‑value of approximately 0.0047. Since 0.0047<0.05, reject H0—the machine is broken.
Visualizing the Z‑Score
A Z‑score of 2.83 lies far in the tail of the standard normal distribution—deep in the “very unlikely under H0” zone.
Python Implementation
from scipy.stats import norm
import numpy as np
mu = 100
sigma = 5
n = 50
x_bar = 102
signal = x_bar - mu
noise = sigma / np.sqrt(n)
z = signal / noise
p_value = 2 * (1 - norm.cdf(abs(z))) # two‑tailed test
print(f"Z = {z:.3f}") # Z = 2.828
print(f"p = {p_value:.4f}") # p = 0.0047The Flaw of the Z‑Test: Unknown Population Standard Deviation
The Z‑test assumes you know σ—the population standard deviation. In real A/B tests, you never know σ beforehand; you have to estimate it from the sample. That added uncertainty requires a different tool: the t‑test.
Example 3: The New Button (Two‑Sample t‑Test)
The Setup
Goal: increase time on site. Group A (old button) has 10 users, mean = 45 s, sample standard deviation = 15 s. Group B (new button) has 10 users, mean = 55 s, sample standard deviation = 15 s. Is the +10 s improvement real or random noise?
The t‑Statistic
Signal: difference in sample means
Noise: combined standard error (using sample standard deviations s instead of population σ)
Applying the Four Steps
Formulate: H0: new button does nothing (difference = 0). H1: new button works (difference ≠ 0).
Calibrate: α=0.05.
Compute:
Signal = 55 – 45 = 10.
Noise = 152/10+152/10=22.5+22.5=45≈6.71.
t=10/6.71≈1.49.
Decide: A t‑score of 1.49 (with approximately 18 degrees of freedom) gives a p‑value of about 0.15. Since 0.15≥0.05, fail to reject H0—the 10‑second improvement is likely just random noise.
Why Did the Test Fail?
The noise (6.71 s) was almost as large as the signal (10 s). Small sample sizes (n=10) produce massive noise.
Two Levers to Win
Increase signal: Make a much bigger improvement.
Increase sample size (n): The most common approach. More data shrinks the noise term because it divides by n.
Python Implementation
from scipy.stats import ttest_ind
group_a = [...] # list of 10 observed times
group_b = [...] # list of 10 observed times
t_stat, p_value = ttest_ind(group_a, group_b)
print(f"t = {t_stat:.2f}") # e.g., t = 2.29
print(f"p = {p_value:.4f}") # e.g., p = 0.0342With a different dataset (p = 0.0342 < 0.05), the test would succeed.
Example 4: The Red Button (Chi‑Square Test for Categorical Data)
The t‑test works for continuous variables (time, weight, money). But what about clicks? Yes/no (binary) data is categorical. For that, the chi‑square (χ2) test is used.
The Setup
100 visitors each see a blue button (A) or a red button (B). Blue: 10 sales (10 % conversion). Red: 20 sales (20 % conversion). Is red truly better, or is it a lucky fluke?
Mental Model: Observed vs. Expected
Observed (O): what actually happened (raw data)
Expected (E): what would happen if H0 were true (no difference between groups)
If the gap between O and E is large → real effect. If small → noise.
χ2 Formula
Difference O−E is squared to make errors positive and penalize big deviations.
Dividing by E normalizes: a difference of 5 is huge if E=10, but trivial if E=10000.
Applying the Four Steps
Formulate: H0: color doesn’t matter (conversion rate is the same). H1: color matters.
Build the observed table (2 × 2):
Group
Bought
Did Not Buy
Blue
10
90
Red
20
80
Build the expected table under H0: Overall conversion rate = 30/200 = 15 %. So expect 15 % of each group to buy:
Blue expected bought = 15, not bought = 85.
Red expected bought = 15, not bought = 85.
Compute χ2:
Blue bought: (10−15)2/15=1.6667
Blue not bought: (90−85)2/85≈0.2941
Red bought: (20−15)2/15=1.6667
Red not bought: (80−85)2/85≈0.2941
Sum: χ2≈3.92
This gives a p‑value of approximately 0.0477.
Decide: 0.0477<0.05 → reject H0 → the red button really is better (just barely).
Reality Check: One Sale Changes Everything
If red had gotten 19 sales instead of 20, the p‑value jumps to 0.0763 (not significant). Categorical data is low‑resolution; a single observation can flip the decision. Therefore, categorical tests require huge sample sizes for reliable conclusions.
Python Implementation
from scipy.stats import chi2_contingency
observed = [[10, 90],
[20, 80]]
chi2, p_value, dof, expected = chi2_contingency(observed)
print(f"χ² = {chi2:.2f}") # 3.92
print(f"p = {p_value:.4f}") # 0.0477The Decision Matrix: Which Test to Use?
Data Type | Question | Tool (when s unknown) | Rarely Used |
|---|---|---|---|
Categorical (yes/no, clicks) | “Is the conversion rate different?” | χ2 test | – |
Continuous (time, revenue) | “Is the average different?” (don’t know σ) | Two‑sample t‑test | – |
Continuous (manufacturing, science) | “Is the average off‑target?” (know σ) | – | One‑sample Z‑test |
Your job is not to be a human calculator. Your job is decision‑making. Know which tool matches your data and question.
Production Pitfall #1: P‑Hacking
P‑hacking is the temptation to peek at results repeatedly and stop the test as soon as p<0.05. P‑values bounce randomly, especially early on. Peeking invalidates the statistics by inflating the chance of a false positive.
The Professional Solution
Pre‑commit: Decide the sample size needed (e.g., 10,000 users) before the test starts.
Run the test – do not touch the dashboard.
No peeking – this is the cardinal sin of A/B testing.
Decide once – check the p‑value only at the predetermined sample size.
Production Pitfall #2: The “Google Problem” – Statistical vs. Practical Significance
The Scenario
A tiny code change at Google scale (50 million users) yields a 0.001 s improvement in search speed. Because the sample size is astronomical, the p‑value is virtually 0 — the effect is statistically significant.
Two Kinds of Significance
Statistical significance: “Is the effect real?” – yes, the math is certain it’s not random noise.
Practical significance: “Does it matter?” – a 0.001 s improvement is invisible to humans and provides no real value.
The Production Rule
Always check two things before deciding:
The p‑value → tells you if an effect actually exists (certainty).
The effect size → tells you if the effect is big enough to care about (magnitude).
A tiny p‑value does not mean a big effect. It only means we are very sure that some effect exists, no matter how small.
Summary: The Universal Algorithm in Action
The four‑step algorithm is universal:
Formulate H0 and H1
Set α
Compute the test statistic (the only part that changes with data type)
Compare p‑value to α and decide
The tests covered (binomial, Z, t, χ2) are all variations on this single framework. Once the logic is internalized, any new test is just a matter of plugging in the correct formula.

Ask anything
We've read this whole study set, so questions about it get the best answers.