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 | from matplotlib.ticker import PercentFormatter
import matplotlib.patches as mpatches
def _to_dt_index(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
if 'trade_date' not in df.columns:
raise ValueError('missing trade_date column')
df['trade_date'] = pd.to_datetime(df['trade_date'].astype(str), errors='coerce')
df = df.dropna(subset=['trade_date']).set_index('trade_date').sort_index()
df.index.name = 'trade_date'
return df
def read_split_signals(folder: str, ts_code: str) -> Optional[pd.DataFrame]:
p1 = os.path.join(folder, f'{ts_code}_signals_split.parquet')
p2 = os.path.join(folder, f'{ts_code}_alligator_signals_split.parquet')
path = p1 if os.path.exists(p1) else p2
if not os.path.exists(path):
return None
df = pd.read_parquet(path)
if 'trade_date' in df.columns:
df = _to_dt_index(df)
elif 'index' in df.columns:
df['index'] = pd.to_datetime(df['index'].astype(str), errors='coerce')
df = df.dropna(subset=['index']).set_index('index').sort_index()
return df
def read_price_series(data_folder: str, ts_code: str, col: str) -> pd.Series:
path = os.path.join(data_folder, f'{ts_code}.parquet')
if not os.path.exists(path):
raise FileNotFoundError(f'missing price file: {path}')
df = pd.read_parquet(path)
df = _to_dt_index(df)
if col not in df.columns:
raise ValueError(f'{path} missing column: {col}')
return df[col]
# ============================ Backtest engine ============================
def backtest_strategy(entries: pd.Series,
exits: pd.Series,
open_price: pd.Series,
init_cash: float = 1e8,
size_granularity: int = 100,
fees: float = 0.00015,
report_mode: bool = True) -> pd.DataFrame:
"""T-day signal, T+1 open execution; sell first then buy; flat-to-full.
report_mode=True disables fees and lot size.
"""
idx = open_price.index.intersection(entries.index).intersection(exits.index)
if len(idx) < 2:
return pd.DataFrame()
px = open_price.loc[idx]
ent = entries.loc[idx].fillna(False)
ex = exits.loc[idx].fillna(False)
if report_mode:
fees = 0.0
size_granularity = 1
cash_before = init_cash
cash_after = init_cash
position = 0.0
rows = []
for i in range(1, len(idx)):
p = float(px.iloc[i])
e_prev = bool(ent.iloc[i-1])
x_prev = bool(ex.iloc[i-1])
# close first
if x_prev and position > 0:
cash_after += position * p * (1 - fees)
cash_before += position * p
position = 0.0
# open after closing
if e_prev and position == 0:
if report_mode:
shares = cash_after / p
else:
max_shares = int(cash_after // (p * (1 + fees)))
shares = (max_shares // size_granularity) * size_granularity
if shares > 0:
position = float(shares)
cash_after -= shares * p * (1 + fees)
cash_before -= shares * p
pv_b = cash_before + position * p
pv_a = cash_after + position * p
rows.append((idx[i], pv_b, pv_a, cash_before, cash_after, position))
res = pd.DataFrame(rows, columns=['date','portfolio_value_before_fees','portfolio_value_after_fees','cash_before','cash_after','position']).set_index('date')
if len(res):
res['daily_return_before_fees'] = res['portfolio_value_before_fees'].pct_change()
res['daily_return_after_fees'] = res['portfolio_value_after_fees'].pct_change()
res['total_return_before_fees'] = res['portfolio_value_before_fees'] / res['portfolio_value_before_fees'].iloc[0] - 1
res['total_return_after_fees'] = res['portfolio_value_after_fees'] / res['portfolio_value_after_fees'].iloc[0] - 1
return res
def backtest_bond_rotation(entries: pd.Series,
exits: pd.Series,
stock_open: pd.Series,
bond_open: pd.Series,
init_cash: float = 1e8,
size_granularity: int = 100,
fees: float = 0.00015,
report_mode: bool = True) -> pd.DataFrame:
"""Equity–Bond rotation: if prev-day wants equity (entry True and not exit) hold equity; else hold bond."""
idx = stock_open.index.intersection(bond_open.index).intersection(entries.index).intersection(exits.index)
if len(idx) < 2:
return pd.DataFrame()
s_px = stock_open.loc[idx]
b_px = bond_open.loc[idx]
ent = entries.loc[idx].fillna(False)
ex = exits.loc[idx].fillna(False)
if report_mode:
fees = 0.0
size_granularity = 1
cash_before = init_cash
cash_after = init_cash
pos_s = 0.0
pos_b = 0.0
rows = []
for i in range(1, len(idx)):
ps = float(s_px.iloc[i])
pb = float(b_px.iloc[i])
# liquidate existing
if pos_s > 0:
cash_after += pos_s * ps * (1 - fees)
cash_before += pos_s * ps
pos_s = 0.0
if pos_b > 0:
cash_after += pos_b * pb * (1 - fees)
cash_before += pos_b * pb
pos_b = 0.0
want_equity = bool(ent.iloc[i-1]) and not bool(ex.iloc[i-1])
if want_equity:
if report_mode:
shares = cash_after / ps
else:
max_shares = int(cash_after // (ps * (1 + fees)))
shares = (max_shares // size_granularity) * size_granularity
if shares > 0:
pos_s = float(shares)
cash_after -= shares * ps * (1 + fees)
cash_before -= shares * ps
else:
if report_mode:
shares = cash_after / pb
else:
max_shares = int(cash_after // (pb * (1 + fees)))
shares = (max_shares // size_granularity) * size_granularity
if shares > 0:
pos_b = float(shares)
cash_after -= shares * pb * (1 + fees)
cash_before -= shares * pb
pv_b = cash_before + pos_s * ps + pos_b * pb
pv_a = cash_after + pos_s * ps + pos_b * pb
rows.append((idx[i], pv_b, pv_a, cash_before, cash_after, 1 if pos_s > 0 else 0))
res = pd.DataFrame(rows, columns=['date','portfolio_value_before_fees','portfolio_value_after_fees','cash_before','cash_after','position']).set_index('date')
if len(res):
res['daily_return_before_fees'] = res['portfolio_value_before_fees'].pct_change()
res['daily_return_after_fees'] = res['portfolio_value_after_fees'].pct_change()
res['total_return_before_fees'] = res['portfolio_value_before_fees'] / res['portfolio_value_before_fees'].iloc[0] - 1
res['total_return_after_fees'] = res['portfolio_value_after_fees'] / res['portfolio_value_after_fees'].iloc[0] - 1
return res
# ============================ Metrics ============================
def calculate_metrics(result_df: pd.DataFrame) -> Dict[str, float]:
"""计算策略指标:quantstats 标准指标 + 自定义仓位指标"""
if result_df is None or len(result_df) == 0:
return {}
returns = result_df['daily_return_after_fees'].dropna()
if len(returns) == 0:
return {}
# ===== quantstats 标准指标(直接调用,不重复计算)=====
metrics = {
'annual_return': float(qs.stats.cagr(returns)),
'max_drawdown': float(qs.stats.max_drawdown(returns)),
'sharpe': float(qs.stats.sharpe(returns)),
'calmar': float(qs.stats.calmar(returns)),
'daily_win_rate': float(qs.stats.win_rate(returns)),
}
# ===== 自定义指标(quantstats 没有的)=====
# 盈亏比
positive_returns = returns[returns > 0]
negative_returns = returns[returns < 0]
metrics['daily_profit_loss_ratio'] = float(
positive_returns.mean() / abs(negative_returns.mean())
) if len(negative_returns) > 0 and negative_returns.mean() != 0 else 0.0
# 仓位相关指标
position_data = result_df.get('position', pd.Series(0, index=result_df.index))
full_position_returns = returns[position_data > 0]
empty_position_returns = returns[position_data == 0]
metrics['full_position_win_rate'] = float((full_position_returns > 0).mean()) if len(full_position_returns) > 0 else 0.0
metrics['empty_position_win_rate'] = float((empty_position_returns > 0).mean()) if len(empty_position_returns) > 0 else 0.0
metrics['empty_position_ratio'] = float((position_data == 0).sum() / len(position_data)) if len(position_data) > 0 else 0.0
# 交易次数和换手率
trade_signals = result_df.get('trade_signal', pd.Series(0, index=result_df.index))
total_trades = (trade_signals != 0).sum()
total_days = len(result_df)
metrics['total_trades'] = int(total_trades)
metrics['annual_turnover'] = float(total_trades / (total_days / 365.25)) if total_days > 0 else 0.0
metrics['monthly_turnover'] = float(total_trades / (total_days / 30.44)) if total_days > 0 else 0.0
metrics['avg_holding_days'] = float(total_days / total_trades) if total_trades > 0 else 0.0
return metrics
# ============================ Report-style plotting ============================
def _plot_report(returns: pd.Series, benchmark_returns: pd.Series, title: str, outpath: str) -> None:
"""策略对比图表:净值曲线 + 从上往下的半透明绿色回撤区域"""
if returns is None or len(returns) < 2:
return
os.makedirs(os.path.dirname(outpath) or '.', exist_ok=True)
# 计算累积收益
cum = (1 + returns).cumprod()
bench = benchmark_returns if benchmark_returns is not None and len(benchmark_returns) > 0 else None
# 回撤负值 -> 幅度正数
dd = qs.stats.to_drawdown_series(returns).fillna(0)
dd_mag = (-dd).clip(lower=0) # 正数
# 创建图表
fig, ax1 = plt.subplots(figsize=(16, 8))
# 先画累计收益线(黑色)
ax1.plot(cum.index, cum.values, linewidth=2.0, color='#FF0000', label='Strategy', zorder=3)
# 基准可选(深灰)
if bench is not None:
cum_bench = (1 + bench).cumprod()
ax1.plot(cum_bench.index, cum_bench.values, linewidth=1.4, color='#777777', label='Benchmark', zorder=2)
ax1.set_ylabel('Net Asset Value', fontsize=12)
ax1.set_xlabel('Date', fontsize=12)
ax1.grid(True, alpha=0.3, zorder=0)
# 右轴:回撤用半透明绿色
ax2 = ax1.twinx()
ax1.set_zorder(ax2.get_zorder() + 1)
ax1.patch.set_visible(False)
# 关键:绿色 + 透明度
ax2.fill_between(
dd_mag.index, 0, dd_mag.values * 100,
facecolor=(0.0, 0.55, 0.0, 0.35), # 深绿,35%透明
edgecolor='none',
zorder=1
)
# 让回撤从上往下灌
hi = dd_mag.max() * 100
ax2.set_ylim(hi * 1.05, 0)
ax2.set_ylabel('Drawdown (%)', fontsize=12)
ax2.yaxis.set_major_formatter(PercentFormatter(xmax=100))
# 标题
ax1.set_title(title, fontsize=16, pad=20)
# 图例:给回撤补一个绿色块
handles, labels = ax1.get_legend_handles_labels()
handles.append(mpatches.Patch(facecolor=(0.0, 0.55, 0.0, 0.35), edgecolor='none', label='Drawdown'))
ax1.legend(handles=handles, loc='upper left', frameon=False, fontsize=11)
plt.tight_layout()
plt.savefig(outpath, dpi=100, bbox_inches='tight')
plt.close()
def plot_reports_for_results(results: Dict[str, dict], bench_close: pd.Series, ts_code: str, out_dir: str) -> Dict[str, str]:
"""为每个策略生成对比报告图表"""
out = {}
order = [
('1_Alligator', '1. Alligator'),
('B_Alligator_AO', '2. Alligator + AO'),
('C_Alligator_Fractal', '3. Alligator + Fractal'),
('D_Alligator_AO_Fractal', '4. Alligator + AO + Fractal'),
('E_Alligator_AO_Fractal_MACD', '5. Alligator + AO + Fractal + MACD'),
('E_Bond_Rotation', '6. Equity–Bond Rotation'),
]
# 计算基准收益率
bench_returns = bench_close.pct_change().dropna()
for key, ttl in order:
if key not in results or 'result_df' not in results[key] or results[key]['result_df'] is None or len(results[key]['result_df']) == 0:
continue
res_df = results[key]['result_df']
strategy_returns = res_df['daily_return_after_fees'].dropna()
if len(strategy_returns) < 2:
continue
# 对齐基准收益率
aligned_bench_returns = bench_returns.reindex(strategy_returns.index).fillna(0)
# 将图表保存到各自的资产文件夹中
f = f'{out_dir}/{ts_code}/report_{key}.png'
_plot_report(strategy_returns, aligned_bench_returns, f'{ts_code} — {ttl}', f)
out[key] = f
return out
# ============================ Orchestrator ============================
def run_staged_backtest(ts_code: str = '000300.SH',
signal_folder: str = signal_dir,
factor_folder: str = factor_dir,
data_folder: str = data_dir,
report_mode: bool = True,
report_folder: str = report_dir,
backtest_start_date: Optional[str] = None,
backtest_end_date: Optional[str] = None,
bond_code: str = 'CBA00101.CS') -> Dict[str, dict]:
sig = read_split_signals(signal_dir, ts_code)
if sig is None:
raise FileNotFoundError('missing split signals; run strategy.py first')
open_px = read_price_series(data_folder, ts_code, col='open')
close_px = read_price_series(data_folder, ts_code, col='close')
# clip window
if backtest_start_date is not None:
dt0 = pd.to_datetime(backtest_start_date)
open_px = open_px[open_px.index >= dt0]
close_px = close_px[close_px.index >= dt0]
sig = sig[sig.index >= dt0]
if backtest_end_date is not None:
dt1 = pd.to_datetime(backtest_end_date)
open_px = open_px[open_px.index <= dt1]
close_px = close_px[close_px.index <= dt1]
sig = sig[sig.index <= dt1]
idx = open_px.index.intersection(sig.index)
if len(idx) < 2:
raise RuntimeError('not enough overlapping dates for backtest')
px = open_px.loc[idx]
sig = sig.loc[idx].fillna(False)
# 策略配置:避免重复代码
strategies = [
('1_Alligator', sig['sig_alligator_long'], sig['sig_alligator_short']),
('B_Alligator_AO', sig['sig_alligator_long'] & sig['sig_ao_long'], sig['sig_alligator_short'] | sig['sig_ao_short']),
('C_Alligator_Fractal', sig['sig_alligator_long'] & sig['sig_fractal_long'], sig['sig_alligator_short'] | sig['sig_fractal_short']),
('D_Alligator_AO_Fractal', sig['sig_alligator_long'] & sig['sig_ao_long'] & sig['sig_fractal_long'], sig['sig_alligator_short'] | sig['sig_ao_short'] | sig['sig_fractal_short']),
('E_Alligator_AO_Fractal_MACD', sig['sig_combo_long'], sig['sig_combo_short']),
]
results: Dict[str, dict] = {}
for key, entries, exits in strategies:
res = backtest_strategy(entries.astype(bool), exits.astype(bool), px, report_mode=report_mode)
if 'trade_signal' in sig.columns and 'position' in sig.columns:
res['trade_signal'] = sig['trade_signal']
res['position'] = sig['position']
results[key] = {'result_df': res}
# Bond rotation strategy (Equity–Bond)
try:
bond_open = read_price_series(data_folder, bond_code, col='open')
if bond_open.isna().all():
bond_open = read_price_series(data_folder, bond_code, col='close')
idx2 = px.index.intersection(bond_open.index)
if len(idx2) >= 2:
rot = backtest_bond_rotation(
sig['sig_combo_long'].reindex(idx2).fillna(False),
sig['sig_combo_short'].reindex(idx2).fillna(False),
px.reindex(idx2),
bond_open.reindex(idx2),
report_mode=report_mode
)
if 'trade_signal' in sig.columns and 'position' in sig.columns:
rot['trade_signal'] = sig['trade_signal'].reindex(idx2)
rot['position'] = sig['position'].reindex(idx2)
results['E_Bond_Rotation'] = {'result_df': rot}
except Exception as e:
print(f'[warn] Bond rotation skipped: {e}')
# plot report-only charts
plot_reports_for_results(results, bench_close=close_px, ts_code=ts_code, out_dir = report_folder)
return results
def save_results_to_csv(results: Dict[str, dict], ts_code: str, output_folder: str = report_dir) -> pd.DataFrame:
"""保存策略对比结果到CSV文件"""
name_map = {
'1_Alligator': '1. Alligator',
'B_Alligator_AO': '2. Alligator + AO',
'C_Alligator_Fractal': '3. Alligator + Fractal',
'D_Alligator_AO_Fractal': '4. Alligator + AO + Fractal',
'E_Alligator_AO_Fractal_MACD': '5. Alligator + AO + Fractal + MACD',
'E_Bond_Rotation': '6. Equity–Bond Rotation',
}
# 计算所有策略的指标
data = {}
for k, v in results.items():
if 'result_df' in v and v['result_df'] is not None and len(v['result_df']) > 0:
data[name_map.get(k, k)] = calculate_metrics(v['result_df'])
df = pd.DataFrame(data).T
# 保存到文件
asset_folder = os.path.join(output_folder, ts_code)
os.makedirs(asset_folder, exist_ok=True)
out = os.path.join(asset_folder, f'{ts_code}_strategies_comparison.csv')
df.to_csv(out)
print(f'Metrics saved: {out}')
return df
def run_all(ts_codes: list[str],
report_mode: bool = True,
strategy_start_date: Optional[str] = None,
strategy_end_date: Optional[str] = None,
bond_code: str = 'CBA00101.CS') -> None:
"""运行所有标的的回测分析"""
print('Starting staged backtests with quantstats...')
for code in ts_codes:
print(f'\nSymbol: {code}')
res = run_staged_backtest(
ts_code=code,
report_mode=report_mode,
backtest_start_date=strategy_start_date,
backtest_end_date=strategy_end_date,
bond_code=bond_code
)
if res:
save_results_to_csv(res, ts_code=code)
print('\nDone.')
run_all(report_mode=True, ts_codes = universe)
|