AI改了个布林策略

用户头像sh_****0851af
2025-06-08 发布

初始化函数,全局只运行一次

def init(context):

设立商品期货子账户,其中stock为0,future为100000

set_subportfolios([{"cash": 0, "type": 'stock'}, {"cash": 100000, "type": "future"}])

打印日志

log.info('策略开始运行,初始化函数全局只运行一次')

设置期货每笔交易的手续费为十万分之四十五(按成交额计算并扣除,期货交易不需要缴纳税费)

set_commission(PerShare(type='future', cost=0.000045))

设置期货交易滑点0.5%,表示买入价为实际价格乘1.005,卖出价为实际价格乘0.995

set_slippage(PriceSlippage(0.005), 'future')

设置期货保证金,RB为螺纹钢,第一个参数做多保证金8%,第二个参数做空保证金9%

set_margin_rate('RB', 0.08, 0.09)

设置日级最大成交比例25%,分钟级最大成交比例50%

set_volume_limit(0.25, 0.5)

设置需要交易的标的,螺纹钢

context.ins = 'RB9999'

螺纹钢主连作为基准

set_benchmark(context.ins)

订阅需要交易的期货品种

subscribe(context.ins)

每日开盘前被调用一次,用于储存自定义参数、全局变量等

def before_trading(context):

获取日期

date = get_datetime().strftime('%Y-%m-%d %H:%M:%S')

打印日期

log.info('{} 盘前运行'.format(date))

每根K线运行函数

def handle_bar(context, bar_dict):

获取时间

time = get_datetime().strftime('%Y%m%d %H%M')

打印时间

log.info('{} 盘中运行'.format(time))

获取螺纹钢的合约代码

g.con = get_futures_dominate('RB')

获取合约行情数据

hist = get_price_future(g.con, None, time, '1d', ['close'], bar_count=20) # 获取过去20天的收盘价数据

计算布林线指标

mid = hist['close'].mean() # 中轨:过去20天收盘价的平均值
std = hist['close'].std() # 标准差
up = mid + 2 * std # 上轨:中轨 + 2倍标准差
down = mid - 2 * std # 下轨:中轨 - 2倍标准差

获取当前价格

current_price = bar_dict[context.ins].close

获取当前账户的螺纹空单数量

short_amount = context.portfolio.future_account.positions[context.ins].short_amount

获取当前账户的螺纹多单数量

long_amount = context.portfolio.future_account.positions[context.ins].long_amount

判断条件

if current_price > up and long_amount == 0: # 当前价格超过上轨且无多单
# 开多
order_future(context.ins, 20, 'open', 'long', None)
# 打印日志
log.info('价格超过上轨,开多 %s' % (context.ins))
elif current_price < down and short_amount == 0: # 当前价格低于下轨且无空单
# 开空
order_future(context.ins, 20, 'open', 'short', None)
# 打印日志
log.info('价格低于下轨,开空 %s' % (context.ins))
elif current_price < mid and long_amount > 0: # 当前价格低于中轨且有多单
# 平多
order_future(context.ins, long_amount, 'close', 'long', None)
# 打印日志
log.info('价格低于中轨,平多 %s' % (context.ins))
elif current_price > mid and short_amount > 0: # 当前价格高于中轨且有空单
# 平空
order_future(context.ins, short_amount, 'close', 'short', None)
# 打印日志
log.info('价格高于中轨,平空 %s' % (context.ins))

收盘后运行函数

def after_trading(context):

获取时间

time = get_datetime().strftime('%Y-%m-%d %H:%M:%S')

打印时间

log.info('{} 盘后运行'.format(time))
log.info('一天结束')

评论