rheon.polars.stream.merge¶
- rheon.polars.stream.merge(*frames: DataFrame, clock: str, source: str = 'source', by: str | None = None, restart_after_step_back: float | timedelta | str | _Expr | None = None, chunk_size: int | None = None, load_state: str | PathLike[str] | bytes | None = None, save_state: str | PathLike[str] | None = None) DataFrame[source]¶
- rheon.polars.stream.merge(*frames: LazyFrame | DataFrame | Mapping[str, LazyFrame | DataFrame], clock: str, source: str = 'source', by: str | None = None, restart_after_step_back: float | timedelta | str | _Expr | None = None, chunk_size: int | None = None, load_state: str | PathLike[str] | bytes | None = None, save_state: str | PathLike[str] | None = None) LazyFrame | DataFrame
Merge streams that each run in clock order into one stream in clock order, every row kept.
Use it to feed one bank, or one
with_windows()run, from several streams that tick at their own times, such as quotes, trades and news, each read from a file of its own. Each row comes out once, at its own clock, tagged with the stream it came from, and nothing is filled in or dropped. To put such series on a common grid instead, one row per instant that every series has ticked by, userefresh_time().Parameters
*framesThe streams, each a
LazyFrameor aDataFrameinclockorder across all its rows, its groups included. Pass them by position, named"0","1"and on in that order, or pass onedictof each stream’s name to its frame. The order they are given in breaks a tie (Notes).clockThe clock column, in every stream, of one dtype across them: an integer, a float, a
Datetime, aDateor aDuration, with one unit and one time zone. A temporal clock is compared exactly, in its integer steps.sourceThe name of the column added to name each row’s stream. Default
"source".byThe column a bank reading the merged stream groups by, in every stream. The merged rows of each of its groups are then checked as that bank checks them (Notes). Default
None: the merged rows are checked as one stream.restart_after_step_backBy default a step back of a stream’s clock is refused, as a spec refuses one. If it is set, a step back larger than it starts that stream again, as a new day’s rows start a clock again, and one no larger is still refused. A number of clock units, or a duration on a temporal clock (
"1h", atimedeltaorpl.duration(hours=1)), at least 0.chunk_sizeThe rows read from each stream 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
merge()saved, to go on from, or the state’s bytes, such as a stageload_checkpoint()gives back. It is read when the query is built. It must have been saved merging streams of the same names, in the same order, on the sameclockandby, and a clock of the same dtype. DefaultNone: start with no state loaded.save_stateThe path of a file to save the state to once the streams are read, or the slice of the output is. Default
None: save nothing (Notes).
Returns
A
DataFramewhen every stream is aDataFrame, and otherwise aLazyFrame, with every row of every stream in clock order. Its columns are the streams’ columns, matched by name in the order they first appear, thensource. A column a stream does not have is null on that stream’s rows.Raises
ColumnNotFoundErrorA stream has no
clockorbycolumn of that name. It is both aValueErrorand Polars’ColumnNotFoundError.WrongTypeErrorThe
clockcolumn is not an integer, a float or a temporal column, or its dtype, unit or time zone differ between two streams, which are named; a column of one name has two dtypes in two streams, which are named; or a column, read or not, isUInt128, which rheon cannot read. It is both aTypeErrorand aValueError.ValueErrorWhen the query is built: no stream is given, or a name twice; a stream already has a column named
source;chunk_sizeis below 1;restart_after_step_backis below 0, or a duration on a numeric clock, or a number on a temporal one;load_stateis not such a state, or was saved with other streams,clock,byor clock dtype. And when the query runs: a clock that is null, NaN or infinite, or one that steps back where the rule above refuses it, each naming the stream and its row, counted from 0 in that stream; or a step back in the merged rows of a group (Notes). Under py-polars 1.x these arrive inside Polars’ComputeError, since the merge runs as a Polars source, for aDataFrametoo. Under 2.0 each is theValueErroritself.TypeErrorA stream is neither a
LazyFramenor aDataFrame, or a name in adictis not text.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.OrderNotGuaranteedWarningA warning: the query before this call does not keep a stream’s rows in order, which the merge reads them in.
Examples
quotes = pl.DataFrame({"t": [1.0, 2.0, 4.0], "bid": [9.9, 10.0, 10.1]}) trades = pl.DataFrame({"t": [2.0, 3.0], "price": [10.05, 10.2]}) merged = rp.stream.merge({"quotes": quotes, "trades": trades}, clock="t") for row in merged.rows(): # (t, bid, price, source) print(row)
(1.0, 9.9, None, 'quotes') (2.0, 10.0, None, 'quotes') (2.0, None, 10.05, 'trades') (3.0, None, 10.2, 'trades') (4.0, 10.1, None, 'quotes')
See also
refresh_time(), which samples series on a common grid rather than interleaving their rows.Polars’
merge_sorted, which merges two frames sorted on one key.Merge streams by the clock, the how-to.
Notes
The order. Rows come out by their clock. At one clock value the stream given first comes first, and a stream’s own rows keep their order, so the output is what sorting the streams’ rows, concatenated in the order given, by the clock with a stable sort gives:
pl.concat(frames, how="diagonal").sort(clock, maintain_order=True), computed a chunk of each stream at a time. Underrestart_after_step_backa stream that starts again sorts after every row before it starts again: the rows of each stream’s second day come after the first day’s rows of every stream, as their own day’s. So every stream must start again at the same places, each day in each stream.Memory. A stream in clock order has its least row still to come at its head, so the least head of all the streams is the next row out. The merge keeps the streams’ heads in a heap, takes the least, and reads a stream’s next chunk when its current one is used up. It holds one chunk of each stream and one chunk of output, and the output is the same however the chunks fall. Each stream is read by a Polars query of its own, whose reader keeps buffers of its own beside the merge’s. A stream that steps back would put a row of its own after rows of the others that should follow it, so the order is checked in each stream, across its groups, as it is read.
The merged rows. With
by, the merged rows of each group are read as a bank grouped bybyreads them, under the samerestart_after_step_back: a group whose rows step back where that bank would refuse it is refused here, naming the stream and its row. Each stream in clock order gives merged rows in clock order, so in one run this catches only a group that steps back by little where its stream started again. Across runs it catches streams cut at different clocks: a resumed run whose rows belong before rows the last run returned. Withoutbythe merged rows are checked as one group.It resumes.
save_statewrites each stream’s last row read, how many times it started again, and the merged rows’ last clock in each group. The state is written in full or not at all. A run resumed withload_stateon the next part of every stream goes on where the last stopped, so feeding the streams in two runs gives the rows one run gives, when every stream is cut at the same clock. A part may end inside a tie: a stream’s next part can bring more rows at the clock the last part ended on, which belong before the rows of the streams after it. So a run that saves its state holds back the rows at the last clock it read, saves them in the state, and the resumed run returns them in their place. The rows held are those of one clock value, and the memory they take is one tie’s rows. A zero-weight row is a row like any other: the merge carries no weights.Under a slice of the output (
.head(n)) each stream is read only up to its last row returned, and nothing is held: the state saved is the state after the rows returned, whatever the chunk size. Resume on each stream after its rows the slice returned, which thesourcecolumn counts.