Hypotheses and Metrics
Lesson opener
In one line: Writing H0 / H1 in plain English for a product change.
Why it matters: Pre-registration stops metric shopping and one-sided peeking after the fact.
Before this lesson: What is A/B testing / Inferential stats
Before you start
| Resource | Link |
|---|---|
| Previous | What is A/B testing |
| Next | Sample size and power |
| Prerequisites | What is A/B testing, Inferential stats |
| Time | ~50 minutes |
What you will learn
- Writing H0 / H1 in plain English for a product change
- Choosing a primary metric and guarding against metric shopping
- Computing conversion rates from experiment tables
- Guardrails, directionality, and a metric registry teammates can review
Pinned libraries for this course
pip install -r docs/abtest/requirements.txtPinned in docs/abtest/requirements.txt:
numpy==2.1.3
scipy==1.14.1
pandas==2.2.3
statsmodels==0.14.4This lesson uses pandas and the standard library offline. Proportion tests appear in Analyzing results with statsmodels.
Hypotheses before looking at data
H0: The new checkout button does not change conversion rate vs control.
H1: The new button changes conversion rate (two-sided) or increases it (one-sided — pre-register which).
Write hypotheses in the ticket before the first exposure. If the team only phrases H1 after seeing a green chart, you are storytelling, not testing.
WHY Pre-registration stops metric shopping and one-sided peeking after the fact.
WHEN In the experiment brief, same day you pick the salt and window.
Demo 1 — State hypotheses as data
# Offline demo: encode H0/H1 and direction for a primary metric
def state_hypotheses(primary_metric: str, direction: str = "two-sided") -> dict:
if direction not in {"two-sided", "increase", "decrease"}:
raise ValueError("direction must be two-sided|increase|decrease")
return {
"H0": f"{primary_metric}: treatment equals control",
"H1": f"{primary_metric}: treatment differs ({direction})",
"primary_metric": primary_metric,
"direction": direction,
}
spec = state_hypotheses("checkout_cvr", "increase")
print(spec)
assert spec["direction"] == "increase"
assert "equals" in spec["H0"]A Bengaluru D2C checkout PM might choose increase only if leadership already committed to shipping any non-negative lift and you still want a one-sided test. Prefer two-sided unless the brief explicitly locks direction.
Primary metric vs vanity metrics
Primary metric — one outcome the decision hinges on (e.g. purchase conversion among exposed users).
Secondary metrics — learning only; do not flip the ship decision unless pre-registered as co-primaries with multiplicity control.
Guardrails — metrics that can veto a win (payment errors, refund rate, latency).
WHY Multiple unplanned metrics inflate false wins.
WHEN Before launch: name primary, secondaries, and guardrails in one table.
Demo 2 — Conversion rate by variant
# Offline demo: CVR by variant from an experiment frame
import pandas as pd
df = pd.DataFrame({
"variant": ["A"] * 100 + ["B"] * 100,
"converted": [1] * 12 + [0] * 88 + [1] * 18 + [0] * 82,
})
def cvr_by_variant(frame: pd.DataFrame) -> pd.Series:
return frame.groupby("variant")["converted"].mean()
rates = cvr_by_variant(df).round(3)
print(rates)
assert abs(float(rates["A"]) - 0.12) < 1e-9
assert abs(float(rates["B"]) - 0.18) < 1e-9Demo 3 — Guardrail check
# Offline demo: guardrail must not drop more than max_drop
def guardrail_ok(control_rate: float, treatment_rate: float, max_drop: float = 0.01) -> bool:
"""False if treatment hurts a guardrail metric by more than max_drop."""
return (treatment_rate - control_rate) >= -max_drop
assert guardrail_ok(0.12, 0.115) is True
assert guardrail_ok(0.12, 0.09) is False
print(guardrail_ok(0.02, 0.021, max_drop=0.005), guardrail_ok(0.02, 0.03, max_drop=0.005))[!important] Pick the primary metric and direction before peeking at results.
Metric shopping and the Indian standup trap
In a Hyderabad SaaS standup, someone says: "CVR is flat but add-to-cart is up — ship?" That is metric shopping unless add-to-cart was the pre-registered primary. Same trap with "revenue per user on Android only" after the overall test is null.
Write a short metric registry in the repo or ticket so analysts cannot invent winners from a dashboard buffet.
Demo 4 — Metric registry validator
# Offline demo: only registered metrics may drive ship decisions
REGISTRY = {
"primary": "checkout_cvr",
"secondaries": ("add_to_cart", "revenue_per_user"),
"guardrails": ("pay_error_rate", "p95_checkout_ms"),
}
def may_decide_on(metric: str, registry: dict = REGISTRY) -> bool:
return metric == registry["primary"]
assert may_decide_on("checkout_cvr") is True
assert may_decide_on("add_to_cart") is False
print("decide on:", REGISTRY["primary"])
print("learning only:", REGISTRY["secondaries"])Demo 5 — Absolute vs relative language
PMs mix " +1 pp" and " +10% relative" in the same sentence. Encode both so the brief stays unambiguous.
# Offline demo: absolute (pp) vs relative lift wording
def describe_lift(control: float, treatment: float) -> dict:
abs_pp = treatment - control
rel = (treatment - control) / control if control else float("nan")
return {
"absolute_pp": round(abs_pp, 4),
"relative": round(rel, 4),
"plain": f"{abs_pp:+.1%} absolute points; {rel:+.1%} relative",
}
print(describe_lift(0.10, 0.11))
assert describe_lift(0.10, 0.11)["absolute_pp"] == 0.01Choosing conversion vs revenue as primary
For a first checkout-colour test, conversion among exposed users is usually cleaner than revenue: revenue is heavy-tailed (one wedding-order in Surat can dominate), needs longer windows, and mixes price tests with UX. Revenue can be secondary. If the change is a fee table, revenue (or contribution margin) may be primary — say so explicitly.
WHY Heavy tails and delayed cash distort early readouts.
WHEN Match the metric to the change mechanism.
Demo 6 — Unit and denominator check
Wrong denominator is a silent bug: conversions / all app opens ≠ conversions / exposed checkout viewers.
# Offline demo: refuse analysis if denominator population is wrong
def cvr(successes: int, exposed: int) -> float:
if exposed <= 0:
raise ValueError("exposed must be positive")
return successes / exposed
def assert_same_population(exposed_ids: set[int], converted_ids: set[int]) -> None:
extra = converted_ids - exposed_ids
if extra:
raise ValueError(f"conversions outside exposure set: {sorted(extra)[:5]}")
exposed = {1, 2, 3, 4, 5}
converted = {2, 4}
assert_same_population(exposed, converted)
print("cvr:", round(cvr(len(converted), len(exposed)), 3))
try:
assert_same_population(exposed, {2, 4, 99})
except ValueError as exc:
print("caught:", str(exc)[:40])How Pune and Bengaluru teams usually fight about metrics
Picture a checkout review in Pune: growth wants purchase CVR, finance wants contribution margin after COD returns, design wants "tap rate on the green button." All three can be true interests. Only one can be the confirmatory primary for a single test. Write the registry in the ticket and paste it into the experiment platform description so a new analyst joining mid-week does not invent a fourth primary from a Looker explore.
A Hyderabad SaaS onboarding test faces the same pressure with "activated within 7 days" versus "invited a teammate." Activation is often cleaner for a first test because invites are sparse and heavy-tailed. Keep invites as secondary learning. If leadership insists on a dual primary, you need a multiplicity plan — Bonferroni, hierarchical testing, or a pre-registered gate — not a handshake in Slack after results land.
Guardrails earn their keep when the primary looks good and payments hurt. A Jaipur D2C brand once saw CVR rise while pay-error rate crept up on UPI timeouts; shipping would have traded conversion for support tickets and chargebacks. Encode the max allowed guardrail drop in the same brief as H0/H1. The demos above are small, but the social contract is large: confirmatory metrics decide, secondaries explain, guardrails veto.
When someone proposes "we will decide based on whichever metric moves," treat that as a request to cancel the confirmatory label. You can still ship as a product bet. You cannot honestly claim a controlled A/B win. The next lesson sizes the traffic you need once the primary is locked; without that lock, sample-size math is theatre.
WHY Ambiguous metrics produce ambiguous readouts and eroded trust.
WHEN Before assignment, in the same document as salt and window.
Failure modes
- One-sided H1 chosen after seeing the sign of the lift.
- Primary switched to a secondary that "won."
- Guardrail ignored because primary looked good.
- City-sliced story treated as confirmatory without multiplicity plan.
Official stats docs define tests; your org defines which metric is allowed to decide. Keep hypotheses boring and written down.
Verified against numpy 2.1.3, scipy 1.14.1, pandas 2.2.3 (+1 more) documentation, September 2026.
Test yourself
- What does H0 usually claim in an A/B test?
- Why pre-register the primary metric?
- What does
cvr_by_variantreturn? - Name one guardrail metric for checkout.
- True or false: you may switch metrics after seeing p-values.
- What is a two-sided alternative?
- Why might conversion rate beat revenue for a first UX test?
- What does
guardrail_okprotect against? - Which stats lesson covers hypotheses?
- True or false: salt and metric choice are unrelated to honesty.