-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
2032 lines (1708 loc) · 67.1 KB
/
Copy pathdashboard.py
File metadata and controls
2032 lines (1708 loc) · 67.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
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
"""
FactorDB Dashboard - Professional Factor Analytics Platform
A clean, professional interface for quantitative factor research.
Usage:
uv run streamlit run dashboard.py
.venv\\Scripts\\python -m streamlit run dashboard.py
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'src'))
import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from factordb import FactorDBConfig, AssetType, FactorType
from factordb.storage import ClickHouseStorage
import networkx as nx
# =============================================================================
# Professional Light Theme & Styling
# =============================================================================
# Color palette - Professional quant style (light theme)
COLORS = {
'primary': '#1E3A5F', # Deep blue - primary
'secondary': '#2E86AB', # Medium blue
'accent': '#3498DB', # Light blue accent
'positive': '#27AE60', # Green - positive
'negative': '#E74C3C', # Red - negative
'neutral': '#95A5A6', # Gray - neutral
'background': '#FFFFFF', # White background
'surface': '#F8F9FA', # Light gray surface
'border': '#E9ECEF', # Border color
'text': '#2C3E50', # Dark text
'text_light': '#495057', # Light text (darker for readability)
}
def apply_professional_theme():
"""Apply professional light theme styling."""
st.markdown("""
<style>
/* Import professional font */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
/* Global Theme - Clean White Professional Style */
.stApp {
background: #FFFFFF;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}
/* Main container */
.main .block-container {
padding-top: 2rem;
padding-bottom: 2rem;
max-width: 100%;
}
/* Header styling */
.main-header {
background: linear-gradient(135deg, #1E3A5F 0%, #2E86AB 100%);
border-radius: 12px;
padding: 1.8rem 2.5rem;
margin-bottom: 2rem;
box-shadow: 0 4px 20px rgba(30, 58, 95, 0.15);
}
.main-header h1 {
color: #FFFFFF;
font-size: 1.9rem;
font-weight: 700;
margin: 0;
letter-spacing: -0.02em;
}
.main-header .subtitle {
color: rgba(255, 255, 255, 0.85);
font-size: 0.95rem;
margin-top: 0.4rem;
font-weight: 400;
}
/* Metric cards styling */
.metric-card {
background: #FFFFFF;
border: 1px solid #E9ECEF;
border-radius: 12px;
padding: 1.2rem 1.5rem;
text-align: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
transition: all 0.2s ease;
}
.metric-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
border-color: #3498DB;
}
.metric-card .label {
color: #495057;
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.08em;
margin-bottom: 0.5rem;
font-weight: 600;
}
.metric-card .value {
color: #2C3E50;
font-size: 1.25rem;
font-weight: 700;
font-family: 'JetBrains Mono', monospace;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.metric-card .value.positive { color: #27AE60; }
.metric-card .value.negative { color: #E74C3C; }
.metric-card .value.accent { color: #2E86AB; }
/* Section headers */
.section-header {
color: #1E3A5F;
font-size: 1.15rem;
font-weight: 700;
margin: 2rem 0 1.2rem 0;
padding-bottom: 0.6rem;
border-bottom: 3px solid #3498DB;
display: flex;
align-items: center;
gap: 0.5rem;
}
/* Info cards */
.info-card {
background: #F8F9FA;
border: 1px solid #E9ECEF;
border-radius: 10px;
padding: 1.2rem;
margin-bottom: 0.8rem;
}
.info-card .label {
color: #495057;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
font-weight: 600;
}
.info-card .value {
color: #2C3E50;
font-size: 1.1rem;
font-weight: 600;
margin-top: 0.4rem;
font-family: 'JetBrains Mono', monospace;
}
/* Expression display */
.expression-box {
background: #F8F9FA;
border: 1px solid #E9ECEF;
border-left: 4px solid #3498DB;
border-radius: 8px;
padding: 1.2rem 1.5rem;
font-family: 'JetBrains Mono', monospace;
font-size: 1rem;
color: #1E3A5F;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
}
/* Performance table styling */
.perf-table {
width: 100%;
border-collapse: collapse;
font-size: 1rem;
margin: 1rem 0;
}
.perf-table th {
background: #1E3A5F;
color: #FFFFFF;
font-weight: 600;
text-transform: uppercase;
font-size: 0.8rem;
letter-spacing: 0.05em;
padding: 1rem 1.2rem;
text-align: center;
}
.perf-table td {
background: #FFFFFF;
color: #2C3E50;
padding: 0.9rem 1.2rem;
text-align: center;
border-bottom: 1px solid #E9ECEF;
font-family: 'JetBrains Mono', monospace;
font-size: 0.95rem;
}
.perf-table tr:hover td {
background: #F8F9FA;
}
.perf-table td.positive { color: #27AE60; font-weight: 600; }
.perf-table td.negative { color: #E74C3C; font-weight: 600; }
.perf-table td.period-label {
background: #F8F9FA;
font-weight: 600;
color: #1E3A5F;
text-align: left;
padding-left: 1.5rem;
}
/* Status badges */
.badge {
display: inline-block;
padding: 0.35rem 0.8rem;
border-radius: 6px;
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.badge-long { background: rgba(39, 174, 96, 0.12); color: #27AE60; }
.badge-short { background: rgba(231, 76, 60, 0.12); color: #E74C3C; }
.badge-pass { background: rgba(39, 174, 96, 0.12); color: #27AE60; }
.badge-fail { background: rgba(231, 76, 60, 0.12); color: #E74C3C; }
/* Sidebar styling */
section[data-testid="stSidebar"] {
background: #F8F9FA;
border-right: 1px solid #E9ECEF;
}
section[data-testid="stSidebar"] .stSelectbox label,
section[data-testid="stSidebar"] .stNumberInput label,
section[data-testid="stSidebar"] .stCheckbox label {
color: #2C3E50 !important;
font-weight: 600;
}
/* Tab styling */
.stTabs [data-baseweb="tab-list"] {
background: #F8F9FA;
border-radius: 10px;
padding: 0.4rem;
gap: 0.5rem;
border: 1px solid #E9ECEF;
}
.stTabs [data-baseweb="tab"] {
background: transparent;
color: #495057;
border-radius: 8px;
padding: 0.6rem 1.8rem;
font-weight: 600;
font-size: 0.95rem;
}
.stTabs [aria-selected="true"] {
background: #1E3A5F !important;
color: white !important;
}
/* Dataframe styling - LARGER FONTS */
.stDataFrame {
border-radius: 10px;
overflow: hidden;
border: 1px solid #E9ECEF;
}
.stDataFrame table {
font-size: 1rem !important;
}
.stDataFrame th {
font-size: 0.9rem !important;
font-weight: 600 !important;
background: #1E3A5F !important;
color: white !important;
padding: 1rem !important;
}
.stDataFrame td {
font-size: 1rem !important;
padding: 0.9rem !important;
font-family: 'JetBrains Mono', monospace !important;
}
/* Button styling */
.stButton > button {
background: linear-gradient(135deg, #1E3A5F 0%, #2E86AB 100%);
color: white;
border: none;
border-radius: 8px;
padding: 0.6rem 1.8rem;
font-weight: 600;
font-size: 0.95rem;
transition: all 0.2s;
}
.stButton > button:hover {
background: linear-gradient(135deg, #2E86AB 0%, #3498DB 100%);
box-shadow: 0 4px 12px rgba(30, 58, 95, 0.25);
transform: translateY(-1px);
}
/* Hide Streamlit branding */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
/* Chart container */
.chart-container {
background: #FFFFFF;
border: 1px solid #E9ECEF;
border-radius: 12px;
padding: 1.5rem;
margin: 1rem 0;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #F8F9FA;
}
::-webkit-scrollbar-thumb {
background: #CED4DA;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #ADB5BD;
}
</style>
""", unsafe_allow_html=True)
# =============================================================================
# Data Loading
# =============================================================================
@st.cache_data(ttl=300)
def load_factor_data(asset_type_str: str, factor_type_str: str) -> pd.DataFrame:
"""Load factor data from database with caching."""
asset_type = AssetType[asset_type_str]
factor_type = FactorType[factor_type_str]
config = FactorDBConfig()
db_name = config.get_factor_db_name(asset_type, factor_type)
# All metrics from evaluation (matching actual schema)
metric_columns = """
e.ic_mean,
e.rank_ic_mean,
e.ic_ir,
e.rank_ic_ir,
e.ic_t_stat,
e.direction,
e.ic_mean_5y,
e.rank_ic_5y,
e.ic_ir_5y,
e.rank_ic_ir_5y,
e.ic_mean_1y,
e.rank_ic_1y,
e.ic_ir_1y,
e.rank_ic_ir_1y,
e.is_mono_5,
e.is_mono_10,
e.is_mono_15,
e.is_mono_5_5y,
e.is_mono_10_5y,
e.is_mono_15_5y,
e.is_mono_5_1y,
e.is_mono_10_1y,
e.is_mono_15_1y,
e.top_bottom_return_abs_5,
e.top_bottom_return_abs_10,
e.top_bottom_return_abs_15,
e.top_bottom_sr_5,
e.top_bottom_sr_10,
e.top_bottom_sr_15,
e.factor_std,
e.factor_skewness,
e.factor_kurtosis,
e.upgrade_datetime as eval_datetime
"""
sql = f"""
SELECT
b.factor_id as factor_id,
b.name,
b.expression,
b.explanation,
b.register_datetime,
u.latest_date,
u.upgrade_datetime as upgrade_datetime,
{metric_columns}
FROM {db_name}.A1_factor_basic b
LEFT JOIN {db_name}.A3_factor_upgrade u ON b.factor_id = u.factor_id
LEFT JOIN {db_name}.A2_factor_evaluate e ON b.factor_id = e.factor_id
ORDER BY b.factor_id
"""
with ClickHouseStorage(config) as storage:
df = storage._fetch(sql, asset_type, factor_type)
return df
def format_metric(value, decimals=4, percentage=False, show_sign=False):
"""Format metric value for display."""
if pd.isna(value):
return "-"
if percentage:
return f"{value * 100:+.2f}%" if show_sign else f"{value * 100:.2f}%"
if show_sign:
return f"{value:+.{decimals}f}"
return f"{value:.{decimals}f}"
@st.cache_data(ttl=300)
def load_factor_values(
factor_id: str,
asset_type_str: str,
factor_type_str: str
) -> pd.Series:
"""Load past 3 years of factor values for distribution display."""
asset_type = AssetType[asset_type_str]
factor_type = FactorType[factor_type_str]
config = FactorDBConfig()
db_name = config.get_factor_db_name(asset_type, factor_type)
sql = f"""
SELECT factor_value
FROM {db_name}.{factor_id}
WHERE factor_value IS NOT NULL
AND date >= addDays(today(), -365 * 3)
ORDER BY date DESC
"""
try:
with ClickHouseStorage(config) as storage:
df = storage._fetch(sql, asset_type, factor_type)
if 'factor_value' in df.columns:
return pd.to_numeric(df['factor_value'], errors='coerce').dropna()
return pd.Series(dtype=float)
except Exception:
return pd.Series(dtype=float)
# =============================================================================
# Orthogonality Analysis Data Loading
# =============================================================================
@st.cache_data(ttl=300)
def load_orthogonality_analysis_list(asset_type_str: str, factor_type_str: str) -> pd.DataFrame:
"""Load list of orthogonality analyses."""
asset_type = AssetType[asset_type_str]
factor_type = FactorType[factor_type_str]
config = FactorDBConfig()
db_name = config.get_factor_db_name(asset_type, factor_type)
sql = f"""
SELECT
analysis_id,
analysis_datetime,
total_factors,
data_start_date,
data_end_date,
effective_n_90,
effective_n_95,
mean_correlation,
max_correlation,
redundancy_ratio,
high_corr_pairs_count,
n_clusters,
n_selected,
n_removed
FROM {db_name}.B1_orthogonality_analysis
ORDER BY analysis_datetime DESC
LIMIT 20
"""
try:
with ClickHouseStorage(config) as storage:
df = storage._fetch(sql, asset_type, factor_type)
return df
except Exception:
return pd.DataFrame()
@st.cache_data(ttl=300)
def load_orthogonality_detail(analysis_id: str, asset_type_str: str, factor_type_str: str) -> dict:
"""Load detailed orthogonality analysis results."""
asset_type = AssetType[asset_type_str]
factor_type = FactorType[factor_type_str]
config = FactorDBConfig()
db_name = config.get_factor_db_name(asset_type, factor_type)
result = {}
# Load summary
sql_summary = f"""
SELECT * FROM {db_name}.B1_orthogonality_analysis
WHERE analysis_id = '{analysis_id}'
"""
# Load high correlation pairs
sql_pairs = f"""
SELECT factor_id_1, factor_id_2, correlation, same_cluster
FROM {db_name}.B2_high_correlation_pairs
WHERE analysis_id = '{analysis_id}'
ORDER BY abs(correlation) DESC
LIMIT 100
"""
# Load clusters
sql_clusters = f"""
SELECT factor_id, cluster_id, is_representative, centrality_score
FROM {db_name}.B3_factor_clusters
WHERE analysis_id = '{analysis_id}'
ORDER BY cluster_id, centrality_score DESC
"""
# Load MST edges
sql_mst = f"""
SELECT source_factor, target_factor, distance, correlation
FROM {db_name}.B4_mst_edges
WHERE analysis_id = '{analysis_id}'
"""
try:
with ClickHouseStorage(config) as storage:
result['summary'] = storage._fetch(sql_summary, asset_type, factor_type)
result['high_corr_pairs'] = storage._fetch(sql_pairs, asset_type, factor_type)
result['clusters'] = storage._fetch(sql_clusters, asset_type, factor_type)
result['mst_edges'] = storage._fetch(sql_mst, asset_type, factor_type)
except Exception as e:
st.error(f"Failed to load orthogonality details: {e}")
return {}
return result
@st.cache_data(ttl=300)
def load_correlation_matrix(analysis_id: str, asset_type_str: str, factor_type_str: str) -> pd.DataFrame:
"""Load correlation matrix from parquet file."""
asset_type = AssetType[asset_type_str]
factor_type = FactorType[factor_type_str]
config = FactorDBConfig()
db_name = config.get_factor_db_name(asset_type, factor_type)
# Get file path from database
sql = f"""
SELECT correlation_matrix_path
FROM {db_name}.B1_orthogonality_analysis
WHERE analysis_id = '{analysis_id}'
"""
def _sparse_corr_to_matrix(df: pd.DataFrame) -> pd.DataFrame:
"""Convert upper-triangular long format (factor_i, factor_j, correlation) to square matrix."""
factors = sorted(set(df['factor_i'].tolist()) | set(df['factor_j'].tolist()))
if not factors:
return pd.DataFrame()
idx = {f: i for i, f in enumerate(factors)}
mat = np.zeros((len(factors), len(factors)), dtype=float)
for _, row in df.iterrows():
i = idx[row['factor_i']]
j = idx[row['factor_j']]
val = row['correlation']
mat[i, j] = val
mat[j, i] = val
return pd.DataFrame(mat, index=factors, columns=factors)
try:
with ClickHouseStorage(config) as storage:
result = storage._fetch(sql, asset_type, factor_type)
if len(result) > 0 and result.iloc[0]['correlation_matrix_path']:
path = result.iloc[0]['correlation_matrix_path']
if os.path.exists(path):
df = pd.read_parquet(path)
# Handle sparse upper-triangular format used by orthogonality_storage
if {'factor_i', 'factor_j', 'correlation'}.issubset(df.columns):
return _sparse_corr_to_matrix(df)
return df
except Exception:
pass
return pd.DataFrame()
# =============================================================================
# Orthogonality Visualization Components
# =============================================================================
def create_correlation_heatmap(corr_matrix: pd.DataFrame, max_factors: int = 50) -> go.Figure:
"""Create correlation matrix heatmap."""
# Limit size for visualization
if len(corr_matrix) > max_factors:
corr_matrix = corr_matrix.iloc[:max_factors, :max_factors]
fig = go.Figure(data=go.Heatmap(
z=corr_matrix.values,
x=corr_matrix.columns,
y=corr_matrix.index,
colorscale='RdBu_r',
zmid=0,
zmin=-1,
zmax=1,
colorbar=dict(title='Correlation', tickfont=dict(size=11)),
hovertemplate='%{x}<br>%{y}<br>Corr: %{z:.3f}<extra></extra>'
))
fig.update_layout(
title=dict(text=f'Factor Correlation Matrix ({len(corr_matrix)} factors)',
font=dict(size=18, color=COLORS['text'])),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family='Inter, sans-serif', size=12, color=COLORS['text']),
height=600,
margin=dict(t=60, b=100, l=100, r=40),
xaxis=dict(tickangle=45, tickfont=dict(size=9)),
yaxis=dict(tickfont=dict(size=9), automargin=True)
)
return fig
def build_corr_matrix_from_pairs(pairs_df: pd.DataFrame, factor_ids: list[str]) -> pd.DataFrame:
"""Reconstruct a symmetric correlation matrix from pair list for a given factor subset."""
if pairs_df.empty or not factor_ids:
return pd.DataFrame()
subset = pairs_df[
pairs_df['factor_id_1'].isin(factor_ids) & pairs_df['factor_id_2'].isin(factor_ids)
]
if subset.empty:
return pd.DataFrame()
matrix = pd.DataFrame(index=factor_ids, columns=factor_ids, dtype=float)
for _, row in subset.iterrows():
f1, f2, corr = row['factor_id_1'], row['factor_id_2'], row['correlation']
matrix.loc[f1, f2] = corr
matrix.loc[f2, f1] = corr
np.fill_diagonal(matrix.values, 1.0)
# Fill any remaining gaps with 0 to avoid NaNs in the heatmap while keeping symmetry.
matrix = matrix.fillna(0.0)
return matrix
def sanitize_corr_matrix(corr_matrix: pd.DataFrame) -> pd.DataFrame:
"""Ensure the correlation matrix is square, numeric, and NaN-free for plotting."""
if corr_matrix.empty:
return corr_matrix
corr_matrix = corr_matrix.copy()
# If factor ids are stored as a column, promote it to index first.
idx_candidates = ['factor_id', 'index', '__index_level_0__']
for cand in idx_candidates:
if cand in corr_matrix.columns and corr_matrix[cand].nunique() == len(corr_matrix):
corr_matrix = corr_matrix.set_index(cand)
break
# Heuristic: parquet sometimes saves factor ids as the first column rather than index.
if isinstance(corr_matrix.index, pd.RangeIndex) and corr_matrix.shape[1] == len(corr_matrix) + 1:
first_col = corr_matrix.columns[0]
if corr_matrix[first_col].nunique() == len(corr_matrix):
corr_matrix = corr_matrix.set_index(first_col)
# Normalize labels to strings to improve intersection matching
corr_matrix.index = corr_matrix.index.map(str)
corr_matrix.columns = corr_matrix.columns.map(str)
# Align rows/cols to shared labels to guarantee squareness
common = [c for c in corr_matrix.columns if c in corr_matrix.index]
if not common:
return pd.DataFrame()
corr_matrix = corr_matrix.loc[common, common]
# Coerce to numeric and fill diagonals + gaps
corr_matrix = corr_matrix.apply(pd.to_numeric, errors='coerce')
if len(corr_matrix) > 0:
np.fill_diagonal(corr_matrix.values, 1.0)
corr_matrix = corr_matrix.fillna(0.0)
return corr_matrix
def create_effective_n_chart(summary: pd.Series) -> go.Figure:
"""Create effective N visualization."""
total = summary.get('total_factors', 0)
eff_90 = summary.get('effective_n_90', 0)
eff_95 = summary.get('effective_n_95', 0)
categories = ['Total Factors', 'Effective N (90%)', 'Effective N (95%)']
values = [total, eff_90, eff_95]
colors = [COLORS['primary'], COLORS['positive'], COLORS['accent']]
fig = go.Figure(data=[
go.Bar(
x=categories,
y=values,
marker_color=colors,
text=values,
textposition='auto',
textfont=dict(size=16, color='white')
)
])
fig.update_layout(
title=dict(text='Factor Dimensionality Analysis',
font=dict(size=18, color=COLORS['text'])),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family='Inter, sans-serif', size=14, color=COLORS['text']),
height=400,
margin=dict(t=60, b=50, l=70, r=40),
yaxis=dict(title='Number of Factors', gridcolor=COLORS['border']),
xaxis=dict(tickfont=dict(size=13))
)
# Add redundancy ratio annotation
redundancy = summary.get('redundancy_ratio', 0)
fig.add_annotation(
x=0.5, y=1.05, xref='paper', yref='paper',
text=f'Redundancy Ratio: {redundancy:.1%}',
showarrow=False,
font=dict(size=14, color=COLORS['negative'])
)
return fig
def create_cluster_distribution_chart(clusters_df: pd.DataFrame) -> go.Figure:
"""Create cluster size distribution chart."""
if clusters_df.empty:
return go.Figure()
cluster_sizes = clusters_df.groupby('cluster_id').size().reset_index(name='size')
cluster_sizes = cluster_sizes.sort_values('size', ascending=False)
fig = go.Figure(data=[
go.Bar(
x=[f'Cluster {i}' for i in cluster_sizes['cluster_id']],
y=cluster_sizes['size'],
marker_color=COLORS['accent'],
text=cluster_sizes['size'],
textposition='auto',
textfont=dict(size=12, color='white')
)
])
fig.update_layout(
title=dict(text='Cluster Size Distribution',
font=dict(size=18, color=COLORS['text'])),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family='Inter, sans-serif', size=14, color=COLORS['text']),
height=400,
margin=dict(t=60, b=80, l=70, r=40),
yaxis=dict(title='Number of Factors', gridcolor=COLORS['border']),
xaxis=dict(tickangle=45, tickfont=dict(size=11))
)
return fig
def create_mst_network_graph(mst_edges: pd.DataFrame, clusters_df: pd.DataFrame) -> go.Figure:
"""Create MST network visualization using Plotly."""
if mst_edges.empty:
return go.Figure()
# Build networkx graph
G = nx.Graph()
for _, row in mst_edges.iterrows():
G.add_edge(row['source_factor'], row['target_factor'], weight=row.get('distance', 1))
# Get layout
pos = nx.spring_layout(G, k=2, iterations=50, seed=42)
# Create cluster color mapping
cluster_colors = {}
if not clusters_df.empty:
color_palette = px.colors.qualitative.Set3
for _, row in clusters_df.iterrows():
cluster_id = row['cluster_id']
cluster_colors[row['factor_id']] = color_palette[cluster_id % len(color_palette)]
# Edge trace
edge_x, edge_y = [], []
for edge in G.edges():
x0, y0 = pos[edge[0]]
x1, y1 = pos[edge[1]]
edge_x.extend([x0, x1, None])
edge_y.extend([y0, y1, None])
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(width=1, color=COLORS['neutral']),
hoverinfo='none',
mode='lines'
)
# Node trace
node_x = [pos[node][0] for node in G.nodes()]
node_y = [pos[node][1] for node in G.nodes()]
node_colors = [cluster_colors.get(node, COLORS['accent']) for node in G.nodes()]
node_text = list(G.nodes())
node_trace = go.Scatter(
x=node_x, y=node_y,
mode='markers+text',
hoverinfo='text',
text=node_text,
textposition='top center',
textfont=dict(size=8),
marker=dict(
size=12,
color=node_colors,
line=dict(width=1, color='white')
)
)
fig = go.Figure(data=[edge_trace, node_trace])
fig.update_layout(
title=dict(text='Factor MST Network (colored by cluster)',
font=dict(size=18, color=COLORS['text'])),
showlegend=False,
plot_bgcolor='white',
paper_bgcolor='white',
height=500,
margin=dict(t=60, b=20, l=20, r=20),
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)
)
return fig
def render_orthogonality_tab(asset_type: str, factor_type: str, factor_df: pd.DataFrame):
"""Render the orthogonality analysis tab."""
st.markdown('<div class="section-header">Orthogonality Analysis Results</div>',
unsafe_allow_html=True)
# Load analysis list
analyses_df = load_orthogonality_analysis_list(asset_type, factor_type)
if analyses_df.empty:
st.info("No orthogonality analysis results found. Run orthogonality analysis first using: `python main.py orthogonality`")
return
# Analysis selector
col1, col2 = st.columns([2, 1])
with col1:
analysis_options = []
for _, row in analyses_df.iterrows():
dt = str(row['analysis_datetime'])[:19]
n_factors = row['total_factors']
analysis_options.append(f"{row['analysis_id']} ({dt}, {n_factors} factors)")
selected_idx = st.selectbox(
"Select Analysis",
range(len(analysis_options)),
format_func=lambda x: analysis_options[x],
key="ortho_analysis_select"
)
selected_analysis_id = analyses_df.iloc[selected_idx]['analysis_id']
# Load detailed results
detail = load_orthogonality_detail(selected_analysis_id, asset_type, factor_type)
if not detail or detail.get('summary') is None or detail['summary'].empty:
st.error("Failed to load analysis details.")
return
summary = detail['summary'].iloc[0]
# Summary metrics row
st.markdown("<br>", unsafe_allow_html=True)
cols = st.columns(6)
metrics = [
("Total Factors", summary.get('total_factors', 0), "accent"),
("Effective N (90%)", summary.get('effective_n_90', 0), "positive"),
("Redundancy", f"{summary.get('redundancy_ratio', 0):.1%}", "negative"),
("Clusters", summary.get('n_clusters', 0), "accent"),
("High Corr Pairs", summary.get('high_corr_pairs_count', 0), "negative"),
("Mean Corr", f"{summary.get('mean_correlation', 0):.3f}", "accent"),
]
for col, (label, value, color) in zip(cols, metrics):
with col:
st.markdown(f"""
<div class="metric-card">
<div class="label">{label}</div>
<div class="value {color}">{value}</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Tabs for different views
ortho_tab1, ortho_tab2, ortho_tab3, ortho_tab4 = st.tabs([
"Overview", "Correlation Matrix", "Clusters & MST", "High Correlation Pairs"
])
with ortho_tab1:
col1, col2 = st.columns(2)
with col1:
# Effective N chart
fig_eff = create_effective_n_chart(summary)
st.plotly_chart(fig_eff, width='stretch')
with col2:
# Cluster distribution
if 'clusters' in detail and not detail['clusters'].empty:
fig_cluster = create_cluster_distribution_chart(detail['clusters'])
st.plotly_chart(fig_cluster, width='stretch')
else:
st.info("No cluster data available.")
# Analysis info
st.markdown('<div class="section-header">Analysis Details</div>', unsafe_allow_html=True)
info_cols = st.columns(4)
with info_cols[0]:
st.markdown(f"""
<div class="info-card">
<div class="label">Data Period</div>
<div class="value">{str(summary.get('data_start_date', ''))[:10]} ~ {str(summary.get('data_end_date', ''))[:10]}</div>
</div>
""", unsafe_allow_html=True)
with info_cols[1]:
st.markdown(f"""
<div class="info-card">
<div class="label">Max Correlation</div>
<div class="value">{summary.get('max_correlation', 0):.3f}</div>
</div>
""", unsafe_allow_html=True)
with info_cols[2]:
st.markdown(f"""
<div class="info-card">
<div class="label">Effective N (95%)</div>
<div class="value">{summary.get('effective_n_95', 0)}</div>
</div>
""", unsafe_allow_html=True)
with info_cols[3]:
st.markdown(f"""
<div class="info-card">
<div class="label">Analysis Time</div>
<div class="value">{str(summary.get('analysis_datetime', ''))[:19]}</div>
</div>
""", unsafe_allow_html=True)
with ortho_tab2:
# Load base correlation matrix from parquet
corr_matrix_raw = load_correlation_matrix(selected_analysis_id, asset_type, factor_type)
corr_matrix = sanitize_corr_matrix(corr_matrix_raw)
pairs_df = detail.get('high_corr_pairs', pd.DataFrame())
# Derive factor sets
top_factors = []
if factor_df is not None and 'rank_ic_mean' in factor_df.columns:
# Sort by absolute RankIC to capture both long/short skill
top_factors = (
factor_df[['factor_id', 'rank_ic_mean']]
.dropna(subset=['rank_ic_mean'])
.assign(rank_ic_abs=lambda x: x['rank_ic_mean'].abs())