在pyalgotrade中格式化来自新来源的数据

时间:2016-07-25 20:53:07

标签: python pyalgotrade

我正在尝试调整pyalgotrade Feed以使用从其他来源流式传输的数据。当我尝试将Feed指向使用函数run_strategy获得的数据数据时,我在getdata()方法中收到错误。

请注意,getdata会返回格式为Date Close的数据,pyalgotrade显然会查找Date Open High Low Close

如何正确格式化数据以输入到Feed?

错误:

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

代码

#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)

1 个答案:

答案 0 :(得分:0)

您尝试将列表用作BarFeed,但这不起作用。使用它作为参考来为您的数据源实现BarFeed类: https://github.com/gbeced/pyalgotrade/blob/master/pyalgotrade/barfeed/yahoofeed.py