Lagged Indicator (eg. SMA)
I would like to build an indicator with lagged data. For example, get the SMA not today's close, but yesterday's or 2 days behind.
Is there such a possibility in Backtrader or do I have to build an indicator by myself?
Below I tried a lagged SMA of 7 days but I can't define the method next. Will you help me?
lines = ('laggedsma1',)
params = (('period', 14),
def next (self): datasum = math.fsum(self.data.get(size=self.p.period)) self.lines.sma = datasum / self.p.period
run-out last edited by
@albertoburchi The simplist way, IIUYC, would be to create the indicator as normal, then when using it, just reference the value n bars ago.
def __init__(self): self.sma = bt.ind.SMA(period=self.p.period) # then... def next(self): # Use the indicator like this for say, 5 bars ago ago = 5 # Use the indicator in your algo like... self.sma[-ago] # do whatever.
@albertoburchi You can also use
self.lagged_sma = self.sma(-7)
__init__method to pre-define it and then just access it as any other data property. I think the function call operator
()is referred to as the "ago" operator on a line.