使用 Pyalgotrade 导入雅虎酒吧时出现 KeyError
KeyError importing yahoo bars with 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 = 开头的行并取消注释下面的行以使用 US stocks 它就完美了。
我的第一个想法是股票代码中的句号,但如果你 运行 它,它会打印出 bars.keys() 的内容,并且这会不断变化,这似乎是问题。它最终会在一个不存在的栏上出错,但我不明白为什么每个栏上的内容都会发生变化。
任何人都可以解释或帮助解决这个现象吗?我非常喜欢 Pyalgotrade 并且一直在寻找 Zipline 作为替代方案但是它太慢了。
我认为问题在于您假设每个日期(在每次调用 onBars 时)您都有所有工具的价格,但情况可能并非如此。
尝试打印日期时间 (bars.getDateTime()),然后查看包含该工具价格的文件。
我 运行 遇到一个问题,其中 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 = 开头的行并取消注释下面的行以使用 US stocks 它就完美了。
我的第一个想法是股票代码中的句号,但如果你 运行 它,它会打印出 bars.keys() 的内容,并且这会不断变化,这似乎是问题。它最终会在一个不存在的栏上出错,但我不明白为什么每个栏上的内容都会发生变化。
任何人都可以解释或帮助解决这个现象吗?我非常喜欢 Pyalgotrade 并且一直在寻找 Zipline 作为替代方案但是它太慢了。
我认为问题在于您假设每个日期(在每次调用 onBars 时)您都有所有工具的价格,但情况可能并非如此。 尝试打印日期时间 (bars.getDateTime()),然后查看包含该工具价格的文件。