版本v2.0
以"交割单模板.csv"为例,展示了成交单分析功能,该数据是直接从模板策略的回测详细数据中的交易详情下载处理后得到。
输入:交割单模板.csv 指定:
此模块会将每日的交易记录读取至DataFrame,并将信号时间前移1天来实现模拟当日成交,输出股票代码列表、起止时间和前移1日后的交易信号数据(包括日期、代码、买卖方向、成交价格和数量)。
# 本代码由可视化策略环境自动生成 2021年8月19日 16:39
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m4_run_bigquant_run(input_1, input_2, input_3):
# 示例代码如下。在这里编写您的代码
df = pd.read_csv('trade_list_1.csv').fillna(method='ffill')
columns_map = {
'日期': 'date',
'股票代码': 'instrument',
'买/卖': 'side',
'成交价': 'trade_price',
'数量': 'trade_volume',
'总成本': 'total_cost'
}
df.rename(columns=columns_map, inplace=True)
df.date = pd.to_datetime(df.date, format="%Y-%m-%d")
td = D.trading_days(start_date=df['date'].min() - pd.Timedelta(10, 'D'),
end_date=df['date'].max())
td['order_date'] = td['date'].shift(1)
df = df.merge(td, on='date', how='left')
df['date'] = df['order_date']
del df['order_date']
df.loc[df.side == '买入', 'side'] = 'BUY'
df.loc[df.side == '卖出', 'side'] = 'SELL'
instrument_data = {
'instruments': list(set(df['instrument'])),
'start_date': df['date'].min().strftime('%Y-%m-%d'),
'end_date': (df['date'].max() + pd.Timedelta(1, 'D')).strftime('%Y-%m-%d'),
# 'end_date': '2015-05-11'
}
df.date = df.date.apply(lambda x: x.strftime('%Y-%m-%d'))
trading_records_ds = DataSource.write_df(df)
instruments_ds = DataSource.write_pickle(instrument_data)
return Outputs(data_1=instruments_ds, data_2=trading_records_ds, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m4_post_run_bigquant_run(outputs):
return outputs
# 回测引擎:初始化函数,只执行一次
def m3_initialize_bigquant_run(context):
context.show_debug_info = False
context.trade_data = context.options['data'].read_df()
context.set_long_only()
from zipline.finance.slippage import SlippageModel
class FixedPriceSlippage(SlippageModel):
def process_order(self, data, order, bar_volume=0, trigger_check_price=0):
if order.limit is None:
price_field = self._price_field_buy if order.amount > 0 else self._price_field_sell
price = data.current(order.asset, price_field)
return (price, order.amount)
else:
price = order.limit
# print("*********", order.asset, price, order.amount, "********")
return (price, order.amount)
fix_slippage = FixedPriceSlippage()
fix_slippage = FixedPriceSlippage(price_field_buy='open', price_field_sell='close')
context.set_slippage(us_equities=fix_slippage)
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
# context.set_commission(PerOrder(buy_cost=0, sell_cost=0, min_cost=0))
# 回测引擎:每日数据处理函数,每天执行一次
def m3_handle_data_bigquant_run(context, data):
# 按日期过滤得到今日收盘后的下单股票
trade_data = context.trade_data[context.trade_data.date == data.current_dt.strftime('%Y-%m-%d')]
# print("handle_data:", data.current_dt, "\n", trade_data)
for i in range(0, len(trade_data)):
volume = trade_data['trade_volume'].iloc[i]
cash = trade_data['total_cost'].iloc[i]
if trade_data['side'].iloc[i] in ['BUY', '配售中签', '新股入帐']:
try:
# print('order -----> ', trade_data['instrument'].iloc[i], cash, trade_data['trade_price'].iloc[i], context.portfolio.cash)
context.order_value(context.symbol(trade_data['instrument'].iloc[i]), cash)
# print('-----'*10)
except Exception as e:
# print('警告:%s' % (e))
# assert 1 > 2
pass
elif trade_data['side'].iloc[i] == 'SELL':
volume = -volume
try:
# print('order -----> ', trade_data['instrument'].iloc[i], volume, trade_data['trade_price'].iloc[i], context.portfolio.cash)
context.order_target(context.symbol(trade_data['instrument'].iloc[i]), 0)
# print('-----'*10)
except Exception as e:
# print('警告:%s' % (e))
# assert 1 > 2
pass
else:
print('警告:未知的买卖标志 %s' % (trade_data['side'].iloc[i]))
# 回测引擎:准备数据,只执行一次
def m3_prepare_bigquant_run(context):
pass
# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
def m3_before_trading_start_bigquant_run(context, data):
pass
m4 = M.cached.v3(
run=m4_run_bigquant_run,
post_run=m4_post_run_bigquant_run,
input_ports='',
params='{}',
output_ports=''
)
m3 = M.trade.v4(
instruments=m4.data_1,
options_data=m4.data_2,
start_date='',
end_date='',
initialize=m3_initialize_bigquant_run,
handle_data=m3_handle_data_bigquant_run,
prepare=m3_prepare_bigquant_run,
before_trading_start=m3_before_trading_start_bigquant_run,
volume_limit=0,
order_price_field_buy='open',
order_price_field_sell='close',
capital_base=1000000,
auto_cancel_non_tradable_orders=False,
data_frequency='daily',
price_type='真实价格',
product_type='股票',
plot_charts=True,
backtest_only=False,
benchmark='000300.HIX'
)
m1 = M.N_days_performance_statistics.v5(
backtest_ds=m3.raw_perf,
N=5
)
[2021-08-19 10:23:52.439219] INFO: moduleinvoker: cached.v3 开始运行..
[2021-08-19 10:23:52.609229] INFO: moduleinvoker: 命中缓存
[2021-08-19 10:23:52.611750] INFO: moduleinvoker: cached.v3 运行完成[0.172545s].
[2021-08-19 10:23:52.671470] INFO: moduleinvoker: backtest.v8 开始运行..
[2021-08-19 10:23:52.675733] INFO: backtest: biglearning backtest:V8.5.0
[2021-08-19 10:23:52.676777] INFO: backtest: product_type:stock by specified
[2021-08-19 10:23:53.403010] INFO: moduleinvoker: cached.v2 开始运行..
[2021-08-19 10:23:53.414164] INFO: moduleinvoker: 命中缓存
[2021-08-19 10:23:53.417073] INFO: moduleinvoker: cached.v2 运行完成[0.014107s].
[2021-08-19 10:23:55.081915] INFO: algo: TradingAlgorithm V1.8.4
[2021-08-19 10:23:55.768785] INFO: algo: trading transform...
[2021-08-19 10:23:57.354712] INFO: algo: handle_splits get splits [dt:2015-05-11 00:00:00+00:00] [asset:Equity(1313 [002381.SZA]), ratio:0.6573165655136108]
[2021-08-19 10:23:57.356211] INFO: Position: position stock handle split[sid:1313, orig_amount:7300, new_amount:11105.0, orig_cost:21.760000228881836, new_cost:14.3032, ratio:0.6573165655136108, last_sale_price:14.059999465942383]
[2021-08-19 10:23:57.357280] INFO: Position: after split: PositionStock(asset:Equity(1313 [002381.SZA]), amount:11105.0, cost_basis:14.3032, last_sale_price:21.389997482299805)
[2021-08-19 10:23:57.358244] INFO: Position: returning cash: 10.6852
[2021-08-19 10:23:57.437187] INFO: algo: handle_splits get splits [dt:2015-05-15 00:00:00+00:00] [asset:Equity(226 [000736.SZA]), ratio:0.9987077116966248]
[2021-08-19 10:23:57.528835] INFO: algo: handle_splits get splits [dt:2015-05-22 00:00:00+00:00] [asset:Equity(817 [300119.SZA]), ratio:0.9944382905960083]
[2021-08-19 10:23:57.530313] INFO: Position: position stock handle split[sid:817, orig_amount:7900, new_amount:7944.0, orig_cost:16.692152192321004, new_cost:16.5993, ratio:0.9944382905960083, last_sale_price:17.880001068115234]
[2021-08-19 10:23:57.531512] INFO: Position: after split: PositionStock(asset:Equity(817 [300119.SZA]), amount:7944.0, cost_basis:16.5993, last_sale_price:17.98000144958496)
[2021-08-19 10:23:57.532576] INFO: Position: returning cash: 3.2763
[2021-08-19 10:23:57.650485] INFO: algo: handle_splits get splits [dt:2015-06-02 00:00:00+00:00] [asset:Equity(341 [300120.SZA]), ratio:0.9976426959037781]
[2021-08-19 10:23:57.652002] INFO: Position: position stock handle split[sid:341, orig_amount:7400, new_amount:7417.0, orig_cost:19.440000534057617, new_cost:19.3942, ratio:0.9976426959037781, last_sale_price:21.160001754760742]
[2021-08-19 10:23:57.653219] INFO: Position: after split: PositionStock(asset:Equity(341 [300120.SZA]), amount:7417.0, cost_basis:19.3942, last_sale_price:21.21000099182129)
[2021-08-19 10:23:57.654376] INFO: Position: returning cash: 10.2683
[2021-08-19 10:23:57.728393] INFO: algo: handle_splits get splits [dt:2015-06-05 00:00:00+00:00] [asset:Equity(916 [002671.SZA]), ratio:0.9965330958366394]
[2021-08-19 10:23:57.729980] INFO: Position: position stock handle split[sid:916, orig_amount:9000, new_amount:9031.0, orig_cost:15.899998664855957, new_cost:15.8449, ratio:0.9965330958366394, last_sale_price:20.120004653930664]
[2021-08-19 10:23:57.731099] INFO: Position: after split: PositionStock(asset:Equity(916 [002671.SZA]), amount:9031.0, cost_basis:15.8449, last_sale_price:20.190000534057617)
[2021-08-19 10:23:57.732032] INFO: Position: returning cash: 6.2511
[2021-08-19 10:23:57.777837] INFO: algo: handle_splits get splits [dt:2015-06-10 00:00:00+00:00] [asset:Equity(11 [002714.SZA]), ratio:0.49969014525413513]
[2021-08-19 10:23:57.780001] INFO: Position: position stock handle split[sid:11, orig_amount:900, new_amount:1801.0, orig_cost:96.25, new_cost:48.0952, ratio:0.49969014525413513, last_sale_price:48.37000274658203]
[2021-08-19 10:23:57.781589] INFO: Position: after split: PositionStock(asset:Equity(11 [002714.SZA]), amount:1801.0, cost_basis:48.0952, last_sale_price:96.79999542236328)
[2021-08-19 10:23:57.794533] INFO: Position: returning cash: 5.6191
[2021-08-19 10:23:57.987162] INFO: algo: handle_splits get splits [dt:2015-06-23 00:00:00+00:00] [asset:Equity(823 [300077.SZA]), ratio:0.9998031258583069]
[2021-08-19 10:23:57.988853] INFO: Position: position stock handle split[sid:823, orig_amount:2600, new_amount:2600.0, orig_cost:51.98999786376953, new_cost:51.9798, ratio:0.9998031258583069, last_sale_price:50.77000045776367]
[2021-08-19 10:23:57.993514] INFO: Position: after split: PositionStock(asset:Equity(823 [300077.SZA]), amount:2600.0, cost_basis:51.9798, last_sale_price:50.779998779296875)
[2021-08-19 10:23:57.995198] INFO: Position: returning cash: 25.9929
[2021-08-19 10:23:58.066493] INFO: algo: handle_splits get splits [dt:2015-06-29 00:00:00+00:00] [asset:Equity(261 [000716.SZA]), ratio:0.997473418712616]
[2021-08-19 10:23:58.068141] INFO: Position: position stock handle split[sid:261, orig_amount:3700, new_amount:3709.0, orig_cost:23.850000381469727, new_cost:23.7897, ratio:0.997473418712616, last_sale_price:23.689992904663086]
[2021-08-19 10:23:58.069400] INFO: Position: after split: PositionStock(asset:Equity(261 [000716.SZA]), amount:3709.0, cost_basis:23.7897, last_sale_price:23.75)
[2021-08-19 10:23:58.070550] INFO: Position: returning cash: 8.8134
[2021-08-19 10:23:58.235693] INFO: algo: handle_splits get splits [dt:2015-07-09 00:00:00+00:00] [asset:Equity(732 [603869.SHA]), ratio:0.9944905042648315]
[2021-08-19 10:23:58.237251] INFO: Position: position stock handle split[sid:732, orig_amount:3200, new_amount:3217.0, orig_cost:28.979999542236328, new_cost:28.8203, ratio:0.9944905042648315, last_sale_price:14.44000244140625]
[2021-08-19 10:23:58.238426] INFO: Position: after split: PositionStock(asset:Equity(732 [603869.SHA]), amount:3217.0, cost_basis:28.8203, last_sale_price:14.520000457763672)
[2021-08-19 10:23:58.239408] INFO: Position: returning cash: 10.5132
[2021-08-19 10:23:59.387570] INFO: algo: handle_splits get splits [dt:2015-09-17 00:00:00+00:00] [asset:Equity(889 [600446.SHA]), ratio:0.33293941617012024]
[2021-08-19 10:23:59.394613] INFO: Position: position stock handle split[sid:889, orig_amount:3800, new_amount:11413.0, orig_cost:151.01868599339537, new_cost:50.2801, ratio:0.33293941617012024, last_sale_price:33.80999755859375]
[2021-08-19 10:23:59.396749] INFO: Position: after split: PositionStock(asset:Equity(889 [600446.SHA]), amount:11413.0, cost_basis:50.2801, last_sale_price:101.54999542236328)
[2021-08-19 10:23:59.399114] INFO: Position: returning cash: 16.4961
[2021-08-19 10:24:01.397835] INFO: algo: handle_splits get splits [dt:2016-03-18 00:00:00+00:00] [asset:Equity(573 [600145.SHA]), ratio:0.2527026832103729]
[2021-08-19 10:24:01.400374] INFO: Position: position stock handle split[sid:573, orig_amount:26400, new_amount:104470.0, orig_cost:6.980000019073486, new_cost:1.7639, ratio:0.2527026832103729, last_sale_price:1.869999885559082]
[2021-08-19 10:24:01.402909] INFO: Position: after split: PositionStock(asset:Equity(573 [600145.SHA]), amount:104470.0, cost_basis:1.7639, last_sale_price:7.400000095367432)
[2021-08-19 10:24:01.405483] INFO: Position: returning cash: 1.1151
[2021-08-19 10:24:01.886513] INFO: algo: handle_splits get splits [dt:2016-05-06 00:00:00+00:00] [asset:Equity(682 [600654.SHA]), ratio:0.9957947731018066]
[2021-08-19 10:24:01.894189] INFO: Position: position stock handle split[sid:682, orig_amount:28000, new_amount:28118.0, orig_cost:23.068570736476353, new_cost:22.9716, ratio:0.9957947731018066, last_sale_price:23.68000030517578]
[2021-08-19 10:24:01.896304] INFO: Position: after split: PositionStock(asset:Equity(682 [600654.SHA]), amount:28118.0, cost_basis:22.9716, last_sale_price:23.780000686645508)
[2021-08-19 10:24:01.898330] INFO: Position: returning cash: 5.7683
[2021-08-19 10:24:01.997391] INFO: algo: handle_splits get splits [dt:2016-05-16 00:00:00+00:00] [asset:Equity(721 [300081.SZA]), ratio:0.3987395465373993]
[2021-08-19 10:24:01.999862] INFO: Position: position stock handle split[sid:721, orig_amount:3200, new_amount:8025.0, orig_cost:35.130001068115234, new_cost:14.0077, ratio:0.3987395465373993, last_sale_price:13.919997215270996]
[2021-08-19 10:24:02.002330] INFO: Position: after split: PositionStock(asset:Equity(721 [300081.SZA]), amount:8025.0, cost_basis:14.0077, last_sale_price:34.90999984741211)
[2021-08-19 10:24:02.004238] INFO: Position: returning cash: 4.0195
[2021-08-19 10:24:02.965552] INFO: algo: handle_splits get splits [dt:2016-08-12 00:00:00+00:00] [asset:Equity(1453 [600578.SHA]), ratio:0.9562363624572754]
[2021-08-19 10:24:02.967261] INFO: Position: position stock handle split[sid:1453, orig_amount:30300, new_amount:31686.0, orig_cost:4.559999942779541, new_cost:4.3604, ratio:0.9562363624572754, last_sale_price:4.37000036239624]
[2021-08-19 10:24:02.968469] INFO: Position: after split: PositionStock(asset:Equity(1453 [600578.SHA]), amount:31686.0, cost_basis:4.3604, last_sale_price:4.570000171661377)
[2021-08-19 10:24:02.969508] INFO: Position: returning cash: 3.1744
[2021-08-19 10:24:04.536690] INFO: Performance: Simulated 488 trading days out of 488.
[2021-08-19 10:24:04.538354] INFO: Performance: first open: 2015-01-05 09:30:00+00:00
[2021-08-19 10:24:04.539676] INFO: Performance: last close: 2016-12-30 15:00:00+00:00
[2021-08-19 10:24:10.537173] INFO: moduleinvoker: backtest.v8 运行完成[17.865702s].
[2021-08-19 10:24:10.538698] INFO: moduleinvoker: trade.v4 运行完成[17.922586s].
[2021-08-19 10:24:10.541084] INFO: moduleinvoker: N_days_performance_statistics.v5 开始运行..
[2021-08-19 10:24:10.886524] INFO: moduleinvoker: N_days_performance_statistics.v5 运行完成[0.345435s].