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/

    Help with starting up

    Indicators/Strategies/Analyzers
    1
    1
    44
    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
      Shubham last edited by

      Hello,
      I am a newbee to backtrader and I am trying to backtest my strategy but whenever I start my code it gets stuck and I don't get any output.
      Can someone please help me to find the issue with my strategy.
      Thanks in advance

      
      
      class ABC(bt.Strategy):
          alias = ('ABC',)
      
          # list of parameters which are configurable for the strategy
          params = dict(
              sma50=10,  # period for the fast moving average
              pslow=30  # period for the slow moving average
          )
      
          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.log(f'Initial portfolio value of {self.broker.get_value():.2f}\n')
              self.sma20 = bt.ind.SMA(period=20)  # fast moving average
              self.sma50 = bt.ind.SMA(period=50)  # slow moving average
              # self.stddev = self.data.close.rolling(window=20).std()
              self.stddev = bt.ind.StdDev(self.close,period=20)
              self.lower_band = self.sma20 - (2 * self.stddev)
              self.upper_band = self.sma20 + (2 * self.stddev)
              offset = 0.005 * self.data.close
              a = abs(self.sma50 - self.lower_band)
              b = abs(self.data.Low - self.lower_band)
              c = abs(self.data.close - self.lower_band)
              self.buy_sig = bt.And(a < offset, bt.Or(b < offset,c < offset))
      
          def next(self):
              tar = 0
              SL = 0
              print("Scanning")
              if not self.position:  # not in the market
                  if self.buy_sig > 0:
                      self.log(f'BUY {self.getsizing()} shares of {self.data._name} at {self.data.close[0]}')
                      print('Entered Trade')
                      if self.data.close[0] > self.data.close[-1]:  # if fast crosses slow to the upside
                          if self.sma50[0] > self.sma2[-3]:
                              if self.sma50[-3] > self.sma2[-6]:
                                  if self.sma50[-6] < self.sma2[-9]:
                                      self.buy()  # enter long
                                      tar = self.data.close[0] + 10
                                      SL = self.data.close[0] + 10
      
              elif self.data.close[0]>tar:
                  self.sell()  # exit long
                  self.log(f'CLOSE LONG position of {self.position.size} shares '
                           f'of {self.data._name} at {self.data.close[0]:.2f}')
              # elif self.data.close[0]<SL:
      
              elif self.data.close[0] <SL:
                  self.sell()  # exit long
                  self.log(f'CLOSE LONG position of {self.position.size} shares '
                               f'of {self.data._name} at {self.data.close[0]:.2f}')
                  print('Do nothing')
      
      
      
      
      def startBackTestEngine(strategyName):
          # Declare position of each column in csv file
      
          btdata = GenericCSVData(dataname='backtestEngine_ABC.csv',
                                  dtformat=('%Y-%m-%d'),
                                  datetime=0,
                                  high=5,
                                  low=6,
                                  open=4,
                                  close=8,
                                  volume=10,
                                  openinterest=-1,
                                  # fromdate=date(2021, 2, 16),
                                  # todate=date(2021, 2, 16)
                                  )
      
          # Create Buy and Sell Signal Observers
      
          # Create cerebro Engine
          cerebro = bt.Cerebro()
      
          # Set Fixed Position Sizing
          cerebro.addsizer(bt.sizers.SizerFix, stake=20)
      
          # Add datafeed to Cerebro Engine
          cerebro.adddata(btdata)
      
          # Set Initial Trading Capital and Trading Commissions
          cerebro.broker.setcash(300000.0)
          cerebro.broker.setcommission(commission=0.002)
      
          # Add Trading Strategy to Cerebro
          cerebro.addstrategy(strategyName)
      
          # Add Buy Sell Signals Observer to Cerebro
          cerebro.addobserver(bt.observers.Value)
      
          # Add Trading Statistics Analyzer
          cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
      
          bt.observers.BuySell = BuySellSignal
      
          # Run Cerebro Engine
      
          start_portfolio_value = cerebro.broker.getvalue()
      
          cerebro.run()
      
          end_portfolio_value = cerebro.broker.getvalue()
          pnl = end_portfolio_value - start_portfolio_value
          print(f'Starting Portfolio Value: {start_portfolio_value:.2f}')
          print(f'Final Portfolio Value: {end_portfolio_value:.2f}')
          print(f'PnL: {pnl:.2f}')
      
          # Plot the Line Chart with Buy or Sell Signals
          cerebro.plot()
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors