pyalgotrade

How to reuse the instance strategy class of pyalgotrade


I define a class as follows. But I can only run myStrategy once. If I change the parameters and run myStrategy again, nothing changes. I hope to use the same strategy many times with different stocks and parameters.

"""

from pyalgotrade import strategy
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.technical import atr
from pyalgotrade.technical import highlow
from pyalgotrade.technical import ma


class turtleStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, period):
        strategy.BacktestingStrategy.__init__(self,feed,1000000)
        #super(turtleStrategy, self).__init__(feed,1000000)
        self.__instrument = instrument
        self.__period = period
        self.__position = None
        barsDs = feed[instrument]
        self.__atr = atr.ATR(barsDs,period)
        self.__closePrice = feed[instrument].getCloseDataSeries()
        self.__hband = highlow.High(self.__closePrice,period)
        self.__lband = highlow.Low(self.__closePrice,period)
    
    def onBars(self,bars):
        
        try:
            high = self.__hband.getDataSeries()[-2]
            low = self.__lband.getDataSeries()[-2]
        except:
            return
                
        price = bars[self.__instrument].getClose()
        
        if self.__position is None:
            if price > high:
                shares = int(self.getBroker().getCash() / price)
                self.marketOrder(self.__instrument,shares)
        elif price < low:
            self.marketOrder(self.__instrument,self.getBroker().getShares())

rdat = "...\\FREE.csv"
instrument = "FREE"
period = 20
feed = quandlfeed.Feed()
feed.addBarsFromCSV(instrument,rdat)

myStrategy = turtleStrategy(feed,instrument,period)

"""


Solution

  • If you just want to change the period, you can try this:

    rdat = "...\\FREE.csv"
    instrument = "FREE"
    feed = quandlfeed.Feed()
    feed.addBarsFromCSV(instrument,rdat)
    
    for period in [20, 30, 40]:
        feed.reset()
        myStrategy = turtleStrategy(feed, instrument, period)
    

    If you also want to change the instrument/feed, then you need to do everything again, not just reset the feed.