Coverage for features/cross_asset_timing.py: 100%
121 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Which bars a cross-asset payload (topology, peer returns, macro proxies,
2cross-sectional momentum rank) may see - shared by `main.py` (live windows) and
3`train.py` (offline dataset) so the two cannot drift again (Problems.md #135).
5Live builds the payload at the START of a tick, before that tick's own bars join
6`symbol_windows`, and a daily bar only exists once its period has closed: a US
7equity bar of day D at D's close, a crypto/forex bar of day D at the following
8midnight. A row therefore sees every bar that became available strictly before
9the row's own bar did - never its own tick's bars, and not yet-unclosed
10crypto/forex bars on the equity tick (but Sunday's crypto bar on Monday).
11"""
13from __future__ import annotations
15import json
16import math
17from bisect import bisect_left
18from collections.abc import Mapping, Sequence
19from datetime import date as _date
20from functools import lru_cache
21from pathlib import Path
22from typing import TYPE_CHECKING, Any
24if TYPE_CHECKING:
25 from datetime import datetime
27WINDOW_BARS = 25 # main.py: deque(maxlen=bar_history_size); up to 24 returns
28MOMENTUM_LOOKBACK_BARS = 20
29_MIDNIGHT_SECURITY_TYPES = frozenset({"crypto", "forex"})
30_SATURDAY = 5 # date.weekday(): Monday is 0
31_EQUITY_CLOSE_FRACTION = 0.5
32_MIDNIGHT_FRACTION = 1.0
35def day_ordinal(stamp: _date | datetime | str) -> int:
36 """Proleptic ordinal of a pandas Timestamp / datetime / date / ISO date string."""
37 if hasattr(stamp, "toordinal"):
38 return stamp.toordinal()
39 return _date.fromisoformat(str(stamp)[:10]).toordinal()
42@lru_cache(maxsize=8)
43def lean_market_holidays(market_hours_path: str, entry: str = "Forex-oanda-[*]") -> frozenset[int]:
44 """Day ordinals of the full-day holidays Lean's market-hours database lists for `entry`. On such a day Lean delivers
45 no bar for the market: the zip's own bar is dropped and the day is not filled forward (V6.1.0: GBPJPY's live
46 momentum on 2024-01-22 equals the calendar without the 2023-12-24 / 12-31 Sunday fills). A missing file or entry
47 returns an empty set (the pre-V6.1.0 calendar)."""
48 path = Path(market_hours_path)
49 if not path.exists():
50 return frozenset()
51 entries = json.loads(path.read_text(encoding="utf-8")).get("entries", {})
52 out = set()
53 for text in (entries.get(entry) or {}).get("holidays", []):
54 month, day, year = (int(part) for part in str(text).split("/"))
55 out.add(_date(year, month, day).toordinal())
56 return frozenset(out)
59def resolve_forex_lean_holidays(config: dict[str, Any], root: Path | None = None) -> frozenset[int]:
60 """Lean's forex market holidays when `phase1.features.forex_lean_holidays` is on (V6.1.0), else an empty set (the
61 V6.0.0 calendar: every Sunday-Friday gap filled, every zip bar kept)."""
62 if not bool(((config or {}).get("phase1", {}).get("features", {}) or {}).get("forex_lean_holidays", False)):
63 return frozenset()
64 base = root if root is not None else Path(__file__).resolve().parents[1]
65 return lean_market_holidays(str(base / "data" / "market-hours" / "market-hours-database.json"))
68def fill_forward_open_forex_days(
69 ordinals: Sequence[int], closes: Sequence[float], holidays: frozenset[int] | set[int] = frozenset()
70) -> tuple[list[int], list[float]]:
71 """Lean fills forward a forex daily bar on every day the market is open without data. The forex market is open
72 Sunday evening through Friday, so any Sunday-Friday day that falls between two bars becomes a flat bar at the
73 previous close (BT1 probe, Problems.md #135: every pair delivered a Sunday bar live equal to the preceding Friday
74 close where the local zip has no Sunday row; the 2019-05-22 weekday missing from the zips moved the live
75 correlations for the next 24 bars). Saturdays and Lean's market holidays (`holidays`, lean_market_holidays) stay
76 closed; only gaps strictly between two bars are filled; ordinals must be ascending."""
77 filled_ordinals: list[int] = []
78 filled_closes: list[float] = []
79 for index, (ordinal, close) in enumerate(zip(ordinals, closes, strict=False)):
80 filled_ordinals.append(ordinal)
81 filled_closes.append(close)
82 if index + 1 == len(ordinals):
83 continue
84 for day in range(ordinal + 1, ordinals[index + 1]):
85 if _date.fromordinal(day).weekday() != _SATURDAY and day not in holidays:
86 filled_ordinals.append(day)
87 filled_closes.append(close)
88 return filled_ordinals, filled_closes
91def is_late_bar_asset(security_type: str | None) -> bool:
92 """Crypto and forex daily bars close at midnight, after the equity session: the equity tick still holds the
93 previous day's bar for them."""
94 return security_type in _MIDNIGHT_SECURITY_TYPES
97class LateBarCrossAssetCache:
98 """The cross-asset inputs (topology node, momentum map) a crypto/forex symbol had at ITS OWN tick, for re-use on the
99 equity tick that scores the same bar again (V6.0.0, todo lead 5).
101 The dataset row of a crypto/forex bar of day D sees the bars that closed before the bar did (key D + 1.0: equity
102 through D, crypto/forex through D - 1). Live builds exactly that payload at the symbol's own midnight tick; the next
103 equity tick (key D + 1.5) holds one more crypto bar, so re-scoring the symbol there with fresh payloads fed the model
104 a correlation window the dataset never has. Re-using the own-tick payloads makes the equity-tick score the dataset's
105 row D exactly (`phase1.features.late_bar_cross_asset: "own_tick"`)."""
107 def __init__(self) -> None:
108 self._entries: dict[str, tuple[dict, Mapping[str, float]]] = {}
110 def record(self, symbol_key: str, topology_node: dict[str, Any] | None, momentum_by_symbol: Mapping[str, float]) -> None:
111 if topology_node is not None:
112 self._entries[symbol_key] = (topology_node, momentum_by_symbol)
114 def lookup(self, symbol_key: str) -> tuple[dict, Mapping[str, float]] | None:
115 return self._entries.get(symbol_key)
118def bar_available_at(ordinal: int, security_type: str) -> float:
119 """When a bar dated `ordinal` becomes known: the following midnight for crypto and forex, the equity close otherwise."""
120 return ordinal + (_MIDNIGHT_FRACTION if security_type in _MIDNIGHT_SECURITY_TYPES else _EQUITY_CLOSE_FRACTION)
123def momentum_from_closes(closes: Sequence[float]) -> float | None:
124 """`closes[-1] / close 20 bars back - 1` over the window; None below two closes or on a zero base."""
125 if len(closes) < 2:
126 return None
127 base = closes[max(0, len(closes) - (MOMENTUM_LOOKBACK_BARS + 1))]
128 if not base:
129 return None
130 momentum = closes[-1] / base - 1.0
131 return momentum if math.isfinite(momentum) else None
134def returns_from_closes(closes: Sequence[float]) -> list[float]:
135 """Simple returns of a close series, skipping a step from a zero close."""
136 returns = []
137 for index in range(1, len(closes)):
138 previous = closes[index - 1]
139 if previous == 0:
140 continue
141 value = closes[index] / previous - 1.0
142 if math.isfinite(value):
143 returns.append(value)
144 return returns
147def cross_asset_inputs(closes_by_symbol: Mapping[str, Sequence[float]]) -> tuple[dict[str, list[float]], dict[str, float]]:
148 """(returns_by_symbol, momentum_by_symbol) from each symbol's trailing close window."""
149 returns_by_symbol: dict[str, list[float]] = {}
150 momentum_by_symbol: dict[str, float] = {}
151 for symbol, closes in closes_by_symbol.items():
152 returns = returns_from_closes(closes)
153 if returns:
154 returns_by_symbol[symbol] = returns
155 momentum = momentum_from_closes(closes)
156 if momentum is not None:
157 momentum_by_symbol[symbol] = momentum
158 return returns_by_symbol, momentum_by_symbol
161class CrossAssetTimeline:
162 """Raw (pre-dropna) close history per ticker, queryable as "what did the live windows hold at this moment"."""
164 def __init__(
165 self,
166 closes_by_ticker: Mapping[str, Sequence[float]],
167 day_ordinals_by_ticker: Mapping[str, Sequence[int]],
168 security_types: Mapping[str, str] | None = None,
169 ) -> None:
170 security_types = security_types or {}
171 self._closes = {ticker: list(closes) for ticker, closes in closes_by_ticker.items()}
172 self._security_types = {ticker: security_types.get(ticker, "equity") for ticker in self._closes}
173 self._availability = {
174 ticker: [bar_available_at(ordinal, self._security_types[ticker]) for ordinal in day_ordinals_by_ticker[ticker]]
175 for ticker in self._closes
176 }
178 @classmethod
179 def from_frames(
180 cls, frames: Mapping[str, Any], security_types: Mapping[str, str] | None = None, forex_holidays: frozenset[int] = frozenset()
181 ) -> CrossAssetTimeline:
182 """`frames`: ticker -> DataFrame with `date` (Timestamp) and `close`, sorted by date. Forex history gets
183 Lean's fill-forward bars (see fill_forward_open_forex_days), so its windows are what live holds."""
184 security_types = security_types or {}
185 closes_by_ticker: dict[str, list[float]] = {}
186 ordinals_by_ticker: dict[str, list[int]] = {}
187 for ticker, frame in frames.items():
188 ordinals = [day_ordinal(stamp) for stamp in frame["date"]]
189 closes = frame["close"].tolist()
190 if security_types.get(ticker) == "forex":
191 ordinals, closes = fill_forward_open_forex_days(ordinals, closes, forex_holidays)
192 ordinals_by_ticker[ticker] = ordinals
193 closes_by_ticker[ticker] = closes
194 return cls(closes_by_ticker, ordinals_by_ticker, security_types)
196 def row_availability(self, ticker: str, date: _date | datetime | str) -> float:
197 return bar_available_at(day_ordinal(date), self._security_types.get(ticker, "equity"))
199 def closes_before(self, availability: float) -> dict[str, list[float]]:
200 windows: dict[str, list[float]] = {}
201 for ticker, keys in self._availability.items():
202 end = bisect_left(keys, availability)
203 if end:
204 windows[ticker] = self._closes[ticker][max(0, end - WINDOW_BARS) : end]
205 return windows
207 def inputs_before(self, availability: float) -> tuple[dict[str, list[float]], dict[str, float]]:
208 return cross_asset_inputs(self.closes_before(availability))
210 def momentum_before(self, availability: float) -> dict[str, float]:
211 return {
212 symbol: momentum
213 for symbol, closes in self.closes_before(availability).items()
214 if (momentum := momentum_from_closes(closes)) is not None
215 }