-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcannae_dashboard.py
More file actions
3227 lines (2727 loc) · 148 KB
/
cannae_dashboard.py
File metadata and controls
3227 lines (2727 loc) · 148 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
# cannae_dashboard.py
# Dynamic port override for Railway compatibility
import os
os.environ["STREAMLIT_SERVER_PORT"] = os.environ.get("PORT", "8501")
os.environ["STREAMLIT_SERVER_ADDRESS"] = "0.0.0.0"
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from datetime import datetime
from fpdf import FPDF
import base64
import os
import io
import pdfplumber
import logging
import re
from cannae_report_generator import generate_pdf_report
# ---------- CONFIG ----------
st.set_page_config(page_title="Cannae Dashboard", layout="wide")
import sys
import socket
# Updated paths for organized directory structure - OS-agnostic for Railway compatibility
import os
# Determine if running locally or on Railway
if os.path.exists("I:\\BW Code\\BD Script"):
# Local Windows path
BASE_PATH = "I:\\BW Code\\BD Script"
else:
# Railway path (current directory)
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
# Use os.path.join for OS-agnostic paths
DATA_PATH = os.path.join(BASE_PATH, "data")
REPORTS_PATH = os.path.join(BASE_PATH, "reports")
ASSETS_PATH = os.path.join(BASE_PATH, "assets")
# Custom CSS for styling
custom_css = """
<style>
@import url('https://fonts.googleapis.com/css2?family=Merriweather:wght@400;700&display=swap');
/* Global styles */
body, .stMarkdown, .stDataFrame, .stTable, .stMetric, .stButton > button, .stDownloadButton > button, .stTextInput > div > div > input, .stTextArea > div > textarea {
font-family: 'Merriweather', serif !important;
color: #333; /* Darker gray for text */
}
/* Headers */
h1 {
font-family: 'Merriweather', serif !important;
font-size: 26px; /* Slightly smaller than default */
color: #1E3A8A; /* A deep blue, adjust as needed */
}
h2 {
font-family: 'Merriweather', serif !important;
font-size: 20px; /* Reduced for cohesion */
color: #1E3A8A;
border-bottom: 1px solid #DDDDDD; /* Subtle separator */
padding-bottom: 5px;
margin-top: 30px;
}
h3 {
font-family: 'Merriweather', serif !important;
font-size: 17px; /* Reduced */
color: #2E5A9A; /* A slightly lighter blue */
}
/* Paragraphs and general text */
p, .stMarkdown p, .stDataFrame, .stTable {
font-size: 14px;
line-height: 1.6;
}
/* Streamlit Metric specific styling */
.stMetric > div:nth-child(1) { /* Metric Label */
font-size: 14px;
color: #555;
}
.stMetric > div:nth-child(2) { /* Metric Value */
font-size: 24px;
font-weight: bold;
color: #1E3A8A;
}
.stMetric > div:nth-child(3) { /* Metric Delta (if present) */
font-size: 13px;
}
/* Improve spacing for main content area */
.main .block-container {
padding-top: 2rem;
padding-bottom: 2rem;
padding-left: 3rem;
padding-right: 3rem;
}
/* Style buttons for a more modern feel */
.stButton>button {
border-radius: 5px;
background-color: #1E3A8A; /* Blue background */
color: white;
padding: 10px 20px;
border: none;
}
.stButton>button:hover {
background-color: #2E5A9A; /* Lighter blue on hover */
}
</style>
"""
st.markdown(custom_css, unsafe_allow_html=True)
# ---------- HELPER FUNCTIONS ----------
def generate_html_pdf(output_path, key_stats, fig_strategy_allocation, allocation_table, recent_trades, top_positions,
fig_deployment_waterfall, attribution_data, fig_attribution, gross_return_bps, net_return_bps,
fig_gainers, fig_sub_strategy, competitor_data, percentile_rank):
"""
Generate a PDF report using HTML/CSS and WeasyPrint.
This provides better layout control and more professional results than FPDF.
"""
try:
# Initialize the HTML PDF generator
html_pdf = HTMLPDFGenerator(DATA_PATH)
# Generate the PDF using the HTML template
html_pdf.generate_pdf(
key_stats=key_stats,
fig_strategy_allocation=fig_strategy_allocation,
allocation_table=allocation_table,
recent_trades=recent_trades,
top_positions=top_positions,
fig_deployment_waterfall=fig_deployment_waterfall,
attribution_data=attribution_data,
fig_attribution=fig_attribution,
gross_return_bps=gross_return_bps,
net_return_bps=net_return_bps,
fig_gainers=fig_gainers,
fig_sub_strategy=fig_sub_strategy,
competitor_data=competitor_data,
percentile_rank=percentile_rank
)
logging.info(f"HTML PDF successfully generated at: {output_path}")
return True
except Exception as e:
logging.error(f"Error generating HTML PDF: {e}", exc_info=True)
raise e
def extract_kpis_from_factsheet():
"""Extract KPI data from the 'Key Stats' sheet in 'Risk Report Format Master Sheet.xlsx'."""
import os # Ensure os is available for path operations
# pandas (pd), logging, DATA_PATH should be available globally/module-level.
kpi_data = {
"monthly_return_str": "N/A",
"monthly_return_float": 0.0,
"ytd_return_str": "N/A",
"ytd_return_float": 0.0,
"ann_return_str": "N/A",
"ann_return_float": 0.0,
"aum_str": "N/A",
"aum_float": 0.0,
"extraction_source": "Fallback (Initial values - Excel)" # extracted_text_snippet removed
}
excel_filename = "Risk Report Format Master Sheet.xlsx"
excel_path = os.path.join(DATA_PATH, excel_filename)
sheet_name = "Key Stats"
if not os.path.exists(excel_path):
logging.warning(f"KPI source file '{excel_filename}' not found at: {excel_path}. Using fallback KPI values.")
kpi_data["extraction_source"] = f"Fallback (Excel file not found: {excel_filename})"
return kpi_data
try:
excel_file_obj = pd.ExcelFile(excel_path)
if sheet_name not in excel_file_obj.sheet_names:
logging.warning(f"Sheet '{sheet_name}' for KPIs not found in '{excel_filename}'. Using fallback values.")
kpi_data["extraction_source"] = f"Fallback (Sheet '{sheet_name}' not found in {excel_filename})"
return kpi_data
df = pd.read_excel(excel_path, sheet_name=sheet_name, header=None, engine='openpyxl')
stats_map = {}
if not df.empty and df.shape[1] >= 2:
stats_map = df.dropna(subset=[0]).set_index(0)[1].to_dict()
else:
logging.warning(f"Sheet '{sheet_name}' in '{excel_filename}' is empty or has fewer than 2 columns. Cannot extract KPIs.")
kpi_data["extraction_source"] = f"Fallback (Sheet '{sheet_name}' empty or malformed in {excel_filename})"
return kpi_data
# Helper to safely get and convert values from the stats_map
def get_value_from_map(label, data_type):
raw_value = stats_map.get(label)
default_str, default_float = "N/A", 0.0
if raw_value is None:
logging.warning(f"KPI Label '{label}' not found in '{sheet_name}' of '{excel_filename}'.")
return default_str, default_float
try:
if data_type == 'percentage':
if isinstance(raw_value, str):
numeric_part = raw_value.replace('%', '').strip()
val_float = float(numeric_part)
elif isinstance(raw_value, (int, float)):
# If value is like 0.0421 (Excel % format) vs 4.21 (direct number)
val_float = float(raw_value) * 100.0 if abs(raw_value) < 1 and raw_value != 0 else float(raw_value)
else:
logging.warning(f"Unexpected type for percentage KPI '{label}': {type(raw_value)}. Value: {raw_value}")
return str(raw_value), default_float
return f"{val_float:.2f}%", val_float
elif data_type == 'aum':
if isinstance(raw_value, str):
numeric_part = raw_value.replace('$', '').replace(',', '').strip()
val_float = float(numeric_part)
elif isinstance(raw_value, (int, float)):
val_float = float(raw_value)
else:
logging.warning(f"Unexpected type for AUM KPI '{label}': {type(raw_value)}. Value: {raw_value}")
return str(raw_value), default_float
return f"${int(val_float):,}", val_float
except ValueError as ve:
logging.error(f"Could not convert value for KPI '{label}' ('{raw_value}') to float: {ve}")
return str(raw_value), default_float
return str(raw_value), default_float # Fallback for unhandled cases
# Extract KPIs
kpi_data["ytd_return_str"], kpi_data["ytd_return_float"] = get_value_from_map("YTD Return", "percentage")
kpi_data["monthly_return_str"], kpi_data["monthly_return_float"] = get_value_from_map("Monthly Return", "percentage")
kpi_data["ann_return_str"], kpi_data["ann_return_float"] = get_value_from_map("Annualized Return", "percentage")
kpi_data["aum_str"], kpi_data["aum_float"] = get_value_from_map("AUM", "aum")
# Update extraction source
parsed_any_kpi = any(kpi_data[key_str] != "N/A" for key_str in ["ytd_return_str", "monthly_return_str", "ann_return_str", "aum_str"])
if parsed_any_kpi:
kpi_data["extraction_source"] = f"Successfully extracted from {excel_filename}, sheet {sheet_name}"
elif not stats_map: # Initial df read was problematic
kpi_data["extraction_source"] = f"Fallback (Could not read data/labels from {excel_filename}, sheet {sheet_name})"
else: # Labels might be missing or values unparseable
kpi_data["extraction_source"] = f"Fallback (KPIs not found or unparseable in {excel_filename}, sheet {sheet_name})"
except Exception as e:
logging.error(f"Error processing Excel file '{excel_path}' for KPIs: {e}", exc_info=True)
kpi_data["extraction_source"] = f"Fallback (Error processing Excel for KPIs: {str(e)[:100]})"
logging.info(f"KPI Data from Excel: {kpi_data}")
return kpi_data
def extract_key_stats_from_risk_report():
"""Extract key statistics directly from the Risk Report Format Master Sheet Excel file.
No PDF fallback - only uses Excel.
Returns:
dict: Dictionary containing key stats extracted from the Excel file
"""
excel_filename = "Risk Report Format Master Sheet.xlsx"
excel_path = os.path.join(DATA_PATH, excel_filename)
# Check if Excel file exists
if not os.path.exists(excel_path):
logging.warning(f"Risk report Excel file '{excel_filename}' not found at: {excel_path}. Using hardcoded fallback key stats.")
return {
'avg_yield': '13.10%',
'wal': '3.20',
'pct_ig': '24.2%',
'pct_risk_rating_1': '52.3%',
'floating_rate_pct': '21.2%',
'monthly_carry_bps': '61 bps',
'bond_line_items': '3',
'bond_breakdown': {'CMBS': 1, 'ABS': 2, 'CLO': 0},
'avg_holding_size': 'N/A',
'top_10_concentration': '20.6%',
'extraction_source': 'hardcoded_fallback'
}
try:
# Try to read the Excel file
excel = pd.ExcelFile(excel_path)
logging.debug(f"Available sheets in {excel_path}: {excel.sheet_names}")
# Check if Key Stats sheet exists
if 'Key Stats' not in excel.sheet_names:
logging.warning("'Key Stats' sheet not found in Excel file! Using hardcoded fallback values.")
logging.debug("KEY STATS EXTRACTED:\n Using hardcoded fallback values (Key Stats sheet not found)")
return {
'avg_yield': '13.10%',
'wal': '3.20',
'pct_ig': '24.2%',
'pct_risk_rating_1': '52.3%',
'floating_rate_pct': '21.2%',
'monthly_carry_bps': '61 bps',
'bond_line_items': '3',
'bond_breakdown': {'CMBS': 1, 'ABS': 2, 'CLO': 0},
'avg_holding_size': 'N/A',
'top_10_concentration': '20.6%',
'extraction_source': 'hardcoded_fallback'
}
# Read the Key Stats sheet
df = pd.read_excel(excel_path, sheet_name='Key Stats', header=None, engine='openpyxl')
logging.debug(f"Successfully read Key Stats sheet from {excel_path} with {len(df)} rows")
# Extract metrics from the sheet
metrics = {}
for i in range(len(df)):
if pd.notna(df.iloc[i, 0]) and pd.notna(df.iloc[i, 1]):
metrics[str(df.iloc[i, 0])] = df.iloc[i, 1]
logging.debug(f"Extracted metrics from Excel {excel_path}: {metrics}")
# Format metrics for display
key_stats = {}
key_stats['attribution_by_strategy'] = {}
def _parse_to_bps(raw_value, default_bps=0):
if pd.isna(raw_value):
return default_bps
try:
if isinstance(raw_value, str) and '%' in raw_value:
numeric_part_str = raw_value.strip('%')
numeric_part_float = float(numeric_part_str)
return int(round(numeric_part_float * 100))
elif isinstance(raw_value, (int, float)):
if abs(raw_value) < 2.0 and raw_value != 0: # Treat 0 as 0 bps, not 0*10000
return int(round(raw_value * 10000))
else:
return int(round(raw_value))
else:
numeric_value = float(raw_value)
if abs(numeric_value) < 2.0 and numeric_value != 0:
return int(round(numeric_value * 10000))
else:
return int(round(numeric_value))
except (ValueError, TypeError):
logging.warning(f"Could not parse value '{raw_value}' to bps. Using default {default_bps} bps.")
return default_bps
# Average Yield
if 'Average Yield' in metrics:
avg_yield_value = float(metrics['Average Yield'])
key_stats['avg_yield'] = f"{avg_yield_value*100:.2f}%"
else:
key_stats['avg_yield'] = "13.10%" # Fallback
# WAL
if 'WAL' in metrics:
key_stats['wal'] = f"{float(metrics['WAL']):.2f}"
else:
key_stats['wal'] = "3.20" # Fallback
# Percent IG
if '% IG' in metrics:
key_stats['pct_ig'] = f"{float(metrics['% IG'])*100:.1f}%"
else:
key_stats['pct_ig'] = "24.2%" # Fallback
# Risk Rating 1%
if 'Risk Rating 1%' in metrics:
key_stats['pct_risk_rating_1'] = f"{float(metrics['Risk Rating 1%'])*100:.1f}%"
else:
key_stats['pct_risk_rating_1'] = "52.3%" # Fallback
# Floating Rate %
if 'Floating Rate %' in metrics:
key_stats['floating_rate_pct'] = f"{float(metrics['Floating Rate %'])*100:.1f}%"
else:
key_stats['floating_rate_pct'] = "21.2%" # Fallback
# Monthly Carry
if 'Monthly Carry' in metrics:
raw_value = metrics['Monthly Carry']
bps_value_str = "57 bps" # Default to fallback
try:
if isinstance(raw_value, str) and '%' in raw_value:
# Case 1: Value is a string like "0.57%"
numeric_part_str = raw_value.strip('%')
numeric_part_float = float(numeric_part_str) # e.g., 0.57
bps = int(round(numeric_part_float * 100)) # 0.57 * 100 = 57 bps
bps_value_str = f"{bps} bps"
elif isinstance(raw_value, (int, float)):
# Case 2: Value is a number, e.g., 0.0057 (from Excel "0.57%") or 57 (from Excel "57")
if abs(raw_value) < 2.0: # Heuristic: if value is like 0.xx or 1.xx, treat as decimal percent
# This handles 0.0057 (for 0.57%) correctly
bps = int(round(raw_value * 10000)) # e.g., 0.0057 * 10000 = 57 bps
else: # Otherwise, assume the number is already in BPS
bps = int(round(raw_value)) # e.g., 57 directly means 57 bps
bps_value_str = f"{bps} bps"
else:
# Case 3: Value is a string without '%', e.g., "57" or "0.0057"
# Attempt to convert to float and apply similar logic as Case 2.
numeric_value = float(raw_value)
if abs(numeric_value) < 2.0:
bps = int(round(numeric_value * 10000))
else:
bps = int(round(numeric_value))
bps_value_str = f"{bps} bps"
key_stats['monthly_carry_bps'] = bps_value_str
except (ValueError, TypeError) as e:
logging.warning(f"Could not parse 'Monthly Carry' value '{raw_value}': {e}. Using fallback '57 bps'.")
key_stats['monthly_carry_bps'] = "57 bps" # Fallback
else:
key_stats['monthly_carry_bps'] = "57 bps" # Fallback if 'Monthly Carry' label not found
# Bond Line Items
if 'Bond Line Items' in metrics:
key_stats['bond_line_items'] = str(int(metrics['Bond Line Items']))
else:
key_stats['bond_line_items'] = "3" # Fallback
# Bond Breakdown
bond_breakdown = {'CMBS': 0, 'ABS': 0, 'CLO': 0}
if 'CMBS Line Items' in metrics:
bond_breakdown['CMBS'] = int(metrics['CMBS Line Items'])
if 'ABS Line Items' in metrics:
bond_breakdown['ABS'] = int(metrics['ABS Line Items'])
if 'CLO Line Items' in metrics:
bond_breakdown['CLO'] = int(metrics['CLO Line Items'])
key_stats['bond_breakdown'] = bond_breakdown
# Average Holding Size
if 'Average Holding Size ($mm)' in metrics:
# Format as plain dollar amount with commas
avg_size = float(metrics['Average Holding Size ($mm)'])
# If the value is in millions, convert to full dollar amount
if avg_size < 1000: # If value is already in millions (e.g., 3.667)
avg_size = avg_size * 1000000 # Convert to full dollar amount
key_stats['avg_holding_size'] = f"${int(avg_size):,}"
else:
# Try to read directly from cell B16 if the label approach didn't work
try:
df_direct = pd.read_excel(excel_path, sheet_name='Key Stats', header=None, engine='openpyxl')
avg_holding_size_value = df_direct.iloc[15, 1] # B16 is row 15, col 1 (0-indexed)
if pd.notna(avg_holding_size_value):
# Format as plain dollar amount with commas
avg_size = float(avg_holding_size_value)
key_stats['avg_holding_size'] = f"${int(avg_size):,}"
else:
key_stats['avg_holding_size'] = "N/A" # No fallback, show N/A if not found
except Exception as e:
logging.warning(f"Could not read Average Holding Size from cell B16: {e}")
key_stats['avg_holding_size'] = "N/A" # No fallback, show N/A if not found
# Top 10 Concentration
if 'Top 10% Concentration' in metrics:
key_stats['top_10_concentration'] = f"{float(metrics['Top 10% Concentration'])*100:.1f}%"
else:
key_stats['top_10_concentration'] = "20.6%" # Fallback
# Total Leverage
if 'Total Leverage' in metrics:
leverage_value = metrics['Total Leverage']
if isinstance(leverage_value, (int, float)):
# Convert to percentage (e.g., 0.10 to 10%)
key_stats['total_leverage'] = f"{leverage_value*100:.1f}%"
else:
key_stats['total_leverage'] = leverage_value
else:
key_stats['total_leverage'] = "10.0%" # Fallback
# Repo MV
if 'Repo MV' in metrics:
repo_value = metrics['Repo MV']
if isinstance(repo_value, (int, float)):
key_stats['repo_mv'] = f"${repo_value:.2f}mm"
else:
key_stats['repo_mv'] = repo_value
else:
key_stats['repo_mv'] = "$75.00mm" # Fallback
# Add extraction source
key_stats['extraction_source'] = 'excel'
# New Attribution by Strategy from Key Stats sheet
attribution_labels = {
"CMBS": "CMBS",
"ABS": "ABS",
"CLO": "CLO",
"Hedges": "Hedges",
"Cash": "Cash",
"Total (Gross)": "Total (Gross)",
"Total (Net)": "Total (Net)"
}
for excel_label, key_name in attribution_labels.items():
if excel_label in metrics:
key_stats['attribution_by_strategy'][key_name] = _parse_to_bps(metrics[excel_label])
else:
key_stats['attribution_by_strategy'][key_name] = 0 # Default to 0 bps if not found
logging.debug(f"Attribution label '{excel_label}' not found in Key Stats metrics. Defaulting to 0 bps for '{key_name}'.")
key_stats['extraction_source'] = 'excel_extract'
logging.debug(f"KEY STATS EXTRACTED ({excel_path}):\n{key_stats}")
return key_stats
except Exception as e:
logging.error(f"Error extracting key stats from Excel {excel_path}: {str(e)}", exc_info=True)
logging.debug(f"KEY STATS EXTRACTED (fallback due to error):\n Using hardcoded fallback values (Error: {str(e)})")
return {
'avg_yield': '13.10%',
'wal': '3.20',
'pct_ig': '24.2%',
'pct_risk_rating_1': '52.3%',
'floating_rate_pct': '21.2%',
'monthly_carry_bps': '61 bps',
'bond_line_items': '3',
'bond_breakdown': {'CMBS': 1, 'ABS': 2, 'CLO': 0},
'avg_holding_size': 'N/A',
'top_10_concentration': '20.6%',
'extraction_source': 'hardcoded_fallback'
}
# Log the extracted key stats for debugging
logging.debug(f"KEY STATS EXTRACTED (after fallback processing in extract_key_stats_from_risk_report):\n {key_stats}")
logging.debug(f"Extraction source (after fallback processing in extract_key_stats_from_risk_report): {key_stats.get('extraction_source', 'unknown')}")
return key_stats
except Exception as e:
logging.warning(f"Error extracting data from risk report (extract_key_stats_from_risk_report): {e}", exc_info=True)
# Ensure key_stats is defined before returning, even if it's just the fallback from the inner try-except
if 'key_stats' not in locals():
key_stats = {
'avg_yield': '13.10%', 'wal': '3.20', 'pct_ig': '24.2%',
'pct_risk_rating_1': '52.3%', 'floating_rate_pct': '21.2%',
'monthly_carry_bps': '61 bps', 'bond_line_items': '3',
'bond_breakdown': {'CMBS': 1, 'ABS': 2, 'CLO': 0},
'avg_holding_size': 'N/A', 'top_10_concentration': '20.6%',
'extraction_source': 'hardcoded_fallback_outer_exception'
}
logging.debug(f"Returning key_stats due to outer exception in extract_key_stats_from_risk_report: {key_stats}")
return key_stats
# ---------- FILES ----------
# Function to find the most recent month-end file
def find_latest_eom_file():
eom_files = [f for f in os.listdir(DATA_PATH) if f.startswith('eom_marks_') and f.endswith('.xlsx')]
if not eom_files:
return None
# Sort by modification date (newest first)
eom_files.sort(key=lambda f: os.path.getmtime(os.path.join(DATA_PATH, f)), reverse=True)
return eom_files[0]
# Function to find the most recent holdings file
def find_latest_holdings_file():
holdings_files = [f for f in os.listdir(DATA_PATH) if
(f.startswith('portfolio_holdings_') or f.startswith('holdings_')) and
f.endswith('.xlsx')]
if not holdings_files:
return None
# Sort by modification date (newest first)
holdings_files.sort(key=lambda f: os.path.getmtime(os.path.join(DATA_PATH, f)), reverse=True)
return holdings_files[0]
# Function to find the most recent trades file
def find_latest_trades_file():
trades_files = [f for f in os.listdir(DATA_PATH) if
f.startswith('_cannae_trade_') and
f.endswith('.xlsx')]
if not trades_files:
return None
# Sort by modification date (newest first)
trades_files.sort(key=lambda f: os.path.getmtime(os.path.join(DATA_PATH, f)), reverse=True)
return trades_files[0]
# Find the latest files
latest_eom_file = find_latest_eom_file()
latest_holdings_file = find_latest_holdings_file()
latest_trades_file = find_latest_trades_file()
# Load the files with error handling
try:
if latest_eom_file:
APRIL_EOM = pd.read_excel(os.path.join(DATA_PATH, latest_eom_file), engine='openpyxl')
else:
st.sidebar.error("No month-end file found. Please add an 'eom_marks_*.xlsx' file to the data directory.")
APRIL_EOM = pd.DataFrame() # Empty DataFrame as fallback
if latest_holdings_file:
HOLDINGS_LATEST = pd.read_excel(os.path.join(DATA_PATH, latest_holdings_file), engine='openpyxl')
else:
st.sidebar.error("No holdings file found. Please add a 'portfolio_holdings_*.xlsx' file to the data directory.")
HOLDINGS_LATEST = pd.DataFrame() # Empty DataFrame as fallback
if latest_trades_file:
TRADES = pd.read_excel(os.path.join(DATA_PATH, latest_trades_file), engine='openpyxl')
else:
st.sidebar.error("No trades file found. Please add a '_cannae_trade_*.xlsx' file to the data directory.")
TRADES = pd.DataFrame() # Empty DataFrame as fallback
except Exception as e:
st.sidebar.error(f"Error loading files: {e}")
# Create empty DataFrames as fallback
APRIL_EOM = pd.DataFrame()
HOLDINGS_LATEST = pd.DataFrame()
TRADES = pd.DataFrame()
# Try to read PEERS file, with fallback if it fails
try:
# Remove any problematic parameters like showZeroes
PEERS = pd.read_excel(
os.path.join(DATA_PATH, "20250506_funds_open-end-fund-profile.xlsx"),
engine='openpyxl'
)
except Exception as e:
# Create synthetic PEERS data as fallback
PEERS = pd.DataFrame({
'Fund Name': ['Fund A', 'Fund B', 'Fund C', 'Fund D', 'Fund E', 'Fund F', 'Fund G', 'Fund H'],
'YTD Return': [2.1, 2.5, 2.8, 3.0, 3.2, 3.5, 3.8, 4.0]
})
# Use OS-agnostic path to assets directory
ASSETS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets')
LOGO_FILE = os.path.join(ASSETS_PATH, "Cannae-logo.jpg")
# Add error handling for logo display
try:
st.sidebar.image(LOGO_FILE)
except Exception as e:
st.sidebar.warning(f"Logo not found. Using text header instead.")
st.sidebar.title("Cannae Dashboard")
# Sidebar already has logo/title
# ---------- EXTRACT KPIS ----------
# Extract KPIs from Excel sheet
kpi_data = extract_kpis_from_factsheet()
# Extract key stats from risk report
key_stats = extract_key_stats_from_risk_report()
# Log key_stats for debugging
logging.debug(f"KEY STATS EXTRACTED: {key_stats}")
logging.debug(f"Extraction source: {key_stats.get('extraction_source', 'unknown')}")
# Populate kpi_data with ITD values from key_stats if available
if 'ITD Return' in key_stats and isinstance(key_stats.get('ITD Return'), dict):
kpi_data['itd_return_str'] = key_stats['ITD Return'].get('string_value', "N/A")
kpi_data['itd_return_float'] = key_stats['ITD Return'].get('float_value', 0.0)
else:
# Fallback if ITD Return is not in key_stats or not in expected format
kpi_data.setdefault('itd_return_str', "N/A")
kpi_data.setdefault('itd_return_float', 0.0)
# Populate kpi_data with Annualized ITD ROR values from key_stats if available
if 'Annualized ITD ROR' in key_stats and isinstance(key_stats.get('Annualized ITD ROR'), dict):
kpi_data['annualized_return_str'] = key_stats['Annualized ITD ROR'].get('string_value', "N/A")
kpi_data['annualized_return_float'] = key_stats['Annualized ITD ROR'].get('float_value', 0.0)
else:
# Fallback if Annualized ITD ROR is not in key_stats or not in expected format
kpi_data.setdefault('annualized_return_str', "N/A")
kpi_data.setdefault('annualized_return_float', 0.0)
# ---------- KPI STRIP ----------
st.markdown("## Returns")
col1, col2, col3, col4 = st.columns(4)
col1.metric("YTD Return", kpi_data["ytd_return_str"])
col2.metric("Monthly Return", kpi_data["monthly_return_str"])
col3.metric("Annualized Return", kpi_data["ann_return_str"])
col4.metric("AUM", kpi_data["aum_str"])
st.markdown("---") # Visual separator
# ---------- KEY STATS ----------
st.markdown("### Key Stats")
# Display key stats extracted from risk report
key_stats_col1, key_stats_col2, key_stats_col3, key_stats_col4 = st.columns(4)
# First row of metrics
key_stats_col1.metric("Average Yield", key_stats["avg_yield"])
key_stats_col2.metric("WAL", key_stats["wal"])
key_stats_col3.metric("% IG", key_stats["pct_ig"])
key_stats_col4.metric("Floating Rate %", key_stats["floating_rate_pct"])
# Second row of metrics
key_stats_row2_col1, key_stats_row2_col2, key_stats_row2_col3, key_stats_row2_col4 = st.columns(4)
key_stats_row2_col1.metric("% Risk Rating 1", key_stats["pct_risk_rating_1"])
key_stats_row2_col2.metric("Monthly Carry", key_stats["monthly_carry_bps"])
key_stats_row2_col3.metric("Bond Line Items", key_stats["bond_line_items"])
key_stats_row2_col4.metric("Average Holding Size", key_stats["avg_holding_size"])
# Third row with remaining metrics
key_stats_row3_col1, key_stats_row3_col2, key_stats_row3_col3, key_stats_row3_col4 = st.columns(4)
key_stats_row3_col1.metric("Top 10% Concentration", key_stats["top_10_concentration"])
key_stats_row3_col2.metric("CMBS Line Items", key_stats["bond_breakdown"].get("CMBS", 0))
key_stats_row3_col3.metric("ABS Line Items", key_stats["bond_breakdown"].get("ABS", 0))
key_stats_row3_col4.metric("CLO Line Items", key_stats["bond_breakdown"].get("CLO", 0))
# Fourth row with leverage metrics
key_stats_row4_col1, key_stats_row4_col2, key_stats_row4_col3, key_stats_row4_col4 = st.columns(4)
key_stats_row4_col1.metric("Total Leverage %", key_stats.get("total_leverage", "N/A"))
key_stats_row4_col2.metric("Repo MV", key_stats.get("repo_mv", "N/A"))
# ---------- ALLOCATION: PIE + DRIFT ----------
def categorize_cmbs(strategy):
"""Categorize CMBS holdings into Conduit, SASB, and Other categories."""
# Check if this is a CMBS strategy
if not isinstance(strategy, str) or 'CMBS' not in str(strategy).upper():
return strategy
strategy_str = str(strategy).upper()
# Debug logging to see what strategies we're processing
logging.debug(f"Categorizing CMBS strategy: {strategy}")
# Categorize CMBS Conduit - check for 2.0/3.0 patterns
if any(conduit_pattern in strategy_str for conduit_pattern in ['2.0/3.0', '2.0', '3.0', 'NON-IG']):
logging.debug(f" -> Categorized as CMBS Conduit: {strategy}")
return 'CMBS Conduit'
# Categorize CMBS SASB - check for all SASB patterns
if 'SASB' in strategy_str or 'SASB F1' in strategy_str or 'SASB F1_INCOME' in strategy_str:
logging.debug(f" -> Categorized as CMBS SASB: {strategy}")
return 'CMBS SASB'
# All other CMBS go to Other category
logging.debug(f" -> Categorized as CMBS - Other: {strategy}")
return 'CMBS - Other'
def summarize_alloc(df, split_cmbs=True):
# Create a copy of the dataframe to avoid modifying the original
df = df.copy()
# Handle different column names for strategy
strategy_column = 'Strategy'
if strategy_column not in df.columns:
# Try alternative column names
alternative_columns = ['Investment Description', 'Asset Class', 'Type', 'Security Type']
for col in alternative_columns:
if col in df.columns:
strategy_column = col
st.warning(f"Using '{strategy_column}' as the strategy column")
# Rename to standardize
df['Strategy'] = df[strategy_column]
break
else:
# If no suitable column found, create a default strategy column
st.warning(f"No strategy column found. Available columns: {df.columns.tolist()}")
logging.warning(f"No strategy column found in dataframe. Available columns: {df.columns.tolist()}")
df['Strategy'] = 'UNKNOWN'
# Create a simple dataframe with basic structure if completely empty
if len(df) == 0:
df = pd.DataFrame({
'Strategy': ['CASH'],
'Market Value': [100000]
})
# Check for Sub Strategy column for CMBS breakdown
sub_strategy_column = 'Sub Strategy'
has_sub_strategy = sub_strategy_column in df.columns
# If we have Sub Strategy column, use it for CMBS F1 items
if has_sub_strategy:
# Create a new column for the effective strategy (either Strategy or Sub Strategy)
df['Effective Strategy'] = df['Strategy']
# For CMBS F1 items, use the Sub Strategy value if available
cmbs_mask = df['Strategy'].str.contains('CMBS F1', case=False, na=False)
has_sub_strategy_mask = ~df[sub_strategy_column].isna() & (df[sub_strategy_column] != '')
# Only replace Strategy with Sub Strategy for CMBS F1 items that have a valid Sub Strategy
replace_mask = cmbs_mask & has_sub_strategy_mask
if replace_mask.any():
# For CMBS F1 items with SASB in the Sub Strategy, set to CMBS SASB
sasb_mask = replace_mask & df[sub_strategy_column].str.contains('SASB', case=False, na=False)
if sasb_mask.any():
df.loc[sasb_mask, 'Effective Strategy'] = 'CMBS SASB'
logging.debug(f"Applied CMBS SASB to {sasb_mask.sum()} CMBS F1 items with SASB in Sub Strategy")
# For other CMBS F1 items, use the Sub Strategy as is
other_mask = replace_mask & ~df[sub_strategy_column].str.contains('SASB', case=False, na=False)
if other_mask.any():
df.loc[other_mask, 'Effective Strategy'] = df.loc[other_mask, sub_strategy_column]
logging.debug(f"Applied Sub Strategy to {other_mask.sum()} other CMBS F1 items")
logging.debug(f"Total: Applied strategy mapping to {replace_mask.sum()} CMBS F1 items")
else:
# If no Sub Strategy column, just use the Strategy column
df['Effective Strategy'] = df['Strategy']
logging.debug("No Sub Strategy column found, using Strategy column only")
# Try to find an appropriate market value column
mv_column = 'Admin Net MV' # Default column name
# Make sure the column exists
if mv_column not in df.columns:
st.warning(f"Column '{mv_column}' not found in holdings data. Available columns: {df.columns.tolist()}")
# Fallback to other columns if needed
for col_name in ['Net MV', 'Curr MV', 'MV', 'Market Value', 'Position Value']:
if col_name in df.columns:
mv_column = col_name
st.warning(f"Falling back to '{mv_column}' column")
break
else:
# If no suitable column found, try to find any column with numeric values that might be market value
numeric_columns = df.select_dtypes(include=['float64', 'int64']).columns
if len(numeric_columns) > 0:
mv_column = numeric_columns[0]
st.warning(f"Using numeric column '{mv_column}' as market value")
else:
st.error("No suitable market value column found")
# Return empty dataframe with expected structure
return pd.DataFrame(columns=["Strategy", "Market Value"])
# Filter out CURRENCY and REPO as requested by user
# Keep HEDGE in the allocation
exclude_strategies = ['CURRENCY', 'REPO']
# Filter out excluded strategies
df = df[~df['Strategy'].isin(exclude_strategies)]
# Debug: Log filtered dataframe details
logging.debug(f"Summarize Alloc - Debug - Filtered Data - Using column: {mv_column}")
logging.debug(f"Summarize Alloc - Debug - Filtered Data - Total {mv_column} before grouping: ${df[mv_column].sum():,.2f}")
logging.debug(f"Summarize Alloc - Debug - Filtered Data - Head of df[['Effective Strategy', mv_column]]:\n{df[['Effective Strategy', mv_column]].head()}")
# Group by Effective Strategy and sum the MV column
result = df.groupby("Effective Strategy")[mv_column].sum().reset_index()
result.columns = ["Strategy", "Market Value"]
# Only include non-zero market values
if not result.empty:
result = result[result["Market Value"] != 0] # Remove zero market value entries
logging.debug(f"Summarize Alloc - Total Market Value: ${result['Market Value'].sum():,.2f}")
logging.debug(f"Summarize Alloc - Should match AUM: {kpi_data['aum_str']}")
# Apply CMBS categorization if requested
if split_cmbs:
# Apply the categorize_cmbs function to each strategy
result['Strategy'] = result['Strategy'].apply(categorize_cmbs)
# Re-group to combine the categorized CMBS strategies
result = result.groupby("Strategy")["Market Value"].sum().reset_index()
return result
# ---------- ALLOCATION VISUALIZATION ----------
st.markdown("## Portfolio Allocation")
# Create two columns for side-by-side pie charts
col1, col2 = st.columns(2)
# Process month-end data
with col1:
# Extract month name from filename for display
import re
month_match = re.search(r'eom_marks_([A-Za-z]+)', latest_eom_file) if latest_eom_file else None
month_name = month_match.group(1) if month_match else "Month-End"
# Update subheader with dynamic month name
st.subheader(f"{month_name} Month-End")
# Load the Position Holdings tab from the month-end file
try:
# Try to get the Position Holdings tab from APRIL_EOM
if 'Position Holdings' in pd.ExcelFile(os.path.join(DATA_PATH, latest_eom_file)).sheet_names:
month_end_holdings = pd.read_excel(os.path.join(DATA_PATH, latest_eom_file), sheet_name="Position Holdings", engine='openpyxl')
sheet_used = "Position Holdings"
else:
# Fallback to the first sheet
month_end_holdings = APRIL_EOM
sheet_used = "Default"
logging.debug(f"Debug - {month_name} Month-End Data:")
logging.debug(f" Using file: {latest_eom_file}")
logging.debug(f" Sheet used: {sheet_used}")
logging.debug(f" Loaded with {len(month_end_holdings)} rows")
logging.debug(f" Columns: {month_end_holdings.columns.tolist()}")
if 'Strategy' in month_end_holdings.columns:
logging.debug(f" Unique strategies: {month_end_holdings['Strategy'].unique()}")
else:
possible_strategy_columns = ['Investment Description', 'Asset Class', 'Type']
for col_name in possible_strategy_columns:
if col_name in month_end_holdings.columns:
logging.debug(f" Found potential strategy column '{col_name}': {month_end_holdings[col_name].unique()}")
# Use summarize_alloc to get month-end allocation data with CMBS breakdown
april_alloc_data = summarize_alloc(month_end_holdings, split_cmbs=True)
except Exception as e:
st.error(f"Error loading data from {month_name} file: {e}")
# Create empty DataFrame as fallback
april_alloc_data = pd.DataFrame(columns=["Strategy", "Market Value"])
# Format market values for display with $ and commas
april_alloc_data["Formatted Value"] = april_alloc_data["Market Value"].apply(lambda x: f"${x:,.0f}")
# Calculate percentages for each strategy
april_total_mv = april_alloc_data["Market Value"].sum()
april_alloc_data["Percentage"] = april_alloc_data["Market Value"] / april_total_mv * 100
# Process current holdings data
with col2:
# Use the global latest_holdings_file variable
holdings_file_path = os.path.join(DATA_PATH, latest_holdings_file) if latest_holdings_file else None
# Extract date from filename for display or use current date
import re
import datetime
# Try different regex patterns to match the date in the filename
date_str = "Current"
if latest_holdings_file:
# Try pattern like portfolio_holdings_5June2025.xlsx
date_match = re.search(r'holdings_([0-9]+[A-Za-z]+[0-9]+)', latest_holdings_file)
if date_match:
date_str = date_match.group(1)
# Try pattern like portfolio_holdings_June5.xlsx
else:
date_match = re.search(r'holdings_([A-Za-z]+[0-9]+)', latest_holdings_file)
if date_match:
date_str = date_match.group(1)
# Update subheader with dynamic date - simpler
st.subheader(f"{date_str} Holdings")
# Load current holdings data
try:
# Use the global HOLDINGS_LATEST variable directly
logging.debug(f"Debug - Current Holdings ({date_str}):")
logging.debug(f" Using file: {latest_holdings_file}")
logging.debug(f" Current holdings data with {len(HOLDINGS_LATEST)} rows")
logging.debug(f" Columns: {HOLDINGS_LATEST.columns.tolist()}")
if 'Strategy' in HOLDINGS_LATEST.columns:
logging.debug(f" Unique strategies: {HOLDINGS_LATEST['Strategy'].unique()}")
else:
possible_strategy_columns = ['Investment Description', 'Asset Class', 'Type']
for col_name in possible_strategy_columns:
if col_name in HOLDINGS_LATEST.columns:
logging.debug(f" Found potential strategy column '{col_name}': {HOLDINGS_LATEST[col_name].unique()}")
# Use summarize_alloc to get current allocation data with CMBS breakdown
current_alloc_data = summarize_alloc(HOLDINGS_LATEST, split_cmbs=True)
except Exception as e:
st.error(f"Error loading current holdings data: {e}")
# Create empty DataFrame as fallback
current_alloc_data = pd.DataFrame(columns=["Strategy", "Market Value"])
# Format market values for display with $ and commas
current_alloc_data["Formatted Value"] = current_alloc_data["Market Value"].apply(lambda x: f"${x:,.0f}")
# Calculate percentages for each strategy
current_total_mv = current_alloc_data["Market Value"].sum()
current_alloc_data["Percentage"] = current_alloc_data["Market Value"] / current_total_mv * 100
# Create pie charts for both April and current data
with col1:
# Display April allocation table
april_display = april_alloc_data.copy()
april_display["Allocation"] = april_display["Percentage"].apply(lambda x: f"{x:.1f}%")
april_display = april_display.sort_values(by="Percentage", ascending=False)
april_display = april_display[["Strategy", "Formatted Value", "Allocation"]]
# Add total row
april_display = pd.concat([april_display, pd.DataFrame({
"Strategy": ["TOTAL"],
"Formatted Value": [f"${april_total_mv:,.0f}"],
"Allocation": ["100.0%"]
})], ignore_index=True)
# Display the month-end table
st.write(f"**{month_name} Allocation by Strategy**")
st.dataframe(april_display, hide_index=True)
# Create hover text for April data
april_alloc_data["Hover Info"] = april_alloc_data.apply(
lambda row: f"Strategy: {row['Strategy']}<br>Amount: {row['Formatted Value']}<br>Allocation: {row['Percentage']:.1f}%",
axis=1
)
# Print strategy names to console for debugging
print("\n--- April Allocation Strategies for Pie Chart ---")
print(april_alloc_data['Strategy'].unique())
print("-----------------------------------------------\n")
logging.debug("--- April Allocation Strategies for Pie Chart ---")
logging.debug(april_alloc_data['Strategy'].unique())
logging.debug("-----------------------------------------------")
# Plot month-end allocation
strategy_color_map = {
# CMBS variations with new breakdown - using teal color variations
'CMBS Conduit': '#0F766E', # Dark teal for CMBS Conduit
'CMBS SASB': '#14B8A6', # Medium teal for CMBS SASB
'CMBS - Other': '#5EEAD4', # Light teal for CMBS Other
# Original CMBS variations (kept for backward compatibility)
'CMBS F1': '#0F766E', # Teal for CMBS F1 (as requested)
'CMBS': '#0F766E', # Same teal for any CMBS variation
'CMBS F2': '#0F766E', # Same teal for any CMBS variation