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, use refresh_time().

Parameters

*frames

The streams, each a LazyFrame or a DataFrame in clock order across all its rows, its groups included. Pass them by position, named "0", "1" and on in that order, or pass one dict of each stream’s name to its frame. The order they are given in breaks a tie (Notes).

clock

The clock column, in every stream, of one dtype across them: an integer, a float, a Datetime, a Date or a Duration, with one unit and one time zone. A temporal clock is compared exactly, in its integer steps.

source

The name of the column added to name each row’s stream. Default "source".

by

The 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_back

By 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", a timedelta or pl.duration(hours=1)), at least 0.

chunk_size

The 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_state

The path of a state merge() 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 merging streams of the same names, in the same order, on the same clock and by, and a clock of the same dtype. Default None: start with no state loaded.

save_state

The 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 DataFrame when every stream is a DataFrame, and otherwise a LazyFrame, with every row of every stream in clock order. Its columns are the streams’ columns, matched by name in the order they first appear, then source. A column a stream does not have is null on that stream’s rows.

Raises

ColumnNotFoundError

A stream has no clock or by column of that name. It is both a ValueError and Polars’ ColumnNotFoundError.

WrongTypeError

The clock column 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, is UInt128, which rheon cannot read. It is both a TypeError and a ValueError.

ValueError

When the query is built: no stream is given, or a name twice; a stream already has a column named source; chunk_size is below 1; restart_after_step_back is below 0, or a duration on a numeric clock, or a number on a temporal one; load_state is not such a state, or was saved with other streams, clock, by or 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 a DataFrame too. Under 2.0 each is the ValueError itself.

TypeError

A stream is neither a LazyFrame nor a DataFrame, or a name in a dict is not text.

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.

OrderNotGuaranteedWarning

A 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

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. Under restart_after_step_back a 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 by by reads them, under the same restart_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. Without by the merged rows are checked as one group.

It resumes. save_state writes 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 with load_state on 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 the source column counts.