-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstrategy_runtime.py
More file actions
917 lines (869 loc) · 37.1 KB
/
strategy_runtime.py
File metadata and controls
917 lines (869 loc) · 37.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field, replace
from typing import Any
import pandas as pd
from quant_platform_kit.common.feature_snapshot import load_feature_snapshot_guarded
from quant_platform_kit.common.feature_snapshot_runtime import (
FeatureSnapshotContextRequest,
FeatureSnapshotRuntimeSettings,
evaluate_feature_snapshot_strategy,
)
from quant_platform_kit.common.strategy_plugins import attach_strategy_plugin_metadata
from quant_platform_kit.ibkr import (
build_ibkr_strategy_context,
build_benchmark_history_inputs,
build_market_history_inputs,
build_semiconductor_rotation_inputs,
fetch_option_chain_snapshot,
fetch_portfolio_snapshot,
)
from quant_platform_kit.strategy_contracts import (
StrategyDecision,
StrategyEntrypoint,
StrategyRuntimeAdapter,
apply_runtime_policy_to_runtime_config,
build_execution_timing_metadata,
build_account_state_from_portfolio_snapshot,
build_portfolio_snapshot_from_account_state,
build_strategy_context_from_available_inputs,
build_strategy_evaluation_inputs,
)
from runtime_config_support import PlatformRuntimeSettings
from strategy_loader import (
load_strategy_definition,
load_strategy_entrypoint_for_profile,
load_strategy_runtime_adapter_for_profile,
)
DEFAULT_CASH_RESERVE_RATIO = 0.03
DEFAULT_REBALANCE_THRESHOLD_RATIO = 0.02
_FEATURE_SNAPSHOT_INPUT = "feature_snapshot"
_MARKET_HISTORY_INPUT = "market_history"
_BENCHMARK_HISTORY_INPUT = "benchmark_history"
_DERIVED_INDICATORS_INPUT = "derived_indicators"
_PORTFOLIO_SNAPSHOT_INPUT = "portfolio_snapshot"
_OPTION_CHAIN_FETCH_RULES = {
"tqqq_leaps_growth_v1": {
"underlier": "TQQQ",
"rights": ("C",),
"min_dte": 540,
"max_dte": 930,
"target_dte": 730,
"strike_range_pct": (0.45, 1.30),
"max_expirations": 3,
"max_contracts": 72,
},
"qqq_leaps_growth_v1": {
"underlier": "QQQ",
"rights": ("C",),
"min_dte": 540,
"max_dte": 930,
"target_dte": 730,
"strike_range_pct": (0.45, 1.30),
"max_expirations": 3,
"max_contracts": 72,
},
"soxx_put_credit_spread_income_v1": {
"underlier": "SOXX",
"rights": ("P",),
"min_dte": 25,
"max_dte": 65,
"target_dte": 45,
"strike_range_pct": (0.65, 1.02),
"max_expirations": 3,
"max_contracts": 72,
},
}
def _get_direct_market_history_profiles() -> frozenset[str]:
try:
from hk_equity_strategies import get_direct_market_history_profiles
except (ImportError, AttributeError): # pragma: no cover - compatibility fallback
return frozenset()
return frozenset(
str(profile).strip().lower()
for profile in get_direct_market_history_profiles()
)
def _requires_materialized_market_history(strategy_profile: str) -> bool:
return str(strategy_profile or "").strip().lower() in _get_direct_market_history_profiles()
def _loaded_history_to_rows(history):
if (
hasattr(history, "items")
and not hasattr(history, "columns")
and not isinstance(history, Mapping)
):
return [
{"date": date_value, "close": close_value}
for date_value, close_value in history.items()
]
return history
@dataclass(frozen=True)
class StrategyEvaluationResult:
decision: StrategyDecision
metadata: Mapping[str, Any] = field(default_factory=dict)
@dataclass(frozen=True)
class LoadedStrategyRuntime:
entrypoint: StrategyEntrypoint
runtime_settings: PlatformRuntimeSettings
runtime_adapter: StrategyRuntimeAdapter
runtime_config: Mapping[str, Any] = field(default_factory=dict)
merged_runtime_config: Mapping[str, Any] = field(default_factory=dict)
status_icon: str = "🐤"
cash_reserve_ratio: float = DEFAULT_CASH_RESERVE_RATIO
rebalance_threshold_ratio: float = DEFAULT_REBALANCE_THRESHOLD_RATIO
cash_reserve_floor_usd: float = 0.0
logger: Callable[[str], None] = print
@property
def profile(self) -> str:
return self.entrypoint.manifest.profile
@property
def required_inputs(self) -> frozenset[str]:
return frozenset(self.entrypoint.manifest.required_inputs)
def _runtime_adapter_with_portfolio(
self,
runtime_adapter: StrategyRuntimeAdapter,
portfolio_snapshot: Any | None,
) -> StrategyRuntimeAdapter:
if portfolio_snapshot is None or runtime_adapter.portfolio_input_name:
return runtime_adapter
available_inputs = set(runtime_adapter.available_inputs or self.required_inputs)
available_inputs.update(self.required_inputs)
available_inputs.add(_PORTFOLIO_SNAPSHOT_INPUT)
return replace(
runtime_adapter,
available_inputs=frozenset(available_inputs),
portfolio_input_name=_PORTFOLIO_SNAPSHOT_INPUT,
)
def _fetch_portfolio_snapshot_for_context(self, ib, *, required: bool) -> Any | None:
if ib is None and not required:
return None
account_ids = tuple(self.runtime_settings.account_ids or ())
if required:
if account_ids:
return fetch_portfolio_snapshot(ib, account_ids=account_ids)
return fetch_portfolio_snapshot(ib)
try:
if account_ids:
return fetch_portfolio_snapshot(ib, account_ids=account_ids)
return fetch_portfolio_snapshot(ib)
except Exception as exc:
self.logger(
"strategy_dashboard_portfolio_snapshot_failed | "
f"profile={self.profile} error_type={type(exc).__name__} error={exc}"
)
return None
@staticmethod
def _attach_strategy_plugin_metadata(
portfolio_snapshot: Any | None,
strategy_plugin_signals,
) -> Any | None:
if portfolio_snapshot is None or not strategy_plugin_signals:
return portfolio_snapshot
return attach_strategy_plugin_metadata(portfolio_snapshot, tuple(strategy_plugin_signals or ()))
@staticmethod
def _normalize_symbols(symbols) -> tuple[str, ...]:
normalized = []
for symbol in symbols or ():
text = str(symbol or "").strip().upper()
if text:
normalized.append(text)
return tuple(dict.fromkeys(normalized))
def _build_price_fallback_symbol_list(
self,
decision: StrategyDecision,
*,
managed_symbols: tuple[str, ...],
current_holdings,
) -> tuple[str, ...]:
decision_symbols = [getattr(position, "symbol", "") for position in decision.positions]
candidates = [
*decision_symbols,
*(current_holdings or ()),
]
if not candidates:
candidates.extend(managed_symbols)
return self._normalize_symbols(candidates)
@staticmethod
def _extract_latest_positive_close(price_history) -> float | None:
if price_history is None:
return None
if isinstance(price_history, pd.DataFrame):
if price_history.empty:
return None
if "close" in price_history.columns:
series = price_history["close"]
else:
series = price_history.iloc[:, 0]
values = pd.to_numeric(series, errors="coerce").dropna()
values = values[values > 0]
if values.empty:
return None
return float(values.iloc[-1])
if isinstance(price_history, pd.Series):
values = pd.to_numeric(price_history, errors="coerce").dropna()
values = values[values > 0]
if values.empty:
return None
return float(values.iloc[-1])
values = []
try:
iterator = iter(price_history)
except TypeError:
iterator = iter((price_history,))
for item in iterator:
if isinstance(item, Mapping):
candidate = item.get("close")
else:
candidate = getattr(item, "close", item)
try:
numeric = float(candidate)
except (TypeError, ValueError):
continue
if numeric > 0.0:
values.append(numeric)
return float(values[-1]) if values else None
@staticmethod
def _as_bool(value: Any, *, default: bool = False) -> bool:
if value is None:
return default
if isinstance(value, bool):
return value
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"1", "true", "yes", "y", "on"}:
return True
if normalized in {"0", "false", "no", "n", "off"}:
return False
return bool(value)
def _active_option_overlay_recipes(
self,
runtime_config: Mapping[str, Any],
portfolio_snapshot: Any | None,
) -> tuple[str, ...]:
total_equity = float(getattr(portfolio_snapshot, "total_equity", 0.0) or 0.0)
recipes = []
for family in ("growth", "income"):
prefix = f"option_{family}_overlay"
if not self._as_bool(runtime_config.get(f"{prefix}_enabled"), default=False):
continue
recipe = str(runtime_config.get(f"{prefix}_recipe") or "").strip()
if recipe not in _OPTION_CHAIN_FETCH_RULES:
continue
start_usd = float(runtime_config.get(f"{prefix}_start_usd") or 0.0)
if portfolio_snapshot is None or total_equity < max(0.0, start_usd):
continue
recipes.append(recipe)
return tuple(dict.fromkeys(recipes))
def _fetch_option_chains_for_runtime(
self,
ib,
runtime_config: Mapping[str, Any],
portfolio_snapshot: Any | None,
) -> dict[str, Any]:
if ib is None:
return {}
overlay_config = dict(self.merged_runtime_config)
overlay_config.update(dict(runtime_config or {}))
chains: dict[str, Any] = {}
for recipe in self._active_option_overlay_recipes(overlay_config, portfolio_snapshot):
rule = _OPTION_CHAIN_FETCH_RULES[recipe]
underlier = str(rule["underlier"])
try:
chains[underlier] = fetch_option_chain_snapshot(
ib,
underlier,
rights=tuple(rule["rights"]),
min_dte=int(rule["min_dte"]),
max_dte=int(rule["max_dte"]),
target_dte=int(rule["target_dte"]),
max_expirations=int(rule["max_expirations"]),
strike_range_pct=tuple(rule["strike_range_pct"]),
max_contracts=int(rule["max_contracts"]),
)
except Exception as exc:
self.logger(
"option_chain_fetch_failed | "
f"profile={self.profile} recipe={recipe} underlier={underlier} "
f"error_type={type(exc).__name__} error={exc}"
)
return chains
def _build_historical_close_map(
self,
ib,
historical_close_loader: Callable[..., Any],
symbols: tuple[str, ...],
) -> dict[str, float]:
close_map: dict[str, float] = {}
for symbol in self._normalize_symbols(symbols):
try:
price_history = historical_close_loader(
ib,
symbol,
duration="10 D",
bar_size="1 day",
)
except Exception as exc:
self.logger(
"historical_price_fallback_failed | "
f"profile={self.profile} symbol={symbol} error_type={type(exc).__name__} error={exc}"
)
continue
latest_close = self._extract_latest_positive_close(price_history)
if latest_close is not None:
close_map[symbol] = latest_close
return close_map
def _market_history_symbols(self) -> tuple[str, ...]:
raw_symbols = (
self.merged_runtime_config.get("universe_symbols")
or dict(getattr(self.entrypoint.manifest, "default_config", {}) or {}).get("universe_symbols")
or self.merged_runtime_config.get("managed_symbols")
or ()
)
if isinstance(raw_symbols, str):
raw_symbols = raw_symbols.replace(";", ",").split(",")
return tuple(
dict.fromkeys(
str(symbol).strip()
for symbol in raw_symbols
if str(symbol).strip()
)
)
def _configured_strategy_symbols(self, *, include_ranking_pool: bool = False) -> tuple[str, ...]:
candidates: list[str] = []
raw_managed = self.merged_runtime_config.get("managed_symbols", ())
if isinstance(raw_managed, str):
raw_managed = raw_managed.replace(";", ",").split(",")
candidates.extend(str(symbol) for symbol in raw_managed or ())
if include_ranking_pool:
raw_pool = self.merged_runtime_config.get("ranking_pool", ())
if isinstance(raw_pool, str):
raw_pool = raw_pool.replace(";", ",").split(",")
candidates.extend(str(symbol) for symbol in raw_pool or ())
safe_haven_symbol = str(self.merged_runtime_config.get("safe_haven") or "").strip()
if safe_haven_symbol and candidates:
candidates.append(safe_haven_symbol)
return tuple(
dict.fromkeys(
symbol.strip().upper()
for symbol in candidates
if symbol.strip()
)
)
def _project_portfolio_snapshot(self, portfolio_snapshot: Any | None, strategy_symbols) -> Any | None:
if portfolio_snapshot is None or not strategy_symbols:
return portfolio_snapshot
if not hasattr(portfolio_snapshot, "positions"):
return portfolio_snapshot
account_state = build_account_state_from_portfolio_snapshot(
portfolio_snapshot,
strategy_symbols=strategy_symbols,
)
account_state["total_strategy_equity"] = float(account_state["available_cash"]) + sum(
float(value) for value in dict(account_state["market_values"]).values()
)
return build_portfolio_snapshot_from_account_state(
account_state,
strategy_symbols=strategy_symbols,
as_of=getattr(portfolio_snapshot, "as_of", None),
metadata=getattr(portfolio_snapshot, "metadata", {}) or {},
)
def _build_market_history_inputs(
self,
ib,
historical_close_loader: Callable[..., Any],
) -> Mapping[str, Any]:
if not _requires_materialized_market_history(self.profile):
return build_market_history_inputs(historical_close_loader)
return {
_MARKET_HISTORY_INPUT: {
symbol: _loaded_history_to_rows(historical_close_loader(ib, symbol))
for symbol in self._market_history_symbols()
}
}
def _build_strategy_context(
self,
*,
runtime_adapter: StrategyRuntimeAdapter,
as_of: pd.Timestamp,
market_inputs: Mapping[str, Any],
portfolio_snapshot: Any | None,
runtime_config: Mapping[str, Any],
current_holdings,
ib,
):
context_adapter = self._runtime_adapter_with_portfolio(runtime_adapter, portfolio_snapshot)
available_inputs = set(context_adapter.available_inputs or self.required_inputs)
available_inputs.update(self.required_inputs)
if portfolio_snapshot is not None and context_adapter.portfolio_input_name:
available_inputs.add(context_adapter.portfolio_input_name)
evaluation_inputs = build_strategy_evaluation_inputs(
available_inputs=available_inputs,
market_inputs=market_inputs,
portfolio_snapshot=portfolio_snapshot,
)
capabilities = {}
if ib is not None:
capabilities["broker_client"] = ib
return build_strategy_context_from_available_inputs(
entrypoint=self.entrypoint,
runtime_adapter=context_adapter,
as_of=as_of,
available_inputs=evaluation_inputs,
runtime_config=runtime_config,
state={"current_holdings": tuple(current_holdings)},
capabilities=capabilities,
)
def evaluate(
self,
*,
ib,
current_holdings,
historical_close_loader: Callable[..., Any],
historical_candle_loader: Callable[..., Any] | None = None,
run_as_of: pd.Timestamp,
translator: Callable[[str], str],
pacing_sec: float,
strategy_plugin_signals=(),
) -> StrategyEvaluationResult:
run_as_of = pd.Timestamp(run_as_of).normalize()
if _FEATURE_SNAPSHOT_INPUT in self.required_inputs:
return self._evaluate_feature_snapshot_strategy(
ib=ib,
current_holdings=current_holdings,
historical_close_loader=historical_close_loader,
historical_candle_loader=historical_candle_loader,
run_as_of=run_as_of,
translator=translator,
pacing_sec=pacing_sec,
strategy_plugin_signals=strategy_plugin_signals,
)
if _MARKET_HISTORY_INPUT in self.required_inputs:
return self._evaluate_market_data_strategy(
ib=ib,
current_holdings=current_holdings,
historical_close_loader=historical_close_loader,
historical_candle_loader=historical_candle_loader,
run_as_of=run_as_of,
translator=translator,
pacing_sec=pacing_sec,
strategy_plugin_signals=strategy_plugin_signals,
)
if _PORTFOLIO_SNAPSHOT_INPUT in self.required_inputs and (
_DERIVED_INDICATORS_INPUT in self.required_inputs
or _BENCHMARK_HISTORY_INPUT in self.required_inputs
):
return self._evaluate_value_target_strategy(
ib=ib,
current_holdings=current_holdings,
historical_close_loader=historical_close_loader,
historical_candle_loader=historical_candle_loader,
run_as_of=run_as_of,
translator=translator,
pacing_sec=pacing_sec,
strategy_plugin_signals=strategy_plugin_signals,
)
raise ValueError(
f"Unsupported required_inputs for IBKR strategy profile {self.profile!r}: "
f"{', '.join(sorted(self.required_inputs)) or '<none>'}"
)
def _evaluate_market_data_strategy(
self,
*,
ib,
current_holdings,
historical_close_loader: Callable[..., Any],
historical_candle_loader: Callable[..., Any] | None,
run_as_of: pd.Timestamp,
translator: Callable[[str], str],
pacing_sec: float,
strategy_plugin_signals=(),
) -> StrategyEvaluationResult:
runtime_config = dict(self.runtime_config)
runtime_config.setdefault("translator", translator)
runtime_config.setdefault("pacing_sec", float(pacing_sec))
apply_runtime_policy_to_runtime_config(runtime_config, self.runtime_adapter)
requires_portfolio = (
_PORTFOLIO_SNAPSHOT_INPUT in self.required_inputs
or self.runtime_adapter.portfolio_input_name == _PORTFOLIO_SNAPSHOT_INPUT
)
portfolio_snapshot = self._fetch_portfolio_snapshot_for_context(
ib,
required=requires_portfolio,
)
portfolio_snapshot = self._project_portfolio_snapshot(
portfolio_snapshot,
self._configured_strategy_symbols(include_ranking_pool=True),
)
portfolio_snapshot = self._attach_strategy_plugin_metadata(portfolio_snapshot, strategy_plugin_signals)
option_chains = self._fetch_option_chains_for_runtime(ib, runtime_config, portfolio_snapshot)
if option_chains:
runtime_config["option_chains"] = option_chains
ctx = self._build_strategy_context(
runtime_adapter=self.runtime_adapter,
as_of=run_as_of,
market_inputs=self._build_market_history_inputs(ib, historical_close_loader),
portfolio_snapshot=portfolio_snapshot,
runtime_config=runtime_config,
current_holdings=current_holdings,
ib=ib,
)
decision = self.entrypoint.evaluate(ctx)
safe_haven_symbol = str(self.merged_runtime_config.get("safe_haven") or "").strip().upper() or None
managed_config_symbols = tuple(
str(symbol) for symbol in self.merged_runtime_config.get("managed_symbols", ())
)
ranking_pool = tuple(str(symbol) for symbol in self.merged_runtime_config.get("ranking_pool", ()))
managed_candidates = [*managed_config_symbols, *ranking_pool]
if safe_haven_symbol:
managed_candidates.append(safe_haven_symbol)
managed_symbols = tuple(dict.fromkeys(managed_candidates))
price_fallbacks = self._build_historical_close_map(
ib,
historical_close_loader,
self._build_price_fallback_symbol_list(
decision,
managed_symbols=managed_symbols,
current_holdings=current_holdings,
),
)
metadata = {
"strategy_profile": self.profile,
"managed_symbols": managed_symbols,
"status_icon": self.status_icon,
"dry_run_only": self.runtime_settings.dry_run_only,
**build_execution_timing_metadata(
signal_date=run_as_of,
signal_effective_after_trading_days=(
self.runtime_adapter.runtime_policy.signal_effective_after_trading_days
),
),
}
if portfolio_snapshot is not None:
metadata["portfolio_total_equity"] = float(getattr(portfolio_snapshot, "total_equity", 0.0) or 0.0)
if safe_haven_symbol:
metadata["safe_haven_symbol"] = safe_haven_symbol
if price_fallbacks:
metadata["price_fallbacks"] = price_fallbacks
metadata["dry_run_price_fallbacks"] = price_fallbacks
metadata["price_fallback_source"] = "historical_close"
return StrategyEvaluationResult(decision=decision, metadata=metadata)
def _evaluate_value_target_strategy(
self,
*,
ib,
current_holdings,
historical_close_loader: Callable[..., Any],
historical_candle_loader: Callable[..., Any] | None,
run_as_of: pd.Timestamp,
translator: Callable[[str], str],
pacing_sec: float,
strategy_plugin_signals=(),
) -> StrategyEvaluationResult:
runtime_config = dict(self.runtime_config)
runtime_config.setdefault("translator", translator)
apply_runtime_policy_to_runtime_config(runtime_config, self.runtime_adapter)
managed_symbols = self._configured_strategy_symbols()
portfolio_snapshot = self._fetch_portfolio_snapshot_for_context(ib, required=True)
portfolio_snapshot = self._project_portfolio_snapshot(portfolio_snapshot, managed_symbols)
portfolio_snapshot = self._attach_strategy_plugin_metadata(portfolio_snapshot, strategy_plugin_signals)
option_chains = self._fetch_option_chains_for_runtime(ib, runtime_config, portfolio_snapshot)
if option_chains:
runtime_config["option_chains"] = option_chains
market_inputs = self._build_value_target_market_inputs(
ib=ib,
historical_close_loader=historical_close_loader,
historical_candle_loader=historical_candle_loader,
)
ctx = build_ibkr_strategy_context(
entrypoint=self.entrypoint,
runtime_adapter=self.runtime_adapter,
as_of=run_as_of,
market_inputs=market_inputs,
portfolio_snapshot=portfolio_snapshot,
runtime_config=runtime_config,
current_holdings=current_holdings,
ib=ib,
)
decision = self.entrypoint.evaluate(ctx)
safe_haven_symbol = next(
(position.symbol for position in decision.positions if position.role == "safe_haven"),
None,
)
price_fallbacks = self._build_historical_close_map(
ib,
historical_close_loader,
self._build_price_fallback_symbol_list(
decision,
managed_symbols=managed_symbols,
current_holdings=current_holdings,
),
)
metadata = {
"strategy_profile": self.profile,
"managed_symbols": managed_symbols,
"status_icon": self.status_icon,
"dry_run_only": self.runtime_settings.dry_run_only,
"portfolio_total_equity": float(portfolio_snapshot.total_equity),
**build_execution_timing_metadata(
signal_date=run_as_of,
signal_effective_after_trading_days=(
self.runtime_adapter.runtime_policy.signal_effective_after_trading_days
),
),
}
if safe_haven_symbol:
metadata["safe_haven_symbol"] = str(safe_haven_symbol)
benchmark_symbol = market_inputs.get("benchmark_symbol")
if benchmark_symbol:
metadata["benchmark_symbol"] = str(benchmark_symbol)
if price_fallbacks:
metadata["price_fallbacks"] = price_fallbacks
metadata["dry_run_price_fallbacks"] = price_fallbacks
metadata["price_fallback_source"] = "historical_close"
return StrategyEvaluationResult(decision=decision, metadata=metadata)
def _build_value_target_market_inputs(
self,
*,
ib,
historical_close_loader: Callable[..., Any],
historical_candle_loader: Callable[..., Any] | None,
) -> dict[str, Any]:
if _DERIVED_INDICATORS_INPUT in self.required_inputs:
return build_semiconductor_rotation_inputs(
ib,
historical_close_loader,
trend_ma_window=int(self.merged_runtime_config.get("trend_ma_window", 150)),
)
if _BENCHMARK_HISTORY_INPUT in self.required_inputs:
if historical_candle_loader is None:
raise ValueError(
f"IBKR strategy profile {self.profile!r} requires benchmark_history but no candle loader was provided"
)
benchmark_symbol = str(self.merged_runtime_config.get("benchmark_symbol") or "QQQ").strip().upper()
market_inputs = build_benchmark_history_inputs(
ib,
historical_candle_loader,
benchmark_symbol=benchmark_symbol,
)
market_inputs["benchmark_symbol"] = benchmark_symbol
return market_inputs
raise ValueError(
f"Unsupported value-target required_inputs for IBKR strategy profile {self.profile!r}: "
f"{', '.join(sorted(self.required_inputs)) or '<none>'}"
)
def _evaluate_feature_snapshot_strategy(
self,
*,
ib,
current_holdings,
historical_close_loader: Callable[..., Any],
historical_candle_loader: Callable[..., Any] | None,
run_as_of: pd.Timestamp,
translator: Callable[[str], str],
pacing_sec: float,
strategy_plugin_signals=(),
) -> StrategyEvaluationResult:
del pacing_sec
runtime_config_path = self.merged_runtime_config.get("runtime_config_path") or self.runtime_settings.strategy_config_path
benchmark_symbol = str(self.merged_runtime_config.get("benchmark_symbol") or "SPY").strip().upper()
portfolio_snapshot_holder: dict[str, Any] = {}
runtime_config = dict(self.runtime_config)
runtime_config.setdefault("translator", translator)
def build_available_inputs(feature_snapshot) -> Mapping[str, Any]:
requires_portfolio = (
_PORTFOLIO_SNAPSHOT_INPUT in self.required_inputs
or self.runtime_adapter.portfolio_input_name == _PORTFOLIO_SNAPSHOT_INPUT
)
portfolio_snapshot = self._fetch_portfolio_snapshot_for_context(
ib,
required=requires_portfolio,
)
portfolio_snapshot = self._attach_strategy_plugin_metadata(portfolio_snapshot, strategy_plugin_signals)
if portfolio_snapshot is not None:
portfolio_snapshot_holder["portfolio_snapshot"] = portfolio_snapshot
option_chains = self._fetch_option_chains_for_runtime(ib, runtime_config, portfolio_snapshot)
if option_chains:
runtime_config["option_chains"] = option_chains
market_inputs: dict[str, Any] = {_FEATURE_SNAPSHOT_INPUT: feature_snapshot}
if _MARKET_HISTORY_INPUT in self.required_inputs:
market_inputs.update(self._build_market_history_inputs(ib, historical_close_loader))
if _BENCHMARK_HISTORY_INPUT in self.required_inputs:
if historical_candle_loader is None:
raise ValueError(
f"IBKR strategy profile {self.profile!r} requires benchmark_history but no candle loader was provided"
)
market_inputs.update(
build_benchmark_history_inputs(
ib,
historical_candle_loader,
benchmark_symbol=benchmark_symbol,
)
)
return market_inputs
def build_context(request: FeatureSnapshotContextRequest):
portfolio_snapshot = portfolio_snapshot_holder.get("portfolio_snapshot")
runtime_adapter = self._runtime_adapter_with_portfolio(
request.runtime_adapter,
portfolio_snapshot,
)
available_inputs = dict(request.available_inputs)
if portfolio_snapshot is not None:
available_inputs[_PORTFOLIO_SNAPSHOT_INPUT] = portfolio_snapshot
capabilities = {}
if ib is not None:
capabilities["broker_client"] = ib
return build_strategy_context_from_available_inputs(
entrypoint=request.entrypoint,
runtime_adapter=runtime_adapter,
as_of=request.as_of,
available_inputs=available_inputs,
runtime_config=request.runtime_config,
state={"current_holdings": tuple(current_holdings)},
capabilities=capabilities,
)
def log_guard_metadata(guard_metadata: Mapping[str, Any]) -> None:
self.logger(
"snapshot_manifest_summary | "
f"profile={self.profile} decision={guard_metadata.get('snapshot_guard_decision')} "
f"snapshot_path={guard_metadata.get('snapshot_path')} "
f"snapshot_as_of={guard_metadata.get('snapshot_as_of')} "
f"snapshot_age_days={guard_metadata.get('snapshot_age_days')} "
f"snapshot_file_ts={guard_metadata.get('snapshot_file_timestamp')} "
f"manifest_path={guard_metadata.get('snapshot_manifest_path')} "
f"manifest_exists={guard_metadata.get('snapshot_manifest_exists')} "
f"manifest_contract={guard_metadata.get('snapshot_manifest_contract_version')} "
f"expected_config={runtime_config_path} "
f"expected_profile={self.profile}"
)
def build_extra_metadata(
feature_snapshot,
managed_symbols: tuple[str, ...],
_decision: StrategyDecision,
) -> Mapping[str, Any]:
price_fallbacks = self._build_snapshot_close_map(
feature_snapshot,
managed_symbols=managed_symbols,
)
return {
"trade_date": run_as_of.date().isoformat(),
"price_fallbacks": price_fallbacks,
"dry_run_price_fallbacks": price_fallbacks,
"price_fallback_source": "snapshot_close",
}
result = evaluate_feature_snapshot_strategy(
entrypoint=self.entrypoint,
runtime_adapter=self.runtime_adapter,
runtime_settings=FeatureSnapshotRuntimeSettings(
feature_snapshot_path=self.runtime_settings.feature_snapshot_path,
feature_snapshot_manifest_path=self.runtime_settings.feature_snapshot_manifest_path,
strategy_config_path=self.runtime_settings.strategy_config_path,
strategy_config_source=self.runtime_settings.strategy_config_source,
dry_run_only=self.runtime_settings.dry_run_only,
),
runtime_config=runtime_config,
merged_runtime_config=self.merged_runtime_config,
as_of=run_as_of,
base_managed_symbols=(),
status_icon=self.status_icon,
default_benchmark_symbol="SPY",
default_safe_haven_symbol="BOXX",
build_available_inputs=build_available_inputs,
context_builder=build_context,
snapshot_loader=load_feature_snapshot_guarded,
on_guard_metadata=log_guard_metadata,
extra_success_metadata=build_extra_metadata,
catch_evaluation_errors=True,
)
return StrategyEvaluationResult(decision=result.decision, metadata=result.metadata)
def _build_snapshot_close_map(
self,
feature_snapshot,
*,
managed_symbols: tuple[str, ...],
) -> dict[str, float]:
if not managed_symbols:
return {}
try:
frame = pd.DataFrame(feature_snapshot)
except Exception:
return {}
if frame.empty or "symbol" not in frame.columns or "close" not in frame.columns:
return {}
frame = frame.copy()
frame["symbol"] = frame["symbol"].astype(str).str.strip().str.upper()
frame = frame[frame["symbol"].isin({str(symbol).strip().upper() for symbol in managed_symbols})]
if frame.empty:
return {}
close_series = pd.to_numeric(frame["close"], errors="coerce")
frame = frame.assign(close_numeric=close_series)
frame = frame[frame["close_numeric"].notna() & frame["close_numeric"].gt(0)]
if frame.empty:
return {}
deduped = frame.drop_duplicates(subset=["symbol"], keep="last")
return {
str(row["symbol"]): float(row["close_numeric"])
for _, row in deduped.iterrows()
}
def load_runtime_parameters(self) -> dict[str, Any]:
runtime_loader = self.runtime_adapter.runtime_parameter_loader
if not callable(runtime_loader):
return {}
return dict(
runtime_loader(
config_path=self.runtime_settings.strategy_config_path,
logger=self.logger,
)
or {}
)
def load_strategy_runtime(
raw_profile: str | None,
*,
runtime_settings: PlatformRuntimeSettings,
logger: Callable[[str], None],
) -> LoadedStrategyRuntime:
strategy_definition = load_strategy_definition(raw_profile)
entrypoint = load_strategy_entrypoint_for_profile(strategy_definition.profile)
runtime_adapter = load_strategy_runtime_adapter_for_profile(strategy_definition.profile)
runtime = LoadedStrategyRuntime(
entrypoint=entrypoint,
runtime_adapter=runtime_adapter,
runtime_settings=runtime_settings,
logger=logger,
)
runtime_config: dict[str, Any] = {}
if _FEATURE_SNAPSHOT_INPUT in frozenset(entrypoint.manifest.required_inputs):
runtime_config = runtime.load_runtime_parameters()
merged_runtime_config = dict(entrypoint.manifest.default_config)
merged_runtime_config.update(runtime_config)
strategy_cash_reserve_ratio = float(
merged_runtime_config.get(
"execution_cash_reserve_ratio",
DEFAULT_CASH_RESERVE_RATIO,
)
)
strategy_rebalance_threshold_ratio = float(
merged_runtime_config.get(
"execution_rebalance_threshold_ratio",
merged_runtime_config.get(
"rebalance_threshold_ratio",
DEFAULT_REBALANCE_THRESHOLD_RATIO,
),
)
)
platform_cash_reserve_ratio = runtime_settings.reserved_cash_ratio
if platform_cash_reserve_ratio is not None:
strategy_cash_reserve_ratio = max(
strategy_cash_reserve_ratio,
float(platform_cash_reserve_ratio),
)
return LoadedStrategyRuntime(
entrypoint=entrypoint,
runtime_adapter=runtime_adapter,
runtime_settings=runtime_settings,
runtime_config=runtime_config,
merged_runtime_config=merged_runtime_config,
status_icon=runtime_adapter.status_icon,
cash_reserve_ratio=strategy_cash_reserve_ratio,
rebalance_threshold_ratio=max(0.0, strategy_rebalance_threshold_ratio),
cash_reserve_floor_usd=float(runtime_settings.reserved_cash_floor_usd or 0.0),
logger=logger,
)