# 导入相应包
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
# 均线长度
context.ma_length = 63
def before_trading(context, data):
"""盘前处理,策略盘前交易函数,每日盘前触发一次。可以在该函数中一些启动前的准备,如订阅行情等"""
# 输出关键日志
msg = "before_trading"
context.write_log(msg, stdout=1)
# 订阅要交易的合约的行情
context.subscribe_bar(context.ins, '1m')
def handle_data(context, data):
#获取当前时间
cur_date = data.current_dt
for instr in context.ins:
# 分别获取多头持仓和空头持仓,主要使用 current_qty 和 avail_qty 两个属性
position_long = context.get_position(instr, Direction.LONG)
position_short = context.get_position(instr, Direction.SHORT)
# 最新价格
price = data.current(instr, "close")
#获取30根1m历史数据数据
hist = context.history_data(instr, ["open","high","low","close"], context.ma_length+5, "1m")
# 计算均值
ma = pd.Series(hist['close']).rolling(context.ma_length).mean()
#价格向上穿越20均线
if ma.iloc[-2] > price and price > ma.iloc[-1] :
#有空单的先平掉
if (position_short.avail_qty != 0):
rv = context.buy_close(instr, position_short.avail_qty, price, order_type=OrderType.MARKET)
msg = "{} 平空 for {} 最新价={} 下单函数返回={}".format(cur_date,instr,str(price),str(rv))
context.write_log(msg, stdout=0)
#没有多单则开多1手
if (position_long.avail_qty == 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.iloc[-2] < price and price < ma.iloc[-1]:
#有多单的先平掉
if (position_long.avail_qty != 0):
rv = context.sell_close(instr, position_long.avail_qty, price, order_type=OrderType.MARKET)
msg = "{} 平多 for {} 最新价={} 下单函数返回={}".format(cur_date,instr,str(price),str(rv))
context.write_log(msg, stdout=0)
#没有空单则开空1手
if (position_short.avail_qty == 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)
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)
# 回测标的
instruments = ["SR2309.CZC","C2309.DCE"]
start_date = "2023-03-20"
end_date = "2023-05-01"
md = M.hftrade.v2(start_date=start_date, #回测开始时间
end_date=end_date, #回测结束时间
instruments=instruments, #合约列表
capital_base=100000, #初始资金
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
)