polars_online.spec.corrchange

polars_online.spec.corrchange(name: str, *, features: list[str], kind: Literal['monitor', 'sequential', 'window'] = 'monitor', window_rows: int | None = None, alpha: float = 0.05, alpha_adjust: Literal['bonferroni', 'none'] = 'bonferroni', bandwidth: int | None = None, scalar: bool = False, crit: float | None = None, n_perm: int | None = None, permute_every_rows: int | None = None, perm_block: int | None = None, norm: Literal['l1', 'linf'] = 'l1', seed: int | None = None, change_action: Literal['flag', 'reset'] = 'flag', monitor_rows: int | None = None, boundary_gamma: float | None = None, **common: Unpack[CommonKwargs]) → dict[str, Any][source]

Tests of whether the correlations between the feature columns have changed, by three kinds of test.

Use kind="monitor" to ask whether the correlations were constant over each span of rows, kind="sequential" to test each row as it arrives against a history taken as stable, and kind="window" to ask how big the change between two adjacent windows is. Use bocpd() for the age of the current regime of the features’ levels and spreads, and deco() to follow an equicorrelation that moves.

Parameters

The stream parameters every builder takes, such as clock, gap_cap, min_weight and group, are in polars_online.spec. This model takes features, at least two, and no targets. Nothing decays but the optional standardizer of scalar and weight_sum beside it, so half_life and lam are refused except under scalar. A row’s positive weight reaches only weight_sum and that standardizer: the span, the windows and the history take each row unweighted. fit_intercept has nothing to act on, as there is no regression, and no diagnostic that reads residuals applies. A parameter that belongs to another kind is refused, naming the kinds it applies to. This model’s own:

kind

"monitor" (the default), "sequential" or "window".

window_rows

Required by every kind: the span "monitor" tests (at least 8), the history "sequential" monitors against (at least 8), or each of "window"’s two windows (at least 3).

alpha, alpha_adjust

The level, in (0, 1) (default 0.05), and, under "monitor" and "sequential", how it is spread over the pairs: "bonferroni", the default, alpha / npairs, or "none", alpha on each pair. Under "window" one permutation statistic covers every pair at once, so there is nothing to spread, and an alpha_adjust other than the default is refused. Under "sequential" without crit each pair’s share is refused below 5e-11: the critical value is solved from the boundary’s law, and in a smaller tail the solve’s quantile is off by more than the 0.03 Wied and Galeano’s own table is good to.

bandwidth

"monitor" and "sequential": overrides the Bartlett bandwidth, floor(ln window_rows), for the span and for the history alike. Lag l is weighted 1 - l / bandwidth for l < bandwidth, so at 1 only lag 0 is left, and 0 is refused. At most window_rows: a span of window_rows rows has no lag past window_rows - 1, so a larger bandwidth adds no lag. It only flattens the weights toward 1, where the centered lags sum to 0, and the long-run variance falls toward 0 with them.

scalar

"monitor" and "sequential": in place of every pair, test the mean of u, the equicorrelation of the standardized row (deco()’s u), with the Bartlett long-run standard deviation of u in place of D: one statistic however many columns there are. half_life/lam parametrize that standardizer, and weight_sum with it, and are accepted only here. Left out, nothing decays. Default False.

crit

"window": a fixed threshold, in place of the permutation quantile. "sequential": replaces Wied & Galeano’s critical value. Finite and above 0. Default none.

n_perm, permute_every_rows, perm_block

"window"’s permutation quantile: n_perm draws (default 200, at most 2^20, and without crit at least 20 and at least ceil(1 / alpha) - 1), redrawn every permute_every_rows rows (default window_rows, at least 1), in blocks of perm_block rows (default 1, from 1 to window_rows). The window test in Notes gives the cost and the size.

norm

"window": "l1" (the default) or "linf".

seed

"window": seeds the permutation draws, at least 0, so two runs with the same seed report the same critical values. Default 0 (None is 0), and nothing draws from the system’s entropy. The critical values a seed gives hold within one release of the package: a release may draw its permutations another way, from the same distribution, and a seed’s critical value then moves by a few percent.

change_action

"window": what a flag does, in the words drift_action takes: "flag" (the default) flags and carries on, and "reset" empties the windows and starts over. A "monitor" span and a "sequential" cycle end at their flag already, so "reset" is refused there.

monitor_rows

"sequential": the rows monitored after each history, the paper’s floor(m T). Default window_rows (T = 1). At least 2.

boundary_gamma

"sequential": the boundary’s exponent, 0 <= boundary_gamma <= 0.49. Default 0, the straight boundary 1 + k/m. Above 0 a change soon after the history is caught sooner and a late one later, at more false alarms (Choosing boundary_gamma in Notes). At 0.5 the boundary would be crossed with probability 1, and the solve behind the critical value costs time in proportion to 1 / (1/2 - boundary_gamma) on the way there, so a value above 0.49 is refused.

Output

One output column, named after the spec, whose value in each row is a record of these fields. stat, crit, flag and since_flag are null except on a row where a statistic is due, and since_change except on a flag. The statistic reported on a row includes that row, and is reported before the row is learned. So a zero-weight row is reported as if it would be learned. It then does not enter the span, the history or the monitoring period, does not advance since_flag for the rows after it, and if it flags, it resets neither since_flag nor, under change_action="reset", the windows. A clock break (a step gap_cap shortened, or a session change) abandons the span, the windows or the cycle. docs/OUTPUTS.md#corrchange gives each field’s type and when it is null:

stat

The test statistic: for the span, for the pair of windows, or for the monitored row against its boundary.

crit

The critical value it is compared against.

flag

True on the row where stat crossed crit.

since_flag

Learned rows since the last flag.

since_change

On a flag, the rows since the change it dates, counted through the flag’s row from the first changed one. That row is the one after the maximum of j * |rho_j - rho_m| over the span ("monitor"), the one the paper’s Eq. 8 gives ("sequential"), or the second window’s first ("window"). Null otherwise. In the pairwise test (without scalar), it is null on a "sequential" flag that has fewer than two monitored rows before it. And it is null where either feature of the flagged pair is constant over those rows, since a correlation then has no spread to divide by.

weight_sum

The weight the model has accumulated before the row and before the row’s own decay.

settled_frac

How far the model had come toward its steady state under decay before the row, null where nothing decays.

withheld_reason

Why the row’s fields were withheld: null on every row at the default min_weight, and below_min_weight while weight_sum is below a min_weight given.

Raises

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

  • fewer than two features, and an alpha outside (0, 1);

  • a kind, alpha_adjust, norm or change_action not one of its words;

  • window_rows left out or below the kind’s minimum;

  • a parameter of another kind, and half_life or lam without scalar;

  • under "sequential" without crit, a share of alpha below 5e-11 a pair;

  • a bandwidth of 0 or above window_rows, a crit not finite or not above 0, and an n_perm, permute_every_rows, perm_block or seed outside the range its parameter entry gives, an n_perm among them too small to flag at alpha;

  • a boundary_gamma outside [0, 0.49], and a monitor_rows below 2;

  • change_action="reset" under "monitor" or "sequential";

  • a switch of a diagnostic that reads residuals.

The update

"monitor" is the closed-sample constancy test of Wied, Krämer & Dehling (2012), run over consecutive spans of window_rows rows. At the last row of a span, per pair, with m the span’s rows and rho_j the sample correlation of its first j rows:

Q = max_{2 <= j <= m} (j / sqrt(m)) * |rho_j - rho_m| / D

D is the delta-method long-run standard deviation of rho (The long-run deviation in Notes). Over the pairs the statistic is the maximum, and the level is alpha / npairs under the default Bonferroni adjustment, or alpha under alpha_adjust="none".

"sequential" is the monitoring procedure of Wied & Galeano (2013). A cycle is window_rows learned rows of history (m), from which each pair’s correlation rho_hist and its D are read as for "monitor". Then the k-th monitored row, for k up to monitor_rows, reports

V_k  = (k / sqrt(m)) * (rho_mon_k - rho_hist) / D
stat = max over pairs of |V_k| / w(k / m)
w(b) = (1 + b) * (b / (1 + b)) ** boundary_gamma

with rho_mon_k the correlation of the k monitored rows so far, this one included, and flags where stat passes crit. The cycle ends at a flag or after its monitor_rows-th row, and the next learned row starts a new history. Nothing is reported during the history, nor on the first monitored row, since a correlation needs two.

"window" reports norm(vech(R_pre - R_post)) over two adjacent blocks of window_rows rows, R_pre and R_post their correlation matrices: how big the change is. The monitor asks instead whether the span was constant. It flags against crit, or without one against a permutation quantile (The window test in Notes).

Example

This code tests two features whose correlation jumps from 0 to 0.8 at row 1,100, over spans of 200 rows, and prints the span that flagged and the row its change was dated to:

import numpy as np

rng = np.random.default_rng(9)
a, e = rng.standard_normal(2_000), rng.standard_normal(2_000)
rho = np.where(np.arange(2_000) < 1_100, 0.0, 0.8)   # the jump at row 1,100
b = rho * a + np.sqrt(1 - rho**2) * e
pl.DataFrame({"a": a, "b": b}).write_parquet("pair.parquet")

c = po.spec.corrchange(
    "brk", features=["a", "b"],
    kind="monitor",                                     # constant in each span?
    window_rows=200,                                    # a verdict on each span's last row
)
out = pl.scan_parquet("pair.parquet").online.fit_predict([c]).collect()
due = out.unnest("brk").with_row_index("row").filter(pl.col("stat").is_not_null())
flags = due.filter("flag")
print(f"{due.height} spans tested, {flags.height} flagged")
for r in flags.iter_rows(named=True):
    first = r["row"] - r["since_change"] + 1          # the first changed row, as dated
    print(f"span ending on row {r['row']}: stat {r['stat']:.2f} against {r['crit']:.2f}")
    print(f"the change dated to row {first}")
10 spans tested, 1 flagged
span ending on row 1199: stat 2.52 against 1.36
the change dated to row 1099

See also

  • bocpd(), a posterior over the age of the current regime.

  • deco(), an equicorrelation that moves with the stream.

  • docs/REGIMES.md, the size and power of these tests, measured against their papers.

Notes

The long-run deviation. D takes the five raw moments (x², y², x, y, xy) centered at their span means and their Bartlett long-run covariance at bandwidth L = floor(ln m) with the paper’s kernel, lag l at weight 1 - l/L (their Appendix A.1). It maps them to (var_x, var_y, cov) and then to rho. It is computed on the span centered at its means and scaled by its standard deviations, as the paper’s xi series, so the columns’ level does not enter. A pair within rounding of |rho| = 1 has no D and no verdict, as a constant column has none.

The monitor test. Under the null Q converges to sup|B|, a Brownian bridge, so the critical value is the Kolmogorov quantile, computed from the series, not pinned, and it reproduces the published 1.3581 at 5%. A span reports on its last row only, and tests only its own rows. So a change is found at most window_rows rows late, and reliably only where it falls well inside a span. A jump in correlation from 0 to 0.8 at row 1,100 of spans of 200 rows was found on 20 of 20 seeds. At rows 1,190 and 1,195, near the span’s end, it was found on 0 to 3 of 20 (each of three sets of 20 seeds). docs/REGIMES.md §2 and §3 measure its size and power against those tables, and tests/test_corrchange.py holds its size near the nominal level.

The sequential test. The critical value is Wied & Galeano’s: with T = monitor_rows / window_rows, crit = (T / (1 + T)) ** (1/2 - boundary_gamma) * q. q is the 1 - alpha quantile of sup_{0 < s <= 1} |W(s)| / s ** boundary_gamma for a Brownian motion W (their Eq. 7), at alpha / npairs under Bonferroni. At boundary_gamma = 0 it comes from that law’s series, 2.2414 at 5%, so crit is 1.5849 at T = 1. Above 0 there is no series and the paper simulates. Here the law is solved as the diffusion it is, without simulation error. The values are within 0.03 of the paper’s Table 1 and above it in 11 of its 12 cells, since a simulation on a grid misses crossings between its points. crit replaces the value.

On a flag, since_change dates the change as the paper’s Eq. 8 does: k_hat = argmax_{j < tau} j * |rho_mon_j - rho_mon_{tau-1}| over the rows monitored before the flag, the history left out (they found it distorts the estimate). It reports tau - k_hat, the rows from the first changed one through the flag’s. They found it biased late for a change early in the period and early for one in its middle, both less as m and T grow.

What it assumes, as the paper does: the history’s correlations are constant (their Assumption 1, which kind = "monitor" over the same rows checks), the rows have finite fourth moments, and dependence fades (near-epoch dependence, which admits GARCH). Against "monitor", every row is tested and the baseline is fixed. So a change is flagged as soon as it is large enough, and a drift that "monitor"’s spans would each absorb is measured against one level.

Choosing boundary_gamma. Above 0 the boundary is lower at the start of the period, so a change soon after the history is caught sooner and a late one later. It also increases the size: the paper measured 0.050-0.077 at boundary_gamma of 0, 0.047-0.087 at 0.25, and 0.106-0.174 at 0.45, for a nominal 0.05 on GARCH pairs (their Table 2). Their summary:

boundary_gamma

when

0

the pair is watched for a long time and false alarms are to be avoided, or a change is not expected soon after the history

0.45

to catch a change soon after it as fast as possible, false alarms accepted

0.25

a compromise

The window test. Without crit the critical value is a permutation quantile: n_perm draws of the pooled rows shuffled between the two windows, redrawn every permute_every_rows rows. A report flags when fewer than floor(alpha * (n_perm + 1)) draws reach its statistic. That is the standard permutation test, which counts the observed statistic as one more draw. On rows the null makes exchangeable, its rank among the n_perm + 1 is uniform. So a test of a report against draws of its own windows has a size of that count over n_perm + 1, at most alpha: at alpha 0.05, 0.0476 at 20 draws and 0.0498 at the default 200. The size here is about that, not exactly it. The critical value is drawn from the windows after a report and held for permute_every_rows reports, so each later report is compared with draws of windows up to permute_every_rows - 1 rows older than its own. Over 200 streams of iid rows at alpha 0.05 and 200 draws, with the value held for window_rows reports (the default), 4.8% to 5.2% of non-overlapping spans flagged at windows of 50 to 400 rows, each within one standard error (0.24%) of 5%. Fewer than ceil(1 / alpha) - 1 draws could never flag, so such an n_perm is refused: at alpha 0.01, 99 draws at least.

The draws are in blocks of perm_block, so that serial dependence does not make the null too liberal. It is not a sign-flip null. Negating a whole row leaves every x x' and so every correlation matrix exactly where it was, so a sign-flip null has no spread at all. The quantile is drawn from the windows after a row is reported, so the first report once the windows fill has no critical value and cannot flag: crit is null there, and in force from the next row. A change_action="reset" empties the windows and the value in force with them, so the first report after the refill has none either. The flag rate per row is not alpha here: two windows that slide by one row are almost the same windows, so a statistic above the quantile stays above it for a run of rows.

A redraw shuffles the 2 * window_rows pooled rows n_perm times and reads both windows’ correlations each time, so it costs n_perm * window_rows * p**2 for p features. At the default permute_every_rows (window_rows), a redraw comes once a window’s length of rows, that is n_perm * p**2 a row, whatever the window, so the draws’ cost per row does not grow with window_rows. Each drawn value is held for those window_rows rows. A smaller permute_every_rows redraws more often, at more cost a row.