rheon.polars.ops

The window operators: exponentially weighted (EW) means, sums, rates and quantiles over a stream’s clock, looking back or ahead, and a variance and a standard deviation looking back. increment, the step of a running total, gives a window operator an input.

Each operator returns a pl.Expr that composes with Polars’ own expressions, in which pl.col reads the current row. rheon.polars.stream.with_windows() computes the expressions in one pass, holding one window of rows in memory, or a spec takes one as its target. A target that looks ahead is known only once its window has closed, so the bank learns it then, under an embargo (rheon.spec) of at least the window. The guide How a window operator weighs the rows near each row explains each.

Every operator is defined once, by the library that has it, and held to it in the tests. A stamp is a clock value, which several rows may share. A clock break is a gap past gap_cap or a session change, and a stretch is the rows between two clock breaks. tau_t is row t’s clock with each step capped at gap_cap, and lam = 2 ** (-1 / half_life):

operator

defined as

held to

ewm_mean()

the time-weighted mean: row i’s value is held over (t_{i-1}, t_i], a stretch’s first value is held from before the stretch begins, and the mean over (tau_t - w, tau_t] weighs each held value by integral lam**(tau_t - s) ds over its interval inside the window

Polars’ ewm_mean_by. A burst of rows does not outweigh a quiet stretch, and a row at a repeated stamp holds no interval, so it moves no mean. No operator offers a mean that weighs each row by its count, the form pandas’ ewm(times=) computes

ewm_mean() with reverse=True

the mirror: value j is held over [t_j, t_{j+1}), until the next row, and weighed by integral lam**(s - tau_t) ds inside (tau_t, tau_t + w]

the reversed stream’s ewm_mean()

ewm_sum(), and with reverse=True

sum lam**|t_j - tau_t| * x_j over the rows of the window, each counted once at its own time

Polars’ ewm_sum_by on distinct stamps. At a repeated stamp every row holds the stamp’s whole window, so each carries the stamp’s total, where ewm_sum_by’s is a running sum

ewm_rate(), and with reverse=True

the sum over the decayed time the window covers, integral_0^T lam**s ds = half_life / ln 2 * (1 - 2 ** (-T / half_life)), T the window’s span inside the stretch: a quantity per unit time

the sum and the mass, each as above

ewm_var(), ewm_std()

the variance about ewm_mean(), each value under the mean’s weight m_i: sum m_i (x_i - mu) ** 2 / V1, V1 = sum m_i. Unless bias, it is multiplied by V1 ** 2 / (V1 ** 2 - V2), V2 = sum m_i ** 2. ewm_std() is its root. Looking back only

Polars’ ewm_var and ewm_std under adjust=False on a clock that steps by 1 a row and an input with no nulls, with Polars’ own correction for unequal weights

ewm_quantile()

the smallest x with W(<= x) >= q W, each row of the window weighing lam**|t_j - tau_t|, as in ewm_sum(), W their total. It is read from buckets each spanning a ratio of at most e**(1/64), so it is within tanh(1/128), 0.78%, of the exact quantile, relatively

numpy’s inverted_cdf quantile over the window’s values and their weights

increment()

x_i - x_{i-1} within the group and session, null on a session’s first row, and in seconds on a temporal column

the row before it

Which rows a window holds follows Polars’ rolling windows (rolling_*_by). A window is a set of timestamps, and closed says which ends are in. Every row at one stamp gets the same backward window, later rows at that stamp included, and looking ahead the mirror holds:

closed

looking back

looking ahead

"right" (the default)

(tau_t - w, tau_t]: the stamp’s own rows are in, so the output waits for the next distinct stamp

(tau_t, tau_t + w]: no row at the stamp is in, and a row exactly w later is

"left"

[tau_t - w, tau_t): the stamp’s own rows are outside, and the output is known as the stamp arrives

[tau_t, tau_t + w): every row at the row’s own stamp is in, the row itself included

"both"

both ends in, so the output waits for the next stamp

both ends in: the stamp’s rows, and a row exactly w later

"none"

neither end, so the output is known as the stamp arrives

neither end

An edge between two rows is decided from the difference of their clocks, exact in nanoseconds on a temporal clock, as Polars decides it, at any age of the stream. min_samples (Polars’ name) nulls a window holding fewer rows with a value. A value that is NaN, infinite or beyond 1e100 in magnitude is read as missing, as a null is. Every model reads its inputs within that bound, since a weight of 1e100 times a square of 1e100 is 1e300, still inside a double’s range. At a row whose value is missing the operator gives the window as it stands, where Polars’ ewm_mean_by gives null. A row is in a window by its stamp, but a mean weighs it by its held interval inside the window. So under "left" or "both", a row exactly one window old counts for min_samples and weighs nothing, since its interval ends at its row. A mean with no other value in the window is null, where a sum’s default min_samples=0 gives 0.0, as Polars’ rolling_sum_by does.

A weighted mean is a ratio of two sums. A volume-weighted average price (VWAP) is decayed notional over decayed volume, and the time mass cancels. For one side’s VWAP, put when/then inside both sums, with min_samples=1 in both: a window with no such trade is then null, where a sum of nothing is 0.0 and its ratio NaN. The operators take no weight=. This code reads trades from Example data:

notional = pl.col("price") * pl.col("quantity")
buys = pl.when(pl.col("side") == "buy")
out = rp.stream.with_windows(
    trades,
    mid_trend=rp.ewm_mean("mid", half_life="5s", window_size="1m") - pl.col("mid"),
    fwd_vwap_vs_mid=rp.ewm_sum(notional, half_life="10s", window_size="1m", reverse=True)
                    / rp.ewm_sum("quantity", half_life="10s", window_size="1m", reverse=True)
                    - pl.col("mid"),
    buy_vwap=rp.ewm_sum(buys.then(notional), half_life="10s", min_samples=1)
             / rp.ewm_sum(buys.then("quantity"), half_life="10s", min_samples=1),
    clock="ts", gap_cap="5m", group="symbol",
)

A feature in units of its spread is a deviation over an operator. (x - ewm_mean(x)) / ewm_std(x) is the feature’s z-score. A model fitted on it has a coefficient per standard deviation of the feature, as the spread stands on each row, where a model on x has one per unit. Where a target responds to a feature relative to its volatility, fit on the z-score. Every model reads it as a column. Scale a feature by its spread gives the measured gain. This code reads trades.parquet from Example data:

spread = {"half_life": "30m"}
z_mid = (pl.col("mid") - rp.ewm_mean("mid", **spread)) / rp.ewm_std("mid", **spread)
zscored = pl.scan_parquet("trades.parquet").rheon.with_windows(
    z_mid=z_mid, clock="ts", gap_cap="5m", group="symbol"
).collect()

The clock settings are given to the call, and every operator in it shares them: clock, gap_cap, restart_after_step_back, session, session_gap and group, in a spec’s own words (rheon.spec). They differ from a spec’s in one way: a session needs no session_gap, since no window measures the clock’s step across a session change. A number given for it changes nothing, and only "reset" acts. A gap past gap_cap or a session change ends every window open across it, and partial says what such a window gives. A backward window whose span reaches before its stretch’s first row is partial too, the stream’s own start included. So partial also says what every stream’s first window_size gives:

partial

the window gives

the default

"keep"

the value over what it saw, the window ending at the last row seen

looking back

"null"

null

looking ahead

"drop"

the row leaves the output

A reset discards a window: it gives null, and the row is never dropped. Under session_gap="reset" a session change is a reset, so it discards the windows rather than cuts them. A forward window under closed="right" or "both" whose far edge is the last row before a cut or a reset is whole: every row it covers has arrived, so it gives its value. A forward window still open when the input ends is null. Under group a forward window needs a clock column, since only a clock ends the windows of a group that falls silent. partial needs a window_size: without one no window is cut short, so partial alone is refused.

An operator’s input is a column name or an element-wise expression of the row, increment() included, and never another window operator. For a formula over an operator’s output, add the inner operator as a column with one call, and pass that column to a second. half_life and window_size are in the clock’s units: numbers on a numeric clock, and durations ("10s", a timedelta, pl.duration) on a temporal one. half_life=float("inf") weighs the window evenly, and needs a window_size for a mean, a variance or a standard deviation.

An operator checks its own arguments when it is called, and names the one it refuses. Each operator’s Raises lists them. rheon.polars.stream.with_windows() refuses the rest when it builds its query: half_life=float("inf") with no window_size for a mean, a variance or a standard deviation, and a window looking ahead under group with no clock column.

Window operators

Polars expressions over a stream’s clock that look back or ahead.

rheon.polars.ops.ewm_mean

The time-weighted EW mean of a column over each row’s window.

rheon.polars.ops.ewm_sum

The EW sum of a column over each row’s window.

rheon.polars.ops.ewm_var

The EW variance of a column about its time-weighted mean, over each row’s window.

rheon.polars.ops.ewm_std

The EW standard deviation of a column, the square root of ewm_var().

rheon.polars.ops.ewm_quantile

The EW quantile of a column over each row’s window.

rheon.polars.ops.ewm_rate

The EW sum of a column per unit of clock time over each row’s window.

rheon.polars.ops.increment

The step of a column from its last value within the group and session.