-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathbacktest_result_window.py
More file actions
3183 lines (2652 loc) · 155 KB
/
backtest_result_window.py
File metadata and controls
3183 lines (2652 loc) · 155 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 logging
logging.getLogger('matplotlib').setLevel(logging.ERROR)
# 先导入 matplotlib 并设置后端
import matplotlib
matplotlib.use('Qt5Agg')
# 其他导入
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QTabWidget, QTableWidget, QTableWidgetItem,
QGroupBox, QSplitter, QGridLayout, QHeaderView, QSizePolicy)
from PyQt5.QtCore import Qt, QSettings
from PyQt5.QtGui import QPalette, QColor, QIcon
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.dates as mdates
from matplotlib import ticker
import pandas as pd
import os
from datetime import datetime, timedelta
import numpy as np
import sys
import time
from khQTTools import KhQuTools
from xtquant import xtdata
# 设置matplotlib的字体和其他参数
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.family'] = 'sans-serif'
# 设置matplotlib深色主题
plt.style.use('dark_background')
class BacktestResultWindow(QMainWindow):
def __init__(self, backtest_dir):
super().__init__()
self.backtest_dir = backtest_dir
# 检测屏幕分辨率并设置字体缩放比例
self.font_scale = self.detect_screen_resolution()
# 从设置读取无风险收益率
settings = QSettings('KHQuant', 'StockAnalyzer')
self.risk_free_rate = float(settings.value('risk_free_rate', '0.03'))
print(f"使用无风险收益率: {self.risk_free_rate}")
# 设置窗口标题栏颜色(仅适用于Windows)
if sys.platform == 'win32':
try:
from ctypes import windll, c_int, byref, sizeof
# 定义Windows API常量
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
DWMWA_CAPTION_COLOR = 35
# 启用深色模式
windll.dwmapi.DwmSetWindowAttribute(
int(self.winId()),
DWMWA_USE_IMMERSIVE_DARK_MODE,
byref(c_int(2)), # 2表示启用
sizeof(c_int)
)
# 设置标题栏颜色
caption_color = c_int(0x2b2b2b) # 使用与主界面相同的颜色
windll.dwmapi.DwmSetWindowAttribute(
int(self.winId()),
DWMWA_CAPTION_COLOR,
byref(caption_color),
sizeof(caption_color)
)
except Exception as e:
print(f"设置标题栏深色模式失败: {str(e)}")
# 设置窗口标题
self.setWindowTitle("回测结果分析")
# 加载窗口图标
self.load_icon()
# 初始化UI和加载数据
self.init_ui()
self.load_data()
self.apply_dark_theme()
def load_icon(self):
"""加载窗口图标"""
try:
# 首先尝试直接加载相对路径
icon_path = "./icons/stock_icon.png"
if os.path.exists(icon_path):
self.setWindowIcon(QIcon(icon_path))
print(f"成功加载图标: {icon_path}")
return True
except Exception as e:
print(f"加载图标时出错: {str(e)}")
return False
def detect_screen_resolution(self):
"""检测屏幕分辨率并返回字体缩放比例"""
from PyQt5.QtWidgets import QApplication
screen = QApplication.desktop().screenGeometry()
width = screen.width()
height = screen.height()
# 根据屏幕宽度确定字体缩放比例
if width >= 3840: # 4K及以上分辨率
return 1.8
elif width >= 2560: # 2K分辨率
return 1.4
elif width >= 1920: # 1080P分辨率
return 1.0
else: # 低分辨率
return 0.8
def get_scaled_stylesheet(self):
"""获取根据分辨率缩放的样式表"""
# 基础字体大小
base_sizes = {
'small': 12,
'normal': 14,
'large': 16,
'xl': 18,
'xxl': 24,
'xxxl': 30
}
# 计算缩放后的字体大小
scaled_sizes = {k: int(v * self.font_scale) for k, v in base_sizes.items()}
return f"""
QMainWindow, QWidget {{
background-color: #2b2b2b;
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
}}
QLabel {{
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
background-color: transparent;
}}
QTabWidget::pane {{
border: 1px solid #3c3c3c;
background-color: #2b2b2b;
}}
QTabBar::tab {{
background-color: #3c3c3c;
color: #e8e8e8;
padding: 8px 16px;
margin-right: 2px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
font-size: {scaled_sizes['normal']}px;
}}
QTabBar::tab:selected {{
background-color: #2b2b2b;
border-bottom: 2px solid #0078d7;
}}
QTabBar::tab:hover {{
background-color: #4a4a4a;
}}
QTableWidget {{
background-color: #333333;
alternate-background-color: #383838;
border: 1px solid #3c3c3c;
color: #e8e8e8;
gridline-color: #3c3c3c;
font-size: {scaled_sizes['normal']}px;
}}
QTableWidget::item {{
padding: 5px;
background-color: transparent;
border: none;
}}
QTableWidget::item:selected {{
background-color: #0078d7;
color: #ffffff;
}}
QHeaderView::section {{
background-color: #3a3a3a;
color: #e8e8e8;
padding: 8px;
border: none;
border-right: 1px solid #454545;
border-bottom: 1px solid #454545;
font-weight: bold;
font-size: {scaled_sizes['normal']}px;
}}
QGroupBox {{
background-color: #333333;
border: 1px solid #4a4a4a;
border-radius: 6px;
margin-top: 1em;
padding-top: 1em;
color: #e8e8e8;
font-size: {scaled_sizes['normal']}px;
}}
QGroupBox::title {{
subcontrol-origin: margin;
left: 10px;
padding: 0 5px;
color: #e8e8e8;
font-weight: bold;
background-color: #333333;
font-size: {scaled_sizes['normal']}px;
}}
"""
def apply_dark_theme(self):
"""应用深色主题样式"""
# 使用缩放后的样式表
self.setStyleSheet(self.get_scaled_stylesheet())
def init_ui(self):
# 根据分辨率自适应窗口大小
base_width, base_height = 1600, 1000
scaled_width = int(base_width * self.font_scale)
scaled_height = int(base_height * self.font_scale)
self.resize(scaled_width, scaled_height)
# 创建主窗口部件
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout()
main_layout.setSpacing(10)
main_layout.setContentsMargins(10, 10, 10, 10)
main_widget.setLayout(main_layout)
# 创建上下分割器
splitter = QSplitter(Qt.Vertical)
splitter.setHandleWidth(2) # 设置分割条宽度
# 上部分:基本信息和收益曲线
top_widget = QWidget()
top_layout = QHBoxLayout()
top_layout.setSpacing(20) # 增加组件之间的间距
top_layout.setContentsMargins(5, 5, 5, 5) # 设置外边距
# 基本信息面板
info_group = QGroupBox("基本信息")
info_group.setStyleSheet(f"""
QGroupBox {{
font-size: {int(16 * self.font_scale)}px;
font-weight: bold;
background-color: #2d2d2d;
border: 2px solid #404040;
border-radius: 8px;
padding: {int(5 * self.font_scale)}px;
}}
QGroupBox::title {{
font-size: {int(16 * self.font_scale)}px;
padding: 0 {int(6 * self.font_scale)}px;
background-color: #2d2d2d;
}}
""")
info_layout = QGridLayout()
info_layout.setVerticalSpacing(int(2 * self.font_scale)) # 减小行间距,更紧凑
info_layout.setHorizontalSpacing(int(8 * self.font_scale)) # 保持合适的列间距
info_layout.setContentsMargins(int(8 * self.font_scale), int(6 * self.font_scale),
int(8 * self.font_scale), int(6 * self.font_scale))
self.info_labels = {}
info_items = ["策略名称", "回测区间", "初始资金", "最终资金",
"总收益率", "年化收益率", "基准收益率", "基准年化收益率", "最大回撤", "夏普比率",
"索提诺比率", "阿尔法", "贝塔",
"胜率", "盈亏比", "日均交易次数", "最大连续盈利",
"最大连续亏损", "最大单笔盈利", "最大单笔亏损", "年化波动率"]
# 创建两列布局显示指标
col1_items = info_items[:len(info_items)//2]
col2_items = info_items[len(info_items)//2:]
# 调整标签和值的宽度以确保足够的显示空间
for i, item in enumerate(col1_items):
label = QLabel(f"{item}:")
label.setStyleSheet(f"""
font-weight: bold;
font-size: {int(14 * self.font_scale)}px;
color: #a0a0a0;
background-color: transparent;
""")
label.setMinimumWidth(int(100 * self.font_scale)) # 标签固定最小宽度
label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) # 标签宽度固定,高度自适应
value = QLabel("--")
value.setStyleSheet(f"""
color: #e8e8e8;
font-size: {int(14 * self.font_scale)}px;
font-family: 'Consolas', 'Microsoft YaHei', monospace;
background-color: transparent;
""")
value.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) # 数值宽度自适应内容
value.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
value.setWordWrap(False) # 禁用自动换行
info_layout.addWidget(label, i, 0, Qt.AlignRight)
info_layout.addWidget(value, i, 1, Qt.AlignLeft)
self.info_labels[item] = value
# 确保两列之间有足够的间距
info_layout.setColumnMinimumWidth(2, int(20 * self.font_scale)) # 增加列间距
for i, item in enumerate(col2_items):
label = QLabel(f"{item}:")
label.setStyleSheet(f"""
font-weight: bold;
font-size: {int(14 * self.font_scale)}px;
color: #a0a0a0;
background-color: transparent;
""")
label.setMinimumWidth(int(100 * self.font_scale)) # 标签固定最小宽度
label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) # 标签宽度固定,高度自适应
value = QLabel("--")
value.setStyleSheet(f"""
color: #e8e8e8;
font-size: {int(14 * self.font_scale)}px;
font-family: 'Consolas', 'Microsoft YaHei', monospace;
background-color: transparent;
""")
value.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) # 数值宽度自适应内容
value.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
value.setWordWrap(False) # 禁用自动换行
info_layout.addWidget(label, i, 3, Qt.AlignRight)
info_layout.addWidget(value, i, 4, Qt.AlignLeft)
self.info_labels[item] = value
info_group.setLayout(info_layout)
# 设置基本信息面板的大小策略,限制其宽度
info_group.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
info_group.setMaximumWidth(int(400 * self.font_scale)) # 限制最大宽度
top_layout.addWidget(info_group, 0) # 伸展因子为0,不拉伸
# 收益曲线图表
chart_group = QGroupBox("收益曲线")
chart_group.setStyleSheet(f"""
QGroupBox {{
font-size: {int(16 * self.font_scale)}px;
font-weight: bold;
background-color: #2d2d2d;
border: 2px solid #404040;
border-radius: 8px;
padding: {int(15 * self.font_scale)}px;
}}
QGroupBox::title {{
font-size: {int(16 * self.font_scale)}px;
padding: 0 {int(8 * self.font_scale)}px;
background-color: #2d2d2d;
}}
""")
chart_layout = QVBoxLayout()
chart_layout.setContentsMargins(int(8 * self.font_scale), int(10 * self.font_scale),
int(8 * self.font_scale), int(8 * self.font_scale)) # 减少图表内边距,让图表更饱满
# 创建图表并保存canvas引用
canvas = self.create_chart()
self.chart_view = canvas
# 添加鼠标移动事件处理
canvas.mpl_connect('motion_notify_event', self.hover)
# 添加窗口大小变化事件处理,确保在窗口调整时重新布局
canvas.mpl_connect('resize_event', self.on_chart_resize)
chart_layout.addWidget(self.chart_view)
chart_group.setLayout(chart_layout)
# 设置图表组件的大小策略,让其占据更多空间
chart_group.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
chart_group.setMinimumSize(int(600 * self.font_scale), int(400 * self.font_scale))
top_layout.addWidget(chart_group, 1) # 伸展因子为1,占据剩余空间
top_widget.setLayout(top_layout)
splitter.addWidget(top_widget)
# 下部分:Tab页面
tab_widget = QTabWidget()
tab_widget.setStyleSheet(f"""
QTabWidget::pane {{
border: 2px solid #404040;
border-radius: 8px;
background: #2d2d2d;
margin-top: -2px;
}}
QTabBar::tab {{
min-width: {int(100 * self.font_scale)}px;
padding: {int(8 * self.font_scale)}px {int(12 * self.font_scale)}px;
margin: 0px 2px;
color: #a0a0a0;
font-size: {int(14 * self.font_scale)}px;
font-weight: bold;
background: #2d2d2d;
border: 2px solid #404040;
border-bottom: none;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}}
QTabBar::tab:selected {{
color: #ffffff;
background: #333333;
border-bottom: 2px solid #007acc;
}}
QTabBar::tab:hover {{
background: #353535;
color: #e8e8e8;
}}
""")
# 交易记录标签页
self.trades_table = QTableWidget()
self.trades_table.setStyleSheet(f"""
QTableWidget {{
background-color: #2d2d2d;
gridline-color: #404040;
color: #e8e8e8;
font-size: {int(14 * self.font_scale)}px;
}}
QTableWidget::item {{
padding: {int(6 * self.font_scale)}px;
border-bottom: 1px solid #404040;
}}
QHeaderView::section {{
background-color: #333333;
color: #e8e8e8;
font-size: {int(14 * self.font_scale)}px;
font-weight: bold;
padding: {int(10 * self.font_scale)}px {int(6 * self.font_scale)}px;
border: none;
border-right: 1px solid #404040;
border-bottom: 2px solid #404040;
}}
QHeaderView::section:hover {{
background-color: #383838;
}}
""")
self.trades_table.setColumnCount(7)
self.trades_table.setHorizontalHeaderLabels(
["交易时间", "证券代码", "交易方向", "成交价格", "成交数量", "成交金额", "手续费"]
)
self.trades_table.setAlternatingRowColors(True)
self.trades_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
self.trades_table.verticalHeader().setVisible(False)
tab_widget.addTab(self.trades_table, "交易记录")
# 每日收益标签页
self.daily_stats_table = QTableWidget()
self.daily_stats_table.setStyleSheet(f"""
QTableWidget {{
background-color: #2d2d2d;
gridline-color: #404040;
color: #e8e8e8;
font-size: {int(14 * self.font_scale)}px;
}}
QTableWidget::item {{
padding: {int(6 * self.font_scale)}px;
border-bottom: 1px solid #404040;
}}
QHeaderView::section {{
background-color: #333333;
color: #e8e8e8;
font-size: {int(14 * self.font_scale)}px;
font-weight: bold;
padding: {int(10 * self.font_scale)}px {int(6 * self.font_scale)}px;
border: none;
border-right: 1px solid #404040;
border-bottom: 2px solid #404040;
}}
QHeaderView::section:hover {{
background-color: #383838;
}}
""")
self.daily_stats_table.setColumnCount(5)
self.daily_stats_table.setHorizontalHeaderLabels(
["日期", "总资产", "持仓市值", "可用资金", "日收益率"]
)
self.daily_stats_table.setAlternatingRowColors(True)
self.daily_stats_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
self.daily_stats_table.verticalHeader().setVisible(False)
tab_widget.addTab(self.daily_stats_table, "日收益")
# 绩效评估标签页
performance_widget = QWidget()
performance_layout = QVBoxLayout()
performance_layout.setContentsMargins(10, 10, 10, 10)
performance_layout.setSpacing(15)
# 创建多图表布局
charts_splitter = QSplitter(Qt.Horizontal)
charts_splitter.setHandleWidth(2)
# 收益分布图
returns_dist_group = QGroupBox("收益分布")
returns_dist_group.setStyleSheet(f"""
QGroupBox {{
font-size: {int(16 * self.font_scale)}px;
font-weight: bold;
background-color: #2d2d2d;
border: 2px solid #404040;
border-radius: 8px;
padding: {int(12 * self.font_scale)}px;
}}
QGroupBox::title {{
font-size: {int(16 * self.font_scale)}px;
padding: 0 {int(8 * self.font_scale)}px;
background-color: #2d2d2d;
}}
""")
returns_dist_layout = QVBoxLayout()
self.returns_dist_figure = Figure(figsize=(5, 4), facecolor='#2d2d2d')
self.returns_dist_canvas = FigureCanvas(self.returns_dist_figure)
returns_dist_layout.addWidget(self.returns_dist_canvas)
returns_dist_group.setLayout(returns_dist_layout)
# 添加月度收益热力图
monthly_returns_group = QGroupBox("月度收益热力图")
monthly_returns_group.setStyleSheet(f"""
QGroupBox {{
font-size: {int(16 * self.font_scale)}px;
font-weight: bold;
background-color: #2d2d2d;
border: 2px solid #404040;
border-radius: 8px;
padding: {int(12 * self.font_scale)}px;
}}
QGroupBox::title {{
font-size: {int(16 * self.font_scale)}px;
padding: 0 {int(8 * self.font_scale)}px;
background-color: #2d2d2d;
}}
""")
monthly_returns_layout = QVBoxLayout()
self.monthly_returns_figure = Figure(figsize=(5, 4), facecolor='#2d2d2d')
self.monthly_returns_canvas = FigureCanvas(self.monthly_returns_figure)
monthly_returns_layout.addWidget(self.monthly_returns_canvas)
monthly_returns_group.setLayout(monthly_returns_layout)
# 添加图表到splitter
charts_splitter.addWidget(returns_dist_group)
charts_splitter.addWidget(monthly_returns_group)
# 设置初始大小
charts_splitter.setSizes([500, 500])
# 将图表添加到总布局
performance_layout.addWidget(charts_splitter)
performance_widget.setLayout(performance_layout)
tab_widget.addTab(performance_widget, "绩效分析")
splitter.addWidget(tab_widget)
# 设置分割器的初始大小比例
splitter.setSizes([750, 250]) # 增加上部分比例,减少底部Tab区域占比
# 设置最小高度
top_widget.setMinimumHeight(550) # 增加图表区域高度
tab_widget.setMinimumHeight(300) # 适当减小tab页最小高度
main_layout.addWidget(splitter)
def create_chart(self):
"""创建matplotlib图表,包含收益曲线、回撤曲线、盈亏分析图和成交记录图"""
# 创建带有四个子图的Figure,共享x轴,设置最小尺寸确保显示完整
fig = Figure(figsize=(12, 10), facecolor='#2d2d2d') # 调整比例,确保布局合理
canvas = FigureCanvas(fig)
# 创建四个子图,高度比例为4:1:1:1
gs = fig.add_gridspec(7, 1) # 7行1列的网格
self.ax = fig.add_subplot(gs[0:4, 0]) # 前4行用于收益曲线
self.ax_drawdown = fig.add_subplot(gs[4, 0], sharex=self.ax) # 第5行用于回撤曲线
self.ax_pnl = fig.add_subplot(gs[5, 0], sharex=self.ax) # 第6行用于盈亏分析图
self.ax_trades = fig.add_subplot(gs[6, 0], sharex=self.ax) # 第7行用于成交记录图
# 根据字体缩放计算图表字体大小,适中调整
title_fontsize = int(16 * self.font_scale) # 适中的标题字体
label_fontsize = int(13 * self.font_scale) # 适中的标签字体
tick_fontsize = int(11 * self.font_scale) # 适中的刻度字体
# 设置上方子图(收益曲线)
self.ax.set_title("策略收益与基准对比", color='#e8e8e8', pad=int(20 * self.font_scale),
fontsize=title_fontsize, fontweight='bold')
self.ax.set_facecolor('#2d2d2d')
self.ax.set_ylabel("净值", color='#a0a0a0', fontsize=label_fontsize)
# 隐藏上方子图的x轴标签,设置y轴刻度字体大小
self.ax.tick_params(axis='x', labelbottom=False)
self.ax.tick_params(axis='y', labelsize=tick_fontsize, colors='#a0a0a0')
# 设置回撤曲线子图
self.ax_drawdown.set_facecolor('#2d2d2d')
self.ax_drawdown.set_ylabel("回撤率 (%)", color='#a0a0a0', fontsize=label_fontsize)
# 隐藏回撤子图的x轴标签,设置y轴刻度字体大小
self.ax_drawdown.tick_params(axis='x', labelbottom=False)
self.ax_drawdown.tick_params(axis='y', labelsize=tick_fontsize, colors='#a0a0a0')
# 设置盈亏分析图子图
self.ax_pnl.set_facecolor('#2d2d2d')
self.ax_pnl.set_ylabel("日盈亏", color='#a0a0a0', fontsize=label_fontsize)
# 隐藏盈亏分析图子图的x轴标签,设置y轴刻度字体大小
self.ax_pnl.tick_params(axis='x', labelbottom=False)
self.ax_pnl.tick_params(axis='y', labelsize=tick_fontsize, colors='#a0a0a0')
# 设置成交记录图子图
self.ax_trades.set_facecolor('#2d2d2d')
self.ax_trades.set_ylabel("买入/卖出量", color='#a0a0a0', fontsize=label_fontsize)
#self.ax_trades.set_xlabel("时间", color='#a0a0a0', fontsize=label_fontsize)
# 设置成交记录图的刻度字体大小
self.ax_trades.tick_params(axis='both', labelsize=tick_fontsize, colors='#a0a0a0')
# 设置所有子图的基本样式
for a in [self.ax, self.ax_drawdown, self.ax_pnl, self.ax_trades]:
a.tick_params(axis='both', colors='#a0a0a0', labelsize=tick_fontsize)
a.grid(True, linestyle='--', alpha=0.1, color='#808080')
for spine in a.spines.values():
spine.set_color('#404040')
# 特别设置:反转回撤图的y轴(使回撤为负值显示在下方)
self.ax_drawdown.invert_yaxis()
# 调整图表边距,为字体留出适当空间避免遮挡
fig.subplots_adjust(left=0.10, right=0.96, top=0.92, bottom=0.12, hspace=0.18) # 适当增加边距以容纳较大字体
# 初始化图表元素为None,避免悬停事件中的错误
self.v_line_ax = None
self.v_line_drawdown = None
self.v_line_pnl = None
self.v_line_trades = None
self.strategy_point = None
self.benchmark_point = None
self.drawdown_point = None
self.pnl_point = None
self.hover_annotation = None
return canvas
def on_chart_resize(self, event):
"""处理图表画布大小变化事件,重新调整布局"""
try:
if hasattr(self, 'chart_view') and self.chart_view:
# 重新调整布局以确保标题、坐标轴和标注完整显示
self.chart_view.figure.subplots_adjust(left=0.10, right=0.96, top=0.92, bottom=0.12, hspace=0.18)
# 重绘图表
self.chart_view.draw_idle()
except Exception as e:
print(f"调整图表布局时出错: {str(e)}")
def load_data(self):
"""加载回测数据"""
try:
# 使用os.path来规范化路径
backtest_dir = os.path.abspath(self.backtest_dir)
# 检查目录是否存在
if not os.path.exists(backtest_dir):
raise FileNotFoundError(f"回测结果目录不存在: {backtest_dir}")
# 构建配置文件路径
config_path = os.path.join(backtest_dir, "config.csv")
time.sleep(1)
# 打印调试信息
print(f"尝试加载配置文件: {config_path}")
print(f"文件是否存在: {os.path.exists(config_path)}")
# 尝试列出目录内容
print("目录内容:")
for file in os.listdir(backtest_dir):
print(f"- {file}")
if not os.path.exists(config_path):
raise FileNotFoundError(f"配置文件不存在: {config_path}")
# 使用 utf-8-sig 编码读取文件,处理可能的 BOM
config_df = pd.read_csv(config_path, encoding='utf-8-sig')
# 读取交易记录和每日统计数据
trades_path = os.path.join(backtest_dir, "trades.csv")
daily_stats_path = os.path.join(backtest_dir, "daily_stats.csv")
benchmark_path = os.path.join(backtest_dir, "benchmark.csv")
# 检查文件是否存在
if not os.path.exists(trades_path):
print(f"警告: 交易记录文件不存在: {trades_path}")
trades_df = pd.DataFrame(columns=['datetime', 'code', 'action', 'price', 'volume', 'amount', 'commission'])
else:
trades_df = pd.read_csv(trades_path, encoding='utf-8-sig')
if not os.path.exists(daily_stats_path):
print(f"警告: 每日统计文件不存在: {daily_stats_path}")
daily_stats_df = pd.DataFrame(columns=['date', 'total_asset', 'cash', 'market_value', 'daily_return'])
else:
daily_stats_df = pd.read_csv(daily_stats_path, encoding='utf-8-sig')
# 检查并计算daily_return列
if 'daily_return' not in daily_stats_df.columns and 'total_asset' in daily_stats_df.columns:
print("daily_stats.csv中没有daily_return列,正在计算...")
# 确保日期列是日期类型,并按日期排序
daily_stats_df['date'] = pd.to_datetime(daily_stats_df['date'])
daily_stats_df = daily_stats_df.sort_values('date')
# 计算每日收益率
daily_stats_df['daily_return'] = daily_stats_df['total_asset'].pct_change()
print(f"已计算daily_return列,共{len(daily_stats_df)}条数据")
# 替换第一行的NaN值为0
daily_stats_df['daily_return'].iloc[0] = 0
# 处理基准数据文件
if not os.path.exists(benchmark_path):
print(f"警告: 基准数据文件不存在: {benchmark_path}")
# 创建一个假的基准数据DataFrame,与daily_stats_df具有相同的日期范围
if len(daily_stats_df) > 0 and 'date' in daily_stats_df.columns:
# 将日期列转换为datetime
daily_stats_df['date'] = pd.to_datetime(daily_stats_df['date'])
# 创建与策略数据相同日期范围的基准数据
dates = daily_stats_df['date']
# 创建一个初始值为1,后续值相同的序列
closes = np.ones(len(dates))
benchmark_df = pd.DataFrame({
'date': dates,
'close': closes
})
print("创建了替代基准数据")
else:
# 如果没有每日统计数据,则创建一个空的基准数据DataFrame
benchmark_df = pd.DataFrame(columns=['date', 'close'])
print("创建了空的基准数据DataFrame")
else:
try:
benchmark_df = pd.read_csv(benchmark_path, encoding='utf-8-sig')
# 检查基准数据是否为空
if len(benchmark_df) == 0 or 'close' not in benchmark_df.columns or 'date' not in benchmark_df.columns:
print("基准数据文件为空或缺少必要列")
# 创建同样的替代数据
if len(daily_stats_df) > 0 and 'date' in daily_stats_df.columns:
daily_stats_df['date'] = pd.to_datetime(daily_stats_df['date'])
dates = daily_stats_df['date']
closes = np.ones(len(dates))
benchmark_df = pd.DataFrame({
'date': dates,
'close': closes
})
print("创建了替代基准数据")
else:
benchmark_df = pd.DataFrame(columns=['date', 'close'])
print("创建了空的基准数据DataFrame")
except Exception as e:
print(f"读取基准数据文件时出错: {str(e)}")
# 创建同样的替代数据
if len(daily_stats_df) > 0 and 'date' in daily_stats_df.columns:
daily_stats_df['date'] = pd.to_datetime(daily_stats_df['date'])
dates = daily_stats_df['date']
closes = np.ones(len(dates))
benchmark_df = pd.DataFrame({
'date': dates,
'close': closes
})
print("创建了替代基准数据")
else:
benchmark_df = pd.DataFrame(columns=['date', 'close'])
print("创建了空的基准数据DataFrame")
# 检查必要的列是否存在
required_columns = {
'daily_stats': ['date', 'total_asset', 'cash', 'market_value', 'daily_return'],
'benchmark': ['date', 'close'],
'trades': ['datetime', 'code', 'action', 'price', 'volume', 'amount', 'commission']
}
# 检查并重命名列
if 'time' in trades_df.columns:
trades_df = trades_df.rename(columns={'time': 'datetime'})
if 'type' in trades_df.columns:
trades_df = trades_df.rename(columns={'type': 'action'})
# 输出调试信息
print(f"交易数据列名: {trades_df.columns.tolist()}")
for df_name, columns in required_columns.items():
df = locals()[f"{df_name}_df"]
missing_columns = [col for col in columns if col not in df.columns]
if missing_columns:
print(f"警告: {df_name} 缺少必要的列: {missing_columns},尝试调整")
# 对于trades,尝试修复最常见的列名问题
if df_name == 'trades':
if 'datetime' not in df.columns and 'time' in df.columns:
print(f" 将'time'列重命名为'datetime'")
df = df.rename(columns={'time': 'datetime'})
if 'action' not in df.columns and 'direction' in df.columns:
print(f" 将'direction'列重命名为'action'")
df = df.rename(columns={'direction': 'action'})
if 'action' not in df.columns and 'type' in df.columns:
print(f" 将'type'列重命名为'action'")
df = df.rename(columns={'type': 'action'})
missing_columns = [col for col in columns if col not in df.columns]
if missing_columns:
print(f" 调整后仍缺少列: {missing_columns}")
if set(missing_columns) == {'commission'} and 'amount' in df.columns:
# 如果只缺少commission列,则添加一个全为0的列
print(f" 添加默认的'commission'列")
df['commission'] = 0.0
missing_columns = []
trades_df = df
if missing_columns:
raise ValueError(f"{df_name} 缺少必要的列: {missing_columns}")
# 重命名 trades_df 的列以匹配期望的列名
trades_df = trades_df.rename(columns={
'datetime': 'time',
'action': 'direction'
})
# 输出调试信息
print(f"重命名后的交易数据列名: {trades_df.columns.tolist()}")
try:
# 将买卖动作映射为中文
direction_map = {
'buy': '买入',
'sell': '卖出'
}
trades_df['direction'] = trades_df['direction'].map(lambda x: direction_map.get(str(x).lower(), x))
print("买卖动作映射完成")
except Exception as e:
print(f"买卖动作映射出错: {str(e)}")
print(f"direction列值: {trades_df['direction'].unique().tolist() if 'direction' in trades_df.columns else 'direction列不存在'}")
# 更新基本信息
self.update_basic_info(config_df.iloc[0], daily_stats_df)
# 更新图表
self.update_chart(daily_stats_df, benchmark_df)
# 更新交易记录表格
self.update_trades_table(trades_df)
# 更新每日统计表格
self.update_daily_stats_table(daily_stats_df)
# 更新绩效评估图表
self.update_performance_charts(daily_stats_df, benchmark_df)
except Exception as e:
print(f"加载回测数据时出错: {str(e)}")
print(f"当前工作目录: {os.getcwd()}")
import traceback
print(traceback.format_exc())
def set_value_color(self, label, value_str, numeric_value):
"""根据数值正负设置颜色:正数红色,负数绿色"""
if numeric_value > 0:
color = "#ff4444" # 红色
elif numeric_value < 0:
color = "#44ff44" # 绿色
else:
color = "#e8e8e8" # 中性色(原色)
# 更新标签文本和颜色
label.setText(value_str)
label.setStyleSheet(f"""
color: {color};
font-size: {int(14 * self.font_scale)}px;
font-family: 'Consolas', 'Microsoft YaHei', monospace;
background-color: transparent;
""")
def update_basic_info(self, config, daily_stats_df):
"""更新基本信息面板"""
try:
# 获取策略名称
strategy_name = os.path.splitext(os.path.basename(config['strategy_file']))[0]
self.info_labels["策略名称"].setText(strategy_name)
# 设置回测区间
start_time = pd.to_datetime(config['start_time']).strftime('%Y-%m-%d')
end_time = pd.to_datetime(config['end_time']).strftime('%Y-%m-%d')
# 检查是否有每日统计数据
if len(daily_stats_df) > 0:
# 从实际数据中获取起止日期
actual_start = pd.to_datetime(daily_stats_df['date'].iloc[0]).strftime('%Y-%m-%d')
actual_end = pd.to_datetime(daily_stats_df['date'].iloc[-1]).strftime('%Y-%m-%d')
self.info_labels["回测区间"].setText(f"{actual_start} 至\n{actual_end}")
else:
# 使用配置中的日期
self.info_labels["回测区间"].setText(f"{start_time} 至\n{end_time}")
# 设置初始资金
init_capital = float(config['init_capital'])
self.info_labels["初始资金"].setText(f"{init_capital:,.2f}")
# 检查是否有每日统计数据
if len(daily_stats_df) > 0:
# 计算最终资金
final_capital = daily_stats_df['total_asset'].iloc[-1]
self.info_labels["最终资金"].setText(f"{final_capital:,.2f}")
# 计算总收益率
if init_capital > 0:
total_return = (final_capital - init_capital) / init_capital * 100
self.set_value_color(self.info_labels["总收益率"], f"{total_return:+.2f}%", total_return)
else:
self.set_value_color(self.info_labels["总收益率"], "0.00%", 0)
# 计算年化收益率
if len(daily_stats_df) > 1:
# 使用daily_stats_df中的实际日期计算天数
first_date = pd.to_datetime(daily_stats_df['date'].iloc[0]).strftime('%Y-%m-%d')
last_date = pd.to_datetime(daily_stats_df['date'].iloc[-1]).strftime('%Y-%m-%d')
# 计算交易日天数
tools = KhQuTools()
trade_days_count = tools.get_trade_days_count(first_date, last_date)
# 如果交易日计算失败,则使用日历天数作为备选方案
if trade_days_count <= 0:
days = (pd.to_datetime(last_date) - pd.to_datetime(first_date)).days
print(f"警告:无法获取交易日天数,使用日历天数 {days} 作为替代")
else:
days = trade_days_count
print(f"使用交易日天数: {days}")
if days > 0 and init_capital > 0:
# 使用公式 ((1+R)^(250/n)-1)*100% 计算年化收益率
# 其中R是总收益率(小数形式),n是交易日天数,250是一年的交易日数
total_return_decimal = (final_capital / init_capital) - 1
annual_return = (pow(1 + total_return_decimal, 250/days) - 1) * 100
self.set_value_color(self.info_labels["年化收益率"], f"{annual_return:+.2f}%", annual_return)
else:
self.set_value_color(self.info_labels["年化收益率"], "0.00%", 0)
else:
self.set_value_color(self.info_labels["年化收益率"], "0.00%", 0)
# 计算最大回撤
max_drawdown = self.calculate_max_drawdown(daily_stats_df['total_asset'])
self.info_labels["最大回撤"].setText(f"{max_drawdown:.2f}%")
# 计算夏普比率
if 'daily_return' in daily_stats_df.columns:
daily_returns = daily_stats_df['daily_return']
# 添加调试输出
print(f"daily_returns数据类型: {type(daily_returns)}")
print(f"daily_returns长度: {len(daily_returns)}")
print(f"daily_returns是否包含NaN: {daily_returns.isna().any()}")
print(f"daily_returns非NaN值的数量: {daily_returns.count()}")
print(f"daily_returns前5个值: {daily_returns.head(5).tolist()}")
sharpe_ratio = self.calculate_sharpe_ratio(daily_returns)
self.set_value_color(self.info_labels["夏普比率"], f"{sharpe_ratio:+.2f}", sharpe_ratio)
else:
self.set_value_color(self.info_labels["夏普比率"], "0.00", 0)
print("警告: daily_stats_df中没有'daily_return'列")
# 计算索提诺比率
if 'daily_return' in daily_stats_df.columns:
sortino_ratio = self.calculate_sortino_ratio(daily_stats_df['daily_return'])
self.set_value_color(self.info_labels["索提诺比率"], f"{sortino_ratio:+.2f}", sortino_ratio)
else:
self.set_value_color(self.info_labels["索提诺比率"], "0.00", 0)
# 计算阿尔法和贝塔
# 需要基准收益率数据
# 这里假设已经有了基准数据,否则需要加载
try:
benchmark_path = os.path.join(self.backtest_dir, "benchmark.csv")
if os.path.exists(benchmark_path):
benchmark_df = pd.read_csv(benchmark_path, encoding='utf-8-sig')
if len(benchmark_df) > 0 and 'date' in benchmark_df.columns and 'close' in benchmark_df.columns:
# 计算基准收益率
benchmark_df['date'] = pd.to_datetime(benchmark_df['date'])
benchmark_df = benchmark_df.sort_values('date')
benchmark_df['return'] = benchmark_df['close'].pct_change()
# 计算基准总收益率
benchmark_return = self.calculate_benchmark_return(benchmark_df)
# 添加基准收益率信息
if "基准收益率" in self.info_labels:
self.set_value_color(self.info_labels["基准收益率"], f"{benchmark_return:+.2f}%", benchmark_return)