# 本代码由可视化策略环境自动生成 2022年10月25日 15:52
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
pd.set_option('display.max_rows',None)
# 回测引擎:初始化函数,只执行一次
def m5_initialize_bigquant_run(context):
# 加载股票指标数据,数据继承自m6模块
context.indicator_data = context.options['data'].read_df()
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
# 设置股票数量
context.stock_num = 5
# 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次
context.rebalance_days = 22
# context.rebalance_days = 2
# 如果策略运行中,需要将数据进行保存,可以借用extension这个对象,类型为dict
# 比如当前运行的k线的索引,比如个股持仓天数、买入均价
# print('context.extension',context.extension)
if 'index' not in context.extension:
context.extension['index'] = 0
# print('context.extension',context.extension)
# 回测引擎:每日数据处理函数,每天执行一次
def m5_handle_data_bigquant_run(context, data):
# 不在换仓日就return,相当于后面的代码只会一个月运行一次,买入的股票会持有1个月
if context.extension['index'] % context.rebalance_days != 0:
return
context.extension['index'] += 1
# 当前的日期
date = data.current_dt.strftime('%Y-%m-%d')
print('date',date)
cur_data = context.indicator_data[context.indicator_data['date'] == date]
# print('cur_data',cur_data)
# print('indicator_dat',context.indicator_dat)
# 根据日期获取调仓需要买入的股票的列表
stock_to_buy = list(cur_data.instrument[:context.stock_num])
print('stock_to_buy',stock_to_buy)
# 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
stock_hold_now = [equity.symbol for equity in context.portfolio.positions]
# print('stock_hold_now',stock_hold_now)
# 继续持有的股票:调仓时,如果买入的股票已经存在于目前的持仓里,那么应继续持有
no_need_to_sell = [i for i in stock_hold_now if i in stock_to_buy]
# 需要卖出的股票
stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]
# 卖出
for stock in stock_to_sell:
# 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态
# 如果返回真值,则可以正常下单,否则会出错
# 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式
if data.can_trade(context.symbol(stock)):
# order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,
# 即卖出全部股票,可参考回测文档
context.order_target_percent(context.symbol(stock), 0)
# 如果当天没有买入的股票,就返回
if len(stock_to_buy) == 0:
return
# 等权重买入
weight = 1 / len(stock_to_buy)
# 买入
for stock in stock_to_buy:
if data.can_trade(context.symbol(stock)):
# 下单使得某只股票的持仓权重达到weight,因为
# weight大于0,因此是等权重买入
context.order_target_percent(context.symbol(stock), weight)
# 回测引擎:准备数据,只执行一次
def m5_prepare_bigquant_run(context):
pass
# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
def m5_before_trading_start_bigquant_run(context, data):
pass
m1 = M.instruments.v2(
start_date=T.live_run_param('trading_date', '2022-08-24'),
end_date=T.live_run_param('trading_date', '2022-10-25'),
market='CN_STOCK_A',
instrument_list='',
max_count=0
)
m2 = M.input_features.v1(
features="""market_cap_float_0
amount_0"""
)
m3 = M.general_feature_extractor.v7(
instruments=m1.data,
features=m2.data,
start_date='',
end_date='',
before_start_days=1
)
m4 = M.sort.v4(
input_ds=m3.data,
sort_by='market_cap_float_0',
group_by='instrument',
keep_columns='--',
ascending=True
)
m6 = M.filter.v3(
input_data=m4.sorted_data,
expr='amount_0 > 10000',
output_left_data=False
)
m5 = M.trade.v4(
instruments=m1.data,
options_data=m6.data,
start_date='',
end_date='',
initialize=m5_initialize_bigquant_run,
handle_data=m5_handle_data_bigquant_run,
prepare=m5_prepare_bigquant_run,
before_trading_start=m5_before_trading_start_bigquant_run,
volume_limit=0.025,
order_price_field_buy='open',
order_price_field_sell='open',
capital_base=1000000,
auto_cancel_non_tradable_orders=True,
data_frequency='daily',
price_type='前复权',
product_type='股票',
plot_charts=True,
backtest_only=False,
benchmark=''
)
[2022-10-27 10:46:56.616870] INFO: moduleinvoker: instruments.v2 开始运行..
[2022-10-27 10:46:57.052664] INFO: moduleinvoker: instruments.v2 运行完成[0.435798s].
[2022-10-27 10:46:57.083882] INFO: moduleinvoker: input_features.v1 开始运行..
[2022-10-27 10:46:57.104283] INFO: moduleinvoker: 命中缓存
[2022-10-27 10:46:57.106901] INFO: moduleinvoker: input_features.v1 运行完成[0.023041s].
[2022-10-27 10:46:57.186089] INFO: moduleinvoker: general_feature_extractor.v7 开始运行..
[2022-10-27 10:46:59.178007] INFO: 基础特征抽取: 年份 2022, 特征行数=196724
[2022-10-27 10:46:59.241228] INFO: 基础特征抽取: 总行数: 196724
[2022-10-27 10:46:59.257585] INFO: moduleinvoker: general_feature_extractor.v7 运行完成[2.071516s].
[2022-10-27 10:46:59.284834] INFO: moduleinvoker: sort.v4 开始运行..
[2022-10-27 10:47:00.303098] INFO: moduleinvoker: sort.v4 运行完成[1.018259s].
[2022-10-27 10:47:00.328792] INFO: moduleinvoker: filter.v3 开始运行..
[2022-10-27 10:47:00.357079] INFO: filter: 使用表达式 amount_0 > 10000 过滤
[2022-10-27 10:47:01.085973] INFO: filter: 过滤 /data, 196719/0/196724
[2022-10-27 10:47:01.121703] INFO: moduleinvoker: filter.v3 运行完成[0.792892s].
[2022-10-27 10:47:07.272617] INFO: moduleinvoker: backtest.v8 开始运行..
[2022-10-27 10:47:07.281956] INFO: backtest: biglearning backtest:V8.6.3
[2022-10-27 10:47:07.284813] INFO: backtest: product_type:stock by specified
[2022-10-27 10:47:07.478680] INFO: moduleinvoker: cached.v2 开始运行..
[2022-10-27 10:47:18.701827] INFO: backtest: 读取股票行情完成:1451991
[2022-10-27 10:47:20.422327] INFO: moduleinvoker: cached.v2 运行完成[12.943649s].
[2022-10-27 10:47:30.776187] INFO: backtest: algo history_data=DataSource(dd1b49c6eadd4dcc9783e38ec1b9fddeT)
[2022-10-27 10:47:30.780420] INFO: algo: TradingAlgorithm V1.8.8
[2022-10-27 10:47:31.831835] INFO: algo: trading transform...
[2022-10-27 10:47:32.412164] INFO: algo: handle_splits get splits [dt:2022-10-19 00:00:00+00:00] [asset:Equity(4324 [833943.BJA]), ratio:0.9780938029289246]
[2022-10-27 10:47:32.416204] INFO: Position: position stock handle split[sid:4324, orig_amount:3400, new_amount:3476.0, orig_cost:7.17044299104968, new_cost:7.0134, ratio:0.9780938029289246, last_sale_price:8.929996490478516]
[2022-10-27 10:47:32.426220] INFO: Position: after split: PositionStock(asset:Equity(4324 [833943.BJA]), amount:3476.0, cost_basis:7.0134, last_sale_price:9.130000114440918)
[2022-10-27 10:47:32.445229] INFO: Position: returning cash: 1.3324
[2022-10-27 10:47:32.487464] INFO: Performance: Simulated 39 trading days out of 39.
[2022-10-27 10:47:32.489830] INFO: Performance: first open: 2022-08-24 09:30:00+00:00
[2022-10-27 10:47:32.492534] INFO: Performance: last close: 2022-10-25 15:00:00+00:00
[2022-10-27 10:47:34.997128] INFO: moduleinvoker: backtest.v8 运行完成[27.724508s].
[2022-10-27 10:47:35.002805] INFO: moduleinvoker: trade.v4 运行完成[33.839426s].