Coverage for data_pipeline/bar_synthesis.py: 100%
49 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"""V5.3.10 - pure functions extracted from main.py so the live-path logic
2they implement becomes unit-testable outside Lean's runtime (established
3pattern: evaluate_non_model_exit(), compute_incremental_order_quantity(),
4etc.). Each function is a VERBATIM copy of the corresponding main.py
5method body - see each function's docstring for its origin line."""
7from __future__ import annotations
9from types import SimpleNamespace
10from typing import TYPE_CHECKING, Any
12if TYPE_CHECKING:
13 from collections.abc import Callable
16def midpoint_bar_from_quote_bar(quote_bar: Any) -> SimpleNamespace | None:
17 """V4.6 - forex quote-bar (bid/ask) to trade-bar-shaped midpoint OHLC
18 (main.py::_midpoint_bar_from_quote_bar verbatim). Volume is always
19 0.0 - forex quote data carries no trade-volume concept. Returns None
20 (never raises) when no quote bar exists or it's missing a bid/ask side."""
21 if quote_bar is None or quote_bar.Bid is None or quote_bar.Ask is None:
22 return None
23 return SimpleNamespace(
24 open=(float(quote_bar.Bid.Open) + float(quote_bar.Ask.Open)) / 2.0,
25 high=(float(quote_bar.Bid.High) + float(quote_bar.Ask.High)) / 2.0,
26 low=(float(quote_bar.Bid.Low) + float(quote_bar.Ask.Low)) / 2.0,
27 close=(float(quote_bar.Bid.Close) + float(quote_bar.Ask.Close)) / 2.0,
28 volume=0.0,
29 # V6.0.0: Lean's fill-forward bar is a clone of the previous bar (same OHLC) flagged IsFillForward; one second
30 # before its end time is the bar's own date in any time zone (the date the dataset row carries).
31 is_fill_forward=bool(_first_attribute(quote_bar, ("IsFillForward", "is_fill_forward"), False)),
32 end_time=_first_attribute(quote_bar, ("EndTime", "end_time"), None),
33 )
36def _first_attribute(source, names: tuple[str, ...], default):
37 for name in names:
38 try:
39 value = getattr(source, name)
40 except Exception:
41 continue
42 if value is not None and not callable(value):
43 return value
44 return default
47def flatten_fill_forward_bar(bar: dict[str, Any], previous_close: float) -> dict[str, Any]:
48 """A fill-forward bar the way the training dataset builds it (`train.fill_forward_forex_frame`): flat at the
49 previous close with no volume. Lean's own fill-forward bar repeats the previous bar's range, so a trailing ATR or
50 high-low spread window that contains one differs from the dataset's (V6.0.0, todo lead 4)."""
51 close = float(previous_close)
52 return {"open": close, "high": close, "low": close, "close": close, "volume": 0.0}
55def pad_sequence_history(history: list[list[float]], window_size: int) -> list[list[float]]:
56 """Left-pads a rolling per-symbol feature-history buffer with zero
57 vectors up to window_size (main.py::_pad_sequence_history verbatim).
58 Pure, no side effects. An empty history returns `window_size` all-zero
59 vectors of the model's width when inferable, else raises a clear
60 ValueError instead of IndexError (V5.4.7 #123)."""
61 if not history:
62 raise ValueError(
63 "pad_sequence_history: empty history - feature width cannot be "
64 "inferred; callers guard this before calling (main.py's own "
65 "truthy filters), so reaching here means a caller contract broke."
66 )
67 input_width = len(history[0])
68 padding_needed = window_size - len(history)
69 return [[0.0] * input_width for _ in range(max(0, padding_needed))] + list(history)
72def adaptive_sell_threshold(
73 *,
74 sell_threshold: float,
75 history: list[float] | None,
76 band_enabled: bool,
77 min_observations: int,
78 band_percentile: float,
79) -> float:
80 """Pure lookup + percentile over accumulated probability_up history
81 (main.py::_effective_sell_threshold verbatim). Never adapts ABOVE the
82 static threshold - the band only makes selling easier."""
83 if not band_enabled:
84 return sell_threshold
85 if history is None or len(history) < min_observations:
86 return sell_threshold
87 sorted_history = sorted(history)
88 index = max(0, min(len(sorted_history) - 1, int(band_percentile * len(sorted_history))))
89 return min(sell_threshold, sorted_history[index])
92def derive_signal(
93 probability_up: float,
94 *,
95 decision_threshold: float,
96 buy_threshold: float,
97 effective_sell_threshold: float,
98 max_position_weight: float,
99 record_observation: Callable[[str | None, float], None] | None=None,
100 symbol_key: str | None = None,
101) -> tuple[str, float, float]:
102 """Signal classification extracted from main.py::_derive_signal()
103 (verbatim arithmetic). `record_observation(symbol_key, probability_up)`
104 is an optional callback so callers can preserve the observation-recording
105 side effect without this function needing state."""
106 confidence = abs(probability_up - decision_threshold) / max(1.0 - decision_threshold, decision_threshold)
107 confidence = max(0.0, min(confidence, 1.0))
109 def _record():
110 if record_observation is not None and symbol_key is not None:
111 record_observation(symbol_key, probability_up)
113 if probability_up >= buy_threshold:
114 target_weight = min(max_position_weight, 0.10 + 0.15 * confidence)
115 _record()
116 return "buy", confidence, target_weight
118 if probability_up <= effective_sell_threshold:
119 target_weight = -min(max_position_weight, 0.10 + 0.15 * confidence)
120 _record()
121 return "sell", confidence, target_weight
123 _record()
124 return "hold", confidence, 0.0