rheon.spec.corrchange¶
- rheon.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, permute_every: float | timedelta | str | _Expr | 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, andkind="window"to ask how big the change between two adjacent windows is. Usebocpd()for the age of the current regime of the features’ levels and spreads, anddeco()to follow an equicorrelation that moves.Parameters
The stream parameters every builder takes, such as
clock,gap_cap,min_weightandgroup, are inrheon.spec. This model takesfeatures, at least two, and notargets. Nothing decays but the optional standardizer ofscalarandweight_sumbeside it, sohalf_lifeandlamare refused except underscalar. A row’s positive weight reaches onlyweight_sumand that standardizer: the span, the windows and the history take each row unweighted.fit_intercepthas 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_rowsRequired 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_adjustThe 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",alphaon each pair. Under"window"one permutation statistic covers every pair at once, so there is nothing to spread, and analpha_adjustother than the default is refused. Under"sequential"withoutcriteach pair’s share is refused below5e-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. Laglis weighted1 - l / bandwidthforl < bandwidth, so at 1 only lag 0 is left, and 0 is refused. At mostwindow_rows: a span ofwindow_rowsrows has no lag pastwindow_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 ofu, the equicorrelation of the standardized row (deco()’su), with the Bartlett long-run standard deviation ofuin place ofD: one statistic however many columns there are.half_life/lamparametrize that standardizer, andweight_sumwith it, and are accepted only here. Left out, nothing decays. DefaultFalse.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_permdraws (default 200, at most 2^20, and withoutcritat least 20 and at leastceil(1 / alpha) - 1), redrawn everypermute_every_rowsrows (defaultwindow_rows, at least 1), in blocks ofperm_blockrows (default 1, from 1 towindow_rows). The window test in Notes gives the cost and the size.permute_every"window": the same redraw on the clock, every this long as well as everypermute_every_rowsreports, whichever comes first; given alone, the count beside it is none. A number of the clock’s units (rows where the spec has no clock) or a duration such as"10m"on a temporal clock, at least 0,0every report. On a clock of one unit a row,permute_every = nispermute_every_rows = n, to the bit.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 (Noneis 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 wordsdrift_actiontakes:"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’sfloor(m T). Defaultwindow_rows(T = 1). At least 2.boundary_gamma"sequential": the boundary’s exponent,0 <= boundary_gamma <= 0.49. Default 0, the straight boundary1 + 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 to1 / (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,flagandsince_flagare null except on a row where a statistic is due, andsince_changeexcept 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 advancesince_flagfor the rows after it, and if it flags, it resets neithersince_flagnor, underchange_action="reset", the windows. A clock break (a stepgap_capshortened, 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:statThe test statistic: for the span, for the pair of windows, or for the monitored row against its boundary.
critThe critical value it is compared against.
flagTrue on the row where
statcrossedcrit.since_flagLearned rows since the last flag.
since_changeOn 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 (withoutscalar), 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_sumThe weight the model has accumulated before the row and before the row’s own decay.
settled_fracHow far the model had come toward its steady state under decay before the row, null where nothing decays.
withheld_reasonWhy the row’s fields were withheld: null on every row at the default
min_weight, andbelow_min_weightwhileweight_sumis below amin_weightgiven.
Raises
As every builder does (
rheon.spec),TypeErrorfortargets, which this model does not take, andValueErrornaming the problem for:fewer than two features, and an
alphaoutside(0, 1);a
kind,alpha_adjust,normorchange_actionnot one of its words;window_rowsleft out or below the kind’s minimum;a parameter of another kind, and
half_lifeorlamwithoutscalar;under
"sequential"withoutcrit, a share ofalphabelow5e-11a pair;a
bandwidthof 0 or abovewindow_rows, acritnot finite or not above 0, and ann_perm,permute_every_rows,perm_blockorseedoutside the range its parameter entry gives, ann_permamong them too small to flag atalpha;a
boundary_gammaoutside[0, 0.49], and amonitor_rowsbelow 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 ofwindow_rowsrows. At the last row of a span, per pair, withmthe span’s rows andrho_jthe sample correlation of its firstjrows:Q = max_{2 <= j <= m} (j / sqrt(m)) * |rho_j - rho_m| / DDis the delta-method long-run standard deviation ofrho(The long-run deviation in Notes). Over the pairs the statistic is the maximum, and the level isalpha / npairsunder the default Bonferroni adjustment, oralphaunderalpha_adjust="none"."sequential"is the monitoring procedure of Wied & Galeano (2013). A cycle iswindow_rowslearned rows of history (m), from which each pair’s correlationrho_histand itsDare read as for"monitor". Then thek-th monitored row, forkup tomonitor_rows, reportsV_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_kthe correlation of thekmonitored rows so far, this one included, and flags wherestatpassescrit. The cycle ends at a flag or after itsmonitor_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"reportsnorm(vech(R_pre - R_post))over two adjacent blocks ofwindow_rowsrows,R_preandR_posttheir correlation matrices: how big the change is. The monitor asks instead whether the span was constant. It flags againstcrit, 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 = rp.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").rheon.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.
Dtakes the five raw moments(x², y², x, y, xy)centered at their span means and their Bartlett long-run covariance at bandwidthL = floor(ln m)with the paper’s kernel, laglat weight1 - l/L(their Appendix A.1). It maps them to(var_x, var_y, cov)and then torho. It is computed on the span centered at its means and scaled by its standard deviations, as the paper’sxiseries, so the columns’ level does not enter. A pair within rounding of|rho| = 1has noDand no verdict, as a constant column has none.The monitor test. Under the null
Qconverges tosup|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 mostwindow_rowsrows 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, andtests/test_corrchange.pyholds 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.qis the1 - alphaquantile ofsup_{0 < s <= 1} |W(s)| / s ** boundary_gammafor a Brownian motionW(their Eq. 7), atalpha / npairsunder Bonferroni. Atboundary_gamma = 0it comes from that law’s series, 2.2414 at 5%, socritis 1.5849 atT = 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.critreplaces the value.On a flag,
since_changedates 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 reportstau - 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 asmandTgrow.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_gammaof 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_gammawhen
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
critthe critical value is a permutation quantile:n_permdraws of the pooled rows shuffled between the two windows, redrawn everypermute_every_rowsrows. A report flags when fewer thanfloor(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 then_perm + 1is uniform. So a test of a report against draws of its own windows has a size of that count overn_perm + 1, at mostalpha: 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 forpermute_every_rowsreports, so each later report is compared with draws of windows up topermute_every_rows - 1rows older than its own. Over 200 streams of iid rows at alpha 0.05 and 200 draws, with the value held forwindow_rowsreports (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 thanceil(1 / alpha) - 1draws could never flag, so such ann_permis 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 everyx 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:critis null there, and in force from the next row. Achange_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 notalphahere: 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_rowspooled rowsn_permtimes and reads both windows’ correlations each time, so it costsn_perm * window_rows * p**2forpfeatures. At the defaultpermute_every_rows(window_rows), a redraw comes once a window’s length of rows, that isn_perm * p**2a row, whatever the window, so the draws’ cost per row does not grow withwindow_rows. Each drawn value is held for thosewindow_rowsrows. A smallerpermute_every_rowsredraws more often, at more cost a row.