polars_online.sim.regimes¶
- polars_online.sim.regimes(m: int, *, states: Sequence[Any], transition: Any, n_blocks: int, rows_per_block: int, durations: Sequence[int] | None = None, design: str = 'step', smooth_rows: int = 0, phi: float | Sequence[float] = 0.0, scale_state: float | Sequence[float] = 0.0, async_rates: Sequence[float] | None = None, noise: float = 0.0, cycle_profile: Sequence[float] | None = None, cycle_rows: int | None = None, activity: tuple[float, float] | None = None, seed: int = 0) dict[str, DataFrame][source]¶
Simulate a stream of
mseries whose correlation changes by regime, with its truth.Use it to measure a detector of changing correlation, such as
deco,hmm,corrchangeorbocpd, against data whose regimes are known. For a stream with a planted relation to a target, build the frame with numpy, as Example data does.Parameters
mThe number of series, at least 2.
statesThe
Kregimes’ correlations:Kcorrelation matrices (m x m, unit diagonal, positive semi-definite), orKfloats, each an equicorrelation, the one correlation of every pair.transitionThe
K x Kmatrix of probabilities, each row summing to 1, that draws the state of each block from the block before it.n_blocks,rows_per_blockThe number of blocks, and the rows in each, each at least 1. A block holds one state.
durationsOne block count of at least 1 per state. Given, each state lasts exactly that many blocks, and the next state is drawn from
transitionwith its diagonal removed: the recurring-state design. DefaultNone: each block’s state is drawn fromtransition.design,smooth_rows"step"(the default) switches at the block boundary."smooth"moves the correlation matrix linearly oversmooth_rowsrows centered on the boundary: rowtfollows(1 - mix) R_before + mix R_after, the states of the blocks before and after the boundary, on both sides of it.smooth_rowsdefaults to 0, which switches at the boundary as"step"does.phiThe coefficient of each series’ AR(1) filter, one number for all or one per series, each above -1 and below 1. Default 0: no filter.
scale_stateThe returns’ scale per state, as the exponent of its multiplier, with
s_tthe row’s state index. One number gives the multiplierexp(scale_state * s_t), so a positive number makes the scale rise with the state index. A list gives one exponent per state, and the multiplierexp(scale_state[s_t]). Default 0: one scale.async_ratesThe expected reports per row of each series, each above 0, one per series. A row where series
ireported nothing carries null forx_i. DefaultNone: every series reports on every row.noiseThe standard deviation of the noise added to each observed level. Default 0: none.
cycle_profile,cycle_rowscycle_rowsmultipliers, each above 0 and at most 1, applied to the off-diagonal ofR_tat rowt mod cycle_rows: a mix toward the identity, so the matrix stays positive semi-definite.cycle_rowsdefaults torows_per_block, and setssession = t // cycle_rows. DefaultNone: no cycle.activity(mean, shape), both above 0, for a Gamma-distributed activity per row whose mean is scaled by the row’s scale multiplier.clockis then the cumulative activity. DefaultNone:clockis the row index.seedThe seed of
numpy.random.default_rng. Default 0.
Returns
A
dictof three frames,"rows","truth_rows"and"truth_blocks":rowsWhat a consumer sees:
entity, the constant"sim";t, the row index;clock;session,t // cycle_rows(the block index unlesscycle_rowsis given); the levelsx_1 .. x_m(null where a series did not report); andactivity(null withoutactivity).truth_rowsPer row:
t,block,state,scale_multandmix, the weight of the later block’s state in the row’s blend: 0 away from a boundary, rising to 1 across it.truth_blocksPer block:
block,state,n_rows, andcorr, the block’s true correlation matrix asvech, its upper triangle with the diagonal, row by row. That matrix is the mean over the block’s rows of the states’ matrices, beforecycle_profilemixes them toward the identity.
Raises
ValueErrorWhen:
mis below 2, orn_blocksorrows_per_blockis below 1;a state is not a correlation matrix of
mseries, or an equicorrelation is not above-1 / (m - 1)and below 1;transitionis notK x K, or a row is not probabilities that sum to 1, ordurationsdoes not give one count of at least 1 per state;designis neither"step"nor"smooth";a
phiis not above -1 and below 1, or aphiorscale_statelist has the wrong length;cycle_rowsis below 1, orcycle_profilehas the wrong length or a multiplier not above 0 and at most 1;activityis not two numbers above 0, orasync_ratesis notmrates above 0.
ModuleNotFoundErrornumpy is not installed.
UnstableWarningA warning, under
POLARS_ONLINE_WARN_UNSTABLE=1, on each call.
Examples
sim = po.sim.regimes( 3, states=[0.2, 0.7], transition=[[0.9, 0.1], [0.1, 0.9]], n_blocks=4, rows_per_block=50, phi=0.3, seed=1, ) rows, truth = sim["rows"], sim["truth_blocks"] print(rows.height, truth["state"].to_list()) # a state per block print([round(c[1], 2) for c in truth["corr"].to_list()]) # true corr(x_1, x_2)
200 [0, 0, 1, 1] [0.2, 0.2, 0.7, 0.7]
See also
po.spec.deco,po.spec.hmm,po.spec.corrchangeandpo.spec.bocpd, the detectors it is made to measure.polars_online.stream.refresh_time(), to put the series on a refresh grid: underasync_rates, unpivotrowsto long form and drop the nulls to feed it.
Notes
The latent returns are
eps_t ~ N(0, R_t), filtered toy_it = phi_i y_i,t-1 + eps_itand scaled byexp(scale_state * s_t)(exp(scale_state[s_t])for a list). The observed series are their levels, the cumulative sums, plus noise. The truth it reports is the innovation correlation: an AR filter moves the return correlation of a pair with unequalphi, which is whatpolars_online.corr.fisher_se()’s inflation is about.A convex combination of two correlation matrices is one, so every matrix along a
"smooth"boundary is valid. Noise on the level is what the literature models, and it makes the observed return an MA(1) with a negative first autocorrelation, the microstructure effectrcovexists to undo. Underasync_rates, last-observation sampling is oneforward_fillaway.Everything is drawn from
numpy.random.default_rng(seed)in one order, so two calls with the same seed give byte-identical frames under one numpy version. numpy’sGeneratormakes no promise across versions.