0
저는 이제 거래 전략 테스트를위한 인기있는 파이썬 라이브러리 인 Pyalgotrade를 사용하고 있습니다. 나는 한 쌍의 주식을 차례로 테스트 할 수있는 루프를 작성하려고합니다.파이썬을 사용하여 여러 주식을 백 테스팅
이 전략에 다음 6 가지 주식을 넣고 각 주식을 한 번 조정하고 여러 결과를 얻고 싶다고 가정 해 보겠습니다. 어떻게 그 루프를 쓸 수 있습니까?
재고 = AAPL, 이베이 NFLX, BBY, GOOG, WBAI]
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.tools import yahoofinance
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].getAdjCloseDataSeries(), 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.getAdjClose() > 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.getAdjClose() < self.__sma[-1]:
self.__position.exitMarket()
def run_strategy(smaPeriod):
instruments = ["AAPL"]
# Download the bars.
feed = yahoofinance.build_feed(instruments, 2011, 2013, ".")
# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "AAPL", smaPeriod)
myStrategy.run()
print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()
run_strategy(10)