Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. nicostro
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    N
    • Profile
    • Following 0
    • Followers 0
    • Topics 3
    • Posts 5
    • Best 3
    • Groups 0

    nicostro

    @nicostro

    3
    Reputation
    91
    Profile views
    5
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    nicostro Unfollow Follow

    Best posts made by nicostro

    • Backtesting strategy gig

      Hello there,

      I am looking for a python developer that is familiar and experimented in backtesting trading strategies using the Backtrader / ta-lib libraries.

      I have a simple trading strategy that enters trades after spotting divergences between price action and stochastic indicator. I would like to backtest this strategy while being able to optimize specific settings.

      Link to the gig is posted here: https://www.freelancer.com/projects/python/Backtesting-Trading-Strategy-Backtrader/proposals

      Please contact me via the freelancer platform if you are interested.

      Many thanks,
      Nicolas

      posted in General Discussion
      N
      nicostro
    • Add Supertrend Indicator to Backtrader

      Dear all,

      I would like to incorporate the supertrend indicator to backtrader (function is shown below). I'm new to backtrader / python, and I'm not sure how to code it to make it work properly with a calling like this:

      self.supertrend = supertrend(self.datas)
      

      Would be much appreciated if someone could provide guidance on how to implement it.

      Many thanks in advance!

      import backtrader as bt
      import numpy as np
      from pandas import DataFrame
      import talib.abstract as ta
      
      def supertrend(dataframe, multiplier=3, period=10):
          df = dataframe.copy()
      
          df['TR'] = ta.TRANGE(df)
          df['ATR'] = df['TR'].ewm(alpha=1 / period).mean()
      
          # atr = 'ATR_' + str(period)
          st = 'ST_' + str(period) + '_' + str(multiplier)
          stx = 'STX_' + str(period) + '_' + str(multiplier)
      
          # Compute basic upper and lower bands
          df['basic_ub'] = (df['high'] + df['low']) / 2 + multiplier * df['ATR']
          df['basic_lb'] = (df['high'] + df['low']) / 2 - multiplier * df['ATR']
      
          # Compute final upper and lower bands
          df['final_ub'] = 0.00
          df['final_lb'] = 0.00
          for i in range(period, len(df)):
              df['final_ub'].iat[i] = df['basic_ub'].iat[i] if df['basic_ub'].iat[i] < df['final_ub'].iat[i - 1] or \
                                                               df['close'].iat[i - 1] > df['final_ub'].iat[i - 1] else \
              df['final_ub'].iat[i - 1]
              df['final_lb'].iat[i] = df['basic_lb'].iat[i] if df['basic_lb'].iat[i] > df['final_lb'].iat[i - 1] or \
                                                               df['close'].iat[i - 1] < df['final_lb'].iat[i - 1] else \
              df['final_lb'].iat[i - 1]
      
          # Set the Supertrend value
          df[st] = 0.00
          for i in range(period, len(df)):
              df[st].iat[i] = df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[
                  i] <= df['final_ub'].iat[i] else \
                  df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[i] > \
                                           df['final_ub'].iat[i] else \
                      df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] >= \
                                               df['final_lb'].iat[i] else \
                          df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] < \
                                                   df['final_lb'].iat[i] else 0.00
      
              # Mark the trend direction up/down
          df[stx] = np.where((df[st] > 0.00), np.where((df['close'] < df[st]), 'down', 'up'), np.NaN)
      
          # Remove basic and final bands from the columns
          df.drop(['basic_ub', 'basic_lb', 'final_ub', 'final_lb'], inplace=True, axis=1)
      
          df.fillna(0, inplace=True)
      
          return DataFrame(index=df.index, data={
              'ST': df[st],
              'STX': df[stx]
          })
      
      
      class TestStrategy(bt.Strategy):
      
          def log(self, txt, dt=None):
              date = self.data.datetime.datetime()
              print('%s, %s' % (date, txt))
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
              self.dataopen = self.datas[0].open
              self.datahigh = self.datas[0].high
              self.datalow = self.datas[0].low
              self.datavolume = self.datas[0].volume
      
              # To keep track of pending orders and buy price/commission
              self.order = None
      
              self.supertrend = supertrend(self.datas)
      
      
      posted in Indicators/Strategies/Analyzers
      N
      nicostro
    • RE: Add Supertrend Indicator to Backtrader

      Many thanks, much appreciated!

      posted in Indicators/Strategies/Analyzers
      N
      nicostro

    Latest posts made by nicostro

    • Backtesting strategy gig

      Hello there,

      I am looking for a python developer that is familiar and experimented in backtesting trading strategies using the Backtrader / ta-lib libraries.

      I have a simple trading strategy that enters trades after spotting divergences between price action and stochastic indicator. I would like to backtest this strategy while being able to optimize specific settings.

      Link to the gig is posted here: https://www.freelancer.com/projects/python/Backtesting-Trading-Strategy-Backtrader/proposals

      Please contact me via the freelancer platform if you are interested.

      Many thanks,
      Nicolas

      posted in General Discussion
      N
      nicostro
    • RE: Add Supertrend Indicator to Backtrader

      Many thanks, much appreciated!

      posted in Indicators/Strategies/Analyzers
      N
      nicostro
    • Add Supertrend Indicator to Backtrader

      Dear all,

      I would like to incorporate the supertrend indicator to backtrader (function is shown below). I'm new to backtrader / python, and I'm not sure how to code it to make it work properly with a calling like this:

      self.supertrend = supertrend(self.datas)
      

      Would be much appreciated if someone could provide guidance on how to implement it.

      Many thanks in advance!

      import backtrader as bt
      import numpy as np
      from pandas import DataFrame
      import talib.abstract as ta
      
      def supertrend(dataframe, multiplier=3, period=10):
          df = dataframe.copy()
      
          df['TR'] = ta.TRANGE(df)
          df['ATR'] = df['TR'].ewm(alpha=1 / period).mean()
      
          # atr = 'ATR_' + str(period)
          st = 'ST_' + str(period) + '_' + str(multiplier)
          stx = 'STX_' + str(period) + '_' + str(multiplier)
      
          # Compute basic upper and lower bands
          df['basic_ub'] = (df['high'] + df['low']) / 2 + multiplier * df['ATR']
          df['basic_lb'] = (df['high'] + df['low']) / 2 - multiplier * df['ATR']
      
          # Compute final upper and lower bands
          df['final_ub'] = 0.00
          df['final_lb'] = 0.00
          for i in range(period, len(df)):
              df['final_ub'].iat[i] = df['basic_ub'].iat[i] if df['basic_ub'].iat[i] < df['final_ub'].iat[i - 1] or \
                                                               df['close'].iat[i - 1] > df['final_ub'].iat[i - 1] else \
              df['final_ub'].iat[i - 1]
              df['final_lb'].iat[i] = df['basic_lb'].iat[i] if df['basic_lb'].iat[i] > df['final_lb'].iat[i - 1] or \
                                                               df['close'].iat[i - 1] < df['final_lb'].iat[i - 1] else \
              df['final_lb'].iat[i - 1]
      
          # Set the Supertrend value
          df[st] = 0.00
          for i in range(period, len(df)):
              df[st].iat[i] = df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[
                  i] <= df['final_ub'].iat[i] else \
                  df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_ub'].iat[i - 1] and df['close'].iat[i] > \
                                           df['final_ub'].iat[i] else \
                      df['final_lb'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] >= \
                                               df['final_lb'].iat[i] else \
                          df['final_ub'].iat[i] if df[st].iat[i - 1] == df['final_lb'].iat[i - 1] and df['close'].iat[i] < \
                                                   df['final_lb'].iat[i] else 0.00
      
              # Mark the trend direction up/down
          df[stx] = np.where((df[st] > 0.00), np.where((df['close'] < df[st]), 'down', 'up'), np.NaN)
      
          # Remove basic and final bands from the columns
          df.drop(['basic_ub', 'basic_lb', 'final_ub', 'final_lb'], inplace=True, axis=1)
      
          df.fillna(0, inplace=True)
      
          return DataFrame(index=df.index, data={
              'ST': df[st],
              'STX': df[stx]
          })
      
      
      class TestStrategy(bt.Strategy):
      
          def log(self, txt, dt=None):
              date = self.data.datetime.datetime()
              print('%s, %s' % (date, txt))
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
              self.dataopen = self.datas[0].open
              self.datahigh = self.datas[0].high
              self.datalow = self.datas[0].low
              self.datavolume = self.datas[0].volume
      
              # To keep track of pending orders and buy price/commission
              self.order = None
      
              self.supertrend = supertrend(self.datas)
      
      
      posted in Indicators/Strategies/Analyzers
      N
      nicostro
    • RE: RSI: moving thresholds signals

      Great thanks, exactly what I needed.

      I just changed the buy / sell signals as per the below:

              if self.rsi[0] <= (np.percentile([self.rsiLLV[0], self.rsiHHV[0]], self.p.threshold_Buy)):
                  self.order = self.buy()
      
       else:
      
              if self.rsi[0] >= (np.percentile([self.rsiLLV[0], self.rsiHHV[0]], self.p.threshold_Sell)):
                  self.order = self.sell()
      

      Many thanks again

      posted in General Code/Help
      N
      nicostro
    • RSI: moving thresholds signals

      Hi everyone,

      I am fairly new to Python and Backtrader. I am testing out a simple RSI cross over strategy. Instead of having two hard-plugged thresholds for buy and sell signals, I’d like those thresholds to be moving across time series. For example, a buy signal would be triggered when current RSI is equal to the 10% minimum / lowest RSI over the last 24 hours, conversely a sell signal would be triggered when current RSI reaches the 90% highest RSI over the same period of time.

      As you can see on the code below, I haven’t been successful figuring out what to code in order to get those moving thresholds (10% lowest and 90% highest thresholds) that would trigger a trade signal.

      Any assistance or feedback would be greatly appreciated.

      class TestStrategy(bt.Strategy):

      params = (
          ('period',195),('threshold_Buy', 50),('threshold_Sell', 56),
          ) #tresholds here are hard plugged, the intent would be to have them as a percentage (for example 10% buy signal and 90% sell signal)
      
      def log(self, txt, dt=None):
          dt = dt or self.datas[0].datetime.date(0)
          print('%s, %s' % (dt.isoformat(), txt))
      
      def __init__(self):
          self.dataclose = self.datas[0].close
          self.order = None
          self.buyprice = None
          self.buycomm = None
      
          self.rsi = bt.indicators.RelativeStrengthIndex(self.datas[0], period=self.params.period) # simple RSI, period here has already been optimized for this particular stock
      
          self.smaRSI = bt.indicators.SimpleMovingAverage(self.rsi, period=288) #period here represents 24 hours cut into 5 minutes timeframe periods
      
      def notify_order(self, order):
          if order.status in [order.Submitted, order.Accepted]:
              # Buy/Sell order submitted/accepted to/by broker - Nothing to do
              return
      
          if order.status in [order.Completed]:
              if order.isbuy():
                  self.log(
                      'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                      (order.executed.price,
                       order.executed.value,
                       order.executed.comm))
      
                  self.buyprice = order.executed.price
                  self.buycomm = order.executed.comm
              else:
                  self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                           (order.executed.price,
                            order.executed.value,
                            order.executed.comm))
      
              self.bar_executed = len(self)
      
          elif order.status in [order.Canceled, order.Margin, order.Rejected]:
              '''self.log('Order Canceled/Margin/Rejected')'''
      
          self.order = None
      
      def notify_trade(self, trade):
          if not trade.isclosed:
              return
      
          self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                   (trade.pnl, trade.pnlcomm))
      
      def next(self):
      
          if self.order:
              return
      
          if not self.position:
      
              print('rsi', self.rsi[0], 'smaRSI', self.smaRSI[0])
      
              if self.rsi[0] < self.params.threshold_Buy:
                  self.order = self.buy()
      
          else:
      
              if self.rsi[0] > self.params.threshold_Sell:
                  self.order = self.sell()
      
      posted in General Code/Help
      N
      nicostro