复制链接
克隆策略
In [13]:
# 本代码由可视化策略环境自动生成 2022年7月19日 23:48
# 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。


# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m2_run_bigquant_run(input_1, input_2, input_3,start_date_input,end_date_input):
    # 示例代码如下。在这里编写您的代码
    df = DataSource("bar1d_CN_CONBOND").read(start_date=start_date_input, end_date=end_date_input)
    df1 = DataSource("market_performance_CN_CONBOND").read(start_date=start_date_input, end_date=end_date_input)
    df2 = df.drop(['close'],axis = 1)
    df3 = pd.merge(df1,df2,on=['date','instrument'],how='inner')
    data_1 = DataSource.write_df(df3)
    data_2 = DataSource.write_df(df3)
    return Outputs(data_1=data_1, data_2=data_2, data_3=None)

# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m2_post_run_bigquant_run(outputs):
    return outputs

# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m14_run_bigquant_run(input_1, input_2, input_3, stock_count, hold_days):
    # 示例代码如下。在这里编写您的代码
    param = {
        "stock_count": stock_count,
        "hold_days": hold_days
        }
    data_1 = DataSource.write_pickle(param)
    return Outputs(data_1=data_1, data_2=None, data_3=None)

# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m14_post_run_bigquant_run(outputs):
    return outputs

# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m1_run_bigquant_run(input_1, input_2, input_3):
    start_date_input = input_1.read()['start_date']
    end_date_input = input_1.read()['end_date']
    # 示例代码如下。在这里编写您的代码
    df = DataSource("bar1d_CN_CONBOND").read(start_date=start_date_input, end_date=end_date_input)
    df1 = DataSource("market_performance_CN_CONBOND").read(start_date=start_date_input, end_date=end_date_input)
    df2 = df.drop(['close'],axis = 1)
    df3 = pd.merge(df1,df2,on=['date','instrument'],how='inner')
    data_1 = DataSource.write_df(df3)
    data_2 = DataSource.write_df(df3)
    return Outputs(data_1=data_1, data_2=data_2, data_3=None)

# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m1_post_run_bigquant_run(outputs):
    return outputs

def del_input(input_1):
    df = input_1.read_df()
    df = df.drop(["trigger_cond_item_desc",'revise_item_desc','trigger_item_desc'],axis=1)
    df = df.dropna(axis=0, how='all', thresh=None, subset=None, inplace=False)
    print(df.columns)
    #df.sort_values(by=['date','double_low'],axis=0,ascending=True,inplace = True)
    df = df.sort_index(axis = 1)
    df = df.reset_index(drop = True)
    df = df.groupby('date').head(10)
    #print(df[['double_low','date']])
    data_1 = DataSource.write_df(df)
    return data_1
# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m23_run_bigquant_run(input_1, input_2, input_3):
    data_1 = del_input(input_1)
    data_2 = del_input(input_2)
    return Outputs(data_1=data_1, data_2=data_2, data_3=None)
# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m23_post_run_bigquant_run(outputs):
    return outputs

# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def m11_run_bigquant_run(input_1, input_2, input_3):
    # 示例代码如下。在这里编写您的代码
    print('m11.input1',input_1)
    df = input_1.read()
    param = input_2.read()
    
    data = {
        "param": param,
        "data": df
    }
    data_1 = DataSource.write_pickle(data)
    return Outputs(data_1=data_1, data_2=None, data_3=None)

# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
def m11_post_run_bigquant_run(outputs):
    return outputs

# 回测引擎:初始化函数,只执行一次
def m21_initialize_bigquant_run(context):
    print('初始化函数开始:')
    print('context.options',context.options)
    # 加载预测数据
    context.ranker_prediction = context.options.get('data').read()['data']
    context.param = context.options['data'].read()["param"]
    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
    context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0003, min_cost=5))
    # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
    # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
    stock_count = context.param["stock_count"]
    # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[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.4
    context.hold_days = context.param["hold_days"]
    print('初始化函数结束')

# 交易引擎:每个单位时间开盘前调用一次。
def m21_before_trading_start_bigquant_run(context, data):
    # 盘前处理,订阅行情等
    print('订阅行情前',data)
    context.subscribe(context.instruments)
    print('订阅行情后',data)
    pass

# 交易引擎:tick数据处理函数,每个tick执行一次
def m21_handle_tick_bigquant_run(context, tick):
    pass

import math
# 回测引擎:每日数据处理函数,每天执行一次
def m21_handle_data_bigquant_run(context, data):
    print('当前日期data.current_dt',data.current_dt)
    print('data',data)
    try:
        context.ranker_prediction = context.options.get('data').read()['data']
        # 相隔几天(hold_days)进行一下换仓
        if context.trading_day_index % context.hold_days != 0:
            return 

        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        # 目前持仓
        positions = {e: p.amount * p.last_sale_price for e, p in context.portfolio.positions.items()}
        # 权重
        buy_cash_weights = context.stock_weights
        # 今日买入股票列表
        stock_to_buy = list(ranker_prediction.instrument[:len(buy_cash_weights)])
        # 持仓上限
        max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
        print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
        stock_hold_now = [equity for equity in context.portfolio.positions ]
        # 继续持有的股票:调仓时,如果买入的股票已经存在于目前的持仓里,那么应继续持有
        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,
                #   即卖出全部股票,可参考回测文档
                print('卖出order target percent',context.symbol(stock))
                print('卖出结果',context.order_target_percent(context.symbol(stock), 0))

        # 如果当天没有买入的股票,就返回
        if len(stock_to_buy) == 0:
            return

        # 买入
        print('买入列表',stock_to_buy)
        for i, instrument in enumerate(stock_to_buy):
            cash = context.portfolio.portfolio_value * 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 > 500:
                cash = int(math.floor(cash))
                print('买入order_value',context.symbol(instrument),' cash ',cash)
                print(context.order_value(context.symbol(instrument), cash))
    except Exception as e:
        print('抛出异常',e)
# 交易引擎:成交回报处理函数,每个成交发生时执行一次
def m21_handle_trade_bigquant_run(context, trade):
    pass

# 交易引擎:委托回报处理函数,每个委托变化时执行一次
def m21_handle_order_bigquant_run(context, order):
    pass

# 交易引擎:盘后处理函数,每日盘后执行一次
def m21_after_trading_bigquant_run(context, data):
    pass


m3 = M.input_features.v1(
    features="""# #号开始的表示注释
# 多个特征,每行一个,可以包含基础特征和衍生特征
double_low = close + bond_prem_ratio
remain_size
rank_swing_volatility_5 = nanstd((high-low)/pre_close, 5)*sqrt(200)*100"""
)

m2 = M.cached.v3(
    run=m2_run_bigquant_run,
    post_run=m2_post_run_bigquant_run,
    input_ports='',
    params="""{"start_date_input":"2017-06-01",
"end_date_input":"2019-11-01"}""",
    output_ports=''
)

m10 = M.auto_labeler_on_datasource.v1(
    input_data=m2.data_1,
    label_expr="""# #号开始的表示注释
# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.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, 10)

# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
where(shift(high, -1) == shift(low, -1), NaN, label)
""",
    drop_na_label=True,
    cast_label_int=True,
    date_col='date',
    instrument_col='instrument',
    user_functions={}
)

m14 = M.cached.v3(
    run=m14_run_bigquant_run,
    post_run=m14_post_run_bigquant_run,
    input_ports='',
    params="""{
    "stock_count": 4,
    "hold_days": 1 
}""",
    output_ports=''
)

m4 = M.instruments.v2(
    start_date=T.live_run_param('trading_date', '2021-06-18'),
    end_date=T.live_run_param('trading_date', '2021-06-18'),
    market='CN_CONBOND',
    instrument_list='',
    max_count=0
)

m1 = M.cached.v3(
    input_1=m4.data,
    run=m1_run_bigquant_run,
    post_run=m1_post_run_bigquant_run,
    input_ports='',
    params='{}',
    output_ports=''
)

m23 = M.cached.v3(
    input_1=m2.data_2,
    input_2=m1.data_2,
    run=m23_run_bigquant_run,
    post_run=m23_post_run_bigquant_run,
    input_ports='',
    params='{}',
    output_ports='',
    m_cached=False
)

m16 = M.derived_feature_extractor.v3(
    input_data=m23.data_1,
    features=m3.data,
    date_col='date',
    instrument_col='instrument',
    drop_na=False,
    remove_extra_columns=False
)

m7 = M.join.v3(
    data1=m10.data,
    data2=m16.data,
    on='date,instrument',
    how='inner',
    sort=False
)

m6 = M.stock_ranker_train.v6(
    training_ds=m7.data,
    features=m3.data,
    learning_algorithm='排序',
    number_of_leaves=3,
    minimum_docs_per_leaf=100,
    number_of_trees=20,
    learning_rate=0.1,
    max_bins=1023,
    feature_fraction=1,
    data_row_fraction=1,
    plot_charts=True,
    ndcg_discount_base=1,
    m_lazy_run=False,
    m_cached=False
)

m18 = M.derived_feature_extractor.v3(
    input_data=m23.data_2,
    features=m3.data,
    date_col='date',
    instrument_col='instrument',
    drop_na=False,
    remove_extra_columns=False
)

m8 = M.stock_ranker_predict.v5(
    model=m6.model,
    data=m18.data,
    m_lazy_run=False
)

m11 = M.cached.v3(
    input_1=m8.predictions,
    input_2=m14.data_1,
    run=m11_run_bigquant_run,
    post_run=m11_post_run_bigquant_run,
    input_ports='',
    params='{}',
    output_ports=''
)

m12 = M.trade_data_generation.v1(
    input=m1.data_2,
    category='CN_STOCK',
    m_cached=False
)

m21 = M.hftrade.v2(
    instruments=m12.instrument_list,
    options_data=m11.data_1,
    start_date='',
    end_date='',
    initialize=m21_initialize_bigquant_run,
    before_trading_start=m21_before_trading_start_bigquant_run,
    handle_tick=m21_handle_tick_bigquant_run,
    handle_data=m21_handle_data_bigquant_run,
    handle_trade=m21_handle_trade_bigquant_run,
    handle_order=m21_handle_order_bigquant_run,
    after_trading=m21_after_trading_bigquant_run,
    capital_base=1000000,
    frequency='daily',
    price_type='真实价格',
    product_type='可转债',
    before_start_days='80',
    order_price_field_buy='open',
    order_price_field_sell='close',
    benchmark='000300.HIX',
    plot_charts=True,
    disable_cache=False,
    replay_bdb=False,
    show_debug_info=True,
    backtest_only=False
)
Index(['remain_size', 'instrument', 'equ_trading_code', 'conversion_chg_pct',
       'date', 'conversion_price', 'name_x', 'trading_code',
       'conversion_chg_pct_week', 'bond_prem_ratio', 'equ_name',
       'redemption_price', 'close_equ', 'total_size', 'pure_bond_prem_ratio',
       'pure_bond_ratio', 'close', 'pre_close', 'name_y', 'open', 'high',
       'low', 'deal_number', 'volume', 'amount', 'accrued_interest',
       'yield_to_maturity', 'vwap', 'gross_close', 'net_close'],
      dtype='object')
Index(['remain_size', 'instrument', 'equ_trading_code', 'conversion_chg_pct',
       'date', 'conversion_price', 'name_x', 'trading_code',
       'conversion_chg_pct_week', 'bond_prem_ratio', 'equ_name',
       'redemption_price', 'close_equ', 'total_size', 'pure_bond_prem_ratio',
       'pure_bond_ratio', 'close', 'pre_close', 'name_y', 'open', 'high',
       'low', 'deal_number', 'volume', 'amount', 'accrued_interest',
       'yield_to_maturity', 'vwap', 'gross_close', 'net_close'],
      dtype='object')
设置评估测试数据集,查看训练曲线
[视频教程]StockRanker训练曲线
bigcharts-data-start/{"__type":"tabs","__id":"bigchart-ed45543c6b8543318862d8c6994bef38"}/bigcharts-data-end
m11.input1 DataSource(b459c9890c444983af97b7c53788aa97T)
2022-07-22 15:42:05.582847 init history datas... 
2022-07-22 15:42:05.584111 init history datas done. 
2022-07-22 15:42:05.590776 run_backtest() capital_base:1000000, frequency:1d, product_type:conbond, date:2021-06-18 ~ 2021-06-18 
2022-07-22 15:42:05.591081 run_backtest() running... 
2022-07-22 15:42:05.597435 initial contracts len=0 
2022-07-22 15:42:05.598190 backtest inited. 
初始化函数开始:
context.options {'data': DataSource(e707eada9d2a4fe8a381dccce7eddc7aT)}
初始化函数结束
2022-07-22 15:42:05.636701 backtest transforming 1d, bars=1... 
2022-07-22 15:42:05.636972 transform start_trading_day=2021-06-18 00:00:00, simulation period=2021-06-18 ~ 2021-06-18 
2022-07-22 15:42:05.637008 transform source=None, before_start_days=80 
2022-07-22 15:42:05.637035 transform replay_func=<cyfunction BacktestEngine.transform.<locals>.replay_bars_dt at 0x7f24dc163d40> 
订阅行情前 BarDatas(current_dt:2021-06-18 08:30:00)
订阅行情后 BarDatas(current_dt:2021-06-18 08:30:00)
当前日期data.current_dt 2021-06-18 15:00:00
data BarDatas(current_dt:2021-06-18 15:00:00)
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
买入列表 ['127028.ZCB', '110048.HCB', '128128.ZCB', '127005.ZCB']
买入order_value Equity(157 [127028.ZCB])  cash  390380
0
买入order_value Equity(334 [110048.HCB])  cash  246302
0
买入order_value Equity(153 [128128.ZCB])  cash  195190
0
买入order_value Equity(360 [127005.ZCB])  cash  168127
0
2022-07-22 15:42:05.711699 backtest run end! 
2022-07-22 15:42:05.729670 run_backtest() finished! time cost 0.139s! 
2022-07-22 15:42:06.942210 perf_render raw_perf=DataSource(820720f972e6498d9c235dba32a84562T), benchmark_data=DataSource(82a126875eb2406c86f9c8193f60b535T), process stats...
2022-07-22 15:42:07.261048 perf_render process transactions...
2022-07-22 15:42:07.315096 perf_render process positions...
2022-07-22 15:42:07.365716 perf_render process logs...
2022-07-22 15:42:07.480339 perf_render process plot...
  • 收益率0.0%
  • 年化收益率nan%
  • 基准收益率0.0%
  • 阿尔法nan
  • 贝塔nan
  • 夏普比率nan
  • 胜率0.0
  • 盈亏比0.0
  • 收益波动率nan%
  • 信息比率nan
  • 最大回撤0.0%
bigcharts-data-start/{"__type":"tabs","__id":"bigchart-283406f5363e4b1ea35bbeb1f9a674a4"}/bigcharts-data-end