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/

    How to display pnl , size, ticker, portfolio value and date on single row?

    General Code/Help
    2
    8
    234
    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.
    • Arun Lama
      Arun Lama last edited by

      Hi, I'm new to python and backtrader. I'm trying to replicate a price and SMA crossover strategy and when I run the program I get the following result. Everything is fine but I want to print that pnl for every trade on the same row as Date, Ticker,...etc.

      I printed Date, ticker, cost, size,... here by using :
      self.log(
      '%s, BUY, %.2f, %.2f, %.2f' %
      (self.params.ticker,
      self.size,
      self.data.close[0],
      cerebro.broker.getvalue()
      ))

      and pnl using :

      def notify_trade(self, trade):
          if not trade.isclosed:
              return
          self.log('%.2f' %
                   (trade.pnl))
      

      3cfa5d27-c235-4824-85c6-c767c99c33dd-image.png

      1 Reply Last reply Reply Quote 0
      • A
        ab_trader last edited by

        def notify_trade(self, trade):
            if not trade.isclosed:
                return
            self.log('%.2f, %s, %.2f, %.2f, %.2f' %
                     (trade.pnl, self.params.ticker, self.size, self.data.close[0], cerebro.broker.getvalue()
        
        Arun Lama 2 Replies Last reply Reply Quote 1
        • Arun Lama
          Arun Lama @ab_trader last edited by

          @ab_trader I got an error in def next(self): as invalid syntax. I've posted my whole code below so that you can get a clear picture. Thank you very much for your help. It means a lot to me. God bless you.

          from datetime import datetime
          import backtrader as bt
          import pandas as pd
          import math

          class SmaCross(bt.Strategy):
          params = dict(pslow=20,order_percentage= 0.99,ticker = 'NEPSE')

          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):
              sma = bt.talib.SMA(self.data.close,timeperiod=self.p.pslow)
              self.crossover = bt.ind.CrossOver(self.data.close, sma)  
              
              
          
          def notify_trade(self, trade):
              if not trade.isclosed:
                  return
              self.log('%.2f' %
                       (trade.pnl))   
                                
          def next(self):
              if not self.position:  
                  if self.crossover > 0:  
                      amount_to_invest = (self.p.order_percentage*self.broker.cash)
                      self.size = math.floor(amount_to_invest/self.data.close)
                      self.log(
                          '%s, BUY, %.2f, %.2f, %.2f' %
                          (self.params.ticker,
                           self.size,
                           self.data.close[0],
                          cerebro.broker.getvalue()
                          ))
                      self.buy(size=self.size) 
          
              elif self.crossover < 0:  
                      self.log(
                          '%s, Sell, %.2f, %.2f, %.2f' %
                          (self.params.ticker,
                           self.size,
                           self.data.close[0],
                           cerebro.broker.getvalue()
                           ))
                      self.close() 
          

          cerebro = bt.Cerebro()
          feed = pd.read_csv('test.csv',index_col = 'Date',parse_dates = True)
          data = bt.feeds.PandasData(dataname = feed)
          data
          cerebro.adddata(data)
          cerebro.addstrategy(SmaCross)

          print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
          cerebro.run()
          cerebro.addwriter(bt.WriterFile, csv = True, out='your_strategy_results')
          print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
          cerebro.plot()

          1 Reply Last reply Reply Quote 0
          • Arun Lama
            Arun Lama @ab_trader last edited by

            @ab_trader It seems that the immediate code that follows notify_trade is shown as invalid syntax.

            1 Reply Last reply Reply Quote 0
            • A
              ab_trader last edited by

              First, repost your code considering statement about backticks on the top of the page.

              Second, post actual error message within the backticks. Your posts described error message in two different places of the script. So let's take a look on the actual one.

              Arun Lama 1 Reply Last reply Reply Quote 1
              • Arun Lama
                Arun Lama @ab_trader last edited by

                from datetime import datetime
                import backtrader as bt
                import pandas as pd
                import math
                
                class SmaCross(bt.Strategy):
                    params = dict(pslow=20,order_percentage= 0.99,ticker = 'NEPSE')
                    
                    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):
                        sma = bt.talib.SMA(self.data.close,timeperiod=self.p.pslow)
                        self.crossover = bt.ind.CrossOver(self.data.close, sma)  
                    
                    def notify_trade(self, trade):
                                    if not trade.isclosed:
                                        return
                                    self.log('%.2f, %s, %.2f, %.2f, %.2f' %
                                     (trade.pnl, self.params.ticker, self.size, self.data.close[0], cerebro.broker.getvalue()  
                                           
                    def next(self):
                        if not self.position:  
                            if self.crossover > 0: 
                                
                                amount_to_invest = (self.p.order_percentage*self.broker.cash)
                                self.size = math.floor(amount_to_invest/self.data.close)
                                self.buy(size=self.size) 
                    
                        elif self.crossover < 0:  
                                self.close() 
                    
                cerebro = bt.Cerebro()  
                feed = pd.read_csv('test.csv',index_col = 'Date',parse_dates = True)
                data = bt.feeds.PandasData(dataname = feed)
                data
                cerebro.adddata(data) 
                cerebro.addstrategy(SmaCross)  
                
                print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
                cerebro.run() 
                print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
                cerebro.plot()  
                
                
                  File "<ipython-input-29-9a6b79c4a5d7>", line 25
                    def next(self):
                      ^
                SyntaxError: invalid syntax
                

                I hope followed your instructions.

                A 1 Reply Last reply Reply Quote 0
                • A
                  ab_trader @Arun Lama last edited by

                  @Arun-Lama I strongly recommend you to study python first. If you will be asking such questions here and waiting for several days for an answer, you will not move anywhere. Looks like parentheses are missed in the script and this is not bt related error:

                  self.log('%.2f, %s, %.2f, %.2f, %.2f' %
                                       (trade.pnl, self.params.ticker, self.size, self.data.close[0], cerebro.broker.getvalue())) 
                  
                  1 Reply Last reply Reply Quote 1
                  • Arun Lama
                    Arun Lama last edited by

                    I feel ashamed for such mistakes. Thank you very much sir. What I thought was if it was parenthesis related problem, I thought it would be indicated in the error but it looks something different. Thank you. God Bless you.

                    1 Reply Last reply Reply Quote 0
                    • 1 / 1
                    • First post
                      Last post
                    Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
                    $(document).ready(function () { app.coldLoad(); }); }