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
|
""" 农业银行量化交易策略 V3版本 作者:GWB 创建时间:2024-11-11 """
from __future__ import print_function import backtrader as bt import pandas as pd import numpy as np from datetime import datetime import argparse
class AgriculturalBankStrategyV3(bt.Strategy): """ 农业银行量化交易策略 V3版本 核心特性:完整的止盈止损体系 + 移动止盈机制 """
params = ( ('ma3_period', 2), ('ma5_period', 5), ('ma10_period', 10), ('ma60_period', 60),
('first_profit_target', 0.10), ('protection_profit_target', 0.08), ('mobile_profit_start', 0.15), ('mobile_retracement', 0.05), ('stop_loss_pct', -0.02),
('printlog', True), ('initial_size', 0.95), )
def __init__(self): self.ma3 = bt.indicators.SMA(self.data.close, period=self.params.ma3_period) self.ma5 = bt.indicators.SMA(self.data.close, period=self.params.ma5_period) self.ma10 = bt.indicators.SMA(self.data.close, period=self.params.ma10_period) self.ma60 = bt.indicators.SMA(self.data.close, period=self.params.ma60_period)
self.position_info = { 'entry_price': 0, 'half_sold': False, 'highest_price': 0, 'mobile_stop_price': 0, 'mobile_stop_active': False, }
self.trades = 0 self.wins = 0
def log(self, txt, dt=None): if self.params.printlog: dt = dt or self.datas[0].datetime.date(0) price = float(self.data.close[0]) print(f'{dt.isoformat()} 价格:{price:.2f} {txt}')
def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: return
if order.status in [order.Completed]: if order.isbuy(): self.position_info['entry_price'] = order.executed.price self.position_info['half_sold'] = False self.position_info['highest_price'] = order.executed.price self.position_info['mobile_stop_active'] = False self.trades += 1 profit_pct = (self.data.close[0] - order.executed.price) / order.executed.price self.log(f'🚀 买入 - 价格:{order.executed.price:.2f} 数量:{order.executed.size}')
elif order.issell(): if self.position_info['entry_price'] > 0: profit_pct = (order.executed.price - self.position_info['entry_price']) / self.position_info['entry_price'] if profit_pct > 0: self.wins += 1 self.log(f'💰 卖出 - 价格:{order.executed.price:.2f} 数量:{order.executed.size} 总盈亏:{profit_pct:+.2%}')
if not self.position: self.position_info = { 'entry_price': 0, 'half_sold': False, 'highest_price': 0, 'mobile_stop_price': 0, 'mobile_stop_active': False, }
def check_buy_signal(self): if len(self) < self.params.ma60_period: return False
ma5 = float(self.ma5[0]) ma10 = float(self.ma10[0]) ma3_current = float(self.ma3[0]) ma3_prev = float(self.ma3[-2]) if len(self) > 1 else ma3_current ma60_current = float(self.ma60[0]) ma60_prev = float(self.ma60[-2]) if len(self) > 1 else ma60_current
condition1 = ma5 > ma10 condition2 = (ma3_prev < ma60_prev) and (ma3_current > ma60_current)
return condition1 and condition2
def check_sell_signal(self): if len(self) < self.params.ma10_period: return False
ma5 = float(self.ma5[0]) ma10 = float(self.ma10[0]) ma_diff_pct = (ma5 - ma10) / ma10
return ma_diff_pct < -0.02
def process_mobile_stop_loss(self, current_price, profit_pct): if profit_pct >= self.params.mobile_profit_start: if current_price > self.position_info['highest_price']: self.position_info['highest_price'] = current_price
mobile_stop_price = self.position_info['highest_price'] * (1 - self.params.mobile_retracement) self.position_info['mobile_stop_price'] = mobile_stop_price self.position_info['mobile_stop_active'] = True
self.log(f'📊 移动止盈监控中: 最高价{self.position_info["highest_price"]:.2f} 止盈线{mobile_stop_price:.2f}')
if (self.position_info['mobile_stop_active'] and current_price < self.position_info['mobile_stop_price']): retracement_amt = (self.position_info['highest_price'] - current_price) / self.position_info['highest_price'] return 'mobile_stop', { 'reason': f'移动止盈触发:从最高价回撤{retracement_amt:.1%}超过{self.params.mobile_retracement:.0%}', 'profit_pct': profit_pct }
return None
def check_all_exit_conditions(self): if not self.position or self.position_info['entry_price'] == 0: return None, {}
current_price = float(self.data.close[0]) entry_price = self.position_info['entry_price'] profit_pct = (current_price - entry_price) / entry_price
if profit_pct <= self.params.stop_loss_pct: return 'stop_loss', { 'reason': f'🛑 硬止损:亏损{abs(profit_pct):.1%}超过{abs(self.params.stop_loss_pct):.0%}', 'profit_pct': profit_pct }
if profit_pct >= self.params.first_profit_target and not self.position_info['half_sold']: return 'take_profit_half', { 'reason': f'💰 第一层止盈:上涨{profit_pct:.1%}达到{self.params.first_profit_target:.0%}', 'profit_pct': profit_pct }
if self.position_info['half_sold']: if profit_pct < self.params.protection_profit_target: return 'protection_stop', { 'reason': f'🛡️ 保护止盈:涨幅回撤至{profit_pct:.1%}低于{self.params.protection_profit_target:.0%}', 'profit_pct': profit_pct }
mobile_result = self.process_mobile_stop_loss(current_price, profit_pct) if mobile_result: return mobile_result
if self.check_sell_signal(): ma5_val = float(self.ma5[0]) ma10_val = float(self.ma10[0]) ma_diff_pct = (ma5_val - ma10_val) / ma10_val * 100 return 'technical_sell', { 'reason': f'📉 技术卖出:MA5({ma5_val:.2f})与MA10({ma10_val:.2f})差值{ma_diff_pct:.1f}% < -2%', 'profit_pct': profit_pct }
return None, {}
def next(self): current_price = float(self.data.close[0])
if self.position: exit_condition, exit_info = self.check_all_exit_conditions()
if exit_condition: if exit_condition == 'stop_loss': self.close() self.log(exit_info['reason']) elif exit_condition == 'take_profit_half': sell_size = int(self.position.size / 2) if sell_size > 0: self.sell(size=sell_size) self.position_info['half_sold'] = True self.log(exit_info['reason']) elif exit_condition == 'protection_stop': self.close() self.log(exit_info['reason']) elif exit_condition == 'mobile_stop': self.close() self.log(exit_info['reason']) elif exit_condition == 'technical_sell': self.close() self.log(exit_info['reason']) return
if not self.position and self.check_buy_signal(): cash = self.broker.cash size = int(cash * self.params.initial_size / current_price) if size > 0: self.buy(size=size) self.log(f'🚀 买入信号:MA5>MA10且MA3上穿MA60,数量:{size}')
def get_data_from_akshare(ticker='601288', start_date='2022-01-01', end_date='2025-11-10'): try: import akshare as ak print(f"从AKShare获取 {ticker} 数据...")
start_date_fmt = start_date.replace('-', '') end_date_fmt = end_date.replace('-', '')
data = ak.stock_zh_a_hist(symbol=ticker, period="daily", start_date=start_date_fmt, end_date=end_date_fmt)
if not data.empty: bt_data = data[['日期', '开盘', '最高', '最低', '收盘', '成交量']].copy() bt_data.columns = ['date', 'open', 'high', 'low', 'close', 'volume'] bt_data['date'] = pd.to_datetime(bt_data['date']) bt_data.set_index('date', inplace=True)
print(f"✅ 成功获取AKShare数据: {len(bt_data)} 条记录") print(f"📅 数据范围: {bt_data.index[0].date()} 到 {bt_data.index[-1].date()}") print(f"💰 价格范围: ¥{bt_data['close'].min():.2f} - ¥{bt_data['close'].max():.2f}") return bt_data except Exception as e: print(f"❌ AKShare获取失败: {e}") return None
def run_backtest(): print("=" * 80) print("农业银行量化交易策略回测(V3版本)") print("=" * 80)
data = get_data_from_akshare('601288', '2022-01-01', '2025-11-10')
if data is None: print("❌ 数据获取失败") return
cerebro = bt.Cerebro() cerebro.addstrategy(AgriculturalBankStrategyV3)
bt_data = bt.feeds.PandasData(dataname=data) cerebro.adddata(bt_data)
cerebro.broker.setcash(100000) cerebro.broker.setcommission(commission=0.0003)
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown') cerebro.addanalyzer(bt.analyzers.Returns, _name='returns') cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trades')
start_value = cerebro.broker.getvalue() print(f"开始回测,初始资金: ¥{start_value:,.2f}") print("-" * 80)
results = cerebro.run() strategy = results[0]
final_value = cerebro.broker.getvalue() total_return = (final_value - start_value) / start_value * 100
print("-" * 80) print("📈 回测结果:") print(f"初始资金: ¥{start_value:,.2f}") print(f"最终资金: ¥{final_value:,.2f}") print(f"收益率: {total_return:+.2f}%") print(f"交易次数: {strategy.trades}") print(f"盈利次数: {strategy.wins}")
if strategy.trades > 0: win_rate = strategy.wins / strategy.trades * 100 print(f"胜率: {win_rate:.1f}%")
try: dd = strategy.analyzers.drawdown.get_analysis() if 'max' in dd: print(f"最大回撤: {dd['max']['drawdown']:.2f}%") except: pass
print("=" * 80)
try: cerebro.plot(style='candlestick', barup='red', bardown='green', title='农业银行V3策略回测结果', figsize=(15, 8)) except Exception as e: print(f"⚠️ 图表生成失败: {e}")
if __name__ == '__main__': run_backtest()
|