-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
7964 lines (7013 loc) · 416 KB
/
app.py
File metadata and controls
7964 lines (7013 loc) · 416 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
"""
Pre-Market Command Center v9.1
Institutional-Grade Market Prep Dashboard
AI Expert Analysis · Earnings Intelligence · Whale Tracker · Risk Turbulence
v9.0 COMPREHENSIVE UPGRADE:
- ENHANCED DATA RESILIENCE: Robust error handling across all data fetches
* Graceful degradation when data sources are unavailable
* Retry logic with exponential backoff for yfinance calls
* Defensive NaN/None handling in every calculation path
* Proper exception chaining and logging
- IMPROVED TECHNICAL ANALYSIS ENGINE:
* VWAP calculation for intraday analysis
* ATR-based dynamic stop calculation
* Multi-timeframe trend confluence scoring
* Enhanced volume profile analysis with VWAP deviation
* Fibonacci retracement levels in S/R calculation
* Improved RSI divergence detection
- UPGRADED MARKET INTELLIGENCE:
* Enhanced sector rotation model with momentum scoring
* Cross-asset correlation dashboard in Market Brief
* Improved fear/greed composite with VIX term structure
* Dollar-weighted breadth indicators
* Enhanced economic calendar with impact scoring
- PERFORMANCE OPTIMIZATIONS:
* Smarter cache TTLs based on market hours
* Batch yfinance downloads for sector scans
* Reduced redundant API calls via shared data pipeline
* Memory-efficient DataFrame operations
- UI/UX POLISH:
* Consistent Bloomberg terminal aesthetics throughout
* Enhanced sparkline micro-charts in summary cards
* Improved mobile responsiveness
* Better loading states and progress indicators
* Auto-refresh option for live market hours
Previous Versions:
- v8.4: Risk Turbulence tab, Bloomberg trade params UI
- v8.3: Redesigned AI Expert Analysis, clickable news
- v8.2: Fixed futures/indices, enhanced institutional analysis
Features:
- 🐋 Institutional Activity & Whale Tracker
- 📅 Earnings Center (calendar, analyzer, news)
- 📰 News Flow Analysis with clickable links
- 📈 Advanced Options Screener
- 🎯 AI-generated institutional-grade analysis
- 🧠 Smart Money indicators
- 🌊 Risk Turbulence & Convergence Early Warning
- 💹 Bloomberg Terminal-style Trade Parameters
- 📊 Cross-Asset Correlation Monitor
- 🔄 Enhanced Sector Rotation Model
"""
import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import pytz
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import requests
from bs4 import BeautifulSoup
import re
from urllib.parse import urlparse
import xml.etree.ElementTree as ET
import warnings
import io
from typing import Optional, Tuple, List, Dict, Any
from functools import lru_cache
import hashlib
import time as time_module
import logging
warnings.filterwarnings('ignore')
# Configure logging for debugging
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
# === UTILITY FUNCTIONS ===
def safe_div(numerator: float, denominator: float, default: float = 0.0) -> float:
"""Safely divide two numbers, returning default if denominator is zero or invalid."""
try:
if denominator is None or denominator == 0 or pd.isna(denominator):
return default
result = numerator / denominator
return default if pd.isna(result) or np.isinf(result) else result
except (TypeError, ZeroDivisionError, ValueError):
return default
def safe_pct_change(current: float, previous: float, default: float = 0.0) -> float:
"""Calculate percentage change safely."""
return safe_div((current - previous), previous, default) * 100
def safe_get(data: dict, key: str, default: Any = None) -> Any:
"""Safely get a value from a dict, handling None and NaN."""
try:
val = data.get(key, default)
if val is None or (isinstance(val, float) and (pd.isna(val) or np.isinf(val))):
return default
return val
except (AttributeError, TypeError):
return default
def safe_float(val: Any, default: float = 0.0) -> float:
"""Safely convert any value to float."""
if val is None:
return default
try:
result = float(val)
return default if pd.isna(result) or np.isinf(result) else result
except (ValueError, TypeError):
return default
def format_large_number(num: float, precision: int = 2) -> str:
"""Format large numbers with B/M/K suffixes."""
if num is None or pd.isna(num):
return "N/A"
try:
num = float(num)
if abs(num) >= 1e12:
return f"${num/1e12:.{precision}f}T"
elif abs(num) >= 1e9:
return f"${num/1e9:.{precision}f}B"
elif abs(num) >= 1e6:
return f"${num/1e6:.{precision}f}M"
elif abs(num) >= 1e3:
return f"${num/1e3:.{precision}f}K"
else:
return f"${num:.{precision}f}"
except (ValueError, TypeError):
return "N/A"
def calculate_vwap(hist: pd.DataFrame) -> Optional[pd.Series]:
"""Calculate Volume Weighted Average Price for intraday analysis."""
try:
if hist is None or hist.empty or 'Volume' not in hist.columns:
return None
typical_price = (hist['High'] + hist['Low'] + hist['Close']) / 3
cum_tp_vol = (typical_price * hist['Volume']).cumsum()
cum_vol = hist['Volume'].cumsum().replace(0, np.nan)
vwap = cum_tp_vol / cum_vol
return vwap
except Exception:
return None
def calculate_atr(hist: pd.DataFrame, period: int = 14) -> float:
"""Calculate Average True Range."""
try:
if hist is None or len(hist) < period + 1:
return 0.0
high = hist['High']
low = hist['Low']
close = hist['Close'].shift(1)
tr1 = high - low
tr2 = (high - close).abs()
tr3 = (low - close).abs()
tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
atr = tr.rolling(period).mean().iloc[-1]
return safe_float(atr, 0.0)
except Exception:
return 0.0
def calculate_fibonacci_levels(high: float, low: float, current: float) -> Dict[str, float]:
"""Calculate Fibonacci retracement/extension levels."""
diff = high - low
if diff <= 0:
return {}
levels = {
'Fib 0.0 (Low)': low,
'Fib 0.236': low + diff * 0.236,
'Fib 0.382': low + diff * 0.382,
'Fib 0.500': low + diff * 0.500,
'Fib 0.618': low + diff * 0.618,
'Fib 0.786': low + diff * 0.786,
'Fib 1.0 (High)': high,
'Fib 1.272': high + diff * 0.272,
'Fib 1.618': high + diff * 0.618,
}
return levels
def get_dynamic_cache_ttl() -> int:
"""Return cache TTL based on market hours - shorter during active trading."""
try:
eastern = pytz.timezone('US/Eastern')
now = datetime.now(eastern)
hour = now.hour
if now.weekday() >= 5: # Weekend
return 1800
if 4 <= hour < 9: # Pre-market
return 180
if 9 <= hour < 16: # Market hours
return 120
if 16 <= hour < 20: # After hours
return 300
return 900 # Overnight
except Exception:
return 300
# === STREAMLIT CONFIG ===
st.set_page_config(page_title="Pre-Market Command Center v9.1", page_icon="📈", layout="wide", initial_sidebar_state="collapsed")
# Enhanced session state initialization
_default_state = {
'selected_stock': None,
'show_stock_report': False,
'chart_tf': '5D',
'auto_refresh': False,
'last_refresh': None,
'watchlist_custom': [],
'comparison_mode': False,
}
for key, default in _default_state.items():
if key not in st.session_state:
st.session_state[key] = default
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=Inter:wght@400;500;600;700&display=swap');
.stApp { background: linear-gradient(180deg, #0d1117 0%, #161b22 100%); }
.main-title { font-family: 'Inter', sans-serif; font-size: 2.5rem; font-weight: 700; color: #ffffff; margin-bottom: 0; }
.subtitle { font-family: 'IBM Plex Mono', monospace; font-size: 0.85rem; color: #8b949e; margin-bottom: 1.5rem; }
.metric-card { background: linear-gradient(145deg, #21262d 0%, #161b22 100%); border: 1px solid #30363d; border-radius: 12px; padding: 1.25rem; margin: 0.5rem 0; transition: all 0.2s; }
.metric-card:hover { border-color: #58a6ff; }
.metric-label { font-family: 'IBM Plex Mono', monospace; font-size: 0.7rem; color: #8b949e; text-transform: uppercase; letter-spacing: 0.1em; }
.metric-value { font-family: 'Inter', sans-serif; font-size: 1.75rem; font-weight: 600; color: #ffffff; }
.positive { color: #3fb950 !important; }
.negative { color: #f85149 !important; }
.neutral { color: #8b949e !important; }
.summary-section { background: linear-gradient(145deg, #161b22 0%, #0d1117 100%); border: 1px solid #30363d; border-radius: 12px; padding: 1.5rem; margin: 1rem 0; }
.summary-header { font-family: 'Inter', sans-serif; font-size: 1.1rem; font-weight: 600; color: #58a6ff; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid #30363d; }
.news-item { background: #21262d; border-left: 3px solid #58a6ff; padding: 0.75rem 1rem; margin: 0.5rem 0; border-radius: 0 8px 8px 0; transition: all 0.2s ease; cursor: pointer; }
.news-item:hover { background: #30363d; border-left-color: #79c0ff; transform: translateX(2px); }
.news-title { font-family: 'Inter', sans-serif; font-size: 0.9rem; color: #ffffff; margin-bottom: 0.25rem; }
.news-title a { color: #ffffff; text-decoration: none; }
.news-title a:hover { color: #58a6ff; text-decoration: underline; }
.news-meta { font-family: 'IBM Plex Mono', monospace; font-size: 0.7rem; color: #8b949e; }
.news-link { display: block; text-decoration: none; color: inherit; }
.news-link:hover .news-title { color: #58a6ff; }
.sentiment-bullish { background: linear-gradient(90deg, #238636 0%, #2ea043 100%); color: white; padding: 0.5rem 1rem; border-radius: 8px; font-weight: 600; }
.sentiment-bearish { background: linear-gradient(90deg, #da3633 0%, #f85149 100%); color: white; padding: 0.5rem 1rem; border-radius: 8px; font-weight: 600; }
.sentiment-neutral { background: linear-gradient(90deg, #6e7681 0%, #8b949e 100%); color: white; padding: 0.5rem 1rem; border-radius: 8px; font-weight: 600; }
.event-card { background: #21262d; border: 1px solid #30363d; border-radius: 8px; padding: 1rem; margin: 0.5rem 0; }
.event-time { font-family: 'IBM Plex Mono', monospace; font-size: 0.75rem; color: #58a6ff; margin-bottom: 0.25rem; }
.event-title { font-family: 'Inter', sans-serif; font-size: 0.9rem; color: #ffffff; }
.event-impact-high { border-left: 3px solid #f85149; }
.event-impact-medium { border-left: 3px solid #d29922; }
.event-impact-low { border-left: 3px solid #3fb950; }
.calls-card { background: linear-gradient(145deg, #0d2818 0%, #0d1117 100%); border: 1px solid #238636; border-radius: 12px; padding: 1.25rem; }
.puts-card { background: linear-gradient(145deg, #2d1215 0%, #0d1117 100%); border: 1px solid #da3633; border-radius: 12px; padding: 1.25rem; }
.options-pick-card { background: linear-gradient(145deg, #21262d 0%, #161b22 100%); border: 1px solid #30363d; border-radius: 12px; padding: 1.25rem; margin: 0.75rem 0; }
.pick-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; padding-bottom: 0.5rem; border-bottom: 1px solid #30363d; }
.pick-symbol { font-family: 'IBM Plex Mono', monospace; font-size: 1.3rem; font-weight: 700; color: #ffffff; }
.pick-score { font-family: 'IBM Plex Mono', monospace; font-size: 1rem; padding: 0.3rem 0.8rem; border-radius: 6px; font-weight: 600; }
.score-excellent { background: linear-gradient(135deg, #238636 0%, #2ea043 100%); color: #ffffff; }
.score-good { background: linear-gradient(135deg, #1f6feb 0%, #388bfd 100%); color: #ffffff; }
.score-fair { background: linear-gradient(135deg, #9e6a03 0%, #d29922 100%); color: #ffffff; }
.score-weak { background: linear-gradient(135deg, #6e7681 0%, #8b949e 100%); color: #ffffff; }
.timestamp { font-family: 'IBM Plex Mono', monospace; font-size: 0.75rem; color: #6e7681; text-align: right; }
.market-status { display: inline-block; padding: 0.4rem 1rem; border-radius: 20px; font-family: 'IBM Plex Mono', monospace; font-size: 0.8rem; font-weight: 500; }
.status-premarket { background: #9e6a0320; color: #d29922; border: 1px solid #9e6a03; }
.status-open { background: #23863620; color: #3fb950; border: 1px solid #238636; }
.status-afterhours { background: #a371f720; color: #a371f7; border: 1px solid #8957e5; }
.status-closed { background: #6e768120; color: #8b949e; border: 1px solid #6e7681; }
.fear-greed-bar { height: 8px; border-radius: 4px; background: linear-gradient(90deg, #f85149 0%, #d29922 50%, #3fb950 100%); position: relative; margin: 1rem 0; }
.fear-greed-indicator { width: 4px; height: 16px; background: white; position: absolute; top: -4px; border-radius: 2px; }
.report-section { background: linear-gradient(145deg, #1c2128 0%, #161b22 100%); border: 1px solid #30363d; border-radius: 12px; padding: 1.5rem; margin: 1rem 0; }
.earnings-inline { border-left: 3px solid #d29922; }
.key-takeaway { background: #21262d; border-left: 3px solid #58a6ff; padding: 0.75rem 1rem; margin: 0.5rem 0; border-radius: 0 8px 8px 0; font-size: 0.9rem; color: #c9d1d9; }
.analyst-rating { display: inline-block; padding: 0.3rem 0.8rem; border-radius: 6px; font-family: 'IBM Plex Mono', monospace; font-size: 0.85rem; font-weight: 600; }
.rating-buy { background: #238636; color: white; }
.rating-hold { background: #9e6a03; color: white; }
.rating-sell { background: #da3633; color: white; }
.company-stat { text-align: center; padding: 0.75rem; }
.stat-value { font-family: 'Inter', sans-serif; font-size: 1.4rem; font-weight: 700; color: #ffffff; }
.stat-label { font-family: 'IBM Plex Mono', monospace; font-size: 0.65rem; color: #8b949e; text-transform: uppercase; }
.econ-indicator { background: #21262d; border-radius: 8px; padding: 0.75rem; margin: 0.25rem; text-align: center; }
.econ-value { font-size: 1.1rem; font-weight: 600; color: #ffffff; }
.econ-label { font-size: 0.65rem; color: #8b949e; }
.econ-change { font-size: 0.75rem; }
.risk-item { padding: 0.5rem; margin: 0.25rem 0; border-radius: 6px; font-size: 0.85rem; }
.risk-high { background: #da363320; border-left: 3px solid #f85149; }
.risk-medium { background: #9e6a0320; border-left: 3px solid #d29922; }
.opportunity-item { padding: 0.5rem; margin: 0.25rem 0; border-radius: 6px; font-size: 0.85rem; background: #1f6feb20; border-left: 3px solid #58a6ff; }
.signal-card { background: #21262d; border: 1px solid #30363d; border-radius: 8px; padding: 0.75rem; margin: 0.5rem 0; }
.signal-bullish { border-left: 3px solid #3fb950; }
.signal-bearish { border-left: 3px solid #f85149; }
.signal-neutral { border-left: 3px solid #8b949e; }
.signal-title { font-weight: 600; color: #ffffff; font-size: 0.9rem; }
.signal-detail { color: #8b949e; font-size: 0.8rem; margin-top: 0.25rem; }
.sr-level { display: flex; justify-content: space-between; padding: 0.4rem 0.75rem; margin: 0.25rem 0; border-radius: 6px; font-size: 0.85rem; }
.resistance-level { background: #da363320; border-left: 3px solid #f85149; }
.support-level { background: #23863620; border-left: 3px solid #3fb950; }
.current-price-level { background: #1f6feb30; border-left: 3px solid #58a6ff; font-weight: 600; }
.expert-analysis { background: linear-gradient(145deg, #1a1f2e 0%, #161b22 100%); border: 1px solid #30363d; border-radius: 12px; padding: 1.5rem; margin: 1rem 0; }
.expert-header { font-family: 'Inter', sans-serif; font-size: 1.1rem; font-weight: 600; color: #a371f7; margin-bottom: 1rem; }
.expert-verdict { font-size: 1.5rem; font-weight: 700; margin: 0.5rem 0; }
.expert-text { color: #c9d1d9; line-height: 1.6; font-size: 0.95rem; }
.earnings-card { background: linear-gradient(145deg, #21262d 0%, #161b22 100%); border: 1px solid #30363d; border-radius: 10px; padding: 1rem; margin: 0.5rem 0; transition: all 0.2s; }
.earnings-card:hover { border-color: #a371f7; }
.earnings-beat { border-left: 4px solid #3fb950; }
.earnings-miss { border-left: 4px solid #f85149; }
.earnings-meet { border-left: 4px solid #d29922; }
.whale-signal { background: rgba(163,113,247,0.1); border: 1px solid rgba(163,113,247,0.3); border-radius: 8px; padding: 0.5rem 1rem; margin: 0.25rem; display: inline-block; }
/* v9.0 Enhanced Styles */
@keyframes pulse-green { 0%, 100% { box-shadow: 0 0 0 0 rgba(63,185,80,0.4); } 50% { box-shadow: 0 0 0 6px rgba(63,185,80,0); } }
@keyframes pulse-red { 0%, 100% { box-shadow: 0 0 0 0 rgba(248,81,73,0.4); } 50% { box-shadow: 0 0 0 6px rgba(248,81,73,0); } }
@keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
.pulse-positive { animation: pulse-green 2s infinite; }
.pulse-negative { animation: pulse-red 2s infinite; }
.fade-in { animation: fadeIn 0.4s ease-out; }
.vwap-indicator { background: rgba(163,113,247,0.15); border: 1px solid rgba(163,113,247,0.4); border-radius: 8px; padding: 0.5rem 0.75rem; }
.correlation-matrix { background: #21262d; border: 1px solid #30363d; border-radius: 8px; padding: 1rem; }
.breadth-bar { height: 6px; border-radius: 3px; background: linear-gradient(90deg, #f85149 0%, #d29922 50%, #3fb950 100%); overflow: hidden; }
.sparkline-container { display: inline-block; vertical-align: middle; margin-left: 0.5rem; }
.regime-badge { padding: 0.2rem 0.6rem; border-radius: 12px; font-size: 0.7rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; }
.regime-green { background: rgba(63,185,80,0.2); color: #3fb950; }
.regime-yellow { background: rgba(210,153,34,0.2); color: #d29922; }
.regime-orange { background: rgba(240,136,62,0.2); color: #f0883e; }
.regime-red { background: rgba(248,81,73,0.2); color: #f85149; }
.terminal-row { background: #0d1117; border-left: 1px solid #333; border-right: 1px solid #333; padding: 0.5rem 1rem; font-family: 'Consolas', 'Monaco', monospace; }
.data-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 0.5rem; }
.mini-metric { background: rgba(22,27,34,0.7); border: 1px solid #30363d; border-radius: 6px; padding: 0.5rem; text-align: center; }
.tab-badge { background: rgba(88,166,255,0.2); color: #58a6ff; padding: 0.1rem 0.4rem; border-radius: 10px; font-size: 0.65rem; }
.live-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 4px; }
.live-dot-green { background: #3fb950; animation: pulse-green 1.5s infinite; }
.live-dot-red { background: #f85149; animation: pulse-red 1.5s infinite; }
</style>
""", unsafe_allow_html=True)
FUTURES_SYMBOLS = {"S&P 500": "ES=F", "Nasdaq 100": "NQ=F", "Dow Jones": "YM=F", "Russell 2000": "RTY=F", "Crude Oil": "CL=F", "Gold": "GC=F", "Silver": "SI=F", "Natural Gas": "NG=F", "VIX": "^VIX", "Dollar Index": "DX=F", "10Y Treasury": "^TNX", "Bitcoin": "BTC-USD", "Ethereum": "ETH-USD", "Copper": "HG=F"}
SECTOR_ETFS = {"Technology": {"symbol": "XLK", "stocks": ["AAPL", "MSFT", "NVDA", "AVGO", "AMD", "CRM", "ORCL", "ADBE"]}, "Financial": {"symbol": "XLF", "stocks": ["JPM", "BAC", "WFC", "GS", "MS", "C", "BLK", "SCHW"]}, "Energy": {"symbol": "XLE", "stocks": ["XOM", "CVX", "COP", "SLB", "EOG", "MPC", "PSX", "VLO"]}, "Healthcare": {"symbol": "XLV", "stocks": ["UNH", "JNJ", "LLY", "PFE", "ABBV", "MRK", "TMO", "ABT"]}, "Consumer Disc.": {"symbol": "XLY", "stocks": ["AMZN", "TSLA", "HD", "MCD", "NKE", "SBUX", "LOW", "TJX"]}, "Consumer Staples": {"symbol": "XLP", "stocks": ["PG", "KO", "PEP", "COST", "WMT", "PM", "MO", "CL"]}, "Industrials": {"symbol": "XLI", "stocks": ["CAT", "GE", "RTX", "UNP", "BA", "HON", "DE", "LMT"]}, "Materials": {"symbol": "XLB", "stocks": ["LIN", "APD", "SHW", "FCX", "NEM", "NUE", "DOW", "ECL"]}, "Utilities": {"symbol": "XLU", "stocks": ["NEE", "DUK", "SO", "D", "AEP", "SRE", "EXC", "XEL"]}, "Real Estate": {"symbol": "XLRE", "stocks": ["AMT", "PLD", "CCI", "EQIX", "SPG", "PSA", "O", "WELL"]}, "Communication": {"symbol": "XLC", "stocks": ["META", "GOOGL", "NFLX", "DIS", "CMCSA", "VZ", "T", "TMUS"]}}
FINANCE_CATEGORIES = {"Major Banks": ["JPM", "BAC", "WFC", "C", "USB", "PNC"], "Investment Banks": ["GS", "MS", "SCHW", "RJF"], "Insurance": ["BRK-B", "AIG", "MET", "PRU", "AFL", "TRV"], "Payments": ["V", "MA", "AXP", "PYPL", "SQ"], "Asset Managers": ["BLK", "BX", "KKR", "APO", "TROW"], "Fintech": ["PYPL", "SQ", "SOFI", "HOOD", "COIN"]}
OPTIONS_UNIVERSE = ["SPY", "QQQ", "IWM", "DIA", "XLF", "XLE", "XLK", "GLD", "SLV", "TLT", "AAPL", "MSFT", "NVDA", "GOOGL", "AMZN", "META", "TSLA", "AMD", "AVGO", "JPM", "BAC", "GS", "MS", "C", "WFC", "XOM", "CVX", "COP", "SLB", "UNH", "JNJ", "LLY", "PFE", "ABBV", "HD", "MCD", "NKE", "SBUX", "COST", "NFLX", "CRM", "ORCL", "V", "MA", "DIS", "COIN", "SOFI", "PLTR", "ARM"]
GLOBAL_INDICES = {"FTSE 100": "^FTSE", "DAX": "^GDAXI", "CAC 40": "^FCHI", "Nikkei 225": "^N225", "Hang Seng": "^HSI", "Shanghai": "000001.SS"}
NEWS_FEEDS = {"Reuters": "https://feeds.reuters.com/reuters/businessNews", "CNBC": "https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=100003114", "MarketWatch": "http://feeds.marketwatch.com/marketwatch/topstories"}
TIMEFRAMES = {"1D": ("1d", "5m"), "5D": ("5d", "15m"), "1M": ("1mo", "1h"), "3M": ("3mo", "1d"), "6M": ("6mo", "1d"), "1Y": ("1y", "1d"), "YTD": ("ytd", "1d")}
# === TECHNICAL ANALYSIS CONSTANTS ===
RSI_OVERBOUGHT = 70
RSI_OVERSOLD = 30
RSI_BULLISH = 60
RSI_BEARISH = 40
RSI_PERIOD = 14
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
BOLLINGER_PERIOD = 20
BOLLINGER_STD = 2
MA_SHORT = 20
MA_LONG = 50
VIX_HIGH = 25
VIX_ELEVATED = 20
VIX_LOW = 15
VOLUME_HIGH_MULTIPLIER = 2.0
VOLUME_EXTREME_MULTIPLIER = 3.0
SHORT_INTEREST_HIGH = 20
SHORT_INTEREST_ELEVATED = 10
INSTITUTIONAL_OWNERSHIP_HIGH = 70
INSTITUTIONAL_OWNERSHIP_VERY_HIGH = 90
INSTITUTIONAL_OWNERSHIP_LOW = 20
# Cache TTLs (in seconds)
CACHE_SHORT = 120 # 2 minutes - real-time data
CACHE_MEDIUM = 300 # 5 minutes - moderate updates
CACHE_LONG = 600 # 10 minutes - slower updates
CACHE_VERY_LONG = 1800 # 30 minutes - rarely changing data
# =====================================================
# RISK TURBULENCE & CONVERGENCE MODEL (PRO)
# Institutional-grade covariance turbulence early warning
# Uses ONLY free data sources (yfinance)
# =====================================================
# Default turbulence model configuration
TURB_DEFAULT_CONFIG = {
'min_points': 300,
'cov_window': 252, # 1 year covariance estimation
'mean_window': 252, # 1 year mean estimation
'corr_window': 60, # 3 month correlation window
'vol_window': 20, # 1 month realized vol window
'pct_window': 504, # 2 year rolling percentiles
'smooth': 5, # composite score smoothing
'ewma_lambda': 0.94, # EWMA decay factor
'shrink_floor': 0.05, # minimum shrinkage
'shrink_cap': 0.60, # maximum shrinkage
'ridge_eps': 1e-6, # numerical stability
'logistic_k': 1.35, # score mapping steepness
'clip_z': 4.0, # z-score clipping
'winsor_p': 0.01, # winsorization percentile
# Composite weights (auto-normalized)
'w_turb': 1.7, # Mahalanobis turbulence
'w_corr': 1.1, # avg abs correlation
'w_corr_jump': 1.0, # correlation matrix jump
'w_pc1': 1.1, # eigen concentration
'w_cov_mag': 1.0, # covariance magnitude
'w_vol': 0.7, # realized vol
'w_credit': 1.0, # credit stress (HYG-LQD spread)
'w_decouple': 0.9, # calm-before-storm detector
# Alert thresholds
'alert_score_jump_5d': 8.0,
'alert_score_level': 70.0,
'alert_turb_pct': 0.90,
'alert_corr_pct': 0.90,
'alert_vol_pct_max': 0.40,
}
# Default universe (liquid, diversified, free via yfinance)
TURB_DEFAULT_UNIVERSE = [
"SPY", # US large cap equities
"QQQ", # US tech/growth
"IWM", # US small cap
"TLT", # Long-term treasuries
"IEF", # Intermediate treasuries
"GLD", # Gold
"USO", # Oil proxy
"UUP", # USD index proxy
"HYG", # High yield credit
"LQD", # Investment grade credit
"BTC-USD", # Crypto risk proxy
]
def turb_resample_bday(df: pd.DataFrame) -> pd.DataFrame:
"""Resample dataframe to business days with forward fill."""
df = df.sort_index()
df = df[~df.index.duplicated(keep="last")]
idx = pd.date_range(df.index.min(), df.index.max(), freq="B")
return df.reindex(idx).ffill()
def turb_winsorize(s: pd.Series, p: float) -> pd.Series:
"""Winsorize series at percentile p and 1-p."""
if s.dropna().empty:
return s
lo = s.quantile(p)
hi = s.quantile(1 - p)
return s.clip(lo, hi)
def turb_zscore_rolling(s: pd.Series, window: int, winsor_p: float) -> pd.Series:
"""Rolling z-score with winsorization."""
s2 = turb_winsorize(s.astype(float), winsor_p)
m = s2.rolling(window, min_periods=int(window * 0.5)).mean()
sd = s2.rolling(window, min_periods=int(window * 0.5)).std(ddof=0).replace(0, np.nan)
return (s2 - m) / sd
def turb_logistic_0_100(z: pd.Series, k: float, clip: float) -> pd.Series:
"""Map z-score to 0-100 via logistic function."""
zc = z.clip(-clip, clip)
return 100.0 / (1.0 + np.exp(-k * zc))
def turb_rolling_percentile(series: pd.Series, window: int) -> pd.Series:
"""Calculate rolling percentile rank."""
def _pct(x: np.ndarray) -> float:
if len(x) < 5 or np.all(np.isnan(x)):
return np.nan
v = x[-1]
xs = x[~np.isnan(x)]
if len(xs) == 0:
return np.nan
return float(np.mean(xs <= v))
return series.rolling(window, min_periods=int(window * 0.3)).apply(_pct, raw=True)
def turb_avg_abs_corr(returns: pd.DataFrame) -> float:
"""Calculate average absolute correlation across assets."""
c = returns.corr()
vals = c.values
n = vals.shape[0]
if n < 2:
return np.nan
triu = vals[np.triu_indices(n, k=1)]
return float(np.nanmean(np.abs(triu)))
def turb_corr_matrix_jump_norm(c1: np.ndarray, c0: np.ndarray) -> float:
"""Frobenius norm of correlation matrix change (regime break detection)."""
if c1.shape != c0.shape:
return np.nan
diff = c1 - c0
return float(np.sqrt(np.nansum(diff * diff)))
def turb_pc1_share_from_cov(cov: np.ndarray) -> float:
"""Eigen concentration: PC1 explained share of total variance."""
if cov.ndim != 2 or cov.shape[0] != cov.shape[1]:
return np.nan
try:
vals = np.linalg.eigvalsh(cov)
except np.linalg.LinAlgError:
return np.nan
vals = np.clip(vals, 0, np.inf)
s = float(np.sum(vals))
if s <= 0:
return np.nan
return float(np.max(vals) / s)
def turb_add_ridge(cov: np.ndarray, ridge_scale: float) -> np.ndarray:
"""Add ridge regularization for numerical stability."""
d = np.nanmean(np.diag(cov))
if not np.isfinite(d) or d <= 0:
d = 1.0
return cov + np.eye(cov.shape[0]) * (ridge_scale * d)
def turb_cov_shrink_to_diag(sample_cov: np.ndarray, shrink: float, ridge_eps: float) -> np.ndarray:
"""Shrink sample covariance toward diagonal target."""
S = sample_cov.copy()
S = turb_add_ridge(S, ridge_eps)
D = np.diag(np.diag(S))
return (1.0 - shrink) * S + shrink * D
def turb_choose_shrinkage(sample_cov: np.ndarray, floor: float, cap: float) -> float:
"""Condition-aware heuristic shrinkage selection."""
try:
cond = np.linalg.cond(sample_cov)
except np.linalg.LinAlgError:
cond = 1e6
x = (min(max(cond, 1.0), 1000.0) - 30.0) / 300.0
shrink = floor + (cap - floor) * float(np.clip(x, 0.0, 1.0))
return float(shrink)
def turb_cov_ewma(returns_window: np.ndarray, lam: float, ridge_eps: float) -> np.ndarray:
"""EWMA covariance estimation."""
X = returns_window.copy()
X = X - np.nanmean(X, axis=0, keepdims=True)
X = np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0)
T, N = X.shape
C = np.eye(N) * 1e-6
for i in range(T):
r = X[i : i + 1].T
C = lam * C + (1.0 - lam) * (r @ r.T)
C = turb_add_ridge(C, ridge_eps)
return C
def turb_cov_blend(sample_cov: np.ndarray, ewma_cov: np.ndarray, shrink_cov: np.ndarray) -> np.ndarray:
"""Blend three covariance estimates: 40% shrink, 40% ewma, 20% sample."""
C = 0.40 * shrink_cov + 0.40 * ewma_cov + 0.20 * turb_add_ridge(sample_cov, 1e-6)
return C
@st.cache_data(ttl=3600, show_spinner=False)
def fetch_turbulence_prices(tickers: tuple, period: str = "5y") -> pd.DataFrame:
"""Fetch price data for turbulence model universe."""
try:
data = yf.download(
tickers=list(tickers),
period=period,
interval="1d",
auto_adjust=True,
progress=False,
group_by="ticker",
threads=True,
)
if isinstance(data.columns, pd.MultiIndex):
closes = data.xs("Close", axis=1, level=1)
else:
closes = data[["Close"]].copy()
closes.columns = [tickers[0]]
closes.index = pd.to_datetime(closes.index)
closes = turb_resample_bday(closes)
# Drop columns with too many missing values
keep = [c for c in closes.columns if closes[c].notna().mean() > 0.80]
return closes[keep]
except Exception as e:
return pd.DataFrame()
@st.cache_data(ttl=3600, show_spinner=False)
def compute_turbulence_model(prices_json: str, cfg: dict) -> dict:
"""
Compute full turbulence model.
Returns dict with:
- metrics: DataFrame with scores, regime, alerts
- diagnostics: DataFrame with raw indicators and z-scores
"""
import math
# Deserialize prices (use StringIO to prevent pandas interpreting string as filepath)
prices = pd.read_json(io.StringIO(prices_json), orient='split')
prices.index = pd.to_datetime(prices.index)
if len(prices) < cfg['min_points']:
return {'error': f"Insufficient data: {len(prices)} points, need {cfg['min_points']}"}
# Calculate log returns
rets = np.log(prices).diff()
idx = prices.index
# Credit stress proxy: HYG-LQD spread (free, no FRED required)
credit_spread = pd.Series(index=idx, dtype=float)
if 'HYG' in prices.columns and 'LQD' in prices.columns:
# Normalize and compute spread (higher = more stress)
hyg_ret = rets['HYG'].rolling(cfg['vol_window']).std() * np.sqrt(252)
lqd_ret = rets['LQD'].rolling(cfg['vol_window']).std() * np.sqrt(252)
credit_spread = (hyg_ret - lqd_ret).fillna(0) * 100 # Convert to pseudo-spread
credit_spread = credit_spread.clip(-5, 10) # Reasonable bounds
# VIX for implied vol (already in prices if available)
vix = pd.Series(index=idx, dtype=float)
if '^VIX' in prices.columns:
vix = prices['^VIX']
# Realized vol (system average)
rv = rets.rolling(cfg['vol_window']).std(ddof=0) * np.sqrt(252)
avg_rv = rv.mean(axis=1).rename("AVG_REALIZED_VOL")
# Initialize diagnostic series
turb = pd.Series(index=idx, dtype=float, name="TURBULENCE")
cov_trace = pd.Series(index=idx, dtype=float, name="COV_TRACE")
cov_frob = pd.Series(index=idx, dtype=float, name="COV_FROBENIUS")
pc1_share = pd.Series(index=idx, dtype=float, name="PC1_SHARE")
corr_jump = pd.Series(index=idx, dtype=float, name="CORR_JUMP_NORM")
avg_abs_corr = pd.Series(index=idx, dtype=float, name="AVG_ABS_CORR")
prev_corr = None
cov_mode = cfg.get('cov_mode', 'blend')
# Main computation loop
for t in range(cfg['cov_window'], len(idx)):
end = idx[t]
win_idx = idx[t - cfg['cov_window'] : t]
rwin_df = rets.loc[win_idx].dropna(how='all')
if rwin_df.shape[0] < int(cfg['cov_window'] * 0.7):
continue
# Fill NaN with 0 for computation
rwin_df = rwin_df.fillna(0)
# Mean estimation
mu_idx = idx[max(0, t - cfg['mean_window']) : t]
mu_df = rets.loc[mu_idx].fillna(0)
mu = mu_df.mean(axis=0).values
X = rwin_df.values
try:
sample_cov = np.cov(X, rowvar=False, ddof=0)
if sample_cov.ndim == 0:
sample_cov = np.array([[sample_cov]])
except Exception:
continue
# Robust covariance estimation
shrink = turb_choose_shrinkage(sample_cov, cfg['shrink_floor'], cfg['shrink_cap'])
shrink_cov = turb_cov_shrink_to_diag(sample_cov, shrink=shrink, ridge_eps=cfg['ridge_eps'])
ewma_cov = turb_cov_ewma(X, lam=cfg['ewma_lambda'], ridge_eps=cfg['ridge_eps'])
if cov_mode == "shrink":
cov = shrink_cov
elif cov_mode == "ewma":
cov = ewma_cov
else:
cov = turb_cov_blend(sample_cov, ewma_cov, shrink_cov)
# Mahalanobis turbulence
x = rets.loc[end].fillna(0).values
diff = x - mu
try:
inv = np.linalg.inv(cov)
except np.linalg.LinAlgError:
inv = np.linalg.pinv(cov)
md2 = float(diff.T @ inv @ diff)
turb.iloc[t] = math.sqrt(max(md2, 0.0))
# Covariance diagnostics
cov_trace.iloc[t] = float(np.trace(cov))
cov_frob.iloc[t] = float(np.linalg.norm(cov, ord="fro"))
pc1_share.iloc[t] = turb_pc1_share_from_cov(cov)
# Average absolute correlation
avg_abs_corr.iloc[t] = turb_avg_abs_corr(rwin_df.iloc[-cfg['corr_window']:])
# Correlation matrix and jump
diag = np.sqrt(np.clip(np.diag(cov), 1e-12, np.inf))
denom = np.outer(diag, diag)
corr = cov / denom
corr = np.clip(corr, -1.0, 1.0)
if prev_corr is not None and corr.shape == prev_corr.shape:
corr_jump.iloc[t] = turb_corr_matrix_jump_norm(corr, prev_corr)
prev_corr = corr
# Build diagnostics DataFrame
diag = pd.DataFrame(index=idx)
diag["TURBULENCE"] = turb
diag["AVG_ABS_CORR"] = avg_abs_corr
diag["CORR_JUMP_NORM"] = corr_jump
diag["PC1_SHARE"] = pc1_share
diag["COV_TRACE"] = cov_trace
diag["COV_FROBENIUS"] = cov_frob
diag["AVG_REALIZED_VOL"] = avg_rv
diag["CREDIT_SPREAD"] = credit_spread
diag["VIX"] = vix
# Implied vs realized mismatch
vix_ann = (vix / 100.0) if vix.notna().any() else pd.Series(index=idx, dtype=float)
diag["IMPL_MINUS_REAL"] = (vix_ann - avg_rv)
# Rolling percentiles
pw = cfg['pct_window']
diag["TURB_PCT"] = turb_rolling_percentile(diag["TURBULENCE"], pw)
diag["CORR_PCT"] = turb_rolling_percentile(diag["AVG_ABS_CORR"], pw)
diag["CJUMP_PCT"] = turb_rolling_percentile(diag["CORR_JUMP_NORM"], pw)
diag["PC1_PCT"] = turb_rolling_percentile(diag["PC1_SHARE"], pw)
diag["COVMAG_PCT"] = turb_rolling_percentile(diag["COV_FROBENIUS"], pw)
diag["VOL_PCT"] = turb_rolling_percentile(diag["AVG_REALIZED_VOL"], pw)
diag["CREDIT_PCT"] = turb_rolling_percentile(diag["CREDIT_SPREAD"], pw)
if vix.notna().any():
diag["VIX_PCT"] = turb_rolling_percentile(diag["VIX"], pw)
# Z-scores for score mapping
z = pd.DataFrame(index=idx)
z["z_turb"] = turb_zscore_rolling(diag["TURBULENCE"], pw, cfg['winsor_p'])
z["z_corr"] = turb_zscore_rolling(diag["AVG_ABS_CORR"], pw, cfg['winsor_p'])
z["z_cjump"] = turb_zscore_rolling(diag["CORR_JUMP_NORM"], pw, cfg['winsor_p'])
z["z_pc1"] = turb_zscore_rolling(diag["PC1_SHARE"], pw, cfg['winsor_p'])
z["z_covmag"] = turb_zscore_rolling(diag["COV_FROBENIUS"], pw, cfg['winsor_p'])
z["z_vol"] = turb_zscore_rolling(diag["AVG_REALIZED_VOL"], pw, cfg['winsor_p'])
z["z_credit"] = turb_zscore_rolling(diag["CREDIT_SPREAD"], pw, cfg['winsor_p'])
z["z_impl_mismatch"] = turb_zscore_rolling(diag["IMPL_MINUS_REAL"].fillna(0), pw, cfg['winsor_p'])
# Decoupling detector (calm-before-storm)
corr_high = diag["CORR_PCT"].fillna(0.5)
vol_low = 1.0 - diag["VOL_PCT"].fillna(0.5)
vix_low = (1.0 - diag.get("VIX_PCT", pd.Series(index=idx, dtype=float)).fillna(0.5))
mismatch01 = 1.0 / (1.0 + np.exp(-1.0 * z["z_impl_mismatch"].clip(-cfg['clip_z'], cfg['clip_z'])))
decouple01 = (0.45 * corr_high + 0.30 * vol_low + 0.25 * vix_low) * (0.6 + 0.4 * mismatch01)
diag["DECOUPLE_0_1"] = decouple01.clip(0, 1)
# Sub-scores (0-100)
sub = pd.DataFrame(index=idx)
sub["TURB_SCORE"] = turb_logistic_0_100(z["z_turb"], cfg['logistic_k'], cfg['clip_z'])
sub["CORR_SCORE"] = turb_logistic_0_100(z["z_corr"], cfg['logistic_k'], cfg['clip_z'])
sub["CORR_JUMP_SCORE"] = turb_logistic_0_100(z["z_cjump"], cfg['logistic_k'], cfg['clip_z'])
sub["PC1_SCORE"] = turb_logistic_0_100(z["z_pc1"], cfg['logistic_k'], cfg['clip_z'])
sub["COVMAG_SCORE"] = turb_logistic_0_100(z["z_covmag"], cfg['logistic_k'], cfg['clip_z'])
sub["VOL_SCORE"] = turb_logistic_0_100(z["z_vol"], cfg['logistic_k'], cfg['clip_z'])
sub["CREDIT_SCORE"] = turb_logistic_0_100(z["z_credit"], cfg['logistic_k'], cfg['clip_z'])
sub["DECOUPLE_SCORE"] = diag["DECOUPLE_0_1"] * 100.0
# Composite score (weighted average, auto-normalized)
weights = {
"TURB_SCORE": cfg['w_turb'],
"CORR_SCORE": cfg['w_corr'],
"CORR_JUMP_SCORE": cfg['w_corr_jump'],
"PC1_SCORE": cfg['w_pc1'],
"COVMAG_SCORE": cfg['w_cov_mag'],
"VOL_SCORE": cfg['w_vol'],
"CREDIT_SCORE": cfg['w_credit'],
"DECOUPLE_SCORE": cfg['w_decouple'],
}
available = [k for k in weights if k in sub.columns and sub[k].notna().any()]
wsum = sum(weights[k] for k in available) if available else 1.0
comp = None
contrib = pd.DataFrame(index=idx)
for k in available:
s = sub[k].ffill().fillna(50.0)
w = weights[k] / wsum
comp = s * w if comp is None else comp + s * w
contrib[k.replace("_SCORE", "_CONTRIB")] = s * w
sub["RISK_TURBULENCE_SCORE"] = comp.rolling(cfg['smooth']).mean() if comp is not None else pd.Series(50.0, index=idx)
sub["SCORE_5D_CHG"] = sub["RISK_TURBULENCE_SCORE"].diff(5)
sub["SCORE_1M_CHG"] = sub["RISK_TURBULENCE_SCORE"].diff(21)
# Regime labels
score = sub["RISK_TURBULENCE_SCORE"]
regime = pd.Series(index=idx, dtype=object)
regime[score < 35] = "GREEN"
regime[(score >= 35) & (score < 55)] = "YELLOW"
regime[(score >= 55) & (score < 70)] = "ORANGE"
regime[score >= 70] = "RED"
sub["REGIME"] = regime
# Alerts
alerts = pd.Series(index=idx, dtype=object)
turb_pct = diag["TURB_PCT"]
corr_pct = diag["CORR_PCT"]
vol_pct = diag["VOL_PCT"]
s5 = sub["SCORE_5D_CHG"]
for i in range(len(idx)):
msg = []
if pd.notna(s5.iloc[i]) and float(s5.iloc[i]) >= cfg['alert_score_jump_5d']:
msg.append(f"Score jump ≥{cfg['alert_score_jump_5d']:.0f} in 5d")
if pd.notna(score.iloc[i]) and float(score.iloc[i]) >= cfg['alert_score_level']:
msg.append(f"Score ≥{cfg['alert_score_level']:.0f}")
if pd.notna(turb_pct.iloc[i]) and float(turb_pct.iloc[i]) >= cfg['alert_turb_pct']:
msg.append("Turbulence ≥90th pct")
if (pd.notna(corr_pct.iloc[i]) and float(corr_pct.iloc[i]) >= cfg['alert_corr_pct'] and
pd.notna(vol_pct.iloc[i]) and float(vol_pct.iloc[i]) <= cfg['alert_vol_pct_max']):
msg.append("⚠️ CALM-BEFORE-STORM: high corr + low vol")
alerts.iloc[i] = " | ".join(msg) if msg else ""
sub["ALERTS"] = alerts
# Combine outputs
metrics = pd.concat([sub, contrib], axis=1)
diagnostics = pd.concat([diag, z.add_prefix("Z_")], axis=1)
return {
'metrics': metrics.to_json(orient='split', date_format='iso'),
'diagnostics': diagnostics.to_json(orient='split', date_format='iso'),
}
def render_turbulence_tab(st_module):
"""Render the Risk Turbulence & Convergence tab."""
st_module.markdown("### 🌊 Risk Turbulence & Convergence Early Warning")
st_module.markdown("<p style='color: #8b949e; font-size: 0.85rem;'>Institutional-grade covariance turbulence model detecting correlation regime breaks, diversification breakdown, and calm-before-storm conditions.</p>", unsafe_allow_html=True)
# Settings expander - values persist in session state automatically
with st_module.expander("⚙️ Model Settings", expanded=False):
st_module.markdown("**Universe & Data**")
cfg_cols = st_module.columns(2)
with cfg_cols[0]:
universe_input = st_module.text_area(
"Universe (comma-separated tickers):",
value=", ".join(TURB_DEFAULT_UNIVERSE),
height=68,
key="turb_universe"
)
with cfg_cols[1]:
cov_mode = st_module.selectbox(
"Covariance Estimation Mode:",
options=["blend", "shrink", "ewma"],
index=0,
key="turb_cov_mode"
)
data_period = st_module.selectbox(
"Historical Data Period:",
options=["3y", "5y", "7y"],
index=1,
key="turb_period"
)
st_module.markdown("**Windows (Trading Days)**")
win_cols = st_module.columns(4)
with win_cols[0]:
cov_window = st_module.number_input("Cov Window", min_value=60, max_value=504, value=252, step=21, key="turb_cov_win")
with win_cols[1]:
corr_window = st_module.number_input("Corr Window", min_value=20, max_value=126, value=60, step=5, key="turb_corr_win")
with win_cols[2]:
vol_window = st_module.number_input("Vol Window", min_value=5, max_value=63, value=20, step=5, key="turb_vol_win")
with win_cols[3]:
smooth = st_module.number_input("Smooth Factor", min_value=1, max_value=21, value=5, step=1, key="turb_smooth")
st_module.markdown("**Component Weights** (higher = more influence)")
w_cols = st_module.columns(4)
with w_cols[0]:
w_turb = st_module.slider("Turbulence", 0.0, 3.0, 1.7, 0.1, key="w_turb")
w_corr = st_module.slider("Correlation", 0.0, 3.0, 1.1, 0.1, key="w_corr")
with w_cols[1]:
w_pc1 = st_module.slider("PC1 Concentration", 0.0, 3.0, 1.1, 0.1, key="w_pc1")
w_cjump = st_module.slider("Corr Jump", 0.0, 3.0, 1.0, 0.1, key="w_cjump")
with w_cols[2]:
w_vol = st_module.slider("Realized Vol", 0.0, 3.0, 0.7, 0.1, key="w_vol")
w_credit = st_module.slider("Credit Stress", 0.0, 3.0, 1.0, 0.1, key="w_credit")
with w_cols[3]:
w_covmag = st_module.slider("Cov Magnitude", 0.0, 3.0, 1.0, 0.1, key="w_covmag")
w_decouple = st_module.slider("Decoupling", 0.0, 3.0, 0.9, 0.1, key="w_decouple")
st_module.markdown("**Alert Thresholds**")
alert_cols = st_module.columns(4)
with alert_cols[0]:
alert_score_level = st_module.number_input("Score Alert ≥", value=70.0, step=5.0, key="alert_score")
with alert_cols[1]:
alert_score_jump = st_module.number_input("5D Jump Alert ≥", value=8.0, step=1.0, key="alert_jump")
with alert_cols[2]:
alert_turb_pct = st_module.number_input("Turb Pct Alert ≥", value=0.90, step=0.05, key="alert_turb")
with alert_cols[3]:
alert_corr_pct = st_module.number_input("Corr Pct Alert ≥", value=0.90, step=0.05, key="alert_corr")
# Get values from session state (widgets automatically persist)
universe_input = st_module.session_state.get('turb_universe', ", ".join(TURB_DEFAULT_UNIVERSE))
cov_mode = st_module.session_state.get('turb_cov_mode', 'blend')
data_period = st_module.session_state.get('turb_period', '5y')
cov_window = st_module.session_state.get('turb_cov_win', 252)
corr_window = st_module.session_state.get('turb_corr_win', 60)
vol_window = st_module.session_state.get('turb_vol_win', 20)
smooth = st_module.session_state.get('turb_smooth', 5)
w_turb = st_module.session_state.get('w_turb', 1.7)
w_corr = st_module.session_state.get('w_corr', 1.1)
w_pc1 = st_module.session_state.get('w_pc1', 1.1)
w_cjump = st_module.session_state.get('w_cjump', 1.0)
w_vol = st_module.session_state.get('w_vol', 0.7)
w_credit = st_module.session_state.get('w_credit', 1.0)
w_covmag = st_module.session_state.get('w_covmag', 1.0)
w_decouple = st_module.session_state.get('w_decouple', 0.9)
alert_score_level = st_module.session_state.get('alert_score', 70.0)
alert_score_jump = st_module.session_state.get('alert_jump', 8.0)
alert_turb_pct = st_module.session_state.get('alert_turb', 0.90)
alert_corr_pct = st_module.session_state.get('alert_corr', 0.90)
# Build config
universe = [t.strip().upper() for t in universe_input.split(",") if t.strip()]
# Always include VIX for implied vol
if "^VIX" not in universe:
universe.append("^VIX")
cfg = TURB_DEFAULT_CONFIG.copy()
cfg.update({
'cov_window': cov_window,
'corr_window': corr_window,
'vol_window': vol_window,
'smooth': smooth,
'cov_mode': cov_mode,
'w_turb': w_turb,
'w_corr': w_corr,
'w_corr_jump': w_cjump,
'w_pc1': w_pc1,
'w_cov_mag': w_covmag,
'w_vol': w_vol,
'w_credit': w_credit,
'w_decouple': w_decouple,
'alert_score_level': alert_score_level,
'alert_score_jump_5d': alert_score_jump,
'alert_turb_pct': alert_turb_pct,
'alert_corr_pct': alert_corr_pct,
})
# Fetch and compute
with st_module.spinner("Loading cross-asset price data..."):
prices = fetch_turbulence_prices(tuple(universe), period=data_period)
if prices.empty or len(prices) < cfg['min_points']:
st_module.error(f"Insufficient data. Need at least {cfg['min_points']} trading days.")
return
with st_module.spinner("Computing turbulence model (this may take a moment)..."):
result = compute_turbulence_model(prices.to_json(orient='split', date_format='iso'), cfg)
if 'error' in result:
st_module.error(result['error'])
return
# Deserialize results (use StringIO to prevent pandas filepath interpretation)
metrics = pd.read_json(io.StringIO(result['metrics']), orient='split')
metrics.index = pd.to_datetime(metrics.index)
diagnostics = pd.read_json(io.StringIO(result['diagnostics']), orient='split')
diagnostics.index = pd.to_datetime(diagnostics.index)
# Filter to valid data
m = metrics.dropna(subset=["RISK_TURBULENCE_SCORE"])
d = diagnostics.loc[m.index]
if m.empty:
st_module.warning("Model computation returned no valid results. Try adjusting parameters or expanding the universe.")
return
latest_m = m.iloc[-1]
latest_d = d.iloc[-1]
score = float(latest_m["RISK_TURBULENCE_SCORE"])
regime = str(latest_m.get("REGIME", "N/A"))
chg_5d = float(latest_m["SCORE_5D_CHG"]) if pd.notna(latest_m.get("SCORE_5D_CHG")) else 0.0
chg_1m = float(latest_m["SCORE_1M_CHG"]) if pd.notna(latest_m.get("SCORE_1M_CHG")) else 0.0
# Regime styling
regime_colors = {
"GREEN": ("#3fb950", "rgba(63,185,80,0.15)", "Normal / Diversified"),
"YELLOW": ("#d29922", "rgba(210,153,34,0.15)", "Tightening / Watch"),
"ORANGE": ("#f0883e", "rgba(240,136,62,0.15)", "Regime Shift Building"),
"RED": ("#f85149", "rgba(248,81,73,0.15)", "Turbulent / Correlation-to-1"),
}
r_color, r_bg, r_desc = regime_colors.get(regime, ("#8b949e", "rgba(139,148,158,0.15)", "Unknown"))
# === ALERTS ===
alert_msg = str(latest_m.get("ALERTS", ""))
if alert_msg:
st_module.markdown(f"""
<div style="background: rgba(248,81,73,0.15); border: 2px solid #f85149; border-radius: 10px; padding: 1rem; margin-bottom: 1rem;">
<div style="display: flex; align-items: center; gap: 0.5rem;">
<span style="font-size: 1.5rem;">🚨</span>
<div>
<div style="color: #f85149; font-weight: 700; font-size: 1rem;">INSTITUTIONAL ALERT</div>
<div style="color: #f0883e; font-size: 0.9rem;">{alert_msg}</div>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# === KPI TILES ROW ===
st_module.markdown("#### 📊 Current Risk State")
kpi_cols = st_module.columns(5)
with kpi_cols[0]: