polars_online.ops.ewm_quantile

polars_online.ops.ewm_quantile(input: str | pl.Expr, *, quantile: float, half_life: float | Duration, window_size: float | Duration | None = None, closed: Literal['right', 'left', 'both', 'none'] = 'right', min_samples: int = 1, partial: Literal['keep', 'null', 'drop'] | None = None, reverse: bool = False) → pl.Expr[source]

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

Use it for a level that one wild row does not move, such as a median, or for a robust scale (Notes). For a mean, use ewm_mean(), and for a standard deviation, ewm_std().

Parameters

input

The values the window reads: a column name, or an element-wise expression of the row, such as pl.col("price") * pl.col("quantity") or increment(). It may hold no other window operator.

quantile

The level of the quantile, above 0 and below 1, such as 0.5 for the median. Required.

half_life

How fast a row’s weight fades with its distance in clock time from the row the window is read at: a row half_life away weighs half as much. A number of clock units on a numeric clock, or a duration ("10s", a timedelta, pl.duration(seconds=10)) on a temporal one. Required. float("inf") weighs every row of the window evenly.

window_size

The span of clock time a window covers, in the same units as half_life. The default, None, covers every row since the last clock break (a gap past gap_cap or a session change), decayed. Required under reverse=True, since the rows after a row have no end without it.

closed

Which ends of the window are in: "right" (the default, as in Polars’ rolling_*_by), "left", "both" or "none". The module’s table of closed (polars_online.ops) gives each end, looking back and ahead.

min_samples

The fewest rows with a value a window must hold to give a value, as in Polars’ rolling functions. Default 1. An integer from 1 to 2**32 - 1.

partial

What a window cut short gives: one that a gap past gap_cap, a session change or the stream’s start cuts before its full span. "keep" gives the value over what it saw, "null" gives null, and "drop" removes the row from the output. None (the default) means "keep" looking back and "null" looking ahead. It needs window_size, since without one no window is cut short.

reverse

True reads the rows after each row, at most window_size later, in place of the rows at or before it, as Polars’ cum_sum(reverse=True) runs from the end. As a spec’s target, a window looking ahead is known only once it has closed, so the bank learns it under an embargo of at least window_size. Default False.

Returns

A pl.Expr that polars_online.stream.with_windows() computes as a column, or that a spec takes as its target. Its value is null where the window holds fewer than min_samples rows with a value. It is null too where partial="null" meets a cut window, where a forward window is still open at the input’s end, and after a reset (the module’s partial table). At a row whose value is missing, it gives the window as it stands.

Raises

TypeError

When:

  • input is neither a column name nor a pl.Expr;

  • half_life or window_size is neither a number nor a duration (text such as "10s", a timedelta or pl.duration);

  • min_samples is not an integer (a WrongTypeError, also a ValueError);

  • reverse is not True or False;

  • quantile is not a number.

ValueError

When:

  • half_life is NaN or not above 0, or window_size is NaN, infinite or not above 0;

  • half_life or window_size is text that is not a duration, such as "abc";

  • closed or partial is a word it does not know, or partial is given without window_size;

  • min_samples is below 1 or above 2**32 - 1;

  • quantile is not above 0 and below 1;

  • input holds another window operator, a part that is not element-wise, or a column whose name starts with @po:, the prefix the operators’ own columns carry.

RefusedValueError

reverse=True without window_size. It is both a ValueError and a TypeError.

polars_online.stream.with_windows() refuses the rest when it builds its query, such as a window looking ahead under group with no clock column.

Examples

rows = pl.DataFrame({"t": [0.0, 1.0, 2.0, 3.0, 4.0], "x": [1.0, 2.0, 3.0, 4.0, 5.0]})
# The median of the last 3 units, weighed evenly.
med = po.ewm_quantile("x", quantile=0.5, half_life=float("inf"), window_size=3.0)
out = po.stream.with_windows(rows, med=med, clock="t", gap_cap=10.0)
print(out["med"].round(3).to_list())   # within 0.78% of the exact medians 1, 1, 2, 3, 4
[1.008, 1.008, 2.016, 3.016, 4.031]

See also

Notes

Each row of the window with a value counts once, at its own time, with the weight ewm_sum() gives it, w_j = lam ** |t_j - tau_t|, lam = 2 ** (-1 / half_life). The quantile at q is the smallest x with W(<= x) >= q W, where W(<= x) is the weight of the values at or below x and W the weight of all of them. That is numpy’s inverted_cdf quantile over the window’s values and weights.

A value is read as the bucket it falls in, each bucket spanning a ratio of at most e ** (1/64). So the result is within tanh(1/128), 0.78%, of the exact quantile, relatively, at any scale and either sign. A magnitude below the smallest normal double counts as 0. A row whose value is missing counts for nothing and gives the window as it stands, as the sums do.

A robust scale. The median of |r| is the median absolute deviation of r about 0. Divided by Φ⁻¹(3/4) = 0.6744897501960817, it estimates a standard deviation for normal r, and holds while up to half the window is wild, where a root mean square is moved by one row. For a residual, which the fit centers on 0:

mad = po.ewm_quantile(pl.col("resid").abs(), quantile=0.5, half_life=500)
scale = mad / 0.6744897501960817

closed="left" leaves the row’s own value out of its window. So a scale of a target, used as a weight on the same row, does not see the target it weighs.