rheon.polars.stream.refresh_time

rheon.polars.stream.refresh_time(lf: pl.LazyFrame, *, series: str, names: Sequence[str], clock: str, value: str, group: str | None = None, pairs: bool = False, keep: Sequence[str] = (), chunk_size: int | None = None, load_state: State | bytes | None = None, save_state: State | None = None) → pl.LazyFrame[source]
rheon.polars.stream.refresh_time(lf: pl.DataFrame, *, series: str, names: Sequence[str], clock: str, value: str, group: str | None = None, pairs: bool = False, keep: Sequence[str] = (), chunk_size: int | None = None, load_state: State | bytes | None = None, save_state: State | None = None) → pl.DataFrame

Put series that tick at their own times on a common grid of refresh times.

Use it before a correlation or a covariance model, such as rcov or ew_cov, over series observed at their own times. A correlation over a fine grid of such series is pulled toward 0 (the Epps effect), and filling each series forward invents observations. For series already observed at the same times, a wide frame needs no grid.

Parameters

lf

The ticks, a LazyFrame or a DataFrame, in long form: one row per tick, with a series column naming it, a clock and a value. lf.unpivot(index=[clock], variable_name="series", value_name="value") makes the long form from a wide one. Rows must be in clock order within each group, as a stream must be.

series

The column that names each tick’s series.

names

The series, at least two and each once, in the order of the output columns. It is required, not discovered from the data, because a lazy query declares its schema before a row is read, and the output columns are named after the series. A row whose series is not in names is refused, naming it, since dropping it would hide a misspelling.

clock

The clock column: numeric or temporal (a Boolean and a column of nulls count as numbers). A temporal clock is compared exactly, in integer nanoseconds.

value

The column of the ticks’ values, numeric (a Boolean and a column of nulls count as numbers). A value that is null, NaN, infinite or past 1e100 in magnitude is missing, the rule every spec column follows: the tick observed nothing, so it does not update its series.

group

A column whose every value gets a grid of its own, such as a trading day. Default None: one grid.

pairs

True runs an independent grid of two series for each unordered pair, which keeps far more of the data when one series is slow. Default False: one grid of every series. With two names the one pair’s grid is the joint grid.

keep

Columns to carry to the output, at their value on the tick that completes each grid point. 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 refresh_time() 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. It must have been saved with the same names and pairs, on the same kind of clock (a temporal state resumes on any unit). Default None: start with no state loaded.

save_state

The path of a file to save the state to once the input is fed. Default None: save nothing (Notes).

Returns

The kind of frame it was given, with one row per grid point:

time_refresh

The clock of the tick that completed the point: the latest, over the series, of their last update (the paper’s Definition 1).

<s>_value

Each series’ last value at that instant.

n_obs_<s>

The ticks of s since the previous point. The grid keeps the last of them, the series’ value at the refresh time.

retained_fraction

m / sum(n_obs), with m the number of series: the share of the interval’s ticks the grid kept. Read it before trusting a correlation computed on the result.

The group column comes first, in the dtype it came in as, and the keep columns last. Under pairs=True it is one long frame of the columns group (with a group), pair, time_refresh, a_value, b_value, n_obs_a, n_obs_b, retained_fraction and the keep columns, with pair = "a|b" and a the pair’s series listed first in names. Each group runs its own pairs.

Raises

ColumnNotFoundError

The frame has no series, clock, value, group or keep column of that name. It is both a ValueError and Polars’ ColumnNotFoundError.

WrongTypeError

The clock column is neither numeric nor temporal (a Boolean and a column of nulls are numbers), is an Int128, wider than the Int64 an integer clock is held in, or is a Time, which starts again at midnight; the value column is not numeric; 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:

  • names lists fewer than two series, or one twice;

  • chunk_size is below 1, or is not a whole number, which raises WrongTypeError;

  • load_state is not such a state, or was saved with other names or pairs, or on the other kind of clock (numeric or temporal), or with a group where this call has none, or the reverse;

  • when the query runs, a row’s series is not in names, or a clock steps below the previous row’s in its group, the row named, as a spec refuses one with restart_after_step_back unset. A row before its group’s saved clock is refused the same way. Under py-polars 1.x the error arrives inside Polars’ ComputeError, since the grid runs as a Polars source, for a DataFrame too. Under 2.0 it is the ValueError itself.

TypeError

A keyword under its old name, such as chunk_rows.

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.

Examples

ticks = pl.DataFrame({              # one row per tick, each series at its own times
    "symbol": ["AAA", "BBB", "AAA", "CCC", "BBB", "AAA", "AAA", "CCC"],
    "t": [0.4, 0.9, 1.3, 1.6, 2.2, 2.5, 2.8, 3.1],
    "px": [100.0, 20.0, 100.2, 50.0, 20.1, 100.1, 100.4, 49.9],
})
grid = rp.stream.refresh_time(      # a DataFrame in, a DataFrame out
    ticks, series="symbol", names=["AAA", "BBB", "CCC"], clock="t", value="px"
)
for row in grid.rows():             # each point: CCC's tick completes it
    print(row)
returns = grid.select(pl.col("^.*_value$").diff())   # what rcov and ew_cov take
(1.6, 100.2, 20.0, 50.0, 2, 1, 1, 0.75)
(3.1, 100.4, 20.1, 49.9, 2, 1, 1, 0.75)

See also

Notes

The grid is Barndorff-Nielsen, Hansen, Lunde & Shephard’s refresh-time rule. A grid point is the first instant by which every series has ticked at least once since the previous point, and each series’ last value there is taken:

tau_0     = max_i (first tick of series i)
tau_{j+1} = max_i (first tick of series i strictly after tau_j)

Nothing is interpolated, every value in the output was observed, and the grid adapts to the slowest series rather than carry a stale value across an interval.

The staleness caveat (their section 2.1): the output looks synchronous and is not. A refresh vector is treated as observed at time_refresh, but each series’ value is up to one of its own inter-tick intervals old. n_obs_<s> counts the ticks of each series the point folded in, of which it kept one. A large count is ticks the grid dropped, and the series holding the grid up, the one whose tick completes each point, sits near 1.

Ties are broken by row order: “strictly after tau_j” is read against the row sequence. So a tick carrying the same clock value as the one that just closed a point, but later in the frame, belongs to the next interval. That lets a point be emitted the moment its last series ticks, which makes the result chunk-invariant: feeding the input in one chunk or a thousand gives the same grid, since a point is a property of the ticks up to it. Sort the input by clock, and by the order you want within a clock value.

It resumes. save_state writes the grid’s state once the input is fed: every group’s grid, part-way through an interval or not, and its last clock. The state is written in full or not at all. Under a slice of the output (.head(n)), the input is read up to the tick that completed the last point returned and no further. So the state saved is the state after that tick, whatever the chunk size, as a bank’s is after the rows a head(n) pulled. A run resumed on the input after that tick goes on with the next point. With pairs=True one tick can complete several pairs’ points at once. If the slice ends among them, the state holds the tick’s points the slice left out, and a run resumed on the input after that tick returns them first. The slice and the resumed run together give the one run’s grid, wherever the slice ends. load_state goes on from where its run stopped, so feeding a stream in two runs gives the grid one run gives.