rheon.polars.stream.embargo

rheon.polars.stream.embargo(lf: LazyFrame, *, clock: str, delay: float | timedelta | str | _Expr, weight: str | None = None, role: str = ROLE) → LazyFrame[source]
rheon.polars.stream.embargo(lf: DataFrame, *, clock: str, delay: float | timedelta | str | _Expr, weight: str | None = None, role: str = ROLE) → DataFrame

Double a stream so that each row’s target is learned delay after its row.

Use it when a target is a forward quantity, known only delay clock units after its row, and you want the delay visible in the data: an independent check of a spec’s own embargo, a demonstration, or a model or engine with no embargo of its own. Otherwise give the spec embargo=delay, which does the same in the stream with no second copy of each row, or a label_clock column when each row’s target becomes known at a time of its own (Notes).

Parameters

lf

The stream, a LazyFrame or a DataFrame, already in clock order across all its rows, not only within each group. The two copies are merged by the clock alone, so a frame sorted within its groups but not across them comes back with a group’s clock stepping back. Sort it first with lf.sort(clock, maintain_order=True), or embargo each group and concatenate.

clock

The clock column: numeric, Datetime, Date or Duration.

delay

The time from predicting a row to learning it, finite and above 0. It is measured as a spec’s clock parameters are: a number of the clock’s own units on a numeric clock, and a duration (pl.duration(minutes=5), a timedelta or "5m") on a temporal one. A duration must be a whole number of the column’s own steps, since the learn copy’s clock is the column plus the delay: a Date clock takes whole days, where "12h" would be cut to nothing. On an integer clock a whole delay, 5.0 as well as 5, keeps the clock’s dtype.

weight

An existing weight column, of any numeric dtype, to carry onto the learn rows and set to 0 on the predict rows. It comes back as Float64, the number a bank reads it as. The default, None, adds a weight column named role + "_weight": 1 on learn rows and 0 on predict rows. Pass that name to the spec’s weight=.

role

The name of the column that says which copy a row is, "predict" or "learn". Default "_online_role" (ROLE).

Returns

The kind of frame it was given, with every row twice, in clock order:

the row

at

carrying

a predict row

clock

its weight forced to 0, so the model predicts it and learns nothing from it

a learn row

clock + delay

the same features and target at the row’s own weight (1 without weight)

The columns are the input’s, then the weight column it adds (without weight), then role. At the same clock value a learn row comes before a predict row, since a target whose delay has just run out is known at that instant, and a prediction made then may use it. A spec’s embargo releases in the same order, so the two can be compared row for row. Keep the predictions with out.filter(pl.col(role) == "predict").

Raises

ColumnNotFoundError

The frame has no clock or weight column of that name. It is both a ValueError and Polars’ ColumnNotFoundError.

WrongTypeError

The clock column is neither numeric nor temporal, is an integer wider than 64 bits (Int128), which a bank refuses as a clock, or is a Time, since a time of day starts again at midnight; or, on a numeric clock, delay is neither a number nor a duration, such as None. It is both a TypeError and a ValueError.

ValueError

When:

  • delay is not finite and above 0 (0 would be the undoubled stream, and a negative delay a target learned before its row);

  • delay is of the wrong kind for the clock, or is not a whole number on an integer clock;

  • delay is a duration that is not a whole number of the clock column’s steps, such as "12h" on a Date;

  • the frame already has a column named role, or, without weight, one named role + "_weight".

TypeError

delay is an expression that reads a column or does not give one duration.

polars.exceptions.InvalidOperationError

When the query runs, if an integer clock within delay of its dtype’s top cannot hold its learn copy. Polars names the column, where wrapping the clock around would put the learn copy before the stream.

ConsumedSourceWarning

A warning, not an error, issued as the query is built when the input reads a source written in Python (Notes).

Examples

rows = pl.DataFrame({"t": [0.0, 1.0, 2.0]})
doubled = rp.stream.embargo(rows, clock="t", delay=1.0)   # adds a weight and a role column
for row in doubled.rows():                                # (t, weight, role)
    print(row)
(0.0, 0.0, 'predict')
(1.0, 1.0, 'learn')
(1.0, 0.0, 'predict')
(2.0, 1.0, 'learn')
(2.0, 0.0, 'predict')
(3.0, 1.0, 'learn')

A bank fed the doubled stream learns each row’s target 5 rows late, and the predict rows carry its predictions. This code reads lf from Example data:

doubled = rp.stream.embargo(lf, clock="t", delay=5.0)
scored = doubled.rheon.fit_predict(
    [rp.spec.ewridge("m", targets=["y"], features=["x0"], clock="t", gap_cap=10.0,
                     half_life=50.0, weight="_online_role_weight")]
).filter(pl.col("_online_role") == "predict").collect()
pred = scored["m"].struct.field("pred_y")
print(scored.height, pred.count())         # predict rows, and those with a prediction
400 393

See also

  • The spec’s embargo and label_clock (rheon.spec), which delay the learning inside the bank.

  • Learn targets known late, the how-to: each of the three ways, with a check that it worked.

Notes

A target that is a forward quantity over delay clock units is not known at the row it sits on. A stream that learns it there has seen delay of the future before predicting the rows in between, and every out-of-sample number after that is contaminated. With an autocorrelated feature, even a pure-noise column shows a correlation with its target. A row of weight 0 is legal and means “advance the clock, learn nothing”, so the doubled stream says what is wanted: predict here, learn later.

When each row’s target becomes known at a time of its own, give the spec a label_clock column of those times rather than doubling by hand. A doubled stream learns the same targets at the same clocks, so its predict rows’ predictions are the ones a label_clock bank serves. But on each learn row the bank predicts again before learning, and computes every residual diagnostic from that second prediction, not the one the predict row was given. On New York’s 2013 flights its 90% interval covered 88.0% of the delays it was shown while reporting 90.0%. label_clock scores each target against the prediction and interval its row was served.

The function reads its input twice, once for each copy, merging the two as they stream. A source that can be read once only, such as what pl.scan_arrow_c_stream builds over a DuckDB relation or a pyarrow reader, gives the second read nothing, and half the stream would go missing with no error. Whether a source is spent cannot be seen until the query runs. So where the query reads a source written in Python, as such a stream does, the function issues a ConsumedSourceWarning as the query is built. Write such an input to a file and read that file as a query, or pass it as a frame.

A bank refuses a doubled stream in which a group’s clock steps back, as it refuses every step back unless restart_after_step_back says it is a new start.