19年创业做过一年的量化交易但没有成功,作为交易系统的开发人员积累了一些经验,最近想重新研究交易系统,一边整理一边写出来一些思考供大家参考,也希望跟做量化的朋友有更多的交流和合作。
接下来会对于聚宽量化/JoinQuant平台介绍。
聚宽量化(JoinQuant)是一款功能强大的量化交易平台,提供了从策略开发、回测到实盘交易的一站式解决方案。聚宽平台支持Python编程,内置丰富的数据接口与回测工具,可以快速验证量化交易策略的有效性。
本文以经典的“双均线策略”为例,展示如何在聚宽平台上进行策略开发、回测及优化。
1. 策略背景:双均线交叉策略
策略逻辑
双均线交叉策略是一种趋势型策略,旨在捕捉市场的中短期趋势。
- 买入信号:当短期均线(如5日均线)上穿长期均线(如20日均线)时,买入标的。
- 卖出信号:当短期均线下穿长期均线时,卖出标的。
优点:逻辑简单,适用范围广。
缺点:在震荡市中可能产生较多虚假信号。
2. 环境准备
(1)注册与登录
用户需在聚宽官网注册账户,并登录在线开发环境。平台提供免费的开发和回测工具,无需本地安装。
(2)创建策略
在聚宽平台的策略研究页面,点击“新建策略”,进入策略编辑器。
3. 策略开发
(1)初始化函数
initialize
函数用于设置策略的基本参数和运行环境。
def initialize(context):
context.s1 = '000001.XSHE' # 标的代码:平安银行
context.short_window = 5 # 短期均线窗口
context.long_window = 20 # 长期均线窗口
context.max_cash_ratio = 0.95 # 最大仓位比例
log.info("策略初始化完成")
(2)生成信号与调仓
handle_data
函数用于定义每个时间点的操作逻辑。
def handle_data(context, data):
# 获取历史数据
hist = attribute_history(context.s1, context.long_window + 1, '1d', ['close'])
# 计算短期和长期均线
short_ma = hist['close'].rolling(window=context.short_window).mean().iloc[-1]
long_ma = hist['close'].rolling(window=context.long_window).mean().iloc[-1]
# 当前持仓
current_position = context.portfolio.positions[context.s1].total_amount
# 买入逻辑:短期均线上穿长期均线
if short_ma > long_ma and current_position == 0:
order_target_percent(context.s1, context.max_cash_ratio) # 买入满仓
log.info(f"买入信号触发:{context.s1},短期均线={short_ma}, 长期均线={long_ma}")
# 卖出逻辑:短期均线下穿长期均线
elif short_ma < long_ma and current_position > 0:
order_target_percent(context.s1, 0) # 清仓
log.info(f"卖出信号触发:{context.s1},短期均线={short_ma}, 长期均线={long_ma}")
4. 回测
(1)设置回测参数
回测设置通过聚宽提供的参数面板或代码配置完成。
set_benchmark('000300.XSHG') # 设置基准为沪深300指数
set_commission(0.0002) # 设置交易手续费为0.02%
set_slippage(0.002) # 设置滑点为0.2%
(2)运行回测
在聚宽的策略研究页面点击“运行回测”,即可查看策略的收益表现和交易记录。
5. 回测结果分析
聚宽平台提供丰富的回测结果,包括:
- 收益率曲线:展示策略收益与基准收益的对比。
- 绩效指标:年化收益率、最大回撤、夏普比率等。
- 交易详情:每笔交易的买卖时间、价格和数量。
6. 策略优化
(1)参数优化
通过参数网格搜索优化短期和长期均线的窗口长度。
def optimize_parameters(context):
best_params = None
best_performance = -float('inf')
for short in range(3, 10):
for long in range(15, 30):
if short >= long:
continue
# 更新策略参数
context.short_window = short
context.long_window = long
# 模拟回测
performance = run_backtest(context) # 自定义回测函数返回收益率等指标
if performance['annual_return'] > best_performance:
best_performance = performance['annual_return']
best_params = (short, long)
log.info(f"最佳参数:短期均线={best_params[0]}, 长期均线={best_params[1]}")
(2)加入风险管理
为策略加入止盈止损机制,增强稳健性。
def handle_data_with_risk_control(context, data):
# 获取历史数据
hist = attribute_history(context.s1, context.long_window + 1, '1d', ['close'])
# 计算均线
short_ma = hist['close'].rolling(window=context.short_window).mean().iloc[-1]
long_ma = hist['close'].rolling(window=context.long_window).mean().iloc[-1]
# 当前持仓信息
current_position = context.portfolio.positions[context.s1]
current_price = data[context.s1].close
# 止盈止损
if current_position.total_amount > 0:
entry_price = current_position.cost_basis
profit_ratio = (current_price - entry_price) / entry_price
if profit_ratio > 0.1 or profit_ratio < -0.05:
order_target_percent(context.s1, 0) # 平仓
log.info("触发止盈或止损,清仓")
# 原有买卖逻辑
if short_ma > long_ma and current_position.total_amount == 0:
order_target_percent(context.s1, context.max_cash_ratio)
elif short_ma < long_ma and current_position.total_amount > 0:
order_target_percent(context.s1, 0)
7. 实盘部署
聚宽支持从回测到实盘的无缝衔接,用户可直接将策略部署到实盘账户:
- 上线策略:将验证完成的策略上传到策略库。
- 绑定账户:绑定模拟账户或实盘账户。
- 启动交易:开启策略后,平台会自动监控市场并执行交易。