版本 v1.0
可视化策略实现如下:
# 本代码由可视化策略环境自动生成 2021年12月1日 16:56
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
# 交易引擎:初始化函数,只执行一次
def m1_initialize_bigquant_run(context):
#输出关键日志
msg = "initialize:"
context.PRINT = 1
context.write_log(msg, stdout=context.PRINT)
contract_date_list=[]
for ins in context.instruments:
contract_date_list.append(int(ins.split('.')[0][-4:]))
#获取每个合约代码
for ins in context.instruments:
if int(ins.split('.')[0][-4:]) == min(contract_date_list):
context.instrument_nearby_contract = ins
elif int(ins.split('.')[0][-4:]) == max(contract_date_list):
context.instrument_forward_contract = ins
#下单手数
context.order_num = 1
#获取数据,提前算出开平仓信号,减少回测时间
all_data = context.options["data"].read()
df_nearby_contract = all_data[all_data.instrument==context.instrument_nearby_contract][["date","close"]].rename(columns={"close":"close_nearby_contract"})
df_forward_contract = all_data[all_data.instrument==context.instrument_forward_contract][["date","close"]].rename(columns={"close":"close_forward_contract"})
merge_df = pd.merge(left=df_nearby_contract,right=df_forward_contract,on=["date"])
merge_df["spread"] = merge_df["close_nearby_contract"]-merge_df["close_forward_contract"]
#现货正向信号
positive_signal = (merge_df["spread"].shift(1)>-200)&(merge_df["spread"]<=-200)
merge_df["signal"] = np.where(positive_signal,1,np.NAN)
#现货负向信号
negative_signal = (merge_df["spread"].shift(1)<100)&(merge_df["spread"]>=100)
merge_df["signal"] = np.where(negative_signal,-1,merge_df["signal"])
context.mydata = merge_df
# 交易引擎:每个单位时间开盘前调用一次。
def m1_before_trading_start_bigquant_run(context, data):
# 订阅要交易的合约的行情
context.subscribe([context.instrument_nearby_contract,context.instrument_forward_contract])
# 交易引擎:tick数据处理函数,每个tick执行一次
def m1_handle_tick_bigquant_run(context, data):
pass
#平仓
def close_orders(context,data):
#获取当前时间
cur_date = data.current_dt.strftime('%Y-%m-%d')
for ins in [context.instrument_nearby_contract,context.instrument_forward_contract]:
# 分别获取多头持仓和空头持仓
position_long = context.get_position(ins, Direction.LONG)
position_short = context.get_position(ins, Direction.SHORT)
price = data.current(ins,"close")
if(position_long.current_qty != 0):
rv = context.sell_close(ins, position_long.avail_qty, price, order_type=OrderType.MARKET)
msg = "{} 平多 for {} 最新价={} 下单函数返回 {}".format(cur_date,ins,price,context.get_error_msg(rv))
context.write_log(msg, stdout=context.PRINT)
if(position_short.current_qty != 0):
rv = context.buy_close(ins, position_short.avail_qty, price, order_type=OrderType.MARKET)
msg = "{} 平空 for {} 最新价={} 下单函数返回 {}".format(cur_date,ins,price,context.get_error_msg(rv))
context.write_log(msg, stdout=context.PRINT)
# 交易引擎:bar数据处理函数,每个时间单位执行一次
def m1_handle_data_bigquant_run(context, data):
#获取当前时间
cur_date = data.current_dt.strftime('%Y-%m-%d')
#获取当天开仓信号
now_data = context.mydata[context.mydata.date==cur_date]
if len(now_data)==0:
context.write_log("{}无数据,直接返回".format(cur_date), stdout=context.PRINT)
return
#正向开仓
if now_data.signal.iloc[0]==1:
#先平掉所有持仓
close_orders(context,data)
#做多2109
price = data.current(context.instrument_nearby_contract,"close")
rv = context.buy_open(context.instrument_nearby_contract, context.order_num, price, order_type=OrderType.MARKET)
msg = "{} 开多 for {} 最新价={} 下单函数返回 {}".format(cur_date,context.instrument_nearby_contract,price,context.get_error_msg(rv))
context.write_log(msg, stdout=context.PRINT)
#做空2111
price = data.current(context.instrument_forward_contract,"close")
rv = context.sell_open(context.instrument_forward_contract, context.order_num, price, order_type=OrderType.MARKET)
msg = "{} 开空 for {} 最新价={} 下单函数返回 {}".format(cur_date,context.instrument_forward_contract,price,context.get_error_msg(rv))
context.write_log(msg, stdout=context.PRINT)
#反向开仓
elif now_data.signal.iloc[0]==-1:
#先平掉所有持仓
close_orders(context,data)
#做多2111
price = data.current(context.instrument_forward_contract,"close")
rv = context.buy_open(context.instrument_forward_contract, context.order_num, price, order_type=OrderType.MARKET)
msg = "{} 开多 for {} 最新价={} 下单函数返回 {}".format(cur_date,context.instrument_forward_contract,price,context.get_error_msg(rv))
context.write_log(msg, stdout=context.PRINT)
#做空2109
price = data.current(context.instrument_nearby_contract,"close")
rv = context.sell_open(context.instrument_nearby_contract, context.order_num, price, order_type=OrderType.MARKET)
msg = "{} 开空 for {} 最新价={} 下单函数返回 {}".format(cur_date,context.instrument_nearby_contract,price,context.get_error_msg(rv))
context.write_log(msg, stdout=context.PRINT)
# 交易引擎:成交回报处理函数,每个成交发生时执行一次
def m1_handle_trade_bigquant_run(context, data):
msg = "handle_trade data:{}".format(data.log_str())
context.write_log(msg, stdout=context.PRINT)
# 交易引擎:委托回报处理函数,每个委托变化时执行一次
def m1_handle_order_bigquant_run(context, data):
msg = "handle_order data:{}".format(data.log_str())
context.write_log(msg, stdout=context.PRINT)
# 交易引擎:盘后处理函数,每日盘后执行一次
def m1_after_trading_bigquant_run(context, data):
pass
m2 = M.instruments.v2(
start_date='2021-04-01',
end_date='2021-08-30',
market='CN_FUTURE',
instrument_list="""RB2109.SHF
RB2111.SHF
""",
max_count=0
)
m3 = M.use_datasource.v1(
instruments=m2.data,
datasource_id='bar1d_CN_FUTURE',
start_date='',
end_date='',
m_cached=False
)
m1 = M.hftrade.v1(
instruments=m2.data,
options_data=m3.data,
start_date='',
end_date='',
initialize=m1_initialize_bigquant_run,
before_trading_start=m1_before_trading_start_bigquant_run,
handle_tick=m1_handle_tick_bigquant_run,
handle_data=m1_handle_data_bigquant_run,
handle_trade=m1_handle_trade_bigquant_run,
handle_order=m1_handle_order_bigquant_run,
after_trading=m1_after_trading_bigquant_run,
capital_base=100000,
frequency='daily',
price_type='真实价格',
product_type='期货',
before_start_days='0',
benchmark='000300.HIX',
plot_charts=True,
disable_cache=False,
show_debug_info=True,
backtest_only=False
)
[2021-11-12 18:47:20.228318] INFO: moduleinvoker: instruments.v2 开始运行..
[2021-11-12 18:47:20.239439] INFO: moduleinvoker: 命中缓存
[2021-11-12 18:47:20.242084] INFO: moduleinvoker: instruments.v2 运行完成[0.013774s].
[2021-11-12 18:47:20.247767] INFO: moduleinvoker: use_datasource.v1 开始运行..
[2021-11-12 18:47:20.435090] INFO: moduleinvoker: use_datasource.v1 运行完成[0.187317s].
[2021-11-12 18:47:20.487883] INFO: moduleinvoker: hfbacktest.v1 开始运行..
[2021-11-12 18:47:20.493816] INFO: hfbacktest: passed-in daily_data_ds:None
[2021-11-12 18:47:20.495953] INFO: hfbacktest: passed-in minute_data_ds:None
[2021-11-12 18:47:20.498339] INFO: hfbacktest: passed-in tick_data_ds:None
[2021-11-12 18:47:20.500349] INFO: hfbacktest: passed-in each_data_ds:None
[2021-11-12 18:47:20.502451] INFO: hfbacktest: passed-in dominant_data_ds:None
[2021-11-12 18:47:20.504453] INFO: hfbacktest: passed-in benchmark_data_ds:None
[2021-11-12 18:47:20.506367] INFO: hfbacktest: passed-in trading_calendar_ds:None
[2021-11-12 18:47:20.508428] INFO: hfbacktest: biglearning V1.3.0
[2021-11-12 18:47:20.510335] INFO: hfbacktest: bigtrader v1.7.8_sp2
[2021-11-12 18:47:20.546396] INFO: hfbacktest: strategy callbacks:{'on_init': , 'on_stop': , 'on_start': , 'handle_data': , 'handle_tick': , 'handle_trade': , 'handle_order': }
[2021-11-12 18:47:20.561661] INFO: hfbacktest: begin reading history data, 2021-04-01 00:00:00~2021-08-30, disable_cache:False
[2021-11-12 18:47:20.564468] INFO: hfbacktest: reading benchmark data 2021-03-01 00:00:00~2021-08-30...
[2021-11-12 18:47:20.577103] INFO: moduleinvoker: cached.v2 开始运行..
[2021-11-12 18:47:20.594577] INFO: moduleinvoker: 命中缓存
[2021-11-12 18:47:20.597579] INFO: moduleinvoker: cached.v2 运行完成[0.020485s].
[2021-11-12 18:47:20.650191] INFO: hfbacktest: reading daily data 20190926~2021-08-30...
[2021-11-12 18:47:20.675177] INFO: moduleinvoker: cached.v2 开始运行..
[2021-11-12 18:47:20.687271] INFO: moduleinvoker: 命中缓存
[2021-11-12 18:47:20.690593] INFO: moduleinvoker: cached.v2 运行完成[0.015397s].
[2021-11-12 18:47:20.804520] INFO: hfbacktest: cached_benchmark_ds:DataSource(7e831bb1520b4494bb195f0901d190d8T)
[2021-11-12 18:47:20.806768] INFO: hfbacktest: cached_daily_ds:DataSource(a7357a5d37684dbbaa014a0d4a9141beT)
[2021-11-12 18:47:20.809091] INFO: hfbacktest: cached_minute_ds:None
[2021-11-12 18:47:20.824275] INFO: hfbacktest: cached_tick_ds:None
[2021-11-12 18:47:20.826787] INFO: hfbacktest: cached_each_ds:None
[2021-11-12 18:47:20.828978] INFO: hfbacktest: dominant_data_ds:None
[2021-11-12 18:47:20.831140] INFO: hfbacktest: read history data done, call run_backtest()
[2021-11-12 18:47:23.991525] INFO: hfbacktest: backtest done, raw_perf_ds:DataSource(0e25851c068f41668cb20baa877f0703T)
[2021-11-12 18:47:24.852735] INFO: moduleinvoker: hfbacktest.v1 运行完成[4.364876s].
[2021-11-12 18:47:24.854673] INFO: moduleinvoker: hftrade.v1 运行完成[4.408946s].