TypeError:+不支持的操作数类型:带有bt backtesting的“ slice”和“ int”

时间:2019-01-02 21:42:05

标签: python-3.x algorithmic-trading back-testing

我正在尝试通过一个名为bt的库对一个简单的策略进行回测。 Bt会为+:'slice'和'int'抛出TypeError:不支持的操作数类型。我似乎不知道为什么。代码和下面的完整错误。尽管可能是特定于库的,但我认为更好的程序员可以更好地理解该错误。

代码

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

0 个答案:

没有答案