Search code examples
pythonglobaltradingpyalgotrade

NameError: global name 'indicator' is not defined using Pyalgotrade in Python


I trying to write a Ultimate 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 import talibext
import numpy
import talib

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

        self.__instrument = instrument

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

    self.__ultosc = indicator.ULTOSC(barDs, 36)

    bar = bars[self.__instrument]
    self.info("%0.2f, %0.2f" % (bar.getClose(), self.__ultosc[-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/untitled.py", line 23, in onBars
    self.__ultosc = indicator.ULTOSC(barDs, 36)
NameError: global name 'indicator' is not defined

The function can be found at http://gbeced.github.io/pyalgotrade/docs/v0.15/html/talib.html

Ultimate Oscillator:

pyalgotrade.talibext.indicator.ULTOSC(barDs, count, timeperiod1=-2147483648, timeperiod2=-2147483648, timeperiod3=-2147483648)


Solution

  • You're not importing indicator, nor are you referencing it via the module it's defined in. Change this:

    self.__ultosc = indicator.ULTOSC(barDs, 36)
    

    Into:

    self.__ultosc = talibext.indicator.ULTOSC(barDs, 36)
    

    And it should be fine.