-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2592 lines (2203 loc) · 114 KB
/
Copy pathapp.py
File metadata and controls
2592 lines (2203 loc) · 114 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
from __future__ import annotations
from datetime import date, timedelta, datetime
import html
import sqlite3
import pandas as pd
import plotly.express as px
import streamlit as st
from streamlit_lightweight_charts import renderLightweightCharts
from db import (
DB_PATH,
get_ledger,
get_trade_by_id,
get_trades,
init_db,
insert_ledger,
insert_trade,
update_trade,
)
from utils.enums import (
ACTION_LABELS,
DEFAULT_SUB_TYPE_BY_STRATEGY,
EXECUTION_SCORES,
LEDGER_TYPES,
MARKETS,
OPTION_RIGHTS,
OUTCOME_TYPES,
RESULT_STATUSES,
STRATEGY_LABELS,
SUB_TYPE_LABELS,
format_action,
format_strategy,
format_sub_type,
format_ledger_type,
)
from utils.metrics import (
build_equity_curve,
build_lightweight_series,
compute_annualized_return,
compute_gross_amount,
compute_net_cash_flow,
infer_break_even,
none_if_zero,
normalize_text,
safe_float,
summarize_trades,
)
def req(label: str) -> str:
return f"**{label}** :red[*]"
st.set_page_config(page_title="期权交易日志", page_icon="📊", layout="wide")
st.markdown(
"""
<style>
#MainMenu {visibility: hidden;}
header, footer, [data-testid="stToolbar"], [data-testid="stDecoration"], [data-testid="stStatusWidget"] {display: none !important;}
.block-container {padding-top: 0rem !important; padding-bottom: 0.5rem !important;}
.trade-header, .trade-row {font-size: 13px;}
.trade-header {font-weight: 700; padding: 3px 0 5px 0; border-bottom: 1px solid rgba(49,51,63,0.18);}
.trade-row {padding: 2px 0; border-bottom: 1px solid rgba(49,51,63,0.10); min-height: 24px;}
.trade-row.trade-open {color: #dc2626; font-weight: 700;}
.detail-card-grid-3 {display: grid; grid-template-columns: repeat(3, minmax(0,1fr)); gap: 10px; margin:6px 0 12px;}
.detail-card-grid-4 {display: grid; grid-template-columns: repeat(4, minmax(0,1fr)); gap: 10px; margin:6px 0 12px;}
.detail-card {border: 1px solid rgba(49,51,63,0.12); border-radius: 14px; padding:10px 12px; background:#f8fafc; min-height:120px;}
.detail-card-title {font-size:18px; font-weight:700; margin-bottom:6px; color:#111827;}
.detail-card-row {display:flex; justify-content:space-between; margin:2px 0; font-size:16px;}
.detail-card-label {color:#6b7280; font-size:14px;}
.detail-card-value {color:#111827; font-weight:600; text-align:right;}
/* 统一按钮样式 */
.stButton > button, .stFormSubmitButton > button {
border-radius: 10px !important;
font-weight: 700 !important;
padding: 0.42rem 0.85rem !important;
border: 1px solid rgba(49,51,63,0.18) !important;
}
.stButton > button:hover, .stFormSubmitButton > button:hover {
border-color: rgba(37,99,235,0.55) !important;
}
/* 分页按钮强制缩小 */
div[data-testid="column"] button {
padding: 0.2rem 0.5rem !important;
font-size: 12px !important;
min-height: 1.8rem !important;
border-radius: 6px !important;
}
/* 分页增强页码 */
div[data-testid="column"] button {
padding: 0.2rem 0.55rem !important;
font-size: 12px !important;
min-height: 1.9rem !important;
border-radius: 6px !important;
white-space: nowrap !important;
}
/* 分页按钮专用:按 key 精准缩小 */
div[data-testid="stButton"] button[kind="secondary"] {
white-space: nowrap !important;
}
div[data-testid="stButton"] button {
line-height: 1.1 !important;
}
</style>
""",
unsafe_allow_html=True,
)
init_db()
COMBO_STRATEGIES = {"COLLAR", "SYNTHETIC_SHORT", "SYNTHETIC_LONG"}
# ====================== 顶部导航跳转处理 ======================
if "pending_nav" in st.session_state:
st.session_state["nav_page"] = st.session_state["pending_nav"]
del st.session_state["pending_nav"]
nav_options = ["录入交易日志", "交易日志显示", "修改交易日志", "交易日志回填", "日志回收站", "资金流水录入", "资金流水查看", "统计总结", "常用链接"]
if "nav_page" not in st.session_state or st.session_state["nav_page"] not in nav_options:
st.session_state["nav_page"] = "交易日志显示"
page = st.sidebar.radio("导航", nav_options, key="nav_page")
if "selected_trade_id" not in st.session_state:
st.session_state.selected_trade_id = None
if "trade_page" not in st.session_state:
st.session_state.trade_page = 1
if "backfill_trade_id" not in st.session_state:
st.session_state.backfill_trade_id = None
if "edit_trade_id" not in st.session_state:
st.session_state.edit_trade_id = None
if "need_clear_selection" not in st.session_state:
st.session_state.need_clear_selection = False
if "show_review_dialog_trade_id" not in st.session_state:
st.session_state.show_review_dialog_trade_id = None
if "edit_save_message" not in st.session_state:
st.session_state.edit_save_message = ""
if "edit_save_error" not in st.session_state:
st.session_state.edit_save_error = ""
if "confirm_delete_trade_id" not in st.session_state:
st.session_state.confirm_delete_trade_id = None
if "last_deleted_trade_id" not in st.session_state:
st.session_state.last_deleted_trade_id = None
if "last_deleted_trade_label" not in st.session_state:
st.session_state.last_deleted_trade_label = ""
if "show_related_contract_dialog_trade_id" not in st.session_state:
st.session_state.show_related_contract_dialog_trade_id = None
def as_date(value, fallback=None):
dt = pd.to_datetime(value, errors="coerce")
if pd.isna(dt):
return fallback or date.today()
return dt.date()
def generate_position_id_by_trade_date(trade_date_value) -> str:
"""
自动生成交易日志编号:YYYYMMDD01 ~ YYYYMMDD99。
只生成用户可见的 position_id,不修改数据库主键 id。
"""
trade_dt = as_date(trade_date_value, date.today())
date_str = trade_dt.strftime("%Y%m%d")
df_today = get_trades("date(trade_date) = date(:d)", {"d": str(trade_dt)})
used_seq = []
if not df_today.empty and "position_id" in df_today.columns:
for pid in df_today["position_id"].dropna().astype(str):
pid = pid.strip()
if pid.startswith(date_str) and len(pid) >= 10:
tail = pid[-2:]
if tail.isdigit():
used_seq.append(int(tail))
next_seq = max(used_seq, default=0) + 1
if next_seq > 99:
raise ValueError(f"{date_str} 当天交易编号已超过 99 条上限,无法继续新增")
return f"{date_str}{next_seq:02d}"
def format_execution_symbol(row) -> str:
"""日志列表用简短腿型显示执行方向:+C/-C/+P/-P。
仅用于展示,不改变数据库字段和任何盈亏计算。
"""
strategy = str(row.get("option_strategy") or "").upper()
action = str(row.get("action") or "").upper()
if strategy == "CALL":
return "+C" if action == "BTO" else "-C"
if strategy in ["PUT", "CSP"]:
return "+P" if action == "BTO" else "-P"
if strategy in ["SYNTHETIC_SHORT", "COLLAR"]:
return "+P -C"
if strategy == "SYNTHETIC_LONG":
return "+C -P"
if strategy == "CALL_SPREAD":
return "+C -C"
if strategy == "PUT_SPREAD":
return "+P -P"
if strategy == "IRON_CONDOR":
return "+P -P -C +C"
if strategy == "STRANGLE":
return "-P -C"
if strategy == "CC":
return "-C"
if strategy == "STOCK":
return "买股" if action == "BUY_SHARES" else "卖股"
return action
def get_strike_leg_symbols(row) -> list[str]:
"""合约信息卡片里给执行价加腿型前缀,如 +P/-C。
仅用于展示,不改变数据库字段和任何盈亏计算。
"""
strategy = str(row.get("option_strategy") or "").upper()
action = str(row.get("action") or "").upper()
if strategy == "CALL":
return ["+C" if action == "BTO" else "-C"]
if strategy in ["PUT", "CSP"]:
return ["+P" if action == "BTO" else "-P"]
if strategy in ["SYNTHETIC_SHORT", "COLLAR"]:
return ["+P", "-C"]
if strategy == "SYNTHETIC_LONG":
return ["+C", "-P"]
if strategy == "CALL_SPREAD":
return ["+C", "-C"]
if strategy == "PUT_SPREAD":
return ["+P", "-P"]
if strategy == "IRON_CONDOR":
return ["+P", "-P", "-C", "+C"]
if strategy == "STRANGLE":
return ["-P", "-C"]
if strategy == "CC":
return ["-C"]
return []
def display_trade_df(df: pd.DataFrame) -> pd.DataFrame:
if df.empty:
return df
out = df.copy()
out["action_display"] = out["action"].fillna("").map(lambda x: f"{x} - {ACTION_LABELS.get(x, x)}")
out["execution_display"] = out.apply(format_execution_symbol, axis=1)
out["strategy_display"] = out["option_strategy"].fillna("").map(lambda x: STRATEGY_LABELS.get(x, x) if x else "")
out["sub_type_display"] = out["sub_type"].fillna("").map(lambda x: str(x) if x else "")
return out
def display_ledger_df(df: pd.DataFrame) -> pd.DataFrame:
if df.empty:
return df
out = df.copy()
if "ledger_type" in out.columns:
out["ledger_type_display"] = out["ledger_type"].fillna("").map(format_ledger_type)
return out
def get_sub_type_options_for_strategy(strategy: str) -> list[str]:
"""根据策略限制子类型,避免录入时选到明显不匹配的 Credit/Debit。"""
strategy = (strategy or "").upper()
if strategy == "STOCK":
return []
if strategy in ["CSP", "CC", "IRON_CONDOR", "STRANGLE"]:
return ["CREDIT"]
if strategy in ["CALL", "PUT", "CALL_SPREAD", "PUT_SPREAD", "COLLAR", "SYNTHETIC_SHORT", "SYNTHETIC_LONG"]:
return ["DEBIT", "CREDIT"]
return list(SUB_TYPE_LABELS.keys())
def get_action_options_for_strategy(strategy: str, sub_type: str | None = None) -> list[str]:
"""根据策略和子类型限制动作。
说明:组合策略没有新增数据库字段,仍用 BTO/STO 表示组合净现金流方向:
- DEBIT -> BTO,代表净付权利金
- CREDIT -> STO,代表净收权利金
这样可以复用原 compute_net_cash_flow 逻辑。
"""
strategy = (strategy or "").upper()
sub_type = (sub_type or "").upper()
if strategy == "STOCK":
return ["BUY_SHARES", "SELL_SHARES"]
if strategy in ["CSP", "CC", "IRON_CONDOR", "STRANGLE"]:
return ["STO"]
if strategy in ["CALL", "PUT", "CALL_SPREAD", "PUT_SPREAD", "COLLAR", "SYNTHETIC_SHORT", "SYNTHETIC_LONG"]:
return ["STO"] if sub_type == "CREDIT" else ["BTO"]
return list(ACTION_LABELS.keys())
def get_default_option_right(strategy: str) -> str:
if strategy == "STOCK": return "NONE"
if strategy in ["PUT", "CSP", "PUT_SPREAD"]: return "PUT"
if strategy in ["CALL", "CC", "CALL_SPREAD"]: return "CALL"
if strategy in ["COLLAR", "SYNTHETIC_SHORT", "SYNTHETIC_LONG"]: return "BOTH"
return "BOTH"
def get_strike_labels(strategy: str) -> list[str]:
if strategy == "CALL": return ["Call Strike Price"]
if strategy == "PUT": return ["Put Strike Price"]
if strategy == "CALL_SPREAD": return ["Long Call Price", "Short Call Price"]
if strategy == "PUT_SPREAD": return ["Long Put Price", "Short Put Price"]
if strategy == "IRON_CONDOR": return ["Long Put Price", "Short Put Price", "Short Call Price", "Long Call Price"]
if strategy == "STRANGLE": return ["Short Put Price", "Short Call Price"]
if strategy == "COLLAR": return ["Long Put Strike Price", "Short Call Strike Price"]
if strategy == "SYNTHETIC_SHORT": return ["Long Put Strike Price", "Short Call Strike Price"]
if strategy == "SYNTHETIC_LONG": return ["Long Call Strike Price", "Short Put Strike Price"]
if strategy == "CSP": return ["Short Put Price"]
if strategy == "CC": return ["Short Call Price"]
if strategy == "STOCK": return []
return ["Strike Price"]
def validate_trade_form(option_strategy: str, sub_type, ticker: str, expiry_date, strike_values):
errors = []
if not (option_strategy or "").strip(): errors.append("期权策略 为必填项")
if not (ticker or "").strip(): errors.append("Ticker / 标的 为必填项")
if option_strategy != "STOCK" and not sub_type: errors.append("子类型 为必填项")
if option_strategy != "STOCK" and not expiry_date: errors.append("到期日 为必填项")
labels = get_strike_labels(option_strategy)
for i, label in enumerate(labels):
v = strike_values[i] if i < len(strike_values) else None
if v is None or float(v) <= 0:
errors.append(f"{label} 必须大于 0")
return errors
def validate_backfill_form(closed_date, result_status, execution_score, closed_pnl, outcome_type):
errors = []
if not closed_date: errors.append("平仓日期 为必填项")
if not result_status: errors.append("结果状态 为必填项")
if not execution_score: errors.append("是否按计划执行 为必填项")
if closed_pnl is None: errors.append("已实现盈亏 为必填项")
if not outcome_type: errors.append("结果归因 为必填项")
return errors
def zh_col_name(col: str) -> str:
mapping = {
"id": "ID", "trade_date": "交易日期", "position_id": "编号", "ticker": "标的",
"action_display": "动作", "execution_display": "执行", "strategy_display": "策略", "sub_type_display": "子类型",
"expiry_date": "到期日", "strike_price": "执行价1", "strike_price_2": "执行价2",
"strike_price_3": "执行价3", "strike_price_4": "执行价4", "qty": "数量",
"premium": "权利金", "fees": "手续费", "net_cash_flow": "净现金流",
"result_status": "状态", "closed_pnl": "已实现盈亏", "closed_date": "平仓日期",
}
return mapping.get(col, col)
def render_detail_cards(detail_row: pd.Series, show_review: bool = True, columns: int = 3):
if detail_row is None or detail_row.empty:
return
# def val(field: str, default: str = ""):
# v = detail_row.get(field, default)
# return "" if pd.isna(v) else str(v)
def val(field: str, default: str = ""):
v = detail_row.get(field, default)
if pd.isna(v):
return ""
# 金额类字段:固定显示 2 位小数
money_fields = {
"premium",
"gross_amount",
"fees",
"net_cash_flow",
"closed_pnl",
"max_profit",
"max_loss",
"margin_req",
"buying_power_effect",
"break_even",
"share_price_at_trans",
"strike_price",
"strike_price_2",
"strike_price_3",
"strike_price_4"
}
if field in money_fields:
try:
return f"{float(v):.2f}"
except Exception:
return str(v)
return str(v)
strike_leg_symbols = get_strike_leg_symbols(detail_row)
def strike_val(field: str, index: int) -> str:
value = val(field)
if not value:
return ""
symbol = strike_leg_symbols[index] if index < len(strike_leg_symbols) else ""
return f"{symbol} {value}".strip()
def assigned_display() -> str:
"""复盘信息中的是否被指派:0/空不显示,1 显示“是”。"""
v = detail_row.get("assigned", None)
if pd.isna(v):
return ""
try:
return "是" if int(float(v)) == 1 else ""
except Exception:
return "是" if str(v).strip().lower() in {"1", "true", "yes", "是"} else ""
groups = {
"基本信息": [
("标的", val("ticker")),
("编号", val("id")), ("持仓ID", val("position_id")), ("交易日期", val("trade_date")),
("开仓日期", val("opened_date")), ("市场", val("market")),
("动作", f"{val('action')} - {ACTION_LABELS.get(val('action'), val('action'))}" if val("action") else ""),
("策略", f"{val('option_strategy')} - {STRATEGY_LABELS.get(val('option_strategy'), val('option_strategy'))}" if val("option_strategy") else ""),
],
"合约信息": [
("子类型", f"{val('sub_type')} - {SUB_TYPE_LABELS.get(val('sub_type'), val('sub_type'))}" if val("sub_type") else ""),
("到期日", val("expiry_date")),
("执行价1", strike_val("strike_price", 0)), ("执行价2", strike_val("strike_price_2", 1)),
("执行价3", strike_val("strike_price_3", 2)), ("执行价4", strike_val("strike_price_4", 3)),
("方向", val("option_right")), ("DTE", val("dte")),
("关联合约", format_related_trade_text(int(detail_row.get("id")))),
("开仓理由", val("entry_reason")),
("退出计划", val("exit_plan")),
("滚动计划", val("roll_plan")),
],
"交易信息": [
("数量", val("qty")), ("乘数", val("multiplier")), ("标的价格", val("share_price_at_trans")),
("权利金 / 单价", val("premium")), ("毛额", val("gross_amount")), ("手续费", val("fees")),
("净现金流", val("net_cash_flow")), ("策略标签", val("strategy_tag")),
],
"风险与Greeks": [
("IV", val("iv")), ("IV Rank", val("iv_rank")), ("IV Percentile", val("iv_percentile")),
("Delta", val("delta")), ("Theta", val("theta")), ("Vega", val("vega")), ("PoP %", val("pop")),
("盈亏平衡", val("break_even")), ("最大收益", val("max_profit")), ("最大风险", val("max_loss")),
("保证金需求", val("margin_req")), ("Buying Power Effect", val("buying_power_effect")),
],
}
if show_review:
groups["复盘信息"] = [
("结果状态", val("result_status")), ("平仓日期", val("closed_date")),
("已实现盈亏", val("closed_pnl")), ("年化收益", val("annualized_return")),
("是否被指派", assigned_display()), ("执行评分", val("execution_score")),
("结果归因", val("outcome_type")), ("复盘说明", val("review_note")),
]
#st.markdown("### 详细信息")
grid_class = "detail-card-grid-4" if columns == 4 else "detail-card-grid-3"
cards_html = []
for title, items in groups.items():
shown = [(k, v) for k, v in items if str(v).strip() or k == "关联合约"]
if not shown: continue
# rows_html = "".join(
# f'<div class="detail-card-row"><div class="detail-card-label">{html.escape(k)}</div>'
# f'<div class="detail-card-value">{html.escape(v)}</div></div>'
# for k, v in shown
# )
rows_html_parts = []
current_trade_id = int(detail_row.get("id"))
for k, v in shown:
value_style = ""
if k == "净现金流":
try:
num_value = float(str(v).replace(",", ""))
if num_value < 0:
value_style = "color:#16a34a;"
except Exception:
pass
if k == "已实现盈亏":
try:
num_value = float(str(v).replace(",", ""))
if num_value > 0:
value_style = "color:#dc2626;font-weight:700;"
elif num_value < 0:
value_style = "color:#16a34a;font-weight:700;"
except Exception:
pass
label_html = html.escape(k)
value_html = html.escape(str(v))
# 关联合约末尾的【现金流合计】如果为负数,只把数字显示为绿色加粗
if k == "关联合约":
raw_value = str(v)
if "【" in raw_value and "】" in raw_value:
prefix, rest = raw_value.rsplit("【", 1)
cash_text, suffix = rest.split("】", 1)
try:
cash_num = float(cash_text.replace(",", ""))
if cash_num < 0:
value_html = (
f'{html.escape(prefix)}【'
f'<span style="color:#16a34a;font-weight:700;">{html.escape(cash_text)}</span>'
f'】{html.escape(suffix)}'
)
except Exception:
value_html = html.escape(raw_value)
rows_html_parts.append(
f'<div class="detail-card-row">'
f'<div class="detail-card-label">{label_html}</div>'
f'<div class="detail-card-value" style="{value_style}">{value_html}</div>'
f'</div>'
)
rows_html = "".join(rows_html_parts)
cards_html.append(f'<div class="detail-card"><div class="detail-card-title">{html.escape(title)}</div>{rows_html}</div>')
st.markdown(f'<div class="{grid_class}">{"".join(cards_html)}</div>', unsafe_allow_html=True)
@st.dialog("编辑复盘说明")
def edit_review_dialog(trade_id: int, current_note: str):
st.write(f"**交易编号:{trade_id}**")
new_note = st.text_area(
"复盘说明",
value=current_note,
height=300,
placeholder="在这里输入详细的复盘内容、经验教训、改进点等..."
)
col1, col2 = st.columns(2)
if col1.button("✅ 确定保存", type="primary", use_container_width=True):
if new_note.strip() != current_note.strip():
update_trade(trade_id, {"review_note": new_note.strip() or None})
st.success("✅ 复盘说明已更新!")
st.session_state.show_review_dialog_trade_id = None
st.rerun()
if col2.button("❌ 取消", use_container_width=True):
st.session_state.show_review_dialog_trade_id = None
st.rerun()
@st.dialog("管理关联合约")
def related_contract_dialog(trade_id: int):
ensure_related_trade_column()
st.write(f"用于自定义多腿策略时关联相关合约")
current_df = get_trade_by_id(int(trade_id))
if current_df.empty:
st.warning("未找到当前交易。")
return
current = current_df.iloc[0]
ticker = str(current.get("ticker") or "")
position_id = str(current.get("position_id") or current.get("id"))
st.write(f"当前合约:**{position_id} / {ticker}**")
# 显示当前已关联的合约信息
current_related_text = format_related_trade_text(int(trade_id))
if not str(current_related_text).strip():
st.info("当前已关联:未关联")
else:
st.info(f"当前已关联:{current_related_text}")
candidates = get_related_candidates(int(trade_id))
if candidates.empty:
st.info("暂无可关联的同标的 OPEN 合约。")
if st.button("关闭", use_container_width=True):
st.session_state.show_related_contract_dialog_trade_id = None
try:
if "manage_related_trade_id" in st.query_params:
del st.query_params["manage_related_trade_id"]
except Exception:
pass
st.rerun()
return
current_related_id = None
if "related_trade_id" in current.index and not pd.isna(current.get("related_trade_id")):
try:
current_related_id = int(current.get("related_trade_id"))
except Exception:
current_related_id = None
# 兼容旧版单向关联:如果当前记录没有 related_trade_id,
# 但其他合约指向了当前记录,也把它识别为当前已关联对象。
if current_related_id is None:
related_row = get_related_trade_row(int(trade_id))
if related_row and related_row["id"] is not None:
try:
current_related_id = int(related_row["id"])
except Exception:
current_related_id = None
option_ids = candidates["id"].astype(int).tolist()
def candidate_label(row):
pid = row.get("position_id") or row.get("id")
strategy = str(row.get("option_strategy") or "")
status = row.get("result_status") or ""
qty = row.get("qty") or ""
strike_1 = row.get("strike_price") or ""
try:
strike_1 = f"{float(strike_1):.2f}" if strike_1 != "" else ""
except Exception:
strike_1 = str(strike_1)
return f"{pid} - {strategy} - {status} - {qty} - {strike_1}"
labels = {
int(row["id"]): candidate_label(row)
for _, row in candidates.iterrows()
}
default_index = 0
if current_related_id in option_ids:
default_index = option_ids.index(current_related_id)
selected_related_id = st.selectbox(
"选择要关联的原有合约",
options=option_ids,
index=default_index,
format_func=lambda x: labels.get(int(x), str(x)),
)
col1, col2, col3 = st.columns(3)
if col1.button("✅ 保存关联", type="primary", use_container_width=True):
set_related_trade(int(trade_id), int(selected_related_id))
st.session_state.show_related_contract_dialog_trade_id = None
try:
if "manage_related_trade_id" in st.query_params:
del st.query_params["manage_related_trade_id"]
except Exception:
pass
st.success("已保存关联合约。")
st.rerun()
if col2.button("🗑️ 删除关联", use_container_width=True):
set_related_trade(int(trade_id), None)
st.session_state.show_related_contract_dialog_trade_id = None
try:
if "manage_related_trade_id" in st.query_params:
del st.query_params["manage_related_trade_id"]
except Exception:
pass
st.success("已删除关联合约。")
st.rerun()
if col3.button("取消", use_container_width=True):
st.session_state.show_related_contract_dialog_trade_id = None
try:
if "manage_related_trade_id" in st.query_params:
del st.query_params["manage_related_trade_id"]
except Exception:
pass
st.rerun()
def render_related_contract_link_button(trade_id: int):
"""用 Streamlit 原生按钮打开关联合约弹窗。样式做成文字链接,避免 HTML 链接无法触发 Python 回调。"""
st.markdown(
"""
<style>
div[data-testid="stButton"] button[key^="manage_related_contract_btn_"] {
background: transparent !important;
border: none !important;
color: #2563eb !important;
text-decoration: underline !important;
padding: 0 !important;
min-height: 0 !important;
font-size: 14px !important;
font-weight: 400 !important;
}
</style>
""",
unsafe_allow_html=True,
)
if st.button("🔗 管理关联合约", key=f"manage_related_contract_btn_{int(trade_id)}"):
st.session_state.show_related_contract_dialog_trade_id = int(trade_id)
st.rerun()
def delete_trade_by_id(trade_id: int) -> None:
"""删除一条交易日志。只删除 trades 表中的交易记录。"""
with sqlite3.connect(DB_PATH) as conn:
conn.execute("DELETE FROM trades WHERE id = ?", (int(trade_id),))
conn.commit()
@st.dialog("确认删除日志")
def delete_trade_confirm_dialog(trade_id: int, position_id: str, ticker: str, strategy_text: str):
st.warning(f"确认删除 {position_id} 编号 {ticker} 标的 {strategy_text} 策略 的日志?")
st.caption("删除后无法在系统内直接恢复,请确认已备份数据库。")
col1, col2 = st.columns(2)
if col1.button("🗑️ 确认删除", type="primary", use_container_width=True, key=f"confirm_delete_{trade_id}"):
delete_trade_by_id(int(trade_id))
st.session_state.selected_trade_id = None
st.session_state.edit_trade_id = None
st.session_state.need_clear_selection = True
st.session_state["pending_nav"] = "交易日志显示"
try:
st.query_params.clear()
except Exception:
pass
st.toast(f"已删除日志:{position_id}", icon="🗑️")
st.rerun()
if col2.button("取消", use_container_width=True, key=f"cancel_delete_{trade_id}"):
st.rerun()
def sync_visible_row_checks(visible_ids: list[int]):
selected = st.session_state.get("selected_trade_id")
for rid in visible_ids:
st.session_state[f"trade_select_{rid}"] = selected == rid
def handle_trade_checkbox_change(trade_id: int, visible_ids: list[int]):
key = f"trade_select_{trade_id}"
checked = bool(st.session_state.get(key, False))
if checked:
st.session_state.selected_trade_id = trade_id
for rid in visible_ids:
st.session_state[f"trade_select_{rid}"] = (rid == trade_id)
else:
if st.session_state.get("selected_trade_id") == trade_id:
st.session_state.selected_trade_id = None
st.session_state[key] = False
def update_backfill_pnl(trade_id: int, action: str, premium: float, qty: int, multiplier: int):
close_key = f"bf_close_price_{trade_id}"
pnl_key = f"bf_closed_pnl_{trade_id}"
close_price = float(st.session_state.get(close_key, 0.0) or 0.0)
if close_price <= 0:
return
action = (action or "").upper()
if action == "BTO":
st.session_state[pnl_key] = round((close_price - premium) * qty * multiplier, 2)
elif action == "STO":
st.session_state[pnl_key] = round((premium - close_price) * qty * multiplier, 2)
def _get_db_path_from_db_module():
"""尽量复用 db.py 里的数据库路径,避免连错库。"""
try:
import db
for name in ["DB_PATH", "DATABASE_PATH", "db_path"]:
if hasattr(db, name):
p = getattr(db, name)
return str(p)
if hasattr(db, "engine"):
url = str(db.engine.url)
if url.startswith("sqlite:///"):
return url.replace("sqlite:///", "", 1)
except Exception:
pass
return r"D:\apps\TradingLog\data\tradinglog.db"
def _sqlite_connect():
conn = sqlite3.connect(_get_db_path_from_db_module())
conn.row_factory = sqlite3.Row
return conn
def ensure_trade_indexes():
"""为交易日志列表常用筛选字段和关联合约字段创建索引。"""
ensure_related_trade_column()
with _sqlite_connect() as conn:
conn.execute("CREATE INDEX IF NOT EXISTS idx_trades_result_status ON trades(result_status)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_trades_ticker ON trades(ticker)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_trades_trade_date ON trades(trade_date)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_trades_option_strategy ON trades(option_strategy)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_trades_sub_type ON trades(sub_type)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_trades_related_trade_id ON trades(related_trade_id)")
conn.commit()
def ensure_related_trade_column():
"""为关联合约准备字段;已存在则忽略。"""
with _sqlite_connect() as conn:
cols = {r["name"] for r in conn.execute("PRAGMA table_info(trades)").fetchall()}
if "related_trade_id" not in cols:
conn.execute("ALTER TABLE trades ADD COLUMN related_trade_id INTEGER")
conn.commit()
def set_related_trade(trade_id: int, related_trade_id):
"""
设置或清除关联合约。
规则:
- A 关联 B 后,同时写入 A -> B 和 B -> A。
- A 重新绑定 C 时,自动解除 A 原来的对手方,以及 C 原来的对手方。
- A 删除关联时,如果 B 正好关联 A,也同步清空 B。
"""
ensure_related_trade_column()
trade_id = int(trade_id)
related_trade_id = int(related_trade_id) if related_trade_id is not None else None
if related_trade_id == trade_id:
return
with _sqlite_connect() as conn:
current = conn.execute(
"SELECT related_trade_id FROM trades WHERE id = ?",
(trade_id,),
).fetchone()
old_related_id = None
if current and current["related_trade_id"] is not None:
old_related_id = int(current["related_trade_id"])
# 先解除当前合约原来的对手方。
if old_related_id is not None:
conn.execute(
"UPDATE trades SET related_trade_id = NULL WHERE id = ? AND related_trade_id = ?",
(old_related_id, trade_id),
)
# 如果只是删除关联,清空当前合约即可。
if related_trade_id is None:
conn.execute(
"UPDATE trades SET related_trade_id = NULL WHERE id = ?",
(trade_id,),
)
conn.commit()
return
# 如果目标合约原本关联了别人,也先解除那一边。
target = conn.execute(
"SELECT related_trade_id FROM trades WHERE id = ?",
(related_trade_id,),
).fetchone()
target_old_related_id = None
if target and target["related_trade_id"] is not None:
target_old_related_id = int(target["related_trade_id"])
if target_old_related_id is not None and target_old_related_id != trade_id:
conn.execute(
"UPDATE trades SET related_trade_id = NULL WHERE id = ? AND related_trade_id = ?",
(target_old_related_id, related_trade_id),
)
# 写入双向绑定。
conn.execute(
"UPDATE trades SET related_trade_id = ? WHERE id = ?",
(related_trade_id, trade_id),
)
conn.execute(
"UPDATE trades SET related_trade_id = ? WHERE id = ?",
(trade_id, related_trade_id),
)
conn.commit()
def get_related_trade_row(trade_id: int):
"""读取当前交易关联的合约记录;兼容旧版单向关联数据。"""
ensure_related_trade_column()
with _sqlite_connect() as conn:
row = conn.execute(
"""
SELECT r.*
FROM trades t
LEFT JOIN trades r ON r.id = t.related_trade_id
WHERE t.id = ?
""",
(int(trade_id),),
).fetchone()
if row and row["id"] is not None:
return row
# 兼容旧数据:如果别人指向当前合约,也认为存在关联。
return conn.execute(
"""
SELECT *
FROM trades
WHERE related_trade_id = ?
ORDER BY id DESC
LIMIT 1
""",
(int(trade_id),),
).fetchone()
def has_related_trade(trade_id: int) -> bool:
"""判断交易是否有关联合约;兼容旧版单向关联数据。"""
row = get_related_trade_row(int(trade_id))
return bool(row and row["id"] is not None)
def get_related_trade_icon(trade_id: int) -> str:
"""关联合约统一使用同一个图标。"""
row = get_related_trade_row(int(trade_id))
if not row or row["id"] is None:
return ""
return "🔗"
def get_related_trade_color(trade_id: int) -> str:
"""
为不同关联对返回不同颜色。
同一对合约用同一个颜色;兼容旧版单向关联数据。
"""
row = get_related_trade_row(int(trade_id))
if not row or row["id"] is None:
return ""
current_id = int(trade_id)
related_id = int(row["id"])
pair_a, pair_b = sorted([current_id, related_id])
colors = [
"#2563eb", # blue
"#16a34a", # green
"#dc2626", # red
"#9333ea", # purple
"#ea580c", # orange
"#0891b2", # cyan
"#be123c", # rose
"#4f46e5", # indigo
"#65a30d", # lime
"#b45309", # amber
]
color_index = (pair_a * 31 + pair_b * 17) % len(colors)
return colors[color_index]
def get_related_pair_color(trade_id: int, related_id) -> str:
"""根据当前记录ID和关联记录ID返回稳定颜色;避免列表逐行查询数据库。"""
try:
current_id = int(trade_id)
related_id = int(related_id)
except Exception:
return ""
pair_a, pair_b = sorted([current_id, related_id])
colors = [
"#2563eb", # blue
"#16a34a", # green
"#dc2626", # red
"#9333ea", # purple
"#ea580c", # orange
"#0891b2", # cyan
"#be123c", # rose
"#4f46e5", # indigo
"#65a30d", # lime
"#b45309", # amber
]
color_index = (pair_a * 31 + pair_b * 17) % len(colors)
return colors[color_index]
def get_related_trade_icon_html(trade_id: int, related_id=None) -> str:
"""返回可变色的关联合约图标 HTML。related_id 存在时不再查询数据库。"""
color = get_related_pair_color(int(trade_id), related_id) if related_id is not None else get_related_trade_color(int(trade_id))
if not color:
return ""
safe_color = html.escape(color)
return (
f'<span style="display:inline-flex;vertical-align:-2px;color:{safe_color};margin-left:4px;">'
f'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" '
f'xmlns="http://www.w3.org/2000/svg" aria-label="关联合约">'
f'<path d="M10.6 13.4a1.8 1.8 0 0 0 2.8 0l3.7-3.7a3.2 3.2 0 0 0-4.5-4.5l-1.1 1.1" '
f'stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>'
f'<path d="M13.4 10.6a1.8 1.8 0 0 0-2.8 0l-3.7 3.7a3.2 3.2 0 0 0 4.5 4.5l1.1-1.1" '
f'stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>'
f'</svg>'
f'</span>'
)
def add_related_info_to_df(df: pd.DataFrame) -> pd.DataFrame:
"""一次性用 SQL 给交易列表补充 has_related / related_id,避免每行查询数据库。"""
if df.empty or "id" not in df.columns:
return df
ensure_related_trade_column()