For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

OLS example

  • Re: linear regression and std #211

    Do you have any example of how to use OLS in backtest ?
    Thank you.

  • I tried to create a new indicator myself and try to get the last N days of data to do OLS and return the value to line, unfortunately my strategy get 0 in value.

    class toroOLS(bt.Indicator):
    #lines = ('slope','intercept',)
    params = (('period', 20),)

    def __init__(self):
    def next(self):
        closes = pd.Series(
        x = np.arange(self.p.period).reshape(-1,1)
        x = sm.add_constant(x, prepend=True)
        #toro, intercept = sm.OLS(x, closes).fit().params
        #self.lines.slope[0] = toro
        #self.lines.intercept[0] = intercept
        toro = linear_model.LinearRegression().fit(x, closes)
        annualize_return = (((1+toro.coef_[0])**250) - 1)*100
        self.lines.slope[0] =  annualize_return

    This is where the indicator is used. Can you please suggest?

    class TestStrategy(bt.Strategy):
    params = (
    ('exitbars', 5),

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0]
        print('%s, %s' % (dt.isoformat(), txt))
    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close
        self.slope = toroOLS(period=20)

    def next(self):
    # Simply log the closing price of the series from the reference
    self.log('Close, %.2f' % self.dataclose[0])
    self.log('Slope, %.10f' % self.slope[0])

Log in to reply