Indicator that calculates the n-candle max of another indicator
-
Hi everyone,
I am writing an Indicator that takes another Indicator as its Data Feed. It should work generically on any Indicator that I pass it. The idea is to calculate the max out of the last n-candles and use that as the value.
Here the indicator in question:
class LastNMaxIndicator(Indicator): lines = ('example', ) params = {'lookback_period': 3} def __init__(self): self.addminperiod(self.params.lookback_period) def next(self): self.lines.example[0] = max(self.data.get(size=self.params.lookback_period))
In my strategy, I am passing the SimpleMovingAverage as its input:
class TestStrategy(Strategy): def __init__(self): self.sma = MovingAverageSimple(self.datas[0]) self.peak = LastNMaxIndicator(self.sma) def next(self): print('=== Date: {} ==='.format(self.datas[0].datetime.date(0))
However, I get an error when running this saying that the result of
self.data.get(size=self.params.lookback_period))
is empty:File "...", line 14, in next self.lines.example[0] = max(self.data.get(size=self.params.lookback_period)) ValueError: max() arg is an empty sequence
What am I missing?
-
bt
hasHighest
orMaxN
indicator which returns what you want. -
Thanks for answering. If I wanted to do it through the
next
method though, how would I do it?I am not sure what I am doing wrong with my code.
-
I am asking because, in the event that there is no off-the-shelf provided functionality by Backtrader, I would like to know how to do it through the
next
method :) -
There is probably an issue with the
minperiod
calculation in your indicator. Calling thesuper(LastNMaxIndicator, self).__init__()
may help, before adding your ownminperiod
. -
@vladisld said in Indicator that calculates the n-candle max of another indicator:
There is probably an issue with the
minperiod
calculation in your indicator. Calling thesuper(LastNMaxIndicator, self).__init__()
may help, before adding your ownminperiod
.That was it. Thank you! For anyone wondering what the indicator looks like now:
class LastNMaxIndicator(Indicator): lines = ('example', ) params = {'lookback_period': 3} def __init__(self): super(LastNMaxIndicator, self).__init__() self.addminperiod(self.params.lookback_period) def next(self): self.lines.example[0] = max( self.data.get(size=self.params.lookback_period))