Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    RSI and MACD combo

    Indicators/Strategies/Analyzers
    1
    1
    553
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      sarah_james last edited by

      Hi all, I am trying to backtest RSI and MACD indicator strategies together like below. However When running my test it never takes any trade and I have tried it with 700 symbols so far. I have also tried just with the MACD and RSI separately and same thing? any help will highly appreciated thank you

      import backtrader
      from datetime import datetime
      import pandas as pd
      from services.trader_service import TraderService
      import numpy,pprint
      from matplotlib import warnings
      #Create Strategy
      class MACD_RSI_TestStrategy(backtrader.Strategy):
         params = dict(
             fastperiod=12,  
             slowperiod=26, 
             signalperiod=9,
             rsi_period=14,
             rsi_lookback=5,
             rsi_under=20,
             rsi_over=80
         )
      
         def log(self, txt, dt=None):
             ''' Logging function for this strategy'''
             dt = dt or self.datas[0].datetime.date(0)
             print('%s, %s' % (dt.isoformat(), txt))
      
         def __init__(self):
             self.movav= backtrader.talib.MACD(self.datas[0].close, fastperiod=self.params.fastperiod, slowperiod=self.params.slowperiod, signalperiod=self.params.signalperiod)
             self.rsi = backtrader.talib.RSI(self.datas[0].close,period=self.params.rsi_period)
             self.order = None
             self.macdabove = False
             self.dataclose = self.datas[0].close
      
         def notify_order(self, order):
             if order.status in [order.Submitted, order.Accepted]:
                 return 
             if order.status in [order.Completed]:
                 if order.isbuy():
                     self.log('BUY EXECUTED {}'.format(order.executed.price))
                 elif order.issell():
                     self.log('SELL EXECUTED {}'.format(order.executed.price))
      
                 self.bar_executed =len(self)
      
             self.order = None
      
         def next(self):
            
             if self.macdabove == False and self.movav.lines.macd[0] > self.movav.lines.macdsignal[0] and self.rsi.lines[0] < self.params.rsi_under:
                 self.macdabove = True
                 self.log(f'BUY CREATE, {self.dataclose[0]}')
                 self.order = self.buy()
             elif self.macdabove == True and self.position and self.rsi.lines[0] > self.params.rsi_over:
                 self.macdabove = False
                 self.log('SELL CREATE {}'.format(self.dataclose[0]))
                 self.order = self.close()
      
      if __name__ == '__main__':
         trading_pair = 'ETH/USDT'
         chartTime= ['1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h']
         date_of_trade="2021-05-03T12:00:00"
         trader = TraderService()
         account_balance=1000
         for  interval in chartTime:
             colums = ['timestamp', 'open','high', 'low', 'close', 'volume']
             klines =  trader.exchange.fetch_ohlcv(trading_pair, timeframe=interval, limit=1500,since=trader.exchange.parse8601(date_of_trade))
             dataFrame = pd.DataFrame(klines, columns=colums)
             dataFrame["timestamp"] = [datetime.fromtimestamp(t/1000) for t in dataFrame["timestamp"]]
      
             data = backtrader.feeds.PandasDirectData(dataname=dataFrame, 
             datetime=dataFrame.columns.get_loc("timestamp")+1, 
                 open=dataFrame.columns.get_loc('open')+1, high=dataFrame.columns.get_loc('high')+1, low=dataFrame.columns.get_loc('low')+1, 
                 close=dataFrame.columns.get_loc('close')+1,volume=dataFrame.columns.get_loc('volume')+1,openinterest=-1)
      
             cerebro = backtrader.Cerebro()
             cerebro.broker.setcash(account_balance)
             cerebro.addsizer(backtrader.sizers.FixedSize, stake=10)
             cerebro.adddata(data)
             cerebro.addstrategy(MACD_RSI_TestStrategy)
             cerebro.broker.setcommission(commission=0.10)
             print(f'timeframe {interval}')
             print(f'Pair {trading_pair}')
             print('Starting Balance: %.2f' % cerebro.broker.getvalue())
             cerebro.run()
      
             print('Final Balance: %.2f' % cerebro.broker.getvalue())
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors