How to determine number of bars price above/below Moving Avg.
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 last edited by
Lets say you have a moving average names
ma(note that this has to be defines in your
self.movingaverage = bt.ind.SMA(self.data, period=10)and called in your
ma = self.movingaverage, which is the currently moving average value).
If your data is already in bar format, you can call the close of the bar by
Therefore, in your
next()you can include a counter that increases every time
self.data.close > maor
self.data.close < 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 counter_above = 0 counter_below = 0 if self.data.close > ma: counter_above += 1 elif self.data.close < ma: counter_below += 1 else: pass
Now each time is changes (bars which were above go to be below), you can reset the counters.