Sequential experiments and anytime-valid inference
Continuous monitoring of a fixed-sample experiment can inflate false positives. Study Wald’s sequential probability ratio test and group-sequential α spending, then use e-values, test martingales and confidence sequences for inference that remains valid under continuous monitoring.
After this lesson you can
- Simulate how continuous monitoring of a fixed-sample test inflates Type I error.
- Implement Wald’s SPRT and justify its thresholds using Ville’s inequality.
- Design a group-sequential experiment using O’Brien–Fleming boundaries or Lan–DeMets spending functions.
- Define and combine e-values and test martingales to make anytime-valid decisions.
- Construct confidence sequences for a bounded mean and compare them with recalculated fixed-sample intervals.
Before you start
- 05Hypothesis testType I and type II errorsp-valueNeyman-Pearson lemmaGeneralized likelihood ratio testUniversal inference (split likelihood ratio test)A/B testing and online controlled experimentsConfidence interval and coverageSample size calculation and minimum detectable effect
- 04Markov's inequalityHoeffding's inequality
- 26MartingaleSubmartingales and supermartingalesOptional stopping theorem
Motivation: the dashboard checked every morning
A product team launches an A/B test on the purchase button. It is well designed: level , 80 % power for the minimum effect of interest and, after the required sample-size calculation, six weeks of traffic. The experimentation dashboard shows the p-value updated in real time, and someone checks every morning. On day 9 the p-value drops to 0.03; the team celebrates, stops the experiment and deploys the variant.
None of this is fraudulent, yet the 5 % guarantee no longer holds. A fixed-size test’s p-value satisfies for each fixed in advance. Someone who stops at the first does not use a fixed : they use the first at which noise supports their conclusion. With one look per day for six weeks (42 analyses), the probability of declaring a nonexistent effect is 31 %, more than six times nominal. Looking after each user, it tends to 1.
The figure teaches two things. First: the problem is not looking, but acting on what is seen. If one looks without stopping, only the final analysis counts and the test retains its size. Second: trajectories cross by chance at arbitrary times; a statistic that is at each instant visits any region of the axis if given enough time.
This lesson explores three statistical responses to this problem, in historical order and increasing generality:
- Wald’s sequential probability ratio test (1945): designed from the outset to read data one at a time and stop as soon as evidence suffices.
- Group sequential designs in clinical trials (Pocock, O’Brien and Fleming, Lan and DeMets): a small number of interim analyses with boundaries calculated to allocate .
- Anytime-valid inference: test martingales, e-values and confidence sequences that permit continuous monitoring, stopping for any reason and retaining a guarantee. Its mathematical basis is Ville’s inequality (1939), with modern development over the last decade by Ramdas, Grünwald, Vovk, Shafer, Howard, Waudby-Smith and others.
The optional stopping problem
Formalize the dashboard. Let be independent observations with mean and variance 1 (in an A/B test, the standardized difference between a pair of users from each arm), and the test statistic for with fixed , . Under and for each fixed , is (exactly or approximately) and the rule “reject if ” has type-I error .
The analyst watching the dashboard does not use a fixed but a stopping time : a random variable taking values in such that event depends only on (today’s decision to stop uses what has been seen through today, not the future; see stopping time). The canonical example is .
The last condition, uniform over time, is exactly what protects the analyst, thanks to an elementary equivalence.
Proof
(1 ⇒ 3) For any , event is contained in . (3 ⇒ 2) Every stopping time is a random time. (2 ⇒ 1) Take , the first rejection, which is a stopping time; then .
∎Point 3 is stronger than it looks: the guarantee survives even stopping rules that are not stopping times, such as “stop when the boss says so” or “stop on the day that looks best in the presentation”. A fixed-size test does not have this property, because of one of probability’s finest limit laws.
Proof
By the law of the iterated logarithm (Khinchin for Bernoulli, Hartman and Wintner for finite variance),
If for all , then , contradicting the upper limit of 1. Therefore almost surely there is some (indeed infinitely many) with .
∎The iterated logarithm law also says how fast this happens: the envelope of grows like , extremely slowly. Thus the figure’s rate rises quickly with the first looks and then crawls: 5 % with one, 14 % with five, 31 % with forty-two, 53 % looking after each of a thousand observations. Thus to build a boundary that is not crossed with probability greater than , make it grow somewhat faster than on the scale. The boundaries in the last part of the lesson grow like .
Before continuing, check the numbers by simulation. Gaussian walks are the exact model of a sum of normal differences and, by the central limit theorem, an excellent approximation for conversions or revenue.
import numpy as np
def primera_salida(n_paseos, N, c=1.959964, seed=0, bloque=250):
"""Primer n en que |S_n|/sqrt(n) >= c para paseos gaussianos (N + 1 si nunca)."""
rng = np.random.default_rng(seed)
n = np.arange(1, N + 1)
out = []
for _ in range(n_paseos // bloque):
S = rng.standard_normal((bloque, N)).cumsum(axis=1)
fuera = np.abs(S) >= c * np.sqrt(n)
out.append(np.where(fuera.any(axis=1), fuera.argmax(axis=1) + 1, N + 1))
return np.concatenate(out)
def tasa_con_miradas(K, n_paseos=4000, N=1000, seed=1):
"""Fracción de A/B tests sin efecto que rechazan en alguna de K miradas equiespaciadas."""
rng = np.random.default_rng(seed)
miradas = np.round(np.arange(1, K + 1) * N / K).astype(int)
S = rng.standard_normal((n_paseos, N)).cumsum(axis=1)[:, miradas - 1]
Z = S / np.sqrt(miradas)
return (np.abs(Z) >= 1.959964).any(axis=1).mean()
for K in [1, 2, 5, 10, 42, 100, 1000]:
print(f"K = {K:4d} miradas: tasa real de falsos positivos = {tasa_con_miradas(K):.3f}")
tau = primera_salida(1000, 10_000, seed=2)
for N in [100, 1_000, 10_000]:
print(f"mirando tras cada dato hasta N = {N:6d}: {np.mean(tau <= N):.3f}")With 4000 experiments, rates match the figure within Monte Carlo error (about ): , , , , , , . Looking after every datum, false rejections rise from with 100 observations to with 1000 and with 10 000: they keep rising toward 1 at the iterated-logarithm rate. These numbers have been known since Armitage, McPherson and Rowe (1969), who computed them by numerical integration for early clinical trials with repeated analyses.
The sequential probability ratio test
The first solution arose in a very different setting: ammunition quality control during World War II, where every observation cost money and decisions were needed as soon as possible. Abraham Wald reversed the question: instead of fixing and then deciding, which test decides as soon as the data permit?
Consider two simple hypotheses about each observation’s density, versus . The Neyman–Pearson lemma says that with fixed the optimal test thresholds the likelihood ratio. With data arriving one at a time, the accumulated ratio updates multiplicatively:
The logarithm is a random walk: it drifts upward if data come from (slope ) and downward if they come from (slope ).
How are and chosen to obtain errors and ? Wald’s answer is a two-line change of measure.
Proof
Let be the event “the test stops at and rejects”; it depends only on and on it . Since is the ratio of joint densities of under and under ,
Summing over , . For acceptance events , where , the same argument in reverse gives , and summing gives .
∎Ignoring the overshoot with which jumps above or below (at stopping time, is not exactly ), inequalities become approximate equalities and give Wald’s thresholds:
With these thresholds the bounds guarantee , and, adding the theorem’s inequalities multiplied by appropriate denominators, . In practice overshoot makes the test somewhat conservative: actual errors are slightly below nominal.
How long it takes: Wald’s identity
is a sum of a random number of iid increments . Wald’s identity, a consequence of optional stopping applied to martingale , says provided . Again ignoring overshoot, equals or , and
Under the denominator is and under , (the Kullback–Leibler divergence). The more distinguishable the hypotheses, the earlier the decision.
We will not prove this theorem, whose proof uses an auxiliary Bayesian optimal-stopping problem. Its practical meaning is clear: for two simple hypotheses there is nothing better, and the improvement over a fixed-size test is often around 40–50 % of observations.
import numpy as np
def sprt_bernoulli(p_real, p0, p1, alpha=0.05, beta=0.2, M=2000, n_max=4000, seed=0, bloque=500):
"""Simula M SPRT de Wald para H0: p = p0 frente a H1: p = p1 con datos Bernoulli(p_real)."""
logA, logB = np.log((1 - beta) / alpha), np.log(beta / (1 - alpha))
a, b = np.log(p1 / p0), np.log((1 - p1) / (1 - p0)) # log-razón si sale 1 y si sale 0
rng = np.random.default_rng(seed)
rech, ns = [], []
for _ in range(M // bloque):
x = rng.random((bloque, n_max)) < p_real
llr = np.cumsum(np.where(x, a, b), axis=1)
fuera = (llr >= logA) | (llr <= logB)
assert fuera.any(axis=1).all(), "sube n_max"
n = fuera.argmax(axis=1) # primer instante fuera de (log B, log A)
ns.append(n + 1)
rech.append(llr[np.arange(bloque), n] >= logA)
return np.concatenate(rech).mean(), np.concatenate(ns).mean()
def kl_bern(p, q):
return p * np.log(p / q) + (1 - p) * np.log((1 - p) / (1 - q))
p0, p1, alpha, beta = 0.5, 0.6, 0.05, 0.2
logA, logB = np.log((1 - beta) / alpha), np.log(beta / (1 - alpha))
print(f"umbrales de Wald: A = {(1 - beta) / alpha:.1f}, B = {beta / (1 - alpha):.4f}")
for p_real in [0.5, 0.6]:
pr, en = sprt_bernoulli(p_real, p0, p1, seed=int(10 * p_real))
print(f"p real = {p_real}: P(rechazar H0) = {pr:.3f}, E[N] = {en:.1f}")
e1 = ((1 - beta) * logA + beta * logB) / kl_bern(p1, p0)
e0 = (alpha * logA + (1 - alpha) * logB) / (-kl_bern(p0, p1))
z_a, z_b = 1.644854, 0.841621
n_fijo = ((z_a * np.sqrt(p0 * (1 - p0)) + z_b * np.sqrt(p1 * (1 - p1))) / (p1 - p0)) ** 2
print(f"aproximación de Wald: E1[N] = {e1:.1f}, E0[N] = {e0:.1f}; test fijo: n = {np.ceil(n_fijo):.0f}")
# la alternativa del diseño no es la verdad
for p_real, p1_mal in [(0.55, 0.6), (0.6, 0.51), (0.55, 0.8)]:
pr, en = sprt_bernoulli(p_real, p0, p1_mal, n_max=8000, seed=3)
print(f"p real = {p_real}, alternativa del SPRT p1 = {p1_mal}: P(rechazar) = {pr:.3f}, E[N] = {en:.0f}")The simulation confirms the bounds: actual type-I error is and power , both conservative due to overshoot, which also makes mean sizes ( and ) slightly exceed approximations ( and ). Even so, the SPRT needs on average one third fewer observations than the fixed test of 153 under and over half fewer under .
The final three lines are the warning. SPRT is optimal for the alternative supplied. If truth is , halfway between, it rejects only 36 % of the time. If designed for a timid alternative, , and truth is , it always rejects but takes 730 observations instead of 103: each datum contributes nats instead of . If designed for an exaggerated alternative, , against truth , the test accepts 89 % of the time after about nine observations on average: data resemble more than , and that is all the SPRT asks. The remedy, seen with martingales, is to bet on a mixture rather than one alternative, or learn the alternative as data arrive.
Group sequential designs
In a clinical trial analysis does not occur after each patient. An independent data monitoring committee meets a few times, when a predetermined fraction of information has accumulated, and at each meeting may recommend stopping for efficacy (treatment works so clearly that continued randomization to control is unethical), toxicity or futility. There are analyses, not infinitely many, and the goal is to allocate total among them.
The canonical distribution
Let be information (the inverse of estimator variance) at analysis , the information fraction, and the Wald statistic at that analysis. For normal means, and asymptotically for nearly any regular model, vector is multivariate normal with
This is because accumulates independent increments: only new data are added between analyses. Equivalently, on the information scale, with a Brownian motion with drift. The entire group sequential design calculation reduces to Brownian crossing probabilities at times.
The two classic families are Pocock (1977), with constant boundary , and O’Brien and Fleming (1979), with , very demanding early and close to the fixed value at the end. For and two-sided , at all five analyses, while O’Brien–Fleming requires , , , and .
The sum’s probabilities are computed by recursive numerical integration (Armitage, McPherson and Rowe, 1969): if is the subdensity of restricted to the continuation region, that of is its convolution with the normal increment, restricted to , and crossing probability at analysis is the integral of against that normal’s tail. This is what the interactive and cell below do.
α-spending functions
Pocock and O’Brien–Fleming require fixing and the times in advance. In a real trial the committee meets when it can, and information accumulated at each meeting is not exactly as planned. Lan and DeMets (1983) reversed the approach: instead of fixing boundaries, specify how much has been spent at each information fraction.
A spending function is a function nondecreasing in with and . At each analysis, with actually observed information fraction , choose boundary so spent at that analysis is . The three most used are:
The first imitates O’Brien–Fleming (spending almost nothing early: ), the second Pocock, and the third interpolates between them. Only the function must be fixed in advance, not the number or schedule of analyses.
The interactive shows the fundamental tradeoff. With 80 % power and five analyses:
| Design | Maximum / fixed size | Expected under | Expected under | ||
|---|---|---|---|---|---|
| Classical Pocock | 2.413 | 2.413 | 1.228 | 0.799 | 1.198 |
| Classical O’Brien–Fleming | 4.562 | 2.040 | 1.028 | 0.818 | 1.021 |
| Pocock-type spending | 2.438 | 2.386 | 1.212 | 0.796 | 1.183 |
| O’Brien–Fleming-type spending | 4.383 | 2.063 | 1.038 | 0.810 | 1.029 |
Pocock distributes equally: it can stop very early with large effects, but the last analysis requires instead of , and maximum size must grow by 23 % to retain power. O’Brien–Fleming spends almost no early: maximum size barely grows (3 %), final analysis is nearly that of the fixed design, yet if the effect exists it stops on average with 82 % of data. (These are classical-boundary numbers with ; spending versions in the figure give 21 % and 4 % additional maximum size and 81 % expected size.) Thus O’Brien–Fleming or its spending function is the usual clinical-trial choice: it guards against stopping for an early noise spike and costs almost nothing if no stopping occurs.
import numpy as np
from scipy.stats import norm
from scipy.optimize import brentq
class Recursion:
"""Subdensidad de S(t_k) = B(t_k) + theta t_k en la región de continuación (regla del trapecio)."""
def __init__(self, theta=0.0, G=201):
self.theta, self.G, self.x, self.pm, self.t = theta, G, None, None, 0.0
def cruce(self, t, c):
"""Probabilidad de parar en el siguiente análisis (t, c) sin haber parado antes."""
dt = t - self.t
mu, sd, b = self.theta * dt, np.sqrt(dt), c * np.sqrt(t)
if self.x is None:
return norm.sf((b - mu) / sd) + norm.cdf((-b - mu) / sd)
return np.sum(self.pm * (norm.sf((b - self.x - mu) / sd) + norm.cdf((-b - self.x - mu) / sd)))
def avanza(self, t, c):
dt = t - self.t
mu, sd, b = self.theta * dt, np.sqrt(dt), c * np.sqrt(t)
x = np.linspace(-b, b, self.G)
if self.x is None:
f = norm.pdf((x - mu) / sd) / sd
else:
f = norm.pdf((x[:, None] - self.x[None, :] - mu) / sd) @ self.pm / sd
w = np.full(self.G, x[1] - x[0]); w[[0, -1]] *= 0.5
self.x, self.pm, self.t = x, f * w, t
def fronteras_gasto(ts, gasto, alpha=0.05):
r, cs, previo = Recursion(), [], 0.0
for t in ts:
objetivo = gasto(t, alpha) - previo
c = brentq(lambda c: r.cruce(t, c) - objetivo, 0.3, 15)
cs.append(c); r.avanza(t, c); previo = gasto(t, alpha)
return np.array(cs)
def prob_parar(ts, cs, theta=0.0):
r, p = Recursion(theta), []
for t, c in zip(ts, cs):
p.append(r.cruce(t, c)); r.avanza(t, c)
return np.array(p)
gasto_obf = lambda t, a: 2 - 2 * norm.cdf(norm.ppf(1 - a / 2) / np.sqrt(t))
gasto_pocock = lambda t, a: a * np.log(1 + (np.e - 1) * t)
K = 5
ts = np.arange(1, K + 1) / K
d = norm.ppf(0.975) + norm.ppf(0.8) # deriva del diseño fijo con potencia 0.8
for nombre, g in [("tipo O'Brien-Fleming", gasto_obf), ("tipo Pocock", gasto_pocock)]:
cs = fronteras_gasto(ts, g)
# tamaño máximo R (relativo al fijo) con el que la potencia vuelve a ser 0.8
R = brentq(lambda R: prob_parar(ts, cs, d * np.sqrt(R)).sum() - 0.8, 0.8, 2)
p1 = prob_parar(ts, cs, d * np.sqrt(R))
para = np.append(p1[:-1], 1 - p1[:-1].sum())
print(f"{nombre}: c = {np.round(cs, 3)}, alfa total = {prob_parar(ts, cs).sum():.4f}, "
f"R = {R:.3f}, E1[N]/n_fijo = {R * np.sum(para * ts):.3f}")
rng = np.random.default_rng(6)
cs = fronteras_gasto(ts, gasto_obf)
S = rng.standard_normal((100_000, K)).cumsum(axis=1) * np.sqrt(1 / K)
Z = S / np.sqrt(ts)
print(f"comprobación por simulación (100 000 ensayos bajo H0): {(np.abs(Z) >= cs).any(axis=1).mean():.4f}")O’Brien–Fleming-type spending boundaries, , spend exactly , confirmed by 100 000 simulated trials under (). Two practical details. First, these are the two-sided Lan–DeMets boundaries, with total; programs such as gsDesign also offer a version spending on each side using the one-sided formula, whose boundaries start at : these are different designs, so know which is used. Second, futility boundaries (stop when the effect looks null) can be binding, if the design commits to respecting them and is recalculated, or nonbinding, if only recommendations; nonbinding is usual because continuing at the committee’s discretion does not compromise type-I error.
Group designs solve the problem well when the number of analyses is small and planned. They do not suit a dashboard checked whenever anyone wishes, continuation of an experiment already finished, or combining studies decided in view of one another. That requires a time-uniform guarantee, and the tool is the martingale.
Test martingales: evidence as capital
Return to the SPRT likelihood ratio, . Under ,
so is a nonnegative martingale starting at 1. Its casino interpretation is more than a metaphor. A gambler starts with 1 euro. Each round they can buy any ticket whose payoff has fair price under the null, , and reinvest all capital. If they choose each round, their capital after rounds is exactly . If the null is true, the game is fair and they should not be able to get rich; capital multiplied by 20 is evidence against the null.
Proof
Let and fix horizon . Time is bounded, so optional stopping for supermartingales gives . On event , , and otherwise, so
Thus for all , and by continuity of probability, .
∎This is Markov’s inequality, , but uniform over time, at no cost: the same constant. The test “reject as soon as ” is anytime-valid. In the SPRT, applied to , it gives without requiring termination and even if acceptance never stops the test.
Betting against a mean
The betting interpretation opens the door to nonparametric nulls. Suppose observations in and composite null , covering infinitely many distributions. With fraction chosen using data through (that is, predictable), capital
is nonnegative and satisfies under any distribution in the null. It is a test martingale with no parametric assumption. For a Bernoulli with , ; the interactive uses fraction on payoff , that is, , also the likelihood ratio of against with .
How much to bet? With fixed fraction and data , the law of large numbers gives , the growth rate. It is concave and maximized at , the Kelly bet (Kelly criterion), with
Kullback–Leibler divergence is the maximum rate at which evidence can accumulate, and time to rejection is around . Under the null, however, for every : capital tends to 0 almost surely, although its expectation is 1 at every time.
The figure captures the approach’s philosophy. Validity comes for free from the fair-betting structure: it does not depend on strategy, number of looks or stopping time. Power depends entirely on strategy: betting too much causes ruin, betting too little is slow, and the best strategy without knowing is to learn it, exactly what the adaptive strategy does with . This also addresses the SPRT’s poorly chosen alternative: there is no need to guess , only estimate it predictably.
import numpy as np
def log_riqueza(x, lam):
"""log W_t de un apostador que arriesga lam_t a favor de «sale 1» con pago justo bajo p = 1/2."""
return np.cumsum(np.log1p(lam * (2 * x - 1)), axis=-1)
def lam_kelly(x, tope=0.6):
"""lam_t = 2 p_t - 1 con p_t = (k + 1/2)/t estimado SOLO con x_1..x_{t-1} (predecible)."""
t = np.arange(1, x.shape[-1] + 1)
k_previo = np.cumsum(x, axis=-1) - x
return np.clip(2 * (k_previo + 0.5) / t - 1, -tope, tope)
rng = np.random.default_rng(3)
M, T = 4000, 1000
umbral = np.log(20)
for p in [0.5, 0.6]:
x = (rng.random((M, T)) < p).astype(float)
for nombre, lam in [("lam = 0.2", 0.2), ("lam = 0.8", 0.8), ("Kelly adaptativo", lam_kelly(x))]:
lw = log_riqueza(x, lam)
cruza = (lw >= umbral).any(axis=1)
t_rech = np.where(cruza, (lw >= umbral).argmax(axis=1) + 1, np.inf)
print(f"p = {p}, {nombre:17s}: P(sup W >= 20) = {cruza.mean():.3f}, "
f"mediana de W_T = {np.median(np.exp(lw[:, -1])):9.3g}, mediana de t de rechazo = {np.median(t_rech):.0f}")
kl = 0.6 * np.log(1.2) + 0.4 * np.log(0.8)
print(f"KL(0.6 || 0.5) = {kl:.5f}; log(20)/KL = {umbral / kl:.0f} observaciones")Under the null, the fractions of gamblers ever reaching 20 in a thousand rounds are , and : below in all three cases, with no adjustment for a thousand looks. Under , Kelly with rejects in a median of 119 observations. Wald’s identity gives a mean time of at least (slightly more for threshold overshoot); the median is lower because rejection time has a long right tail. The adaptive strategy, which does not know , takes a median of 225, and excessive bet rejects only 15 % of the time because its growth rate is negative: .
E-values
A test martingale stopped at any time produces a nonnegative number whose expectation under the null is at most 1. That number is the basic unit of anytime-valid inference.
Three familiar sources of e-values:
- Stopped martingales. If is a test supermartingale and any stopping time, is an e-value: by optional stopping, for each , and by Fatou’s lemma, (at , , which exists almost surely by the nonnegative supermartingale convergence theorem). An e-value calculated in an experiment stopped for any reason remains an e-value.
- Likelihood ratios and Bayes factors. For a simple null, and any Bayes factor have expectation 1 under (exchange integrals). A Bayes factor against a simple null is an e-value.
- Universal inference. The split likelihood ratio of universal inference, , where is the likelihood of one half of the data, any estimator fitted on the other half and the null maximum-likelihood estimator on the first, is an e-value for arbitrary composite nulls without regularity conditions.
Markov converts an e-value into a test: rejecting if has type-I error at most (you will prove it in the exercises), and is a valid p-value. The reverse uses calibrators: decreasing functions with . If is a p-value, is an e-value, because is stochastically greater than uniform and is decreasing, so . Examples: for , and their mixture .
import numpy as np
def calibrador(p, kappa=0.5):
return kappa * p ** (kappa - 1)
def calibrador_mezcla(p):
"""Integral en kappa de kappa p^(kappa-1) sobre [0, 1]."""
return (1 - p + p * np.log(p)) / (p * np.log(p) ** 2)
for p in [0.05, 0.01, 0.001]:
print(f"p = {p:5}: e (kappa = 1/2) = {calibrador(p):6.2f} e (mezcla) = {calibrador_mezcla(p):6.2f} "
f"cota de Vovk-Sellke -1/(e p log p) = {-1 / (np.e * p * np.log(p)):6.2f}")
rng = np.random.default_rng(4)
x = rng.standard_normal(1_000_000) # datos bajo H0: N(0, 1)
mu = 0.3
E = np.exp(mu * x - mu ** 2 / 2) # razón de verosimilitudes N(mu,1)/N(0,1): un valor e
print(f"\nE[E] = {E.mean():.3f} P(E >= 20) = {np.mean(E >= 20):.4f}")
copias = 10 # diez «estudios» que reutilizan los mismos datos
prod = E ** copias
print(f"producto de {copias} copias dependientes: E[prod] = {prod.mean():.2f} P(prod >= 20) = {np.mean(prod >= 20):.3f}")
print(f"media de las {copias} copias: E = {E.mean():.3f} P(media >= 20) = {np.mean(E >= 20):.4f}")
indep = np.exp(mu * rng.standard_normal((200_000, copias)) - mu ** 2 / 2).prod(axis=1)
print(f"producto de {copias} valores e independientes: E[prod] = {indep.mean():.3f} P(prod >= 20) = {np.mean(indep >= 20):.4f}")The first table is a lesson in humility about p-values: with power calibrators , corresponds to an e-value of at most (the Vovk and Sellke–Bayarri–Berger bound, , the maximum over and thus not itself a valid calibrator). An multiplies the skeptic’s capital by less than 2.5; reaching requires a p-value of order . Any calibrator satisfies , because , and bound is reached only with , betting everything on threshold fixed before seeing data and giving above it: the classical test in disguise, not a graded evidence measure.
Combining e-values
Here e-values show their practical advantage:
- Average. If are e-values for the same null, is an e-value under any dependence, by linearity of expectation. Vovk and Wang (2021) show the arithmetic mean is, in a precise sense, the best symmetric way to combine arbitrarily dependent e-values. For dependent p-values, their mean is valid only when multiplied by 2.
- Product. If independent or, more generally, sequentially valid ( under the null), product is an e-value. This is the martingale rule: each study reinvests its predecessor’s capital. It permits optional continuation: after an experiment with (inconclusive), another may be launched, chosen in view of the first, and the values multiplied.
The cell shows why the second rule needs sequential validity: ten “studies” reusing the same data give a product with expectation that exceeds 20 in 12.5 % of cases, while their average remains a perfectly valid e-value and the product of ten independent ones has expectation .
A design question remains: among all e-values for a null, which should we choose? Grünwald, de Heide and Koolen’s answer (Safe Testing) is the Kelly analogue: maximize expected logarithmic growth under the alternative, , in the worst case over the alternative (GROW, growth-rate optimal in the worst case). For simple nulls and alternatives it is the likelihood ratio, with growth equal to Kullback–Leibler divergence, as in the interactive.
Confidence sequences
A 95 % confidence interval covers the parameter with probability 0.95 for fixed . Recalculated after each datum, it fails at some time with probability tending to 1, by the same iterated-logarithm argument. Monitoring requires a different object.
Confidence sequences were introduced by Darling and Robbins (1967) and relate to intervals as test martingales relate to tests. The general construction uses duality between tests and confidence sets, now uniform over time: if for each candidate value there is a test supermartingale for null , then
is a confidence sequence, because for some requires the true-value martingale, , to reach , which Ville bounds by . Since the intersection of with also excludes only on that event, is another, narrower and monotone confidence sequence.
By mixture: Robbins’ boundary
Let be conditionally -sub-Gaussian increments, that is, for all . For a variable in , by Hoeffding’s lemma, which also gives Hoeffding’s inequality. With , each process is a test supermartingale. One detects only deviations of one size well; Robbins’ idea is to mix over , still producing a test supermartingale (an average of nonnegative supermartingales is one, by Fubini), and compute the Gaussian integral:
Solving for ,
and the confidence sequence for the mean is . Its width decreases like , a factor slower than a fixed interval: the price of time uniformity. Parameter determines when it is narrowest; Howard, Ramdas, McAuliffe and Sekhon (2021) give choice for near-optimality around and show how to “stitch” boundaries to reduce overhead to from the iterated-logarithm law, the minimum possible.
By betting: bounded means
Hoeffding’s boundary uses the worst possible variance, . For a Bernoulli with , actual variance is , and the boundary wastes a factor . Waudby-Smith and Ramdas (2024) construct the sequence with the previous section’s betting martingale, one per , and fractions that learn the variance: the hedged capital
bets simultaneously on the mean being above and below , and is a test martingale for as the average of two. With , clipped so capital cannot become negative, width adapts to estimated variance, like an empirical Bernstein inequality.
import numpy as np
def cs_mezcla(xbar, t, sigma=0.5, alpha=0.05, t0=500):
"""Secuencia de confianza de mezcla normal para incrementos sigma-subgaussianos, casi óptima en t0."""
rho2 = (-2 * np.log(alpha) + np.log(-2 * np.log(alpha) + 1)) / (sigma ** 2 * t0)
v = sigma ** 2 * t
u = np.sqrt((v + 1 / rho2) * (2 * np.log(1 / alpha) + np.log(1 + rho2 * v))) / t
return xbar - u, xbar + u
def lambdas_plugin(x, alpha=0.05):
"""Fracciones predecibles de Waudby-Smith y Ramdas: dependen solo de x_1..x_{t-1}."""
t = np.arange(1, x.shape[-1] + 1)
mu_hat = (0.5 + np.cumsum(x, axis=-1)) / (t + 1)
ss = 0.25 + np.cumsum((x - mu_hat) ** 2, axis=-1)
s2_prev = np.concatenate([np.full(x.shape[:-1] + (1,), 0.25), (ss / (t + 1))[..., :-1]], axis=-1)
return np.sqrt(2 * np.log(2 / alpha) / (s2_prev * t * np.log(1 + t)))
def log_capital(x, m, lam, c=0.5):
"""log del capital cubierto (K+ + K-)/2 para la nula E[X] = m (m puede ser un vector columna)."""
lp = np.cumsum(np.log1p(np.minimum(lam, c / m) * (x - m)), axis=-1)
lm = np.cumsum(np.log1p(-np.minimum(lam, c / (1 - m)) * (x - m)), axis=-1)
return np.logaddexp(lp, lm) + np.log(0.5)
def cs_apuestas(x, alpha=0.05, rejilla=np.linspace(0.0025, 0.9975, 400)):
lam = lambdas_plugin(x, alpha)
dentro = log_capital(x[None, :], rejilla[:, None], lam[None, :]) < np.log(1 / alpha)
lo = np.where(dentro.any(0), rejilla[dentro.argmax(0)], np.nan)
hi = np.where(dentro.any(0), rejilla[len(rejilla) - 1 - dentro[::-1].argmax(0)], np.nan)
return lo, hi
mu, T = 0.1, 10_000
rng = np.random.default_rng(5)
x = (rng.random(T) < mu).astype(float)
t = np.arange(1, T + 1)
xbar = np.cumsum(x) / t
lo_m, hi_m = cs_mezcla(xbar, t)
lo_b, hi_b = cs_apuestas(x)
print(" t IC fijo Hoeffding-mezcla apuestas (anchuras, mu = 0.1)")
for tt in [100, 1_000, 10_000]:
i = tt - 1
w_fijo = 2 * 1.96 * np.sqrt(xbar[i] * (1 - xbar[i]) / tt)
print(f"{tt:6d} {w_fijo:.4f} {hi_m[i] - lo_m[i]:.4f} {hi_b[i] - lo_b[i]:.4f}")
M, T2, mu = 1000, 2000, 0.3
X = (rng.random((M, T2)) < mu).astype(float)
t2 = np.arange(1, T2 + 1)
xb = np.cumsum(X, axis=1) / t2
mira = t2 >= 20
fijo = (np.abs(xb - mu) > 1.96 * np.sqrt(xb * (1 - xb) / t2))[:, mira].any(axis=1).mean()
l, h = cs_mezcla(xb, t2)
mezcla = ((mu < l) | (mu > h)).any(axis=1).mean()
apuestas = (log_capital(X, mu, lambdas_plugin(X)) >= np.log(20)).any(axis=1).mean()
print(f"\nexcluyen mu en algún t <= {T2} ({M} secuencias, mu = {mu}): IC fijo {fijo:.3f}, mezcla {mezcla:.3f}, apuestas {apuestas:.3f}")The numbers summarize the section. With and , the fixed interval measures , the Hoeffding sequence (almost triple), and betting , having learned variance is small. Adaptation has a price: near worst-case variance, these fractions give a slightly wider sequence than the mixture tuned for (with and , about versus ); the advantage appears when variance is small. The guarantee: across 1000 sequences with , the recalculated fixed interval excludes at some time before in 50 % of cases; Hoeffding does so in 0.9 % (conservative), and betting in 4.5 %, close to the permitted 5 %.
Continuous monitoring of A/B tests
Johari, Pekelis and Walsh (2015, published in Operations Research in 2022) brought these ideas to experimentation platforms, explicitly aiming to allow the dashboard at the beginning to be checked whenever desired. Their tool is the mixture SPRT (mSPRT): for observations with known (in a paired A/B test, is the difference between a B user and an A user) and null , mix the likelihood ratio over :
This is the same Robbins boundary as in the previous section. It constructs always-valid p-values, , which the dashboard can display in real time with guarantee , and always-valid intervals by inverting the test for each . Parameter plays the SPRT alternative’s role, but a poor choice costs efficiency, not validity.
import numpy as np
def log_msprt(suma, n, sigma2, tau2):
"""log Lambda_n del mSPRT con mezcla N(0, tau2) sobre la diferencia, datos N(delta, sigma2)."""
return 0.5 * np.log(sigma2 / (sigma2 + n * tau2)) + tau2 * suma ** 2 / (2 * sigma2 * (sigma2 + n * tau2))
def simula_msprt(delta, sigma2=2.0, tau2=0.01, n_max=6000, M=2000, alpha=0.05, seed=0, bloque=500):
"""Instante en que Lambda_n alcanza 1/alpha por primera vez (inf si no llega antes de n_max)."""
rng = np.random.default_rng(seed)
n = np.arange(1, n_max + 1)
tiempos = []
for _ in range(M // bloque):
y = delta + np.sqrt(sigma2) * rng.standard_normal((bloque, n_max))
lam = log_msprt(np.cumsum(y, axis=1), n, sigma2, tau2)
cruza = lam >= np.log(1 / alpha)
tiempos.append(np.where(cruza.any(axis=1), cruza.argmax(axis=1) + 1, np.inf))
return np.concatenate(tiempos)
n_fijo = int(np.ceil((1.959964 + 0.841621) ** 2 * 2.0 / 0.1 ** 2))
t0 = simula_msprt(0.0, seed=7)
t1 = simula_msprt(0.1, seed=8)
print(f"n fijo para delta = 0.1, sigma2 = 2, potencia 0.8: {n_fijo} parejas")
print(f"H0, mirando tras cada pareja hasta 6000: falsos positivos = {np.mean(t0 < np.inf):.3f}")
print(f"H1: potencia con n_max = n_fijo: {np.mean(t1 <= n_fijo):.3f}; con 6000: {np.mean(t1 <= 6000):.3f}")
print(f"H1: mediana del instante de parada = {np.median(t1):.0f}; n para el 80 % de rechazos = {np.quantile(t1, 0.8):.0f}")Under , looking after each of 6000 pairs, mSPRT rejects 2.4 % of the time. Under effect that the fixed design detects with 80 % power in 1570 pairs, half the sequential experiments have stopped by 1513 pairs, but reaching 80 % rejection requires 2611, 66 % more than the fixed design, and at the fixed-design horizon power is only 52 %. This is the power cost of anytime validity: pay in the worst case for flexibility and early stopping when effects are large. If the analysis schedule is fixed and small, an O’Brien–Fleming group design costs much less (3 %); if the dashboard is checked at arbitrary times, mSPRT or a confidence sequence is the honest option.
A complete monitor
The final lab combines the pieces in a monitor for a conversion A/B test with pairs of users. For each pair, has mean , and has mean , so the previous section’s betting confidence sequence applies unchanged, without normality or known variance. Rules: stop for efficacy when the sequence excludes 0 and for futility when it excludes every effect greater than the minimum relevant effect, . Upon stopping report the sequence, which remains valid at that time.
import numpy as np
def cs_diferencia(xa, xb, alpha=0.05, rejilla=np.linspace(-0.12, 0.12, 481)):
"""Secuencia de confianza por apuestas para Delta = p_B - p_A con parejas (xa_t, xb_t).
Usa y = (xb - xa + 1)/2 en [0, 1], de media (Delta + 1)/2, y la intersección acumulada."""
y = (xb - xa + 1) / 2
m = (rejilla + 1) / 2
logK = log_capital(y[None, :], m[:, None], lambdas_plugin(y, alpha)[None, :])
excluido = np.maximum.accumulate(logK >= np.log(1 / alpha), axis=1) # lo excluido no vuelve
dentro = ~excluido
lo = np.where(dentro.any(0), rejilla[dentro.argmax(0)], np.nan)
hi = np.where(dentro.any(0), rejilla[len(rejilla) - 1 - dentro[::-1].argmax(0)], np.nan)
return lo, hi
def monitor(xa, xb, delta_min=0.01, t_min=200, alpha=0.05):
lo, hi = cs_diferencia(xa, xb, alpha)
t = np.arange(1, len(xa) + 1)
eficacia = (lo > 0) & (t >= t_min)
futilidad = (hi < delta_min) & (t >= t_min)
k = np.flatnonzero(eficacia | futilidad)
if len(k) == 0:
return "sin decisión", len(xa), lo[-1], hi[-1]
k = k[0]
return ("eficacia" if eficacia[k] else "futilidad"), k + 1, lo[k], hi[k]
rng = np.random.default_rng(9)
pA, pB, T = 0.10, 0.12, 10_000
xa = (rng.random(T) < pA).astype(float)
xb = (rng.random(T) < pB).astype(float)
decision, n, lo, hi = monitor(xa, xb)
est = xb[:n].mean() - xa[:n].mean()
print(f"decisión: {decision} tras {n} parejas; Delta estimada = {est:.4f}; secuencia de confianza: [{lo:.4f}, {hi:.4f}]")
n_fijo = (1.959964 + 0.841621) ** 2 * (pA * (1 - pA) + pB * (1 - pB)) / (pB - pA) ** 2
print(f"tamaño del diseño fijo con potencia 0.8: {np.ceil(n_fijo):.0f} parejas")
def estudio(pA, pB, R=200, T=8000, alpha=0.05, t_min=200, seed=0):
"""R experimentos: parada por eficacia, estimación ingenua al parar y si la secuencia excluyó la verdad."""
rng = np.random.default_rng(seed)
xa = (rng.random((R, T)) < pA).astype(float)
xb = (rng.random((R, T)) < pB).astype(float)
y = (xb - xa + 1) / 2
lam = lambdas_plugin(y, alpha)
t = np.arange(1, T + 1)
rech0 = (log_capital(y, 0.5, lam) >= np.log(1 / alpha)) & (t >= t_min) # la secuencia excluye Delta = 0
para = np.where(rech0.any(1), rech0.argmax(1) + 1, T)
falla = log_capital(y, (pB - pA + 1) / 2, lam) >= np.log(1 / alpha) # la secuencia excluye la verdad
fallo = np.array([falla[r, :para[r]].any() for r in range(R)])
est = np.array([xb[r, :para[r]].mean() - xa[r, :para[r]].mean() for r in range(R)])
return rech0.any(1), para, est, fallo
r0, _, _, _ = estudio(0.10, 0.10, seed=1)
print(f"\nH0 (10 % frente a 10 %): falsos positivos = {r0.mean():.3f}")
r1, n1, est1, fallo1 = estudio(0.10, 0.12, seed=2)
print(f"H1 (10 % frente a 12 %): potencia en 8000 parejas = {r1.mean():.3f}, mediana de parada = {np.median(n1[r1]):.0f}")
temprano = r1 & (n1 < np.median(n1[r1]))
print(f"Delta estimada al parar por eficacia: media {est1[r1].mean():.4f} (verdad 0.02); "
f"en la mitad más temprana {est1[temprano].mean():.4f}")
print(f"la secuencia excluye la verdad en algún momento antes de parar: {fallo1.mean():.3f}")Three results deserve careful attention. The example experiment stops for efficacy after 1358 pairs, far fewer than the fixed design’s 3839, with point estimate when truth is : three times as large. The reported confidence sequence, , does contain the truth. In the repeated study, the false-positive rate under stays below 5 % despite looking after each pair, and the sequence rarely excludes truth; but the average naive estimate at stopping overestimates the effect, more so the earlier it stops. This is the winner’s curse of early stopping: stopping happens precisely when noise has pushed the estimate upward. Report the confidence sequence (or a corrected estimator), not just the point estimate.
Statistics as a game
All of the above admits an interpretation that, strictly speaking, needs no probability measure over the data. Shafer and Vovk (Probability and Finance: It’s Only a Game!, 2001; Game-Theoretic Foundations for Probability and Finance, 2019) reconstruct probability as a game among three players: a Forecaster announcing prices (the null: “the next observation averages ”), a Skeptic buying or selling at those prices with their capital, and Reality, revealing the datum. An event is unlikely if the Skeptic has a strategy that becomes rich if it occurs without risking more than initial capital. Laws of large numbers, the iterated logarithm and the central limit theorem have versions in this language, with constructive proofs: the winning strategy.
The idea has old roots. Jean Ville introduced martingales in his 1939 thesis precisely to criticize von Mises’ definition of randomness using betting arguments, and his inequality is this lesson’s theorem. The modern view (Shafer, “Testing by betting”, 2021; Ramdas, Grünwald, Vovk and Shafer, 2023) suggests communicating evidence as: “betting against the hypothesis with this strategy, declared beforehand, capital multiplied by 37”. This statement can be understood without sampling theory, continued with new data by multiplication, and remains valid if someone looks early.
The professional version
| Tool | What it offers | Comment |
|---|---|---|
gsDesign, rpact (R) | Group sequential designs, spending functions, futility, sizes | Clinical-trial standard; validated for regulated environments |
confseq (Python and C++) | Mixture and stitched boundaries and nonparametric confidence sequences | By Howard and Waudby-Smith; unavailable in the browser |
scipy.stats, numpy | Normal distribution, simulation, recursive integration | Everything in this lesson fits in a hundred lines, as seen |
Those libraries cannot be installed in the browser, so the lesson’s cells implement everything with numpy and scipy. In production, three decisions must be written down before seeing data: which guarantee is wanted (planned analyses or anytime), which martingale or spending function is used, and what will be reported upon stopping.
Common mistakes
Exercises
Step 1 of 3. Which inequality do you use?
Step 1 of 3. How do you calculate ?
More than one answer may be correct.
More than one answer may be correct.
gasto_obf(t, alpha=0.05), the two-sided Lan–DeMets O'Brien–Fleming-type spending function (accept scalars and arrays), and error_simulado(cs, ts, n_sim=200_000, seed=0), which simulates n_sim trials under with the canonical distribution (independent increments of , and ) and returns the fraction crossing at any analysis. The function fronteras(ts, gasto) is supplied: it computes boundaries by recursive numerical integration. Tests check that with 5 analyses the total simulated error is 0.05.import numpy as np
from scipy.stats import norm
from scipy.optimize import brentq
def fronteras(ts, gasto, alpha=0.05, G=201):
"""Fronteras c_k (escala z) que gastan gasto(t_k) - gasto(t_{k-1}) en cada análisis. Ya implementada."""
ts = np.asarray(ts, dtype=float)
cs, x, pm, tprev, previo = [], None, None, 0.0, 0.0
for t in ts:
sd = np.sqrt(t - tprev)
def cruce(c):
b = c * np.sqrt(t)
if x is None:
return 2 * norm.sf(b / sd)
return np.sum(pm * (norm.sf((b - x) / sd) + norm.cdf((-b - x) / sd)))
objetivo = float(gasto(t, alpha)) - previo
c = brentq(lambda c: cruce(c) - objetivo, 0.3, 15)
b = c * np.sqrt(t)
xn = np.linspace(-b, b, G)
f = norm.pdf(xn / sd) / sd if x is None else norm.pdf((xn[:, None] - x[None, :]) / sd) @ pm / sd
w = np.full(G, xn[1] - xn[0]); w[[0, -1]] *= 0.5
x, pm, tprev, previo = xn, f * w, t, float(gasto(t, alpha))
cs.append(c)
return np.array(cs)
def gasto_obf(t, alpha=0.05):
"""alpha(t) = 2 - 2 Phi(z_{1 - alpha/2} / sqrt(t))."""
# tu código (ahora mismo es el gasto lineal)
return alpha * np.asarray(t, dtype=float)
def error_simulado(cs, ts, n_sim=200_000, seed=0):
"""Fracción de ensayos simulados bajo H0 que cruzan |Z_k| >= c_k en algún análisis."""
# tu código
return 0.0Summary
- Optional stopping. for each fixed implies nothing for random . With 42 looks error is 31 % and continuous monitoring tends to 1 by the iterated-logarithm law. The correct guarantee is time-uniform, , equivalent to validity under any stopping time.
- SPRT. Thresholds accumulated likelihood ratio at and ; it minimizes expected size under both hypotheses (Wald and Wolfowitz), but is fragile if the alternative is poorly chosen.
- Group designs. Pocock, O’Brien–Fleming and Lan–DeMets spending functions allocate among analyses using the Brownian structure of ; O’Brien–Fleming costs 3 % maximum size and stops early when the effect exists.
- Test martingales and e-values. , , a supermartingale under the null: by Ville, . Stopped at any time it gives an e-value (). E-values can be averaged under any dependence and multiplied if sequential; Kelly betting grows at rate .
- Confidence sequences. , constructed by inverting martingales: by mixture (Robbins, width ) or betting (variance-adaptive). Report them if an experiment can stop at any time; the point estimate at stopping is upward biased.