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/

    How to determine number of bars price above/below Moving Avg.

    Indicators/Strategies/Analyzers
    2
    2
    104
    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.
    • Don
      Don last edited by

      How do I determine the number of bars/periods that have been above or below a moving average?

      Pierre Cilliers 0 1 Reply Last reply Reply Quote 0
      • Pierre Cilliers 0
        Pierre Cilliers 0 @Don last edited by

        @don

        Hi.

        Lets say you have a moving average names ma (note that this has to be defines in your init() as self.movingaverage = bt.ind.SMA(self.data, period=10) and called in your next() as ma = self.movingaverage[0], which is the currently moving average value).

        If your data is already in bar format, you can call the close of the bar by self.data.close[0].

        Therefore, in your next() you can include a counter that increases every time self.data.close[0] > ma or self.data.close[0] < ma.

        A naive example can look like this:

        def __init__(self):
             self.movingaverage = bt.ind.SMA(self.data1, period=10)
        
        def next(self):
             ma = self.movingaverage[0]
             counter_above = 0
             counter_below = 0
             
             if self.data.close[0] > ma:
                  counter_above += 1
        
             elif self.data.close[0] < ma:
                  counter_below += 1
        
             else:
                  pass
        

        Now each time is changes (bars which were above go to be below), you can reset the counters.

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