Need help converting 2 lines of code to backtrader
-
Hi All,
Working on translating the famous Squeeze Momentum indicator from LazyBear (which is available in Pine on TradingView), to use it in Backtrader in Python.
More specifically, I have issues with the momentum indicator itself.
It uses the df.rolling.apply syntax from pandas and polyfit from numpy, but the syntax seems incompatible with Backtrader, so I need some help from the community.
I think I need help to help with the last 2 lines of code (fit_y and self.lines.Mom), basically.The last 2 lines were transcribed from Pine to Python as:
fit_y = np.array(range(0,length_KC)) df['value'] = df['value'].rolling(window = length_KC).apply(lambda x: np.polyfit(fit_y, x, 1)[0] * (length_KC-1) + np.polyfit(fit_y, x, 1)[1], raw=True)
The code I have translated to Backtrader so far:
# Create Momentum indicator class MomentumInd(bt.Indicator): lines = ('Mom',) params = (('period', 20),) plotinfo = dict(subplot=False) def _plotlabel(self): plabels = [self.p.period] return plabels def __init__(self): highest = bt.ind.Highest(self.data.high, period=self.p.period) lowest = bt.ind.Lowest(self.data.low, period=self.p.period) midline = (highest + lowest) / 2 mavg = bt.ind.MovingAverageSimple(self.data.close, period=self.p.period) delta = self.data.close - ((midline + mavg) / 2) fit_y = np.array(range(0, self.p.period, 1)) self.lines.Mom = delta.rolling(window=self.p.period).apply(lambda x: np.polyfit(fit_y, x, 1)[0] * (self.p.period - 1) + np.polyfit(fit_y, x, 1)[1], raw=True)
Unfortunately, I get the error:
AttributeError: 'LinesOperation' object has no attribute 'rolling'
I think it relates to the rolling window function in pandas, followed by the apply function, which seems incompatible with backtrader.
Any idea how to translate these last 2 lines in a way that backtrader can interpret the programme by any chance?
Thanks for your help!