Backtrader Community

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

    Arun Lama

    @Arun Lama

    I used to do backtesting in Excel but due to some limitations there I'm shifting to python. I started learning python during the COVID-19 lockdown. Passed CMT Level III.

    1
    Reputation
    23
    Profile views
    7
    Posts
    0
    Followers
    1
    Following
    Joined Last Online

    Arun Lama Unfollow Follow

    Best posts made by Arun Lama

    • RE: Passing a dataframe with all indicator/signal precalculated

      @azuric This is how I add Pandas Dataframe to datafeeds

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

      and this is how I used talib library to calculate indicators (you can get indicator calculations from backtrader itself too)

      class SmaCross(bt.Strategy):    
              params = dict(pslow=20,order_percentage= 0.99,ticker = 'NEPSE')         
                  def __init__(self):    
                  sma = bt.talib.SMA(self.data.close,timeperiod=self.p.pslow)    
                  self.crossover = bt.ind.CrossOver(self.data.close, sma, plot = True)  
          
              ``
      posted in General Code/Help
      Arun Lama
      Arun Lama

    Latest posts made by Arun Lama

    • How to create pyfolio round trip tearsheet?

      Hi, I'm trying to create round_trip_tearsheet using pyfolio because it has trade stats like profit factor, average winning trade, average losing trade, percent profitable, etc. I found two ways to do it. One is by adding round_trips= True in pf.create_full_tearsheet and another is using pf.create_round_trip_tear_sheet but I failed in both.

      upon running the first one, I get some stats and charts but not the stats I want with RuntimeError: Selected KDE bandwidth is 0. Cannot estiamte density.

      Second alternative with create_round_trip_tear_sheet gives KeyError: ('block_dir', 'block_time')

      Please shed some light here on how I can get those trade stats. Thank you in advance. @ab_trader Below is my full code.

      %matplotlib inline
      from datetime import datetime
      import backtrader as bt
      import pandas as pd
      import math
      import pyfolio as pf
      import backtrader.analyzers as btanalyzers
      class SmaCross(bt.Strategy):
          params = dict(pslow=20,order_percentage= 0.99,ticker = 'NEPSE')
          
          def log(self, txt, dt=None):
                  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, plot = True)  
          
          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)           
      #                 self.log('%s,Buy, %d,%d 0,%.0f' % (self.params.ticker,self.size,self.data.close[0],cerebro.broker.getvalue()))
              elif self.crossover < 0: 
                      self.close() 
      #                 self.log('%s,Sell, %d,%d 0,%.0f' % (self.params.ticker,self.size,self.data.close[0],cerebro.broker.getvalue()))
          
      cerebro = bt.Cerebro()  
      feed = pd.read_csv('test.csv',index_col = 'Date',parse_dates = True)
      data = bt.feeds.PandasData(dataname = feed)
      cerebro.adddata(data) 
      cerebro.addstrategy(SmaCross)  
      print('Starting Portfolio Value: %.0f' % cerebro.broker.getvalue())
      # strat = cerebro.run()
      print('Final Portfolio Value: %.0f' % cerebro.broker.getvalue())
      cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio')
      results = cerebro.run()
      strat = results[0]
      pyfoliozer = strat.analyzers.getbyname('pyfolio')
      returns, positions, transactions, gross_lev = pyfoliozer.get_pf_items()
      pf.create_round_trip_tear_sheet(returns, positions, transactions)
      # pf.create_full_tear_sheet(
      #     returns,
      #     positions=positions,
      #     transactions=transactions,
      #     round_trips=True)
      
      
      posted in Indicators/Strategies/Analyzers
      Arun Lama
      Arun Lama
    • RE: Passing a dataframe with all indicator/signal precalculated

      @azuric This is how I add Pandas Dataframe to datafeeds

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

      and this is how I used talib library to calculate indicators (you can get indicator calculations from backtrader itself too)

      class SmaCross(bt.Strategy):    
              params = dict(pslow=20,order_percentage= 0.99,ticker = 'NEPSE')         
                  def __init__(self):    
                  sma = bt.talib.SMA(self.data.close,timeperiod=self.p.pslow)    
                  self.crossover = bt.ind.CrossOver(self.data.close, sma, plot = True)  
          
              ``
      posted in General Code/Help
      Arun Lama
      Arun Lama
    • RE: How to display pnl , size, ticker, portfolio value and date on single row?

      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.

      posted in General Code/Help
      Arun Lama
      Arun Lama
    • RE: How to display pnl , size, ticker, portfolio value and date on single row?
      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.

      posted in General Code/Help
      Arun Lama
      Arun Lama
    • RE: How to display pnl , size, ticker, portfolio value and date on single row?

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

      posted in General Code/Help
      Arun Lama
      Arun Lama
    • RE: How to display pnl , size, ticker, portfolio value and date on single row?

      @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()

      posted in General Code/Help
      Arun Lama
      Arun Lama
    • How to display pnl , size, ticker, portfolio value and date on single row?

      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

      posted in General Code/Help
      Arun Lama
      Arun Lama