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.
-
How do I determine the number of bars/periods that have been above or below a moving average?
-
Hi.
Lets say you have a moving average names
ma
(note that this has to be defines in yourinit()
asself.movingaverage = bt.ind.SMA(self.data, period=10)
and called in yournext()
asma = 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 timeself.data.close[0] > ma
orself.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.