我遇到了一个问题,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 = 开头的行并取消注释下面的行以使用美国股票,它会完美运行。
我的第一个想法是股票代码中的句号,但如果你运行它,它会打印出 bar.keys() 的内容,并且这会不断变化,这似乎是问题的原因。它最终会在一个不存在的错误上出错,但为什么每个栏的内容都会发生变化,这超出了我的理解。
谁能解释或帮助解决这种现象?我非常喜欢 Pyalgotrade,并且一直在寻找 Zipline 作为替代方案,但它太慢了。