Module contents
Lesson 25 of 27Advanced 110 min

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

Motivation: the dashboard checked every morning

A product team launches an A/B test on the purchase button. It is well designed: level α=0.05\alpha = 0.05, 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 P0(pn≤α)≤α\Pr_0(p_n \le \alpha) \le \alpha for each nn fixed in advance. Someone who stops at the first pn≤0.05p_n \le 0.05 does not use a fixed nn: they use the first nn 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.

InteractiveChecking every day
ZnZ_n statistic for 46 of 400 experiments (under H0H_0)
p < 0.05
Actual false-positive rate by number of looks
nominal 5 %
  • no rejection
  • rejects at a look (and stops)
  • what would happen without stopping
  • current simulation (95 % CI)
42
False positives in 400 A/B tests with no effect34.0 % ± 4.6 %
Exact rate with 42 looks30.7 %
With 42 looks and stopping at the first p<0.05p < 0.05, the actual rate is 30.7 %, 6.1 times nominal. 99 % of rejections in this simulation occur early; many paths would have returned to the band.
Four hundred A/B tests with no effect. Each curve is an experiment's statistic ZnZ_n as data arrive; the shaded band is the region ∣Zn∣>1.96|Z_n| > 1.96, that is, p<0.05p < 0.05. With 42 looks and stopping at the first p<0.05p < 0.05, red curves are experiments the team would have declared winners; their dotted continuations show that many would have returned to the band. At right, the actual false-positive rate by number of looks. Turn stopping off: with the same trajectories, the rate returns to 5 %. Turn on the anytime-valid boundary studied at the end of the lesson.

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 N(0,1)\Normal(0, 1) 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:

  1. 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.
  2. 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 α\alpha.
  3. 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 X1,X2,…X_1, X_2, \dots be independent observations with mean μ\mu and variance 1 (in an A/B test, the standardized difference between a pair of users from each arm), Sn=∑i≤nXiS_n = \sum_{i \le n} X_i and the test statistic for H0:μ=0H_0: \mu = 0 with fixed nn, Zn=Sn/nZ_n = S_n/\sqrt{n}. Under H0H_0 and for each fixed nn, ZnZ_n is (exactly or approximately) N(0,1)\Normal(0, 1) and the rule “reject if ∣Zn∣≥z1−α/2|Z_n| \ge z_{1 - \alpha/2}” has type-I error α\alpha.

The analyst watching the dashboard does not use a fixed nn but a stopping time τ\tau: a random variable taking values in {1,2,… }∪{∞}\{1, 2, \dots\} \cup \{\infty\} such that event {τ=n}\{\tau = n\} depends only on X1,…,XnX_1, \dots, X_n (today’s decision to stop uses what has been seen through today, not the future; see stopping time). The canonical example is τc=inf⁡{n:∣Zn∣≥c}\tau_c = \inf\{n : |Z_n| \ge c\}.

The last condition, uniform over time, is exactly what protects the analyst, thanks to an elementary equivalence.

Proof

(1 ⇒ 3) For any TT, event {ϕT=1}\{\phi_T = 1\} is contained in {∃n:ϕn=1}\{\exists n : \phi_n = 1\}. (3 ⇒ 2) Every stopping time is a random time. (2 ⇒ 1) Take τ=inf⁡{n:ϕn=1}\tau = \inf\{n : \phi_n = 1\}, the first rejection, which is a stopping time; then {ϕτ=1}={τ<∞}={∃n:ϕn=1}\{\phi_\tau = 1\} = \{\tau < \infty\} = \{\exists n : \phi_n = 1\}.

∎

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),

lim sup⁡n→∞Sn2nlog⁡log⁡n=1casi seguro.\limsup_{n\to\infty} \frac{S_n}{\sqrt{2n\log\log n}} = 1 \quad \text{casi seguro}.

If ∣Sn∣/n<c|S_n|/\sqrt{n} < c for all nn, then Sn/2nlog⁡log⁡n<c/2log⁡log⁡n→0S_n/\sqrt{2n\log\log n} < c/\sqrt{2\log\log n} \to 0, contradicting the upper limit of 1. Therefore almost surely there is some nn (indeed infinitely many) with ∣Sn∣/n≥c|S_n|/\sqrt{n} \ge c.

∎

The iterated logarithm law also says how fast this happens: the envelope of ZnZ_n grows like 2log⁡log⁡n\sqrt{2\log\log n}, 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 α\alpha, make it grow somewhat faster than nlog⁡log⁡n\sqrt{n \log\log n} on the SnS_n scale. The boundaries in the last part of the lesson grow like nlog⁡n\sqrt{n\log n}.

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.

[ ]Checking every day: the actual false-positive rateBrowser
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 ±0.015\pm 0.015): 0.050.05, 0.080.08, 0.140.14, 0.190.19, 0.300.30, 0.380.38, 0.540.54. Looking after every datum, false rejections rise from 0.380.38 with 100 observations to 0.540.54 with 1000 and 0.690.69 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 nn and then deciding, which test decides as soon as the data permit?

Consider two simple hypotheses about each observation’s density, H0:f=f0H_0: f = f_0 versus H1:f=f1H_1: f = f_1. The Neyman–Pearson lemma says that with fixed nn the optimal test thresholds the likelihood ratio. With data arriving one at a time, the accumulated ratio updates multiplicatively:

Λn=∏i=1nf1(Xi)f0(Xi),log⁡Λn=∑i=1nlog⁡f1(Xi)f0(Xi).\Lambda_n = \prod_{i=1}^n \frac{f_1(X_i)}{f_0(X_i)}, \qquad \log\Lambda_n = \sum_{i=1}^n \log\frac{f_1(X_i)}{f_0(X_i)}.

The logarithm is a random walk: it drifts upward if data come from f1f_1 (slope KL⁡(f1 ∥ f0)\KL(f_1 \,\|\, f_0)) and downward if they come from f0f_0 (slope −KL⁡(f0 ∥ f1)-\KL(f_0 \,\|\, f_1)).

How are AA and BB chosen to obtain errors α\alpha and β\beta? Wald’s answer is a two-line change of measure.

Proof

Let RnR_n be the event “the test stops at nn and rejects”; it depends only on X1,…,XnX_1, \dots, X_n and on it Λn≥A\Lambda_n \ge A. Since Λn\Lambda_n is the ratio of joint densities of (X1,…,Xn)(X_1, \dots, X_n) under H1H_1 and under H0H_0,

P0(Rn)=∫Rn∏if0(xi) ⁣dx=∫Rn1Λn∏if1(xi) ⁣dx≤1AP1(Rn).\Pr_0(R_n) = \int_{R_n} \prod_i f_0(x_i) \dd \vb{x} = \int_{R_n} \frac{1}{\Lambda_n}\prod_i f_1(x_i) \dd \vb{x} \le \frac{1}{A}\Pr_1(R_n).

Summing over nn, α′=∑nP0(Rn)≤P1(rechazar)/A=(1−β′)/A\alpha' = \sum_n \Pr_0(R_n) \le \Pr_1(\text{rechazar})/A = (1 - \beta')/A. For acceptance events DnD_n, where Λn≤B\Lambda_n \le B, the same argument in reverse gives P1(Dn)=∫DnΛn∏if0≤B P0(Dn)\Pr_1(D_n) = \int_{D_n} \Lambda_n \prod_i f_0 \le B\,\Pr_0(D_n), and summing gives β′≤B(1−α′)\beta' \le B(1 - \alpha').

∎

Ignoring the overshoot with which ΛN\Lambda_N jumps above AA or below BB (at stopping time, ΛN\Lambda_N is not exactly AA), inequalities become approximate equalities and give Wald’s thresholds:

A≈1−βα,B≈β1−α.A \approx \frac{1 - \beta}{\alpha}, \qquad B \approx \frac{\beta}{1 - \alpha}.

With these thresholds the bounds guarantee α′≤α/(1−β)\alpha' \le \alpha/(1 - \beta), β′≤β/(1−α)\beta' \le \beta/(1 - \alpha) and, adding the theorem’s inequalities multiplied by appropriate denominators, α′+β′≤α+β\alpha' + \beta' \le \alpha + \beta. In practice overshoot makes the test somewhat conservative: actual errors are slightly below nominal.

How long it takes: Wald’s identity

log⁡ΛN\log\Lambda_N is a sum of a random number of iid increments Yi=log⁡(f1/f0)(Xi)Y_i = \log(f_1/f_0)(X_i). Wald’s identity, a consequence of optional stopping applied to martingale ∑i≤n(Yi−EY)\sum_{i \le n} (Y_i - \E Y), says E[log⁡ΛN]=E[N] E[Y]\E[\log\Lambda_N] = \E[N]\,\E[Y] provided E[N]<∞\E[N] < \infty. Again ignoring overshoot, log⁡ΛN\log\Lambda_N equals log⁡A\log A or log⁡B\log B, and

Eθ[N]≈Pθ(rechazar)log⁡A+Pθ(aceptar)log⁡BEθ[Y].\E_\theta[N] \approx \frac{\Pr_\theta(\text{rechazar})\log A + \Pr_\theta(\text{aceptar})\log B}{\E_\theta[Y]}.

Under H1H_1 the denominator is KL⁡(f1 ∥ f0)\KL(f_1 \,\|\, f_0) and under H0H_0, −KL⁡(f0 ∥ f1)-\KL(f_0 \,\|\, f_1) (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.

[ ]Wald's SPRT for a Bernoulli and what happens when the alternative is poorly chosenBrowser
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 0.045<0.050.045 < 0.05 and power 0.815>0.80.815 > 0.8, both conservative due to overshoot, which also makes mean sizes (7171 and 103103) slightly exceed approximations (6666 and 9595). Even so, the SPRT needs on average one third fewer observations than the fixed test of 153 under H1H_1 and over half fewer under H0H_0.

The final three lines are the warning. SPRT is optimal for the alternative supplied. If truth is p=0.55p = 0.55, halfway between, it rejects only 36 % of the time. If designed for a timid alternative, p1=0.51p_1 = 0.51, and truth is 0.60.6, it always rejects but takes 730 observations instead of 103: each datum contributes E0.6[Y]=0.0038\E_{0.6}[Y] = 0.0038 nats instead of 0.02010.0201. If designed for an exaggerated alternative, p1=0.8p_1 = 0.8, against truth 0.550.55, the test accepts H0H_0 89 % of the time after about nine observations on average: data resemble 0.50.5 more than 0.80.8, 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 KK analyses, not infinitely many, and the goal is to allocate total α\alpha among them.

The canonical distribution

Let IkI_k be information (the inverse of estimator variance) at analysis kk, tk=Ik/IKt_k = I_k/I_K the information fraction, and ZkZ_k the Wald statistic at that analysis. For normal means, and asymptotically for nearly any regular model, vector (Z1,…,ZK)(Z_1, \dots, Z_K) is multivariate normal with

E[Zk]=θIk,Cov⁡(Zj,Zk)=Ij/Ik(j≤k).\E[Z_k] = \theta\sqrt{I_k}, \qquad \Cov(Z_j, Z_k) = \sqrt{I_j/I_k} \quad (j \le k).

This is because Sk=ZkIkS_k = Z_k\sqrt{I_k} accumulates independent increments: only new data are added between analyses. Equivalently, Zk=B(tk)/tkZ_k = B(t_k)/\sqrt{t_k} on the information scale, with BB a Brownian motion with drift. The entire group sequential design calculation reduces to Brownian crossing probabilities at KK times.

The two classic families are Pocock (1977), with constant boundary ck=cPc_k = c_P, and O’Brien and Fleming (1979), with ck=cOFK/kc_k = c_{OF}\sqrt{K/k}, very demanding early and close to the fixed value at the end. For K=5K = 5 and two-sided α=0.05\alpha = 0.05, cP=2.413c_P = 2.413 at all five analyses, while O’Brien–Fleming requires 4.5624.562, 3.2263.226, 2.6342.634, 2.2812.281 and 2.0402.040.

The sum’s probabilities are computed by recursive numerical integration (Armitage, McPherson and Rowe, 1969): if gk−1g_{k-1} is the subdensity of Sk−1S_{k-1} restricted to the continuation region, that of SkS_k is its convolution with the normal increment, restricted to ∣s∣<cktk|s| < c_k\sqrt{t_k}, and crossing probability at analysis kk is the integral of gk−1g_{k-1} against that normal’s tail. This is what the interactive and cell below do.

α-spending functions

Pocock and O’Brien–Fleming require fixing KK 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 α\alpha has been spent at each information fraction.

A spending function is a function α(t)\alpha(t) nondecreasing in [0,1][0, 1] with α(0)=0\alpha(0) = 0 and α(1)=α\alpha(1) = \alpha. At each analysis, with actually observed information fraction tkt_k, choose boundary ckc_k so α\alpha spent at that analysis is α(tk)−α(tk−1)\alpha(t_k) - \alpha(t_{k-1}). The three most used are:

αOF(t)=2−2Φ(z1−α/2t),αP(t)=αlog⁡(1+(e−1)t),αρ(t)=αtρ.\alpha_{OF}(t) = 2 - 2\Phi\Big(\frac{z_{1 - \alpha/2}}{\sqrt{t}}\Big), \qquad \alpha_{P}(t) = \alpha\log\big(1 + (e - 1)t\big), \qquad \alpha_\rho(t) = \alpha t^\rho.

The first imitates O’Brien–Fleming (spending almost nothing early: αOF(0.2)=1.2×10−5\alpha_{OF}(0.2) = 1.2\times 10^{-5}), the second Pocock, and the third interpolates between them. Only the function must be fixed in advance, not the number or schedule of analyses.

InteractiveStopping boundaries
Rejection boundaries ±ck\pm c_k and a simulated trial Z(t)Z(t)
fixed 1.96
α spent at each analysis (bars) and cumulative
α = 0.05
  • boundary ±ck\pm c_k
  • fixed-design boundary, 1.96
  • simulated trial (shown until stopping)
  • α spent at analysis
  • cumulative α / spending function
5
Target power
True effect in simulated trial
Boundaries c1,…,cKc_1, \dots, c_K on z scale4.38 3.10 2.55 2.25 2.06
Nominal level of final analysis0.0391
Maximum / fixed size× 1.038
Expected / fixed size, under H1H_1 | under H0H_081 % | 103 %
Simulated trialstops at analysis 3 (Z = 2.62)
Cautious early. The first boundary is high (4.38), spending almost no early α; the final boundary is 2.06, near 1.96. Maximum cost is small (×1.038), and if an effect exists mean stopping size is 81 % of fixed.
Left: boundaries ±ck\pm c_k on the zz scale (red points) versus the fixed-design boundary, 1.961.96, and a simulated trial stopping at the first crossing. Right: α\alpha spent at each analysis (bars) and cumulative spending or the spending function. Readouts compare maximum and expected size with the fixed design of equal power. With five analyses, compare O'Brien–Fleming with Pocock: which pays more in the worst case and which gains more when the effect exists? Simulate trials under H0H_0: only 5 % cross overall, distributed across analyses as the bars show.

The interactive shows the fundamental tradeoff. With 80 % power and five analyses:

Designc1c_1c5c_5Maximum / fixed sizeExpected under H1H_1Expected under H0H_0
Classical Pocock2.4132.4131.2280.7991.198
Classical O’Brien–Fleming4.5622.0401.0280.8181.021
Pocock-type spending2.4382.3861.2120.7961.183
O’Brien–Fleming-type spending4.3832.0631.0380.8101.029

Pocock distributes α\alpha equally: it can stop very early with large effects, but the last analysis requires 2.412.41 instead of 1.961.96, and maximum size must grow by 23 % to retain power. O’Brien–Fleming spends almost no α\alpha 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 K=5K = 5; 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.

[ ]α-spending boundaries by recursive numerical integrationBrowser
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, 4.383,3.100,2.553,2.254,2.0634.383, 3.100, 2.553, 2.254, 2.063, spend exactly 0.050.05, confirmed by 100 000 simulated trials under H0H_0 (0.05040.0504). Two practical details. First, these are the two-sided Lan–DeMets boundaries, with α(1)=0.05\alpha(1) = 0.05 total; programs such as gsDesign also offer a version spending 0.0250.025 on each side using the one-sided formula, whose boundaries start at 4.8774.877: 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 α\alpha 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, Λn=∏i≤nf1(Xi)/f0(Xi)\Lambda_n = \prod_{i \le n} f_1(X_i)/f_0(X_i). Under H0H_0,

E0[f1(Xn)f0(Xn) ∣ X1,…,Xn−1]=∫f1(x)f0(x)f0(x) ⁣dx=1,\E_0\Big[\frac{f_1(X_n)}{f_0(X_n)} \,\Big|\, X_1, \dots, X_{n-1}\Big] = \int \frac{f_1(x)}{f_0(x)} f_0(x) \dd x = 1,

so Λn\Lambda_n 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 g(Xn)≥0g(X_n) \ge 0 has fair price under the null, E0[g(Xn)]=1\E_0[g(X_n)] = 1, and reinvest all capital. If they choose g=f1/f0g = f_1/f_0 each round, their capital after nn rounds is exactly Λn\Lambda_n. 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 τ=inf⁡{t:Mt≥1/α}\tau = \inf\{t : M_t \ge 1/\alpha\} and fix horizon TT. Time τ∧T\tau \wedge T is bounded, so optional stopping for supermartingales gives EP[Mτ∧T]≤M0=1\E_P[M_{\tau \wedge T}] \le M_0 = 1. On event {τ≤T}\{\tau \le T\}, Mτ∧T=Mτ≥1/αM_{\tau\wedge T} = M_\tau \ge 1/\alpha, and M≥0M \ge 0 otherwise, so

1αPP(τ≤T)≤EP[Mτ∧T 1[τ≤T]]≤EP[Mτ∧T]≤1.\frac{1}{\alpha}\Pr_P(\tau \le T) \le \E_P\big[M_{\tau\wedge T}\,\ind[\tau \le T]\big] \le \E_P[M_{\tau\wedge T}] \le 1.

Thus PP(τ≤T)≤α\Pr_P(\tau \le T) \le \alpha for all TT, and by continuity of probability, PP(τ<∞)=lim⁡TPP(τ≤T)≤α\Pr_P(\tau < \infty) = \lim_T \Pr_P(\tau \le T) \le \alpha.

∎

This is Markov’s inequality, P(M≥1/α)≤α E[M]\Pr(M \ge 1/\alpha) \le \alpha\,\E[M], but uniform over time, at no cost: the same constant. The test “reject as soon as Mt≥1/αM_t \ge 1/\alpha” is anytime-valid. In the SPRT, applied to Λn\Lambda_n, it gives α′≤1/A\alpha' \le 1/A 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 [0,1][0, 1] and composite null H0:E[Xt∣Ft−1]=mH_0: \E[X_t \given \mathcal{F}_{t-1}] = m, covering infinitely many distributions. With fraction λt\lambda_t chosen using data through t−1t - 1 (that is, predictable), capital

Wt=∏i=1t(1+λi(Xi−m)),−11−m≤λi≤1m,W_t = \prod_{i=1}^t \big(1 + \lambda_i (X_i - m)\big), \qquad -\frac{1}{1 - m} \le \lambda_i \le \frac{1}{m},

is nonnegative and satisfies E[Wt∣Ft−1]=Wt−1(1+λt E[Xt−m∣Ft−1])=Wt−1\E[W_t \given \mathcal{F}_{t-1}] = W_{t-1}(1 + \lambda_t\,\E[X_t - m \given \mathcal{F}_{t-1}]) = W_{t-1} under any distribution in the null. It is a test martingale with no parametric assumption. For a Bernoulli with m=1/2m = 1/2, λ(X−1/2)=(λ/2)(2X−1)\lambda(X - 1/2) = (\lambda/2)(2X - 1); the interactive uses fraction λ\lambda on payoff 2X−1∈{−1,1}2X - 1 \in \{-1, 1\}, that is, Wt=Wt−1(1+λt(2Xt−1))W_t = W_{t-1}(1 + \lambda_t(2X_t - 1)), also the likelihood ratio of Bern⁡(p1)\Bern(p_1) against Bern⁡(1/2)\Bern(1/2) with p1=(1+λ)/2p_1 = (1 + \lambda)/2.

How much to bet? With fixed fraction λ\lambda and data Bern⁡(p)\Bern(p), the law of large numbers gives 1tlog⁡Wt→g(λ)=plog⁡(1+λ)+(1−p)log⁡(1−λ)\frac{1}{t}\log W_t \to g(\lambda) = p\log(1 + \lambda) + (1 - p)\log(1 - \lambda), the growth rate. It is concave and maximized at λ∗=2p−1\lambda^* = 2p - 1, the Kelly bet (Kelly criterion), with

g(λ∗)=plog⁡(2p)+(1−p)log⁡(2(1−p))=KL⁡(Bern⁡(p) ∥ Bern⁡(12)).g(\lambda^*) = p\log(2p) + (1 - p)\log\big(2(1 - p)\big) = \KL\big(\Bern(p) \,\|\, \Bern(\tfrac12)\big).

Kullback–Leibler divergence is the maximum rate at which evidence can accumulate, and time to rejection is around log⁡(1/α)/KL⁡\log(1/\alpha)/\KL. Under the null, however, g(λ)=12log⁡(1−λ2)<0g(\lambda) = \frac12\log(1 - \lambda^2) < 0 for every λ≠0\lambda \ne 0: capital tends to 0 almost surely, although its expectation is 1 at every time.

InteractiveBetting against the null
Wealth WtW_t of 60 gamblers (log scale)
1/α = 20: reject
Expected growth per bet g(λ)g(\lambda)
Kelly
  • highlighted gambler
  • reaches 20: false rejection
  • has not reached 20
  • g(λ)g(\lambda) with true pp
  • Kelly bet λ∗=2p−1\lambda^* = 2p - 1
0.50
Strategy
0.20
t = 500
Highlighted gambler's wealth at t = 5005.6×10−85.6 \times 10^{-8}
Maximum reached2.382.38
Gamblers who reached 1/α = 203 of 200 (1.5 %)
Median wealth of 2008.3×10−58.3 \times 10^{-5}
Growth per bet g(λ)g(\lambda) | maximum (Kelly)−0.0204 | 0.0000
The null is true. 3 of 200 gamblers (1.5 %) have reached 20; Ville bounds that probability by 5 %, even when looking after every bet. Median wealth (8.3×10−58.3 \times 10^{-5}) collapses, but its expectation is always 1: a few lucky paths offset those ruined.
Two hundred gamblers, each with their own sequence of tosses of a coin with P(1)=pP(1) = p, bet against the null p=1/2p = 1/2. Left: wealth WtW_t on a logarithmic scale for 60 of them; those touching 1/α=201/\alpha = 20 reject. Right: growth rate g(λ)g(\lambda) for the true pp, the Kelly point and selected bet. With p=0.5p = 0.5, count how many touch 20: Ville guarantees at most 5 %, even looking after every bet. Raise pp to 0.60.6 and try λ=0.2\lambda = 0.2 (Kelly), λ=0.05\lambda = 0.05 (timid) and λ=0.8\lambda = 0.8 (excessive): with an excessive bet wealth collapses even when the null is false. The adaptive strategy learns λ\lambda from data without knowing pp.

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 pp is to learn it, exactly what the adaptive strategy does with λt=2p^t−1−1\lambda_t = 2\hat{p}_{t-1} - 1. This also addresses the SPRT’s poorly chosen alternative: there is no need to guess p1p_1, only estimate it predictably.

[ ]Betting test martingales: Ville under the null, Kelly under the alternativeBrowser
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 0.0420.042, 0.0280.028 and 0.0320.032: below 0.050.05 in all three cases, with no adjustment for a thousand looks. Under p=0.6p = 0.6, Kelly with λ=0.2\lambda = 0.2 rejects in a median of 119 observations. Wald’s identity gives a mean time of at least log⁡20/KL⁡=149\log 20/\KL = 149 (slightly more for threshold overshoot); the median is lower because rejection time has a long right tail. The adaptive strategy, which does not know pp, takes a median of 225, and excessive bet λ=0.8\lambda = 0.8 rejects only 15 % of the time because its growth rate is negative: g(0.8)=0.6log⁡1.8+0.4log⁡0.2=−0.29g(0.8) = 0.6\log 1.8 + 0.4\log 0.2 = -0.29.

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 (Mt)(M_t) is a test supermartingale and τ\tau any stopping time, MτM_\tau is an e-value: by optional stopping, E[Mτ∧T]≤1\E[M_{\tau \wedge T}] \le 1 for each TT, and by Fatou’s lemma, E[Mτ]≤lim inf⁡TE[Mτ∧T]≤1\E[M_\tau] \le \liminf_T \E[M_{\tau\wedge T}] \le 1 (at {τ=∞}\{\tau = \infty\}, M∞=lim⁡tMtM_\infty = \lim_t M_t, 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, f1(X)/f0(X)f_1(X)/f_0(X) and any Bayes factor ∫fθ(X) π(θ) ⁣dθ/f0(X)\int f_\theta(X)\,\pi(\theta)\dd\theta / f_0(X) have expectation 1 under f0f_0 (exchange integrals). A Bayes factor against a simple null is an e-value.
  • Universal inference. The split likelihood ratio of universal inference, L0(θ^1)/L0(θ^0)\mathcal{L}_0(\hat\theta_1)/\mathcal{L}_0(\hat\theta_0), where L0\mathcal{L}_0 is the likelihood of one half of the data, θ^1\hat\theta_1 any estimator fitted on the other half and θ^0\hat\theta_0 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 E≥1/αE \ge 1/\alpha has type-I error at most α\alpha (you will prove it in the exercises), and p=min⁡(1,1/E)p = \min(1, 1/E) is a valid p-value. The reverse uses calibrators: decreasing functions f:[0,1]→[0,∞)f: [0, 1] \to [0, \infty) with ∫01f(u) ⁣du=1\int_0^1 f(u)\dd u = 1. If PP is a p-value, f(P)f(P) is an e-value, because PP is stochastically greater than uniform and ff is decreasing, so E[f(P)]≤E[f(U)]=1\E[f(P)] \le \E[f(U)] = 1. Examples: fκ(p)=κpκ−1f_\kappa(p) = \kappa p^{\kappa - 1} for κ∈(0,1)\kappa \in (0, 1), and their mixture ∫01κpκ−1 ⁣dκ=1−p+plog⁡pp (log⁡p)2\int_0^1 \kappa p^{\kappa - 1}\dd\kappa = \frac{1 - p + p\log p}{p\,(\log p)^2}.

[ ]Calibrators and combining e-valuesBrowser
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 fκf_\kappa, p=0.05p = 0.05 corresponds to an e-value of at most 2.462.46 (the Vovk and Sellke–Bayarri–Berger bound, −1/(e plog⁡p)-1/(e\,p\log p), the maximum over κ\kappa and thus not itself a valid calibrator). An p=0.05p = 0.05 multiplies the skeptic’s capital by less than 2.5; reaching e=20e = 20 requires a p-value of order 0.0010.001. Any calibrator satisfies f(p)≤1/pf(p) \le 1/p, because p f(p)≤∫0pf≤1p\,f(p) \le \int_0^p f \le 1, and bound 1/p1/p is reached only with f=1[u≤p0]/p0f = \ind[u \le p_0]/p_0, betting everything on threshold p0p_0 fixed before seeing data and giving e=0e = 0 above it: the classical test in disguise, not a graded evidence measure.

Combining e-values

Here e-values show their practical advantage:

  • Average. If E1,…,EKE_1, \dots, E_K are e-values for the same null, 1K∑kEk\frac{1}{K}\sum_k E_k 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 (E[Ek∣E1,…,Ek−1]≤1\E[E_k \given E_1, \dots, E_{k-1}] \le 1 under the null), product ∏kEk\prod_k E_k is an e-value. This is the martingale rule: each study reinvests its predecessor’s capital. It permits optional continuation: after an experiment with E1=4E_1 = 4 (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 5454 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 1.001.00.

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, EQ[log⁡E]\E_Q[\log E], 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 nn. 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 mm there is a test supermartingale Mt(m)M_t(m) for null θ=m\theta = m, then

Ct={m:Mt(m)<1/α}C_t = \{m : M_t(m) < 1/\alpha\}

is a confidence sequence, because θ∉Ct\theta \notin C_t for some tt requires the true-value martingale, Mt(θ)M_t(\theta), to reach 1/α1/\alpha, which Ville bounds by α\alpha. Since the intersection of CsC_s with s≤ts \le t also excludes θ\theta only on that event, ⋂s≤tCs\bigcap_{s \le t} C_s is another, narrower and monotone confidence sequence.

By mixture: Robbins’ boundary

Let Xi−μX_i - \mu be conditionally σ\sigma-sub-Gaussian increments, that is, E[eλ(Xi−μ)∣Fi−1]≤eλ2σ2/2\E[e^{\lambda(X_i - \mu)} \given \mathcal{F}_{i-1}] \le e^{\lambda^2\sigma^2/2} for all λ\lambda. For a variable in [0,1][0, 1], σ=1/2\sigma = 1/2 by Hoeffding’s lemma, which also gives Hoeffding’s inequality. With St=∑i≤t(Xi−μ)S_t = \sum_{i \le t}(X_i - \mu), each process exp⁡(λSt−λ2σ2t/2)\exp(\lambda S_t - \lambda^2\sigma^2 t/2) is a test supermartingale. One λ\lambda detects only deviations of one size well; Robbins’ idea is to mix over λ∼N(0,ρ2)\lambda \sim \Normal(0, \rho^2), still producing a test supermartingale (an average of nonnegative supermartingales is one, by Fubini), and compute the Gaussian integral:

Mt=∫eλSt−λ2σ2t/2 e−λ2/(2ρ2)2πρ ⁣dλ=11+ρ2σ2texp⁡(ρ2St22(1+ρ2σ2t)).M_t = \int e^{\lambda S_t - \lambda^2\sigma^2 t/2}\,\frac{e^{-\lambda^2/(2\rho^2)}}{\sqrt{2\pi}\rho}\dd\lambda = \frac{1}{\sqrt{1 + \rho^2\sigma^2 t}}\exp\Big(\frac{\rho^2 S_t^2}{2(1 + \rho^2\sigma^2 t)}\Big).

Solving for Mt≥1/αM_t \ge 1/\alpha,

∣St∣≥u(t)=(σ2t+1ρ2)(2log⁡1α+log⁡(1+ρ2σ2t)),|S_t| \ge u(t) = \sqrt{\Big(\sigma^2 t + \frac{1}{\rho^2}\Big)\Big(2\log\frac{1}{\alpha} + \log(1 + \rho^2\sigma^2 t)\Big)},

and the confidence sequence for the mean is Xˉt±u(t)/t\bar{X}_t \pm u(t)/t. Its width decreases like log⁡t/t\sqrt{\log t/t}, a factor log⁡t\sqrt{\log t} slower than a fixed interval: the price of time uniformity. Parameter ρ\rho determines when it is narrowest; Howard, Ramdas, McAuliffe and Sekhon (2021) give choice ρ2=(−2log⁡α+log⁡(1−2log⁡α))/(σ2t0)\rho^2 = \big(-2\log\alpha + \log(1 - 2\log\alpha)\big)/(\sigma^2 t_0) for near-optimality around t0t_0 and show how to “stitch” boundaries to reduce overhead to log⁡log⁡t\sqrt{\log\log t} from the iterated-logarithm law, the minimum possible.

By betting: bounded means

Hoeffding’s boundary uses the worst possible variance, 1/41/4. For a Bernoulli with μ=0.1\mu = 0.1, actual variance is 0.090.09, and the boundary wastes a factor 0.25/0.09≈1.7\sqrt{0.25/0.09} \approx 1.7. Waudby-Smith and Ramdas (2024) construct the sequence with the previous section’s betting martingale, one per mm, and fractions λt\lambda_t that learn the variance: the hedged capital

Kt(m)=12∏i≤t(1+λi+(m)(Xi−m))+12∏i≤t(1−λi−(m)(Xi−m))K_t(m) = \tfrac12\prod_{i \le t}\big(1 + \lambda_i^+(m)(X_i - m)\big) + \tfrac12\prod_{i \le t}\big(1 - \lambda_i^-(m)(X_i - m)\big)

bets simultaneously on the mean being above and below mm, and is a test martingale for EX=m\E X = m as the average of two. With λi≈2log⁡(2/α)/(σ^i−12 ilog⁡(1+i))\lambda_i \approx \sqrt{2\log(2/\alpha)/(\hat\sigma^2_{i-1}\, i\log(1 + i))}, clipped so capital cannot become negative, width adapts to estimated variance, like an empirical Bernstein inequality.

InteractiveConfidence sequence versus repeated intervals
Intervals for a Bernoulli mean as data arrive (observed from t=20t = 20)
μ = 0.25
  • sample mean
  • recalculated fixed 95 % CI
  • Hoeffding mixture sequence
  • betting sequence
  • fixed CI excludes μ
0.25
t = 2000
Sample mean at t = 20000.255
Width: fixed CI | Hoeffding mixture | betting0.038 | 0.070 | 0.079
Exclude μ\mu at some t≤2000t \le 2000 (of 200): fixed CI45.0 %
Same: Hoeffding mixture | betting0.0 % | 2.0 %
The fixed interval failed in this sequence (first at t=396t = 396): an analyst stopping there would make a false “95 %” confidence claim. Among 200 sequences, 45 % fail by t=2000t = 2000; confidence sequences fail 0.0 % and 2.0 %.
Bernoulli data of mean μ\mu arrive one at a time, on a logarithmic time scale, observed from t=20t = 20. The orange band is the fixed 95 % confidence interval recalculated at each step; red axis marks indicate times it excludes μ\mu. Dashed aquamarine curves are the Hoeffding mixture sequence, and magenta curves the betting sequence. Play the arriving data. Readouts count, across 200 sequences, the fraction of each procedure excluding μ\mu at any time. With μ=0.25\mu = 0.25 variance 0.190.19 is barely below the worst possible, and the betting sequence is slightly wider than the mixture tuned for t0=500t_0 = 500. Lower μ\mu to 0.050.05: betting narrows while Hoeffding does not react.
[ ]Confidence sequences: Hoeffding mixture and bettingBrowser
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 μ=0.1\mu = 0.1 and t=10 000t = 10\,000, the fixed interval measures 0.0120.012, the Hoeffding sequence 0.0330.033 (almost triple), and betting 0.0250.025, 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 t0=500t_0 = 500 (with μ=0.5\mu = 0.5 and t=2000t = 2000, about 0.0970.097 versus 0.0700.070); the advantage appears when variance is small. The guarantee: across 1000 sequences with μ=0.3\mu = 0.3, the recalculated fixed interval excludes μ\mu at some time before t=2000t = 2000 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 Yi∼N(δ,σ2)Y_i \sim \Normal(\delta, \sigma^2) with known σ2\sigma^2 (in a paired A/B test, YiY_i is the difference between a B user and an A user) and null δ=0\delta = 0, mix the likelihood ratio over δ∼N(0,τ2)\delta \sim \Normal(0, \tau^2):

Λn=∫∏i≤nϕσ(Yi−δ)ϕσ(Yi)  ⁣dN(0,τ2)(δ)=σ2σ2+nτ2exp⁡(τ2(∑iYi)22σ2(σ2+nτ2)).\Lambda_n = \int \prod_{i \le n}\frac{\phi_\sigma(Y_i - \delta)}{\phi_\sigma(Y_i)}\,\dd\Normal(0, \tau^2)(\delta) = \sqrt{\frac{\sigma^2}{\sigma^2 + n\tau^2}}\exp\Big(\frac{\tau^2 (\sum_i Y_i)^2}{2\sigma^2(\sigma^2 + n\tau^2)}\Big).

This is the same Robbins boundary as in the previous section. It constructs always-valid p-values, pn=min⁡(1,min⁡k≤n1/Λk)p_n = \min\big(1, \min_{k \le n} 1/\Lambda_k\big), which the dashboard can display in real time with guarantee P0(∃n:pn≤α)≤α\Pr_0(\exists n: p_n \le \alpha) \le \alpha, and always-valid intervals by inverting the test for each δ0\delta_0. Parameter τ\tau plays the SPRT alternative’s role, but a poor choice costs efficiency, not validity.

[ ]mSPRT: validity under continuous monitoring and power costBrowser
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 H0H_0, looking after each of 6000 pairs, mSPRT rejects 2.4 % of the time. Under effect δ=0.1\delta = 0.1 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, Dt=XtB−XtA∈{−1,0,1}D_t = X^B_t - X^A_t \in \{-1, 0, 1\} has mean Δ=pB−pA\Delta = p_B - p_A, and Yt=(Dt+1)/2∈[0,1]Y_t = (D_t + 1)/2 \in [0, 1] has mean (Δ+1)/2(\Delta + 1)/2, 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, δmin⁡=0.01\delta_{\min} = 0.01. Upon stopping report the sequence, which remains valid at that time.

[ ]Anytime-valid A/B monitor with efficacy, futility and estimator bias at stoppingBrowser
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 0.0600.060 when truth is 0.020.02: three times as large. The reported confidence sequence, [0.0005,0.0685][0.0005, 0.0685], does contain the truth. In the repeated study, the false-positive rate under H0H_0 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 mm”), 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

ToolWhat it offersComment
gsDesign, rpact (R)Group sequential designs, spending functions, futility, sizesClinical-trial standard; validated for regulated environments
confseq (Python and C++)Mixture and stitched boundaries and nonparametric confidence sequencesBy Howard and Waudby-Smith; unavailable in the browser
scipy.stats, numpyNormal distribution, simulation, recursive integrationEverything 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

ProofAn e-value gives a valid test
Prove: If EE is an e-value for H0\mathcal{H}_0 (E≥0E \ge 0 and EP[E]≤1\E_P[E] \le 1 for every P∈H0P \in \mathcal{H}_0), the test rejecting when E≥1/αE \ge 1/\alpha has type-I error at most α\alpha.
0
Fix P∈H0P \in \mathcal{H}_0 and α∈(0,1)\alpha \in (0, 1). Bound PP(E≥1/α)\Pr_P(E \ge 1/\alpha).

Step 1 of 3. Which inequality do you use?

ProofThe product of sequential e-values is an e-value
Prove: Let E1,…,EK≥0E_1, \dots, E_K \ge 0 satisfy, under every P∈H0P \in \mathcal{H}_0, EP[Ek∣Fk−1]≤1\E_P[E_k \given \mathcal{F}_{k-1}] \le 1 for each kk, where Fk−1=σ(E1,…,Ek−1)\mathcal{F}_{k-1} = \sigma(E_1, \dots, E_{k-1}) (or any information including the preceding values). Then ∏k=1KEk\prod_{k=1}^K E_k is an e-value.
0
Let Pk=∏j≤kEjP_k = \prod_{j \le k} E_j, with P0=1P_0 = 1. It suffices to prove E[Pk]≤E[Pk−1]\E[P_k] \le \E[P_{k-1}] for each kk.

Step 1 of 3. How do you calculate E[Pk]\E[P_k]?

NumericWald's upper threshold
Calculate the approximate SPRT upper threshold A≈(1−β)/αA \approx (1 - \beta)/\alpha for α=0.05\alpha = 0.05 and β=0.2\beta = 0.2.
NumericExpected SPRT observations
For the SPRT of H0:p=0.5H_0: p = 0.5 versus H1:p=0.6H_1: p = 0.6 with Bernoulli data, α=0.05\alpha = 0.05 and β=0.2\beta = 0.2, use Wald's approximation to calculate the expected number of observations under H1H_1, E1[N]≈(1−β)log⁡A+βlog⁡BKL⁡(Bern⁡(0.6) ∥ Bern⁡(0.5))\E_1[N] \approx \frac{(1-\beta)\log A + \beta\log B}{\KL(\Bern(0.6)\,\|\,\Bern(0.5))}.
NumericKelly's time
A gambler knows p=0.6p = 0.6 and bets the Kelly fraction against null p=1/2p = 1/2. At optimal growth rate, approximately how many observations are needed for log⁡Wt\log W_t to reach log⁡20\log 20? Use t≈log⁡20/KL⁡(Bern⁡(0.6) ∥ Bern⁡(0.5))t \approx \log 20 / \KL(\Bern(0.6)\,\|\,\Bern(0.5)).
NumericFrom p-value to e-value
With calibrator fκ(p)=κpκ−1f_\kappa(p) = \kappa p^{\kappa - 1} and κ=1/2\kappa = 1/2, what e-value corresponds to p=0.01p = 0.01?
QuizCombining dependent e-values
E1E_1 and E2E_2 are e-values for the same null, calculated on data overlapping in an unknown way. Which quantities are certainly e-values?

More than one answer may be correct.

QuizStopping for a business decision
An A/B test was designed for n=20 000n = 20\,000 users. At 9000, management decides to stop after seeing the dashboard. Available are the fixed-test p-value, fixed 95 % confidence interval, 95 % confidence sequence and test-martingale e-value, all calculated with 9000 users. Which inferences retain their nominal guarantee?

More than one answer may be correct.

QuizChoosing the spending function
A clinical trial will have four interim analyses. The committee wants the final analysis, if reached, to resemble a fixed design as closely as possible, and fears stopping for an early noise spike. Which design fits best?
CodeO'Brien–Fleming spending function and verification
Implement gasto_obf(t, alpha=0.05), the two-sided Lan–DeMets O'Brien–Fleming-type spending function α(t)=2−2Φ(z1−α/2/t)\alpha(t) = 2 - 2\Phi(z_{1-\alpha/2}/\sqrt{t}) (accept scalars and arrays), and error_simulado(cs, ts, n_sim=200_000, seed=0), which simulates n_sim trials under H0H_0 with the canonical distribution (independent N(0,tk−tk−1)\Normal(0, t_k - t_{k-1}) increments of SS, and Zk=S(tk)/tkZ_k = S(t_k)/\sqrt{t_k}) and returns the fraction crossing ∣Zk∣≥ck|Z_k| \ge c_k 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.0
Shift+Enter to run

Summary

Key idea
A fixed-size test does not survive data-dependent stopping: given enough looks, it eventually rejects. The solution is to measure evidence as capital from a fair bet under the null, a test martingale, because Ville’s inequality makes it anytime-valid regardless of stopping.
  • Optional stopping. P0(pn≤α)≤α\Pr_0(p_n \le \alpha) \le \alpha for each fixed nn implies nothing for random nn. With 42 looks error is 31 % and continuous monitoring tends to 1 by the iterated-logarithm law. The correct guarantee is time-uniform, P0(∃n:ϕn=1)≤α\Pr_0(\exists n: \phi_n = 1) \le \alpha, equivalent to validity under any stopping time.
  • SPRT. Thresholds accumulated likelihood ratio at A≈(1−β)/αA \approx (1-\beta)/\alpha and B≈β/(1−α)B \approx \beta/(1-\alpha); 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 α\alpha among KK analyses using the Brownian structure of (Zk)(Z_k); O’Brien–Fleming costs 3 % maximum size and stops early when the effect exists.
  • Test martingales and e-values. Mt≥0M_t \ge 0, M0=1M_0 = 1, a supermartingale under the null: by Ville, P(∃t:Mt≥1/α)≤α\Pr(\exists t: M_t \ge 1/\alpha) \le \alpha. Stopped at any time it gives an e-value (E0[E]≤1\E_0[E] \le 1). E-values can be averaged under any dependence and multiplied if sequential; Kelly betting grows at rate KL⁡\KL.
  • Confidence sequences. P(∀t:θ∈Ct)≥1−α\Pr(\forall t: \theta \in C_t) \ge 1 - \alpha, constructed by inverting martingales: by mixture (Robbins, width log⁡t/t\sqrt{\log t/t}) or betting (variance-adaptive). Report them if an experiment can stop at any time; the point estimate at stopping is upward biased.