使用Pyalgotrade时Python中的TypeError

使用Pyalgotrade时Python中的TypeError,python,numpy,pyalgotrade,Python,Numpy,Pyalgotrade,我试图使用Pyalgotrade库中的list函数用python编写一个Stochcastic振荡器 我的代码如下: from pyalgotrade.tools import yahoofinance from pyalgotrade import strategy from pyalgotrade.barfeed import yahoofeed from pyalgotrade.technical import stoch from pyalgotrade import dataserie

我试图使用Pyalgotrade库中的list函数用python编写一个Stochcastic振荡器

我的代码如下:

from pyalgotrade.tools import yahoofinance
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import stoch
from pyalgotrade import dataseries
from pyalgotrade.technical import ma
from pyalgotrade import technical
from pyalgotrade.technical import highlow
from pyalgotrade import bar
from pyalgotrade.talibext import indicator
import numpy
import talib

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)  
        self.__instrument = instrument

    def onBars(self, bars):

        barDs = self.getFeed().getDataSeries("002389.SZ")

        self.__stoch = indicator.STOCH(barDs, 20, 3, 3)

        bar = bars[self.__instrument]
        self.info("%0.2f, %0.2f" % (bar.getClose(), self.__stoch[-1]))

# Downdload then Load the yahoo feed from the CSV file
yahoofinance.download_daily_bars('002389.SZ', 2013, '002389.csv')
feed = yahoofeed.Feed()
feed.addBarsFromCSV("002389.SZ", "002389.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "002389.SZ")
myStrategy.run()
我得到的错误如下:

  File "/Users/johnhenry/Desktop/simple_strategy.py", line 46, in onBars
    self.info("%0.2f, %0.2f" % (bar.getClose(), self.__stoch[-1]))
TypeError: float argument required, not numpy.ndarray
随机:


pyalgotrade.talibext.indicator.STOCHbarDs,count,fastk_period=-2147483648,slowk_period=-2147483648,slowk_matype=0,slowd_period=-2147483648,slowd_matype=0

这是行上的字符串格式化操作,%

self.info("%0.2f, %0.2f" % (bar.getClose(), self.__stoch[-1]))
%0.2f是一个标量,但bar.getClose或self中的一个都是。__stoch[-1]是一个矩阵

您可以将格式化字符串更改为expect string,该字符串将接受任何Python对象,只要该对象具有可打印的表单:

self.info("%s, %s" % (bar.getClose(), self.__stoch[-1]))

问题是,您试图将talibext指标用作数据系列,但事实并非如此

我认为你必须使用:

self.__stoch[0][-1]
要获取最后的%K值,请执行以下操作:

self.__stoch[1][-1]
以获取最后的%D值

我建议您改用pyalgotrade.technical.stoch.stochasticsonator,它的行为实际上类似于dataseries,您将能够执行以下操作:

self.__stoch[-1]


请记住,在这种情况下,您只需构建一次随机振荡器。

不幸的是,我对numpy不太熟悉,但可以尝试新的字符串格式:self.info{},{}.formatbar.getClose,self.\u stoch[01],您好,那么,如何解决这个问题呢?我确定自我的类型。u stoch不是浮动的。@qifengwu-见我更新的答案。这是推测,因为我不确定self.info调用的作用。如果这不起作用,请用更多信息更新问题。我确信self的类型。\uu stoch不是float。字符串插值要求它是float。您应该编辑您的问题,告知您对self的期望。信息%0.2f,%0.2f%bar.getClose,self.\u stoch[-1]。
self.__stoch.getD()[-1]