各路大神,这个止盈止损条件如何加到AI策略中呢?求修改意见

策略分享
用户成长系列
标签: #<Tag:0x00007fcf64958d38> #<Tag:0x00007fcf64958b80>

(1899) #1

https://i.bigquant.com/user/rainfall1994/lab/share/AI%E9%80%89%E8%82%A1%E7%AD%96%E7%95%A52.ipynb?_t=1508314478675


(小Q) #2

现在,使用BigStudio可视化AI策略开发,是最灵活,便捷的方式。参考:第一个人工智能量化投资策略。在可视化策略开发中,你可以切换到代码模式查看代码。

如果你还是希望以代码模式直接开发策略,并且你并不知道最新策略版本的代码,你可以这样获取:

  • 新建-人工智能策略生成器

image

  • 然后选择因子,自动生成代码
    image

这样生成的代码是没有问题的。你如果还要加入止盈止损,直接在handle_data函数添加即可。

克隆策略
In [1]:
# 基础参数配置
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, split_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 = [
        'pe_ttm_0',  # 市盈率TTM
    ]

# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
m1 = M.fast_auto_labeler.v8(
    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.v3(training_ds=m4.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(),
        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()

    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
    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

# 回测引擎:每日数据处理函数,每天执行一次
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
                
            #----------------------------止赢模块START------------------------
    positions = {e.symbol: p.cost_basis  for e, p in context.portfolio.positions.items()}
    # 新建当日止赢股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
    current_stopwin_stock = [] 
    if len(positions) > 0:
        for i in positions.keys():
            stock_cost = positions[i]  
            stock_market_price = data.current(context.symbol(i), 'price') 
            # 赚10%就止赢
            if (stock_market_price - stock_cost ) / stock_cost>= 0.1:   
                context.order_target_percent(context.symbol(i),0)     
                current_stopwin_stock.append(i)
#                 print('日期:',date,'股票:',i,'出现止盈状况')
    #---------------------------止赢模块END-------------------------
    

    # 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)


# 调用交易引擎
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=1000000,               # 初始资金
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id}
)
[2017-10-18 20:43:32.961414] INFO: bigquant: fast_auto_labeler.v8 开始运行..
[2017-10-18 20:43:32.972318] INFO: bigquant: 命中缓存
[2017-10-18 20:43:32.989878] INFO: bigquant: fast_auto_labeler.v8 运行完成[0.028474s].
[2017-10-18 20:43:33.037583] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-10-18 20:43:33.040443] INFO: bigquant: 命中缓存
[2017-10-18 20:43:33.041248] INFO: bigquant: general_feature_extractor.v5 运行完成[0.003701s].
[2017-10-18 20:43:33.053260] INFO: bigquant: transform.v2 开始运行..
[2017-10-18 20:43:33.056044] INFO: bigquant: 命中缓存
[2017-10-18 20:43:33.056767] INFO: bigquant: transform.v2 运行完成[0.003517s].
[2017-10-18 20:43:33.067032] INFO: bigquant: join.v2 开始运行..
[2017-10-18 20:43:37.108690] INFO: join: /y_2010, rows=431024/431567, timetaken=3.190429s
[2017-10-18 20:43:39.814629] INFO: join: /y_2011, rows=510714/511250, timetaken=2.673747s
[2017-10-18 20:43:43.177593] INFO: join: /y_2012, rows=564552/565648, timetaken=3.32247s
[2017-10-18 20:43:45.934619] INFO: join: /y_2013, rows=563127/564168, timetaken=2.713778s
[2017-10-18 20:43:48.875178] INFO: join: /y_2014, rows=552619/569948, timetaken=2.894612s
[2017-10-18 20:43:48.997468] INFO: join: total result rows: 2622036
[2017-10-18 20:43:48.999239] INFO: bigquant: join.v2 运行完成[15.932221s].
[2017-10-18 20:43:49.015861] INFO: bigquant: stock_ranker_train.v3 开始运行..
[2017-10-18 20:43:50.764077] INFO: df2bin: prepare data: training ..
[2017-10-18 20:44:08.482976] INFO: stock_ranker_train: fcf8395a training: 2622036 rows
[2017-10-18 20:49:20.032799] INFO: bigquant: stock_ranker_train.v3 运行完成[331.016953s].
[2017-10-18 20:49:20.102841] INFO: bigquant: backtest.v7 开始运行..
[2017-10-18 20:49:20.128118] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-10-18 20:49:20.886970] INFO: general_feature_extractor: year 2015, featurerows=569698
[2017-10-18 20:49:36.255184] INFO: general_feature_extractor: year 2016, featurerows=641546
[2017-10-18 20:49:37.021668] INFO: general_feature_extractor: year 2017, featurerows=0
[2017-10-18 20:49:37.038448] INFO: general_feature_extractor: total feature rows: 1211244
[2017-10-18 20:49:37.040474] INFO: bigquant: general_feature_extractor.v5 运行完成[16.912382s].
[2017-10-18 20:49:37.049332] INFO: bigquant: transform.v2 开始运行..
[2017-10-18 20:49:37.505149] INFO: transform: transformed /y_2015, 569698/569698
[2017-10-18 20:49:38.059732] INFO: transform: transformed /y_2016, 641520/641546
[2017-10-18 20:49:38.078344] INFO: transform: transformed rows: 1211218/1211244
[2017-10-18 20:49:38.099958] INFO: bigquant: transform.v2 运行完成[1.050613s].
[2017-10-18 20:49:38.113259] INFO: bigquant: stock_ranker_predict.v2 开始运行..
/var/app/enabled/biglearning/module2/modules/transform/v2/__init__.py:68: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
[2017-10-18 20:49:38.586845] INFO: df2bin: prepare data: prediction ..
[2017-10-18 20:49:46.972025] INFO: stock_ranker_predict: prediction: 1211218 rows
[2017-10-18 20:49:55.898032] INFO: bigquant: stock_ranker_predict.v2 运行完成[17.784749s].
/var/app/enabled/pandas/tseries/index.py:817: PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex
  "or DatetimeIndex", PerformanceWarning)
/var/app/enabled/empyrical/stats.py:534: RuntimeWarning: divide by zero encountered in double_scalars
  sortino = mu / dsr
[2017-10-18 20:50:28.105689] INFO: Performance: Simulated 488 trading days out of 488.
[2017-10-18 20:50:28.106792] INFO: Performance: first open: 2015-01-05 14:30:00+00:00
[2017-10-18 20:50:28.107569] INFO: Performance: last close: 2016-12-30 20:00:00+00:00
/var/app/enabled/pandas/core/generic.py:1138: PerformanceWarning: 
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->mixed,key->block4_values] [items->['LOG', 'POS_FAC', 'TRA_FAC', 'orders', 'period_label', 'positions', 'transactions']]

  return pytables.to_hdf(path_or_buf, key, self, **kwargs)
/var/app/enabled/pandas/core/indexing.py:141: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)
  • 收益率50.42%
  • 年化收益率23.47%
  • 基准收益率-6.33%
  • 阿尔法0.24
  • 贝塔0.61
  • 夏普比率0.81
  • 收益波动率24.78%
  • 信息比率1.35
  • 最大回撤21.79%
[2017-10-18 20:50:30.837260] INFO: bigquant: backtest.v7 运行完成[70.734389s].