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 create a strategy that uses indicators from different timeframes
-
Sorry for this noob question...
What I'm trying to do is a simple sample strategy that checks the RSI indicator for 14 days, and buys when the a engulfing pattern is detected on the minute timeframe, however I can't figure out how to add both timeframes on my strategy
class MYStrategy(bt.Strategy): def __init__(self): self.cdl = bt.talib.CDLENGULFING(self.data.open, self.data.high, self.data.low, self.data.close) self.rsi = bt.talib.RSI(self.data, timeperiod=14) def next(self): if self.rsi > 70 and self.cdl == 100 and not self.position: self.buy(size=1.00) if self.rsi < 30 and self.cdl == -100 and self.position: self.close() cerebro = bt.Cerebro() data = bt.feeds.GenericCSVData(dataname='MYDATA_minute.csv', dtformat=2, compression=1, timeframe=bt.TimeFrame.Minutes) cerebro.adddata(data) data2 = bt.feeds.GenericCSVData(dataname='MYDATA_daily.csv', dtformat=2, compression=1, timeframe=bt.TimeFrame.Days) cerebro.adddata(data2) cerebro.addstrategy(MYStrategy) cerebro.run() cerebro.plot()
-
So, I did some more trying and I sort of got it working like this:
def __init__(self): self.inds = dict() for i, d in enumerate(self.datas): self.inds[d] = dict() self.inds[d]['rsi'] = bt.talib.RSI(d, timeperiod=14) self.inds[d]['eng'] = bt.talib.CDLENGULFING(d.open, d.high, d.low, d.close) def next(self): for i, d in enumerate(self.datas): if self.inds[d]['rsi'] > 70 and self.inds[d]['eng'] == 100 and not self.position: self.buy(size=0.05) if self.inds[d]['rsi'] < 30 and self.inds[d]['eng'] == -100 and self.position: self.close()
This code actually works, however I don't really understand how since nowhere I state that I want use the daily data for the RSI and the minute data for the engulfing.... So I'm confused... What else can I improve in this code?
-
Try with add 2 data feeds
class MYStrategy(bt.Strategy): def __init__(self): self.cdl = bt.talib.CDLENGULFING(self.data.open, self.data.high, self.data.low, self.data.close) self.rsi = bt.talib.RSI(self.data, timeperiod=14) def next(self): if self.rsi > 70 and self.cdl == 100 and not self.position: self.buy(size=1.00) if self.rsi < 30 and self.cdl == -100 and self.position: self.close() cerebro = bt.Cerebro() data0 = bt.feeds.GenericCSVData(dataname='MYDATA_minute.csv', dtformat=2, compression=1, timeframe=bt.TimeFrame.Minutes) cerebro.adddata(data0) data1 = bt.feeds.GenericCSVData(dataname='MYDATA_day.csv', dtformat=2, compression=1, timeframe=bt.TimeFrame.Days) cerebro.adddata(data1)
then use data1 to load indicators from
self.data1
orself.datas[1]
ind = bt.talib.CDLENGULFING(self.data1.open, self.data1.high, self.data1low, self.data1.close)