polars_online.stream.refresh_time¶
- polars_online.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 | None = None, save_state: State | None = None) pl.LazyFrame[source]¶
- polars_online.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 | 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
rcovorew_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
lfThe ticks, a
LazyFrameor aDataFrame, in long form: one row per tick, with aseriescolumn naming it, aclockand avalue.lf.unpivot(index=[clock], variable_name="series", value_name="value")makes the long form from a wide one. Rows must be inclockorder within eachgroup, as a stream must be.seriesThe column that names each tick’s series.
namesThe 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
seriesis not innamesis refused, naming it, since dropping it would hide a misspelling.clockThe clock column: numeric or temporal (a Boolean and a column of nulls count as numbers). A temporal clock is compared exactly, in integer nanoseconds.
valueThe 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.
groupA column whose every value gets a grid of its own, such as a trading day. Default
None: one grid.pairsTrueruns an independent grid of two series for each unordered pair, which keeps far more of the data when one series is slow. DefaultFalse: one grid of every series. With twonamesthe one pair’s grid is the joint grid.keepColumns to carry to the output, at their value on the tick that completes each grid point. 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
refresh_time()saved, to go on from. It is read when the query is built. It must have been saved with the samenamesandpairs, on the same kind of clock (a temporal state resumes on any unit). DefaultNone: start with no state loaded.save_stateThe 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_refreshThe clock of the tick that completed the point: the latest, over the series, of their last update (the paper’s Definition 1).
<s>_valueEach series’ last value at that instant.
n_obs_<s>The ticks of
ssince the previous point. The grid keeps the last of them, the series’ value at the refresh time.retained_fractionm / sum(n_obs), withmthe number of series: the share of the interval’s ticks the grid kept. Read it before trusting a correlation computed on the result.
The
groupcolumn comes first, in the dtype it came in as, and thekeepcolumns last. Underpairs=Trueit is one long frame of the columnsgroup(with a group),pair,time_refresh,a_value,b_value,n_obs_a,n_obs_b,retained_fractionand thekeepcolumns, withpair = "a|b"andathe pair’s series listed first innames. Each group runs its own pairs.Raises
ColumnNotFoundErrorThe frame has no
series,clock,value,grouporkeepcolumn of that name. It is both aValueErrorand Polars’ColumnNotFoundError.WrongTypeErrorThe
clockcolumn is neither numeric nor temporal (a Boolean and a column of nulls are numbers), is anInt128, wider than theInt64an integer clock is held in, or is aTime, which starts again at midnight; thevaluecolumn is not numeric; or a column, read or not, isUInt128, which polars-online cannot read (the message names a cast to make). It is both aTypeErrorand aValueError.ValueErrorWhen:
nameslists fewer than two series, or one twice;chunk_sizeis below 1, or is not a whole number, which raisesWrongTypeError;load_stateis not such a state, or was saved with othernamesorpairs, or on the other kind of clock (numeric or temporal), or with agroupwhere this call has none, or the reverse;when the query runs, a row’s
seriesis not innames, or a clock steps below the previous row’s in its group, the row named, as a spec refuses one withrestart_after_step_backunset. 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 aDataFrametoo. Under 2.0 it is theValueErroritself.
TypeErrorA keyword under its old name, such as
chunk_rows.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.
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 = po.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
po.spec.rcovandpo.spec.ew_cov, the models a grid’s returns feed.polars_online.corr.epps_invert(), which corrects a correlation for the Epps effect instead.Align series that tick at their own times, the how-to.
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 byclock, and by the order you want within a clock value.It resumes.
save_statewrites 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 ahead(n)pulled. A run resumed on the input after that tick goes on with the next point. Withpairs=Trueone 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_stategoes on from where its run stopped, so feeding a stream in two runs gives the grid one run gives.