复制链接
克隆策略

策略名称

菲阿里四价策略-期货分钟

策略逻辑

菲阿里四价指的是:昨日高点、昨日低点、昨天收盘、今天开盘四个价格。 菲阿里四价上下轨的计算非常简单。昨日高点为上轨,昨日低点为下轨。当价格突破上轨时,买入开仓;当价格突破下轨时,卖出开仓。

In [5]:
# 导入相应包
from biglearning.api import M
import math 
from bigtrader.sdk import *
import pandas as pd
import warnings
warnings.filterwarnings('ignore')

def initialize(context):
    """策略初始化函数,只触发一次。可以在该函数中初始化一些变量,如读取配置和全局使用数据"""
    #输出关键日志
    msg = "initialize:" 
    context.write_log(msg, stdout=1)
    #从传入参数中获取需要交易的合约
    context.ins = context.instruments[0] # 从传入参数中获取需要交易的合约
    context.order_num = 2 # 下单手数
    context.closetime_day = "14:58" # 日内策略白盘平仓时间,一般14:58
    context.closetime_night = "22:58" # 日内策略夜盘平仓时间,一般22:58,注意有些商品夜盘收盘时间不一样

def before_trading(context, data):
    """盘前处理,策略盘前交易函数,每日盘前触发一次。可以在该函数中一些启动前的准备,如订阅行情等"""
    # 盘前处理,订阅行情等
    context.subscribe_bar(context.ins,'1m') # 注册合约
    context.flag = 0 # 用于获取今开
    context.count = 0 # 交易次数记录
    bar1d_df = data.history(context.ins, ["high","low",'close'], 1, "1d")
    context.high = bar1d_df['high'][0] # 昨高
    context.low = bar1d_df['low'][0]  # 昨低

def handle_data(context, data):

    # 获取当天开盘价
    from datetime import datetime,timedelta
    if context.flag == 0:
        open_price = data.history(context.ins, ["open"], 1, "1m")
        context.flag += 1
        context.today_open = open_price['open'][0] 
    
    # 当前k线时间,具体到分
    cur_date =  data.current_dt
    cur_hm = cur_date.strftime('%H:%M') 
    
    # 部分品种夜盘收盘时间不一样,此时间表示指定的尾盘平仓时间往后偏移30分钟,这段时间内不能开新仓,只能平仓。给30分钟是为了足够的冗余
    closetime_nightshift = (datetime.strptime(context.closetime_night,'%H:%M') + timedelta(minutes = 30)).strftime('%H:%M')
    # 分别获取多头持和空头持仓
    position_long = context.get_position(context.ins, Direction.LONG)
    position_short = context.get_position(context.ins, Direction.SHORT)
    # 获取当前价格
    price = data.current(context.ins, "close")
    
    # 尾盘平仓
    if((cur_hm>=context.closetime_day and cur_hm<="15:00") or (cur_hm>=context.closetime_night and cur_hm<=closetime_nightshift)):
        if(position_long.current_qty != 0):
            rv = context.sell_close(context.ins, position_long.avail_qty, price, order_type=OrderType.MARKET)
            msg = "{} 尾盘平多 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
            context.write_log(msg, stdout=1) #输出关键日志
        if(position_short.current_qty != 0):
            rv = context.buy_close(context.ins, position_short.avail_qty, price, order_type=OrderType.MARKET)
            msg = "{} 尾盘平空 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
            context.write_log(msg, stdout=1) #输出关键日志
        #尾盘不开新仓,直接返回
        return
    
    # 建仓逻辑
    # 多头持仓,最新价小于开盘价 平多
    if position_long.current_qty != 0 and price < context.today_open:
        rv = context.sell_close(context.ins, position_long.avail_qty, price, order_type=OrderType.MARKET)
        msg = "{} 平多 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
        context.write_log(msg, stdout=1) 
        
    # 空头持仓,最新价大于开盘价 平空
    elif position_short.current_qty != 0 and price > context.today_open:
        rv = context.buy_close(context.ins, position_short.avail_qty, price, order_type=OrderType.MARKET)
        msg = "{} 平空 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
        context.write_log(msg, stdout=1) 

    # 当前的最新价大于前一天的最高价且没有持仓 开多
    if (position_long.current_qty == 0) and (price > context.high) and (context.count<=1):
        rv = context.buy_open(context.ins, context.order_num, price, order_type=OrderType.MARKET)
        msg = "{} 开多 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
        context.count += 1 #只开仓一次的判断
        context.write_log(msg, stdout=1) 
    # 当前最新价小于前一天的最低价且没有持仓 开空
    elif (position_short.current_qty == 0) and (price < context.low) and (context.count<=1):
        rv = context.sell_open(context.ins, context.order_num, price, order_type=OrderType.MARKET)
        msg = "{} 开空 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
        context.count += 1
        context.write_log(msg, stdout=1) 
            
def handle_order(context, order):
    """委托回报通知函数,每个订单状态有变化时会触发"""
    msg = "handle_order data:{}".format(order.log_str())
    context.write_log(msg, stdout=0)

def handle_trade(context, trade):
    """成交回报通知函数,有成交时会触发"""
    msg = "handle_trade data:{}".format(trade.log_str())
    context.write_log(msg, stdout=0)  # stdout=0表示不打印
    # 分别获取最新的多头持仓和空头持仓
    position_long = context.get_position(trade.symbol, Direction.LONG)
    position_short = context.get_position(trade.symbol, Direction.SHORT)
    msg = "当前多头持仓:{} 当前空头持仓:{}".format(str(position_long),str(position_short))
    context.write_log(msg, stdout=0)

# 回测标的
instruments = ["RU2309.SHF"]
start_date = "2023-04-01"
end_date = "2023-05-01"
md = M.hftrade.v2(start_date=start_date, #回测开始时间
                end_date=end_date, #回测结束时间
                instruments=instruments, #合约列表
                capital_base=200000, #初始资金
                product_type=Product.FUTURE,
                frequency=Frequency.MINUTE,  #回测频率
                initialize=initialize,
                before_trading_start=before_trading,
                handle_data=handle_data,
                handle_order=handle_order,
                handle_trade=handle_trade,
                plot_charts=True, #画出回测结果分析图
                disable_cache=0, #启用缓存加速
                show_debug_info=1, #打印debug日志
                before_start_days=10   
                )
[2023-05-17 14:30:31.760846] INFO moduleinvoker: hfbacktest.v2 开始运行..
INFO:moduleinvoker:hfbacktest.v2 开始运行..
[2023-05-17 14:30:31.769569] INFO hfbacktest: passed-in daily_data_ds:None
INFO:hfbacktest:passed-in daily_data_ds:None
[2023-05-17 14:30:31.772743] INFO hfbacktest: passed-in minute_data_ds:None
INFO:hfbacktest:passed-in minute_data_ds:None
[2023-05-17 14:30:31.775534] INFO hfbacktest: passed-in tick_data_ds:None
INFO:hfbacktest:passed-in tick_data_ds:None
[2023-05-17 14:30:31.778131] INFO hfbacktest: passed-in each_data_ds:None
INFO:hfbacktest:passed-in each_data_ds:None
[2023-05-17 14:30:31.780718] INFO hfbacktest: passed-in dominant_data_ds:None
INFO:hfbacktest:passed-in dominant_data_ds:None
[2023-05-17 14:30:31.783421] INFO hfbacktest: passed-in basic_data_ds:None
INFO:hfbacktest:passed-in basic_data_ds:None
[2023-05-17 14:30:31.786716] INFO hfbacktest: passed-in benchmark_data_ds:None
INFO:hfbacktest:passed-in benchmark_data_ds:None
[2023-05-17 14:30:31.790429] INFO hfbacktest: hfbacktest2 V2.0.0
INFO:hfbacktest:hfbacktest2 V2.0.0
[2023-05-17 14:30:31.793609] INFO hfbacktest: pytradersdk v1.0.0 2023-05-15
INFO:hfbacktest:pytradersdk v1.0.0 2023-05-15
[2023-05-17 14:30:31.819813] INFO hfbacktest: strategy callbacks:{'initialize': <function initialize at 0x7ff2222248b0>, 'before_trading': <function before_trading at 0x7ff2222245e0>, 'handle_data': <function handle_data at 0x7ff22226d1f0>, 'handle_trade': <function handle_trade at 0x7ff4bc5f2040>, 'handle_order': <function handle_order at 0x7ff22228e9d0>}
INFO:hfbacktest:strategy callbacks:{'initialize': <function initialize at 0x7ff2222248b0>, 'before_trading': <function before_trading at 0x7ff2222245e0>, 'handle_data': <function handle_data at 0x7ff22226d1f0>, 'handle_trade': <function handle_trade at 0x7ff4bc5f2040>, 'handle_order': <function handle_order at 0x7ff22228e9d0>}
[2023-05-17 14:30:31.825342] INFO hfbacktest: begin reading history data, 2023-04-01 00:00:00~2023-05-01, disable_cache:0, replay_bdb:False
INFO:hfbacktest:begin reading history data, 2023-04-01 00:00:00~2023-05-01, disable_cache:0, replay_bdb:False
[2023-05-17 14:30:31.831288] INFO hfbacktest: reading benchmark data 000300.HIX 2023-04-01 00:00:00~2023-05-01...
INFO:hfbacktest:reading benchmark data 000300.HIX 2023-04-01 00:00:00~2023-05-01...
[2023-05-17 14:30:31.871093] INFO moduleinvoker: cached.v2 开始运行..
INFO:moduleinvoker:cached.v2 开始运行..
[2023-05-17 14:30:31.884896] INFO moduleinvoker: 命中缓存
INFO:moduleinvoker:命中缓存
[2023-05-17 14:30:31.889526] INFO moduleinvoker: cached.v2 运行完成[0.01846s].
INFO:moduleinvoker:cached.v2 运行完成[0.01846s].
[2023-05-17 14:30:32.138953] INFO hfbacktest: reading daily data 2022-04-01 00:00:00~2023-05-01...
INFO:hfbacktest:reading daily data 2022-04-01 00:00:00~2023-05-01...
[2023-05-17 14:30:32.164623] INFO moduleinvoker: cached.v2 开始运行..
INFO:moduleinvoker:cached.v2 开始运行..
[2023-05-17 14:30:32.358132] INFO moduleinvoker: cached.v2 运行完成[0.193453s].
INFO:moduleinvoker:cached.v2 运行完成[0.193453s].
[2023-05-17 14:30:32.394577] INFO hfbacktest: reading minute data 2023-03-20 20:55:00~2023-05-01...
INFO:hfbacktest:reading minute data 2023-03-20 20:55:00~2023-05-01...
[2023-05-17 14:30:32.413049] INFO moduleinvoker: cached.v2 开始运行..
INFO:moduleinvoker:cached.v2 开始运行..
[2023-05-17 14:30:32.557334] INFO moduleinvoker: cached.v2 运行完成[0.144286s].
INFO:moduleinvoker:cached.v2 运行完成[0.144286s].
[2023-05-17 14:30:32.648585] INFO hfbacktest: cached_benchmark_ds:DataSource(e17d0c76726c4f74b3733ca3c72f9dceT)
INFO:hfbacktest:cached_benchmark_ds:DataSource(e17d0c76726c4f74b3733ca3c72f9dceT)
[2023-05-17 14:30:32.651909] INFO hfbacktest: cached_daily_ds:DataSource(bc5aee752c3a482696224a0b6a3ce6f6T)
INFO:hfbacktest:cached_daily_ds:DataSource(bc5aee752c3a482696224a0b6a3ce6f6T)
[2023-05-17 14:30:32.654587] INFO hfbacktest: cached_minute_ds:DataSource(b780634b11314c4796d2490d7b53cd0aT)
INFO:hfbacktest:cached_minute_ds:DataSource(b780634b11314c4796d2490d7b53cd0aT)
[2023-05-17 14:30:32.657189] INFO hfbacktest: cached_tick_ds:None
INFO:hfbacktest:cached_tick_ds:None
[2023-05-17 14:30:32.659778] INFO hfbacktest: cached_each_ds:None
INFO:hfbacktest:cached_each_ds:None
[2023-05-17 14:30:32.662375] INFO hfbacktest: dominant_data_ds:None
INFO:hfbacktest:dominant_data_ds:None
[2023-05-17 14:30:32.664967] INFO hfbacktest: read history data done, call run backtest(future,1m,200000,2023-04-01~2023-05-01) ...
INFO:hfbacktest:read history data done, call run backtest(future,1m,200000,2023-04-01~2023-05-01) ...
[2023-05-17 14:30:32.667714] INFO hfbacktest: run_algo: PyTradeEngine ver=1.0.0
INFO:hfbacktest:run_algo: PyTradeEngine ver=1.0.0
[2023-05-17 14:30:32.673034] INFO hfbacktest: run algo: init rv=0
INFO:hfbacktest:run algo: init rv=0
[2023-05-17 14:30:32.681716] INFO hfbacktest: run_algo: set_history_data frequency='1m', len=9540, rv=0
INFO:hfbacktest:run_algo: set_history_data frequency='1m', len=9540, rv=0
[2023-05-17 14:30:32.684542] INFO hfbacktest: run_algo: add strategy funcs done rv=5, running...
INFO:hfbacktest:run_algo: add strategy funcs done rv=5, running...
2023-05-17 14:30:32.687304 initialize:
2023-05-17 14:30:32.713876 2023-04-03 21:01:00 开空 for RU2309.SHF  最新价=11860.0 下单函数返回=1
2023-05-17 14:30:32.724001 2023-04-03 22:58:00 尾盘平空 for RU2309.SHF  最新价=11820.0 下单函数返回=2
2023-05-17 14:30:32.729689 2023-04-04 09:01:00 开空 for RU2309.SHF  最新价=11810.0 下单函数返回=3
2023-05-17 14:30:32.744522 2023-04-04 14:58:00 尾盘平空 for RU2309.SHF  最新价=11790.0 下单函数返回=4
2023-05-17 14:30:32.757824 2023-04-06 13:50:00 开空 for RU2309.SHF  最新价=11745.0 下单函数返回=5
2023-05-17 14:30:32.764015 2023-04-06 13:51:00 平空 for RU2309.SHF  最新价=11750.0 下单函数返回=6
2023-05-17 14:30:32.769696 2023-04-06 13:52:00 开空 for RU2309.SHF  最新价=11745.0 下单函数返回=7
2023-05-17 14:30:32.775814 2023-04-06 13:53:00 平空 for RU2309.SHF  最新价=11735.0 下单函数返回=8
2023-05-17 14:30:32.787633 2023-04-06 21:49:00 开空 for RU2309.SHF  最新价=11635.0 下单函数返回=9
2023-05-17 14:30:32.798873 2023-04-06 22:58:00 尾盘平空 for RU2309.SHF  最新价=11595.0 下单函数返回=10
2023-05-17 14:30:32.804882 2023-04-07 09:01:00 开空 for RU2309.SHF  最新价=11610.0 下单函数返回=11
2023-05-17 14:30:32.825143 2023-04-07 14:58:00 尾盘平空 for RU2309.SHF  最新价=11610.0 下单函数返回=12
2023-05-17 14:30:32.865839 2023-04-11 09:10:00 开空 for RU2309.SHF  最新价=11625.0 下单函数返回=13
2023-05-17 14:30:32.873970 2023-04-11 09:14:00 平空 for RU2309.SHF  最新价=11695.0 下单函数返回=14
2023-05-17 14:30:32.891958 2023-04-11 14:34:00 开多 for RU2309.SHF  最新价=11725.0 下单函数返回=15
2023-05-17 14:30:32.899303 2023-04-11 14:58:00 尾盘平多 for RU2309.SHF  最新价=11720.0 下单函数返回=16
2023-05-17 14:30:32.905639 2023-04-11 21:05:00 开多 for RU2309.SHF  最新价=11755.0 下单函数返回=17
2023-05-17 14:30:32.917937 2023-04-11 22:38:00 平多 for RU2309.SHF  最新价=11720.0 下单函数返回=18
2023-05-17 14:30:32.945999 2023-04-13 13:41:00 开空 for RU2309.SHF  最新价=11655.0 下单函数返回=19
2023-05-17 14:30:32.956029 2023-04-13 14:58:00 尾盘平空 for RU2309.SHF  最新价=11685.0 下单函数返回=20
2023-05-17 14:30:32.969108 2023-04-14 09:36:00 开多 for RU2309.SHF  最新价=11775.0 下单函数返回=21
2023-05-17 14:30:32.984218 2023-04-14 14:37:00 平多 for RU2309.SHF  最新价=11670.0 下单函数返回=22
2023-05-17 14:30:33.001380 2023-04-17 09:05:00 开多 for RU2309.SHF  最新价=11790.0 下单函数返回=23
2023-05-17 14:30:33.022093 2023-04-17 14:58:00 尾盘平多 for RU2309.SHF  最新价=11905.0 下单函数返回=24
2023-05-17 14:30:33.029289 2023-04-17 21:10:00 开多 for RU2309.SHF  最新价=11935.0 下单函数返回=25
2023-05-17 14:30:33.038248 2023-04-17 22:33:00 平多 for RU2309.SHF  最新价=11895.0 下单函数返回=26
2023-05-17 14:30:33.048587 2023-04-18 09:50:00 开多 for RU2309.SHF  最新价=11930.0 下单函数返回=27
2023-05-17 14:30:33.057125 2023-04-18 10:04:00 平多 for RU2309.SHF  最新价=11895.0 下单函数返回=28
2023-05-17 14:30:33.078343 2023-04-18 22:17:00 开多 for RU2309.SHF  最新价=11970.0 下单函数返回=29
2023-05-17 14:30:33.086968 2023-04-18 22:58:00 尾盘平多 for RU2309.SHF  最新价=12040.0 下单函数返回=30
2023-05-17 14:30:33.093263 2023-04-19 09:01:00 开多 for RU2309.SHF  最新价=12035.0 下单函数返回=31
2023-05-17 14:30:33.108142 2023-04-19 14:58:00 尾盘平多 for RU2309.SHF  最新价=11975.0 下单函数返回=32
2023-05-17 14:30:33.116766 2023-04-19 21:43:00 开空 for RU2309.SHF  最新价=11875.0 下单函数返回=33
2023-05-17 14:30:33.124229 2023-04-19 22:22:00 平空 for RU2309.SHF  最新价=11925.0 下单函数返回=34
2023-05-17 14:30:33.140902 2023-04-20 21:02:00 开多 for RU2309.SHF  最新价=12055.0 下单函数返回=35
2023-05-17 14:30:33.147833 2023-04-20 21:18:00 平多 for RU2309.SHF  最新价=12020.0 下单函数返回=36
2023-05-17 14:30:33.155209 2023-04-20 21:52:00 开多 for RU2309.SHF  最新价=12050.0 下单函数返回=37
2023-05-17 14:30:33.164204 2023-04-20 22:43:00 平多 for RU2309.SHF  最新价=12020.0 下单函数返回=38
2023-05-17 14:30:33.180157 2023-04-21 21:03:00 开空 for RU2309.SHF  最新价=11835.0 下单函数返回=39
2023-05-17 14:30:33.191688 2023-04-21 22:58:00 尾盘平空 for RU2309.SHF  最新价=11695.0 下单函数返回=40
2023-05-17 14:30:33.198916 2023-04-24 09:01:00 开空 for RU2309.SHF  最新价=11685.0 下单函数返回=41
2023-05-17 14:30:33.214266 2023-04-24 14:58:00 尾盘平空 for RU2309.SHF  最新价=11700.0 下单函数返回=42
2023-05-17 14:30:33.223261 2023-04-24 22:07:00 开多 for RU2309.SHF  最新价=11905.0 下单函数返回=43
2023-05-17 14:30:33.233622 2023-04-24 22:58:00 尾盘平多 for RU2309.SHF  最新价=12135.0 下单函数返回=44
2023-05-17 14:30:33.239906 2023-04-25 09:01:00 开多 for RU2309.SHF  最新价=12220.0 下单函数返回=45
2023-05-17 14:30:33.254344 2023-04-25 14:58:00 尾盘平多 for RU2309.SHF  最新价=12000.0 下单函数返回=46
2023-05-17 14:30:33.281919 2023-04-27 10:04:00 开空 for RU2309.SHF  最新价=11825.0 下单函数返回=47
2023-05-17 14:30:33.296363 2023-04-27 14:58:00 尾盘平空 for RU2309.SHF  最新价=11735.0 下单函数返回=48
2023-05-17 14:30:33.305329 2023-04-27 21:24:00 开空 for RU2309.SHF  最新价=11725.0 下单函数返回=49
2023-05-17 14:30:33.315223 2023-04-27 22:04:00 平空 for RU2309.SHF  最新价=11760.0 下单函数返回=50
2023-05-17 14:30:33.325919 2023-04-27 22:34:00 开空 for RU2309.SHF  最新价=11730.0 下单函数返回=51
2023-05-17 14:30:33.334382 2023-04-27 22:45:00 平空 for RU2309.SHF  最新价=11755.0 下单函数返回=52
[2023-05-17 14:30:33.356779] INFO hfbacktest: run_algo: done
INFO:hfbacktest:run_algo: done
[2023-05-17 14:30:33.597120] INFO hfbacktest: backtest done, raw_perf_ds:DataSource(c4f57e6a383c4299aec3ede6d2dac592T)
INFO:hfbacktest:backtest done, raw_perf_ds:DataSource(c4f57e6a383c4299aec3ede6d2dac592T)
/usr/local/python3/lib/python3.8/site-packages/pandas/compat/_optional.py:116: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
  if distutils.version.LooseVersion(version) < minimum_version:
/usr/local/python3/lib/python3.8/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
  other = LooseVersion(other)
/usr/local/python3/lib/python3.8/site-packages/tables/atom.py:1224: DeprecationWarning: tostring() is deprecated. Use tobytes() instead.
  return pickle.loads(array.tostring())
[2023-05-17 14:30:33.997708] INFO: bigcharts.impl.render:render.py:407:render_chart Data is None, skip loading it to chart.
2023-05-17 14:30:34.226921 perf_render_future process plot...
  • 收益率-0.08%
  • 年化收益率-0.99%
  • 基准收益率-1.5%
  • 阿尔法-0.01
  • 贝塔0.13
  • 夏普比率-0.35
  • 胜率0
  • 盈亏比0
  • 收益波动率9.98%
  • 最大回撤2.66%
成交时间 合约代码 合约名称 买/卖 开/平 数量 成交价 交易金额 交易佣金 平仓盈亏
Loading... (need help?)
日期 合约代码 合约名称 持仓均价 收盘价 数量 持仓保证金 浮动盈亏 平仓盈亏
Loading... (need help?)
时间 级别 内容
Loading... (need help?)
[2023-05-17 14:30:34.315574] INFO moduleinvoker: hfbacktest.v2 运行完成[2.554732s].
INFO:moduleinvoker:hfbacktest.v2 运行完成[2.554732s].
[2023-05-17 14:30:34.321255] INFO moduleinvoker: hftrade.v2 运行完成[2.574898s].
INFO:moduleinvoker:hftrade.v2 运行完成[2.574898s].