如何查看下一个交易日应该买卖哪些股票?

新手专区
标签: #<Tag:0x00007f61dd455150>

(cwxuzhou) #1

策略写好之后,如何买卖股票呢?比如今天是4月21日,如果策略是每日买入,那么下周一4月24日发买卖指令是如何看?


(小米) #2

来看这个例子,比如现在是2017-04-19晚上8点半,之所以是晚上8点半,因为这个时候BigQuant当天的数据才更新到服务器上。我们关心的问题是,AI模型根据2017-04-19这天出来的最新数据,怎样获得一个全市场股票的排序,排序前的股票就优先买入,排序靠后的股票就优先卖出,等到4-20号开盘直接买入、卖出即可。

一个完整的策略:

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

    # 机器学习目标标注函数
    # 如下标注函数等价于 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 = [
        'market_cap_0',  # 总市值
    ]

# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
m1 = M.fast_auto_labeler.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.end_date,
    label_expr=conf.label_expr, hold_days=conf.hold_days,
    benchmark='000300.SHA', sell_at='open', buy_at='open')
# 计算特征数据
m2 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.end_date,
    features=conf.features)
# 数据预处理:缺失数据处理,数据规范化,T.get_stock_ranker_default_transforms为StockRanker模型做数据预处理
m3 = M.transform.v2(
    data=m2.data, transforms=T.get_stock_ranker_default_transforms(),
    drop_null=True, astype='int32', except_columns=['date', 'instrument'],
    clip_lower=0, clip_upper=200000000)
# 合并标注和特征数据
m4 = M.join.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)

# 训练数据集
m5_training = M.filter.v2(data=m4.data, expr='date < "%s"' % conf.split_date)
# 评估数据集
m5_evaluation = M.filter.v2(data=m4.data, expr='"%s" <= date' % conf.split_date)
# StockRanker机器学习训练
m6 = M.stock_ranker_train.v2(training_ds=m5_training.data, features=conf.features)
# 对评估集做预测
m7 = M.stock_ranker_predict.v2(model_id=m6.model_id, data=m5_evaluation.data)


## 量化回测 https://bigquant.com/docs/strategy_backtest.html
# 回测引擎:初始化函数,只执行一次
def initialize(context):
    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
    context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
    context.ranker_prediction = context.options['ranker_prediction'].read_df()
    # 设置买入的股票数量,这里买入预测股票列表排名靠前的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

# 回测引擎:每日数据处理函数,每天执行一次
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)

# 调用回测引擎
m8 = M.backtest.v5(
    instruments=m7.instruments,
    start_date=m7.start_date,
    end_date=m7.end_date,
    initialize=initialize,
    handle_data=handle_data,
    order_price_field_buy='open',       # 表示 开盘 时买入
    order_price_field_sell='close',     # 表示 收盘 前卖出
    capital_base=1000000,               # 初始资金
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'ranker_prediction': m7.predictions, 'hold_days': conf.hold_days}
)
[2017-04-21 20:03:34.200871] INFO: bigquant: fast_auto_labeler.v5 start ..
[2017-04-21 20:03:34.204112] INFO: bigquant: hit cache
[2017-04-21 20:03:34.213120] INFO: bigquant: fast_auto_labeler.v5 end [0.01223s].
[2017-04-21 20:03:34.218652] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-04-21 20:03:34.221000] INFO: bigquant: hit cache
[2017-04-21 20:03:34.222324] INFO: bigquant: general_feature_extractor.v5 end [0.003615s].
[2017-04-21 20:03:34.228237] INFO: bigquant: transform.v2 start ..
[2017-04-21 20:03:34.231131] INFO: bigquant: hit cache
[2017-04-21 20:03:34.232291] INFO: bigquant: transform.v2 end [0.004054s].
[2017-04-21 20:03:34.235955] INFO: bigquant: join.v2 start ..
[2017-04-21 20:03:34.238007] INFO: bigquant: hit cache
[2017-04-21 20:03:34.239291] INFO: bigquant: join.v2 end [0.003309s].
[2017-04-21 20:03:34.245393] INFO: bigquant: filter.v2 start ..
[2017-04-21 20:03:34.247433] INFO: bigquant: hit cache
[2017-04-21 20:03:34.248746] INFO: bigquant: filter.v2 end [0.003329s].
[2017-04-21 20:03:34.252170] INFO: bigquant: filter.v2 start ..
[2017-04-21 20:03:34.254151] INFO: bigquant: hit cache
[2017-04-21 20:03:34.255590] INFO: bigquant: filter.v2 end [0.003415s].
[2017-04-21 20:03:34.259191] INFO: bigquant: stock_ranker_train.v2 start ..
[2017-04-21 20:03:34.261059] INFO: bigquant: hit cache
[2017-04-21 20:03:34.262279] INFO: bigquant: stock_ranker_train.v2 end [0.003083s].
[2017-04-21 20:03:34.265928] INFO: bigquant: stock_ranker_predict.v2 start ..
[2017-04-21 20:03:34.268670] INFO: bigquant: hit cache
[2017-04-21 20:03:34.269894] INFO: bigquant: stock_ranker_predict.v2 end [0.003888s].
[2017-04-21 20:03:34.288492] INFO: bigquant: backtest.v5 start ..
[2017-04-21 20:03:34.294187] INFO: bigquant: hit cache
  • 收益率211.47%
  • 年化收益率81.12%
  • 基准收益率-5.6%
  • 阿尔法0.73
  • 贝塔0.74
  • 夏普比率4.41
  • 收益波动率32.81%
  • 信息比率6.23
  • 最大回撤41.8%
[2017-04-21 20:03:36.770684] INFO: bigquant: backtest.v5 end [2.482106s].
In [19]:
# 抽取预测集上数据特征
m9 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date='2017-04-19',end_date='2017-04-19',
    features=conf.features)
# 转化成AI算法可以接受的数据
m10 = M.transform.v2(
    data=m9.data, transforms=T.get_stock_ranker_default_transforms(),
    drop_null=True, astype='int32', except_columns=['date', 'instrument'],
    clip_lower=0, clip_upper=200000000)
# 进行预测
m11 = M.stock_ranker_predict.v2(model_id=m6.model_id, data=m10.data) 

# 预测结果,score较高的股票就是我们当天应该优先买入,score较低的股票我们优先卖出。
print('应该买入的股票:',list(m11.predictions.read_df().head(3).instrument))
print('应该卖出的股票:',list(m11.predictions.read_df().tail(3).instrument))
[2017-04-21 20:04:55.645394] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-04-21 20:04:55.649004] INFO: bigquant: hit cache
[2017-04-21 20:04:55.650389] INFO: bigquant: general_feature_extractor.v5 end [0.005233s].
[2017-04-21 20:04:55.656610] INFO: bigquant: transform.v2 start ..
[2017-04-21 20:04:55.658744] INFO: bigquant: hit cache
[2017-04-21 20:04:55.660004] INFO: bigquant: transform.v2 end [0.003388s].
[2017-04-21 20:04:55.663705] INFO: bigquant: stock_ranker_predict.v2 start ..
[2017-04-21 20:04:55.666443] INFO: bigquant: hit cache
[2017-04-21 20:04:55.667722] INFO: bigquant: stock_ranker_predict.v2 end [0.004009s].
应该买入的股票: ['002725.SZA', '600354.SHA', '002758.SZA']
应该卖出的股票: ['002554.SZA', '002126.SZA', '600790.SHA']

(cwxuzhou) #3

非常感谢。学习了。
另外仓位信息如何查看?比如在策略英雄榜中的最新卖出、最新持仓、最新交易等。
还是期待模拟交易的上线。


(小米) #4

其实仓位信息可以在策略细节里面看出来,知道各个股票的权重就能知道仓位。
因为目前StockRanker是排序选股模型,因此排序靠前的股票按理应该权重更大,仓位更高。
仓位的设置在策略代码里具体参考T.norm内置方法,具体使用可以参考下图:

# 如果是3只股票,每只股票的权重计算
stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, 3)])
[round(i,2) for i in stock_weights]


从上图可以看出,如果买3只或5只股票, 每只股票的具体仓位的比例是多少。


(csh) #5

如果持仓时间为3天,3天才买一次股票而不是每日都买股票,代码该怎么修改呢?


(matrixreloaded) #6

如何计算单只股票的持仓时间??

我这里算这个根据文档有问题啊。
股票Equity
这里的start_date并不是买入的时间咋办?这个不是应该是handle_date里面的股票买入时间么?

万分感谢及时回复,谢谢!


(hbweng) #7

嗯,这个文档写的有些歧义,已经去除。 现在需要用户自行在handle_data处记录买入时间。


(小马哥) #8

可以参考我的代码,不晓得问题大不大,欢迎交流!

克隆策略

注:本例子在股灾期间,由于停牌股票、跌停股票太多,所以会出现无法成交,导致仓位有出入。

In [17]:
# 基础参数配置
class conf:
    start_date = '2014-01-01'
    end_date='2017-07-04'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2017-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, end_date)[:300]

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

    # 特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征
    features = [
        'ta_sma_10_0/ta_sma_20_0',
        'amount_5/amount_0', 
    ]
    label_expr = ['return * 100', 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(15)]
In [18]:
m1 = M.fast_auto_labeler.v6(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    label_expr=conf.label_expr, hold_days=conf.hold_days,
    benchmark='000300.SHA', sell_at='open', buy_at='open')
# 计算特征数据
m2 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    features=conf.features)
# 数据预处理:缺失数据处理,数据规范化,T.get_stock_ranker_default_transforms为StockRanker模型做数据预处理
m3 = M.transform.v2(
    data=m2.data, transforms=T.get_stock_ranker_default_transforms(),
    drop_null=True, astype='int32', except_columns=['date', 'instrument'],
    clip_lower=0, clip_upper=200000000)
# 合并标注和特征数据
m4 = M.join.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)
# StockRanker机器学习训练
m5 = M.stock_ranker_train.v2(training_ds=m4.data, features=conf.features)

## 量化回测 https://bigquant.com/docs/module_trade.html
# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    instruments = D.instruments()[:300]
 
    n1 = M.general_feature_extractor.v5(
        instruments=instruments,
        start_date=context.start_date, end_date=context.end_date,
        model_id=context.options['model_id'])
    n2 = M.transform.v2(
        data=n1.data, transforms=T.get_stock_ranker_default_transforms(),
        drop_null=True, astype='int32', except_columns=['date', 'instrument'],
        clip_lower=0, clip_upper=200000000)
    n3 = M.stock_ranker_predict.v2(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().set_index('date')
    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
    context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    # 设置买入的股票数量,这里买入预测股票列表排名靠前的4只
    context.stock_count = 4
    context.i = 0
     
    
# 回测引擎:每日数据处理函数,每天执行一次
def handle_data(context, data):
    
    # 持有固定天数就换仓
    context.i += 1
    if context.i % conf.hold_days != 0:
        return
    
    # 先卖出目前持仓的股票
    for e, p in context.perf_tracker.position_tracker.positions.items():
        context.order_target(context.symbol(e.symbol), 0)
    
    # 按日期过滤得到今日的预测数据,
    predictions =  context.ranker_prediction 
    prediction =  predictions.ix[data.current_dt.strftime('%Y-%m-%d')][:context.stock_count]
  
    # 买入股票
    buy_instruments = list(prediction.instrument)
    stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, context.stock_count)])
    for i, instrument in enumerate(buy_instruments):
        context.order_target_percent(context.symbol(instrument), stock_weights[i])  
        
 # 调用交易引擎
m6 = M.trade.v1(
    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='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id},
    m_deps=np.random.rand(),
)
[2017-07-08 11:40:18.561824] INFO: bigquant: fast_auto_labeler.v6 start ..
[2017-07-08 11:40:19.751604] INFO: fast_auto_labeler: load history data: 191363 rows
[2017-07-08 11:40:19.817578] INFO: fast_auto_labeler: start labeling
[2017-07-08 11:40:23.574329] INFO: bigquant: fast_auto_labeler.v6 end [5.012499s].
[2017-07-08 11:40:23.579716] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-07-08 11:40:24.497896] INFO: general_feature_extractor: year 2014, featurerows=66293
[2017-07-08 11:40:25.876270] INFO: general_feature_extractor: year 2015, featurerows=61213
[2017-07-08 11:40:26.946955] INFO: general_feature_extractor: year 2016, featurerows=63857
[2017-07-08 11:40:27.408109] INFO: general_feature_extractor: year 2017, featurerows=0
[2017-07-08 11:40:27.416022] INFO: general_feature_extractor: total feature rows: 191363
[2017-07-08 11:40:27.418422] INFO: bigquant: general_feature_extractor.v5 end [3.838664s].
[2017-07-08 11:40:27.425533] INFO: bigquant: transform.v2 start ..
[2017-07-08 11:40:27.585117] INFO: transform: transformed /y_2014, 66293/66293
[2017-07-08 11:40:28.245081] INFO: transform: transformed /y_2015, 61194/61213
[2017-07-08 11:40:28.362908] INFO: transform: transformed /y_2016, 63857/63857
[2017-07-08 11:40:28.374830] INFO: transform: transformed rows: 191344/191363
[2017-07-08 11:40:28.379540] INFO: bigquant: transform.v2 end [0.953972s].
[2017-07-08 11:40:28.386137] INFO: bigquant: join.v2 start ..
[2017-07-08 11:40:28.710863] INFO: join: /y_2014, rows=66110/66293, timetaken=0.221682s
[2017-07-08 11:40:28.929623] INFO: join: /y_2015, rows=60333/61194, timetaken=0.211314s
[2017-07-08 11:40:29.069541] INFO: join: /y_2016, rows=62231/63857, timetaken=0.136489s
[2017-07-08 11:40:29.089056] INFO: join: total result rows: 188674
[2017-07-08 11:40:29.091344] INFO: bigquant: join.v2 end [0.705225s].
[2017-07-08 11:40:29.097936] INFO: bigquant: stock_ranker_train.v2 start ..
[2017-07-08 11:40:29.235355] INFO: df2bin: prepare data: training ..
[2017-07-08 11:40:31.542126] INFO: stock_ranker_train: training: 188674 rows
[2017-07-08 11:40:36.607840] INFO: bigquant: stock_ranker_train.v2 end [7.509889s].
[2017-07-08 11:40:36.626431] INFO: bigquant: backtest.v6 start ..
[2017-07-08 11:40:36.759900] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-07-08 11:40:37.372869] INFO: general_feature_extractor: year 2017, featurerows=31295
[2017-07-08 11:40:37.375772] INFO: general_feature_extractor: total feature rows: 31295
[2017-07-08 11:40:37.378683] INFO: bigquant: general_feature_extractor.v5 end [0.618767s].
[2017-07-08 11:40:37.386257] INFO: bigquant: transform.v2 start ..
[2017-07-08 11:40:37.483728] INFO: transform: transformed /y_2017, 31295/31295
[2017-07-08 11:40:37.487517] INFO: transform: transformed rows: 31295/31295
[2017-07-08 11:40:37.490091] INFO: bigquant: transform.v2 end [0.103823s].
[2017-07-08 11:40:37.495206] INFO: bigquant: stock_ranker_predict.v2 start ..
[2017-07-08 11:40:37.532541] INFO: df2bin: prepare data: prediction ..
[2017-07-08 11:40:37.887789] INFO: stock_ranker_predict: prediction: 31295 rows
[2017-07-08 11:40:43.186679] INFO: bigquant: stock_ranker_predict.v2 end [5.691422s].
[2017-07-08 11:40:46.324549] INFO: Performance: Simulated 121 trading days out of 121.
[2017-07-08 11:40:46.326075] INFO: Performance: first open: 2017-01-03 14:30:00+00:00
[2017-07-08 11:40:46.327130] INFO: Performance: last close: 2017-07-04 19:00:00+00:00
  • 收益率-16.05%
  • 年化收益率-30.54%
  • 基准收益率9.36%
  • 阿尔法-0.52
  • 贝塔1.04
  • 夏普比率-1.2
  • 收益波动率29.16%
  • 信息比率-1.86
  • 最大回撤27.46%
[2017-07-08 11:40:47.120281] INFO: bigquant: backtest.v6 end [10.493826s].