pythonpyalgotrade

Formatting data from a new source in pyalgotrade


I am trying to adapt a pyalgotrade feed to use data streamed from another source. I am getting an error inside of the run_strategy method when I try to point the feed to data obtained using the function getdata().

NOTE that getdata returns data in the format: Date Close and pyalgotrade apparently looks for Date Open High Low Close.

How do I correctly format my data for input into a feed?

Error:

barFeed.getNewValuesEvent().subscribe(self.onBars)
AttributeError: 'list' object has no attribute 'getNewValuesEvent'

Code

#http://gbeced.github.io/pyalgotrade/docs/v0.17/html/tutorial.html
#run this first in cmd prompt to download data:
#python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')"
import httplib
import urllib
import json
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma


class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, smaPeriod):
        strategy.BacktestingStrategy.__init__(self, feed, 1000)
        self.__position = None
        self.__instrument = instrument
        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)
        self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)

    def onEnterOk(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()
        #self.info("BUY at $%.2f" % (execInfo.getPrice()))

    def onEnterCanceled(self, position):
        self.__position = None

    def onExitOk(self, position):
        execInfo = position.getExitOrder().getExecutionInfo()
        #self.info("SELL at $%.2f" % (execInfo.getPrice()))
        self.__position = None

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.exitMarket()

    def onBars(self, bars):
        # Wait for enough bars to be available to calculate a SMA.
        if self.__sma[-1] is None:
            return

        bar = bars[self.__instrument]
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if bar.getPrice() > self.__sma[-1]:
                # Enter a buy market order for 10 shares. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, 10, True)
        # Check if we have to exit the position.
        elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive():
            self.__position.exitMarket()

def getdata(period,pair,granularity):
    conn = httplib.HTTPSConnection("api-fxpractice.oanda.com")
    url = ''.join(["/v1/candles?count=", str(period + 1), "&instrument=", pair, "&granularity=", str(granularity), "&candleFormat=bidask"])#defines URL as what??
    print url
    conn.request("GET", url)
    response = conn.getresponse().read()
    candles = json.loads(response)['candles']
    print candles
    return(candles)

def run_strategy(smaPeriod):
    # Load the yahoo feed from the CSV file
    #feed = yahoofeed.Feed()
    #feed.addBarsFromCSV("orcl", "orcl-2000.csv")

    ###########attempting to add data feed from another source
    feed=getdata(50,"EUR_USD","H1")
    #________________
    
    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "orcl", smaPeriod)
    myStrategy.run()
    print "SMA: {} Final portfolio value: {}".format(smaPeriod, myStrategy.getBroker().getEquity())

run_strategy(15)
#for i in range(10, 30):
#    run_strategy(i)

Solution

  • You're trying to use a list as a BarFeed and that won't work. Use this as a reference to implement a BarFeed class for your datasource: https://github.com/gbeced/pyalgotrade/blob/master/pyalgotrade/barfeed/yahoofeed.py