-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3735 lines (3407 loc) · 145 KB
/
Copy pathapp.py
File metadata and controls
3735 lines (3407 loc) · 145 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
import hmac
import importlib
import os
from html import escape
from pathlib import Path
import numpy as np
import pandas as pd
import altair as alt
import streamlit as st
try:
from streamlit.errors import StreamlitSecretNotFoundError
except ImportError: # pragma: no cover - compatibility with older Streamlit
StreamlitSecretNotFoundError = RuntimeError
import account_review as account_review_module
import strategy_books as strategy_books_module
from config import DATA_DIR
from portfolio_data import (
SNAPSHOT_STATUS_INTERIM,
SNAPSHOT_STATUS_OFFICIAL,
available_snapshots,
discover_snapshot_files,
load_snapshots,
snapshot_display_label,
)
account_review_module = importlib.reload(account_review_module)
strategy_books_module = importlib.reload(strategy_books_module)
asset_evidence = account_review_module.asset_evidence
asset_evidence_year_open = account_review_module.asset_evidence_year_open
comparison_summary = account_review_module.comparison_summary
assign_strategy_book_columns = strategy_books_module.assign_strategy_book_columns
STRATEGY_CLASSIFICATION_VERSION = strategy_books_module.STRATEGY_CLASSIFICATION_VERSION
EQUITY_DASHBOARD_LABEL_ORDER = strategy_books_module.EQUITY_DASHBOARD_LABEL_ORDER
EXTERNAL_STRATEGY_BOOK_ORDER = strategy_books_module.EXTERNAL_STRATEGY_BOOK_ORDER
OUTSOURCED_EQUITY_HOLDING_TYPE_ORDER = strategy_books_module.OUTSOURCED_EQUITY_HOLDING_TYPE_ORDER
MANAGER_DISPLAY_COLUMN = strategy_books_module.MANAGER_DISPLAY_COLUMN
STRATEGY_BOOK_LABEL_ORDER = strategy_books_module.STRATEGY_BOOK_LABEL_ORDER
equity_dashboard_summary = strategy_books_module.equity_dashboard_summary
excluded_strategy_book_detail = strategy_books_module.excluded_strategy_book_detail
outsourced_equity_holding_slice = strategy_books_module.outsourced_equity_holding_slice
strategy_book_detail_summary = strategy_books_module.strategy_book_detail_summary
strategy_book_summary = strategy_books_module.strategy_book_summary
ALL = "全部"
RETURN_BASE_THRESHOLD = 0.0001
DATA_SCHEMA_VERSION = "2026-07-22-parquet-only-v3"
ASSET_RETURN_PLAN_PATH = DATA_DIR.parent / "asset_return_plan_2026.csv"
MAINTENANCE_MESSAGE = "多事之秋,我们秋天再见"
MAINTENANCE_SUBMESSAGE = "如有需要微信找我"
CHART_EPSILON = 1e-9
# Columbia / BioShock Infinite palette: sky navy, brass, parchment, refined crimson.
POSITIVE_COLOR = "#1B3A5C"
NEGATIVE_COLOR = "#8C3A3A"
NEUTRAL_COLOR = "#8BA9BF"
FUNDING_COLOR = "#6E7F92"
HEATMAP_NEUTRAL_COLOR = "#F7F1E3"
HEATMAP_POSITIVE_LIGHT = "#B7D0E4"
HEATMAP_NEGATIVE_LIGHT = "#E3B6B0"
FUNDING_COST_RATE = 0.0341
GUARANTEE_COST_RATE = 0.0324
EFFECTIVE_COST_RATE = 0.0326
ACCOUNT_ORDER_PREFIX = [
"传统",
"自有",
"分红一",
"分红1",
"分红二",
"分红2",
"万能一",
"万能二",
"万能三",
"万能四",
"穿透账户",
]
REPO_FINANCING_ASSET_CLASSES = {"正回购"}
REVERSE_REPO_ASSET_CLASSES = {"逆回购", "买入返售"}
FUNDING_ASSET_CLASSES = REPO_FINANCING_ASSET_CLASSES | REVERSE_REPO_ASSET_CLASSES
EQUITY_THEME_KEYWORDS = ("股权", "长股投")
REAL_ESTATE_THEME_KEYWORDS = ("不动产",)
st.set_page_config(page_title="组合管理账户复盘 · Columbia", layout="wide")
def apply_columbia_theme() -> None:
"""Apply a restrained Columbia-inspired shell around the operating dashboard."""
st.html(
"""
<style>
:root {
--columbia-ink: #1C2433;
--columbia-navy: #1B3A5C;
--columbia-sky: #6FA8C9;
--columbia-sky-soft: #A8D0E4;
--columbia-brass: #C9A84C;
--columbia-brass-deep: #A8882E;
--columbia-brass-soft: #E8D48B;
--columbia-parchment: #F7F1E3;
--columbia-cream: #FFFBF3;
--columbia-border: #D9CDB5;
--columbia-muted: #5C6B7A;
--columbia-crimson: #8C3A3A;
--columbia-foam: #FBF6EC;
--rat-internal: #3D6F9A;
--rat-external: #2F7A6B;
}
html, body, [class*="css"] {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
}
.stApp {
background: #F4F3EE;
color: var(--columbia-ink);
}
.stApp::before {
display: none;
}
section.main > div {
position: relative;
z-index: 1;
}
section[data-testid="stSidebar"] {
background:
linear-gradient(180deg, #142844 0%, #1B3A5C 42%, #0F1F33 100%);
border-right: 1px solid rgba(201, 168, 76, 0.35);
}
section[data-testid="stSidebar"] * {
color: var(--columbia-foam);
}
section[data-testid="stSidebar"] div[data-baseweb="select"] * {
color: var(--columbia-ink);
}
section[data-testid="stSidebar"] div[data-baseweb="select"] {
background: var(--columbia-cream);
border-radius: 4px;
border: 1px solid rgba(201, 168, 76, 0.45);
}
section[data-testid="stSidebar"] input {
color: var(--columbia-ink);
background: var(--columbia-cream);
}
section[data-testid="stSidebar"] code,
section[data-testid="stSidebar"] pre,
section[data-testid="stSidebar"] kbd {
color: var(--columbia-ink) !important;
background: var(--columbia-cream) !important;
border: 1px solid rgba(201, 168, 76, 0.45);
border-radius: 4px;
white-space: normal;
overflow-wrap: anywhere;
}
section[data-testid="stSidebar"] p,
section[data-testid="stSidebar"] label,
section[data-testid="stSidebar"] span {
color: var(--columbia-foam);
}
section[data-testid="stSidebar"] h1,
section[data-testid="stSidebar"] h2,
section[data-testid="stSidebar"] h3 {
color: var(--columbia-brass-soft) !important;
font-family: inherit;
letter-spacing: 0;
border-bottom: none !important;
}
h1, h2, h3 {
color: var(--columbia-navy);
font-family: inherit;
letter-spacing: 0;
font-weight: 700;
}
h1 {
border-bottom: 2px solid var(--columbia-sky-soft);
padding-bottom: 0.38rem;
}
h2 {
border-left: 3px solid var(--columbia-brass);
padding-left: 0.65rem;
margin-top: 0.4rem;
}
h3 {
color: #2A4A6B;
}
div[data-testid="stMetric"] {
background: rgba(255, 255, 255, 0.78);
border: 1px solid var(--columbia-border);
border-radius: 6px;
padding: 0.85rem 1rem;
box-shadow: 0 2px 10px rgba(27, 58, 92, 0.05);
}
div[data-testid="stMetric"] label {
color: var(--columbia-navy);
font-family: inherit;
letter-spacing: 0;
}
div[data-testid="stMetricValue"] {
color: var(--columbia-ink);
}
.hero-banner {
margin: 0.15rem 0 0.9rem 0;
padding: 0.25rem 0 0.72rem 0.85rem;
background: transparent;
border: none;
border-left: 3px solid var(--columbia-brass);
}
.hero-banner::before,
.hero-banner::after {
display: none;
}
.hero-banner::before { left: 0.7rem; }
.hero-banner::after { right: 0.7rem; }
.hero-kicker {
font-family: inherit;
font-size: 0.72rem;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--columbia-brass-deep);
margin-bottom: 0.2rem;
text-align: left;
}
.hero-title {
font-family: inherit;
font-size: 1.8rem;
font-weight: 700;
color: var(--columbia-navy);
text-align: left;
letter-spacing: 0;
line-height: 1.25;
margin: 0;
}
.hero-subtitle {
margin-top: 0.28rem;
text-align: left;
color: var(--columbia-muted);
font-size: 0.9rem;
line-height: 1.4;
}
.filter-pills {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin: 0.55rem 0 1rem 0;
}
.filter-pill {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.34rem 0.62rem;
background: rgba(255, 255, 255, 0.72);
border: 1px solid var(--columbia-border);
border-radius: 5px;
color: var(--columbia-ink);
font-size: 0.86rem;
line-height: 1.25;
}
.filter-pill span {
color: var(--columbia-muted);
font-weight: 700;
font-family: inherit;
font-size: 0.78rem;
letter-spacing: 0;
}
.kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(176px, 1fr));
gap: 0.85rem;
margin: 0.65rem 0 0.85rem 0;
}
.kpi-card {
min-height: 96px;
background: rgba(255, 255, 255, 0.8);
border: 1px solid var(--columbia-border);
border-left: 4px solid var(--columbia-brass);
border-radius: 6px;
padding: 0.82rem 0.95rem;
box-shadow: 0 2px 10px rgba(27, 58, 92, 0.05);
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.kpi-card:hover {
border-color: rgba(201, 168, 76, 0.65);
box-shadow: 0 6px 18px rgba(27, 58, 92, 0.09);
}
.kpi-card.kpi-card-internal {
background: linear-gradient(180deg, rgba(61, 111, 154, 0.14) 0%, rgba(61, 111, 154, 0.06) 100%);
border-color: rgba(61, 111, 154, 0.35);
border-left-color: var(--rat-internal);
}
.kpi-card.kpi-card-external {
background: linear-gradient(180deg, rgba(47, 122, 107, 0.14) 0%, rgba(47, 122, 107, 0.06) 100%);
border-color: rgba(47, 122, 107, 0.34);
border-left-color: var(--rat-external);
}
.kpi-label {
color: var(--columbia-navy);
font-size: 0.8rem;
font-weight: 600;
font-family: inherit;
letter-spacing: 0;
line-height: 1.3;
margin-bottom: 0.45rem;
}
.kpi-value {
color: var(--columbia-ink);
font-size: 1.58rem;
font-weight: 700;
font-family: inherit;
line-height: 1.16;
overflow-wrap: anywhere;
}
.kpi-delta {
display: inline-block;
margin-top: 0.45rem;
color: #1F6B4A;
background: rgba(31, 107, 74, 0.1);
border-radius: 999px;
padding: 0.12rem 0.48rem;
font-size: 0.82rem;
font-weight: 700;
}
.kpi-delta.kpi-delta-positive {
color: var(--columbia-navy);
background: rgba(111, 168, 201, 0.2);
}
.kpi-delta.kpi-delta-negative {
color: var(--columbia-crimson);
background: rgba(140, 58, 58, 0.12);
}
.decision-summary {
margin: 0.35rem 0 0.75rem 0;
padding: 0.35rem 0 0.35rem 0.85rem;
color: var(--columbia-ink);
font-size: 1.02rem;
line-height: 1.7;
font-family: inherit;
background: transparent;
border-left: 2px solid var(--columbia-brass);
border-radius: 0;
}
.action-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
gap: 0.75rem;
margin: 0.8rem 0 1rem 0;
}
.action-card {
display: block;
min-height: 96px;
background: rgba(255, 255, 255, 0.8);
border: 1px solid var(--columbia-border);
border-radius: 6px;
padding: 0.85rem 0.9rem;
color: var(--columbia-ink) !important;
text-decoration: none;
box-shadow: 0 3px 12px rgba(27, 58, 92, 0.05);
transition: transform 0.12s ease, border-color 0.12s ease, box-shadow 0.12s ease;
}
.action-card,
.action-card * {
text-decoration: none !important;
}
.action-card:hover {
border-color: var(--columbia-brass);
box-shadow: 0 8px 20px rgba(27, 58, 92, 0.1);
transform: translateY(-1px);
text-decoration: none;
}
.action-title {
color: var(--columbia-navy);
font-family: inherit;
font-weight: 700;
letter-spacing: 0;
margin-bottom: 0.32rem;
}
.action-copy {
color: var(--columbia-muted);
font-size: 0.88rem;
line-height: 1.45;
}
.quality-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(142px, 1fr));
gap: 0.55rem;
margin: 0.8rem 0 0.6rem 0;
}
.quality-card {
background: rgba(255, 255, 255, 0.78);
border: 1px solid var(--columbia-border);
border-radius: 6px;
padding: 0.65rem 0.75rem;
}
.quality-card.hot {
border-color: var(--columbia-brass-deep);
background: linear-gradient(180deg, #FFF6E0 0%, #F8E8C4 100%);
box-shadow: inset 0 0 0 1px rgba(201, 168, 76, 0.25);
}
.quality-label {
color: var(--columbia-muted);
font-size: 0.78rem;
font-weight: 700;
font-family: inherit;
letter-spacing: 0;
margin-bottom: 0.2rem;
}
.quality-value {
color: var(--columbia-ink);
font-size: 1.35rem;
font-weight: 700;
font-family: inherit;
line-height: 1.12;
}
div[data-testid="stAlert"] {
border-radius: 6px;
border-color: rgba(201, 168, 76, 0.55);
background: rgba(255, 251, 243, 0.85);
}
.stButton > button {
background: var(--columbia-navy);
color: var(--columbia-foam);
border: 1px solid var(--columbia-navy);
border-radius: 4px;
font-family: inherit;
letter-spacing: 0;
font-weight: 600;
box-shadow: none;
}
.stButton > button:hover {
background: linear-gradient(180deg, #3A5F88 0%, #243F63 100%);
color: #FFF8E7;
border-color: var(--columbia-brass);
}
.stButton > button:focus {
box-shadow: 0 0 0 2px rgba(201, 168, 76, 0.35);
}
.sidebar-nav-button {
display: block;
width: 100%;
margin: 0.32rem 0;
padding: 0.45rem 0.7rem;
background: rgba(168, 208, 228, 0.1);
color: var(--columbia-foam) !important;
border: 1px solid rgba(201, 168, 76, 0.22);
border-left: 2px solid rgba(201, 168, 76, 0.55);
border-radius: 4px;
text-decoration: none;
font-weight: 600;
font-size: 0.88rem;
transition: background 0.12s ease, border-color 0.12s ease;
}
.sidebar-nav-button:hover {
background: rgba(201, 168, 76, 0.18);
border-color: rgba(201, 168, 76, 0.5);
color: #FFF8E7 !important;
text-decoration: none;
}
.sidebar-nav-title {
margin: 1rem 0 0.45rem 0;
color: var(--columbia-brass-soft) !important;
font-family: inherit;
font-weight: 600;
letter-spacing: 0;
text-transform: none;
font-size: 0.78rem;
opacity: 0.95;
}
div[data-testid="stDataFrame"] {
border: 1px solid var(--columbia-border);
border-radius: 6px;
overflow: hidden;
background: var(--columbia-cream);
box-shadow: 0 3px 12px rgba(27, 58, 92, 0.04);
}
div[data-testid="stVegaLiteChart"] {
background: rgba(255, 255, 255, 0.76);
border: 1px solid var(--columbia-border);
border-radius: 6px;
padding: 0.45rem;
box-shadow: 0 3px 12px rgba(27, 58, 92, 0.04);
}
div[data-testid="stCaptionContainer"] {
color: var(--columbia-muted);
font-family: inherit;
}
hr {
border-color: var(--columbia-border);
background: none;
}
</style>
""",
)
def render_hero_banner(title: str, subtitle: str, kicker: str = "Columbia · Portfolio Review") -> None:
st.markdown(
f"""
<div class="hero-banner">
<div class="hero-kicker">{html_text(kicker)}</div>
<div class="hero-title">{html_text(title)}</div>
<div class="hero-subtitle">{html_text(subtitle)}</div>
</div>
""",
unsafe_allow_html=True,
)
def _configured_password() -> str | None:
"""Read the app password from deployment-safe config, not source code."""
try:
if "app_password" in st.secrets:
return str(st.secrets["app_password"])
except StreamlitSecretNotFoundError:
pass
return os.environ.get("PORTFOLIO_APP_PASSWORD")
def _truthy(value: object) -> bool:
if value is None:
return False
return str(value).strip().lower() in {"1", "true", "yes", "on", "y"}
def _secret_flag(name: str) -> str | None:
try:
if name in st.secrets:
return str(st.secrets[name])
except StreamlitSecretNotFoundError:
return None
return None
def maintenance_mode_enabled() -> bool:
configured = os.environ.get("PORTFOLIO_APP_MAINTENANCE") or _secret_flag("maintenance_mode")
return _truthy(configured)
def render_maintenance_page() -> None:
st.markdown(
f"""
<style>
div[data-testid="stSidebar"] {{
display: none;
}}
section.main > div {{
padding-top: 24vh;
}}
.maintenance-message {{
color: var(--columbia-navy, #1B3A5C);
font-family: inherit;
font-size: clamp(2.4rem, 6.5vw, 5.5rem);
font-weight: 700;
line-height: 1.2;
text-align: center;
letter-spacing: 0;
border-bottom: 2px solid var(--columbia-brass, #C9A84C);
padding-bottom: 0.55rem;
}}
.maintenance-submessage {{
margin-top: 1.35rem;
color: var(--columbia-brass-deep, #A8882E);
font-family: inherit;
font-size: clamp(1.15rem, 2.3vw, 1.9rem);
font-weight: 600;
line-height: 1.3;
text-align: center;
letter-spacing: 0;
}}
</style>
<div class="maintenance-message">{html_text(MAINTENANCE_MESSAGE)}</div>
<div class="maintenance-submessage">{html_text(MAINTENANCE_SUBMESSAGE)}</div>
""",
unsafe_allow_html=True,
)
def require_login() -> None:
expected_password = _configured_password()
if not expected_password:
st.error("未配置访问密码。请在 Streamlit secrets 中设置 app_password,或设置环境变量 PORTFOLIO_APP_PASSWORD。")
st.stop()
if st.session_state.get("authenticated"):
return
render_hero_banner(
"组合管理账户复盘",
"请输入访问密码后继续。",
kicker="Columbia / Authorized Entry",
)
password = st.text_input("访问密码", type="password")
if st.button("进入"):
if hmac.compare_digest(password, expected_password):
st.session_state["authenticated"] = True
st.rerun()
else:
st.error("密码不正确。")
st.stop()
DISPLAY_NAMES = {
"snapshot_date": "数据时点",
"snapshot_month": "快照月份",
"snapshot_status": "快照状态",
"source_file_name": "源文件名",
"source_file_hash": "源文件哈希",
"source_rows": "源表行数",
"status": "状态",
"message": "校验信息",
"full_market_value": "全价市值(亿)",
"finance_income_mtd": "本月财务收益(亿)",
"comprehensive_income_mtd": "本月综合收益(亿)",
"duration": "久期",
"account_bucket": "账户",
"mandate_type": "委受托维度",
"fund_book_name": "基金账套名称",
"group_book_name": "分组账套名称",
"asset_major_class": "资产大类",
"asset_class_level_1": "资产分类一级",
"asset_class_level_2": "资产分类二级",
"asset_class_level_3": "资产分类三级",
"asset_theme": "资产主题",
"asset_class_display": "投资品种展示",
"asset_class": "投资品种",
"trade_strategy": "交易策略",
"manager": "投资经理",
"manager_display": "投资经理/受托机构",
"asset_name": "资产名称",
"asset_code": "资产代码",
"trade_code": "交易代码",
"change_type": "变化类型",
"full_market_value_current": "当前时点市值(亿)",
"full_market_value_prior": "上月市值(亿)",
"full_market_value_delta": "较上月变化(亿)",
"net_full_market_value_delta": "扣收益后较上月规模变化(亿)",
"ytd_position_flow_delta": "扣综合收益后较年初加减仓(亿)",
"monthly_position_flow_delta": "扣本月综合收益后较上月加减仓(亿)",
"finance_income_mtd_current": "本月财务收益(亿)",
"comprehensive_income_mtd_current": "本月综合收益(亿)",
"finance_income_mtd_delta": "财务收益变化(亿)",
"comprehensive_income_mtd_delta": "综合收益变化(亿)",
"finance_income_period": "本月财务收益(亿)",
"comprehensive_income_period": "本月综合收益(亿)",
"avg_capital_mtd_current": "本月平均资本占用(亿)",
"finance_return_mtd": "本月财务收益率",
"comprehensive_return_mtd": "本月综合收益率",
"record_count_current": "当前记录数",
"source_rows_current": "当前源行数",
"source_rows_prior": "上月源行数",
"weighted_duration": "账户加权久期",
"duration_market_value": "纳入久期计算市值(亿)",
"duration_coverage_ratio": "久期市值覆盖率",
"duration_asset_count": "纳入久期资产数",
"plan_asset": "计划资产项",
"plan_balance": "计划余额(亿)",
"target_return_mid": "目标收益率中枢",
"target_return_low": "目标收益率下限",
"target_return_high": "目标收益率上限",
"target_return_range": "目标收益率区间",
"actual_ytd_comprehensive_return": "当前YTD综合收益率",
"actual_annualized_comprehensive_return": "当前年化综合收益率",
"planned_income": "年度计划综合收益(亿)",
"actual_ytd_income": "当前YTD综合收益(亿)",
"actual_annualized_income": "当前年化综合收益(亿)",
"income_gap": "收益缺口/超额(亿)",
"income_completion_rate": "收益金额完成率",
"allocation_gap": "配置差额(亿)",
"return_completion_status": "收益金额完成状态",
"return_rate_status": "收益率状态",
"return_deviation": "收益率偏离幅度",
"mapped_asset_classes": "映射投资品种",
"strategy_book_scope": "委内/委外",
"strategy_book": "配置/交易分类",
"strategy_book_display_label": "委内/委外分类",
"strategy_book_section": "二级展示",
"strategy_book_item": "明细展示",
"strategy_book_exclusion_reason": "未纳入原因",
"outsourced_equity_holding_type": "权益类型",
"equity_scope": "范围",
"equity_group_display_label": "比较项",
}
YTD_DISPLAY_OVERRIDES = {
"full_market_value_prior": "年初市值(亿)",
"full_market_value_delta": "较年初变化(亿)",
"net_full_market_value_delta": "扣收益后较年初规模变化(亿)",
"finance_income_mtd_current": "年初以来财务收益(亿)",
"comprehensive_income_mtd_current": "年初以来综合收益(亿)",
"finance_income_period": "年初以来财务收益(亿)",
"comprehensive_income_period": "年初以来综合收益(亿)",
"avg_capital_mtd_current": "本年以来平均资本占用(亿)",
"finance_return_mtd": "年初以来财务收益率",
"comprehensive_return_mtd": "年初以来综合收益率",
"source_rows_prior": "年初源行数",
}
AMOUNT_COLUMNS = {
"full_market_value",
"finance_income_mtd",
"comprehensive_income_mtd",
"full_market_value_current",
"full_market_value_prior",
"full_market_value_delta",
"net_full_market_value_delta",
"ytd_position_flow_delta",
"monthly_position_flow_delta",
"finance_income_mtd_current",
"comprehensive_income_mtd_current",
"finance_income_mtd_delta",
"comprehensive_income_mtd_delta",
"finance_income_period",
"comprehensive_income_period",
"avg_capital_mtd_current",
"duration_market_value",
"plan_balance",
"planned_income",
"actual_ytd_income",
"actual_annualized_income",
"income_gap",
"allocation_gap",
}
PCT_COLUMNS = {
"finance_return_mtd",
"comprehensive_return_mtd",
"duration_coverage_ratio",
"target_return_mid",
"target_return_low",
"target_return_high",
"actual_ytd_comprehensive_return",
"actual_annualized_comprehensive_return",
"income_completion_rate",
"return_deviation",
}
DURATION_COLUMNS = {"duration", "weighted_duration"}
COUNT_COLUMNS = {
"record_count",
"record_count_current",
"source_rows",
"source_rows_current",
"source_rows_prior",
"duration_asset_count",
}
RUNTIME_COLUMN_DEFAULTS = {
"market_value_year_open": 0.0,
"avg_capital_ytd": 0.0,
"finance_income_ytd": 0.0,
"comprehensive_income_ytd": 0.0,
"asset_major_class": "",
"asset_class_level_1": "",
"asset_class_level_2": "",
"asset_class_level_3": "",
"trade_strategy": "",
}
def data_source_signature(data_dir: Path) -> tuple[tuple[str, int, int], ...]:
parquet_dir = data_dir.parent / "snapshot_parquet"
candidates = [
*discover_snapshot_files(data_dir),
*parquet_dir.glob("*.parquet"),
parquet_dir / "manifest.json",
]
signature: list[tuple[str, int, int]] = []
for path in sorted({candidate for candidate in candidates if candidate.exists()}):
stat = path.stat()
signature.append((str(path.relative_to(data_dir.parent)), stat.st_size, stat.st_mtime_ns))
return tuple(signature)
def snapshot_slice(data: pd.DataFrame, snapshot_date: str) -> pd.DataFrame:
key = "snapshot_date" if "snapshot_date" in data.columns else "snapshot_month"
return data[data[key] == snapshot_date]
def snapshot_status_map(data: pd.DataFrame) -> dict[str, str]:
if data.empty or not {"snapshot_date", "snapshot_status"}.issubset(data.columns):
return {}
metadata = data[["snapshot_date", "snapshot_status"]].drop_duplicates("snapshot_date")
return dict(zip(metadata["snapshot_date"].astype(str), metadata["snapshot_status"].astype(str)))
def previous_official_snapshots(data: pd.DataFrame, current_snapshot: str) -> list[str]:
if data.empty or not {"snapshot_date", "snapshot_month", "snapshot_status"}.issubset(data.columns):
return []
current_rows = data[data["snapshot_date"].astype(str).eq(current_snapshot)]
if current_rows.empty:
return []
current_report_month = str(current_rows["snapshot_month"].iloc[0])
previous_report_month = str(pd.Period(current_report_month, freq="M") - 1)
metadata = data[["snapshot_date", "snapshot_month", "snapshot_status"]].drop_duplicates("snapshot_date")
candidates = metadata[
metadata["snapshot_status"].eq(SNAPSHOT_STATUS_OFFICIAL)
& metadata["snapshot_month"].astype(str).eq(previous_report_month)
]
return sorted(candidates["snapshot_date"].astype(str).tolist())
@st.cache_data(show_spinner="正在读取并预处理月度宽表...")
def cached_load(
data_dir: str,
schema_version: str,
classification_version: str,
source_signature: tuple[tuple[str, int, int], ...],
):
del schema_version, classification_version, source_signature
data, validation, errors = load_snapshots(Path(data_dir))
if errors or data.empty:
return data, validation, errors
return assign_strategy_book_columns(data), validation, errors
def missing_runtime_columns(data: pd.DataFrame) -> list[str]:
return [column for column in RUNTIME_COLUMN_DEFAULTS if column not in data.columns]
def ensure_runtime_columns(data: pd.DataFrame) -> tuple[pd.DataFrame, list[str]]:
missing = missing_runtime_columns(data)
if not missing:
return data, []
data = data.copy()
for column in missing:
data[column] = RUNTIME_COLUMN_DEFAULTS[column]
return data, missing
def ensure_summary_columns(summary: pd.DataFrame, comparison_mode: str) -> pd.DataFrame:
summary = summary.copy()
def numeric_column(column: str, default: float = 0.0) -> pd.Series:
if column not in summary.columns:
return pd.Series(default, index=summary.index, dtype=float)
return pd.to_numeric(summary[column], errors="coerce").fillna(default)
if "finance_income_period" not in summary.columns:
if comparison_mode == "年初以来":
summary["finance_income_period"] = numeric_column("finance_income_ytd_current")
else:
summary["finance_income_period"] = numeric_column("finance_income_mtd_current")
if "comprehensive_income_period" not in summary.columns:
if comparison_mode == "年初以来":
summary["comprehensive_income_period"] = numeric_column("comprehensive_income_ytd_current")
else:
summary["comprehensive_income_period"] = numeric_column("comprehensive_income_mtd_current")
if "net_full_market_value_delta" not in summary.columns:
summary["net_full_market_value_delta"] = (
numeric_column("full_market_value_delta") - numeric_column("comprehensive_income_period")
)
return summary
def display_names_for_mode(comparison_mode: str) -> dict[str, str]:
names = DISPLAY_NAMES.copy()
if comparison_mode == "年初以来":
names.update(YTD_DISPLAY_OVERRIDES)
return names
def clean_for_display(frame: pd.DataFrame, comparison_mode: str = "单月复盘") -> pd.DataFrame:
display = frame.replace([np.inf, -np.inf], np.nan).copy()
display = display.where(pd.notna(display), np.nan)
return display.rename(columns=display_names_for_mode(comparison_mode))
def format_table(frame: pd.DataFrame, precision: str = "display", comparison_mode: str = "单月复盘"):
display_names = display_names_for_mode(comparison_mode)
display = clean_for_display(frame, comparison_mode)
amount_decimals = 4 if precision == "source" else 2
formatters = {}
for source_col, display_col in display_names.items():
if display_col not in display.columns:
continue
if source_col in AMOUNT_COLUMNS:
formatters[display_col] = f"{{:,.{amount_decimals}f}}"
elif source_col in PCT_COLUMNS:
formatters[display_col] = "{:.2%}"
elif source_col in DURATION_COLUMNS:
formatters[display_col] = "{:,.2f}"
elif source_col in COUNT_COLUMNS:
formatters[display_col] = "{:,.0f}"
return display.style.format(formatters, na_rep="—")
def amount(value: float) -> str:
if value is None or not np.isfinite(value):
return "—"
return f"{value:,.2f} 亿"
def pct(value: float) -> str:
if value is None or not np.isfinite(value):
return "—"
return f"{value:.2%}"
def signed_amount(value: float) -> str:
if value is None or not np.isfinite(value):
return "—"
sign = "+" if value >= 0 else ""
return f"{sign}{value:,.2f} 亿"
def html_text(value: object) -> str:
return escape(str(value), quote=True)
def render_filter_pills(
current_month: str,
comparison_mode: str,
prior_month: str,
selected_account: str,
selected_asset_class: str,
selected_manager: str,
) -> None:
current_label = snapshot_display_label(current_month)
if comparison_mode == "年初以来":
view_text = f"年初以来,截至 {current_label}"
else:
view_text = f"{current_label} 单月复盘,规模较 {snapshot_display_label(prior_month)}"
items = [
("当前视角", view_text),
]
items.extend(
[
("账户", selected_label(selected_account)),
("投资品种", selected_label(selected_asset_class)),
("投资经理/受托机构", selected_label(selected_manager)),
]
)
pills = "".join(
f'<div class="filter-pill"><span>{html_text(label)}</span>{html_text(value)}</div>'
for label, value in items
)
st.markdown(f'<div class="filter-pills">{pills}</div>', unsafe_allow_html=True)