老师帮忙给我看看,我的策略运行正常,挂上模拟交易怎么出不了股票

求助
标签: #<Tag:0x00007fd33511d2e8>

(gdmmmqfc) #1

老师帮忙给我看看,我的策略运行正常,挂上模拟交易怎么出不了股票。

本代码由可视化策略环境自动生成 2021年2月2日 15:40

本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。

回测引擎:初始化函数,只执行一次

def m21_initialize_bigquant_run(context):
# 加载预测数据
context.ranker_prediction = context.options[‘data’].read_df()

# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
# 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
# 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
stock_count = 2
# 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])
# 设置每只股票占用的最大资金比例
context.max_cash_per_instrument = 0.5
context.options['hold_days'] = 5

回测引擎:每日数据处理函数,每天执行一次

def m21_handle_data_bigquant_run(context, data):
# 按日期过滤得到今日的预测数据
ranker_prediction = context.ranker_prediction[
context.ranker_prediction.date == data.current_dt.strftime(’%Y-%m-%d’)]

# 1. 资金分配
# 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
# 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
cash_avg = context.portfolio.portfolio_value / context.options['hold_days']
cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
positions = {e.symbol: p.amount * p.last_sale_price
             for e, p in context.portfolio.positions.items()}

# 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
if not is_staging and cash_for_sell > 0:
    equities = {e.symbol: e for e, p in context.portfolio.positions.items()}
    instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
            lambda x: x in equities)])))

    for instrument in instruments:
        context.order_target(context.symbol(instrument), 0)
        cash_for_sell -= positions[instrument]
        if cash_for_sell <= 0:
            break

# 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
buy_cash_weights = context.stock_weights
buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
for i, instrument in enumerate(buy_instruments):
    cash = cash_for_buy * buy_cash_weights[i]
    if cash > max_cash_per_instrument - positions.get(instrument, 0):
        # 确保股票持仓量不会超过每次股票最大的占用资金量
        cash = max_cash_per_instrument - positions.get(instrument, 0)
    if cash > 0:
        context.order_value(context.symbol(instrument), cash)

#----------------------------START:持有固定天数卖出---------------------------
today = data.current_dt
# 不是建仓期(在前hold_days属于建仓期)
if not is_staging:
equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
for instrument in equities:

print('last_sale_date: ', equities[instrument].last_sale_date)

        sid = equities[instrument].sid  # 交易标的
        # 今天和上次交易的时间相隔hold_days就全部卖出
        if today-equities[instrument].last_sale_date>=datetime.timedelta(context.options['hold_days']) and data.can_trade(context.symbol(instrument)):
            context.order_target_percent(sid, 0)
#--------------------------------END:持有固定天数卖出---------------------------  

回测引擎:准备数据,只执行一次

def m21_prepare_bigquant_run(context):
pass

g = T.Graph({

'm5': 'M.input_features.v1',
'm5.features': """

#号开始的表示注释,注释需单独一行

多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征

return_0
avg_turn_9/2
(shift(close_0, -1)/shift(open_0, -1)-1)*100
(shift(open_0, -2)/shift(open_0, -1)-1)*100
(shift(close_0, -2)/shift(open_0, -1)-1)*100
(shift(high_0, -2)/shift(open_0, -1)-1)100
100
shift(open_0, -1)/close_0-100

#avg_turn_0
#avg_turn_13
#avg_turn_5
#sum(where(return_0>1,where(turn_0>turn_1,1,-1),where(turn_0<turn_1,1,-1)),10)
daily_return_0

daily_return_1
daily_return_2
#mto=100*shift(open_0, -1)/close_0-100

return_5
return_10
return_20
avg_amount_0/avg_amount_5
avg_amount_5/avg_amount_20
rank_avg_amount_0/rank_avg_amount_5
rank_avg_amount_5/rank_avg_amount_10
rank_return_0
rank_return_5
rank_return_10
rank_return_0/rank_return_5
rank_return_5/rank_return_10
pe_ttm_0

(high_0-open_0/2-close_0/2)/open_010
(high_1-open_1/2-close_1/2)/open_1
10
(open_0/2+close_0/2-low_0)/open_010
(open_1/2+close_1/2-low_1)/open_1
10
(close_0-open_0)/open_0
(close_1-open_1)/open_1
(high_0-open_0/2-close_0/2)/(close_0-open_0)
(high_1-open_1/2-close_1/2)/(close_1-open_1)
rank((high_0-open_0/2-close_0/2)/(close_0-open_0))
rank((high_1-open_1/2-close_1/2)/(close_1-open_1))
(high_0+low_0)/close_1
(high_1+low_1)/close_2
((high_0+low_0)/close_1)/((high_1+low_1)/close_2)
#((high_1+low_1)/close_2)/((high_2+low_2)/close_3)

rank_avg_mf_net_amount_3
#rank_avg_mf_net_amount_0
rank_avg_mf_net_amount_10
rank_avg_mf_net_amount_20

“”",

'm6': 'M.instruments.v2',
'm6.start_date': T.live_run_param('trading_date', '2019-01-02'),
'm6.end_date': T.live_run_param('trading_date', '2020-01-01'),
'm6.market': 'CN_STOCK_A',
'm6.instrument_list': '',
'm6.max_count': 0,

'm4': 'M.general_feature_extractor.v7',
'm4.instruments': T.Graph.OutputPort('m6.data'),
'm4.features': T.Graph.OutputPort('m5.data'),
'm4.start_date': '',
'm4.end_date': '',
'm4.before_start_days': 90,

'm22': 'M.chinaa_stock_filter.v1',
'm22.input_data': T.Graph.OutputPort('m4.data'),
'm22.index_constituent_cond': ['全部'],
'm22.board_cond': ['上证主板', '深证主板', '创业板'],
'm22.industry_cond': ['全部'],
'm22.st_cond': ['正常'],
'm22.delist_cond': ['非退市'],
'm22.output_left_data': False,

'm11': 'M.derived_feature_extractor.v3',
'm11.input_data': T.Graph.OutputPort('m22.data'),
'm11.features': T.Graph.OutputPort('m5.data'),
'm11.date_col': 'date',
'm11.instrument_col': 'instrument',
'm11.drop_na': True,
'm11.remove_extra_columns': True,
'm11.user_functions': {},

'm10': 'M.advanced_auto_labeler.v2',
'm10.instruments': T.Graph.OutputPort('m6.data'),
'm10.label_expr': """# #号开始的表示注释

0. 每行一个,顺序执行,从第二个开始,可以使用label字段

1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html

添加benchmark_前缀,可使用对应的benchmark数据

2. 可用操作符和函数见 表达式引擎 <https://bigquant.com/docs/big_expr.html>_

计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)

shift(close, -5) / shift(open, -1)

极值处理:用1%和99%分位的值做clip

clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))

将分数映射到分类,这里使用20个分类

all_wbins(label, 20)

过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)

where(shift(high, -1) == shift(low, -1), NaN, label)
“”",
‘m10.start_date’: ‘’,
‘m10.end_date’: ‘’,
‘m10.benchmark’: ‘000300.SHA’,
‘m10.drop_na_label’: True,
‘m10.cast_label_int’: True,
‘m10.user_functions’: {},

'm12': 'M.join.v3',
'm12.data1': T.Graph.OutputPort('m10.data'),
'm12.data2': T.Graph.OutputPort('m11.data'),
'm12.on': 'date,instrument',
'm12.how': 'inner',
'm12.sort': False,

'm15': 'M.input_features.v1',
'm15.features': """

#号开始的表示注释,注释需单独一行

多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征

close/shift(close,5)-1
amount+1
ta_sma(close,5)
#rank_sh_holder_num_0

“”",

'm19': 'M.index_feature_extract.v3',
'm19.input_1': T.Graph.OutputPort('m6.data'),
'm19.input_2': T.Graph.OutputPort('m15.data'),
'm19.before_days': 100,
'm19.index': '000300.HIX',

'm1': 'M.join.v3',
'm1.data1': T.Graph.OutputPort('m19.data_1'),
'm1.data2': T.Graph.OutputPort('m12.data'),
'm1.on': 'date',
'm1.how': 'inner',
'm1.sort': False,

'm7': 'M.features_add.v1',
'm7.input_1': T.Graph.OutputPort('m19.data_2'),
'm7.input_2': T.Graph.OutputPort('m5.data'),

'm8': 'M.stock_ranker_train.v6',
'm8.training_ds': T.Graph.OutputPort('m1.data'),
'm8.features': T.Graph.OutputPort('m7.data_1'),
'm8.learning_algorithm': '排序',
'm8.number_of_leaves': 30,
'm8.minimum_docs_per_leaf': 1000,
'm8.number_of_trees': 20,
'm8.learning_rate': 0.5,
'm8.max_bins': 1023,
'm8.feature_fraction': 1,
'm8.data_row_fraction': 1,
'm8.ndcg_discount_base': 1,
'm8.m_lazy_run': False,

'm16': 'M.instruments.v2',
'm16.start_date': T.live_run_param('trading_date', '2020-01-01'),
'm16.end_date': T.live_run_param('trading_date', '2021-02-02'),
'm16.market': 'CN_STOCK_A',
'm16.instrument_list': '',
'm16.max_count': 0,

'm17': 'M.general_feature_extractor.v7',
'm17.instruments': T.Graph.OutputPort('m16.data'),
'm17.features': T.Graph.OutputPort('m5.data'),
'm17.start_date': '',
'm17.end_date': '',
'm17.before_start_days': 90,

'm3': 'M.chinaa_stock_filter.v1',
'm3.input_data': T.Graph.OutputPort('m17.data'),
'm3.index_constituent_cond': ['全部'],
'm3.board_cond': ['上证主板', '深证主板', '创业板'],
'm3.industry_cond': ['全部'],
'm3.st_cond': ['正常'],
'm3.delist_cond': ['非退市'],
'm3.output_left_data': False,

'm18': 'M.derived_feature_extractor.v3',
'm18.input_data': T.Graph.OutputPort('m3.data'),
'm18.features': T.Graph.OutputPort('m5.data'),
'm18.date_col': 'date',
'm18.instrument_col': 'instrument',
'm18.drop_na': True,
'm18.remove_extra_columns': True,
'm18.user_functions': {},

'm14': 'M.dropnan.v2',
'm14.input_data': T.Graph.OutputPort('m18.data'),

'm13': 'M.index_feature_extract.v3',
'm13.input_1': T.Graph.OutputPort('m16.data'),
'm13.input_2': T.Graph.OutputPort('m15.data'),
'm13.before_days': 100,
'm13.index': '000300.HIX',

'm2': 'M.join.v3',
'm2.data1': T.Graph.OutputPort('m13.data_1'),
'm2.data2': T.Graph.OutputPort('m14.data'),
'm2.on': 'date',
'm2.how': 'inner',
'm2.sort': False,

'm20': 'M.filter.v3',
'm20.input_data': T.Graph.OutputPort('m2.data'),
'm20.expr': 'daily_return_0>1.095',
'm20.output_left_data': False,

'm9': 'M.stock_ranker_predict.v5',
'm9.model': T.Graph.OutputPort('m8.model'),
'm9.data': T.Graph.OutputPort('m20.data'),
'm9.m_lazy_run': False,

'm21': 'M.trade.v4',
'm21.instruments': T.Graph.OutputPort('m16.data'),
'm21.options_data': T.Graph.OutputPort('m9.predictions'),
'm21.start_date': '',
'm21.end_date': '',
'm21.initialize': m21_initialize_bigquant_run,
'm21.handle_data': m21_handle_data_bigquant_run,
'm21.prepare': m21_prepare_bigquant_run,
'm21.volume_limit': 0.025,
'm21.order_price_field_buy': 'close',
'm21.order_price_field_sell': 'close',
'm21.capital_base': 1000000,
'm21.auto_cancel_non_tradable_orders': True,
'm21.data_frequency': 'daily',
'm21.price_type': '真实价格',
'm21.product_type': '股票',
'm21.plot_charts': True,
'm21.backtest_only': False,
'm21.benchmark': '000300.SHA',

})

g.run({})

def m23_param_grid_builder_bigquant_run():
param_grid = {}

# 在这里设置需要调优的参数备选
#param_grid['m3.features'] = ['close_1/close_0', 'close_2/close_0\nclose_3/close_0']
param_grid['m8.number_of_trees'] = [3, 5, 7]
#param_grid['m21.volume_limit'] = [0.025, 0.03]


return param_grid

def m23_scoring_bigquant_run(result):
score = result.get(‘m21’).read_raw_perf()[‘sharpe’].tail(1)[0]
#result.get(‘m19’).display()
result[‘m21’].display()
return score

m23 = M.hyper_parameter_search.v1(
param_grid_builder=m23_param_grid_builder_bigquant_run,
scoring=m23_scoring_bigquant_run,
search_algorithm=‘随机搜索’,
search_iterations=2,
workers=1,
worker_distributed_run=True,
worker_silent=False,
run_now=True,
bq_graph=g
)