使用Pyalgotrade导入yahoo栏的KeyError

时间:2015-04-08 03:38:55

标签: python python-2.7 pyalgotrade

我遇到了一个问题,当python尝试在pyalgotrade的onBars函数中引用股票价格时抛出KeyError。有趣的是,它取决于您尝试访问的股票。以下代码不起作用并抛出错误:

from pyalgotrade import strategy
from pyalgotrade.tools import yahoofinance
from pyalgotrade.technical import ma
from pyalgotrade.stratanalyzer import returns
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.utils import stats
from pyalgotrade.barfeed import yahoofeed
import os
import sys

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

        strategy.BacktestingStrategy.__init__(self, feed, 1000)
        self.__position = {}
        self.__instruments = instruments
        self.__sma20 = {}
        self.__sma200 = {}

        for inst in instruments:
            price = feed[inst].getCloseDataSeries()
            self.__sma20[inst] = ma.SMA(price, 20)
            self.__sma200[inst] = ma.SMA(price, 200)

        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)

    def onEnterOk(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()
        self.info("BUY " + str(position.getEntryOrder().getInstrument()) +" at " +str((execInfo.getPrice())) )

    def onEnterCanceled(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()
        self.info("onEnterCanceled " + str(position.getEntryOrder().getInstrument()) +" at " +str((execInfo.getPrice())) )

    def onBars(self, bars):
        #print bars['AAD'].getClose()
        for key in bars.keys():
            print key
        #sys.exit()
        for inst in self.__instruments:
            print inst

            self.info(bars[inst].getClose())
            print self.__sma20[inst][-1]
            if self.__sma20[inst][-1]  > self.__sma200[inst][-1] :
              print "go long"


def run_strategy():
        # Load the yahoo feed from the CSV file
        stocks = ["ABP.AX","AGL.AX","ALL.AX","ALQ.AX","AMC.AX","AMP.AX","ANN.AX","ANZ.AX","APA.AX","APN.AX"]
        #stocks = ['AAPL', 'IBM', 'MSFT', 'DOW', 'AXP','BA','CSCO','CVX','DD','DIS','GE','GS','HD','INTC','JNJ']
        feed = yahoofinance.build_feed(stocks, 2003, 2014, "./DailyStockPrices")

        # Evaluate the strategy with the feed.
        myStrategy = MyStrategy(feed, stocks)
        myStrategy.run()
        print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()

run_strategy()

股票是澳大利亚股票,全部有效。 yahoofeed模块下载它们。如果我注释掉以stocks =开头的行,并取消注释下面的行以使用美股,那么它的效果非常好。

我的第一个想法是在股票代码中完全停止,但如果你运行它,它会打印出bars.keys()的内容,这会不断变化,这似乎是问题的原因。它最终会出现一个不存在的错误,但为什么每个条形图上的内容都会发生变化。

任何人都可以解释或帮助解决这一现象吗?我非常喜欢Pyalgotrade并且​​一直在寻找Zipline,但它太慢了。

1 个答案:

答案 0 :(得分:0)

我认为问题在于你假设每个日期(每次打电话给onBars)你都有所有乐器的价格,而情况可能并非如此。 尝试打印日期时间(bars.getDateTime()),然后查看该文件的价格。