2

我正在尝试使用一个名为 bt 的库来回测一个简单的策略。Bt 抛出 TypeError: unsupported operand type(s) for +: 'slice' 和 'int'。我似乎无法弄清楚为什么。下面的代码和完整错误。尽管可能是特定于库的,但我认为更好的程序员可以更好地理解错误。

代码

#Format price data
csv_f = pd.read_csv('cryptodata.csv')
data = pd.DataFrame(csv_f)
data['date'] = pd.to_datetime(data['date'])
data.set_index('date', inplace = True)
df1 = data[:-1]
df1 = df1.dropna()

def momentum_strategy(data, mom1 = 15, mom2 = 30, mom3 = 60, selection = 5 , cost = 0.025):

    #Momentum calc 
    mom_1 = data.pct_change(mom1)
    mom_2 = data.pct_change(mom2)
    mom_3 = data.pct_change(mom3)

    mom_average = (mom_1 + mom_2 + mom_3) / 3
    mom_average = mom_average.dropna()

    #Weight
    mom_average_rank = mom_average.rank(1, ascending = True)
    mom_selection = selection > mom_average_rank

    #create strategy

    s = bt.Strategy('mom_s',[bt.algos.SelectWhere(mom_selection),
                        bt.algos.RunWeekly(),
                        bt.algos.SelectAll(),
                        bt.algos.WeighEqually(),
                        bt.algos.Rebalance()])

    return bt.Backtest(s, data, commissions = lambda q, p: max(100, abs(q) * cost ))

#create the backtests
mom_1 = momentum_strategy(df1, 15, 30, 60, 5, 0.025)

#run backtests
res = bt.run(mom_1)

数据示例

df1

date        BTC  ETH .... 
2016-10-28  670  11 
... 
2018-12-27  3700 122



mom_Selection 
date        BTC   ETH .... 
2017-04-25  True  False 
... 
2018-12-27  True  True

完全错误

TypeError                                 Traceback (most recent call last)
<ipython-input-112-c6eb6fbb2dc4> in <module>()
      1 #run backtests
----> 2 res = bt.run(mom_1)

/anaconda3/lib/python3.6/site-packages/bt/backtest.py in run(*backtests)
     26     # run each backtest
     27     for bkt in backtests:
---> 28         bkt.run()
     29 
     30     return Result(*backtests)

/anaconda3/lib/python3.6/site-packages/bt/backtest.py in run(self)
    199 
    200             if not self.strategy.bankrupt:
--> 201                 self.strategy.run()
    202                 # need update after to save weights, values and such
    203                 self.strategy.update(dt)

/anaconda3/lib/python3.6/site-packages/bt/core.cpython-36m-darwin.so in bt.core.Strategy.run()

/anaconda3/lib/python3.6/site-packages/bt/core.cpython-36m-darwin.so in bt.core.AlgoStack.__call__()

/anaconda3/lib/python3.6/site-packages/bt/algos.py in __call__(self, target)
    163                 index_offset = 1
    164 
--> 165             date_to_compare = target.data.index[index + index_offset]
    166             date_to_compare = pd.Timestamp(date_to_compare)
    167 

TypeError: unsupported operand type(s) for +: 'slice' and 'int'
4

0 回答 0