For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Is it possible to bulid a data filter using backtrader's built-in indicators?
-
I want to bulid a data filter using backtrader's built in indicators, as the following codes:
class ImpulseSystem(object): def __init__(self, data): self.ema = bt.indicators.EMA(data.close, period=13) macd, signal, self.macd_hist = bt.indicators.MACDHisto(data.close, period_me1=12, period_me2=26, period_signal=9) data.impulse = np.zeros_like(data.close) def __call__(self, data): if len(data) > 1: if (self.ema[0] > self.ema[-1]) and (self.macd_hist[0] > self.macd_hist[-1]): data.impulse[0] = 1 elif (self.ema[0] < self.ema[-1]) and (self.macd_hist[0] < self.macd_hist[-1]): data.impulse[0] = -1 return False # length of data stream is unaltered .... data = bt.feeds.PandasData(dataname=datas.loc[code], tz=tz_cn) data._name = code[0:6] data1 = data.clone() data1.addfilter(ImpulseSystem) cerebro.adddata(data1)
This code will atempt to and a signal line 'impulse' to the data feed,
but it reports the following error,File "D:/Python/Jupyter/BackTrader/Test/Record/Order_History_C1.py", line 397, in runstrat data1.addfilter(ImpulseSystem) File "C:\Users\WEI\.conda\envs\backtrader37\lib\site-packages\backtrader\feed.py", line 332, in addfilter pobj = p(self, *args, **kwargs) File "D:/Python/Jupyter/BackTrader/Test/Record/Order_History_C1.py", line 89, in __init__ self.ema = bt.indicators.EMA(data.close, period=13) File "C:\Users\WEI\.conda\envs\backtrader37\lib\site-packages\backtrader\indicator.py", line 53, in __call__ return super(MetaIndicator, cls).__call__(*args, **kwargs) File "C:\Users\WEI\.conda\envs\backtrader37\lib\site-packages\backtrader\metabase.py", line 89, in __call__ _obj, args, kwargs = cls.dopostinit(_obj, *args, **kwargs) File "C:\Users\WEI\.conda\envs\backtrader37\lib\site-packages\backtrader\lineiterator.py", line 143, in dopostinit _obj._owner.addindicator(_obj) File "C:\Users\WEI\.conda\envs\backtrader37\lib\site-packages\backtrader\lineseries.py", line 461, in __getattr__ return getattr(self.lines, name) AttributeError: 'Lines_LineSeries_DataSeries_OHLC_OHLCDateTime_Abst' object has no attribute 'addindicator'
What's the matter?
-
as a guess - indicators are recognized and initialized within the strategy class, but not some object. therefore it is possible that all line written in the
__init__
above are meaningless from thebt
point of view.