Either bar.getClose()
or self.__stoch[-1]
is returning a numpy.ndarray
while both should be returning float
s.
TypeError in Python when using Pyalgotrade
-
01-07-2023 - |
Question
I trying to write a Stochcastic Oscillator in python using the list function in Pyalgotrade library.
My code is below:
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()
And I got the error like this:
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
Stochastic:
pyalgotrade.talibext.indicator.STOCH(barDs, count, fastk_period=-2147483648, slowk_period=-2147483648, slowk_matype=0, slowd_period=-2147483648, slowd_matype=0)
Solution
OTHER TIPS
It is the string formatting operation, %
, on the line
self.info("%0.2f, %0.2f" % (bar.getClose(), self.__stoch[-1]))
The %0.2f
is promising a scalar, but one of both (bar.getClose()
or self.__stoch[-1]
) is a matrix instead.
You can change the formatted string to expect strings, which will accept any Python object as long as it has a printable form:
self.info("%s, %s" % (bar.getClose(), self.__stoch[-1]))
The problem is that you're trying to use talibext indicators as dataseries, and they're not.
I think that you have to use:
self.__stoch[0][-1]
to get the last %K value, and:
self.__stoch[1][-1]
to get the last %D value.
I'd recommend you to use pyalgotrade.technical.stoch.StochasticOscillator instead, that actually behaves like a dataseries and you will be able to do:
self.__stoch[-1]
or
self.__stoch.getD()[-1]
Remember that in that case you'll have to build the StochasticOscillator only once.