Copy from QUANTAXIS.QAStrategy import QAStrategyCtaBase
import QUANTAXIS as QA
class DualMAStrategy(QAStrategyCtaBase):
"""双均线CTA策略
策略逻辑:
- 快线上穿慢线:买入开仓
- 快线下穿慢线:卖出平仓
- 设置固定止损止盈
"""
def user_init(self):
"""初始化策略参数"""
# 均线参数
self.fast_period = 5
self.slow_period = 20
# 风控参数
self.stop_loss_pct = 0.02 # 止损2%
self.take_profit_pct = 0.05 # 止盈5%
# 仓位管理
self.max_position = 5 # 最大持仓手数
self.position_size = 1 # 每次开仓手数
# 状态变量
self.entry_price = 0 # 入场价格
self.is_long = False # 是否持有多单
print(f"策略初始化完成: 快线{self.fast_period}, 慢线{self.slow_period}")
def on_bar(self, bar):
"""K线更新回调"""
# 1. 获取市场数据
market_data = self.get_code_marketdata(bar.code)
if len(market_data) < self.slow_period:
return # 数据不足,跳过
# 2. 计算技术指标
close_prices = [x['close'] for x in market_data]
ma_fast = QA.MA(close_prices, self.fast_period)
ma_slow = QA.MA(close_prices, self.slow_period)
# 3. 获取当前持仓
positions = self.acc.positions
current_pos = positions.get(bar.code, None)
# 4. 生成交易信号
if len(ma_fast) >= 2 and len(ma_slow) >= 2:
# 金叉信号
if ma_fast[-2] <= ma_slow[-2] and ma_fast[-1] > ma_slow[-1]:
if current_pos is None or current_pos.volume_long == 0:
# 无持仓,开仓
self.BuyOpen(bar.code, self.position_size)
self.entry_price = bar.close
self.is_long = True
print(f"[{bar.datetime}] 金叉买入开仓 @ {bar.close:.2f}")
# 死叉信号
elif ma_fast[-2] >= ma_slow[-2] and ma_fast[-1] < ma_slow[-1]:
if current_pos and current_pos.volume_long > 0:
# 有持仓,平仓
self.SellClose(bar.code, current_pos.volume_long)
self.is_long = False
print(f"[{bar.datetime}] 死叉卖出平仓 @ {bar.close:.2f}")
# 5. 风险控制
if current_pos and current_pos.volume_long > 0 and self.entry_price > 0:
# 计算盈亏比例
pnl_pct = (bar.close - self.entry_price) / self.entry_price
# 止损
if pnl_pct <= -self.stop_loss_pct:
self.SellClose(bar.code, current_pos.volume_long)
self.is_long = False
print(f"[{bar.datetime}] 止损平仓 @ {bar.close:.2f}, 亏损{pnl_pct*100:.2f}%")
# 止盈
elif pnl_pct >= self.take_profit_pct:
self.SellClose(bar.code, current_pos.volume_long)
self.is_long = False
print(f"[{bar.datetime}] 止盈平仓 @ {bar.close:.2f}, 盈利{pnl_pct*100:.2f}%")
def on_dailyclose(self):
"""每日收盘回调"""
# 输出每日统计信息
print(f"[日终] 权益: {self.acc.balance:.2f}, 可用: {self.acc.cash_available:.2f}")
def on_dailyopen(self):
"""每日开盘回调"""
print(f"[开盘] 新的交易日开始")
# 运行策略
if __name__ == '__main__':
strategy = DualMAStrategy(
code='rb2501',
frequence='5min',
strategy_id='dual_ma_cta',
start='2024-01-01',
end='2024-12-31',
init_cash=1000000,
)
strategy.run_backtest()