遇到一个编程小问题,请大家看看!

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

(wicked_code) #1
克隆策略
In [284]:
import datetime
start_data = "2017-7-9"
d = datetime.datetime.strptime(start_data, '%Y-%m-%d')
delta = datetime.timedelta(days=-3)
n_days = d + delta
print (n_days.strftime('%Y-%m-%d'))
2017-07-06
In [285]:
import datetime
class conf:
    start_date = '2013-01-01'
    end_date='2017-09-10'
    split_date = '2017-01-01'
    instruments = D.instruments(start_date, end_date)
    hold_days = 5
    #自定义函数
   
        
    features = [
        '0.75*fs_operating_revenue_0/(fs_current_assets_0+fs_current_liabilities_0+fs_non_current_liabilities_0)',
        'pb_lf_0',  # 市净率
        
    ]
    
    # 数据标注标注
    label_expr = [
    # 计算未来一段时间(hold_days)的相对收益
    'shift(close, -5) / shift(open, -1) - shift(benchmark_close, -5) / shift(benchmark_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)'
    ]

## 量化回测 https://bigquant.com/docs/module_trade.html


# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    instruments = D.instruments()
    ## 在样本外数据上进行预测
    n0 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        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.v5(model=context.options['model'], 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)
    # 设置买入的股票数量,这里买入预测股票列表排名靠前的3只
    stock_count = 5
    # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多max_cash_per_instrument一点的资金,[0.339160, 0.213986, 0.169580, ..]
    context.stock_weights = T.norm([1 / math.log(i + 1.5) for i in range(0, stock_count)])
    # 设置每只股票占用的最大资金比例
    context.max_cash_per_instrument = 0.4
    #context.set_max_leverage(max_leverage=1) 

# 回测引擎:每日数据处理函数,每天执行一次
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()}
    
    
        
    def mk(_close,_open):
        if(_close-_open)/_open<-0.01:
            return 1
        elif abs((_close-_open)/_open)<=0.01:
            return 2
        elif(_close-_open)/_open>0.01:
            return 3
    
    def mkarr(df):
        ob=[]
        transfer=[[0,0,0],[0,0,0],[0,0,0]]
        open_list=df.open.reset_index(drop=True)
        close_list=df.close.reset_index(drop=True)
        for i in range(len(df.open)):
            #print(close_list[i],open_list[i])
            flag= mk(close_list[i],open_list[i])
            ob.append(flag)
        for i in ob:
            if i==len(ob)-2:break
            transfer[ob[i]-1][ob[i+1]-1]+=1
                
        return transfer
    
    
    buy_cash_weights = context.stock_weights
    buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
    end_date = data.current_dt.strftime('%Y-%m-%d')
    d = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    start_date=(d+datetime.timedelta(days=-80)).strftime('%Y-%m-%d')
    df = D.history_data(buy_instruments, start_date, end_date,fields=['open','close'],groupped_by_instrument=False)
    df.set_index("date")
    for i in range(len(buy_cash_weights)):
        print(buy_instruments[i])
        df1=df[df['instrument']==buy_instruments[i]]
        martix=np.mat(mkarr(df1))
        today_open=df1.open.reset_index(drop=True)
        today_close=df1.close.reset_index(drop=True)
        flag=mk(today_close[len(today_close)-1],today_open[len(today_open)-1])
        up=0
        down=0
        shock=0
        if flag==1:down+=1
        elif flag==2:shock+=1
        else:up+=1
        status=[[down],[shock],[up]] 
        k_martix=martix*status
        #print(k_martix)
    
        if k_martix[0][0]>=k_martix[1][0]:
            max=k_martix[0][0]
            max_status=0
        else:
            max=k_martix[1][0]
            max_status=1
            
        if k_martix[2][0]>max:
            max_status=2    
        
        if max_status==0:
            del(buy_instruments[i])
    
        
    
    # 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只股票
    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:
            price = data.current(context.symbol(instrument), 'price')
            lots = int(cash/price/100)
            context.order_lots(context.symbol(instrument), lots)
            

    
    
## 通过训练集数据训练模型            
# 高级数据标注
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='000300.SHA')


    
# 抽取基础特征           
m2_1 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        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.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)


    

# 开始训练模型
m5 = M.stock_ranker_train.v4(training_ds=m4.data, features=conf.features)

## 测试集上进行回测
m6 = M.trade.v3(
    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=100000000,               
    benchmark='000300.SHA',             
    options={'hold_days': conf.hold_days, 'model': m5.model_id},
    m_deps=np.random.rand()
)
[2017-09-17 02:55:23.610072] INFO: bigquant: advanced_auto_labeler.v1 开始运行..
[2017-09-17 02:55:23.613783] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.614594] INFO: bigquant: advanced_auto_labeler.v1 运行完成[0.004566s].
[2017-09-17 02:55:23.633561] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-17 02:55:23.635815] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.636550] INFO: bigquant: general_feature_extractor.v5 运行完成[0.002999s].
[2017-09-17 02:55:23.642404] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-17 02:55:23.644170] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.644921] INFO: bigquant: derived_feature_extractor.v1 运行完成[0.002512s].
[2017-09-17 02:55:23.650782] INFO: bigquant: transform.v2 开始运行..
[2017-09-17 02:55:23.652644] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.653360] INFO: bigquant: transform.v2 运行完成[0.002577s].
[2017-09-17 02:55:23.658752] INFO: bigquant: join.v2 开始运行..
[2017-09-17 02:55:23.660523] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.661302] INFO: bigquant: join.v2 运行完成[0.002542s].
[2017-09-17 02:55:23.667204] INFO: bigquant: stock_ranker_train.v4 开始运行..
[2017-09-17 02:55:23.668963] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.669795] INFO: bigquant: stock_ranker_train.v4 运行完成[0.002586s].
[2017-09-17 02:55:23.690746] INFO: bigquant: backtest.v7 开始运行..
[2017-09-17 02:55:23.722637] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-17 02:55:23.724730] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.725497] INFO: bigquant: general_feature_extractor.v5 运行完成[0.002878s].
[2017-09-17 02:55:23.730507] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-17 02:55:23.732192] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.732836] INFO: bigquant: derived_feature_extractor.v1 运行完成[0.002328s].
[2017-09-17 02:55:23.738364] INFO: bigquant: transform.v2 开始运行..
[2017-09-17 02:55:23.740142] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.740965] INFO: bigquant: transform.v2 运行完成[0.00259s].
[2017-09-17 02:55:23.746713] INFO: bigquant: stock_ranker_predict.v5 开始运行..
[2017-09-17 02:55:23.751740] INFO: bigquant: 命中缓存
[2017-09-17 02:55:23.752479] INFO: bigquant: stock_ranker_predict.v5 运行完成[0.005767s].
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-285-7c3d7e1d5e5f> in <module>()
    218     benchmark='000300.SHA',
    219     options={'hold_days': conf.hold_days, 'model': m5.model_id},
--> 220     m_deps=np.random.rand()
    221 )

<ipython-input-285-7c3d7e1d5e5f> in handle_data(context, data)
    113     for i in range(len(buy_cash_weights)):
    114         #print(buy_instruments[i])
--> 115         df1=df[df['instrument']==buy_instruments[i]]
    116         martix=np.mat(mkarr(df1))
    117         today_open=df1.open.reset_index(drop=True)

IndexError: list index out of range

(iQuant) #2

因为不知道你的想法和目的,所以不知道怎么修改代码。

首先,你可以将变量使用print函数打印出来

其次,你可以使用global variable 将函数中的局部变量转化成全局变量进行查看

克隆策略
In [1]:
import datetime
start_data = "2017-7-9"
d = datetime.datetime.strptime(start_data, '%Y-%m-%d')
delta = datetime.timedelta(days=-3)
n_days = d + delta
print (n_days.strftime('%Y-%m-%d'))
2017-07-06
In [7]:
import datetime
class conf:
    start_date = '2013-01-01'
    end_date='2017-09-10'
    split_date = '2017-01-01'
    instruments = D.instruments(start_date, end_date)
    hold_days = 5
    #自定义函数
   
        
    features = [
        '0.75*fs_operating_revenue_0/(fs_current_assets_0+fs_current_liabilities_0+fs_non_current_liabilities_0)',
        'pb_lf_0',  # 市净率
        
    ]
    
    # 数据标注标注
    label_expr = [
    # 计算未来一段时间(hold_days)的相对收益
    'shift(close, -5) / shift(open, -1) - shift(benchmark_close, -5) / shift(benchmark_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)'
    ]

## 量化回测 https://bigquant.com/docs/module_trade.html


# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    instruments = D.instruments()
    ## 在样本外数据上进行预测
    n0 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        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.v5(model=context.options['model'], 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)
    # 设置买入的股票数量,这里买入预测股票列表排名靠前的3只
    stock_count = 5
    # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多max_cash_per_instrument一点的资金,[0.339160, 0.213986, 0.169580, ..]
    context.stock_weights = T.norm([1 / math.log(i + 1.5) for i in range(0, stock_count)])
    # 设置每只股票占用的最大资金比例
    context.max_cash_per_instrument = 0.4
    #context.set_max_leverage(max_leverage=1) 

# 回测引擎:每日数据处理函数,每天执行一次
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()}
    
    
        
    def mk(_close,_open):
        if(_close-_open)/_open<-0.01:
            return 1
        elif abs((_close-_open)/_open)<=0.01:
            return 2
        elif(_close-_open)/_open>0.01:
            return 3
    
    def mkarr(df):
        ob=[]
        transfer=[[0,0,0],[0,0,0],[0,0,0]]
        open_list=df.open.reset_index(drop=True)
        close_list=df.close.reset_index(drop=True)
        for i in range(len(df.open)):
            #print(close_list[i],open_list[i])
            flag= mk(close_list[i],open_list[i])
            ob.append(flag)
        for i in ob:
            if i==len(ob)-2:break
            transfer[ob[i]-1][ob[i+1]-1]+=1
                
        return transfer
    
    
    buy_cash_weights = context.stock_weights
   
    buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
    end_date = data.current_dt.strftime('%Y-%m-%d')
    d = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    start_date=(d+datetime.timedelta(days=-80)).strftime('%Y-%m-%d')
    df = D.history_data(buy_instruments, start_date, end_date,fields=['open','close'],groupped_by_instrument=False)
    df.set_index("date")
    global buy_cash_weights
    global buy_instruments
    global df
    print(buy_cash_weights,len(buy_cash_weights))
    print('buy_instrument out of loop ',buy_instruments,len(buy_instruments))
    
    print('df:',df)
    for i in range(len(buy_cash_weights)):
        print('buy_instrument in loop ',buy_instruments)
        df1=df[df['instrument']==buy_instruments[i]]
        martix=np.mat(mkarr(df1))
        today_open=df1.open.reset_index(drop=True)
        today_close=df1.close.reset_index(drop=True)
        flag=mk(today_close[len(today_close)-1],today_open[len(today_open)-1])
        up=0
        down=0
        shock=0
        if flag==1:down+=1
        elif flag==2:shock+=1
        else:up+=1
        status=[[down],[shock],[up]] 
        k_martix=martix*status
        #print(k_martix)
    
        if k_martix[0][0]>=k_martix[1][0]:
            max=k_martix[0][0]
            max_status=0
        else:
            max=k_martix[1][0]
            max_status=1
            
        if k_martix[2][0]>max:
            max_status=2    
        
        if max_status==0:
            del(buy_instruments[i])
    
        
    
    # 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只股票
    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:
            price = data.current(context.symbol(instrument), 'price')
            lots = int(cash/price/100)
            context.order_lots(context.symbol(instrument), lots)
            

    
    
## 通过训练集数据训练模型            
# 高级数据标注
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='000300.SHA')


    
# 抽取基础特征           
m2_1 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        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.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)


    

# 开始训练模型
m5 = M.stock_ranker_train.v4(training_ds=m4.data, features=conf.features)

## 测试集上进行回测
m6 = M.trade.v3(
    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=100000000,               
    benchmark='000300.SHA',             
    options={'hold_days': conf.hold_days, 'model': m5.model_id},
    m_deps=np.random.rand()
)
[2017-09-17 13:52:38.767966] INFO: bigquant: advanced_auto_labeler.v1 开始运行..
[2017-09-17 13:52:38.771092] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.772208] INFO: bigquant: advanced_auto_labeler.v1 运行完成[0.004282s].
[2017-09-17 13:52:38.794868] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-17 13:52:38.797950] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.799007] INFO: bigquant: general_feature_extractor.v5 运行完成[0.00417s].
[2017-09-17 13:52:38.805538] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-17 13:52:38.808407] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.809649] INFO: bigquant: derived_feature_extractor.v1 运行完成[0.004126s].
[2017-09-17 13:52:38.816484] INFO: bigquant: transform.v2 开始运行..
[2017-09-17 13:52:38.819851] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.821009] INFO: bigquant: transform.v2 运行完成[0.004543s].
[2017-09-17 13:52:38.828267] INFO: bigquant: join.v2 开始运行..
[2017-09-17 13:52:38.831195] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.832612] INFO: bigquant: join.v2 运行完成[0.004333s].
[2017-09-17 13:52:38.839633] INFO: bigquant: stock_ranker_train.v4 开始运行..
[2017-09-17 13:52:38.842207] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.843003] INFO: bigquant: stock_ranker_train.v4 运行完成[0.003386s].
[2017-09-17 13:52:38.865948] INFO: bigquant: backtest.v7 开始运行..
[2017-09-17 13:52:38.902150] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-17 13:52:38.904829] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.905692] INFO: bigquant: general_feature_extractor.v5 运行完成[0.003573s].
[2017-09-17 13:52:38.911717] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-17 13:52:38.914155] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.914901] INFO: bigquant: derived_feature_extractor.v1 运行完成[0.003194s].
[2017-09-17 13:52:38.921561] INFO: bigquant: transform.v2 开始运行..
[2017-09-17 13:52:38.924084] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.925016] INFO: bigquant: transform.v2 运行完成[0.003486s].
[2017-09-17 13:52:38.932393] INFO: bigquant: stock_ranker_predict.v5 开始运行..
[2017-09-17 13:52:38.938549] INFO: bigquant: 命中缓存
[2017-09-17 13:52:38.939483] INFO: bigquant: stock_ranker_predict.v5 运行完成[0.007098s].
[0.4398338884022915, 0.1946295961609296, 0.14235517779142337, 0.11856922754966208, 0.10461211009569339] 5
buy_instrument out of loop  ['600339.SHA', '600581.SHA', '000968.SZA', '000627.SZA', '600603.SHA'] 5
df:             open  instrument       date        close
0     219.446503  000627.SZA 2016-10-17   216.747284
1      18.045084  000968.SZA 2016-10-17    18.733402
2      25.020533  600339.SHA 2016-10-17    24.784491
3      18.242832  600581.SHA 2016-10-17    17.812422
4    1128.184570  600603.SHA 2016-10-17  1135.859375
5     216.747284  000627.SZA 2016-10-18   220.256271
6      18.789211  000968.SZA 2016-10-18    19.198483
7      24.705809  600339.SHA 2016-10-18    25.099213
8      17.713095  600581.SHA 2016-10-18    18.011072
9    1136.626831  600603.SHA 2016-10-18  1140.464233
10    220.796112  000627.SZA 2016-10-19   219.446503
11     19.198483  000968.SZA 2016-10-19    19.179878
12     25.020533  600339.SHA 2016-10-19    25.020533
13     18.044182  600581.SHA 2016-10-19    17.977964
14   1138.929199  600603.SHA 2016-10-19  1128.184570
15    219.716431  000627.SZA 2016-10-20   220.526199
16     19.142672  000968.SZA 2016-10-20    19.161276
17     25.099213  600339.SHA 2016-10-20    25.177895
18     17.977964  600581.SHA 2016-10-20    17.779312
19   1132.789429  600603.SHA 2016-10-20  1122.812256
20    220.256271  000627.SZA 2016-10-21   220.256271
21     19.068260  000968.SZA 2016-10-21    18.975245
22     25.099213  600339.SHA 2016-10-21    24.941853
23     17.845530  600581.SHA 2016-10-21    17.878639
24   1122.812256  600603.SHA 2016-10-21  1067.554321
25    220.796112  000627.SZA 2016-10-24   222.685562
26     18.975245  000968.SZA 2016-10-24    19.142672
27     24.902512  600339.SHA 2016-10-24    25.020533
28     17.812422  600581.SHA 2016-10-24    18.110399
29   1067.554321  600603.SHA 2016-10-24  1075.229004
..           ...         ...        ...          ...
250   206.490250  000627.SZA 2016-12-26   209.459396
251    18.807816  000968.SZA 2016-12-26    18.900831
252    27.538322  600339.SHA 2016-12-26    28.010408
253    21.454367  600581.SHA 2016-12-26    22.050322
254  1190.349854  600603.SHA 2016-12-26  1237.933228
255   209.189468  000627.SZA 2016-12-27   208.379700
256    18.807816  000968.SZA 2016-12-27    18.845022
257    28.010408  600339.SHA 2016-12-27    27.695684
258    21.851669  600581.SHA 2016-12-27    22.248972
259  1217.978882  600603.SHA 2016-12-27  1175.767944
260   208.919556  000627.SZA 2016-12-28   205.950409
261    18.882227  000968.SZA 2016-12-28    18.845022
262    28.049747  600339.SHA 2016-12-28    28.285791
263    22.182755  600581.SHA 2016-12-28    21.851669
264  1181.907715  600603.SHA 2016-12-28  1147.371460
265   205.950409  000627.SZA 2016-12-29   204.600800
266    18.900831  000968.SZA 2016-12-29    18.733402
267    28.207109  600339.SHA 2016-12-29    28.207109
268    21.984104  600581.SHA 2016-12-29    21.785452
269  1151.208740  600603.SHA 2016-12-29  1154.278687
270   205.410568  000627.SZA 2016-12-30   206.490250
271    18.975245  000968.SZA 2016-12-30    19.310101
272    28.679195  600339.SHA 2016-12-30    29.623367
273    21.785452  600581.SHA 2016-12-30    22.050322
274  1151.208740  600603.SHA 2016-12-30  1158.883545
275   207.300018  000627.SZA 2017-01-03   211.618774
276    19.440323  000968.SZA 2017-01-03    20.072832
277    30.134792  600339.SHA 2017-01-03    29.466005
278    22.149647  600581.SHA 2017-01-03    22.944252
279  1157.348633  600603.SHA 2017-01-03  1155.046143

[280 rows x 4 columns]
buy_instrument in loop  ['600339.SHA', '600581.SHA', '000968.SZA', '000627.SZA', '600603.SHA']
buy_instrument in loop  ['600581.SHA', '000968.SZA', '000627.SZA', '600603.SHA']
buy_instrument in loop  ['600581.SHA', '000627.SZA', '600603.SHA']
buy_instrument in loop  ['600581.SHA', '000627.SZA', '600603.SHA']
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-d4de58545478> in <module>()
    226     benchmark='000300.SHA',
    227     options={'hold_days': conf.hold_days, 'model': m5.model_id},
--> 228     m_deps=np.random.rand()
    229 )

<ipython-input-7-d4de58545478> in handle_data(context, data)
    121     for i in range(len(buy_cash_weights)):
    122         print('buy_instrument in loop ',buy_instruments)
--> 123         df1=df[df['instrument']==buy_instruments[i]]
    124         martix=np.mat(mkarr(df1))
    125         today_open=df1.open.reset_index(drop=True)

IndexError: list index out of range
In [5]:
buy_cash_weights
Out[5]:
[0.4398338884022915,
 0.1946295961609296,
 0.14235517779142337,
 0.11856922754966208,
 0.10461211009569339]
In [6]:
buy_instruments
Out[6]:
['600581.SHA', '000627.SZA', '600603.SHA']