3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
网格交易(Grid Trading)是一种利用行情震荡进行逢低买入、逢高卖出的量化交易策略。在震荡市中,网格交易能够通过反复低吸高抛获取稳定的波动收益。本文将为您提供一个在 ptrade 平台上运行的经典网格交易策略 Python 源码。
handle_data 中实时监控最新价格,计算当前价格所处的网格层级。以下是完整的 Python 策略代码,可直接在 ptrade 的回测或交易环境中使用:
# -*- coding: utf-8 -*-
def initialize(context):
# 1. 设置操作的标的(以恒生电子为例)
g.security = '600570.SS'
set_universe(g.security)
# 2. 初始化网格参数
g.base_price = 40.0 # 网格基准价格(可根据实际情况调整)
g.grid_percent = 0.02 # 网格间距(2%)
g.trade_amount = 100 # 每档交易数量(100股)
g.grid_levels = 5 # 向上/向下最大网格层数
g.last_grid = 0 # 记录上一次价格所处的网格层级
log.info("网格交易策略初始化完成,基准价: %s, 步长: %s" % (g.base_price, g.grid_percent))
def handle_data(context, data):
security = g.security
# 获取当前周期的收盘价
current_price = data[security]['close']
# 计算当前价格相对于基准价格偏离了多少个网格步长
current_grid = int((current_price - g.base_price) / (g.base_price * g.grid_percent))
# 限制网格层级在设定的最大层数范围内
if current_grid > g.grid_levels:
current_grid = g.grid_levels
elif current_grid < -g.grid_levels:
current_grid = -g.grid_levels
# 获取当前持仓信息
position = get_position(security)
hold_amount = position.amount if position else 0
# 逻辑判断:价格下跌,网格层级降低,触发买入
if current_grid < g.last_grid:
diff = g.last_grid - current_grid
buy_amount = g.trade_amount * diff
# 检查可用资金是否足够
if context.portfolio.cash >= buy_amount * current_price:
order(security, buy_amount)
log.info("【买入】当前价格: %s, 网格由 %s 降至 %s, 买入 %s 股" %
(current_price, g.last_grid, current_grid, buy_amount))
g.last_grid = current_grid
else:
log.warning("资金不足,无法执行买入!")
# 逻辑判断:价格上涨,网格层级升高,触发卖出
elif current_grid > g.last_grid:
if hold_amount > 0:
diff = current_grid - g.last_grid
# 卖出数量不能超过当前持仓量
sell_amount = min(g.trade_amount * diff, hold_amount)
order(security, -sell_amount)
log.info("【卖出】当前价格: %s, 网格由 %s 升至 %s, 卖出 %s 股" %
(current_price, g.last_grid, current_grid, sell_amount))
g.last_grid = current_grid
set_universe(security_list):设置策略订阅的股票池,确保能获取到对应的行情数据。get_position(security):实时获取当前标的的持仓对象,通过 .amount 属性获取总持仓,避免超卖废单。order(security, amount):ptrade 核心下单接口。amount 为正数代表买入,负数代表卖出。g.trade_amount 设置符合交易所规则。