8

Używam pyalgotrade dla strategii handlowej, w której chcę użyć wielu tickerów na liście.Jak stworzyć złożoną strategię, używając wielu instrumentów, w Pyalgotrade?

Sposób, w jaki jest teraz skonfigurowany, uruchamia strategię dla każdego indywidualnego znacznika na liście, ale chcę go uruchomić jako jedną, złożoną strategię.

Jak mam to zrobić?

Oto kod:

from pyalgotrade.tools  import yahoofinance 
    from pyalgotrade   import strategy 
    from pyalgotrade.barfeed import yahoofeed 
    from pyalgotrade.technical import stoch 
    from pyalgotrade   import dataseries 
    from pyalgotrade.technical import ma 
    from pyalgotrade   import technical 
    from pyalgotrade.technical import highlow 
    from pyalgotrade   import talibext 
    from pyalgotrade.talibext import indicator 
    import numpy as np 
    import talib 


    testlist = ['aapl', 'msft', 'z'] 

    class MyStrategy(strategy.BacktestingStrategy): 

     def __init__(self, feed, instrument): 
      strategy.BacktestingStrategy.__init__(self, feed) 
      self.__position = [] 
      self.__instrument = instrument 
      self.setUseAdjustedValues(True) 
      self.__prices = feed[instrument].getPriceDataSeries() 

      self.__stoch = stoch.StochasticOscillator(feed[instrument], 20, dSMAPeriod = 3, maxLen = 3) 

     def onBars(self, bars): 

      self.__PPO = talibext.indicator.PPO(self.__prices, len(self.__prices), 12, 26, matype = 1) 

      try: slope = talib.LINEARREG_SLOPE(self.__PPO, 3)[-1] 
      except Exception: slope = np.nan 


      bar = bars[self.__instrument] 
      self.info("%s,%s,%s" % (bar.getClose(), self.__PPO[-1], slope)) 

      if self.__PPO[-1] is None: 
       return 

      for inst in self.__instrument: 
       print inst 
       #INSERT STRATEGY HERE 

def run_strategy(): 
    # Load the yahoo feed from the CSV file 
    instruments = ['aapl', 'msft', 'z'] 
    feed = yahoofinance.build_feed(instruments,2015,2016, ".") 

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




run_strategy() 
+0

Proponuję wiodącym z 'z pyalgotrade import *', ponieważ wydaje się trochę wyczerpująca robić osoby, chyba że istnieje zmienna sprzeczność w klasie. – GreenHawk1220

+0

@ GreenHawk1220 Dzięki, zrobi! Każdy pomysł, jak uzyskać to działa z wieloma instrumentami? – RageAgainstheMachine

+0

Musisz znaleźć sposób, aby połączyć je wszystkie razem. Nie jestem zaznajomiony z biblioteką 'pyalgotrade', ale myślę, że problem polega na tym, że uruchamiasz każdy element w tablicy osobno. Może się mylę. Sugerowałbym znalezienie sposobu na połączenie tablicy z miejscem, w którym nadal można z nią pracować, ale mógłbym się pomylić, ponieważ nie jestem bardzo zaznajomiony z 'pyalgotrade'. – GreenHawk1220

Odpowiedz

0

Można użyć tego przykładu jako przewodnik do obrotu wielu instrumentach: http://gbeced.github.io/pyalgotrade/docs/v0.18/html/sample_statarb_erniechan.html

+0

Dzięki za komentarz, zmodyfikowałem powyższy kod, ale dostaję błąd dla linii cenowej self .__ prices (TypeError: unhashable type: 'list'), jakikolwiek pomysł jak to naprawić? Dzięki. – RageAgainstheMachine

+0

Ponadto, moja lista 3 tickerów będzie naprawdę ponad 100, na wypadek gdyby to miało znaczenie. – RageAgainstheMachine

0

feed jest instancją pyalgotrade.feed.BaseFeed. zawiera jeden lub wiele instrumentów "BarDataSeries", który definiuje kolejność cen. Po wywołaniu feed[instrument] otrzymasz instrument BarDataSeries. Potrzebujesz 1 for loop do przetworzenia każdego pojedynczego instrumentu. I sprawi, że twój kod będzie czysty, aby dodać dedykowaną klasę do obsługi każdego instrumentu. Zobacz klasę InstrumentManager. Naprawię wiele błędów programu.

class InstrumentManager(): 
    def __init__(self, feed, instrument): 
     self.instrument = instrument 

     self.__prices = feed[instrument].getPriceDataSeries() 

     self.__stoch = stoch.StochasticOscillator(feed[instrument], 20, dSMAPeriod = 3, maxLen = 3) 

     self.__signal = None 

    def onBars(self, bars): 
     bar = bars.getBar(self.instrument) 
     if bar: 
      self.__PPO = talibext.indicator.PPO(self.__prices, len(self.__prices), 12, 26, matype = 1) 

      try: slope = talib.LINEARREG_SLOPE(self.__PPO, 3)[-1] 
      except Exception: slope = np.nan 

      print("%s,%s,%s" % (bar.getClose(), self.__PPO[-1], slope)) 

      if self.__PPO[-1] is None: 
       return 

      # set signal in some conditions. eg self.__signal = 'buy' 

    def signal(): 
     return self.__signal 

class MyStrategy(strategy.BacktestingStrategy): 

    def __init__(self, feed, instruments): 
     strategy.BacktestingStrategy.__init__(self, feed) 
     self.__position = [] 
     self.__feed = feed 
     self.__instruments = instruments 
     self.setUseAdjustedValues(True) 
     self.instManagers = {} 
     self.loadInstManagers() 

    def loadInstManagers(self): 
     for i in self.__instruments: 
      im = InstrumentManager(self.__feed, i) 

      self.instManagers[i] = im 

    def updateInstManagers(self, bars): 
     for im in self.instManagers.values(): 
      im.onBars(bars) 

    def onBars(self, bars): 
     self.updateInstManagers(bars) 

     for inst in self.__instruments: 
      instManager = self.instManagers[inst] 
      print inst 

      # Do something by instManager.signal() 
Powiązane problemy