-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktest.py
More file actions
3737 lines (3511 loc) · 202 KB
/
Copy pathbacktest.py
File metadata and controls
3737 lines (3511 loc) · 202 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 argparse
import os
from pathlib import Path
from typing import Optional, Dict, List, Tuple, Any, cast
import numpy as np
import torch
import torch.nn as nn
import json
import time
import re
import pandas as pd
from datetime import datetime
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# 设置中文字体(使用系统实际可用的字体)
plt.rcParams['font.sans-serif'] = ['Noto Sans CJK JP', 'Droid Sans Fallback', 'SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
# 不再抑制字体警告 - 如果有字体问题应该明确暴露
import warnings
# warnings.filterwarnings('ignore', category=UserWarning, module='matplotlib.font_manager') # 已禁用:让字体问题明确暴露
from model import SpacetimeGNNMAM
from train import StreamingPanelDataset
from types import SimpleNamespace
from typing import cast
# RL 对比所需(策略网络与环境)
try:
from rl_env import StockSelectionEnv # 仅在启用 RL 对比时使用
from rl_train import ActorCritic, prepare_env_arrays, make_env_from_data
except Exception:
StockSelectionEnv = None # 延迟到运行期校验
ActorCritic = None
prepare_env_arrays = None
make_env_from_data = None
_VE_EDM_MULTI_WARNED = False
class StepVarianceRecorder:
"""记录多步推理每一步的预测值,最后跨时间计算std(分标的、分样本)。
逻辑:
1. 每个决策日记录 x_i[step, sample, asset] 和 y0_hat_i[step, sample, asset]
2. 累计S个决策日后,对每个(step, sample, asset)计算跨时间的std
3. 这样可以看到每一步的预测值的时间波动性演化
"""
def __init__(self, steps: int, num_samples: int, num_assets: int):
self.steps = int(max(0, steps))
self.num_samples = int(max(0, num_samples))
self.num_assets = int(max(0, num_assets))
# 存储每个时间点的值: list of (steps, M, N) arrays
self.x_history: List[np.ndarray] = []
self.y0_history: List[np.ndarray] = []
self.sigma_sequence: Optional[List[float]] = None
def add_window(self, sigmas: np.ndarray, x_steps: np.ndarray, y0_steps: np.ndarray) -> None:
"""
添加一个时间窗口的数据
Args:
sigmas: (steps,)
x_steps: (steps, M, N) 每一步的x值
y0_steps: (steps, M, N) 每一步的y0_hat值
"""
if self.steps == 0 or self.num_samples == 0 or self.num_assets == 0:
return
if sigmas.shape[0] != self.steps:
return
if x_steps.shape != (self.steps, self.num_samples, self.num_assets):
return
if y0_steps.shape != (self.steps, self.num_samples, self.num_assets):
return
if self.sigma_sequence is None:
self.sigma_sequence = sigmas.astype(np.float64).tolist()
self.x_history.append(x_steps.astype(np.float64))
self.y0_history.append(y0_steps.astype(np.float64))
def export(self) -> Optional[Dict[str, Any]]:
"""计算跨时间的std (分标的、分样本)"""
if len(self.x_history) == 0:
return None
# 堆叠: (S, steps, M, N)
x_all = np.stack(self.x_history, axis=0) # [S, steps, M, N]
y0_all = np.stack(self.y0_history, axis=0) # [S, steps, M, N]
S = x_all.shape[0]
# 对每个(step, m, n)计算跨时间的std
# 结果: (steps, M, N)
std_x = np.std(x_all, axis=0) # [steps, M, N]
std_y0 = np.std(y0_all, axis=0) # [steps, M, N]
# 跨样本平均: (steps, N)
std_x_avg_samples = std_x.mean(axis=1) # [steps, N]
std_y0_avg_samples = std_y0.mean(axis=1) # [steps, N]
return {
"count_windows": int(S),
"num_samples": int(self.num_samples),
"num_assets": int(self.num_assets),
"sigmas": (self.sigma_sequence if self.sigma_sequence is not None else []),
"mean_std_x": std_x_avg_samples.tolist(), # [steps, N]
"mean_std_y0": std_y0_avg_samples.tolist(), # [steps, N]
}
# ==== 扩散推理辅助:单步DDIM近似采样(T→0,一步) ====
def _make_alpha_bar_sbdm() -> float:
"""SBDM 单步近似:常量 abar 作为噪声-信号折中。"""
return 0.5
def _fd_bins(samples: np.ndarray, min_bins: int = 10, max_bins: int = 200) -> int:
"""Freedman–Diaconis 规则计算直方图 bin 数,带稳健护栏。
bins = ceil((x_max - x_min) / (2*IQR*n^{-1/3})),并剪裁到 [min_bins, max_bins]。
当 IQR≈0 或范围≈0 时退化为 Rice 或 Sturges 规则。
"""
try:
x = np.asarray(samples, dtype=np.float64)
# 若全为 NaN/非有限数,直接返回最小 bins,避免后续 nanmin/nanmax 警告
if not np.isfinite(x).any():
return max(1, min_bins)
n = int(x.size)
if n <= 1:
return max(1, min_bins)
x_min = float(np.nanmin(x))
x_max = float(np.nanmax(x))
rng = x_max - x_min
if not np.isfinite(rng) or rng <= 0:
return max(1, min_bins)
q25, q75 = np.percentile(x, [25, 75])
iqr = float(q75 - q25)
if not np.isfinite(iqr) or iqr <= 1e-12:
# 退化规则:Rice 或 Sturges
rice = int(np.ceil(2.0 * (n ** (1.0 / 3.0))))
sturges = int(np.ceil(np.log2(n) + 1.0))
bins = max(rice, sturges)
else:
width = 2.0 * iqr / max(1e-12, (n ** (1.0 / 3.0)))
bins = int(np.ceil(rng / max(width, 1e-12)))
# 护栏与唯一值限制
bins = int(np.clip(bins, min_bins, max_bins))
uniq = int(len(np.unique(x)))
if uniq > 0:
bins = int(min(bins, uniq))
return max(1, bins)
except Exception:
return max(1, min_bins)
@torch.no_grad()
def diffusion_single_step_samples(
model: SpacetimeGNNMAM,
X_win: torch.Tensor, # [1,N,T,F]
num_samples: int,
device: torch.device,
chunk_size: int | None = None,
use_amp: bool = True,
) -> torch.Tensor:
"""SBDM 单步近似采样:从 x_T 与骨干条件反推 y0_hat 分布(标准化域)。
采用按块采样以降低显存峰值;避免不必要的 contiguous 拷贝。"""
model.eval()
B1, N, T, F = X_win.shape
assert B1 == 1
abar = _make_alpha_bar_sbdm()
sqrt_abar = float(np.sqrt(abar))
sqrt_1m = float(np.sqrt(max(1e-9, 1.0 - abar)))
sigma2 = (sqrt_1m * sqrt_1m) / max(1e-9, (sqrt_abar * sqrt_abar))
M = int(num_samples)
if chunk_size is None or chunk_size <= 0:
chunk_size = min(32, M)
outs: list[torch.Tensor] = []
# 采样路径禁用 AMP,统一使用全精度以避免半精度数值不稳定
use_cuda_amp = False
for start in range(0, M, int(chunk_size)):
m_here = int(min(chunk_size, M - start))
# 以视图方式扩展,不做不必要的拷贝
X_rep = X_win.expand(m_here, -1, -1, -1).to(device)
x_T = torch.randn(m_here, N, 1, device=device)
t_idx = torch.ones(m_here, device=device, dtype=torch.long)
score_hat = model.forward_score(X_rep, x_T, t_idx)
y0_hat = x_T + float(sigma2) * score_hat
outs.append(y0_hat)
# 释放临时变量引用,帮助显存回收
del X_rep, x_T, t_idx, score_hat, y0_hat
return torch.cat(outs, dim=0)
@torch.no_grad()
def ve_edm_samples(
model: SpacetimeGNNMAM,
X_win: torch.Tensor, # [1,N,T,F]
num_samples: int,
device: torch.device,
sigma_min: float = 0.01,
sigma_max: float = 1.0,
steps: int = 50, # EDM 迭代去噪步数(仅steps>1时生效)
s_churn: float = 0.0, # Stochastic采样噪声(0=确定性,>0=随机)
s_churn_topk_ratio: float = 0.2, # 步数门限法:仅前k步应用s_churn (k=ceil(ratio*steps))
chunk_size: int | None = None,
diff_steps: int = 1000,
mask: torch.Tensor | None = None, # [1,N,T,F] mask(兼容)
objective: str = 'eps', # 训练目标:'eps' 或 'edm'
sigma_data: float = 0.025, # EDM 预条件化参数
use_random_sigma: bool = True, # 是否使用随机σ采样(与训练对齐)
vol_cond: torch.Tensor | None = None, # [1,N,1] 波动率条件
vol_cond_as_input: bool = True, # yzvol 作为条件输入
vol_cond_scale_output: bool = False, # yzvol 直接乘到输出上
step_var_recorder: Optional[StepVarianceRecorder] = None,
) -> torch.Tensor:
"""
EDM 采样器(与训练分布对齐)
参数:
objective: 'eps' 或 'edm'(与训练一致)
sigma_data: EDM 预条件化参数(仅当 objective='edm' 时使用)
steps: 仅当 use_random_sigma=False 且 steps>1 时使用多步迭代
use_random_sigma: True=每个样本随机采样σ(与训练对齐), False=固定σ_max或多步
vol_cond_as_input: yzvol 作为条件特征输入网络
vol_cond_scale_output: yzvol 直接乘到输出上
返回: [M,N,1] 采样的 log-return
核心原则:训练-推理一致性
- 训练时: σ ~ LogUniform(σ_min, σ_max), x_t = y0 + σ·ε
- 推理时: 应该用相同的σ分布,而不是固定σ_max
"""
model.eval()
B1, N, T, F = X_win.shape
assert B1 == 1
steps = max(1, int(steps))
s_churn = float(max(0.0, s_churn))
s_churn_topk_ratio = float(max(0.0, min(1.0, s_churn_topk_ratio)))
objective = str(objective).lower()
sigma_data = float(sigma_data)
sigma_max = float(max(sigma_min, sigma_max))
sigma_min = float(max(1e-12, min(sigma_min, sigma_max)))
M = int(num_samples)
if chunk_size is None or chunk_size <= 0:
chunk_size = min(32, M)
if use_random_sigma or steps == 1:
# 模式A: 随机σ采样(与训练对齐) - 推荐!
outs_random: List[torch.Tensor] = []
for start in range(0, M, int(chunk_size)):
m_here = int(min(chunk_size, M - start))
X_rep = X_win.to(device).expand(m_here, -1, -1, -1) # [m,N,T,F]
# 每个样本独立采样 σ ~ LogUniform(σ_min, σ_max)
log_sigma_samples = torch.rand(m_here, device=device) * (math.log(sigma_max) - math.log(sigma_min)) + math.log(sigma_min)
sigma_samples = torch.exp(log_sigma_samples).view(m_here, 1, 1) # [m,1,1]
# 初始噪声: x ~ N(0, σ²)
x = torch.randn(m_here, N, 1, device=device) * sigma_samples # [m,N,1]
# t_idx 映射
if sigma_max > sigma_min:
t_float = (log_sigma_samples - math.log(sigma_min)) / max(1e-9, (math.log(sigma_max) - math.log(sigma_min)))
t_idx = torch.clamp((t_float * diff_steps).long() + 1, 1, diff_steps)
else:
t_idx = torch.ones(m_here, dtype=torch.long, device=device)
if objective == 'edm':
# EDM 预条件化
sigma_data_sq = sigma_data ** 2
sigma_sq = sigma_samples ** 2
c_skip = sigma_data_sq / (sigma_sq + sigma_data_sq)
c_out = sigma_samples * sigma_data / torch.sqrt(sigma_sq + sigma_data_sq)
c_in = 1.0 / torch.sqrt(sigma_sq + sigma_data_sq)
x_scaled = c_in * x
# 传递 vol_cond 和开关到 forward_score
vol_cond_chunk = None
if vol_cond is not None and vol_cond.numel() > 0:
vol_cond_chunk = vol_cond.expand(m_here, -1, -1) # [m,N,1]
f_theta = model.forward_score(
X_rep, x_scaled, t_idx,
vol_cond=vol_cond_chunk,
vol_cond_as_input=vol_cond_as_input,
vol_cond_scale_output=vol_cond_scale_output
)
y0_hat = c_skip * x + c_out * f_theta # 移除 τ
outs_random.append(y0_hat)
else:
# score/eps 模式
vol_cond_chunk = None
if vol_cond is not None and vol_cond.numel() > 0:
vol_cond_chunk = vol_cond.expand(m_here, -1, -1) # [m,N,1]
score = model.forward_score(
X_rep, x, t_idx,
vol_cond=vol_cond_chunk,
vol_cond_as_input=vol_cond_as_input,
vol_cond_scale_output=vol_cond_scale_output
)
sigma2 = sigma_samples ** 2
y0_hat = x + sigma2 * score
outs_random.append(y0_hat)
del X_rep, x
return torch.cat(outs_random, dim=0)
else:
# 模式B: 多步迭代(从σ_max开始) - 不推荐,仅用于对比实验
global _VE_EDM_MULTI_WARNED
if not _VE_EDM_MULTI_WARNED:
print(f"[warn] using multi-step EDM sampling (steps={steps}), which may not align with training", flush=True)
_VE_EDM_MULTI_WARNED = True
sigmas = np.exp(np.linspace(np.log(sigma_max + 1e-12), np.log(sigma_min + 1e-12), steps + 1)).astype(np.float64)
outs_multistep: List[torch.Tensor] = []
record_stats = False
# 记录每一步的完整值: (steps, M, N)
x_steps_record: Optional[np.ndarray] = None
y0_steps_record: Optional[np.ndarray] = None
if step_var_recorder is not None and step_var_recorder.steps == steps and step_var_recorder.num_samples == M and step_var_recorder.num_assets == N:
record_stats = True
x_steps_record = np.zeros((steps, M, N), dtype=np.float64)
y0_steps_record = np.zeros((steps, M, N), dtype=np.float64)
# 步数门限:仅前 topk_steps 应用 s_churn
topk_steps = int(max(0, min(steps, math.ceil(steps * s_churn_topk_ratio))))
for start in range(0, M, int(chunk_size)):
m_here = int(min(chunk_size, M - start))
X_rep = X_win.to(device).expand(m_here, -1, -1, -1)
# 初始化:x ~ N(0, sigma_max²)
x = torch.randn(m_here, N, 1, device=device) * float(sigma_max)
# EDM 确定性去噪迭代
for i in range(steps):
sigma_cur = float(sigmas[i])
sigma_next = float(sigmas[i + 1])
# t 索引(与训练映射一致)
if sigma_max > sigma_min:
log_sigma_cur = np.log(max(sigma_cur, 1e-12))
t_float = (log_sigma_cur - math.log(max(sigma_min, 1e-12))) / max(1e-9, (math.log(max(sigma_max, 1e-12)) - math.log(max(sigma_min, 1e-12))))
t_idx = torch.full((m_here,), int(min(diff_steps, max(1, int(t_float * diff_steps) + 1))), dtype=torch.long, device=device)
else:
t_idx = torch.ones(m_here, dtype=torch.long, device=device)
if record_stats and x_steps_record is not None:
x_cpu = x.detach().cpu().view(m_here, N).numpy().astype(np.float64)
x_steps_record[i, start:start+m_here, :] = x_cpu
if objective == 'edm':
# EDM 预条件化:直接预测 y0
sigma_cur_t = torch.tensor(sigma_cur, device=device).view(1, 1, 1)
sigma_data_sq = sigma_data ** 2
sigma_sq = sigma_cur_t ** 2
c_skip = sigma_data_sq / (sigma_sq + sigma_data_sq)
c_out = sigma_cur_t * sigma_data / torch.sqrt(sigma_sq + sigma_data_sq)
c_in = 1.0 / torch.sqrt(sigma_sq + sigma_data_sq)
# 预条件化输入并预测 y0_hat
x_scaled = c_in * x
vol_cond_chunk = None
if vol_cond is not None and vol_cond.numel() > 0:
vol_cond_chunk = vol_cond.expand(m_here, -1, -1) # [m,N,1]
f_theta = model.forward_score(
X_rep, x_scaled, t_idx,
vol_cond=vol_cond_chunk,
vol_cond_as_input=vol_cond_as_input,
vol_cond_scale_output=vol_cond_scale_output
)
y0_hat = c_skip * x + c_out * f_theta # 移除 τ
if record_stats and y0_steps_record is not None:
y_cpu = y0_hat.detach().cpu().view(m_here, N).numpy().astype(np.float64)
y0_steps_record[i, start:start+m_here, :] = y_cpu
# EDM更新: x_{next} = y0_hat + σ_{next}·ε
# 其中 ε 从当前预测反推: ε ≈ (x - y0_hat) / σ_cur
if i < steps - 1:
# 多步: 保留噪声方向,缩放到下一个σ级别
eps_approx = (x - y0_hat) / max(sigma_cur, 1e-6)
# SDE模式: 添加随机噪声 (s_churn > 0) — 仅前 topk_steps 生效
if s_churn > 0.0 and i < topk_steps:
# 先添加噪声到当前状态
gamma_i = min(s_churn / steps, math.sqrt(2.0) - 1.0)
sigma_hat_cur = sigma_cur * (1.0 + gamma_i)
noise_extra = torch.randn_like(x) * math.sqrt(max(0, sigma_hat_cur**2 - sigma_cur**2))
x = x + noise_extra
# 重新预测y0_hat (可选,为简化跳过)
# 更新到下一步
x = y0_hat + sigma_next * eps_approx
else:
# 最后一步: 直接输出预测的y0
x = y0_hat
else:
# score/eps 模式:使用 score-based更新(保持原逻辑)
vol_cond_chunk = None
if vol_cond is not None and vol_cond.numel() > 0:
vol_cond_chunk = vol_cond.expand(m_here, -1, -1) # [m,N,1]
score = model.forward_score(
X_rep, x, t_idx,
vol_cond=vol_cond_chunk,
vol_cond_as_input=vol_cond_as_input,
vol_cond_scale_output=vol_cond_scale_output
)
# score模式下: y0_hat = x + sigma^2 * score
if record_stats and y0_steps_record is not None:
y0_hat_score = x + (sigma_cur ** 2) * score
y_cpu = y0_hat_score.detach().cpu().view(m_here, N).numpy().astype(np.float64)
y0_steps_record[i, start:start+m_here, :] = y_cpu
# SDE模式: 先添加随机噪声 — 仅前 topk_steps 生效
if s_churn > 0.0 and i < steps - 1 and i < topk_steps:
gamma_i = min(s_churn / steps, math.sqrt(2.0) - 1.0)
sigma_hat_cur = sigma_cur * (1.0 + gamma_i)
noise_extra = torch.randn_like(x) * math.sqrt(max(0, sigma_hat_cur**2 - sigma_cur**2))
x = x + noise_extra
sigma_cur_used = sigma_hat_cur
else:
sigma_cur_used = sigma_cur
d = x + (sigma_next - sigma_cur_used) * score
if i < steps - 1:
# Heun 二阶修正
sigma_mid = sigma_next
if sigma_max > sigma_min:
log_sigma_mid = np.log(max(sigma_mid, 1e-12))
t_float_mid = (log_sigma_mid - math.log(max(sigma_min, 1e-12))) / max(1e-9, (math.log(max(sigma_max, 1e-12)) - math.log(max(sigma_min, 1e-12))))
t_idx_mid = torch.full((m_here,), int(min(diff_steps, max(1, int(t_float_mid * diff_steps) + 1))), dtype=torch.long, device=device)
else:
t_idx_mid = t_idx
score_mid = model.forward_score(
X_rep, d, t_idx_mid,
vol_cond=vol_cond_chunk,
vol_cond_as_input=vol_cond_as_input,
vol_cond_scale_output=vol_cond_scale_output
)
x = x + (sigma_next - sigma_cur_used) * 0.5 * (score + score_mid)
else:
x = d
outs_multistep.append(x)
del X_rep, x
# 将这个时间窗口的记录添加到recorder
if record_stats and step_var_recorder is not None and x_steps_record is not None and y0_steps_record is not None:
sigma_seq = np.asarray(sigmas[:-1], dtype=np.float64)
step_var_recorder.add_window(sigma_seq, x_steps_record, y0_steps_record)
return torch.cat(outs_multistep, dim=0)
@torch.no_grad()
def diffusion_ddim_samples(
model: SpacetimeGNNMAM,
X_win: torch.Tensor, # [1,N,T,F]
num_samples: int,
device: torch.device,
chunk_size: int | None = None,
steps: int = 1,
eta: float = 0.0,
sigma_min: float = 0.01,
sigma_max: float = 1.0,
diff_steps: int = 1000,
vol_cond: torch.Tensor | None = None, # [1,N,1] 当前窗口的波动率条件
sigma_schedule: str = "log_uniform",
time_warp_gamma: float = 0.5,
) -> torch.Tensor:
"""多步 DDIM 风格的确定性近似(基于 score 的逐步积分)。
steps=1 时等价于单步;steps>1 时按等步长迭代:
x_{k+1} = x_k + (sigma2_total/steps) * score(X, x_k, t=const)
返回 [M,N,1]
"""
model.eval()
B1, N, T, F = X_win.shape
assert B1 == 1
steps = max(1, int(steps))
eta = float(max(0.0, min(1.0, eta)))
# 构建 σ 调度(与训练一致):从 sigma_max 递减到 sigma_min,共 steps 步
sigma_max = float(max(sigma_min, sigma_max))
sigma_min = float(max(1e-12, min(sigma_min, sigma_max)))
schedule = str(sigma_schedule).lower()
if schedule == "karras":
rho = 7.0
u = np.linspace(0.0, 1.0, steps + 1)
lo = sigma_min ** (1.0 / rho)
hi = sigma_max ** (1.0 / rho)
sig = (lo + u * (hi - lo)) ** rho # 从 sigma_min → sigma_max
levels = sig[::-1].astype(np.float64) # 反转: sigma_max → sigma_min
else:
levels = np.exp(
np.linspace(
np.log(sigma_max + 1e-12),
np.log(sigma_min + 1e-12),
steps + 1,
)
).astype(np.float64) # [steps+1]
# 训练使用的时间索引映射(与 train 相同公式)
diff_steps = int(max(1, diff_steps))
M = int(num_samples)
if chunk_size is None or chunk_size <= 0:
chunk_size = min(32, M)
# 仅预计算每步的 Δσ² 和 t 索引(推理时调用 forward_score,保持与训练一致的条件注入)
delta_sigma2_steps: list[float] = []
t_idx_vals: list[int] = []
for k in range(steps):
sig_k = float(levels[k])
sig_next = float(levels[k + 1])
if sigma_max > sigma_min:
log_sigma = float(np.log(max(sig_k, 1e-12)))
t_float = (log_sigma - math.log(max(sigma_min, 1e-12))) / max(1e-9, (math.log(max(sigma_max, 1e-12)) - math.log(max(sigma_min, 1e-12))))
t_idx_val = int(min(diff_steps, max(1, int(t_float * diff_steps) + 1)))
else:
t_idx_val = 1
t_idx_vals.append(t_idx_val)
delta_sigma2_steps.append(float(max(0.0, (sig_k * sig_k) - (sig_next * sig_next))))
outs: list[torch.Tensor] = []
for start in range(0, M, int(chunk_size)):
m_here = int(min(chunk_size, M - start))
X_rep = X_win.to(device).expand(m_here, -1, -1, -1)
x = torch.randn(m_here, N, 1, device=device) * float(sigma_max)
# 预展开并缓存 s_yz 与 s_yz_sq,减少循环内广播开销
if (vol_cond is not None) and (vol_cond.numel() > 0):
vol_e = cast(torch.Tensor, vol_cond)
s_yz_cached = torch.clamp(vol_e.expand(m_here, -1, -1), min=1e-6)
s_yz_sq_cached = s_yz_cached * s_yz_cached
else:
s_yz_cached = None
s_yz_sq_cached = None
for k in range(steps):
# 基础 t 映射(0..1)
if sigma_max > sigma_min:
t_float = float((np.log(max(float(levels[k]), 1e-12)) - math.log(max(sigma_min, 1e-12))) / max(1e-9, (math.log(max(sigma_max, 1e-12)) - math.log(max(sigma_min, 1e-12)))))
else:
t_float = 0.0
# 条件化时间扭曲:t_eff = clamp(t * s_bar^gamma, 0..1)
warp_gamma = float(time_warp_gamma)
if (vol_cond is not None) and (vol_cond.numel() > 0):
vol_e = cast(torch.Tensor, vol_cond)
s_yz_warp = torch.clamp(vol_e.expand(m_here, -1, -1), min=1e-6) # [m,N,1]
s_bar = s_yz_warp.view(m_here, -1).mean(dim=1) # [m]
factor = torch.pow(s_bar, warp_gamma) # [m]
t_eff = torch.clamp(torch.full((m_here,), float(t_float), device=device) * factor, 0.0, 1.0)
t_idx = (t_eff * float(diff_steps)).long().clamp(1, int(diff_steps))
else:
t_idx = torch.full((m_here,), int(t_idx_vals[k]), dtype=torch.long, device=device)
score_hat = model.forward_score(X_rep, x, t_idx, vol_cond=vol_cond) # 显式条件化
delta_sigma2 = float(delta_sigma2_steps[k])
# 从 vol_cond 推导 per-asset s_yz(若无则为 1)
if s_yz_cached is not None:
s_yz = cast(torch.Tensor, s_yz_cached)
s_yz_sq = cast(torch.Tensor, s_yz_sq_cached)
else:
s_yz = torch.ones_like(x)
s_yz_sq = s_yz * s_yz
if eta > 0.0 and delta_sigma2 > 0.0:
noise = torch.randn_like(x) * math.sqrt(delta_sigma2) * eta * s_yz
x = x + (delta_sigma2 * s_yz_sq) * score_hat + noise
else:
x = x + (delta_sigma2 * s_yz_sq) * score_hat
outs.append(x)
del X_rep, x, score_hat
return torch.cat(outs, dim=0)
def diffusion_direct_score_samples(
model: SpacetimeGNNMAM,
X_win: torch.Tensor, # [1,N,T,F]
base_pred: torch.Tensor, # [1,N,1] 作为 y0 的近似中心
num_samples: int,
device: torch.device,
chunk_size: int | None = None,
sigma_min: float = 0.01,
sigma_max: float = 1.0,
diff_steps: int = 1000,
vol_cond: torch.Tensor | None = None, # [1,N,1]
sigma_schedule: str = "log_uniform",
time_warp_gamma: float = 0.5,
direct_anchor: str = "random",
direct_lambda: float = 1.0,
) -> torch.Tensor:
"""训练一致的单步直推:
对每个样本独立抽取 σ~训练同分布,构造 x_t = y0̂ + σ·s_yz·ε,
再按 Tweedie 公式 y0_hat = x_t + (σ²·s_yz²)·score(X, x_t, t_idx(σ))。
返回 [M,N,1]
"""
model.eval()
B1, N, T, F = X_win.shape
assert B1 == 1
M = int(num_samples)
if chunk_size is None or chunk_size <= 0:
chunk_size = min(32, M)
# 诊断:检查 base_pred 分布
base_np = base_pred.detach().cpu().numpy().flatten()
print(f"[diag-base_pred] mean={float(base_np.mean()):.6f}, std={float(base_np.std()):.6f}, "
f"min={float(base_np.min()):.6f}, max={float(base_np.max()):.6f}", flush=True)
# 预展开波动条件
has_vol = (vol_cond is not None) and (vol_cond.numel() > 0)
outs: list[torch.Tensor] = []
schedule = str(sigma_schedule).lower()
anchor = str(direct_anchor).lower()
lam = float(direct_lambda)
sigma_min = float(max(1e-12, sigma_min))
sigma_max = float(max(sigma_min, sigma_max))
diff_steps = int(max(1, diff_steps))
with torch.no_grad():
for start in range(0, M, int(chunk_size)):
m_here = int(min(chunk_size, M - start))
X_rep = X_win.to(device).expand(m_here, -1, -1, -1)
mu = base_pred.to(device).expand(m_here, -1, -1) # [m,N,1]
# 直推锚点 σ 选择
if anchor.startswith("fixed:"):
# 指定绝对 σ 数值
try:
s_fix = float(anchor.split(":",1)[1])
except Exception:
s_fix = float((sigma_min * sigma_max) ** 0.5)
sigmas = torch.full((m_here,), float(np.clip(s_fix, sigma_min, sigma_max)), device=device)
elif anchor.startswith("quantile:"):
try:
q = float(anchor.split(":",1)[1])
except Exception:
q = 0.5
q = float(min(0.999, max(0.001, q)))
if schedule == "karras":
rho = 7.0
smax_r = sigma_max ** (1.0 / rho)
smin_r = sigma_min ** (1.0 / rho)
sig_q = (smax_r + q * (smin_r - smax_r)) ** rho
else:
sig_q = math.exp(q * (math.log(sigma_min) - math.log(sigma_max)) + math.log(sigma_max))
sigmas = torch.full((m_here,), float(sig_q), device=device)
elif anchor == "median":
if schedule == "karras":
rho = 7.0
smax_r = sigma_max ** (1.0 / rho)
smin_r = sigma_min ** (1.0 / rho)
sig_med = (smax_r + 0.5 * (smin_r - smax_r)) ** rho
else:
sig_med = math.exp(0.5 * (math.log(sigma_min) - math.log(sigma_max)) + math.log(sigma_max))
sigmas = torch.full((m_here,), float(sig_med), device=device)
elif anchor.startswith("multi:"):
# 多分位锚点,均匀分配到一批样本
try:
parts = anchor.split(":",1)[1]
qs = [float(x) for x in parts.split(",") if x.strip()]
except Exception:
qs = [0.4, 0.7]
qs = [float(min(0.999, max(0.001, q))) for q in qs]
vals = []
for q in qs:
if schedule == "karras":
rho = 7.0
smax_r = sigma_max ** (1.0 / rho)
smin_r = sigma_min ** (1.0 / rho)
vals.append((smax_r + q * (smin_r - smax_r)) ** rho)
else:
vals.append(math.exp(q * (math.log(sigma_min) - math.log(sigma_max)) + math.log(sigma_max)))
vals_t = torch.tensor(vals, device=device, dtype=torch.float32)
idx = torch.arange(m_here, device=device) % max(1, len(vals))
sigmas = vals_t[idx]
else:
# random:按训练同分布随机抽样
if schedule == "karras":
rho = 7.0
u = torch.rand(m_here, device=device)
smax_r = sigma_max ** (1.0 / rho)
smin_r = sigma_min ** (1.0 / rho)
sigmas = torch.pow(smax_r + u * (smin_r - smax_r), rho) # [m]
else:
u = torch.rand(m_here, device=device)
sigmas = torch.exp(u * (math.log(sigma_min) - math.log(sigma_max)) + math.log(sigma_max)) # [m]
# t 索引(含时间扭曲)
log_sigma = torch.log(sigmas.clamp(min=1e-12))
t_cont = (log_sigma - math.log(sigma_min)) / max(1e-9, (math.log(sigma_max) - math.log(sigma_min)))
t_cont = t_cont.clamp(0.0, 1.0)
if has_vol and float(time_warp_gamma) > 0.0:
vol_e = cast(torch.Tensor, vol_cond)
s_bar = torch.clamp(vol_e.expand(m_here, -1, -1).view(m_here, -1).mean(dim=1), min=1e-6)
factor = torch.pow(s_bar, float(time_warp_gamma))
t_cont = (t_cont * factor).clamp(0.0, 1.0)
t_idx = (t_cont * float(diff_steps)).long().clamp(1, int(diff_steps)) # [m]
# 构造 x_t 与 s_yz
if has_vol:
vol_e = cast(torch.Tensor, vol_cond)
s_yz = torch.clamp(vol_e.expand(m_here, -1, -1).to(device), min=1e-6)
else:
s_yz = torch.ones_like(mu)
eps = torch.randn_like(mu)
# 训练一致性:x_t = mu + sigma*eps(不含 s_yz),s_yz 只在 Tweedie 恢复时使用
x_t = mu + sigmas.view(-1, 1, 1) * eps # [m,N,1]
score_hat = model.forward_score(X_rep, x_t, t_idx, vol_cond=(vol_cond if has_vol else None))
y0_hat = x_t + lam * (sigmas.view(-1, 1, 1) ** 2) * (s_yz * s_yz) * score_hat
outs.append(y0_hat)
del X_rep, mu, eps, x_t, score_hat
return torch.cat(outs, dim=0)
def _detect_board(stock_id: str) -> str:
sid = str(stock_id)
if sid.endswith(".XSHG") and sid.startswith("688"):
return "KSH"
if sid.endswith(".XSHE") and (sid.startswith("300") or sid.startswith("301")):
return "GEM"
if sid.endswith(".BJ") or ".BJ" in sid:
return "BSE"
if sid.endswith(".XSHG") or sid.endswith(".XSHE"):
return "MainBoard"
return "UNKNOWN"
def _build_price_limit_vec(stocks: List[str], default_pct: float = 0.10) -> Tuple[np.ndarray, Dict[str, int]]:
vec = []
stats = {"MainBoard": 0, "KSH": 0, "GEM": 0, "BSE": 0, "UNKNOWN": 0}
for sid in stocks:
board = _detect_board(sid)
if board == "KSH":
vec.append(0.20)
elif board in ("GEM", "BSE"):
vec.append(0.30)
elif board == "MainBoard":
vec.append(0.10)
else:
print(f"[warn] 未识别板块,按默认阈值处理: {sid} -> {default_pct:.0%}")
vec.append(float(default_pct))
stats[board] = stats.get(board, 0) + 1
return np.asarray(vec, dtype=np.float32), stats
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="模型市场回测与指标计算(t+1 决策、t+2 结算),支持 OOS 与高级流动性约束与涨跌停启发式")
parser.add_argument("--data_dir", type=str, default="data/processed")
parser.add_argument("--checkpoint", type=str, required=True, help="模型权重路径 .pt")
parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
# panels 推理,test_env 环境
parser.add_argument("--oos_stock_ratio", type=float, default=0.0, help="样本外股票比例(按训练期股票池随机留出),0 表示不做 OOS 拆分")
parser.add_argument("--oos_stock_list", type=str, default="", help="样本外股票列表文件(每行一个股票ID),优先于比例")
parser.add_argument("--results_dir", type=str, default="experiments", help="实验结果保存目录")
parser.add_argument("--results_name", type=str, default="", help="实验命名(可选)")
parser.add_argument("--all_exclude_oos", type=int, default=1, help="ALL 回测是否默认排除 OOS(1排除/0不排除)")
parser.add_argument("--enable_oos_backtest", type=int, default=1, help="是否执行 OOS 回测(1=执行,0=跳过)")
# 交易参数
parser.add_argument("--initial_capital", type=float, default=1000000.0, help="初始资金(元)")
parser.add_argument("--impact_linear", type=float, default=0.01, help="线性冲击成本系数:cost = linear * (our_volume / avg_volume)")
parser.add_argument("--impact_sqrt", type=float, default=0.005, help="平方根冲击成本系数:cost = sqrt * sqrt(our_volume / avg_volume)")
parser.add_argument("--liquidity_alpha", type=float, default=0.3, help="流动性阈值:决策日成交量 >= alpha * 训练期平均量才可交易")
parser.add_argument("--min_lot", type=int, default=100, help="最小交易单位(股/手)")
parser.add_argument("--commission_rate", type=float, default=0.0005, help="双边佣金费率")
parser.add_argument("--stamp_duty_sell", type=float, default=0.001, help="卖出印花税费率")
parser.add_argument("--price_limit_pct", type=float, default=0.10, help="按价格跨度判断涨跌停阈值(如0.10表示10%)")
parser.add_argument("--debug_stockid", type=str, default="", help="调试股票ID,输出该股票逐日详情")
# 采样驱动策略参数
parser.add_argument("--sampler", type=str, default="auto", help="采样器选择:auto|ve_edm|direct|ddim")
parser.add_argument("--objective", type=str, default="score", help="训练目标类型:score/edm,用于推理对齐")
parser.add_argument("--edm_steps", type=int, default=50, help="VE-EDM 多步 Heun 采样步数(sampler=ve_edm/auto 时生效)")
parser.add_argument("--use_random_sigma", type=int, default=1, help="1=按训练分布随机σ(单步);0=关闭随机σ,使用多步 edm_steps")
parser.add_argument("--num_samples", type=int, default=64, help="每只股票价格分布的采样次数(SBDM 单步近似)")
parser.add_argument("--ddim_steps", type=int, default=1, help="DDIM 多步采样步数(1 表示单步,>1 提升推理质量)")
parser.add_argument("--direct_score", type=int, default=1, help="1=使用训练一致的单步直推;0=使用 DDIM 步进")
parser.add_argument("--direct_anchor", type=str, default="random", help="直推锚点选择:random|median|quantile:p|fixed:sigma|multi:q1,q2,...(q为0..1分位)")
parser.add_argument("--direct_lambda", type=float, default=1.0, help="直推温度系数 λ,缩放 Tweedie 更新项 (σ²·s_yz²·score)")
parser.add_argument("--ddim_eta", type=float, default=0.0, help="DDIM 采样噪声系数 η∈[0,1];0=确定性,>0 引入随机性")
parser.add_argument("--chunk_size", type=int, default=0, help="采样块大小(每批生成 M 的子批量);0 表示自动按 num_samples/4 并夹在 [16,64]")
# 与训练一致的 σ 调度参数
parser.add_argument("--score_sigma_min", type=float, default=0.01, help="训练用最小噪声强度 σ_min,用于推理调度对齐")
parser.add_argument("--score_sigma_max", type=float, default=1.0, help="训练用最大噪声强度 σ_max,用于推理调度对齐")
parser.add_argument("--sigma_data", type=float, default=0.025, help="EDM 预条件化参数 σ_data,用于 ve_edm 采样")
parser.add_argument("--s_churn", type=float, default=0.0, help="VE-EDM 采样的随机扰动系数 s_churn")
parser.add_argument("--s_churn_topk_ratio", type=float, default=0.2, help="步数门限:仅前 ceil(ratio*steps) 步应用 s_churn")
parser.add_argument("--diff_steps", type=int, default=1000, help="训练用离散时间步数,用于 t 索引映射对齐")
parser.add_argument("--progress", type=int, default=1, help="是否打印进度信息(1/0)")
parser.add_argument("--log_interval", type=int, default=20, help="进度打印间隔(步)")
parser.add_argument("--risk_k", type=float, default=3.0, help="风险因子 k,用于 tanh(k*|S|)")
parser.add_argument("--max_lots", type=int, default=10, help="tanh 输出映射到的最大手数(等手数模式时生效)")
parser.add_argument("--value_based_position", type=int, default=1, help="1=按名义资金映射手数;0=按等手数映射")
parser.add_argument("--max_notional_per_stock", type=float, default=5000.0, help="单股最大名义资金(元),用于按名义资金映射")
parser.add_argument("--benchmark_discrete", type=int, default=1, help="等资金基准是否应用手数离散(按最小交易单位)")
parser.add_argument("--cvar_alpha", type=float, default=0.05, help="CVaR 分位阈值(下 5%)")
parser.add_argument("--entropy_bins", type=int, default=20, help="信息熵直方图的分箱数(离散熵)")
parser.add_argument("--cvar_eps", type=float, default=1e-6, help="CVaR 防除零小常数")
parser.add_argument("--entropy_eps", type=float, default=1e-6, help="信息熵防除零小常数")
parser.add_argument("--cvar_power", type=float, default=1.0, help="|CVaR| 权重幂指数 ∈[0,1],越小对尾部风险惩罚越弱")
parser.add_argument("--er_positive_buy", type=int, default=0, help="1=启用简单规则:ER>0 则按 max_notional_per_stock 买入(整手取整),否则 0;忽略 tanh 映射")
# ER 口径为净收益率(已含手续费/印花/滑点),不再额外设置开仓阈值参数
# RL 对比(在本回测内叠加 RL 策略权益曲线)
parser.add_argument("--rl_compare", type=int, default=0, help="1=叠加RL策略曲线(需要 checkpoints/rl/policy.pt)")
parser.add_argument("--rl_checkpoint", type=str, default=os.path.join("checkpoints", "rl", "policy.pt"), help="RL 策略权重路径 .pt")
# 尾部裁剪(避免评估预处理填充的天数)
parser.add_argument("--trim_tail_days", type=int, default=0, help="回测时裁掉末尾 k 天(与预处理 tail_fill_days 对齐)")
parser.add_argument("--use_yz_cond", type=int, default=1, help="是否在采样时启用 yz_vol 条件 (1/0)")
parser.add_argument("--time_warp_gamma", type=float, default=0.0, help="时间扭曲指数 γ,与训练 time_warp_gamma 对齐")
parser.add_argument("--entmax_alpha", type=float, default=1.5, help="entmax激活函数的α参数")
parser.add_argument("--exp_clip_bound", type=float, default=0.0, help="log-return转价格前的裁剪阈值;<=0 表示不裁剪")
parser.add_argument("--diffusion_head_hidden", type=int, default=None, help="Diffusion head隐藏维度(None=使用d_model)")
parser.add_argument("--diffusion_head_dropout", type=float, default=None, help="Diffusion head dropout(None=使用模型dropout)")
return parser.parse_args()
def load_checkpoint(path: str, device: torch.device) -> Dict:
pack = torch.load(path, map_location=device, weights_only=False)
return pack
def load_dataset_split(data_dir: str, split: str):
pack = torch.load(os.path.join(data_dir, f"{split}.pt"), weights_only=False)
return pack
def load_meta(data_dir: str) -> Dict:
meta_path = os.path.join(data_dir, "meta.json")
if not os.path.exists(meta_path):
raise FileNotFoundError("缺少 meta.json,无法保证复现")
with open(meta_path, "r", encoding="utf-8") as f:
return json.load(f)
def build_oos_stocks(stocks: List[str], oos_list_path: str, ratio: float) -> List[str]:
if oos_list_path and os.path.exists(oos_list_path):
with open(oos_list_path, "r", encoding="utf-8") as f:
oos = [line.strip() for line in f if line.strip()]
return [s for s in oos if s in stocks]
if ratio > 0:
k = max(1, int(len(stocks) * ratio))
rng = np.random.default_rng(42)
idx = rng.choice(len(stocks), size=k, replace=False)
return [stocks[i] for i in idx]
return []
# 已移除单独的"预测精度"指标输出(MSE/MAE/Corr),专注交易回测指标
def save_results(results_dir: str, results_name: str, payload: Dict):
Path(results_dir).mkdir(parents=True, exist_ok=True)
ts = time.strftime("%Y%m%d_%H%M%S")
name = results_name if results_name else f"exp_{ts}"
out_path = os.path.join(results_dir, f"{name}.json")
with open(out_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
print(f"结果已保存: {out_path}")
return name
def save_backtest_plots(bt: Dict, plot_dir: str, prefix: str, index_data: Optional[pd.DataFrame] = None):
Path(plot_dir).mkdir(parents=True, exist_ok=True)
# 取日期轴(若有)
trades = bt.get("daily_trades", [])
x_dates = None
if isinstance(trades, list) and len(trades) > 0:
x_dates = [row.get("date", "") for row in trades]
from datetime import datetime, timedelta
import matplotlib.dates as mdates
def to_dt(s):
try:
return datetime.fromisoformat(str(s)[:10])
except Exception:
return None
x_parsed = [to_dt(s) for s in x_dates]
if any(dt is None for dt in x_parsed):
x_dates = None
else:
x_dates = x_parsed
# 构建"首末精确日期 + 中间按月刻度"的刻度
def month_tick_positions(first_dt: datetime, last_dt: datetime):
# 月初对齐
cur = datetime(first_dt.year, first_dt.month, 1)
end = datetime(last_dt.year, last_dt.month, 1)
ticks = [first_dt]
while cur <= end:
if cur > first_dt and cur < last_dt:
ticks.append(cur)
# 下一个月月初
if cur.month == 12:
cur = datetime(cur.year + 1, 1, 1)
else:
cur = datetime(cur.year, cur.month + 1, 1)
ticks.append(last_dt)
return ticks
if x_dates and x_dates[0] is not None and x_dates[-1] is not None:
month_ticks = month_tick_positions(cast(datetime, x_dates[0]), cast(datetime, x_dates[-1]))
# 权益曲线(含基准和指数对比)+ 超额收益(日度柱状图)
values = np.array(bt.get("values", []), dtype=np.float64)
cash_series = np.array(bt.get("cash_series", []), dtype=np.float64)
holding_value_series = np.array(bt.get("holding_value_series", []), dtype=np.float64)
benchmark_cumulative = np.array(bt.get("benchmark_cumulative", []), dtype=np.float64)
benchmark_returns = np.array(bt.get("benchmark_returns", []), dtype=np.float64)
benchmark_equal_lots_cum = np.array(bt.get("benchmark_equal_lots_cumulative", []), dtype=np.float64)
daily_returns = np.array(bt.get("daily_returns", []), dtype=np.float64)
# 对比策略(手数映射策略)
alt_values = np.array(bt.get("alt_values", []), dtype=np.float64)
alt_init = float(bt.get("alt_initial_capital", alt_values[0] if alt_values.size > 0 else 1.0))
alt_label = str(bt.get("alt_label", "手数映射策略"))
if values.size > 0:
init_cap = float(bt.get("initial_capital", values[0] if values.size > 0 else 1.0))
eq_norm = values / max(1e-9, init_cap) - 1.0
# 创建上下两个子图:上-收益曲线,下-超额收益柱状图
fig, (ax_top, ax_bottom) = plt.subplots(2, 1, figsize=(12, 8), sharex=True, gridspec_kw={'height_ratios': [3, 1]})
if x_dates is not None:
# 转换日期格式用于对齐
try:
plot_dates = [datetime.strptime(str(d), "%Y-%m-%d") if isinstance(d, str) else d for d in x_dates]
except Exception:
plot_dates = x_dates
# 策略收益曲线
ax_top.plot(plot_dates, eq_norm, color="#1f77b4", linewidth=2.2, label="策略收益", alpha=0.9)
# 等资金基准(每标的固定名义资金)
if benchmark_cumulative.size > 0 and benchmark_cumulative.size == eq_norm.size:
ax_top.plot(plot_dates, benchmark_cumulative, color="#ff7f0e", linewidth=1.8, label="等资金基准(每标的固定名义资金)", alpha=0.85)
# 等手数基准(一次性成本,买入持有)
if benchmark_equal_lots_cum.size > 0 and benchmark_equal_lots_cum.size == eq_norm.size:
ax_top.plot(plot_dates, benchmark_equal_lots_cum, color="#8c564b", linewidth=1.6, linestyle='--', label="等手数基准(B&H, 含一次性成本)", alpha=0.8)
# 对比策略(若存在)
if alt_values.size > 0:
alt_eq = alt_values / max(1e-9, alt_init) - 1.0
if alt_eq.size == eq_norm.size:
ax_top.plot(plot_dates, alt_eq, color="#9467bd", linewidth=1.6, linestyle='-.', label=alt_label, alpha=0.85)
# 自定义日收益(按单利累加):来自 backtest.custom_daily_returns
try:
custom = bt.get("custom_daily_returns", None)
if custom is None:
# 从 cfg.backtest 读取(若保存了 config_used)
cfg_used = bt.get("config_used", {})
bcfg = cfg_used.get("backtest", {}) if isinstance(cfg_used, dict) else {}
series = bcfg.get("custom_daily_returns", []) if isinstance(bcfg, dict) else []
else:
series = custom
if isinstance(series, list):
S = len(eq_norm)
arr = np.array(series, dtype=np.float64)
if arr.size < S:
pad = np.zeros(S - arr.size, dtype=np.float64)
arr = np.concatenate([arr, pad], axis=0)
elif arr.size > S:
arr = arr[:S]
cum_simple = np.cumsum(arr)
ax_top.plot(plot_dates, cum_simple, color="#000000", linewidth=1.4, linestyle=':', label="自定义(单利)", alpha=0.9)
except Exception:
pass
# 添加大盘指数对比
if index_data is not None:
index_colors = ['#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f']
index_styles = ['-', '--', '-.', ':', '-', '--']
start_date = plot_dates[0] if plot_dates else None
end_date = plot_dates[-1] if plot_dates else None
if start_date and end_date:
mask = (index_data.index >= start_date) & (index_data.index <= end_date)
filtered_index = index_data[mask]
color_idx = 0
for col in index_data.columns:
if not col.endswith('_return') and color_idx < len(index_colors):
index_name = col
if filtered_index[col].notna().sum() > 0:
aligned_dates = []
aligned_returns = []
base_price = None
for plot_date in plot_dates:
closest_date = filtered_index.index[filtered_index.index <= plot_date]
if len(closest_date) > 0:
closest_date = closest_date[-1] # pyright: ignore[reportIndexIssue]
if pd.notna(filtered_index.loc[closest_date, col]):
current_price = filtered_index.loc[closest_date, col]
if base_price is None:
base_price = current_price
normalized_return = 0.0
else:
normalized_return = (current_price - base_price) / base_price
aligned_dates.append(plot_date)
aligned_returns.append(normalized_return)
if len(aligned_dates) > 0:
ax_top.plot(
aligned_dates,
aligned_returns,
color=index_colors[color_idx],
linestyle=index_styles[color_idx % len(index_styles)],
linewidth=1.2,
label=index_name,
alpha=0.7,
)
color_idx += 1
# 超额收益(累计):策略累计收益 - 等资金基准累计收益
if benchmark_cumulative.size > 0 and benchmark_cumulative.size == eq_norm.size:
cum_excess = eq_norm - benchmark_cumulative
ax_bottom.plot(plot_dates, cum_excess, color="#2ca02c", linewidth=1.6, label="累计超额")