rheon.polars.stream.with_windows¶
- rheon.polars.stream.with_windows(lf: LazyFrame, *exprs: Expr, clock: str | None = None, gap_cap: float | timedelta | str | _Expr | None = None, restart_after_step_back: float | timedelta | str | _Expr | None = None, session: str | None = None, session_gap: float | timedelta | str | _Expr | None = None, group: str | None = None, like: dict[str, Any] | None = None, chunk_size: int | None = None, load_state: str | PathLike[str] | bytes | None = None, save_state: str | PathLike[str] | None = None, **named: Expr) LazyFrame[source]¶
- rheon.polars.stream.with_windows(lf: DataFrame, *exprs: Expr, clock: str | None = None, gap_cap: float | timedelta | str | _Expr | None = None, restart_after_step_back: float | timedelta | str | _Expr | None = None, session: str | None = None, session_gap: float | timedelta | str | _Expr | None = None, group: str | None = None, like: dict[str, Any] | None = None, chunk_size: int | None = None, load_state: str | PathLike[str] | bytes | None = None, save_state: str | PathLike[str] | None = None, **named: Expr) DataFrame
Add columns of formulas over the window operators, computed over a stream in one pass.
Use it, as you would Polars’
with_columns, for features or targets that look back or ahead over the stream’s clock, built from the operators ofrheon.polars.ops, with one window of rows in memory, never the whole stream. For a formula that reads only its own row, use Polars’with_columns. A spec also takes a formula over the operators as its target, computed inside the bank.Parameters
lfThe stream, a
LazyFrameor aDataFrame, in clock order across groups, as one stream.*exprsFormulas passed by position, each named by its
.alias().clockThe clock column. The default,
None, counts one unit a row.gap_capThe longest step of the clock between two rows of one stretch (the rows between two clock breaks): a longer step is a clock break, which ends every window open across it. Required with a clock. A number of clock units, or a duration on a temporal clock: text such as
"5m", atimedelta, or an expression that reads no column, such aspl.duration(minutes=5).restart_after_step_backBy default a step back of the clock is refused. If it is set, a step back larger than it resets every window, and one no larger is still refused. In the units
gap_captakes. Needsclock.sessionA column whose change of value ends every window open across it.
session_gap"reset", to discard the windows a session change leaves open rather than cut them. Needssession. A number or a duration is refused here, since no window reads it (Notes).groupA column whose every value has its own clock, sessions and windows. A window looking ahead under
groupneedsclock.likeA spec to take the clock settings from, all six above, in place of giving them. With them it takes the rule for the rows the spec learns from: a window looking ahead over a row the spec would skip is null (Notes). Default
None.chunk_sizeThe rows read at a time, at least 1. The default,
None, is the library’s default chunk size. It changes no output.load_stateThe path of a state this call saved, to go on from, or the state’s bytes, such as a stage
load_checkpoint()gives back. It is read when the query is built. DefaultNone: start with no state loaded.save_stateThe path of a file to save the state to once the input is fed, or the slice of the output is. Default
None: save nothing (Notes).**namedFormulas by keyword, each named by its keyword. The six clock keywords (
clocktogroup) are the call’s clock settings, not output names: to add a column namedsession, name its expression with.alias("session")and pass it by position.
A formula is element-wise Polars over the operators: columns, literals, arithmetic, negation, comparisons,
&and|,log,exp,abs,sqrt,pow,clip,fill_null,is_null,is_not_null,when/then/otherwise,castandalias. Each formula must hold at least one operator. Ashift, a cumulative or rolling function,overor an aggregation would depend on the chunking, and is refused by name when the query is built.Returns
The kind of frame it was given: the input’s columns, unchanged and in order, then a column for each formula. Rows leave in input order, each once every window over it has resolved. A row whose window has not passed when the input ends gives null, unless
save_statekeeps it for the next run.Raises
TypeErrorWhen the query is built: a value that is not an expression, an expression given to
clock,sessionorgroup, agap_cap,restart_after_step_backorsession_gapexpression that is not one duration reading no column, a keyword under its old name, or alikethat is not a spec.RefusedValueErrorA clock keyword given beside
like=. It is both aValueErrorand aTypeError.WrongTypeErrorWhen the query is built, a window operator’s input is not a number, or an increment’s is neither a number nor temporal; or a column, read or not, is
UInt128, which rheon cannot read (the message names a cast to make). It is both aTypeErrorand aValueError.ValueErrorWhen the query is built:
a formula, a clock policy or a column that cannot run, such as a window looking ahead under
groupwith noclock, orhalf_life=float("inf")with nowindow_sizefor a mean, a variance or a standard deviation;a formula that holds no window operator, or a formula by position that has no name of its own;
a
session_gapwithoutsession, or arestart_after_step_backwithoutclock, which would do nothing;an output name that collides, or
chunk_sizebelow 1;a
load_statethat another call saved.
And when the query runs: a step back of the clock, naming the row, or a state resumed on another input (Notes). Under py-polars 1.x these arrive inside Polars’
ComputeError, since the rows come from a Python source. Under 2.0 each is theValueErroritself.FileNotFoundErrorload_stateis not there, or the folder ofsave_stateis not.IsADirectoryErrorsave_stateis a folder, on every system. Aload_statethat is a folder raises it too on macOS and Linux, andPermissionErroron Windows, where opening a folder fails that way.OrderNotGuaranteedWarningA warning: the query before this call does not keep its rows in order, while a window is taken over rows in row order.
ConsumedSourceWarningA warning: a run that reads a source written in Python gave no rows, the shape of a stream that gives its rows once and was spent by an earlier run.
Examples
rows = pl.DataFrame({"t": [0.0, 1.0, 2.0, 5.0, 6.0], "x": [1.0, 2.0, 3.0, 4.0, 5.0]}) out = rp.stream.with_windows( rows, trend=pl.col("x") - rp.ewm_mean("x", half_life=1.0), # x above its trailing mean ahead=rp.ewm_sum("x", half_life=float("inf"), window_size=1.0, reverse=True), clock="t", gap_cap=2.0, # the gap from 2 to 5 is a clock break ) print(out["trend"].round(4).to_list()) # 0 at row 3: the windows start over print(out["ahead"].to_list()) # next unit's sum: null if cut, or open at the end
[0.0, 0.5, 0.75, 0.0, 0.5] [2.0, 3.0, None, None, None]
Over
trades, quotes with amidand trades between them with aside, aquantityand aprice, a trailing mean of the mid and forward VWAPs of all trades and of the buys. This code readstradesfrom Example data:notional = pl.col("price") * pl.col("quantity") buys = pl.when(pl.col("side") == "buy") ahead = {"half_life": "10s", "window_size": "1m", "reverse": True, "min_samples": 1} out = rp.stream.with_windows( trades, mid_trend=rp.ewm_mean("mid", half_life="5s", window_size="1m") - pl.col("mid"), fwd_vwap=rp.ewm_sum(notional, half_life="10s", window_size="1m", reverse=True) / rp.ewm_sum("quantity", half_life="10s", window_size="1m", reverse=True), fwd_buy_vwap=rp.ewm_sum(buys.then(notional), **ahead) / rp.ewm_sum(buys.then("quantity"), **ahead), clock="ts", gap_cap="5m", group="symbol", ) print(out.height, out.columns[-3:], out["fwd_vwap"].count())
3000 ['mid_trend', 'fwd_vwap', 'fwd_buy_vwap'] 2890
See also
rheon.polars.ops, the operators, and the tables ofclosedandpartial.lf.rheon.with_windowsanddf.rheon.with_windows, the same call on a frame’srheonnamespace.Make features that look back over the stream, Make a target that looks ahead and Resume a window run, the guides.
Notes
The operators are stateful kernels the core computes, each distinct one once. The formula around them is element-wise Polars, evaluated on each chunk the call emits. The formula is kept as a compact tree of the library’s own, in the query and in a saved state, so a state saved under one Polars version loads under another: Polars’ own serialized form of an expression changes between versions.
The clock. A window is measured on the clock with each step capped at
gap_cap. A gap longer thangap_capor a session change ends every window open across it, under each operator’spartial. A reset discards them: each gives null, and its row stays in the output. Only a window looking ahead is still open at a session change, sosession_gap="reset"changes those windows and nothing else. Since every window ends at a session change, no window measures the clock’s step across one, and the number a spec takes there would change nothing. So a session needs nosession_gaphere. A window looking ahead underclosed="right"or"both"whose far edge is the last row before a cut or a reset holds every row it covers, so it is whole, and gives its value under anypartial.The clock is also read in input order, under the same settings. So a step back there is refused or, past
restart_after_step_back, resets every group, and a gap there ends every group’s windows. Withgroupa session is each group’s, read on its own clock, so a clock that starts over with a session is a step back on the stream’s. Withoutgroupthe stream is the one group. A group silent pastgap_capis cut as the stream’s clock passes the cap, before its next row can say its session changed, so asession_gap="reset"there discards only what is still open.Under
like=spec, a window looking ahead over a row the spec would skip is null, as the model never learns its target. The spec skips a row whose feature or weight it cannot use: null, NaN, infinite or past1e100in magnitude, each of which counts as null.The rows’ order and memory. A backward window under
closed="right"or"both"waits for the next distinct stamp (a clock value), and a look-ahead for its window to pass, so the output trails the input by one clock step for a backward window and by the longest window for a look-ahead. A group that falls silent holds every later row for at mostgap_capof the stream’s time. Past that its next row is certain to open with a gap past the cap, so its windows end then. Only a clock column has a cap, so a look-ahead undergroupneeds one, and is refused without it: each group’s clock would count only its own rows, and a silent group would hold every later row to the end of the input. The rows a look-ahead holds are kept as the input’s own chunks, not copied, so the memory is one window of input whatever its width. The kernels’ own sums are one window of the rows that count in them.It resumes.
save_statewrites the kernels’ sums and the rows still waiting, which the next run, givenload_state, emits first. Feeding a stream in two runs gives what one run gives. Any resumed run refuses by name an input whose first row is at the last stamp the state read, unless that row starts a new session. A file boundary inside a tied stamp cannot be told from an input that repeats rows the state read, which would come out twice. So cut a stream into files between stamps. Without a clock column there is no stamp to compare, and a repeated row is not caught.A state one release saves loads in every later release, as a bank’s does, the formula tree it holds included: its file names its version, and each later layout ships a loader for the one before.
Under a slice of the output (
.head(n)) the input is read only up to the row that resolved the n-th row, and the state records how many rows of the input were consumed so far. A run resumed withload_stateon the same input, unsliced, skips those rows and goes on. So any chain of sliced runs gives what one run gives, whatever the chunk size. Such a state knows its input by its first row’s clock and session, and by the last rows it read: the rows it holds that are the input’s, or the last row alone where it holds none. An input whose first row differs is the next file when the clock settings take that row as a step forward or a new start, which is a step back pastrestart_after_step_backor a new session. The run then skips nothing and first returns the rows the state held. Besides the input at the last stamp read, a state saved under a slice refuses by name:an input that steps back where the clock settings refuse it: the same input sliced by hand, or an overlapping file (a hand slice that starts after the last clock read is taken as the next file);
without a clock column, an input that does not begin with a new session;
an input that starts as the saved input did but differs where the state was cut, and one shorter than the rows consumed.
A clock that starts over at the same stamp each day needs a session column for the next day’s file to differ from the saved input at its first row. Without a clock column a row-count clock steps forward at every row. So the next file is one that begins with a new session (under
group, a new session of a group the state has read), and not with the saved input’s first session, which marks the saved input itself. Without a session column either, there is no next file: resume on the same input. An input whose rows match the state’s where it was cut is taken as the same input, so resume a stream whose rows can repeat (a daily grid with the same values) on the same input only. A state resumes only the call that saved it, on the same kind of clock.