2016-08-27 2 views
2

안녕하세요 저는 10 개의 피드를로드하고 10 개의 SMA를 작성한 다음 매일 매일 10 개의 피드를로드하는 작업을 단순화하기 위해 배열을 사용하여 1 ~ 10 개의 가능한 투자를 전략으로 일반화하고자합니다. 하나 또는 그 이상의 계측기에서 신호 교차가 발생했는지 확인.PyAlgoTrade에서 여러 계측기를 사용한 백 테스팅

나는 여기에 갇혀있다. 또한 플로터 그래프를 별도로 음모를 꾸미고 있지만 하나의 그래프에 모든 intruments 결과를 음모 싶어요.

내 코드입니다 :

from pyalgotrade import strategy, plotter 
from pyalgotrade.barfeed import yahoofeed 
from pyalgotrade.technical import ma 
from pyalgotrade.tools import yahoofinance 

class MyStrategy(strategy.BacktestingStrategy): 
    def __init__(self, feed, instruments, smaPeriod): 
     strategy.BacktestingStrategy.__init__(self, feed, 1000) 
     self.__position = None 
     # We'll use adjusted close values instead of regular close values. 
     self.setUseAdjustedValues(True) 
     self.__sma = {} 
     self.__instruments = instruments 
     for instrument in instruments: 
      self.__sma[instrument] = 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): 
     execInfo = position.getEntryOrder().getExecutionInfo() 

    def onExitOk(self, position): 
     execInfo = position.getExitOrder().getExecutionInfo() 
     self.info("SELL at $%.2f" % (execInfo.getPrice())) 

    def onExitCanceled(self, position): 
     # If the exit was canceled, re-submit it. 
     self.__position[str(position.getEntryOrder().getInstrument())].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 25 shares. The order is good till canceled. 
       self.__position = self.enterLong(self.__instrument, 25, True) 
     # Check if we have to exit the position. 
     elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive(): 
      self.__position.exitMarket() 

def run_strategy(smaPeriod): 

    # Load the yahoo feed from the CSV file 
    instruments = [ 
     "AMZN", 
     "ADBE", 
     "C" , 
     "BA" , 
     "HOG" , 
     "MMM" , 
     "MS" , 
     "MSFT" , 
     "CVS" , 
     "AXP" 
    ] 
    #Download and Load yahoo feed from CSV files 
    #Change year range 2000 to 2001 to your desired one 
    feed = yahoofinance.build_feed(instruments, 2000,2001, ".") 

    # Evaluate the strategy with the feed. 
    myStrategy = MyStrategy(feed, instruments, smaPeriod) 

    # Attach a plotter to the strategy 
    plt = plotter.StrategyPlotter(myStrategy) 


    # Run the strategy 
    myStrategy.run() 
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity() 

    # Plot the strategy. 
    plt.plot() 


run_strategy(10) 
+0

각 악기의 중단 신호와 커밋 순서를 확인하려면 루프를 'onBars'에 넣어야합니다. – gzc

+0

누군가가이 예를들 수 있습니까? – RageAgainstheMachine

답변

0

난 그냥 pyalgotrade을 취급하기 시작했습니다,하지만 난 당신이 (GZC으로 표시됨) 오히려 단순한 실수하고 있다고 생각 : 클래스 Bars의 인스턴스 모음입니다 다른 악기의 막대는 모두 동일한 타임 스탬프를 사용합니다. 따라서 onBars 이벤트가 호출되면 실제로 사전의 모든 악기를 반복해야합니다.

관련 문제