pybacktest 库 hello world 错误:builtins.AttributeError: 'Series' 对象没有属性 'ix'

时间:2021-05-01 08:15:55

标签: python python-3.x finance quantitative-finance back-testing

运行以下 pybacktest 代码:

import matplotlib
import matplotlib.pyplot as plt
import pybacktest
import pandas as pd

short_ma = 50
long_ma = 200

ohlc = pybacktest.load_from_yahoo('AAPL', start=2000)
ohlc.tail()

ms = ohlc.C.rolling(short_ma).mean()
ml = ohlc.C.rolling(long_ma).mean()

buy = cover = (ms > ml) & (ms.shift() < ml.shift())  # ma cross up
sell = short = (ms < ml) & (ms.shift() > ml.shift())  # ma cross down

bt = pybacktest.Backtest(locals(), 'ma_cross')

print(bt.summary())

bt.plot_equity()

我收到标题中的错误信息,有关详细信息,请参阅此屏幕截图:

pybacktest hello world error

有人知道解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:0)

根据这个线程:

AttributeError: 'DataFrame' object has no attribute 'ix'

我使用 WingWare 的调用堆栈来备份调用 __getattribute__ 的内容

然后我替换了该行:

    eq = self.equity.ix[subset].cumsum()

(backtest.py 的第 188 行):

    eq = self.equity.loc[subset].cumsum()

也感谢评论者@GustiAdli 的确认。

该代码也适用于 Jupyter 笔记本,正确的代码应该是:

import matplotlib
import matplotlib.pyplot as plt
import pybacktest
import pandas as pd

short_ma = 50
long_ma = 200

ohlc = pybacktest.load_from_yahoo('AAPL', start=2000)
ohlc.tail()

ms = ohlc.C.rolling(short_ma).mean()
ml = ohlc.C.rolling(long_ma).mean()

buy = cover = (ms > ml) & (ms.shift() < ml.shift())  # ma cross up
sell = short = (ms < ml) & (ms.shift() > ml.shift())  # ma cross down

bt = pybacktest.Backtest(locals(), 'ma_cross')

print(bt.summary())

fig,ax = bt.plot_equity()
plt.show()

正确的输出应该是:

matplotlib output

我正在为此更改(以及需要完成的其他修复)创建一个新存储库:

https://github.com/enjoysmath/pybacktest

因为原版似乎被搁置了(最近的问题消息来自去年)。