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/

    Analyzer problem

    General Code/Help
    2
    3
    165
    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.
    • G
      Gleetche last edited by

      Hi there,

      The full code below works perfectly as it is but I wonder why removing the

              else:
                  if self.rsi > 70:
                      self.sell(size=100)
      

      from the next function will cause an error?

      This is the error i get
      07ed5f8c-b82c-41b4-8c3e-b654156c8aa0-image.png

      This is the full code:

      import backtrader as bt
      from datetime import datetime
      from collections import OrderedDict
      
      class firstStrategy(bt.Strategy):
      
          def __init__(self):
              self.rsi = bt.indicators.RSI_SMA(self.data.close, period=21)
      
          def next(self):
              if not self.position:
                  if self.rsi < 30:
                      self.buy(size=100)
              else:
                  if self.rsi > 70:
                      self.sell(size=100)
      
      
      def printTradeAnalysis(analyzer):
          '''
          Function to print the Technical Analysis results in a nice format.
          '''
          #Get the results we are interested in
          total_open = analyzer.total.open
          total_closed = analyzer.total.closed
          total_won = analyzer.won.total
          total_lost = analyzer.lost.total
          win_streak = analyzer.streak.won.longest
          lose_streak = analyzer.streak.lost.longest
          pnl_net = round(analyzer.pnl.net.total,2)
          strike_rate = (total_won / total_closed) * 100
          #Designate the rows
          h1 = ['Total Open', 'Total Closed', 'Total Won', 'Total Lost']
          h2 = ['Strike Rate','Win Streak', 'Losing Streak', 'PnL Net']
          r1 = [total_open, total_closed,total_won,total_lost]
          r2 = [strike_rate, win_streak, lose_streak, pnl_net]
          #Check which set of headers is the longest.
          if len(h1) > len(h2):
              header_length = len(h1)
          else:
              header_length = len(h2)
          #Print the rows
          print_list = [h1,r1,h2,r2]
          row_format ="{:<15}" * (header_length + 1)
          print("Trade Analysis Results:")
          for row in print_list:
              print(row_format.format('',*row))
      
      def printSQN(analyzer):
          sqn = round(analyzer.sqn,2)
          print('SQN: {}'.format(sqn))
      
      #Variable for our starting cash
      startcash = 100000
      
      #Create an instance of cerebro
      cerebro = bt.Cerebro()
      
      #Add our strategy
      cerebro.addstrategy(firstStrategy)
      
      #Get Apple data from Yahoo Finance.
      data = bt.feeds.YahooFinanceData(
          dataname='AAPL',
          fromdate = datetime(2009,1,1),
          todate = datetime(2017,1,1),
          buffered= True
          )
      
      #Add the data to Cerebro
      cerebro.adddata(data)
      
      # Set our desired cash start
      cerebro.broker.setcash(startcash)
      
      # Add the analyzers we are interested in
      cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
      cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
      
      # Run over everything
      strategies = cerebro.run()
      firstStrat = strategies[0]
      
      # print the analyzers
      printTradeAnalysis(firstStrat.analyzers.ta.get_analysis())
      printSQN(firstStrat.analyzers.sqn.get_analysis())
      
      #Get final portfolio Value
      portvalue = cerebro.broker.getvalue()
      
      #Print out the final result
      print('Final Portfolio Value: ${}'.format(portvalue))
      
      #Finally plot the end results
      cerebro.plot(style='candlestick')
      
      run-out 1 Reply Last reply Reply Quote 0
      • run-out
        run-out @Gleetche last edited by

        @gleetche said in Analyzer problem:

        else:
        if self.rsi > 70:
        self.sell(size=100)

        Removing this will result in no closed trades. In the trade analyzer, I would presume some of the fields/results don't get created if there are no closed trades, resulting in a lack of a field, resulting in a key error.

        RunBacktest.com

        G 1 Reply Last reply Reply Quote 3
        • G
          Gleetche @run-out last edited by

          @run-out Ohhhh thanks!

          1 Reply Last reply Reply Quote 0
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors