港股—AI选股策略

策略分享
标签: #<Tag:0x00007f3143191da8>

(brantyz) #1

现在可以使用港股数据进行回测研究了,下面是示例代码。和A股模板策略相比,改了如下几处:
1.获取股票列表,需要指定港股市场, D.instruments(start_date, split_date,market=‘HK_STOCK’)
2.回测时指定benchmark为恒生指数HSI.HKEX,或者国企指数HSCEI.HKEX
3.训练时,需要过滤掉交易量较小的股票,否则策略可能偏向买这种成交量很小的股票。
4.回测时,买入列表同样需要过滤掉成交量较小的股票

目前港股支持的因子请参考https://bigquant.com/docs/data_features.html
网页表格适用市场这一列包含港股的是因子,才能在港股市场使用。

详细策略如下:

克隆策略
In [4]:
# 基础参数配置
class conf:
    start_date = '2010-01-01'
    end_date='2017-08-01'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2015-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, split_date,market='HK_STOCK')

    # 机器学习目标标注函数
    # 如下标注函数等价于 min(max((持有期间的收益 * 100), -20), 20) + 20 (后面的M.fast_auto_labeler会做取整操作)
    # 说明:max/min这里将标注分数限定在区间[-20, 20],+20将分数变为非负数 (StockRanker要求标注分数非负整数)
    label_expr = ['return * 100', 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(20)]
    # 持有天数,用于计算label_expr中的return值(收益)
    hold_days = 5

    # 特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征
    features = [
        'rank_return_20',  # 20日收益排名
        'ta_sma_10_0/ta_sma_20_0',
        'ta_sma_20_0/ta_sma_30_0',
        'ta_sma_30_0/ta_sma_60_0',
        'ta_rsi_14_0',
        'ta_rsi_28_0',
        'close_5/close_0', 
        'close_1/open_0', 
        'close_0/open_0', 
        'high_0/low_0',
        'close_1/close_0',  
        'close_2/close_0', 
        'close_3/close_0',  
        'close_4/close_0', 
        'amount_1/amount_0', 
        'amount_2/amount_0',  
        'amount_3/amount_0', 
        'amount_4/amount_0', 
        'amount_5/amount_0', 
    ]

conf.label_expr = [
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    'shift(close, - %s) / shift(open, -1) - 1'%conf.hold_days,
#     极值处理:用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)'
]

m1 = M.advanced_auto_labeler.v1(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    label_expr=conf.label_expr, benchmark=None,cast_label_int=True)

# 将最近20天平均交易量较小的数据过滤掉
def filter_by_amount(ds,start_date,end_date):
    filter_field='avg_amount_20'
    filter_df = D.features(D.instruments(market='HK_STOCK'),start_date=start_date,end_date=end_date, fields=[filter_field])
    filter_df = filter_df[filter_df[filter_field]>1000000]
    base_df = ds.read_df()
    print('原始数据行数是%s'% len(base_df))
    base_df = filter_df.merge(base_df, on=['date','instrument'], how='inner')
    base_df.drop(filter_field, inplace=True, axis=1)
    print('过滤后数据行数是%s'% len(base_df))
    new_ds = DataSource.write_df(base_df)
    return Outputs(data=new_ds)
m2 = M.cached.v3(run=filter_by_amount, kwargs={'ds':m1.data, 'start_date':conf.start_date, 'end_date':conf.split_date})
# 计算特征数据
m3 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    features=conf.features)
# 衍生特征计算,比如 ta_sma_10_0/ta_sma_20_0 相除计算
m3_1 = M.derived_feature_extractor.v1(data=m3.data, features=conf.features)
# 数据预处理:缺失数据处理,数据规范化
m4 = M.transform.v2(data=m3_1.data, transforms=None, drop_null=True)
# 合并标注和特征数据
m5 = M.join.v2(data1=m2.data, data2=m4.data, on=['date', 'instrument'], sort=True)
# StockRanker机器学习训练
m6 = M.stock_ranker_train.v5(training_ds=m5.data, features=conf.features)


## 量化回测 https://bigquant.com/docs/module_trade.html
# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    n1 = M.general_feature_extractor.v5(
        instruments=D.instruments(market='HK_STOCK'),
        start_date=context.start_date, end_date=context.end_date,
        model_id=context.options['model_id'])
    n2 = M.derived_feature_extractor.v1(data=n1.data, model_id=context.options['model_id'])
    n3 = M.transform.v2(data=n2.data, transforms=None, drop_null=True)
    n4 = M.stock_ranker_predict.v5(model=context.options['model_id'], data=n3.data)
    context.instruments = n4.instruments
    context.options['predictions'] = n4.predictions

# 回测引擎:初始化函数,只执行一次
def initialize(context):
    # 加载预测数据
    global filter_df
    context.ranker_prediction = context.options['predictions'].read_df()
    filter_field = 'avg_amount_20'
    filter_df = D.features(context.instruments, fields=[filter_field],start_date=context.start_date, end_date=context.end_date)
    filter_df = filter_df[filter_df[filter_field]>40000000]
    context.filter_df = filter_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.2

# 回测引擎:每日数据处理函数,每天执行一次
def handle_data(context, data):
    # 按日期过滤得到今日的预测数据
    ranker_prediction = context.ranker_prediction[
        context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
    # 如果交易量过小,不买入
    can_buy_instruments = set(context.filter_df[context.filter_df.date == data.current_dt.date()].instrument)

    # 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.perf_tracker.position_tracker.positions.items()}

    # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
    if not is_staging and cash_for_sell > 0:
        equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
        instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
        # print('rank order for sell %s' % instruments)
        for instrument in instruments:
            context.order_target(context.symbol(instrument), 0)
            cash_for_sell -= positions[instrument]
            if cash_for_sell <= 0:
                break

    # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票
    buy_cash_weights = context.stock_weights
    buy_instruments = [instrument for instrument in list(ranker_prediction.instrument) if instrument in can_buy_instruments][: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)


# 调用交易引擎
m7 = M.trade.v2(
    instruments=None,
    start_date=conf.split_date,
    end_date=conf.end_date,
    prepare=prepare,
    initialize=initialize,
    handle_data=handle_data,
    order_price_field_buy='open',       # 表示 开盘 时买入
    order_price_field_sell='close',     # 表示 收盘 前卖出
    capital_base=100000,               # 初始资金
    benchmark='HSI.HKEX',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m6.model_id},
)
[2017-09-04 10:38:07.995642] INFO: bigquant: advanced_auto_labeler.v1 开始运行..
[2017-09-04 10:38:07.998563] INFO: bigquant: 命中缓存
[2017-09-04 10:38:07.999506] INFO: bigquant: advanced_auto_labeler.v1 运行完成[0.00392s].
[2017-09-04 10:38:08.009707] INFO: bigquant: cached.v3 开始运行..
[2017-09-04 10:38:08.025414] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.026889] INFO: bigquant: cached.v3 运行完成[0.017184s].
[2017-09-04 10:38:08.038373] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-04 10:38:08.048711] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.049673] INFO: bigquant: general_feature_extractor.v5 运行完成[0.011291s].
[2017-09-04 10:38:08.057330] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-04 10:38:08.062082] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.063338] INFO: bigquant: derived_feature_extractor.v1 运行完成[0.005995s].
[2017-09-04 10:38:08.072366] INFO: bigquant: transform.v2 开始运行..
[2017-09-04 10:38:08.075104] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.075985] INFO: bigquant: transform.v2 运行完成[0.003617s].
[2017-09-04 10:38:08.084183] INFO: bigquant: join.v2 开始运行..
[2017-09-04 10:38:08.087302] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.088182] INFO: bigquant: join.v2 运行完成[0.004012s].
[2017-09-04 10:38:08.098192] INFO: bigquant: stock_ranker_train.v5 开始运行..
[2017-09-04 10:38:08.103437] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.104349] INFO: bigquant: stock_ranker_train.v5 运行完成[0.00618s].
[2017-09-04 10:38:08.135697] INFO: bigquant: backtest.v7 开始运行..
[2017-09-04 10:38:08.163689] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-04 10:38:08.166970] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.168036] INFO: bigquant: general_feature_extractor.v5 运行完成[0.004359s].
[2017-09-04 10:38:08.178690] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-04 10:38:08.182051] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.183157] INFO: bigquant: derived_feature_extractor.v1 运行完成[0.004457s].
[2017-09-04 10:38:08.194934] INFO: bigquant: transform.v2 开始运行..
[2017-09-04 10:38:08.198458] INFO: bigquant: 命中缓存
[2017-09-04 10:38:08.199399] INFO: bigquant: transform.v2 运行完成[0.00449s].
[2017-09-04 10:38:08.211146] INFO: bigquant: stock_ranker_predict.v5 开始运行..
[2017-09-04 10:38:14.666390] INFO: df2bin: prepare data: prediction ..
[2017-09-04 10:38:32.351890] INFO: stock_ranker_predict: 准备预测: 1060795 行
[2017-09-04 10:38:50.552077] INFO: bigquant: stock_ranker_predict.v5 运行完成[42.340949s].
[2017-09-04 10:39:19.444647] INFO: Performance: Simulated 635 trading days out of 635.
[2017-09-04 10:39:19.445943] INFO: Performance: first open: 2015-01-02 14:30:00+00:00
[2017-09-04 10:39:19.447090] INFO: Performance: last close: 2017-08-01 20:00:00+00:00
[注意] 有 793 笔卖出是在多天内完成的。当日卖出股票超过了当日股票交易的2.5%会出现这种情况。
  • 收益率20.62%
  • 年化收益率7.72%
  • 基准收益率16.67%
  • 阿尔法0.02
  • 贝塔0.71
  • 夏普比率0.1
  • 收益波动率33.17%
  • 信息比率0.05
  • 最大回撤42.19%
[2017-09-04 10:39:22.282496] INFO: bigquant: backtest.v7 运行完成[74.146758s].
In [ ]:
 

[量化学堂-新手专区]BigQuant=人工智能+量化投资
(Apollo) #2

回测引擎没有成交量占比限制吗


(brantyz) #3

有, 下面的volume_limit就是用来设置的,默认是0.025,0是不限制。

调用交易引擎

m7 = M.trade.v2(
instruments=None,
start_date=conf.split_date,
end_date=conf.end_date,
prepare=prepare,
initialize=initialize,
handle_data=handle_data,
order_price_field_buy=‘open’, # 表示 开盘 时买入
order_price_field_sell=‘close’, # 表示 收盘 前卖出
capital_base=100000, # 初始资金
benchmark=‘HSI.HKEX’, # 比较基准,不影响回测结果
# 通过 options 参数传递预测数据和参数给回测引擎
options={‘hold_days’: conf.hold_days, ‘model_id’: m6.model_id},
volume_limit=0,
)


(Apollo) #4

直接克隆没事
更改一下因子报错了


(Apollo) #5


(brantyz) #6

更新到了最新的模板策略,再试试


(iQuant) #7

使用最新模板的港股测试,可以参考:

克隆策略

基础参数配置

In [27]:
class conf:
    start_date = '2012-01-01'
    end_date='2017-07-17'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2015-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, end_date, market='HK_STOCK')

    hold_days = 30
    
    # 因子,这里可以通过表达式构建因子,参考bigexpr:https://bigquant.com/docs/big_expr.html
    features = [  
        'rank_return_20',  # 20日收益排名
        'ta_sma_10_0/ta_sma_20_0',
        'ta_sma_20_0/ta_sma_30_0',
        'ta_sma_30_0/ta_sma_60_0',
        'ta_rsi_14_0',
        'ta_rsi_28_0',
        'close_5/close_0', 
        'close_1/open_0', 
        'close_0/open_0', 
        'high_0/low_0',
        'close_1/close_0',  
        'close_2/close_0', 
        'close_3/close_0',  
        'close_4/close_0', 
        'amount_1/amount_0', ]
    
    # 标注
    label_expr = [
        
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    'shift(close, -30) / 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)'
    ]
    

策略函数定义

In [46]:
## 量化回测 https://bigquant.com/docs/module_trade.html
# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    instruments = D.instruments(market='HK_STOCK')
    ## 在样本外数据上进行预测
    n0 = M.general_feature_extractor.v5(
        instruments=D.instruments(market='HK_STOCK'),
        start_date=context.start_date, end_date=context.end_date,
        features=conf.features)
    n1 = M.derived_feature_extractor.v1(
        data=n0.data,
        features= conf.features)
    n2 = M.transform.v2(data=n1.data, transforms=None, drop_null=True)
    n3 = M.stock_ranker_predict.v4(model_id=context.options['model_id'], data=n2.data)
    context.instruments = n3.instruments
    context.options['predictions'] = n3.predictions

# 回测引擎:初始化函数,只执行一次
def initialize(context):
    # 加载预测数据
    context.ranker_prediction = context.options['predictions'].read_df()

    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
    context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
    # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
    stock_count = 3
    # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[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.2

# 回测引擎:每日数据处理函数,每天执行一次
def handle_data(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.perf_tracker.position_tracker.positions.items()}

    # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
    if not is_staging and cash_for_sell > 0:
        equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
        instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
        # print('rank order for sell %s' % instruments)
        for instrument in instruments:
            context.order_target(context.symbol(instrument), 0)
            cash_for_sell -= positions[instrument]
            if cash_for_sell <= 0:
                break

    # 3. 生成买入订单:按StockRanker预测的排序,买入前面的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)

模型训练

In [44]:
# 标注
m1 = M.advanced_auto_labeler.v1(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    label_expr=conf.label_expr, benchmark='HSI.HKEX', cast_label_int=True)           
            
# 抽取基础特征           
m2_1 = M.general_feature_extractor.v5(
        instruments=D.instruments(start_date=conf.start_date, end_date=conf.split_date, market='HK_STOCK'),
        start_date=conf.start_date, end_date=conf.split_date,
        features=conf.features)

# 抽取衍生特征 
m2_2 = M.derived_feature_extractor.v1(
        data=m2_1.data,
        features= conf.features)
# 特征转换
m3 = M.transform.v2(data=m2_2.data, transforms=None, drop_null=True)

# 合并标注和特征数据
m4 = M.join.v3(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)

# 开始训练模型
m5 = M.stock_ranker_train.v5(training_ds=m4.data, features=conf.features )
[2017-09-04 14:48:18.417911] INFO: bigquant: advanced_auto_labeler.v1 开始运行..
[2017-09-04 14:48:18.421000] INFO: bigquant: 命中缓存
[2017-09-04 14:48:18.422008] INFO: bigquant: advanced_auto_labeler.v1 运行完成[0.004155s].
[2017-09-04 14:48:18.443074] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-04 14:48:24.672471] INFO: general_feature_extractor: year 2012, featurerows=301612
[2017-09-04 14:48:33.151001] INFO: general_feature_extractor: year 2013, featurerows=326945
[2017-09-04 14:48:40.102775] INFO: general_feature_extractor: year 2014, featurerows=371198
[2017-09-04 14:48:45.602084] INFO: general_feature_extractor: year 2015, featurerows=0
[2017-09-04 14:48:45.619844] INFO: general_feature_extractor: total feature rows: 999755
[2017-09-04 14:48:45.621376] INFO: bigquant: general_feature_extractor.v5 运行完成[27.178351s].
[2017-09-04 14:48:45.627231] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-04 14:48:46.881423] INFO: derived_feature_extractor: extracted ta_sma_10_0/ta_sma_20_0, 0.003s
[2017-09-04 14:48:46.884682] INFO: derived_feature_extractor: extracted ta_sma_20_0/ta_sma_30_0, 0.002s
[2017-09-04 14:48:46.887733] INFO: derived_feature_extractor: extracted ta_sma_30_0/ta_sma_60_0, 0.002s
[2017-09-04 14:48:46.890532] INFO: derived_feature_extractor: extracted close_5/close_0, 0.002s
[2017-09-04 14:48:46.893546] INFO: derived_feature_extractor: extracted close_1/open_0, 0.002s
[2017-09-04 14:48:46.897113] INFO: derived_feature_extractor: extracted close_0/open_0, 0.003s
[2017-09-04 14:48:46.900794] INFO: derived_feature_extractor: extracted high_0/low_0, 0.002s
[2017-09-04 14:48:46.904210] INFO: derived_feature_extractor: extracted close_1/close_0, 0.002s
[2017-09-04 14:48:46.907016] INFO: derived_feature_extractor: extracted close_2/close_0, 0.002s
[2017-09-04 14:48:46.910321] INFO: derived_feature_extractor: extracted close_3/close_0, 0.003s
[2017-09-04 14:48:46.913693] INFO: derived_feature_extractor: extracted close_4/close_0, 0.002s
[2017-09-04 14:48:46.917141] INFO: derived_feature_extractor: extracted amount_1/amount_0, 0.002s
[2017-09-04 14:48:49.167735] INFO: derived_feature_extractor: /y_2012, 301612
[2017-09-04 14:48:50.231820] INFO: derived_feature_extractor: /y_2013, 326945
[2017-09-04 14:48:50.900284] INFO: derived_feature_extractor: /y_2014, 371198
[2017-09-04 14:48:52.036307] INFO: bigquant: derived_feature_extractor.v1 运行完成[6.409037s].
[2017-09-04 14:48:52.043444] INFO: bigquant: transform.v2 开始运行..
[2017-09-04 14:48:52.599312] INFO: transform: transformed /y_2012, 297117/301612
[2017-09-04 14:48:53.185800] INFO: transform: transformed /y_2013, 322365/326945
[2017-09-04 14:48:53.867440] INFO: transform: transformed /y_2014, 363696/371198
[2017-09-04 14:48:53.884866] INFO: transform: transformed rows: 983178/999755
[2017-09-04 14:48:53.900348] INFO: bigquant: transform.v2 运行完成[1.85687s].
[2017-09-04 14:48:53.906526] INFO: bigquant: join.v3 开始运行..
[2017-09-04 14:48:55.901895] INFO: join: /y_2012, 行数=260790/297117, 耗时=1.805266s
[2017-09-04 14:48:58.026117] INFO: join: /y_2013, 行数=291830/322365, 耗时=2.11275s
[2017-09-04 14:48:59.528867] INFO: join: /y_2014, 行数=292748/363696, 耗时=1.490487s
[2017-09-04 14:48:59.579979] INFO: join: 最终行数: 845368
[2017-09-04 14:48:59.581652] INFO: bigquant: join.v3 运行完成[5.675124s].
[2017-09-04 14:48:59.588425] INFO: bigquant: stock_ranker_train.v5 开始运行..
[2017-09-04 14:49:01.674880] INFO: df2bin: prepare bins ..
[2017-09-04 14:49:02.709258] INFO: df2bin: prepare data: training ..
[2017-09-04 14:49:14.725776] INFO: stock_ranker_train: 214e4278 准备训练: 845368 行数
[2017-09-04 14:49:51.415477] INFO: bigquant: stock_ranker_train.v5 运行完成[51.827021s].

调用策略引擎

In [47]:
m6 = M.trade.v2(
    instruments=None,
    start_date=conf.split_date,
    end_date=conf.end_date,
    prepare=prepare,
    initialize=initialize,
    handle_data=handle_data,
    order_price_field_buy='open',       # 表示 开盘 时买入
    order_price_field_sell='close',     # 表示 收盘 前卖出
    capital_base=50000,               # 初始资金
    benchmark='HSI.HKEX',            # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id},
    m_deps=np.random.rand()
)
[2017-09-04 14:54:16.625702] INFO: bigquant: backtest.v7 开始运行..
[2017-09-04 14:54:16.655249] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-04 14:54:20.395955] INFO: general_feature_extractor: year 2015, featurerows=400765
[2017-09-04 14:54:30.501951] INFO: general_feature_extractor: year 2016, featurerows=418465
[2017-09-04 14:54:44.764445] INFO: general_feature_extractor: year 2017, featurerows=240406
[2017-09-04 14:54:44.780462] INFO: general_feature_extractor: total feature rows: 1059636
[2017-09-04 14:54:44.784865] INFO: bigquant: general_feature_extractor.v5 运行完成[28.129613s].
[2017-09-04 14:54:44.790937] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-04 14:54:46.067230] INFO: derived_feature_extractor: extracted ta_sma_10_0/ta_sma_20_0, 0.006s
[2017-09-04 14:54:46.072911] INFO: derived_feature_extractor: extracted ta_sma_20_0/ta_sma_30_0, 0.004s
[2017-09-04 14:54:46.078462] INFO: derived_feature_extractor: extracted ta_sma_30_0/ta_sma_60_0, 0.005s
[2017-09-04 14:54:46.083332] INFO: derived_feature_extractor: extracted close_5/close_0, 0.004s
[2017-09-04 14:54:46.088593] INFO: derived_feature_extractor: extracted close_1/open_0, 0.004s
[2017-09-04 14:54:46.094492] INFO: derived_feature_extractor: extracted close_0/open_0, 0.005s
[2017-09-04 14:54:46.100533] INFO: derived_feature_extractor: extracted high_0/low_0, 0.005s
[2017-09-04 14:54:46.106582] INFO: derived_feature_extractor: extracted close_1/close_0, 0.005s
[2017-09-04 14:54:46.110795] INFO: derived_feature_extractor: extracted close_2/close_0, 0.003s
[2017-09-04 14:54:46.121602] INFO: derived_feature_extractor: extracted close_3/close_0, 0.010s
[2017-09-04 14:54:46.130075] INFO: derived_feature_extractor: extracted close_4/close_0, 0.007s
[2017-09-04 14:54:46.135800] INFO: derived_feature_extractor: extracted amount_1/amount_0, 0.005s
[2017-09-04 14:54:50.565940] INFO: derived_feature_extractor: /y_2015, 400765
[2017-09-04 14:54:52.214578] INFO: derived_feature_extractor: /y_2016, 418465
[2017-09-04 14:54:52.699713] INFO: derived_feature_extractor: /y_2017, 240406
[2017-09-04 14:54:53.516914] INFO: bigquant: derived_feature_extractor.v1 运行完成[8.725946s].
[2017-09-04 14:54:53.523075] INFO: bigquant: transform.v2 开始运行..
[2017-09-04 14:54:54.054232] INFO: transform: transformed /y_2015, 394161/400765
[2017-09-04 14:54:54.765746] INFO: transform: transformed /y_2016, 411101/418465
[2017-09-04 14:54:55.388668] INFO: transform: transformed /y_2017, 235542/240406
[2017-09-04 14:54:55.405772] INFO: transform: transformed rows: 1040804/1059636
[2017-09-04 14:54:55.416029] INFO: bigquant: transform.v2 运行完成[1.892912s].
[2017-09-04 14:54:55.422566] INFO: bigquant: stock_ranker_predict.v4 开始运行..
[2017-09-04 14:55:01.108934] INFO: df2bin: prepare data: prediction ..
[2017-09-04 14:55:27.164383] INFO: stock_ranker_predict: prediction: 1040804 rows
[2017-09-04 14:55:39.510149] INFO: bigquant: stock_ranker_predict.v4 运行完成[44.087549s].
[2017-09-04 14:56:13.031187] INFO: Performance: Simulated 624 trading days out of 624.
[2017-09-04 14:56:13.032339] INFO: Performance: first open: 2015-01-02 14:30:00+00:00
[2017-09-04 14:56:13.033097] INFO: Performance: last close: 2017-07-17 20:00:00+00:00
[注意] 有 1144 笔卖出是在多天内完成的。当日卖出股票超过了当日股票交易的2.5%会出现这种情况。
  • 收益率26.64%
  • 年化收益率10.01%
  • 基准收益率12.14%
  • 阿尔法0.05
  • 贝塔0.38
  • 夏普比率0.32
  • 收益波动率17.44%
  • 信息比率0.27
  • 最大回撤33.06%
[2017-09-04 14:56:15.876478] INFO: bigquant: backtest.v7 运行完成[119.250754s].

(Apollo) #8


(Apollo) #9

我这里依然是老版生成器,何解?


(iQuant) #10

不好意思,策略生成器我们还没有更新,如果你要用最新的模板,使用克隆功能,然后自己手动修改源代码。


(hk2000) #11

太好了,一直等待这个


(大胡子) #12

我发现平台上港股的证券代码只有四位,比如理文化工的代码为:0746.HKEX
而很多软件上是 00746.HKEX


(LIHAO117) #13

hihi 我复制了模板, 运行后报错.

FileNotFoundError Traceback (most recent call last)
in ()
12 # 通过 options 参数传递预测数据和参数给回测引擎
13 options={‘hold_days’: conf.hold_days, ‘model_id’: m5.model_id},
—> 14 m_deps=np.random.rand()
15 )

in prepare(context)
13 features= conf.features)
14 n2 = M.transform.v2(data=n1.data, transforms=None, drop_null=True)
—> 15 n3 = M.stock_ranker_predict.v4(model_id=context.options[‘model_id’], data=n2.data)
16 context.instruments = n3.instruments
17 context.options[‘predictions’] = n3.predictions

FileNotFoundError: [Errno 2] No such file or directory: ‘/bqmnt/bqranker/data/trainingv2/58dcf4427ad811e9bdf40a580a8102f6/features.ini.mapping.json’


(iQuant) #14

您好,目前港股的数据不全,之后我们会逐步完善,您使用的这个模板是旧版,稍后我们补一个新版可视化模板策略哈。


(达达) #15

目前港股/美股数据接口还没恢复

克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:model"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-250:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-250:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1055:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-250:benchmark_ds","SourceOutputPortId":"-1055:data_1"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"HK_STOCK","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na_label","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"cast_label_int","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nreturn_5\nreturn_10\nreturn_20\navg_amount_0/avg_amount_5\navg_amount_5/avg_amount_20\nrank_avg_amount_0/rank_avg_amount_5\nrank_avg_amount_5/rank_avg_amount_10\nrank_return_0\nrank_return_5\nrank_return_10\nrank_return_0/rank_return_5\nrank_return_5/rank_return_10\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","ModuleId":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v5","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":30,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":20,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"}],"OutputPortsInternal":[{"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"feature_gains","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","ModuleId":"BigQuantSpace.join.join-v3","ModuleParameters":[{"Name":"on","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"how","Value":"inner","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"sort","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data1","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","ModuleId":"BigQuantSpace.stock_ranker_predict.stock_ranker_predict-v5","ModuleParameters":[{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-250","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.options['hold_days']\n cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)\n cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.portfolio.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities)])))\n\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])\n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy_instruments):\n cash = cash_for_buy * buy_cash_weights[i]\n if cash > max_cash_per_instrument - positions.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions.get(instrument, 0)\n if cash > 0:\n context.order_value(context.symbol(instrument), cash)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.2\n context.options['hold_days'] = 5\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"后复权","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"product_type","Value":"股票","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-250"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-250"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-250","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1055","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n # 示例代码如下。在这里编写您的代码\n start_date = input_1.read_pickle()['start_date']\n end_date = input_1.read_pickle()['end_date']\n df = D.history_data('HSI.HKEX',start_date,end_date)\n data_1 = DataSource.write_df(df)\n return Outputs(data_1=data_1, data_2=None, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-1055"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-1055"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-1055"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-1055","OutputType":null},{"Name":"data_2","NodeId":"-1055","OutputType":null},{"Name":"data_3","NodeId":"-1055","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='208,64,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='70,183,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,21,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-43' Position='638,561,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='906,647,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1072,127,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='376,467,200,200'/><NodePosition Node='-86' Position='1078,418,200,200'/><NodePosition Node='-215' Position='381,188,200,200'/><NodePosition Node='-222' Position='385,280,200,200'/><NodePosition Node='-231' Position='1078,236,200,200'/><NodePosition Node='-238' Position='1081,327,200,200'/><NodePosition Node='-250' Position='1037,751,200,200'/><NodePosition Node='-1055' Position='1285,601,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":true}
    In [11]:
    # 本代码由可视化策略环境自动生成 2019年5月21日 11:20
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m4_run_bigquant_run(input_1, input_2, input_3):
        # 示例代码如下。在这里编写您的代码
        start_date = input_1.read_pickle()['start_date']
        end_date = input_1.read_pickle()['end_date']
        df = D.history_data('HSI.HKEX',start_date,end_date)
        data_1 = DataSource.write_df(df)
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m4_post_run_bigquant_run(outputs):
        return outputs
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_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)
    
    # 回测引擎:准备数据,只执行一次
    def m19_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:初始化函数,只执行一次
    def m19_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 = 5
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[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.2
        context.options['hold_days'] = 5
    
    
    m1 = M.instruments.v2(
        start_date='2010-01-01',
        end_date='2015-01-01',
        market='HK_STOCK',
        instrument_list='',
        max_count=0
    )
    
    m2 = M.advanced_auto_labeler.v2(
        instruments=m1.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 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, 20)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        start_date='',
        end_date='',
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    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
    """
    )
    
    m15 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m16 = M.derived_feature_extractor.v3(
        input_data=m15.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False
    )
    
    m7 = M.join.v3(
        data1=m2.data,
        data2=m16.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m13 = M.dropnan.v1(
        input_data=m7.data
    )
    
    m6 = M.stock_ranker_train.v5(
        training_ds=m13.data,
        features=m3.data,
        learning_algorithm='排序',
        number_of_leaves=30,
        minimum_docs_per_leaf=1000,
        number_of_trees=20,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1,
        m_lazy_run=False
    )
    
    m9 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2015-01-01'),
        end_date=T.live_run_param('trading_date', '2017-01-01'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m17 = M.general_feature_extractor.v7(
        instruments=m9.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m18 = M.derived_feature_extractor.v3(
        input_data=m17.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False
    )
    
    m14 = M.dropnan.v1(
        input_data=m18.data
    )
    
    m8 = M.stock_ranker_predict.v5(
        model=m6.model,
        data=m14.data,
        m_lazy_run=False
    )
    
    m4 = M.cached.v3(
        input_1=m9.data,
        run=m4_run_bigquant_run,
        post_run=m4_post_run_bigquant_run,
        input_ports='',
        params='{}',
        output_ports=''
    )
    
    m19 = M.trade.v4(
        instruments=m9.data,
        options_data=m8.predictions,
        benchmark_ds=m4.data_1,
        start_date='',
        end_date='',
        handle_data=m19_handle_data_bigquant_run,
        prepare=m19_prepare_bigquant_run,
        initialize=m19_initialize_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark='000300.SHA'
    )
    
    设置测试数据集,查看训练迭代过程的NDCG
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-6bf580491f26400296374f0c2dc53c4e"}/bigcharts-data-end
    • 收益率95.36%
    • 年化收益率41.31%
    • 基准收益率-12.21%
    • 阿尔法0.45
    • 贝塔0.8
    • 夏普比率1.04
    • 胜率0.55
    • 盈亏比1.02
    • 收益波动率37.2%
    • 信息比率0.09
    • 最大回撤50.15%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-1b9485b7403e44e6ad09a8b9dc00cd10"}/bigcharts-data-end

    (LIHAO117) #16

    感谢更新和回复!