polars_online.spec.seqtest

polars_online.spec.seqtest(name: str, *, targets: Sequence[str | Target | FormulaTarget | Expr], a: str | None = None, b: str | None = None, a_suffix: str | None = None, b_suffix: str | None = None, **common: Unpack[CommonKwargs]) → dict[str, Any][source]

A sequential test of a target’s sign by betting, whose evidence can be read at any row.

Use it to ask whether a target is positive more often than negative, or, with a and b, whether one spec of the bank predicts closer than another. You can read the answer at every row and act the first time it is enough, which a p-value checked over and over does not allow. Use polars_online.eval.seqtest() for the same test over a frame in memory, and polars_online.eval.compare_specs() for several specs’ scores over the whole stream in one table.

Parameters

The stream parameters every builder takes, such as clock, group, session and restart_after_step_back, are in polars_online.spec. This model is not a regression and makes no prediction. It reads only its targets (or the residuals of the specs a and b name) and takes no features: a spec dict or a TOML table says features = []. A trial is a row, so weight is refused. A test that forgot its losses would not keep its guarantee, so half_life and lam are refused. min_weight defaults to 0, and fit_intercept has nothing to act on. The test resets at a session change under session_gap = "reset" and at a step back past restart_after_step_back, and starts over at each session span under group_close = "session". This model’s own:

a, b, a_suffix, b_suffix

Compare two specs of the same bank. Each target t names a residual field both carry: resid_<t> on each side, plus the side’s grid suffix when it is a grid (a_suffix="@h50" picks resid_<t>@h50 of a, and "__r0.1" a ridge value). The sign tested is that of |resid_b| - |resid_a|, positive when a was closer on the row. Any loss that grows with |resid| (squared, absolute, Huber) gives the same sign, so this tests “a beats b” under any of them. The bank runs a and b first, so the comparison reads the same out-of-sample residuals their output columns report. A row where either side is null (warm-up, a skipped row) is a row the test sits out. Default none: the test is of each target’s own sign. a and b are given together, and a suffix only beside them. Two instances of one grid (an instance is the part of a model that fits one half-life), such as a_suffix="@h20" against b_suffix="@h400", are a comparison like any other.

Output

One output column, named after the spec, whose value in each row is a record of these fields, per target t and read before the row is learned. docs/OUTPUTS.md#seqtest gives each field’s type and when it is null:

log_e_pos_<t>, log_e_neg_<t>

The log wealth (log E) of the two gamblers of The update, one betting that the target is positive and one that it is negative. 0 is no evidence, and log(20), about 3.0, is level 0.05.

n_pos_<t>, n_neg_<t>

The signs counted so far (Int64). A zero or null target bets nothing and counts nothing.

weight_sum

The weight the model has accumulated before the row, decayed by nothing: the count of rows before it.

settled_frac

Always null, since nothing decays.

withheld_reason

Why the row’s fields were withheld: null on every row at the default min_weight of 0, and below_min_weight where a min_weight given is not yet reached.

With a and b, these fields take the place of log_e_pos_<t>, log_e_neg_<t>, n_pos_<t> and n_neg_<t>:

log_e_a_<t>, log_e_b_<t>

The log wealth of the gambler betting that a is closer on the next row, and of the one betting that b is: log_e_a_<t> past log(1/alpha) is evidence at level alpha that a beats b.

wins_a_<t>, wins_b_<t>

The rows so far on which a was closer, and on which b was (Int64). A tie, or a row where either side is null, counts for neither.

There is no coef, and no diagnostic that reads residuals applies, since the model makes no prediction.

Raises

As every builder does (polars_online.spec), TypeError for features, which this model does not take, and ValueError naming the problem for:

  • weight, half_life or lam;

  • a without b or the reverse, and a suffix without them;

  • a and b naming the same spec with no suffix or the same one, or either naming this spec.

The bank refuses, by name, when it is built: a side that is not in the bank or is itself a seqtest, and a target either side has no residual for.

The update

The model keeps, per target, the wealth of two gamblers: E_pos bets that the next sign is positive, and E_neg that it is negative, each 1 at the first row. The row’s value is reduced to its sign s in {-1, 0, +1}. n_pos and n_neg are the counts of positive and negative rows before this one, and n = n_pos + n_neg:

stake_pos = max(0, (n_pos - n_neg) / (n + 1))     E_pos *= 1 + stake_pos * s
stake_neg = max(0, (n_neg - n_pos) / (n + 1))     E_neg *= 1 - stake_neg * s

The stakes are computed from the rows before. (E_pos + E_neg) / 2 is the two-sided e-value (The guarantee in Notes).

Example

This code tests two targets, one positive half the time and one 58% of the time, and prints the most evidence each reached and the first row where it passed level 0.05:

import numpy as np

rng = np.random.default_rng(3)
fair = rng.standard_normal(2_000)              # positive half the time
up = 0.2 + rng.standard_normal(2_000)          # positive 58% of the time
pl.DataFrame({"fair": fair, "up": up}).write_parquet("signs.parquet")

sign = po.spec.seqtest("sign", targets=["fair", "up"])
out = pl.scan_parquet("signs.parquet").online.fit_predict([sign]).collect()
out = out.unnest("sign")
for t in ["fair", "up"]:
    e = out[f"log_e_pos_{t}"]
    crossed = (e >= np.log(20)).arg_true()     # level 0.05
    first = crossed[0] if len(crossed) else None
    print(f"{t}: largest log_e_pos {e.max():.2f}, first row past log(20): {first}")
fair: largest log_e_pos 0.51, first row past log(20): None
up: largest log_e_pos 19.81, first row past log(20): 46

See also

Notes

The stake. (n_pos - n_neg) / (n + 1) is 2p - 1 for the Krichevsky-Trofimov estimate p = (n_pos + 1/2) / (n + 1) of P(s = +1). That is the stake a gambler with a Beta(1/2, 1/2) prior puts on the next sign, clipped so that each side bets only on the direction it tests.

The guarantee. Under the null (given everything before it, a row is at least as likely to be negative as positive), E_pos is a non-negative supermartingale with E_pos[0] = 1. Ville’s inequality then gives P(max_t E_pos[t] >= 1/alpha) <= alpha. That is the whole guarantee. log_e_pos >= log(1/alpha) on any row rejects “no more positives than negatives” at level alpha, and the stream can be read at every row and stopped the moment it crosses. A p-value cannot be: checking it repeatedly inflates its error rate. Nothing about the target but its sign is assumed: no independence of the sizes, no bound, no variance. What it does not test is the size: a stream up by a hair 60% of the time and down by a mile the rest rejects.