BigQuant使用文档

均线突破策略-期货分钟

由iquant创建,最终由iquant 被浏览 21 用户

策略介绍

本策略是均线突破策略的期货分钟实现,通过计算均线值,并与最新价比较来进行建仓。

策略流程

  1. 筛选条件:计算均线值,如果最新价向上突破均线,建立多头仓位;如果最新价向下突破均线,建立空头仓位。
  2. 策略回测:回测时间为2024-05-01 09:00:00至2024-06-01 15:15:00。

策略实现

输入特征模块

  • 计算此刻的均线值:m_ta_sma(close, 63) AS ma ;上一时刻的均线值: m_lag(ma, 1) AS ma_1
  • 过滤条件中进行期货合约的筛选:instrument in ('b2412.DCE', 'bb2412.DCE','AP412.CZC','jd2412.DCE','jm2412.DCE','fu2412.SHF','bu2412.SHF','TS2412.CFE', 'UR412.CZC', 'ZC412.CZC', 'ag2412.SHF', 'al2412.SHF')

数据抽取模块

  • 将数据抽取出来,在这当中设置起始时间为2024-05-01 09:00:00,结束时间为2024-06-01 15:15:00。

BigTrader模块

  • m3”BigTrader“模块中,实现交易逻辑,依据条件进行买卖。
  • K线处理函数
# 交易引擎:bar数据处理函数,每个时间单位执行一次
def bigquant_run(context, data):
    import pandas as pd 
    from bigtrader.constant  import Direction 
    from bigtrader.constant  import OrderType
    #获取当前时间
    cur_date =  data.current_dt.strftime('%Y-%m-%d %H:%M:%S')
    now_data = context.data[context.data.date==cur_date]
    if len(now_data)==0:
        return
    for instr in context.ins:
        
        long_position = context.get_account_position(instr, direction=Direction.LONG).avail_qty#多头持仓
        short_position = context.get_account_position(instr, direction=Direction.SHORT).avail_qty#空头持仓
        
        in_data = now_data[now_data['instrument']==instr]
        if(len(in_data)==0):
            return
        # 最新价格
        price = in_data['close'].values[0]
        # 均线
        ma = in_data['ma'].values[0]
        # 前一分钟均线/价格
        ma_1 = in_data['ma_1'].values[0]
        price_1 = in_data['close_1'].values[0]
 
        #价格向上穿越20均线
        if ma < price and ma_1 > price_1:
            #有空单的先平掉
            if short_position > 0:
                rv = context.buy_close(instr, short_position, price, order_type=OrderType.MARKET)
                msg = "{} 平空 for {}  最新价={} 下单函数返回={}".format(cur_date,instr,str(price),str(rv))
                context.write_log(msg, stdout=0)
            #没有多单则开多1手
            if long_position == 0:
                rv = context.buy_open(instr, 1, price, order_type=OrderType.MARKET)
                msg = "{} 开多 for {}  最新价={} 下单函数返回={}".format(cur_date,instr,str(price),str(rv))
                context.write_log(msg, stdout=0) 
        #价格向下穿越20均线
        if ma > price and ma_1 < price_1:
            #有多单的先平掉
            if long_position > 0:
                rv = context.sell_close(instr, long_position, price, order_type=OrderType.MARKET)
                msg = "{} 平多 for {}  最新价={} 下单函数返回={}".format(cur_date,instr,str(price),str(rv))
                context.write_log(msg, stdout=0)
            #没有空单则开空1手    
            if short_position == 0:
                rv = context.sell_open(instr, 1, price, order_type=OrderType.MARKET)
                msg = "{} 开空 for {}  最新价={} 下单函数返回={}".format(cur_date,instr,str(price),str(rv))
                context.write_log(msg, stdout=0)   

策略源码

https://bigquant.com/codesharev2/dae16e91-5c92-4b47-8338-db6de1e96208

\

{link}