Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@
- Retry transient external documentation-link failures with bounded backoff. Broken links and
persistent service errors still fail qualification.

### Changed

- Avoid redundant prepared-signal masking and per-row index construction in RuntimeServices.
Preserve exact publication timestamps, eligibility, missing observations and instrument
lifetimes.

## 0.2.0 - 2026-10-22

### Added
Expand Down
3 changes: 3 additions & 0 deletions release/changelog.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
"Update build and workflow dependencies and repair contributor-environment security locks. Require PyArrow 26.0.1 or later in the pinned installed successor qualification cohort.",
"Correct the executable limit-order tutorial to match favorable opening fills and simplify documentation navigation. Keep public examples qualified against the built wheel.",
"Retry transient external documentation-link failures with bounded backoff. Broken links and persistent service errors still fail qualification."
],
"Changed": [
"Avoid redundant prepared-signal masking and per-row index construction in RuntimeServices. Preserve exact publication timestamps, eligibility, missing observations and instrument lifetimes."
]
}
},
Expand Down
171 changes: 132 additions & 39 deletions src/ml4t/backtest/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from ._history_clock import expected_times, session_times
from ._instruments import InstrumentSource, InstrumentView
from ._temporal import temporal_frame, temporal_row, temporal_rows
from ._temporal import temporal_frame, temporal_row, temporal_rows, timestamp_values
from .auxiliary import AuxiliaryData
from .execution.callbacks import SessionScheduler
from .futures_lifecycle import FuturesLifecyclePolicy
Expand All @@ -24,6 +24,22 @@
from .engine import Engine


_QUOTE_FIELDS = (
"price",
"open",
"high",
"low",
"close",
"volume",
"vwap",
"bid",
"ask",
"mid",
"bid_size",
"ask_size",
)


class PreparedHistory(Protocol):
"""Read interface for Data's causal prepared-history output."""

Expand Down Expand Up @@ -137,26 +153,41 @@ def __init__(
self._frame.schema[column], pl.Datetime
):
raise ValueError(f"Known-at column {column!r} must contain datetimes")
index_columns = list(
dict.fromkeys([self._timestamp_col, self._entity_col, *self._known_at_cols.values()])
stamps = self._frame[self._timestamp_col]
for column in dict.fromkeys(self._known_at_cols.values()):
if self._frame[column].null_count() == self._frame.height:
continue
known_dtype = self._frame.schema[column]
if not isinstance(stamps.dtype, pl.Datetime) or (
cast(pl.Datetime, known_dtype).time_zone is None
) != (stamps.dtype.time_zone is None):
raise ValueError("Known-at and observation timezones must be compatible")
# One Python value per distinct instant, shared by every asset's index; rows are
# grouped by asset in Polars instead of being iterated one by one.
instants = stamps.unique().sort()
self._timestamps = timestamp_values(instants)
values = dict(zip(instants.to_physical().to_list(), self._timestamps, strict=True))
index = self._frame.select(
pl.col(self._entity_col), pl.col(self._timestamp_col).to_physical().alias("__ml4t_key")
).with_row_index("__ml4t_row")
repeated = index.filter(
pl.struct(self._entity_col, "__ml4t_key").is_first_distinct().not_()
)
for index, row in enumerate(temporal_rows(self._frame.select(index_columns), named=True)):
asset, timestamp = row[self._entity_col], row[self._timestamp_col]
rows = self._rows.setdefault(asset, {})
if timestamp in rows:
raise ValueError(f"Duplicate market observation for {asset!r} at {timestamp}")
for column in self._known_at_cols.values():
if row[column] is not None:
try:
_ = row[column] <= timestamp
except TypeError as exc:
raise ValueError(
"Known-at and observation timezones must be compatible"
) from exc
rows[timestamp] = index
if repeated.height:
asset, key = repeated.row(0)[1:]
raise ValueError(f"Duplicate market observation for {asset!r} at {values[key]}")
for part in index.partition_by(self._entity_col, maintain_order=True):
self._rows[part[self._entity_col][0]] = dict(
zip(
map(values.__getitem__, part["__ml4t_key"].to_list()),
part["__ml4t_row"].to_list(),
strict=True,
)
)
for asset, rows in self._rows.items():
self._times[asset] = sorted(rows)
self._timestamps = sorted({t for times in self._times.values() for t in times})
self._timestamp_set = frozenset(self._timestamps)
self._hidden: dict[frozenset[str], dict[int, tuple[str, ...]]] = {}
self._asof: datetime | None = None
self._inclusive = False

Expand All @@ -180,6 +211,54 @@ def _row(self, asset: str, timestamp: datetime) -> dict[str, Any] | None:
index = self._rows.get(asset, {}).get(timestamp)
return temporal_row(self._frame, index) if index is not None else None

def _hidden_at_own_time(self, fields: frozenset[str]) -> dict[int, tuple[str, ...]]:
"""Row index -> the fields `_available` masks when the clock stands at that row's time.

Valid only for views without quote fields: they read inclusively and carry no instrument
lifetime, so the mask of a row at its own timestamp depends on the row alone and is
computed once, in Polars, for every row.
"""
assert not self._quote_fields
cached = self._hidden.get(fields)
if cached is not None:
return cached
timestamp = pl.col(self._timestamp_col)
units = {"ms": 1_000_000, "us": 1_000, "ns": 1}
stamp_dtype = cast(pl.Datetime, self._frame.schema[self._timestamp_col])
observation_ns = timestamp.cast(pl.Int128) * units[stamp_dtype.time_unit]
masks = []
for field in sorted(fields):
declaration = self._known_at_cols.get(field)
hidden = (
timestamp.is_null()
if declaration is None
else pl.col(declaration).is_null()
| (
pl.col(declaration).cast(pl.Int128)
* units[cast(pl.Datetime, self._frame.schema[declaration]).time_unit]
> observation_ns
)
)
eligible = self._eligible_cols.get(field)
if eligible is not None:
hidden = hidden | pl.col(eligible).fill_null(False).not_()
masks.append(pl.when(hidden).then(pl.lit(field)))
cached = (
{
row: tuple(names)
for row, names in self._frame.select(
pl.concat_list(masks).list.drop_nulls().alias("hidden")
)
.with_row_index("row")
.filter(pl.col("hidden").list.len() > 0)
.iter_rows()
}
if masks
else {}
)
self._hidden[fields] = cached
return cached

def _column(self, field: str) -> str:
return self._roles.get(field, field)

Expand Down Expand Up @@ -1110,35 +1189,49 @@ def _advance(self, timestamp: datetime, data: dict[str, dict]) -> dict[str, dict
)
if not self.known_at_cols and not signal_fields and self._assets is None:
return data
# A bar at the current timestamp is published to an inclusive clock. Without known-at or
# eligibility declarations, or instrument lifetimes for quotes, no market field can be
# masked, so the per-asset, per-field checks below are skipped.
masks_market = bool(market._known_at_cols or market._eligible_cols) or (
market._quote_fields and self._assets is not None
)
check_signals = (
signal_view is not None
and bool(signal_fields)
and timestamp in signal_view._timestamp_set
)
if not masks_market and not check_signals:
return data # no signal row at this event and no market field to mask
# The clock stands at the signal rows' own timestamp, so their masks are precomputed.
hidden = (
signal_view._hidden_at_own_time(frozenset(signal_fields))
if check_signals and signal_view is not None
else {}
)
visible = {asset: dict(values) for asset, values in data.items()}
for asset, values in visible.items():
if signal_fields:
if check_signals:
assert signal_view is not None
view = signal_view
signal = view._row(asset, timestamp)
if signal is not None:
index = signal_view._rows.get(asset, {}).get(timestamp)
if index is not None:
delivered = dict(values.get("signals", {}))
for field in signal_fields:
if not view._available(field, signal):
delivered[field] = None
delivered.update(dict.fromkeys(hidden.get(index, ())))
values["signals"] = delivered
if not masks_market:
continue
if not (market._known_at_cols or market._eligible_cols):
# Only an instrument's lifetime can mask this bar; it masks every field at once,
# so one membership check replaces reading the row and testing each field.
assert self._assets is not None
if timestamp in market._rows.get(asset, {}) and not self._assets._active_at(
asset, timestamp, timestamp
):
values.update(dict.fromkeys(_QUOTE_FIELDS))
continue
row = market._row(asset, timestamp)
if row is None:
continue
for field in [
"price",
"open",
"high",
"low",
"close",
"volume",
"vwap",
"bid",
"ask",
"mid",
"bid_size",
"ask_size",
]:
for field in _QUOTE_FIELDS:
raw = market._column(field)
source = (
field
Expand Down
89 changes: 89 additions & 0 deletions tests/test_prepared_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import hashlib
import json
from copy import deepcopy
from datetime import timedelta
from pathlib import Path

import pandas as pd
Expand Down Expand Up @@ -142,6 +143,47 @@ def on_data(self, timestamp, data, context, broker):
assert panel["average"].to_list() == [2.0, 20.0, 3.0, 30.0]


@pytest.mark.parametrize("late", [False, True])
def test_feature_values_reach_a_strategy_only_at_decisions_when_prices_have_events_between_them(
late,
):
panel = _panel()
if late:
panel = panel.with_columns(
pl.when(pl.col("asset") == "A")
.then(pl.col("decision_time") + pl.duration(seconds=1))
.otherwise(pl.col("available_at"))
.alias("available_at")
)
prices = _panel().select(
pl.col("decision_time").alias("timestamp"), "asset", pl.lit(100.0).alias("close")
)
between = prices["timestamp"].min() + timedelta(hours=1)
extra = pl.select(
pl.lit(between, dtype=prices.schema["timestamp"]).alias("timestamp"),
pl.Series("asset", ["A", "B"]),
pl.lit(100.0).alias("close"),
)
feed = DataFeed(
prices_df=pl.concat([prices, extra]).sort("timestamp", "asset"),
signals_df=panel,
feature_spec=MANIFEST["feature_spec"],
feed_spec={
"time_contract_version": 2,
"calendar": None,
"timestamp_semantics": "event_time",
},
)
seen = []

class Read(Strategy):
def on_data(self, timestamp, data, context, broker):
seen.append((data["A"].get("signals") or {}).get("average"))

Engine(feed, Read(), BacktestConfig(calendar=None)).run()
assert seen == ([None, None, None] if late else [2.0, None, 3.0])


def test_feature_metadata_is_a_defensive_copy_of_the_original_producer_contract():
feed = _feed()
metadata = feed.feature_metadata
Expand Down Expand Up @@ -220,3 +262,50 @@ def test_captured_panel_can_be_rebuilt_by_the_actual_installed_engineer_producer
actual = actual.collect() if isinstance(actual, pl.LazyFrame) else actual
assert_frame_equal(actual, _panel())
assert _feed(actual, spec).feature_metadata["spec"] == spec.to_dict()


@pytest.mark.parametrize("unit", ["ms", "us", "ns"])
@pytest.mark.parametrize("delay_ns", [0, 1])
@pytest.mark.parametrize("append_future", [False, True])
def test_prepared_feature_publication_keeps_nanosecond_causality_at_coarser_decision_clocks(
unit, delay_ns, append_future
):
panel = _panel().with_columns(
pl.col("decision_time").cast(pl.Datetime(unit, "UTC")),
(
pl.col("decision_time").cast(pl.Datetime("ns", "UTC"))
+ pl.duration(nanoseconds=delay_ns)
).alias("available_at"),
)
if append_future:
future = panel.tail(2).with_columns(
pl.col("timestamp") + pl.duration(days=1),
(pl.col("decision_time") + pl.duration(days=1, time_unit="ns")).cast(
panel.schema["decision_time"]
),
pl.col("available_at") + pl.duration(days=1, time_unit="ns"),
pl.lit(99999.0).alias("average"),
)
panel = pl.concat([panel, future])
runtime = RuntimeServices(end=_panel()["decision_time"].max())
seen = []

class Read(Strategy):
def on_data(self, timestamp, data, context, broker):
values = [(data.get(a, {}).get("signals") or {}).get("average") for a in ["A", "B"]]
current = runtime.signals.current(["A", "B"], ["average"])["average"].to_list()
assert current == values
seen.append(values)
if values[0] is not None:
broker.submit_order("A", 1)

# Original two decision observations only. A future appended panel must not change them.
feed = _feed(panel)
result = Engine(
feed,
Read(),
BacktestConfig(calendar=None, execution_mode=ExecutionMode.SAME_BAR),
runtime=runtime,
).run()
assert seen == ([[2.0, None], [3.0, None]] if delay_ns == 0 else [[None, None], [None, None]])
assert [f.price for f in result.fills] == ([100.0, 100.0] if delay_ns == 0 else [])