-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComplete_Model_Python
More file actions
6672 lines (5353 loc) · 242 KB
/
Copy pathComplete_Model_Python
File metadata and controls
6672 lines (5353 loc) · 242 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
"""
COMPLETE ULTIMATE TRADING SYSTEM
=================================
The definitive trading platform with ALL features integrated:
CORE FEATURES:
- Interactive user input & custom ticker selection
- Real-time trading signals (BUY/SELL/HOLD)
- 5 Trading strategies (MA, Mean Reversion, RSI, BB, Momentum)
- Regime-aware strategy allocation
- Complete backtesting framework
- Walk-forward testing & validation
- Monte Carlo simulation
- 6+ Comprehensive visualizations
- Performance comparison tables
- Portfolio mode for multi-asset analysis
ADVANCED FEATURES:
- Multi-timeframe analysis (daily/weekly/monthly alignment)
- Machine learning regime prediction
- Automatic parameter optimization
- Portfolio optimization (Markowitz, Risk Parity)
- Enhanced backtesting with realistic costs
- Real-time alert system with export
- Advanced performance metrics
This is the complete, production-ready system.
"""
import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import warnings
from datetime import datetime, timedelta
from typing import Tuple, Dict, List, Optional
import seaborn as sns
import json
from scipy.optimize import minimize
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.preprocessing import StandardScaler
from dataclasses import dataclass
from enum import Enum
warnings.filterwarnings('ignore')
plt.style.use('seaborn-v0_8-darkgrid')
# ==================================================
# CONFIGURATION
# ==================================================
class Config:
"""Centralized configuration management"""
# Data Parameters
START_DATE = "2010-01-01"
DEFAULT_UNIVERSE = ["SPY", "QQQ", "IWM", "EFA", "EEM"]
# Strategy Parameters
LOOKBACK_MOM = 126 # ~6 months
TOP_N = 2
TARGET_VOL = 0.10
REB_FREQ = "ME" # Month End
VOL_LOOKBACK = 20
VOL_THRESHOLD = 0.20
REGIME_CONFIRM_DAYS = 5
# MA Parameters
MA_FAST = 50
MA_SLOW = 200
# Z-Score Parameters
ZSCORE_WINDOW = 20
ZSCORE_ENTRY = -1.0
ZSCORE_EXIT = 0.0
# RSI Parameters
RSI_PERIOD = 14
RSI_OVERSOLD = 30
RSI_OVERBOUGHT = 70
# Bollinger Bands Parameters
BB_PERIOD = 20
BB_STD = 2.0
# Performance Parameters
ROLL_WINDOW = 252
TRANSACTION_COST = 0.001 # 10 bps
# Walk-Forward Parameters
TRAIN_YEARS = 5
TEST_YEARS = 1
# Monte Carlo Parameters
MC_SIMULATIONS = 1000
MC_SAMPLE_SIZE = 252 # 1 year
# Multi-Timeframe Parameters
TIMEFRAMES = {
'daily': '1d',
'weekly': '1wk',
'monthly': '1mo'
}
# Alert Parameters
DRAWDOWN_ALERT_THRESHOLD = 0.05 # 5% drawdown triggers alert
# ML Parameters
ML_LOOKBACK_FEATURES = 60 # Days for feature calculation
ML_TRAIN_SIZE = 1000 # Minimum training samples
# Enhanced Backtesting Parameters
SLIPPAGE = 0.0005 # 5 bps
MARKET_IMPACT = 0.0002 # 2 bps
# Portfolio Optimization Parameters
RISK_FREE_RATE = 0.04 # 4% annual
MAX_POSITION_SIZE = 0.25 # 25% max per position
MIN_POSITION_SIZE = 0.01 # 1% min per position
# ==================================================
# ENUMS AND DATA CLASSES
# ==================================================
class Signal(Enum):
"""Trading signal enumeration"""
STRONG_BUY = 2
BUY = 1
HOLD = 0
SELL = -1
STRONG_SELL = -2
@dataclass
class Alert:
"""Alert data structure"""
timestamp: datetime
ticker: str
signal: Signal
strategy: str
price: float
confidence: float
message: str
timeframes_aligned: bool
@dataclass
class TradeRecommendation:
"""Trade recommendation structure"""
ticker: str
action: str # BUY, SELL, HOLD
current_price: float
target_price: float
stop_loss: float
position_size: float # As percentage of portfolio
confidence: float
timeframe_alignment: Dict[str, str]
strategies_agreeing: List[str]
regime: str
risk_reward_ratio: float
# ==================================================
# DATA MANAGEMENT
# ==================================================
# ==================================================
# DATA VALIDATION & FETCHING
# ==================================================
class DataManager:
"""Manage data fetching and validation for securities"""
@staticmethod
def validate_ticker(ticker: str) -> Tuple[bool, str]:
"""Validate if ticker exists and has data"""
try:
stock = yf.Ticker(ticker)
info = stock.info
# Check if ticker is valid
if not info or 'regularMarketPrice' not in info:
return False, f"Ticker {ticker} not found or has no data"
return True, f"Valid ticker: {info.get('shortName', ticker)}"
except Exception as e:
return False, f"Error validating {ticker}: {str(e)}"
@staticmethod
def fetch_data(tickers: List[str], start_date: str,
end_date: Optional[str] = None) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Fetch historical price data for given tickers"""
try:
data = yf.download(
tickers,
start=start_date,
end=end_date,
auto_adjust=True,
progress=False
)
if len(tickers) == 1:
# For single ticker, extract Close column and convert to DataFrame
if "Close" in data.columns:
prices = pd.DataFrame(data["Close"])
prices.columns = [tickers[0]]
else:
# Handle case where Close is the only column
prices = pd.DataFrame(data)
if prices.shape[1] == 1:
prices.columns = [tickers[0]]
else:
# For multiple tickers
if isinstance(data.columns, pd.MultiIndex):
prices = data["Close"]
else:
prices = data
returns = prices.pct_change(fill_method=None).dropna()
return prices, returns
except Exception as e:
raise ValueError(f"Error fetching data: {str(e)}")
@staticmethod
def get_ticker_info(ticker: str) -> Dict:
"""Get detailed information about a ticker"""
try:
stock = yf.Ticker(ticker)
info = stock.info
return {
'name': info.get('shortName', ticker),
'sector': info.get('sector', 'N/A'),
'industry': info.get('industry', 'N/A'),
'market_cap': info.get('marketCap', 'N/A'),
'currency': info.get('currency', 'USD'),
'exchange': info.get('exchange', 'N/A')
}
except:
return {'name': ticker, 'sector': 'N/A', 'industry': 'N/A',
'market_cap': 'N/A', 'currency': 'USD', 'exchange': 'N/A'}
@staticmethod
def fetch_multi_timeframe(ticker: str, start_date: str) -> Dict[str, pd.DataFrame]:
"""Fetch data across multiple timeframes"""
data = {}
for name, interval in Config.TIMEFRAMES.items():
try:
raw_data = yf.download(
ticker,
start=start_date,
interval=interval,
auto_adjust=True,
progress=False
)
if not raw_data.empty and "Close" in raw_data.columns:
prices = pd.DataFrame(raw_data["Close"])
prices.columns = [ticker]
data[name] = prices
else:
data[name] = None
except Exception as e:
print(f"Could not fetch {name} data: {str(e)}")
data[name] = None
return data
# ==================================================
# UTILITY FUNCTIONS
# ==================================================
def safe_divide(numerator: pd.Series, denominator: pd.Series,
fill_value: float = 0.0) -> pd.Series:
"""Safely divide two series, handling zeros and NaNs"""
result = numerator / denominator
result = result.replace([np.inf, -np.inf], fill_value)
return result.fillna(fill_value)
def compute_zscore(series: pd.Series, window: int) -> pd.Series:
"""Compute rolling z-score"""
mean = series.rolling(window).mean()
std = series.rolling(window).std()
return safe_divide(series - mean, std)
def compute_returns(prices: pd.DataFrame, periods: int = 1) -> pd.DataFrame:
"""Compute returns with proper handling of missing data"""
return prices.pct_change(periods, fill_method=None)
def compute_rsi(prices: pd.Series, period: int = 14) -> pd.Series:
"""Compute Relative Strength Index"""
delta = prices.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = safe_divide(gain, loss, fill_value=100)
rsi = 100 - (100 / (1 + rs))
return rsi
def compute_bollinger_bands(prices: pd.Series, period: int = 20,
num_std: float = 2.0) -> Tuple[pd.Series, pd.Series, pd.Series]:
"""Compute Bollinger Bands"""
middle = prices.rolling(window=period).mean()
std = prices.rolling(window=period).std()
upper = middle + (std * num_std)
lower = middle - (std * num_std)
return upper, middle, lower
# ==================================================
# INSTITUTIONAL-GRADE PERFORMANCE ANALYTICS
# ==================================================
class PerformanceAnalytics:
"""
Comprehensive institutional-grade performance metrics
Features:
- Return metrics (Total, CAGR, Excess)
- Risk-adjusted ratios (Sharpe, Sortino, Calmar, Information, Omega)
- Drawdown analysis (Max, Average, Recovery, Ulcer Index)
- Distribution metrics (Skewness, Kurtosis, Tail risk)
- Trading metrics (Win rate, Profit factor, Expectancy, Payoff ratio)
- Risk metrics (VaR, CVaR, Downside deviation, Tracking error)
- Consistency metrics (Gain/Pain ratio, Sterling ratio, Burke ratio)
- Time-based analysis (Monthly/Yearly returns, Rolling metrics)
"""
# Risk-free rate for Sharpe/Sortino calculations
RISK_FREE_RATE = 0.04 # 4% annual
@staticmethod
def calculate_metrics(returns: pd.Series, benchmark: Optional[pd.Series] = None,
risk_free_rate: float = None) -> Dict[str, float]:
"""
Calculate comprehensive performance metrics
Args:
returns: Series of period returns
benchmark: Optional benchmark returns for relative metrics
risk_free_rate: Annual risk-free rate (default 4%)
Returns:
Dictionary with 40+ performance metrics
"""
if risk_free_rate is None:
risk_free_rate = PerformanceAnalytics.RISK_FREE_RATE
returns = returns.dropna()
if len(returns) == 0:
return PerformanceAnalytics._empty_metrics()
# Basic equity curve
equity = (1 + returns).cumprod()
# Initialize metrics dict
metrics = {}
# =====================================================
# SECTION 1: RETURN METRICS
# =====================================================
metrics['total_return'] = equity.iloc[-1] - 1
metrics['num_periods'] = len(returns)
metrics['num_years'] = len(returns) / 252
# CAGR (Compound Annual Growth Rate)
if len(returns) > 0:
metrics['cagr'] = (equity.iloc[-1] ** (252 / len(returns))) - 1
else:
metrics['cagr'] = 0
# Excess return over risk-free rate
daily_rf = risk_free_rate / 252
metrics['excess_return'] = metrics['cagr'] - risk_free_rate
# Average returns
metrics['avg_daily_return'] = returns.mean()
metrics['avg_monthly_return'] = returns.mean() * 21
metrics['avg_annual_return'] = returns.mean() * 252
# Geometric mean return
metrics['geometric_mean'] = ((1 + returns).prod() ** (252 / len(returns))) - 1
# =====================================================
# SECTION 2: VOLATILITY & RISK METRICS
# =====================================================
metrics['volatility'] = returns.std() * np.sqrt(252)
metrics['downside_volatility'] = PerformanceAnalytics._downside_deviation(returns, risk_free_rate)
# Tracking error (if benchmark provided)
if benchmark is not None:
aligned_bench = benchmark.reindex(returns.index).fillna(0)
tracking_diff = returns - aligned_bench
metrics['tracking_error'] = tracking_diff.std() * np.sqrt(252)
metrics['information_ratio'] = PerformanceAnalytics._information_ratio(
returns, aligned_bench
)
else:
metrics['tracking_error'] = 0
metrics['information_ratio'] = 0
# =====================================================
# SECTION 3: RISK-ADJUSTED RETURN RATIOS
# =====================================================
# Sharpe Ratio: (Return - RiskFree) / Volatility
excess_daily = returns.mean() - daily_rf
if returns.std() > 0:
metrics['sharpe'] = (excess_daily / returns.std()) * np.sqrt(252)
else:
metrics['sharpe'] = 0
# Sortino Ratio: (Return - RiskFree) / Downside Volatility
if metrics['downside_volatility'] > 0:
metrics['sortino'] = metrics['excess_return'] / metrics['downside_volatility']
else:
metrics['sortino'] = 0
# Calmar Ratio: CAGR / Max Drawdown
drawdown_series = PerformanceAnalytics.get_drawdown_series(returns)
max_dd = abs(drawdown_series.min())
metrics['max_drawdown'] = -max_dd
if max_dd > 0:
metrics['calmar'] = metrics['cagr'] / max_dd
else:
metrics['calmar'] = 0
# Omega Ratio: Probability-weighted gains vs losses
metrics['omega'] = PerformanceAnalytics._omega_ratio(returns, risk_free_rate)
# Gain-to-Pain Ratio: Sum(gains) / Sum(|losses|)
metrics['gain_to_pain'] = PerformanceAnalytics._gain_to_pain(returns)
# Sterling Ratio: CAGR / Average Max Drawdown (3 years)
metrics['sterling'] = PerformanceAnalytics._sterling_ratio(returns, drawdown_series)
# Burke Ratio: CAGR / Square root of sum of squared drawdowns
metrics['burke'] = PerformanceAnalytics._burke_ratio(returns, drawdown_series)
# =====================================================
# SECTION 4: DRAWDOWN ANALYSIS
# =====================================================
metrics['avg_drawdown'] = drawdown_series[drawdown_series < 0].mean()
metrics['max_drawdown_duration'] = PerformanceAnalytics._max_drawdown_duration(drawdown_series)
metrics['avg_drawdown_duration'] = PerformanceAnalytics._avg_drawdown_duration(drawdown_series)
metrics['recovery_factor'] = PerformanceAnalytics._recovery_factor(
metrics['total_return'], max_dd
)
metrics['ulcer_index'] = PerformanceAnalytics._ulcer_index(drawdown_series)
# Pain Index: Average of squared drawdowns
metrics['pain_index'] = (drawdown_series ** 2).mean() * 100
# =====================================================
# SECTION 5: DISTRIBUTION METRICS
# =====================================================
metrics['skewness'] = returns.skew()
metrics['kurtosis'] = returns.kurtosis()
metrics['excess_kurtosis'] = metrics['kurtosis'] - 3 # Excess over normal
# =====================================================
# SECTION 6: TAIL RISK METRICS
# =====================================================
metrics['var_95'] = returns.quantile(0.05) # 95% VaR
metrics['var_99'] = returns.quantile(0.01) # 99% VaR
metrics['cvar_95'] = returns[returns <= metrics['var_95']].mean() # Expected Shortfall
metrics['cvar_99'] = returns[returns <= metrics['var_99']].mean()
# Tail Ratio: 95th percentile / 5th percentile
metrics['tail_ratio'] = abs(returns.quantile(0.95) / returns.quantile(0.05))
# =====================================================
# SECTION 7: TRADING METRICS
# =====================================================
# Win rate and related
winners = returns[returns > 0]
losers = returns[returns < 0]
metrics['win_rate'] = len(winners) / len(returns) if len(returns) > 0 else 0
metrics['loss_rate'] = len(losers) / len(returns) if len(returns) > 0 else 0
# Average win/loss
metrics['avg_win'] = winners.mean() if len(winners) > 0 else 0
metrics['avg_loss'] = losers.mean() if len(losers) > 0 else 0
# Largest win/loss
metrics['largest_win'] = winners.max() if len(winners) > 0 else 0
metrics['largest_loss'] = losers.min() if len(losers) > 0 else 0
# Payoff Ratio: Average Win / Average Loss
if metrics['avg_loss'] != 0:
metrics['payoff_ratio'] = abs(metrics['avg_win'] / metrics['avg_loss'])
else:
metrics['payoff_ratio'] = 0
# Profit Factor: Gross Profit / Gross Loss
gross_profit = winners.sum()
gross_loss = abs(losers.sum())
if gross_loss > 0:
metrics['profit_factor'] = gross_profit / gross_loss
else:
metrics['profit_factor'] = 0
# Expectancy: (Win Rate × Avg Win) - (Loss Rate × |Avg Loss|)
metrics['expectancy'] = (
metrics['win_rate'] * metrics['avg_win'] +
metrics['loss_rate'] * metrics['avg_loss']
)
# =====================================================
# SECTION 8: CONSISTENCY METRICS
# =====================================================
# Percentage of positive days/periods
metrics['positive_periods_pct'] = metrics['win_rate']
# Longest winning/losing streaks
metrics['max_winning_streak'] = PerformanceAnalytics._max_streak(returns, positive=True)
metrics['max_losing_streak'] = PerformanceAnalytics._max_streak(returns, positive=False)
# =====================================================
# SECTION 9: TIME-BASED METRICS
# =====================================================
# Best/worst day
metrics['best_day'] = returns.max()
metrics['worst_day'] = returns.min()
# Best/worst month (approximate)
if len(returns) >= 21:
rolling_month = returns.rolling(21).sum()
metrics['best_month'] = rolling_month.max()
metrics['worst_month'] = rolling_month.min()
else:
metrics['best_month'] = 0
metrics['worst_month'] = 0
return metrics
@staticmethod
def _downside_deviation(returns: pd.Series, risk_free_rate: float) -> float:
"""Calculate downside deviation (semi-deviation below risk-free rate)"""
daily_rf = risk_free_rate / 252
downside_returns = returns[returns < daily_rf]
if len(downside_returns) == 0:
return 0
return np.sqrt(((downside_returns - daily_rf) ** 2).mean()) * np.sqrt(252)
@staticmethod
def _information_ratio(returns: pd.Series, benchmark: pd.Series) -> float:
"""Calculate Information Ratio: Excess return / Tracking error"""
excess = returns - benchmark
if excess.std() == 0:
return 0
return (excess.mean() / excess.std()) * np.sqrt(252)
@staticmethod
def _omega_ratio(returns: pd.Series, threshold: float) -> float:
"""
Calculate Omega Ratio
Omega = Sum of gains above threshold / Sum of losses below threshold
Better captures entire return distribution than Sharpe
"""
daily_threshold = threshold / 252
gains = returns[returns > daily_threshold] - daily_threshold
losses = daily_threshold - returns[returns < daily_threshold]
if losses.sum() == 0:
return 0
return gains.sum() / losses.sum()
@staticmethod
def _gain_to_pain(returns: pd.Series) -> float:
"""Calculate Gain-to-Pain Ratio: Sum(positive) / Sum(|negative|)"""
gains = returns[returns > 0].sum()
pains = abs(returns[returns < 0].sum())
if pains == 0:
return 0
return gains / pains
@staticmethod
def _sterling_ratio(returns: pd.Series, drawdown_series: pd.Series) -> float:
"""
Calculate Sterling Ratio
Sterling = CAGR / Average of worst N drawdowns
"""
cagr = ((1 + returns).prod() ** (252 / len(returns))) - 1
# Get worst drawdowns per year
years = len(returns) / 252
n_periods = max(1, int(years))
# Get N worst drawdowns
dd_values = drawdown_series[drawdown_series < 0]
if len(dd_values) == 0:
return 0
worst_dds = dd_values.nsmallest(min(n_periods, len(dd_values)))
avg_worst_dd = abs(worst_dds.mean())
if avg_worst_dd == 0:
return 0
return cagr / avg_worst_dd
@staticmethod
def _burke_ratio(returns: pd.Series, drawdown_series: pd.Series) -> float:
"""
Calculate Burke Ratio
Burke = CAGR / sqrt(sum of squared drawdowns)
"""
cagr = ((1 + returns).prod() ** (252 / len(returns))) - 1
squared_dd_sum = (drawdown_series ** 2).sum()
if squared_dd_sum == 0:
return 0
return cagr / np.sqrt(squared_dd_sum)
@staticmethod
def _max_drawdown_duration(drawdown_series: pd.Series) -> int:
"""Calculate maximum drawdown duration in periods"""
underwater = (drawdown_series < 0).astype(int)
# Find continuous underwater periods
underwater_diff = underwater.diff()
starts = drawdown_series.index[underwater_diff == 1].tolist()
ends = drawdown_series.index[underwater_diff == -1].tolist()
# Handle case where still underwater at end
if len(starts) > len(ends):
ends.append(drawdown_series.index[-1])
if len(starts) == 0:
return 0
# Calculate durations
durations = []
for start, end in zip(starts, ends):
duration = (drawdown_series.index.get_loc(end) -
drawdown_series.index.get_loc(start))
durations.append(duration)
return max(durations) if durations else 0
@staticmethod
def _avg_drawdown_duration(drawdown_series: pd.Series) -> float:
"""Calculate average drawdown duration"""
underwater = (drawdown_series < 0).astype(int)
# Find continuous underwater periods
underwater_diff = underwater.diff()
starts = drawdown_series.index[underwater_diff == 1].tolist()
ends = drawdown_series.index[underwater_diff == -1].tolist()
if len(starts) > len(ends):
ends.append(drawdown_series.index[-1])
if len(starts) == 0:
return 0
# Calculate durations
durations = []
for start, end in zip(starts, ends):
duration = (drawdown_series.index.get_loc(end) -
drawdown_series.index.get_loc(start))
durations.append(duration)
return np.mean(durations) if durations else 0
@staticmethod
def _recovery_factor(total_return: float, max_drawdown: float) -> float:
"""
Calculate Recovery Factor
Recovery = Net Profit / Max Drawdown
"""
if max_drawdown == 0:
return 0
return total_return / max_drawdown
@staticmethod
def _ulcer_index(drawdown_series: pd.Series) -> float:
"""
Calculate Ulcer Index
Ulcer = sqrt(mean of squared drawdowns)
Measures depth and duration of drawdowns
"""
return np.sqrt((drawdown_series ** 2).mean()) * 100
@staticmethod
def _max_streak(returns: pd.Series, positive: bool = True) -> int:
"""Calculate maximum winning or losing streak"""
if positive:
streak_series = (returns > 0).astype(int)
else:
streak_series = (returns < 0).astype(int)
# Count consecutive occurrences
streaks = []
current_streak = 0
for val in streak_series:
if val == 1:
current_streak += 1
else:
if current_streak > 0:
streaks.append(current_streak)
current_streak = 0
# Don't forget last streak
if current_streak > 0:
streaks.append(current_streak)
return max(streaks) if streaks else 0
@staticmethod
def _empty_metrics() -> Dict[str, float]:
"""Return empty metrics dictionary"""
keys = [
'total_return', 'num_periods', 'num_years', 'cagr', 'excess_return',
'avg_daily_return', 'avg_monthly_return', 'avg_annual_return', 'geometric_mean',
'volatility', 'downside_volatility', 'tracking_error', 'information_ratio',
'sharpe', 'sortino', 'calmar', 'omega', 'gain_to_pain', 'sterling', 'burke',
'max_drawdown', 'avg_drawdown', 'max_drawdown_duration', 'avg_drawdown_duration',
'recovery_factor', 'ulcer_index', 'pain_index',
'skewness', 'kurtosis', 'excess_kurtosis',
'var_95', 'var_99', 'cvar_95', 'cvar_99', 'tail_ratio',
'win_rate', 'loss_rate', 'avg_win', 'avg_loss', 'largest_win', 'largest_loss',
'payoff_ratio', 'profit_factor', 'expectancy',
'positive_periods_pct', 'max_winning_streak', 'max_losing_streak',
'best_day', 'worst_day', 'best_month', 'worst_month'
]
return {k: 0.0 for k in keys}
@staticmethod
def rolling_sharpe(returns: pd.Series, window: int = 252) -> pd.Series:
"""Calculate rolling Sharpe ratio"""
daily_rf = PerformanceAnalytics.RISK_FREE_RATE / 252
excess = returns - daily_rf
rolling_mean = excess.rolling(window).mean()
rolling_std = returns.rolling(window).std()
return safe_divide(rolling_mean, rolling_std) * np.sqrt(252)
@staticmethod
def get_drawdown_series(returns: pd.Series) -> pd.Series:
"""Calculate drawdown series"""
equity = (1 + returns).cumprod()
running_max = equity.expanding().max()
return (equity - running_max) / running_max
@staticmethod
def print_performance_report(metrics: Dict[str, float],
title: str = "PERFORMANCE REPORT"):
"""
Print formatted performance report
Args:
metrics: Dictionary from calculate_metrics()
title: Report title
"""
print("\n" + "="*80)
print(title.center(80))
print("="*80)
# Section 1: Returns
print("\nRETURN METRICS")
print("-" * 80)
print(f"Total Return: {metrics.get('total_return', 0):>12.2%}")
print(f"CAGR: {metrics.get('cagr', 0):>12.2%}")
print(f"Excess Return (over RF): {metrics.get('excess_return', 0):>12.2%}")
print(f"Geometric Mean: {metrics.get('geometric_mean', 0):>12.2%}")
# Section 2: Risk-Adjusted Returns
print("\nRISK-ADJUSTED RATIOS")
print("-" * 80)
print(f"Sharpe Ratio: {metrics.get('sharpe', 0):>12.2f}")
print(f"Sortino Ratio: {metrics.get('sortino', 0):>12.2f}")
print(f"Calmar Ratio: {metrics.get('calmar', 0):>12.2f}")
print(f"Omega Ratio: {metrics.get('omega', 0):>12.2f}")
print(f"Information Ratio: {metrics.get('information_ratio', 0):>12.2f}")
print(f"Gain-to-Pain Ratio: {metrics.get('gain_to_pain', 0):>12.2f}")
print(f"Sterling Ratio: {metrics.get('sterling', 0):>12.2f}")
# Section 3: Risk Metrics
print("\nRISK METRICS")
print("-" * 80)
print(f"Volatility (Annual): {metrics.get('volatility', 0):>12.2%}")
print(f"Downside Volatility: {metrics.get('downside_volatility', 0):>12.2%}")
print(f"Max Drawdown: {metrics.get('max_drawdown', 0):>12.2%}")
print(f"Average Drawdown: {metrics.get('avg_drawdown', 0):>12.2%}")
print(f"Ulcer Index: {metrics.get('ulcer_index', 0):>12.2f}")
print(f"VaR (95%): {metrics.get('var_95', 0):>12.2%}")
print(f"CVaR (95%): {metrics.get('cvar_95', 0):>12.2%}")
# Section 4: Trading Metrics
print("\nTRADING METRICS")
print("-" * 80)
print(f"Win Rate: {metrics.get('win_rate', 0):>12.2%}")
print(f"Profit Factor: {metrics.get('profit_factor', 0):>12.2f}")
print(f"Payoff Ratio: {metrics.get('payoff_ratio', 0):>12.2f}")
print(f"Expectancy: {metrics.get('expectancy', 0):>12.4f}")
print(f"Average Win: {metrics.get('avg_win', 0):>12.2%}")
print(f"Average Loss: {metrics.get('avg_loss', 0):>12.2%}")
# Section 5: Distribution
print("\nDISTRIBUTION METRICS")
print("-" * 80)
print(f"Skewness: {metrics.get('skewness', 0):>12.2f}")
print(f"Excess Kurtosis: {metrics.get('excess_kurtosis', 0):>12.2f}")
print(f"Tail Ratio: {metrics.get('tail_ratio', 0):>12.2f}")
# Section 6: Streaks
print("\nCONSISTENCY METRICS")
print("-" * 80)
print(f"Max Winning Streak: {metrics.get('max_winning_streak', 0):>12.0f} periods")
print(f"Max Losing Streak: {metrics.get('max_losing_streak', 0):>12.0f} periods")
print(f"Max DD Duration: {metrics.get('max_drawdown_duration', 0):>12.0f} periods")
print("="*80 + "\n")
# ==================================================
# REGIME DETECTION
# ==================================================
# ==================================================
# COMPREHENSIVE MARKET REGIME DETECTOR
# ==================================================
class MarketRegimeDetector:
"""
Advanced market regime detection system
Detects:
1. Volatility regimes (High/Low)
2. Trend regimes (Trending/Mean-Reverting)
3. Combined market states
Uses multiple indicators for robust classification
"""
def __init__(self, price: pd.Series, returns: pd.Series,
vol_lookback: int = 20,
trend_lookback: int = 50,
confirm_days: int = 3):
"""
Args:
price: Price series
returns: Returns series
vol_lookback: Period for volatility calculation
trend_lookback: Period for trend detection
confirm_days: Days to confirm regime change (reduces whipsaws)
"""
self.price = price
self.returns = returns
self.vol_lookback = vol_lookback
self.trend_lookback = trend_lookback
self.confirm_days = confirm_days
# Pre-calculate indicators
self._calculate_indicators()
def _calculate_indicators(self):
"""Pre-calculate all regime indicators"""
# Volatility measures
self.realized_vol = self.returns.rolling(self.vol_lookback).std() * np.sqrt(252)
self.vol_percentile = self.realized_vol.rolling(252).rank(pct=True)
# Trend measures
self.sma_50 = self.price.rolling(50).mean()
self.sma_200 = self.price.rolling(200).mean()
self.price_to_ma = self.price / self.sma_50
# ADX for trend strength
self.adx = self._calculate_adx(self.price, period=14)
# ATR for volatility
self.atr = self._calculate_atr(self.price, period=14)
# R-squared for trend quality
self.r_squared = self._calculate_r_squared(self.price, period=self.trend_lookback)
def _calculate_adx(self, price: pd.Series, period: int = 14) -> pd.Series:
"""Calculate Average Directional Index (ADX) - trend strength"""
high = price.rolling(period).max()
low = price.rolling(period).min()
# Simplified ADX
tr = high - low
directional_movement = price.diff().abs()
adx = (directional_movement.rolling(period).mean() /
(tr.rolling(period).mean() + 1e-10) * 100)
return adx.fillna(25) # Neutral value
def _calculate_atr(self, price: pd.Series, period: int = 14) -> pd.Series:
"""Calculate Average True Range (ATR)"""
high = price.rolling(period).max()
low = price.rolling(period).min()
tr = high - low
atr = tr.rolling(period).mean()
return atr / price # Normalized ATR
def _calculate_r_squared(self, price: pd.Series, period: int = 50) -> pd.Series:
"""
Calculate R-squared of linear regression
Measures how well price follows a linear trend
High R² = Strong trend
Low R² = Mean-reverting/choppy
"""
def rolling_r_squared(x):
if len(x) < 10:
return 0.5
y = x.values
n = len(y)
x_vals = np.arange(n)
# Linear regression
x_mean = x_vals.mean()
y_mean = y.mean()
numerator = ((x_vals - x_mean) * (y - y_mean)).sum()
denominator = np.sqrt(((x_vals - x_mean)**2).sum() * ((y - y_mean)**2).sum())
if denominator == 0:
return 0.5
r = numerator / denominator
return r ** 2
r_squared = price.rolling(period).apply(rolling_r_squared, raw=False)
return r_squared.fillna(0.5)
def detect_volatility_regime(self) -> pd.Series:
"""
Detect volatility regime: High or Low
Uses:
- Realized volatility percentile
- ATR
Returns:
Series with 'High Vol' or 'Low Vol'
"""
# Multiple volatility signals
vol_high_percentile = self.vol_percentile > 0.7 # Top 30%
vol_low_percentile = self.vol_percentile < 0.3 # Bottom 30%
atr_high = self.atr > self.atr.rolling(100).median()
# Classify
regime = pd.Series('Medium Vol', index=self.price.index)
regime[vol_high_percentile | atr_high] = 'High Vol'
regime[vol_low_percentile & ~atr_high] = 'Low Vol'
# Apply confirmation filter
return self._apply_hysteresis(regime)
def detect_trend_regime(self) -> pd.Series:
"""
Detect trend regime: Trending or Mean-Reverting
Uses:
- ADX (trend strength)
- R-squared (trend quality)
- Moving average alignment
Returns:
Series with 'Trending' or 'Mean-Reverting'
"""
# Multiple trend signals
adx_trending = self.adx > 25 # Standard ADX threshold