我尝试使用Pyalgotrade库中的list函数在python中编写Stochcastic Oscillator。
我的代码如下:
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
随机:
p p p p p p p p((((((((答案 0 :(得分:0)
bar.getClose()
或self.__stoch[-1]
返回numpy.ndarray
,而两者都应返回float
。
答案 1 :(得分:0)
行
上的字符串格式化操作%
self.info("%0.2f, %0.2f" % (bar.getClose(), self.__stoch[-1]))
%0.2f
承诺标量,但两者之一(bar.getClose()
或self.__stoch[-1]
)都是矩阵。
您可以更改格式化的字符串以期望字符串,只要它具有可打印的形式,它将接受任何Python对象:
self.info("%s, %s" % (bar.getClose(), self.__stoch[-1]))
答案 2 :(得分:0)
问题在于您尝试将talibext指标用作数据集,而它们不是。
我认为你必须使用:
self.__stoch[0][-1]
获取最后的%K值,并且:
self.__stoch[1][-1]
获取最后的%D值。
我建议您使用pyalgotrade.technical.stoch.StochasticOscillator,它实际上就像数据集一样,您可以这样做:
self.__stoch[-1]
或
self.__stoch.getD()[-1]
请记住,在这种情况下,您只需要构建一次StochasticOscillator。