Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    OLS example

    Indicators/Strategies/Analyzers
    1
    2
    1344
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • J
      jirathh last edited by

      Re: linear regression and std #211

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

      1 Reply Last reply Reply Quote 0
      • J
        jirathh last edited by

        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',)
        lines=('slope',)
        params = (('period', 20),)

        def __init__(self):
            self.addminperiod(self.params.period)
        
        def next(self):
            closes = pd.Series(self.data.close.get(size=self.p.period))
            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].datetime.date(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])

        1 Reply Last reply Reply Quote 0
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors