Skip to content

Anytime-valid and nonparametric inference

sequential_analysis.procedures.mixture

Anytime-valid test and confidence sequence for a normal mean (mixture SPRT).

Observations are N(theta, sigma^2) with sigma known. Mixing the likelihood ratio over theta ~ N(theta0, tau^2) (Robbins 1970) gives

Lambda_n = sqrt(sigma^2 / (sigma^2 + n tau^2))
           * exp( n^2 tau^2 (xbar_n - theta0)^2 / (2 sigma^2 (sigma^2 + n tau^2)) ),

a non-negative martingale with mean one under theta = theta0. By Ville's inequality P(sup_n Lambda_n >= 1/alpha) <= alpha, so

  • rejecting when Lambda_n >= 1/alpha is a level-alpha test that may be monitored after every observation and stopped at any time;
  • p_n = min(1, 1 / max_{k<=n} Lambda_k) is an always-valid p-value;
  • inverting the test gives a confidence sequence: with probability at least 1 - alpha the true mean lies in every interval simultaneously,

    xbar_n +/- sqrt( 2 sigma^2 (sigma^2 + n tau^2) / (n^2 tau^2) * (log(1/alpha) + log(1 + n tau^2 / sigma^2) / 2) ).

tau sets where the test is most sensitive: roughly to effects of size tau. This is the mSPRT used for continuously monitored A/B tests (Johari et al. 2017, 2022).

sequential_analysis.procedures.t_mixture

Anytime-valid t-test and confidence sequence: normal mean, unknown variance.

Observations are N(theta, sigma^2) with sigma unknown. The standardised effect delta = (theta - theta0) / sigma gets the prior N(0, c^2) and sigma the scale-invariant prior d sigma / sigma. The resulting Bayes factor (Goenen et al. 2005)

B_n = (1 + n c^2)^(-1/2)
      * [ (1 + t_n^2 / nu) / (1 + t_n^2 / (nu (1 + n c^2))) ]^((nu + 1) / 2),

with nu = n - 1 and t_n the one-sample t statistic, is the likelihood ratio of the scale-invariant reduction of the data. Under H0 it is therefore a non-negative martingale with mean one whatever sigma is (Lai 1976; Perez-Ortiz et al. 2024), and Ville's inequality makes

  • rejecting when B_n >= 1/alpha a level-alpha test under continuous monitoring and optional stopping,
  • 1 / max_k B_k an always-valid p-value, and
  • the set of theta0 not rejected a (1 - alpha) confidence sequence. It is xbar_n +/- t* s_n / sqrt(n) with t* in closed form, and the whole line while the data cannot yet exclude anything.

c is the effect size, in units of sigma, at which the test is most sensitive. The first observation carries no information about the standardised effect, so B_1 = 1.

TMixtureSPRT

Bases: Procedure

critical_t(n)

|t| at which B_n reaches 1/alpha, or None if it cannot at this n.

sequential_analysis.procedures.betting

Nonparametric anytime-valid tests by betting.

Testing by betting (Shafer 2021; Waudby-Smith and Ramdas 2024) needs no model for the data. For observations Y_i in [0, 1] and the null hypothesis E[Y_i | past] = m, a gambler who starts with wealth 1 and stakes a fraction lambda_i, chosen before Y_i is seen, ends with

K_n = prod_{i<=n} (1 + lambda_i (Y_i - m)).

Under the null K_n is a non-negative martingale with mean one, whatever the distribution of the Y_i, so by Ville's inequality P(sup_n K_n >= 1/alpha) <= alpha. Rejecting when the wealth reaches 1/alpha is a level-alpha test that may be monitored after every observation and stopped at any time; 1 / max_k K_k is an always-valid p-value. The only assumption is boundedness (for the mean test) or P(X > m) = P(X < m) (for the sign test); no distribution family is involved.

Bets follow the aGRAPA rule: lambda = (mu - m) / (s2 + (mu - m)^2) from predictable estimates mu, s2 of the mean and variance, truncated to [0, c/m] for bets on a larger mean and [0, c/(1 - m)] for bets on a smaller one (c = 1/2), so that the wealth stays positive. A two-sided test averages the two one-sided wealth processes.

Cost per step (PERFORMANCE.md): the tests take 3 µs and a constant state; BettingConfidenceSequence updates two wealths per grid point, 0.2 ms with numpy and 0.5 ms in Python for grid=1000, and checkpoints 40 kB.

BettingMeanTest

Bases: _Betting

Anytime-valid test of E[X] = mean0 for observations bounded in [lower, upper].

Valid for every distribution on [lower, upper] -- including skewed, discrete and heavy-tailed-but-bounded ones -- and for dependent data whose conditional mean given the past equals mean0.

SequentialSignTest

Bases: _Betting

Anytime-valid sign test of the median: H0 says P(X > median0) = P(X < median0).

Only the signs of X - median0 are used, so the test is valid for every distribution with P(X > median0) = P(X < median0), with no moment assumptions at all (Cauchy data are fine). Observations equal to median0 carry no sign; they are counted as ties and skipped.

Without an atom at median0 that hypothesis says median0 is the median. With one -- discrete data, paired differences that are often zero -- a distribution can have median median0 and still more mass above it than below (0 with probability 0.5, 1 with 0.3, -1 with 0.2), and the test then rightly rejects H0, which is about the signs, not the median. For paired data, test the differences against 0: pair the inputs with PositionalPair and map them with difference.

estimate is the fraction of positive signs among the non-tied observations.

BettingConfidenceSequence

Bases: Procedure

Confidence sequence for the mean of observations bounded in [lower, upper] (Waudby-Smith and Ramdas 2024).

Exact, for every distribution on [lower, upper] and for dependent data with a constant conditional mean: with probability at least 1 - alpha the interval contains the mean at every n simultaneously. For each candidate mean m on a grid the hedged capital process

K_n(m) = (prod (1 + l_i^+ (y_i - m)) + prod (1 - l_i^- (y_i - m))) / 2

is kept, with the predictable plug-in stakes l_i = sqrt(2 log(2/alpha) / (s2_{i-1} i log(1 + i))), truncated at c/m and c/(1 - m) (c = 1/2); m is excluded once K_n(m) >= 1/alpha. The interval spans the grid points not excluded, widened by one grid step on each side, and is intersected over time. These are the tightest known confidence sequences for bounded data; for a conversion rate use lower = 0, upper = 1.

The state holds two log-wealths per grid point (grid, default 1000).

sequential_analysis.procedures.quantile

Anytime-valid inference for a quantile, for every distribution (Howard and Ramdas 2022).

Whatever the distribution of the X_i -- heavy-tailed, skewed, discrete -- the indicators 1{X_i <= q} are Bernoulli with mean F(q). For a p-quantile q of the distribution, F(q) >= p and F(q-) <= p: the counts of observations at or below q cannot fall far below p n, nor the counts strictly below q rise far above it. How far is measured by a mixture of likelihood ratios over the Bernoulli mean theta, with a beta prior restricted to one side of p,

M_n(k) = integral over theta < p of (theta/p)^k ((1-theta)/(1-p))^(n-k) dBeta(theta; a, b) / P(theta < p),

for k = #{X_i <= q} (and symmetrically, over theta > p, for #{X_i < q}). Under F(q) >= p it is a non-negative supermartingale with mean at most one, so by Ville's inequality it exceeds 2/alpha with probability at most alpha/2, at any time. This gives

  • QuantileTest: an anytime-valid test of "q0 is a p-quantile" (for p = 1/2, of the median) from two counts. Unlike the sign test it is valid when the distribution has an atom at q0 -- discrete data, ties -- as long as q0 is a p-quantile;
  • QuantileConfidenceSequence: the values q that the test keeps, an interval between two order statistics that contains every p-quantile at every n simultaneously with probability at least 1 - alpha.

No moments, no density and no continuity are assumed; only independence of the observations given the past and a common distribution (or, more generally, F_i(q) >= p and F_i(q-) <= p for each i given the past).

The prior Beta(r p, r (1 - p)) is tuned by tuned_for, the number of observations at which the sequence is to be tightest; any value is valid.

Cost per step (PERFORMANCE.md): QuantileTest keeps three counts, 30 to 120 µs (an incomplete beta function); QuantileConfidenceSequence holds the sorted sample, about 20 bytes per observation, 0.2 ms after 100 observations and 0.9 ms after 10 000.

QuantileTest

Bases: Procedure

Anytime-valid test of H0: q0 is a p-quantile, i.e. P(X < q0) <= p <= P(X <= q0).

alternative="greater" rejects when the p-quantile is above q0 (too few observations at or below q0), "less" when it is below q0; the two-sided test spends alpha/2 on each side. p_value is always valid and never increases. The state is three counts, whatever the length of the run.

log_evidence(n, below, at_or_below)

log of the larger mixture, minus log 2 for a two-sided test: rejects at log(1/alpha).

QuantileConfidenceSequence

Bases: Procedure

Confidence sequence for the p-quantile of any distribution.

With probability at least 1 - alpha, every p-quantile of the distribution lies in [lower, upper] at every n simultaneously, so the interval may be watched continuously and the experiment stopped whenever it is narrow enough. The bounds are order statistics of the sample, intersected over time; None stands for an infinite bound (too few observations so far).

The state holds the sorted sample: memory grows with the run, and each step costs O(n) to insert and O(log n) evaluations of the incomplete beta function. To test one value q0, QuantileTest needs three counts.

bounds(sample)

The interval the mixtures keep at n = len(sample), before intersection over time.

sequential_analysis.procedures.two_sample_betting

Anytime-valid nonparametric two-sample test by betting (Shekhar and Ramdas 2023).

Observations arrive in pairs (A_t, B_t). H0: A_t and B_t have the same distribution -- any distribution, possibly changing over time -- and are independent of each other given the past. The alternative is any difference of the distributions: location, scale, shape, tails.

Before each pair, a witness function g is formed from the past pairs: the kernel mean embedding of the A sample minus that of the B sample,

g(z) = (1/(t-1)) sum_{s<t} [ k(z, A_s) - k(z, B_s) ],   k(z, u) = exp(-(z - u)^2 / (2 h^2)),

which is large where A has been more frequent than B (the witness of the maximum mean discrepancy). The gambler then stakes a fraction lambda_t on

v_t = clip( (g(A_t) - g(B_t)) / (2 G_t), -1, 1 ),

G_t the largest |g| seen so far. v_t is an odd function of the swap A_t <-> B_t, so under H0 it has mean zero whatever the distribution, and the wealth prod (1 + lambda_t v_t) is a non-negative martingale: reject when it reaches 1/alpha (Ville's inequality). lambda_t in [-1/2, 1/2] is chosen by online Newton steps (Cutkosky and Orabona 2018), as Shekhar and Ramdas do.

The kernel width h is the median distance within the first burn_in pairs (the median heuristic), on which nothing is staked; or it is given. The state holds the past pairs: memory grows with the run and each step costs O(n) kernel evaluations.

For two streams that arrive separately, pair them with PositionalPair.

Cost per step (PERFORMANCE.md): O(n) kernel evaluations; after 10 000 pairs 0.75 ms with numpy, 6 ms in Python; the state holds both samples, about 40 bytes per pair.

KernelTwoSampleTest

Bases: Procedure

Is the distribution of A the same as that of B? Anytime-valid, for any distributions.

Use it for A/B comparisons when the data are far from normal: revenue with many zeros and a long tail, latencies, counts. It detects any difference of the distributions, not only of the means; to test the means alone with bounded data use BettingMeanTest on the differences.

witness(z, a, b, bandwidth) staticmethod

g(z): mean kernel similarity of z to the A sample minus that to the B sample, in [-1, 1].

sequential_analysis.procedures.robust_mean

Confidence sequences for a mean without normality.

CatoniConfidenceSequence (Wang and Ramdas 2023) assumes only a known upper bound sigma^2 on the variance -- heavy tails, skewness and outliers are allowed. With Catoni's influence function

psi(y) = log(1 + y + y^2/2) for y >= 0,   psi(y) = -log(1 - y + y^2/2) for y < 0,

which satisfies exp(psi(y)) <= 1 + y + y^2/2 and exp(-psi(y)) <= 1 - y + y^2/2, and predictable lambda_i > 0, both

exp( +- sum_i psi(lambda_i (X_i - m)) - sigma^2 sum_i lambda_i^2 / 2 )

are non-negative supermartingales when m is the mean, so by Ville's inequality the set of m with |sum psi(lambda_i (X_i - m))| <= sigma^2 sum lambda_i^2 / 2 + log(2/alpha) contains the mean at every n simultaneously with probability at least 1 - alpha. psi grows only logarithmically, so a few wild observations move the interval little. The interval is found by bisection over the stored sample. It is intersected over time; data that contradict the variance bound (values far beyond sigma) can make the intersection empty, and the reported lower bound then lies above the upper one: read it as evidence that sigma is too small, not as an interval.

AsymptoticConfidenceSequence (Waudby-Smith, Arbour, Sinha, Kennedy and Ramdas 2024) assumes only a finite variance (and slightly more than two moments); the variance is estimated. It is Robbins' normal-mixture boundary with the running standard deviation in place of sigma,

xbar_n +- s_n sqrt( 2 (n rho^2 + 1) / (n^2 rho^2) log( sqrt(n rho^2 + 1) / alpha ) ),

and its coverage is 1 - alpha asymptotically (time-uniformly, as the start of monitoring grows), not exactly. In simulations at alpha = 0.05 the probability that the interval ever misses the mean was 0.06 for normal data from the first observations, but for skewed data (lognormal, Pareto with tail index 2.5) 0.21 when monitored from the start, 0.08 to 0.09 from n = 300 and 0.04 to 0.05 from n = 1000. It therefore reports nothing before start observations (default 1000). Use it for long runs; when a variance bound is known, or n is small, the Catoni sequence has exact coverage. rho is tuned so that the sequence is tightest after tuned_for observations. Its state is a handful of numbers.

Cost per step (PERFORMANCE.md): the Catoni sequence holds the sample and solves for its bounds by Newton steps over it -- 0.6 ms after 1000 observations with numpy, 3 ms in Python; the asymptotic sequence takes 2 µs and a constant state.

CatoniConfidenceSequence

Bases: Procedure

Confidence sequence for a mean, given only an upper bound sigma on the standard deviation.

Valid for every distribution with that variance bound (and, more generally, for dependent data whose conditional mean is the constant m and conditional variance at most sigma^2). With mean0, the procedure also tests H0: E[X] = mean0, rejecting when mean0 leaves the interval. The state holds the sample; each step costs O(n log(1/precision)).

rate(i)

lambda_i, the predictable stake on the i-th observation (Wang and Ramdas 2023).

interval(sample, guess=None)

The means m kept after the sample (in arrival order), before intersection over time.

Each bound is a root of a decreasing function of m, found by Newton steps kept inside a bracket (bisection when a step leaves it), from guess -- the previous bounds -- if given.

AsymptoticConfidenceSequence

Bases: Procedure

Asymptotic confidence sequence for a mean: needs only a finite variance, which it estimates.

The anytime-valid counterpart of the t interval for data far from normal (Waudby-Smith et al. 2024): coverage 1 - alpha holds asymptotically and uniformly over time, not exactly at small n -- see the module docstring for how large n has to be. No interval (None) is reported before start observations, nor while all of them are equal; it is not intersected over time, as asymptotic coverage does not license that. With mean0, also tests H0: E[X] = mean0 (rejecting when mean0 leaves the interval).

sequential_analysis.procedures.linear_model

Anytime-valid tests and confidence sequences for regression coefficients.

After Lindon, Ham, Tingley and Bojinov (2022), "Anytime-Valid Linear Models and Regression Adjusted Causal Inference in Randomized Experiments" (arXiv:2210.08589). The model is

y_t = x_t' beta + z_t' delta + eps_t,    eps_t ~ N(0, sigma^2) i.i.d.,

with p nuisance coefficients beta (an intercept and the covariates), d tested coefficients delta (the tested inputs, e.g. a treatment indicator: d = 1 gives a covariate-adjusted A/B effect) and sigma unknown. H0: delta = delta0.

The Bayes factor. Write X_n (n x p), Z_n (n x d) for the designs, P the projection onto the columns of X_n, Zr = (I - P) Z_n and yr = (I - P)(y - Z_n delta0) the parts the nuisance covariates do not explain, S = Zr'Zr, and

RSS = the residual sum of squares of the full regression,
nu  = n - p - d (its degrees of freedom),
Q0  = yr'yr = RSS + (dhat - delta0)' S (dhat - delta0),
F   = (Q0 - RSS) / d / (RSS / nu)   (the usual F statistic; t^2 if d = 1).

Under the alternative, (beta, sigma) gets the right-Haar prior d beta d sigma / sigma and delta | sigma ~ N(delta0, g sigma^2 I_d): the standardised coefficients (delta - delta0) / sigma have the fixed prior N(0, g I_d), Phi = I_d / g in the paper's notation. Integrating beta (Gaussian), delta (Gaussian) and then sigma (a Gamma integral) gives, under the alternative and under H0 alike, a constant times Q^(-(n - p) / 2), with the same constant except for a determinant, so

B_n = det(I + g S)^(-1/2) * (Q0 / Q1)^((nu + d) / 2),
Q1  = Q0 - h' (S + I/g)^(-1) h,   h = Zr' yr = S (dhat - delta0),
    = RSS + (dhat - delta0)' (S^-1 + g I)^(-1) (dhat - delta0),

the Bayes factor of the paper with Phi = I/g, written with the quantities of a regression table (its sequential t-test is the case d = 1). For d = 1 with s = S (a number), r = 1 / (1 + g s) and t the usual t statistic of the tested coefficient,

B_n = r^(1/2) * [ (1 + t^2 / nu) / (1 + r t^2 / nu) ]^((nu + 1) / 2),

the one-sample t-mixture of t_mixture.py with n c^2 replaced by g s (and nu = n - p - 1). The tests check both forms against a direct numerical integration of the mixture.

Validity. The model is invariant under y -> a y + X b (a > 0), the prior on (beta, sigma) is that group's right-Haar measure and the prior on the standardised effect does not depend on n or on the data, so B_n is the likelihood ratio of the maximal invariant of y_1..y_n (Wijsman's representation). The maximal invariants are nested in n, so under H0 B_n is a non-negative martingale with mean one in their filtration, whatever beta and sigma are, and Ville's inequality gives P(sup_n B_n >= 1/alpha) <= alpha. Hence rejecting when B_n >= 1/alpha is a level-alpha test under continuous monitoring and any stopping rule, 1/max_k B_k is an anytime-valid p-value, and {delta0 : B_n(delta0) < 1/alpha} is a (1 - alpha) confidence sequence. The conditions: Gaussian errors with a common variance, independent of the covariates; the covariates may be random, but the argument is conditional on their whole sequence, so they must not depend on earlier outcomes (randomised assignment and pre-treatment covariates qualify; an adaptive design that looks at the outcomes does not). The guarantee is exact for Gaussian errors and only approximate otherwise.

B_n is reported as 1 (log_e_value 0) while [X, Z] does not yet have full rank or nu < 1. Which steps those are depends on the covariates alone, so this changes nothing above: the process is B_n from the first full-rank step with nu >= 1 on, and E[B_n] = 1 there.

For d = 1 the set is an interval, dhat +/- t* se(dhat), t* in closed form (as in t_mixture.py), and None (the whole line) while the data cannot yet exclude anything. g is the prior variance of a tested coefficient in units of sigma^2 per unit of its input squared: for a 0/1 treatment indicator, of the standardised effect (Cohen's d). The test is most sensitive to effects of about that size; it is valid for every g, but g is not invariant to rescaling the tested inputs (the nuisance covariates may be rescaled and shifted freely). This is a fixed prior, not Zellner's g-prior N(0, g sigma^2 S^-1): that one depends on the design at time n, and the Bayes factors would no longer form a martingale.

State: n, the means of (covariates, tested, y) and their centred cross-product matrix (packed lower triangle), updated by Welford's rank-one step; without an intercept, the raw cross products. The normal equations are solved by Cholesky; the cost of a step is O((p + d)^3), independent of n.

AnytimeLinearModel

Bases: Procedure

Anytime-valid F-test (t-test for d = 1) and confidence sequence for regression coefficients.

Inputs: the outcome input and every name in covariates (nuisance, with an intercept unless intercept=False) and tested (the d tested coefficients), all real numbers, in every step.

critical_log_ratio(nu, log_r_inv)

t*^2 / nu at which B_n reaches 1/alpha (d = 1, log_r_inv = log(1 + g s)), or None.

fit(n, comoment)

Estimates, F, log B_n and (d = 1) the interval from the sufficient statistics.