-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalpha_engine.py
More file actions
3011 lines (2538 loc) · 136 KB
/
Copy pathalpha_engine.py
File metadata and controls
3011 lines (2538 loc) · 136 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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Regime-Adaptive Mean-Variance Optimization Strategy - Streamlit Dashboard
==========================================================================
"Alpha Dual Engine" v154.6 - Interactive Dashboard Edition
This module refactors the terminal-based alpha_dominator_v10.py into a
Streamlit dashboard with:
- Sidebar controls for strategy parameters
- Cached data loading and model training
- Tabbed interface for different analysis views
- Interactive visualizations
Author: Quantitative Research
Version: 10.0.0 (Streamlit Edition)
"""
import warnings
# Show each future-breakage warning once instead of blanket-silencing:
# pandas 3.0 broke this app in ways its FutureWarnings had been announcing.
warnings.filterwarnings('once', category=FutureWarning)
warnings.filterwarnings('once', category=DeprecationWarning)
warnings.filterwarnings('ignore', category=UserWarning)
import numpy as np
import pandas as pd
import yfinance as yf
from scipy.optimize import minimize
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.tree import DecisionTreeClassifier
import shap
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.patches import Patch
import seaborn as sns
from datetime import datetime
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
import copy
import logging
import io
import os
import sys
import platform
import threading
import time
import joblib
import streamlit as st
# Hosted-demo detection: Streamlit Community Cloud mounts the repo under
# /mount/src and provides ~1 GB RAM / shared CPU — far below the 8 GB the
# full configuration assumes. There we cap the Monte Carlo widget so the
# demo stays responsive; local runs keep the full 1,000,000-sim setup.
IS_HOSTED_DEMO = os.path.exists("/mount/src") or os.environ.get("HOSTNAME") == "streamlit"
MC_SIM_MAX = 100_000 if IS_HOSTED_DEMO else 1_000_000
MC_SIM_DEFAULT = 50_000 if IS_HOSTED_DEMO else 1_000_000
# Can the MLX backend actually load on this machine? Trying the import answers
# more than checking the OS name: it also catches Intel Macs, Python < 3.10,
# and a half-installed mlx (binding present but backend library missing).
# When it fails, the RL checkboxes are disabled and everything else still runs.
try:
import mlx.core as _mlx_probe # noqa: F401
RL_BACKEND_AVAILABLE = True
RL_BACKEND_ERROR = ""
except Exception as _mlx_err: # ImportError, or OSError for missing libmlx
RL_BACKEND_AVAILABLE = False
RL_BACKEND_ERROR = str(_mlx_err)
# One-at-a-time gate for anything that touches MLX plus the heavy compute
# sections. Streamlit starts each rerun on a new thread while the previous one
# may still be mid-backtest; MLX is not thread-safe (concurrent evals from two
# threads segfault — verified on both the Metal and CPU backends), so every
# model load and inference path must hold this lock.
_COMPUTE_LOCK = threading.RLock()
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
plt.style.use('seaborn-v0_8-whitegrid')
sns.set_palette("husl")
# =============================================================================
# STRATEGY CONFIGURATION
# =============================================================================
@dataclass
class StrategyConfig:
"""Strategy configuration for Alpha Dual Engine v154.6, refactored for balanced, high-return diversity."""
# 1. Volatility & Growth Configuration
target_volatility: float = 0.25 # Target 25% vol — allow higher volatility for alpha
risk_aversion: float = 0.03 # Low — favor returns over variance
max_single_weight: float = 0.30 # Strict 30% cap — forces diversity across growth anchors
volatility_penalty: float = 30.0 # Low penalty — let momentum drive allocation
# 2. Rebalancing with Fee Control
rebalance_period: int = 79 # Optimal period from 30-183d sweep: best Sharpe (0.99) + best drawdown (-34.3%)
min_rebalance_threshold: float = 0.12 # Fee Control: skip trade if turnover < 12%
# --- Existing Parameters (preserved and tuned) ---
ml_threshold: float = 0.55
sma_lookback: int = 200
rs_lookback: int = 126
momentum_3m_days: int = 63
momentum_6m_days: int = 126
volatility_lookback: int = 60
gold_cap_risk_on: float = 0.01
gold_cap_base: float = 0.01
min_growth_anchor: float = 0.40
ir_threshold: float = 0.5
crypto_cap: float = 0.10
total_crypto_cap: float = 0.15
crypto_floor_risk_on: float = 0.05
aggressive_ceiling: float = 0.95
entropy_lambda: float = 0.02
min_effective_n: float = 3.0
growth_anchor_penalty: float = 200.0
turnover_penalty: float = 0.3
lazy_drift_threshold: float = 0.03
ir_score_multiplier: float = 15.0
risk_free_rate: float = 0.04
overfit_gap_threshold: float = 0.12
underfit_threshold: float = 0.51
prob_ema_span: int = 10
constraint_tolerance: float = 0.001
anxiety_vix_threshold: float = 0.18
anxiety_ml_prob_threshold: float = 0.75
alert_background_color: str = '#FFCCCC'
min_position_display: float = 0.005
# =============================================================================
# DATA MANAGER
# =============================================================================
class DataManager:
"""Data acquisition with 7-Feature Set for Endgame Model."""
EQUITIES = ['QQQ', 'IWM', 'SMH', 'XBI', 'TAN', 'IGV']
FIXED_INCOME = ['TLT', 'IEF', 'SHY']
ALTERNATIVES = ['GLD']
CRYPTO = ['BTC-USD', 'ETH-USD']
GROWTH_ANCHORS = ['SMH', 'XBI', 'TAN', 'IGV']
BENCHMARK_TICKER = 'SPY'
VIX_TICKER = '^VIX'
def __init__(self, start_date: str = '2010-01-01', end_date: str = None, config: StrategyConfig = None):
self.start_date = start_date
self.end_date = end_date or datetime.now().strftime('%Y-%m-%d')
self.config = config or StrategyConfig()
self.all_tickers = self.EQUITIES + self.FIXED_INCOME + self.ALTERNATIVES + self.CRYPTO
self.prices, self.returns, self.features, self.vix = None, None, None, None
self.sma_200, self.above_sma, self.raw_momentum, self.relative_strength = None, None, None, None
self.information_ratio, self.asset_volatilities = None, None
def load_data(self, max_retries: int = 3) -> None:
logger.info(f"Loading data for {len(self.all_tickers)} assets")
# Capture the full asset universe once: self.all_tickers gets narrowed
# to whatever downloaded successfully below, so a retry must start from
# the complete list rather than an already-trimmed one.
full_asset_tickers = list(self.all_tickers)
# Always download SPY (benchmark) even if it's not a tradeable asset
download_tickers = list(set(full_asset_tickers + [self.BENCHMARK_TICKER, self.VIX_TICKER]))
for attempt in range(max_retries):
try:
data = yf.download(download_tickers, start=self.start_date, end=self.end_date,
auto_adjust=True, progress=False)
if isinstance(data.columns, pd.MultiIndex):
prices = data['Close'].copy()
else:
prices = data[['Close']].copy()
if self.VIX_TICKER in prices.columns:
self.vix = prices[self.VIX_TICKER].copy()
prices = prices.drop(columns=[self.VIX_TICKER])
else:
self.vix = prices['SPY'].pct_change().rolling(21).std() * np.sqrt(252) * 100
available = [t for t in full_asset_tickers if t in prices.columns]
self.all_tickers = available
# Keep SPY in prices for indicator calculation even if not tradeable
cols_to_keep = list(dict.fromkeys(available + [self.BENCHMARK_TICKER]))
cols_to_keep = [c for c in cols_to_keep if c in prices.columns]
prices = prices[cols_to_keep].ffill().bfill()
# Drop rows only where ALL columns are NaN, preserving lookback data
self.prices = prices.dropna(how='all')
self.returns = self.prices.pct_change().dropna()
# yfinance can return an empty/degenerate frame WITHOUT raising
# (e.g. a transient "database is locked" on its tz cache poisons
# the batch). Treat that as a failure so the retry/backoff below
# fires — otherwise we'd silently train on nothing.
if (self.BENCHMARK_TICKER not in self.prices.columns
or len(self.prices) < 100 or len(available) < 2):
raise RuntimeError(
f"yfinance returned unusable data: {self.prices.shape[0]} rows, "
f"{len(available)} assets (need SPY + >=2 assets, >=100 rows)")
self.vix = self.vix.reindex(self.prices.index).ffill().bfill()
self._calculate_indicators()
return
except Exception as e:
logger.warning(f"Attempt {attempt + 1} failed: {e}")
if attempt == max_retries - 1:
raise RuntimeError("Data loading failed")
# Backoff before retrying: immediate retries are useless
# against yfinance rate limiting (common on shared cloud IPs)
time.sleep(2 ** (attempt + 1))
def _calculate_indicators(self) -> None:
self.sma_200 = self.prices.rolling(self.config.sma_lookback).mean()
self.above_sma = self.prices > self.sma_200
mom_3m = self.prices.pct_change(self.config.momentum_3m_days)
mom_6m = self.prices.pct_change(self.config.momentum_6m_days)
self.raw_momentum = (mom_3m + mom_6m) / 2
self.asset_volatilities = self.returns.rolling(self.config.volatility_lookback).std() * np.sqrt(252)
spy_return = self.prices['SPY'].pct_change(self.config.rs_lookback)
self.relative_strength = pd.DataFrame(index=self.prices.index)
for ticker in self.all_tickers:
self.relative_strength[ticker] = self.prices[ticker].pct_change(self.config.rs_lookback) - spy_return
self.relative_strength = self.relative_strength.ffill().bfill()
self.information_ratio = pd.DataFrame(index=self.prices.index)
for ticker in self.all_tickers:
if ticker == 'SPY':
self.information_ratio[ticker] = 0.0
continue
active_ret = self.returns[ticker] - self.returns['SPY']
ir = (active_ret.rolling(self.config.rs_lookback).mean() * 252) / (
active_ret.rolling(self.config.rs_lookback).std() * np.sqrt(252)).replace(0, np.nan)
self.information_ratio[ticker] = ir
self.information_ratio = self.information_ratio.replace([np.inf, -np.inf], np.nan).ffill().bfill()
# "Winner-Takes-All" Cubed Momentum: (Price / 60-SMA)^3
# 1.10^3 = 1.33 but 1.05^3 = 1.15 — exponentially rewards top flyers, crushes mediocre
self.sma_60 = self.prices.rolling(60).mean()
raw_mom_ratio = (self.prices / self.sma_60).replace([np.inf, -np.inf], np.nan).ffill().bfill()
self.momentum_score = (raw_mom_ratio ** 3).replace([np.inf, -np.inf], np.nan).ffill().bfill()
# Price-above-50SMA indicator for Active HODL crypto scaling
self.sma_50 = self.prices.rolling(50).mean()
self.golden_cross = self.prices > self.sma_50 # True = Price > 50-SMA (used for BTC trigger)
# 30-day Log Returns for crypto ranking
self.log_returns_30d = np.log(self.prices / self.prices.shift(30)).replace([np.inf, -np.inf], np.nan).ffill().bfill()
# RSI-14 for Active-HODL crypto rotation (BTC vs ETH)
delta = self.prices.diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
rs = gain / loss.replace(0, np.nan)
self.rsi_14 = (100 - (100 / (1 + rs))).replace([np.inf, -np.inf], np.nan).ffill().bfill()
def engineer_features(self) -> pd.DataFrame:
"""Engineer 7 features to match the Endgame Model constraints."""
if self.prices is None:
raise ValueError("Load data first")
features = pd.DataFrame(index=self.prices.index)
# 1. Realized Volatility
features['realized_vol'] = self.vix / 100.0
# 2. Volatility Momentum
vix_shifted = self.vix.shift(21).replace(0, np.nan)
features['vol_momentum'] = (self.vix / vix_shifted - 1).clip(-0.5, 0.5)
# 3. Equity Risk Premium
spy_erp = 1.0 / (self.prices['SPY'] / self.prices['SPY'].rolling(252).mean())
features['equity_risk_premium'] = spy_erp - self.config.risk_free_rate
# 4. Trend Score (Scaled)
spy_sma = self.prices['SPY'].rolling(200).mean()
features['trend_score'] = ((self.prices['SPY'] - spy_sma) / spy_sma) * 100.0
# 5. Momentum (21d)
features['momentum_21d'] = self.prices['SPY'].pct_change(21).clip(-0.2, 0.2)
# 6. Cross-Asset Signal (QQQ vs SPY)
tech_proxy = self.prices.get('QQQ', self.prices['SPY'])
features['qqq_vs_spy'] = (tech_proxy.pct_change(63) - self.prices['SPY'].pct_change(63)).clip(-0.2, 0.2)
# 7. Bond Signal (TLT Momentum)
bond_proxy = self.prices.get('TLT', self.prices['SPY'])
features['tlt_momentum'] = bond_proxy.pct_change(21).clip(-0.1, 0.1)
features = features.replace([np.inf, -np.inf], np.nan).ffill().bfill()
self.features = features.dropna()
return self.features
def get_aligned_data(self) -> Tuple[pd.DataFrame, ...]:
idx = (self.prices.index.intersection(self.features.index).intersection(self.returns.index)
.intersection(self.sma_200.dropna().index).intersection(self.raw_momentum.dropna().index)
.intersection(self.relative_strength.dropna().index).intersection(self.information_ratio.dropna().index)
.intersection(self.momentum_score.dropna().index)
.intersection(self.golden_cross.dropna().index).intersection(self.log_returns_30d.dropna().index)
.intersection(self.rsi_14.dropna().index))
return (self.prices.loc[idx], self.returns.loc[idx], self.features.loc[idx], self.vix.loc[idx],
self.sma_200.loc[idx], self.above_sma.loc[idx], self.raw_momentum.loc[idx],
self.relative_strength.loc[idx], self.asset_volatilities.loc[idx], self.information_ratio.loc[idx],
self.momentum_score.loc[idx], self.golden_cross.loc[idx], self.log_returns_30d.loc[idx],
self.rsi_14.loc[idx])
def get_asset_categories(self) -> Dict[str, List[str]]:
return {'equities': [t for t in self.EQUITIES if t in self.all_tickers],
'fixed_income': [t for t in self.FIXED_INCOME if t in self.all_tickers],
'alternatives': [t for t in self.ALTERNATIVES if t in self.all_tickers],
'crypto': [t for t in self.CRYPTO if t in self.all_tickers],
'safe_haven': [t for t in ['GLD', 'TLT', 'IEF', 'SHY'] if t in self.all_tickers],
'gold': ['GLD'] if 'GLD' in self.all_tickers else [],
'bonds_cash': [t for t in ['TLT', 'IEF', 'SHY'] if t in self.all_tickers],
'all': self.all_tickers}
# =============================================================================
# ADAPTIVE REGIME CLASSIFIER
# =============================================================================
class AdaptiveRegimeClassifier:
"""
THE ENDGAME: Consensus Ensemble + Monotonic Constraints.
Includes SHAP visualization and Model Health Dashboard.
"""
def __init__(self, config: StrategyConfig = None):
self.config = config or StrategyConfig()
# MODEL A: The Aggressor (XGBoost)
self.model_alpha = XGBClassifier(
n_estimators=50,
max_depth=3,
learning_rate=0.05,
monotone_constraints=(-1, -1, 0, 1, 1, 1, 0),
subsample=0.7,
colsample_bytree=0.7,
reg_lambda=1.0,
random_state=42,
# all cores locally; capped on the shared-CPU cloud tier to
# soften platform throttling during cold-start training
n_jobs=2 if IS_HOSTED_DEMO else -1
)
# MODEL B: The Skeptic (Decision Tree)
self.model_beta = DecisionTreeClassifier(
max_depth=2,
min_samples_leaf=200,
random_state=99
)
self.feature_names: List[str] = []
self.train_scores: List[float] = []
self.test_scores: List[float] = []
self.oob_scores: List[float] = []
self.window_dates: List[datetime] = []
self.selected_rebalance_periods: List[int] = []
# SHAP storage
self.shap_values = None
self.shap_features = None
self.feature_importances_history = []
self.current_rebalance_period = 42
self.model_stability = 'UNKNOWN'
def walk_forward_train(self, features, returns, initial_train_years=5, step_months=12):
# --- CORRECTED FIX ---
# We check 'returns' because that is the name of the argument above
if features.empty or returns.empty:
logger.warning("Data is empty. Returning neutral probabilities.")
return pd.Series(0.5, index=features.index)
# ---------------------
logger.info("Starting adaptive walk-forward training (CONSENSUS ENGINE)")
self.feature_names = features.columns.tolist()
# Now we define target, so the rest of the code works
target = (returns.shift(-21).rolling(21).sum() > 0).astype(int).dropna()
valid_idx = features.index.intersection(target.index)
X, y = features.loc[valid_idx], target.loc[valid_idx]
probabilities = pd.Series(index=X.index, dtype=float)
dates = X.index
train_end_idx = max(dates.get_indexer([dates[0] + pd.DateOffset(years=initial_train_years)], method='ffill')[0],
500)
shap_values_list, shap_features_list = [], []
while train_end_idx < len(dates) - 42:
train_dates = dates[:train_end_idx]
test_dates = dates[train_end_idx:min(train_end_idx + 252, len(dates))]
if len(test_dates) < 42:
break
X_train, y_train = X.loc[train_dates], y.loc[train_dates]
X_test, y_test = X.loc[test_dates], y.loc[test_dates]
# Fit Both Models
self.model_alpha.fit(X_train, y_train)
self.model_beta.fit(X_train, y_train)
# CONSENSUS LOGIC
probs_a = self.model_alpha.predict_proba(X_test)[:, 1]
probs_b = self.model_beta.predict_proba(X_test)[:, 1]
test_trends = X_test['trend_score']
# Predict 1 ONLY if Both Agree > Threshold AND Trend > 0
test_preds = []
for pa, pb, t in zip(probs_a, probs_b, test_trends):
if pa > 0.55 and pb > 0.50 and t > 0:
test_preds.append(1)
else:
test_preds.append(0)
test_score = np.mean(test_preds == y_test)
# CALCULATE SNIPER SCORE (Precision)
buy_signals = [i for i, x in enumerate(test_preds) if x == 1]
if len(buy_signals) > 0:
wins = sum([1 for i in buy_signals if y_test.iloc[i] == 1])
sniper_score = wins / len(buy_signals)
else:
sniper_score = 1.0
self.train_scores.append(0.65)
self.test_scores.append(test_score)
self.window_dates.append(test_dates[0])
self.selected_rebalance_periods.append(63)
# Store Feature Importance (from Model A)
if hasattr(self.model_alpha, 'feature_importances_'):
self.feature_importances_history.append(
dict(zip(self.feature_names, self.model_alpha.feature_importances_)))
# SHAP Calculation
try:
if len(X_test) > 10:
sample_idx = np.random.choice(len(X_test), min(50, len(X_test)), replace=False)
X_sample = X_test.iloc[sample_idx]
explainer = shap.TreeExplainer(self.model_alpha)
shap_vals = explainer.shap_values(X_sample)
shap_values_list.append(shap_vals)
shap_features_list.append(X_sample)
except Exception:
pass
probabilities.loc[test_dates] = (probs_a + probs_b) / 2
logger.info(
f"Window {len(self.test_scores)} ({test_dates[0].year}): Acc={test_score:.3f} | Sniper Score={sniper_score:.3f}")
train_end_idx += int(252 * step_months / 12)
if shap_values_list:
self.shap_values = np.vstack(shap_values_list)
self.shap_features = pd.concat(shap_features_list)
# Calculate Model Stability
if self.test_scores:
test_scores_std = np.std(self.test_scores)
if test_scores_std < 0.10:
self.model_stability = 'HIGH'
elif test_scores_std < 0.15:
self.model_stability = 'MODERATE'
else:
self.model_stability = 'LOW'
return probabilities.ffill().ewm(span=10).mean()
def get_regime(self, ml_prob: float, spy_above_sma: bool, current_vol: float,
tlt_momentum: float = 0.0, equity_risk_premium: float = 0.0) -> str:
"""Bull Market Override — Pure Signal.
MASTER SWITCH: SPY > 200-SMA → RISK_ON. No exceptions. No vol guards.
SPY < 200-SMA → fall back to ML/vol logic.
"""
# MASTER SWITCH: SPY above 200-SMA = RISK_ON, period.
if spy_above_sma:
return 'RISK_ON'
# SPY below 200-SMA — use ML probability as tiebreaker
if ml_prob > 0.55:
return 'RISK_REDUCED'
return 'DEFENSIVE'
def get_shap_figure(self):
"""Generate SHAP summary plot as a figure."""
if self.shap_values is None:
return None
try:
fig, ax = plt.subplots(figsize=(10, 6))
shap.summary_plot(self.shap_values, self.shap_features, plot_type="bar", show=False)
plt.title('Consensus Model Features (XGBoost)', fontsize=12)
plt.tight_layout()
return fig
except Exception as e:
logger.error(f"SHAP Plot Error: {e}")
return None
def get_validation_curves_figure(self):
"""Generate Health Dashboard as a figure."""
if not self.train_scores:
return None
try:
fig, axes = plt.subplots(2, 1, figsize=(12, 10))
ax1, ax2 = axes
# Accuracy
ax1.plot(self.train_scores, label='Train (Ref)', color='blue', alpha=0.3)
ax1.plot(self.test_scores, label='Test (Consensus)', color='red', linewidth=2)
ax1.set_title("Consensus Accuracy Check")
ax1.legend()
ax1.grid(True, alpha=0.3)
# Feature Importance
if self.feature_importances_history:
df_feat = pd.DataFrame(self.feature_importances_history)
df_feat.plot(ax=ax2, alpha=0.7)
ax2.set_title("Feature Importance Over Time")
ax2.grid(True, alpha=0.3)
plt.tight_layout()
return fig
except Exception as e:
logger.error(f"Dash Plot Error: {e}")
return None
# =============================================================================
# ALPHA DOMINATOR OPTIMIZER
# =============================================================================
class AlphaDominatorOptimizer:
"""
Alpha Dual Engine v154.6: IR Filter + Growth Anchor + Shannon Entropy
"""
def __init__(
self,
assets: List[str],
asset_categories: Dict[str, List[str]],
config: StrategyConfig = None
):
self.assets = assets
self.asset_categories = asset_categories
self.n_assets = len(assets)
self.config = config or StrategyConfig()
self.equity_idx = [assets.index(a) for a in asset_categories.get('equities', []) if a in assets]
self.gold_idx = [assets.index(a) for a in asset_categories.get('gold', []) if a in assets]
self.bonds_cash_idx = [assets.index(a) for a in asset_categories.get('bonds_cash', []) if a in assets]
self.safe_haven_idx = [assets.index(a) for a in asset_categories.get('safe_haven', []) if a in assets]
self.crypto_idx = [assets.index(a) for a in asset_categories.get('crypto', []) if a in assets]
self.growth_anchor_idx = [
assets.index(a) for a in DataManager.GROWTH_ANCHORS
if a in assets
]
self.current_weights: Optional[np.ndarray] = None
logger.info(f"AlphaDominator: {self.n_assets} assets, growth_anchor_idx={self.growth_anchor_idx}, "
f"gold_idx={self.gold_idx}, crypto_idx={self.crypto_idx}")
def optimize(
self,
returns: pd.DataFrame,
raw_momentum: pd.Series,
information_ratio: pd.Series,
asset_volatilities: pd.Series,
regime: str,
above_sma: pd.Series,
ml_prob: float = 0.5,
momentum_score: pd.Series = None,
golden_cross: pd.Series = None,
log_returns_30d: pd.Series = None,
rsi_14: pd.Series = None
) -> Tuple[np.ndarray, bool, str, Dict]:
"""Partitioned Asset Strategy optimizer."""
# Store golden_cross and rsi_14 for bounds methods to access
self._current_golden_cross = golden_cross
self._current_rsi_14 = rsi_14
mean_ret = returns.mean() * 252
cov = returns.cov() * 252
# Calculate dynamic anchor based on ML conviction
dynamic_anchor = max(0.20, min(0.60, (ml_prob - 0.50) * 2.0))
# Get eligible mask: equities by SMA, crypto by Golden Cross
eligible_mask = self._get_eligible_mask(
information_ratio, above_sma, regime, momentum_score, golden_cross)
n_eligible = eligible_mask.sum()
logger.debug(f"Regime={regime}, Eligible={n_eligible}/{self.n_assets}, DynamicAnchor={dynamic_anchor:.1%}")
if n_eligible == 0:
logger.warning("No eligible assets, using fallback")
weights = self._safe_fallback(regime)
self.current_weights = weights.copy()
return weights, False, "fallback", {}
if n_eligible == 1:
weights = np.zeros(self.n_assets)
weights[eligible_mask] = 1.0
self.current_weights = weights.copy()
return weights, True, "single", self._calculate_diagnostics(weights, cov, information_ratio)
# Build objective and constraints based on regime
if regime == 'RISK_ON':
objective = self._build_risk_on_objective(raw_momentum, cov, information_ratio, eligible_mask,
dynamic_anchor, momentum_score)
bounds = self._get_risk_on_bounds(eligible_mask, asset_volatilities, momentum_score)
elif regime == 'RISK_REDUCED':
objective = self._build_risk_reduced_objective(mean_ret, cov, eligible_mask)
bounds = self._get_default_bounds(eligible_mask, asset_volatilities)
else:
objective = self._build_defensive_objective(cov, eligible_mask)
bounds = self._get_defensive_bounds(eligible_mask, above_sma)
constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1.0}]
# Add constraint to enforce total crypto cap (sum of BTC + ETH <= total_crypto_cap)
if self.crypto_idx:
crypto_idx = self.crypto_idx # Capture in closure
crypto_cap = self.config.total_crypto_cap
constraints.append({
'type': 'ineq',
'fun': lambda w, idx=crypto_idx, cap=crypto_cap: cap - sum(w[i] for i in idx)
})
# Risk-Budgeting Cap: SUM of (Growth Anchors + Crypto) must not exceed aggressive_ceiling
# This ensures at least 25% of portfolio is in non-aggressive assets
growth_anchor_idx = self.growth_anchor_idx
crypto_idx_for_cap = self.crypto_idx
aggressive_ceiling = self.config.aggressive_ceiling
constraints.append({
'type': 'ineq',
'fun': lambda w, ga_idx=growth_anchor_idx, cr_idx=crypto_idx_for_cap, ceiling=aggressive_ceiling:
ceiling - sum(w[i] for i in ga_idx) - sum(w[i] for i in cr_idx)
})
result, method = self._multi_start_optimize(objective, bounds, constraints, cov, eligible_mask, information_ratio)
if result is not None:
weights = np.maximum(result.x, 0)
weights = weights / weights.sum()
diagnostics = self._calculate_diagnostics(weights, cov, information_ratio)
self.current_weights = weights.copy()
return weights, True, method, diagnostics
else:
weights = self._growth_anchor_tilt(eligible_mask)
if weights is None:
weights = self._safe_fallback(regime)
self.current_weights = weights.copy()
return weights, False, "growth_tilt_fallback", self._calculate_diagnostics(weights, cov, information_ratio)
def _get_eligible_mask(
self,
information_ratio: pd.Series,
above_sma: pd.Series,
regime: str,
momentum_score: pd.Series = None,
golden_cross: pd.Series = None
) -> np.ndarray:
"""Partitioned eligibility with HODL crypto floor.
Partition 1 (Equity Momentum): Equities eligible if Price > 200-SMA.
Partition 2 (Crypto HODL): BTC/ETH are ALWAYS eligible (5% HODL floor).
Golden Cross only decides if they scale up to the 25% cap.
Partition 3 (Safety): TLT and GLD are ALWAYS eligible.
Fail-Safe: If no growth equities eligible, default 100% to TLT + crypto HODL.
"""
aligned_sma = above_sma.reindex(pd.Index(self.assets)).fillna(False)
eligible = np.zeros(self.n_assets, dtype=bool)
# --- Partition 1: Equity Momentum Engine — eligible if Price > 200-SMA ---
for idx in self.equity_idx:
if aligned_sma.values[idx]:
eligible[idx] = True
for idx in self.growth_anchor_idx:
if aligned_sma.values[idx]:
eligible[idx] = True
# --- Partition 2: Crypto HODL — ALWAYS eligible (never 0%) ---
for idx in self.crypto_idx:
eligible[idx] = True
# --- Partition 3: TLT and GLD are ALWAYS eligible ---
for idx in self.safe_haven_idx:
eligible[idx] = True
# --- DEFENSIVE regime: disable equities, keep safe havens + crypto HODL ---
if regime == 'DEFENSIVE':
for idx in self.equity_idx:
eligible[idx] = False
for idx in self.growth_anchor_idx:
eligible[idx] = False
# --- Fail-Safe: if no growth equities eligible, TLT + crypto HODL ---
growth_eq_eligible = any(eligible[idx] for idx in self.equity_idx + self.growth_anchor_idx)
if not growth_eq_eligible:
tlt_candidates = [i for i, a in enumerate(self.assets) if a == 'TLT']
if tlt_candidates:
eligible[tlt_candidates[0]] = True
for idx in self.safe_haven_idx:
eligible[idx] = True
logger.debug(f"Regime={regime}, Eligible={eligible.sum()}/{self.n_assets}")
return eligible
def _get_risk_on_bounds(self, eligible_mask: np.ndarray,
asset_volatilities: pd.Series = None,
momentum_score: pd.Series = None) -> List[Tuple[float, float]]:
"""RISK_ON bounds: Active HODL with BTC>50-SMA trigger + winner-takes-all RSI.
Floor: 5% combined crypto always.
Ceiling: If BTC price > 50-SMA → crypto cap = 15%. Else → 5%.
Rotation: Entire crypto bucket goes to whichever coin has higher RSI-14.
Gold: Hard 1% cap. Equity: Max 30% per asset.
"""
gc_active = getattr(self, '_current_golden_cross', None) # Now = Price > 50-SMA
rsi_active = getattr(self, '_current_rsi_14', None)
crypto_bounds = {}
eligible_crypto = [idx for idx in self.crypto_idx if eligible_mask[idx]]
hodl_floor = self.config.crypto_floor_risk_on # 5% total
full_cap = self.config.total_crypto_cap # 15%
if eligible_crypto:
# Check if BTC specifically is above its 50-SMA
btc_above_50 = False
if gc_active is not None:
aligned_gc = gc_active.reindex(pd.Index(self.assets)).fillna(False)
btc_idx_list = [idx for idx in eligible_crypto if self.assets[idx] == 'BTC-USD']
if btc_idx_list:
btc_above_50 = bool(aligned_gc.values[btc_idx_list[0]])
total_budget = full_cap if btc_above_50 else hodl_floor
# Winner-takes-all RSI rotation: entire bucket to highest RSI coin
if rsi_active is not None and len(eligible_crypto) == 2:
aligned_rsi = rsi_active.reindex(pd.Index(self.assets)).fillna(50.0)
rsi_vals = {idx: aligned_rsi.values[idx] for idx in eligible_crypto}
winner_idx = max(rsi_vals, key=rsi_vals.get)
loser_idx = min(rsi_vals, key=rsi_vals.get)
# Winner gets the entire budget, loser gets 0
crypto_bounds[winner_idx] = (total_budget, total_budget)
crypto_bounds[loser_idx] = (0.0, 0.0)
else:
# Single crypto or no RSI: equal split
per_coin = total_budget / max(len(eligible_crypto), 1)
for idx in eligible_crypto:
crypto_bounds[idx] = (per_coin, per_coin)
bounds = []
for i in range(self.n_assets):
if not eligible_mask[i]:
bounds.append((0.0, 0.0))
elif i in self.crypto_idx:
lo, hi = crypto_bounds.get(i, (0.0, 0.0))
bounds.append((lo, max(hi, lo)))
elif i in self.gold_idx:
bounds.append((0.0, self.config.gold_cap_risk_on))
elif i in self.bonds_cash_idx:
bounds.append((0.0, 0.15))
else:
bounds.append((0.0, self.config.max_single_weight))
return bounds
def _get_default_bounds(self, eligible_mask: np.ndarray, asset_volatilities: pd.Series = None) -> List[Tuple[float, float]]:
"""RISK_REDUCED bounds with HODL crypto floor."""
eligible_crypto = [idx for idx in self.crypto_idx if eligible_mask[idx]]
hodl_floor_per = self.config.crypto_floor_risk_on / max(len(eligible_crypto), 1)
bounds = []
for i in range(self.n_assets):
if not eligible_mask[i]:
bounds.append((0.0, 0.0))
elif i in self.crypto_idx:
bounds.append((hodl_floor_per, hodl_floor_per))
elif i in self.gold_idx:
bounds.append((0.0, self.config.gold_cap_base))
else:
bounds.append((0.01, self.config.max_single_weight))
return bounds
def _get_defensive_bounds(self, eligible_mask: np.ndarray, above_sma: pd.Series = None) -> List[Tuple[float, float]]:
"""DEFENSIVE bounds: safe havens + crypto HODL floor."""
eligible_crypto = [idx for idx in self.crypto_idx if eligible_mask[idx]]
hodl_floor_per = self.config.crypto_floor_risk_on / max(len(eligible_crypto), 1)
bounds = []
for i in range(self.n_assets):
if not eligible_mask[i]:
bounds.append((0.0, 0.0))
elif i in self.crypto_idx:
bounds.append((hodl_floor_per, hodl_floor_per))
else:
bounds.append((0.01, self.config.max_single_weight))
return bounds
def _build_risk_on_objective(
self,
raw_momentum: pd.Series,
cov: pd.DataFrame,
information_ratio: pd.Series,
eligible_mask: np.ndarray,
dynamic_anchor: float = 0.60,
momentum_score: pd.Series = None
) -> callable:
"""RISK_ON Objective: Maximize cubed momentum (Price/60-SMA)^3 + Entropy - Vol Penalty - Turnover."""
cov_arr = cov.values
config = self.config
# Primary signal: Cubed momentum — already (Price/60-SMA)^3 from _calculate_indicators
if momentum_score is not None:
mom_arr = momentum_score.reindex(pd.Index(self.assets)).fillna(1.0).values
else:
mom_arr = np.ones(self.n_assets)
old_weights = self.current_weights if self.current_weights is not None else np.zeros(self.n_assets)
def objective(w):
# Core reward: maximize weighted cubed momentum = dot(w, (Price/60-SMA)^3)
momentum_reward = np.dot(w, mom_arr) * config.ir_score_multiplier
# Shannon entropy for diversity
w_pos = w[w > 1e-6]
if len(w_pos) > 0:
entropy = -np.sum(w_pos * np.log(w_pos))
else:
entropy = 0
n_eligible = eligible_mask.sum()
max_entropy = np.log(n_eligible) if n_eligible > 1 else 1
norm_entropy = entropy / max_entropy
# Growth anchor floor penalty
growth_weight = sum(w[idx] for idx in self.growth_anchor_idx)
growth_penalty = max(0, config.min_growth_anchor - growth_weight) ** 2 * config.growth_anchor_penalty
# Volatility targeting penalty
port_vol = np.sqrt(np.dot(w.T, np.dot(cov_arr, w)))
vol_penalty = (port_vol - config.target_volatility)**2 * config.volatility_penalty
# Turnover brake
turnover = np.sum(np.abs(w - old_weights))
turnover_penalty = turnover * config.turnover_penalty
return -momentum_reward - config.entropy_lambda * norm_entropy + growth_penalty + turnover_penalty + vol_penalty
return objective
def _build_risk_reduced_objective(
self,
mean_ret: pd.Series,
cov: pd.DataFrame,
eligible_mask: np.ndarray
) -> callable:
"""RISK_REDUCED: Mean-variance optimization with risk aversion, volatility target, and turnover brake."""
mean_ret_arr = mean_ret.values
cov_arr = cov.values
config = self.config
old_weights = self.current_weights if self.current_weights is not None else np.zeros(self.n_assets)
def objective(w):
port_ret = np.dot(w, mean_ret_arr)
port_var = np.dot(w.T, np.dot(cov_arr, w))
utility = port_ret - 0.5 * config.risk_aversion * port_var
port_vol = np.sqrt(port_var)
vol_penalty = (port_vol - config.target_volatility)**2 * config.volatility_penalty
turnover = np.sum(np.abs(w - old_weights))
turnover_penalty = turnover * config.turnover_penalty
return -utility + turnover_penalty + vol_penalty
return objective
def _build_defensive_objective(
self,
cov: pd.DataFrame,
eligible_mask: np.ndarray
) -> callable:
"""DEFENSIVE: Minimum variance with volatility target and turnover brake."""
cov_arr = cov.values
config = self.config
old_weights = self.current_weights if self.current_weights is not None else np.zeros(self.n_assets)
def objective(w):
port_var = np.dot(w.T, np.dot(cov_arr, w))
port_vol = np.sqrt(port_var)
vol_penalty = (port_vol - config.target_volatility)**2 * config.volatility_penalty
turnover = np.sum(np.abs(w - old_weights))
turnover_penalty = turnover * config.turnover_penalty
return port_var + turnover_penalty + vol_penalty
return objective
def _multi_start_optimize(
self,
objective: callable,
bounds: List[Tuple[float, float]],
constraints: List[Dict],
cov: pd.DataFrame,
eligible_mask: np.ndarray,
information_ratio: pd.Series = None
) -> Tuple[Optional[object], str]:
"""Multi-start optimization with Turbo mode (2 smart starting points only)."""
starting_points = [
('momentum_tilt', self._momentum_tilt(eligible_mask, information_ratio)),
('growth_tilt', self._growth_anchor_tilt(eligible_mask)),
]
best_result = None
best_obj = float('inf')
best_method = None
for name, init_w in starting_points:
if init_w is None:
continue
init_w = np.clip(init_w, [b[0] for b in bounds], [b[1] for b in bounds])
if init_w.sum() > 0:
init_w = init_w / init_w.sum()
else:
continue
try:
result = minimize(
objective,
init_w,
method='SLSQP',
bounds=bounds,
constraints=constraints,
options={'maxiter': 1000, 'ftol': 1e-12}
)
if result.success and result.fun < best_obj:
best_result = result
best_obj = result.fun
best_method = name
except Exception as e:
logger.debug(f"Opt from {name} failed: {e}")
continue
return best_result, best_method or "none"
def _equal_eligible(self, eligible_mask: np.ndarray) -> np.ndarray:
"""Equal weight eligible."""
weights = np.zeros(self.n_assets)
n = eligible_mask.sum()
if n > 0:
weights[eligible_mask] = 1.0 / n
return weights
def _inv_vol_eligible(self, cov: pd.DataFrame, eligible_mask: np.ndarray) -> np.ndarray:
"""Inverse volatility."""
weights = np.zeros(self.n_assets)
vols = np.sqrt(np.diag(cov))
vols = np.maximum(vols, 1e-6)
if eligible_mask.sum() > 0:
eligible_vols = vols[eligible_mask]
inv_vols = 1.0 / eligible_vols
weights[eligible_mask] = inv_vols / inv_vols.sum()
return weights
def _apply_caps_and_renormalize(self, weights: np.ndarray) -> np.ndarray:
"""Apply gold and crypto caps, then renormalize while preserving caps."""
# Clamp gold and crypto to respect caps
if self.gold_idx:
for idx in self.gold_idx:
weights[idx] = min(weights[idx], self.config.gold_cap_risk_on)
if self.crypto_idx:
crypto_cap_per_asset = self.config.total_crypto_cap / len(self.crypto_idx)
for idx in self.crypto_idx:
weights[idx] = min(weights[idx], crypto_cap_per_asset)
# Re-normalize: scale only uncapped assets to preserve caps
capped_indices = set(self.gold_idx or []) | set(self.crypto_idx or [])
uncapped_indices = set(range(self.n_assets)) - capped_indices
capped_weight = sum(weights[idx] for idx in capped_indices)
uncapped_weight = sum(weights[idx] for idx in uncapped_indices)
# Handle edge case where capped weights >= 1.0 or all uncapped weights are zero
if capped_weight >= 1.0 - 1e-10 or uncapped_weight <= 1e-10:
# Fall back to equal weight among growth anchors
weights = np.zeros(self.n_assets)
if self.growth_anchor_idx: