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 of rheon.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

lf

The stream, a LazyFrame or a DataFrame, in clock order across groups, as one stream.

*exprs

Formulas passed by position, each named by its .alias().

clock

The clock column. The default, None, counts one unit a row.

gap_cap

The 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", a timedelta, or an expression that reads no column, such as pl.duration(minutes=5).

restart_after_step_back

By 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_cap takes. Needs clock.

session

A 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. Needs session. A number or a duration is refused here, since no window reads it (Notes).

group

A column whose every value has its own clock, sessions and windows. A window looking ahead under group needs clock.

like

A 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_size

The rows read at a time, at least 1. The default, None, is the library’s default chunk size. It changes no output.

load_state

The 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. Default None: start with no state loaded.

save_state

The 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).

**named

Formulas by keyword, each named by its keyword. The six clock keywords (clock to group) are the call’s clock settings, not output names: to add a column named session, 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, cast and alias. Each formula must hold at least one operator. A shift, a cumulative or rolling function, over or 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_state keeps it for the next run.

Raises

TypeError

When the query is built: a value that is not an expression, an expression given to clock, session or group, a gap_cap, restart_after_step_back or session_gap expression that is not one duration reading no column, a keyword under its old name, or a like that is not a spec.

RefusedValueError

A clock keyword given beside like=. It is both a ValueError and a TypeError.

WrongTypeError

When 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 a TypeError and a ValueError.

ValueError

When the query is built:

  • a formula, a clock policy or a column that cannot run, such as a window looking ahead under group with no clock, or half_life=float("inf") with no window_size for 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_gap without session, or a restart_after_step_back without clock, which would do nothing;

  • an output name that collides, or chunk_size below 1;

  • a load_state that 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 the ValueError itself.

FileNotFoundError

load_state is not there, or the folder of save_state is not.

IsADirectoryError

save_state is a folder, on every system. A load_state that is a folder raises it too on macOS and Linux, and PermissionError on Windows, where opening a folder fails that way.

OrderNotGuaranteedWarning

A warning: the query before this call does not keep its rows in order, while a window is taken over rows in row order.

ConsumedSourceWarning

A 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 a mid and trades between them with a side, a quantity and a price, a trailing mean of the mid and forward VWAPs of all trades and of the buys. This code reads trades from 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

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 than gap_cap or a session change ends every window open across it, under each operator’s partial. 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, so session_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 no session_gap here. A window looking ahead under closed="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 any partial.

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. With group a 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. Without group the stream is the one group. A group silent past gap_cap is cut as the stream’s clock passes the cap, before its next row can say its session changed, so a session_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 past 1e100 in 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 most gap_cap of 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 under group needs 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_state writes the kernels’ sums and the rows still waiting, which the next run, given load_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 with load_state on 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 past restart_after_step_back or 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.