Skip to content

Methods

Each procedure states what it promises in its guarantee attribute: exact (error rates or coverage at every sample size, under the stated assumptions), asymptotic, model (exact under a stated model or prior), approximate or none. Where an exact procedure answers the question, it is the one the documentation recommends first; the full list is on the which-method page.

Kind Procedures
Tests of simple hypotheses SPRT (Wald), TwoSPRT (Lorden's 2-SPRT for the Kiefer–Weiss problem), PlanTest (executes any precomputed plan)
Group sequential trials GroupSequentialTest (one mean), GroupSequentialTwoMeans, GroupSequentialProportions, GroupSequentialLogRank (two arms: continuous, binary and time-to-event endpoints; stratified log-rank), GroupSequentialMonitor (any statistic, alpha spent at the information actually reached); efficacy and non-binding futility boundaries; checked against rpact and R's survival package
Anytime-valid inference NormalMixtureSPRT (mSPRT, known variance), TMixtureSPRT (unknown variance); both with always-valid p-value and confidence sequence
Nonparametric, anytime-valid QuantileTest, QuantileConfidenceSequence (any quantile — median, 90th percentile — of any distribution, ties and atoms included; no moments), KernelTwoSampleTest (are A and B equally distributed? any difference: location, scale, shape; by betting), BettingMeanTest, BettingConfidenceSequence (mean of bounded data: conversion rates, scores), SequentialSignTest (P(X > m) = P(X < m); paired data via topology)
Means without normality CatoniConfidenceSequence (exact, needs only a bound on the standard deviation; heavy tails and outliers), AsymptoticConfidenceSequence (estimated variance; coverage asymptotic, for long runs)
A/B tests BoundedABTest (exact confidence sequence for an effect on any bounded metric), RateRatioTest (exact, events per unit of exposure, robust to a drifting common rate), TwoProportionTest (exact for any n, one- or two-sided; GROW e-values on blocks of units, 1.3–1.6 times the users of the asymptotic test; or universal inference for outcome-adaptive allocation), SampleRatioMismatch (is the traffic split as intended?), ABTest (difference of means with a pre-experiment covariate, CUPED-like, confidence sequence), RatioABTest (ratio metrics such as revenue per session or click-through rate, and relative lift: delta method on user totals, asymptotic confidence sequences for the difference and the lift), MultipleTests and e_bh (many metrics or arms, false discovery rate at any stopping time), MultipleTests.versus_control; ThompsonAllocation (redirects traffic to the arms likely to be best, with a floor and an optional reserve for the control; expected-loss deployment rule) with BoundedABTest(propensity_input=...), exact under any allocation
Regression and survival AnytimeLinearModel (anytime-valid F/t tests and confidence sequences for regression coefficients, covariate-adjusted effects; exact under Gaussian errors), AnytimeLogRankTest (anytime-valid log-rank test and hazard-ratio confidence sequence, any baseline hazard; stratified with strata=)
Experiment programmes and planning OnlineFDR (e-LOND: false discovery rate over a series of experiments decided one by one), sequential_analysis.planning.simulate (power and stopping-time distribution of any procedure)
Change-point detection CUSUM, ShiryaevRoberts; MeanEDetector, QuantileEDetector (nonparametric e-detectors: average run length to a false alarm at least the target for every distribution with the given mean or quantile)
Filtering and estimation KalmanFilter (any linear Gaussian state-space model: trends, autoregressions, tracking, control input; exact likelihood), RobustKalmanFilter (Student-t observation noise: outliers discounted), HiddenMarkovFilter (which hidden regime now; categorical, Gaussian, Student-t, multivariate Gaussian or Poisson observations), OnlineHMM (the same while learning the transition and emission parameters on the stream: online EM), ParticleFilter (any model you can simulate: stochastic volatility, heavy tails; unbiased likelihood), LocalLevelKalman, BootstrapParticleFilter, MeanDifference, EMA
Smoothing and fitting (offline) sequential_analysis.smoothing: kalman_smoother (Rauch–Tung–Striebel), forward_backward and viterbi for hidden Markov models; sequential_analysis.hmm_fit.fit_hmm (Baum–Welch with restarts; agrees with hmmlearn)
Forecasting ExponentialSmoothing (ETS: level, additive or damped trend, additive season; forecasts and intervals agree with statsmodels), AutoRegressive (AR(p)), each with regressors known ahead (promotions, holidays, prices), an optional log scale, and fixed parameters from sequential_analysis.forecasting.fit_ets / fit_ar or learnt on the stream (Bayesian regression on the lags and regressors with forgetting; the noise level; the effects of regressors); PoissonSmoothing (counts: negative binomial forecasts with count intervals, fit_counts, averaged_counts); ModelAveraging, averaged_smoothing (weights forecasters by their predictive densities, with forgetting: learns the smoothing parameters); ConformalForecast (distribution-free intervals around any forecaster: long-run coverage for any data); ForecastComparison (anytime-valid: is forecaster A better than B?)
Several series VectorAutoRegressive (VAR(p) with fixed coefficients from fit_var, which agrees with statsmodels, or learnt online with forgetting: multivariate Student t forecasts), CrossCorrelation (lead-lag correlations at lags -L..L), Lagged (feeds any procedure the past of its inputs; with AnytimeLinearModel, an anytime-valid Granger test), DynamicRegression (drifting coefficients with unknown variance: hedge ratios, time-varying betas, the spread's z-score)
Event streams HawkesProcess (exact filter of a self-exciting process: intensity, likelihood, time-rescaled compensators, expected events; fit_hawkes, simulate_hawkes), EventStudy (cumulative reaction after events, with confidence sequences), the AsOfJoin topology (events attached to the bars that knew them, with decayed sums, no look-ahead)
Volatility GARCH (GARCH(1,1) and GJR-GARCH(1,1), normal or Student t shocks: variance forecasts, value at risk, standardized residuals), sequential_analysis.garch_fit.fit_garch (maximum likelihood; agrees with the arch package)
Bayesian change points BayesianChangePoint (Adams–MacKay run-length posterior; unknown parameters before and after the change; normal, Poisson, 0/1 data)

Likelihood-ratio procedures take a family: Gaussian (known variance), Bernoulli, Poisson, Exponential.

Filters are checked against exact references. The Kalman filter agrees with exact Gaussian conditioning computed in rational arithmetic to 2·10⁻¹⁵; the hidden Markov filter and the change-point posterior agree with enumeration of every hidden path or segmentation to 10⁻¹⁵; the particle filter converges to the Kalman filter and to a filter by numerical integration, and its likelihood estimate is unbiased (tests/test_filters.py).

Which method for data that are not normal? For a median or another quantile — latencies, revenue per user, anything heavy-tailed — use the quantile procedures: they assume nothing about the distribution. To ask whether two groups differ at all, KernelTwoSampleTest. For a mean, the data have to be bounded (BettingConfidenceSequence, exact) or have a known bound on their variance (CatoniConfidenceSequence, exact); otherwise AsymptoticConfidenceSequence is valid only approximately and for long runs — no method can guarantee coverage of a mean of arbitrary unbounded data. All of them may be monitored after every observation; each docstring gives the simulated error rates on skewed, heavy-tailed and discrete data.

Design (sequential_analysis.design), computed offline before the experiment:

  • operating_characteristic(plan, family, theta) — error probabilities, stopping-time distribution and expected sample size of a plan, without simulation: exact for Bernoulli and Poisson data, on a fine lattice (error of order h²) for normal and exponential data;
  • kiefer_weiss_plan(theta0, theta1, alpha0, alpha1, horizon, family=...) — the plan with a maximum sample size that minimises the expected sample size at θ* (modified Kiefer–Weiss problem), by backward induction, for Bernoulli, Poisson, normal and exponential data. With theta_star="least-favourable" it solves the Kiefer–Weiss problem itself: θ* is placed where the maximum expected sample size is attained (Lorden's characterisation) — the root of that condition for normal and exponential data, the best candidate of a bisection for discrete data, where the condition holds only approximately. For response rates 30% against 50% at error rates 0.05 it lowers the maximum expected sample size from 50.8 (Wald's SPRT calibrated to the same errors) to 45.2, and to 45.0 with the least favourable θ. For a normal mean 0 against 0.5 (horizon 120) it needs 31.0 observations on average at θ, against 31.3 for Lorden's 2-SPRT with thresholds calibrated to the same errors: the 2-SPRT is already close to optimal there. A design takes about a second for the Bernoulli example and from seconds to a minute for normal data on the default lattice. The least favourable θ* takes longer: for discrete data it designs about a dozen candidates and compares their largest expected sample sizes, some thirty times the time of one design; for normal data it finds the root of Lorden's characterisation from the precomputed table below, in a few designs. With numpy installed (optional: pip install "sequential-analysis[fast]") the backward pass on wide lattices — normal, exponential, Poisson with larger rates — runs as array operations, about ten times faster, with the same plans. Targets that no test with horizon observations can meet (the Neyman–Pearson bound) are reported at once.

Least favourable θ* for normal data is precomputed: tabulated_least_favourable(alpha0, alpha1, rho) gives the root of Lorden's characterisation for α₀, α₁ ∈ [0.005, 0.2] to about 3·10⁻⁴ of θ₁ − θ₀ (rho is how much longer the horizon is than the shortest fixed-sample test; the root hardly depends on it above 1.5). theta_star="least-favourable" starts its search from it, which makes it two to four times faster; the search still verifies the characterisation. The table is computed by tools/least_favourable_table.py on Gauss–Lobatto–Legendre nodes (D-optimal for polynomial regression) and checked on Halton points not used in the fit.

Design cache (sequential_analysis.cache): every plan kiefer_weiss_plan computes is stored on disk and returned from there when the same question is asked again — the key is every argument, the family, the library version and the version of the design algorithm. A stored plan is not trusted blindly: its operating characteristic is recomputed and must reproduce the stored one and meet the requested error rates, otherwise it is computed again. Every save, load and ignored file is reported on the logger sequential_analysis.cache (visible by default):

design cache: computed kiefer_weiss_plan(0.3, 0.5, 0.05, 0.05, horizon=150, family=bernoulli, theta_star=None) in 1.2 s and saved it to /home/me/.cache/sequential-analysis/kiefer_weiss-<hash>.json
design cache: loaded kiefer_weiss_plan(...) from /home/me/.cache/sequential-analysis/kiefer_weiss-<hash>.json (computed in 1.2 s); error rates verified

The directory is cache= if given, else $SEQUENTIAL_ANALYSIS_CACHE, else $XDG_CACHE_HOME/sequential-analysis or ~/.cache/sequential-analysis; cache=False or SEQUENTIAL_ANALYSIS_CACHE=off turns it off, clear_design_cache() empties it. A cache that cannot be written is reported and never fails the design.

Group sequential designs (sequential_analysis.group_sequential): group_sequential_design(alpha, fractions, spending) computes efficacy boundaries for planned analyses from an alpha-spending function (O'Brien–Fleming and Pocock types, power family, or your own), one- or two-sided, and gives crossing probabilities, power, expected sample size and the maximum sample size for a target power. With futility=..., power=... it adds non-binding futility boundaries by beta spending. The O'Brien–Fleming boundaries for five looks reproduce the published 4.877, 3.357, 2.680, 2.290, 2.031.

design.at(fractions) recomputes the boundaries for analyses that do not happen as planned. The design also gives maximum sample sizes for two means and two proportions, the number of events for a log-rank test, and the inflation factor.

These agree with rpact: 56 designs, boundaries to 2·10⁻⁷, and 44 sample sizes. tools/r_reference.R computes the reference values, and a CI job regenerates them with R and compares again on every change.

Inputs: sequential_analysis.sources binds values, files (from_csv, with explicit conversion), simulators and replayed logs to logical inputs. Transformations between topology and procedure, or between the stages of a Chain, are Transform objects (Difference, Field, or your own) with a name, a version and a configuration that the checkpoint records.

Every statistical claim in the docstrings — error rates, coverage, run lengths, optimality — is checked by a test (tests/test_methods.py).