Navigation

    Backtrader Community

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

    curious_one

    @curious_one

    0
    Reputation
    2
    Profile views
    13
    Posts
    0
    Followers
    0
    Following
    Joined Last Online

    curious_one Unfollow Follow

    Latest posts made by curious_one

    • Bollinger band top/bot .shift ability

      Re: BBand Strategy - code runs forever with no output

      @run-out

      I am trying to create a signal/trigger for my buy and sell when self.dataclose < self.bband.lines.bot.shift() ------ because I want to trade when the close price is above/below the bollinger top/bot at T-1.

      I tried it but I am getting this error below as per screenshot. please advise if there is a way to deal with that. thank you!

      Have also showed part of the code showing how I added .shift to my bollinger band strategy. Thanks.

                     (trade.pnl, trade.pnlcomm))
      
          
          def next(self):
              
      # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
      
      # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
              if self.getposition().size == 0:
                  if self.datahigh > self.bband.top.shift(1):
                      self.sell()
                  elif self.datalow < self.bband.bot.shift(1):
                      self.buy()
      
              if (self.getposition().size > 0 and self.dataclose > self.sma) or (
                  self.getposition().size < 0 and self.dataclose < self.sma):
                  self.close()
          
      
      
      AttributeError                            Traceback (most recent call last)
      <ipython-input-47-9a474057fbd2> in <module>
          123     cerebro.adddata(data)
          124     print('run begin')
      --> 125     optimized_runs = cerebro.run(maxcpus=1)
          126 
          127     print('runs completed: ' + str(len(optimized_runs)))
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\cerebro.py in run(self, **kwargs)
         1125             # let's skip process "spawning"
         1126             for iterstrat in iterstrats:
      -> 1127                 runstrat = self.runstrategies(iterstrat)
         1128                 self.runstrats.append(runstrat)
         1129                 if self._dooptimize:
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\cerebro.py in runstrategies(self, iterstrat, predata)
         1291                     self._runonce_old(runstrats)
         1292                 else:
      -> 1293                     self._runonce(runstrats)
         1294             else:
         1295                 if self.p.oldsync:
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\cerebro.py in _runonce(self, runstrats)
         1693 
         1694             for strat in runstrats:
      -> 1695                 strat._oncepost(dt0)
         1696                 if self._event_stop:  # stop if requested
         1697                     return
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\strategy.py in _oncepost(self, dt)
          309             self.next()
          310         elif minperstatus == 0:
      --> 311             self.nextstart()  # only called for the 1st value
          312         else:
          313             self.prenext()
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\lineiterator.py in nextstart(self)
          345 
          346         # Called once for 1st full calculation - defaults to regular next
      --> 347         self.next()
          348 
          349     def next(self):
      
      <ipython-input-47-9a474057fbd2> in next(self)
           86 
           87         if self.getposition().size == 0:
      ---> 88             if self.datahigh > self.bband.top.shift(1):
           89                 self.sell()
           90             elif self.datalow < self.bband.bot.shift(1):
      
      AttributeError: 'LineBuffer' object has no attribute 'shift'
      
      
      posted in Indicators/Strategies/Analyzers
      C
      curious_one
    • RE: BBand Strategy - code runs forever with no output

      @run-out Long time no chat :)

      I am trying to create a signal/trigger for my buy and sell when self.dataclose < self.bband.lines.bot.shift() ------ because I want to trade when the close price is above/below the bollinger top/bot at T-1.

      I tried it but I am getting this error below as per screenshot. please advise if there is a way to deal with that. thank you!

      AttributeError                            Traceback (most recent call last)
      <ipython-input-47-9a474057fbd2> in <module>
          123     cerebro.adddata(data)
          124     print('run begin')
      --> 125     optimized_runs = cerebro.run(maxcpus=1)
          126 
          127     print('runs completed: ' + str(len(optimized_runs)))
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\cerebro.py in run(self, **kwargs)
         1125             # let's skip process "spawning"
         1126             for iterstrat in iterstrats:
      -> 1127                 runstrat = self.runstrategies(iterstrat)
         1128                 self.runstrats.append(runstrat)
         1129                 if self._dooptimize:
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\cerebro.py in runstrategies(self, iterstrat, predata)
         1291                     self._runonce_old(runstrats)
         1292                 else:
      -> 1293                     self._runonce(runstrats)
         1294             else:
         1295                 if self.p.oldsync:
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\cerebro.py in _runonce(self, runstrats)
         1693 
         1694             for strat in runstrats:
      -> 1695                 strat._oncepost(dt0)
         1696                 if self._event_stop:  # stop if requested
         1697                     return
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\strategy.py in _oncepost(self, dt)
          309             self.next()
          310         elif minperstatus == 0:
      --> 311             self.nextstart()  # only called for the 1st value
          312         else:
          313             self.prenext()
      
      ~\AppData\Local\Continuum\anaconda3\lib\site-packages\backtrader\lineiterator.py in nextstart(self)
          345 
          346         # Called once for 1st full calculation - defaults to regular next
      --> 347         self.next()
          348 
          349     def next(self):
      
      <ipython-input-47-9a474057fbd2> in next(self)
           86 
           87         if self.getposition().size == 0:
      ---> 88             if self.datahigh > self.bband.top.shift(1):
           89                 self.sell()
           90             elif self.datalow < self.bband.bot.shift(1):
      
      AttributeError: 'LineBuffer' object has no attribute 'shift'
      
      
      posted in Indicators/Strategies/Analyzers
      C
      curious_one
    • RE: BBand Strategy - code runs forever with no output

      @run-out thanks so much. This code you provided works now. Though the sharpe ratio and pnl are both horrible (no surprise here since it is such a simple strategy). However, it works! and I can tweak the strategy accordingly from here. Cheers!

      posted in Indicators/Strategies/Analyzers
      C
      curious_one
    • RE: BBand Strategy - code runs forever with no output

      @ab_trader and anyone else in the community....

      I am currently switching up my strategies from the original version. As I just started coding python, especially for this backtrader suite (amazing), I am posting following code to check if I am doing it correctly....

      It is a simple strategy.

      • Buy (open new position) when close price is below the lower band.
      • Sell (close the position due to my buy) when close price is at or above the mid band.

      Conversely

      • Sell (open new position) when close price is above the upper band
      • Buy (close the position due to my sell) when close price is at or below the mid band.

      Pls feedback and advise. Thanks.

      ###### VERSION 2 ##########
      
      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      
      import backtrader.indicators as btind
      
      class BBands(bt.Strategy):
          params = (('BBandsperiod', 20), ('devfactor' , 2),('logging',True))
      
          def log(self, txt, dt=None):
              ''' Logging function fot this strategy'''
              if self.params.logging:
                  dt = dt or self.datas[0].datetime.date(0)
                  print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
      
              # To keep track of pending orders and buy price/commission
              self.order = None
              self.buyprice = None
              self.buycomm = None
              self.redline = None
              self.blueline = None
              self.topline = None
      
      
              # Add a BBand indicator
              self.bband = bt.indicators.BBands(self.datas[0], period=self.params.BBandsperiod, devfactor = self.params.devfactor)
      
          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
      
              # Check if an order has been completed
              # Attention: broker could reject order if not enougth cash
              if order.status in [order.Canceled, order.Margin]:
                  if order.isbuy():
                      self.log(
                          'BUY FAILED, Cancelled or Margin'
                          )
                  self.log
              if order.status in [order.Completed, order.Canceled, order.Margin]:
                  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:  # Sell
                      self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm))
      
                  self.bar_executed = len(self)
      
              # Write down: no pending order
              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):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
              if self.dataclose < self.bband.lines.bot and not self.position:
              	self.redline = True
      
              if self.dataclose > self.bband.lines.top and self.position:
              	self.blueline = True
                  
              if self.dataclose > self.bband.lines.top and not self.position:
                  self.topline = True
                  
              if self.dataclose < self.bband.lines.bot and not self.position and self.redline:
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  self.order = self.buy()
               
              if self.dataclose >= self.bband.lines.mid and self.position and self.redline:
                  self.log('SELL CLOSE, %.2f' % self.dataclose[0])
                  self.order = self.sell()
                  
              if self.dataclose > self.bband.lines.top and not self.position:
                  self.log('SELL CREATE, %.2f' % self.dataclose[0])
                  self.order = self.sell()
      
              if self.dataclose <= self.bband.lines.mid and self.position and self.topline:
                  self.log('BUY CLOSE, %.2f' % self.dataclose[0])
                  self.order = self.buy()
                 
      
      def optimizer_callbacks(cb):
          print('optcallback executed')
      
      if __name__ == '__main__':
          print('Starting up Cerebro...')
          cerebro = bt.Cerebro(optreturn=False)
          cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe_ratio') 
          cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trades")   
          cerebro.optcallback(optimizer_callbacks)    
          cerebro.broker.setcommission(commission=0.0)  # 0% commission
          
          cerebro.optstrategy(BBands,
                              BBandsperiod=range(18,31),
                              devfactor = range(1,6),
                              logging=False
                              )
      
          cerebro.addsizer(bt.sizers.SizerFix, stake=0.1)
          start_portfolio_value = 10000.0
          cerebro.broker.setcash(start_portfolio_value)
          #print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
          
          data = bt.feeds.PandasData(dataname = df_daily)
          
          cerebro.adddata(data)
          print('run begin')
          optimized_runs = cerebro.run(maxcpus=1)
          print('runs completed: ' + str(len(optimized_runs)))
      
          
          for optimized_run in optimized_runs:
              for strategy in optimized_run:
                  print(strategy.params.BBandsperiod)
                  print(strategy.params.devfactor)
                  try:
                      print(strategy.analyzers.trades.get_analysis())
                      print(strategy.analyzers.sharpe_ratio.get_analysis())
                      print('---------------------------------------')
                  except:
                      print('not enough data...')
      
      posted in Indicators/Strategies/Analyzers
      C
      curious_one
    • RE: BBand Strategy - code runs forever with no output

      @ab_trader Hi, it does run the close price. However, it seems to work now after I used the slightly edited version of this code in this thread (https://community.backtrader.com/topic/2549/beginner-optimizer-and-analyzer-help/6). Code below. Thanks :)

      code_text
      
      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      
      import backtrader.indicators as btind
      
      class BBands(bt.Strategy):
          params = (('BBandsperiod', 20),('logging',True))
      
          def log(self, txt, dt=None):
              ''' Logging function fot this strategy'''
              if self.params.logging:
                  dt = dt or self.datas[0].datetime.date(0)
                  print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
      
              # To keep track of pending orders and buy price/commission
              self.order = None
              self.buyprice = None
              self.buycomm = None
              self.redline = None
              self.blueline = None
      
              # Add a BBand indicator
              self.bband = bt.indicators.BBands(self.datas[0], period=self.params.BBandsperiod)
      
          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
      
              # Check if an order has been completed
              # Attention: broker could reject order if not enougth cash
              if order.status in [order.Canceled, order.Margin]:
                  if order.isbuy():
                      self.log(
                          'BUY FAILED, Cancelled or Margin'
                          )
                  self.log
              if order.status in [order.Completed, order.Canceled, order.Margin]:
                  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:  # Sell
                      self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                               (order.executed.price,
                                order.executed.value,
                                order.executed.comm))
      
                  self.bar_executed = len(self)
      
              # Write down: no pending order
              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):
              # Simply log the closing price of the series from the reference
              #self.log('Close, %.2f' % self.dataclose[0])
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
              if self.dataclose < self.bband.lines.bot and not self.position:
              	self.redline = True
      
              if self.dataclose > self.bband.lines.top and self.position:
              	self.blueline = True
      
              if self.dataclose > self.bband.lines.mid and not self.position and self.redline:        	
              	# BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose > self.bband.lines.top and not self.position:
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose < self.bband.lines.mid and self.position and self.blueline:
                  # SELL, SELL, SELL!!! (with all possible default parameters)
                  self.log('SELL CREATE, %.2f' % self.dataclose[0])
                  self.blueline = False
                  self.redline = False
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.sell()                
                 
      
      def optimizer_callbacks(cb):
          print('optcallback executed')
      
      if __name__ == '__main__':
          print('Starting up Cerebro...')
          cerebro = bt.Cerebro(optreturn=False)
          cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe_ratio') 
          cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trades")   
          cerebro.optcallback(optimizer_callbacks)    
          cerebro.broker.setcommission(commission=0.0)  # 0% commission
          
          cerebro.optstrategy(BBands,
                              BBandsperiod=range(90,96),
                              logging=False
                              )
      
          cerebro.addsizer(bt.sizers.SizerFix, stake=0.1)
          start_portfolio_value = 10000.0
          cerebro.broker.setcash(start_portfolio_value)
          #print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
          
          data = bt.feeds.PandasData(dataname = df_daily)
          
          cerebro.adddata(data)
          print('run begin')
          optimized_runs = cerebro.run(maxcpus=1)
          print('runs completed: ' + str(len(optimized_runs)))
      
          
          for optimized_run in optimized_runs:
              for strategy in optimized_run:
                  print(strategy.params.BBandsperiod)
                  try:
                      print(strategy.analyzers.trades.get_analysis())
                      print(strategy.analyzers.sharpe_ratio.get_analysis())
                      print('---------------------------------------')
                  except:
                      print('not enough data...')
      
      posted in Indicators/Strategies/Analyzers
      C
      curious_one
    • RE: BBand Strategy - code runs forever with no output

      @ab_trader Thanks a lot for the response. And apologies on creating multiple topics regarding the same thing. It is my first time using this (or in fact any type of) community platform hence I am trying to figure out the best way to post these questions to the community.

      Regarding me using df_daily. I was using this data set as per below screenshot - apols for the confusion. The code runs forever with while having only the one output of "Starting Portfolio Value: 10000.00".

      1d22c3af-4cd5-4f7b-9393-b6f973a02845-image.png

      posted in Indicators/Strategies/Analyzers
      C
      curious_one
    • RE: Code running forever but no output

      @run-out Really appreciate your reply! I used the code provided in this thread (https://community.backtrader.com/topic/122/bband-strategy) at BBand Strategy and it worked. The queries you had were addressed in that thread too as per screenshot below. It worked for others but not for me. Hence, I am not sure where I went wrong :/

      cf53cb19-c050-4328-a6f3-014132016515-image.png

      posted in General Code/Help
      C
      curious_one
    • BBand Strategy - code runs forever with no output

      Re: BBand Strategy

      Hi, I tried using almost the exact same code you provided on this Bband strategy, albeit with a different dataframe here (screenshot of dataframe table is below).

      The code does not stop running and it has technically no output other than this: "Starting Portfolio Value: 10000.00".

      The code has been running (as shown in image screenshot below with the * circled in pink) in Jupyter notebook for an hour (forever)and I only have 3000 rows and 2 columns worth of data containing Date on the index and Close price in another column. Hence, I am very puzzled by this.

      I have copy and pasted the code below. Can someone help please? Thank you vm in advance~!

      ed529d5f-0bea-469c-8e9c-507ce9e3b9ce-image.png

      ed6e6001-4c2c-4d4d-a5e9-23a17d2dff27-image.png

      code_text 
      
      class teststrat(bt.Strategy):
          
          params = (
              ('n',20),
              ('m',2),# Tuple of tuples containing any variable settings required by the strategy.
              ('printlog',False), # Stop printing the log of the trading strategy
              
          )
          
          def __init__(self):
              self.dataclose= self.datas[0].close    # Keep a reference to the "close" line in the data[0] dataseries
              self.order = None # Property to keep track of pending orders.  There are no orders when the strategy is initialized.
              self.buyprice = None
              self.buycomm = None
              self.redline = None
              self.blueline = None
              
              # Add Bband indicator for use in the trading strategy
              self.bband = bt.indicators.BBands( 
                  self.datas[0], period=self.params.n, devfactor=self.params.m)
          
          def log(self, txt, dt=None, doprint=False):
              if self.params.printlog or doprint: # Add if statement to only log of printlog or doprint is True
                  dt = dt or self.datas[0].datetime.date(0)
                  print('{0},{1}'.format(dt.isoformat(),txt))
          
          def notify_order(self, order):
              # 1. If order is submitted/accepted, do nothing 
              if order.status in [order.Submitted, order.Accepted]:
                  return
              # 2. If order is buy/sell executed, report price executed
              if order.status in [order.Completed]: 
                  if order.isbuy():
                      self.log('BUY EXECUTED, Price: {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm: {3:8.2f}'.format(
                          order.executed.price,
                          order.executed.size,
                          order.executed.value,
                          order.executed.comm))
                      
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else:
                      self.log('SELL EXECUTED, {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm{3:8.2f}'.format(
                          order.executed.price, 
                          order.executed.size, 
                          order.executed.value,
                          order.executed.comm))
                  
                  self.bar_executed = len(self) #when was trade executed
              # 3. If order is canceled/margin/rejected, report order canceled
              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 {0:8.2f}, NET {1:8.2f}'.format(
                  trade.pnl, trade.pnlcomm))
          
      def next(self):
              # Simply log the closing price of the series from the reference
              self.log('close, %.2f' % self.dataclose[0])
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
              if self.dataclose < self.bband.lines.bot and not self.position:
                  self.redline = True
      
              if self.dataclose > self.bband.lines.top and self.position:
                  self.blueline = True
      
              if self.dataclose > self.bband.lines.mid and not self.position and self.redline:        	
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose > self.bband.lines.top and not self.position:
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose < self.bband.lines.mid and self.position and self.blueline:
                  # SELL, SELL, SELL!!! (with all possible default parameters)
                  self.log('SELL CREATE, %.2f' % self.dataclose[0])
                  self.blueline = False
                  self.redline = False
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.sell()
      
      # Create a cerebro entity            
      cerebro = bt.Cerebro()
      
      # Add a strategy
      cerebro.addstrategy(teststrat)
      
      # Create a Data Feed
      data = bt.feeds.PandasData(dataname = df_daily)
                                  #, openinterest=False,open=False,high=False,low=False,close=-1,volume=False)
      
      # Add the Data Feed to Cerebro
      cerebro.adddata(data)
                  
      
      
      # Datas are in a subfolder of the samples. Need to find where the script is
      # because it could have been called from anywhere
      #modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
      #datapath = os.path.join(modpath, 'TSLA-USD.csv')
      
      
      strats = cerebro.optstrategy(
          teststrat,
          n=range(10,50),
          m=range(1,5),
          printlog=False)
      
      # Set our desired cash start
      cerebro.broker.setcash(10000.0)
      
      # Add a FixedSize sizer according to the stake
      cerebro.addsizer(bt.sizers.FixedSize, stake=5)
      
      # Set the commission
      cerebro.broker.setcommission(commission=0.002)
      
      # Print out the starting conditions
      print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Run over everything
      cerebro.run()
      
      # Print out the final result
      print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Plot the result
      cerebro.plot()
      
      

      Starting Portfolio Value: 10000.00

      posted in Indicators/Strategies/Analyzers
      C
      curious_one
    • Code running forever but no output

      Hi, after fixing the datetime such that it is datetimeindex, I can run the code with no errors. However, now the code does not stop running and it has technically no output other than this: "Starting Portfolio Value: 10000.00".

      The code has been running (as shown in image screenshot below with the * circled in pink) in Jupyter notebook for at least 15 minutes and I only have 3000 rows and 2 columns worth of data containing Date on the index and Close price in another column. Hence, I am very puzzled by this.

      I have copy and pasted the code below. Can someone help please? Thank you vm in advance~!

      b121d31b-d3e5-44ce-a944-5c8463371362-image.png

      code_text
      
      class teststrat(bt.Strategy):
          
          params = (
              ('n',20),
              ('m',2),# Tuple of tuples containing any variable settings required by the strategy.
              ('printlog',False), # Stop printing the log of the trading strategy
              
          )
          
          def __init__(self):
              self.dataclose= self.datas[0].close    # Keep a reference to the "close" line in the data[0] dataseries
              self.order = None # Property to keep track of pending orders.  There are no orders when the strategy is initialized.
              self.buyprice = None
              self.buycomm = None
              self.redline = None
              self.blueline = None
              
              # Add Bband indicator for use in the trading strategy
              self.bband = bt.indicators.BBands( 
                  self.datas[0], period=self.params.n, devfactor=self.params.m)
          
          def log(self, txt, dt=None, doprint=False):
              if self.params.printlog or doprint: # Add if statement to only log of printlog or doprint is True
                  dt = dt or self.datas[0].datetime.date(0)
                  print('{0},{1}'.format(dt.isoformat(),txt))
          
          def notify_order(self, order):
              # 1. If order is submitted/accepted, do nothing 
              if order.status in [order.Submitted, order.Accepted]:
                  return
              # 2. If order is buy/sell executed, report price executed
              if order.status in [order.Completed]: 
                  if order.isbuy():
                      self.log('BUY EXECUTED, Price: {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm: {3:8.2f}'.format(
                          order.executed.price,
                          order.executed.size,
                          order.executed.value,
                          order.executed.comm))
                      
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else:
                      self.log('SELL EXECUTED, {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm{3:8.2f}'.format(
                          order.executed.price, 
                          order.executed.size, 
                          order.executed.value,
                          order.executed.comm))
                  
                  self.bar_executed = len(self) #when was trade executed
              # 3. If order is canceled/margin/rejected, report order canceled
              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 {0:8.2f}, NET {1:8.2f}'.format(
                  trade.pnl, trade.pnlcomm))
          
      def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
              if self.dataclose < self.bband.lines.bot and not self.position:
                  self.redline = True
      
              if self.dataclose > self.bband.lines.top and self.position:
                  self.blueline = True
      
              if self.dataclose > self.bband.lines.mid and not self.position and self.redline:        	
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose > self.bband.lines.top and not self.position:
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose < self.bband.lines.mid and self.position and self.blueline:
                  # SELL, SELL, SELL!!! (with all possible default parameters)
                  self.log('SELL CREATE, %.2f' % self.dataclose[0])
                  self.blueline = False
                  self.redline = False
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.sell()
      
      # Create a cerebro entity            
      cerebro = bt.Cerebro()
      
      # Add a strategy
      cerebro.addstrategy(teststrat)
      
      # Create a Data Feed
      data = bt.feeds.PandasData(dataname = df_daily)
                                  #, openinterest=False,open=False,high=False,low=False,close=-1,volume=False)
      
      # Add the Data Feed to Cerebro
      cerebro.adddata(data)
                  
      
      
      # Datas are in a subfolder of the samples. Need to find where the script is
      # because it could have been called from anywhere
      #modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
      #datapath = os.path.join(modpath, 'TSLA-USD.csv')
      
      
      strats = cerebro.optstrategy(
          teststrat,
          n=range(10,50),
          m=range(1,5),
          printlog=False)
      
      # Set our desired cash start
      cerebro.broker.setcash(10000.0)
      
      # Add a FixedSize sizer according to the stake
      cerebro.addsizer(bt.sizers.FixedSize, stake=5)
      
      # Set the commission
      cerebro.broker.setcommission(commission=0.002)
      
      # Print out the starting conditions
      print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Run over everything
      cerebro.run()
      
      # Print out the final result
      print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Plot the result
      cerebro.plot()
      
      

      Starting Portfolio Value: 10000.00

      posted in General Code/Help
      C
      curious_one
    • RE: Resolve this error!

      Hi, after fixing the datetime such that it is datetimeindex, I can run the code with no errors. However, now the code does not stop running and it has technically no output other than this: "Starting Portfolio Value: 10000.00".

      The code has been running (as shown in image screenshot below with the * circled in pink) in Jupyter notebook for at least 15 minutes and I only have 3000 rows and 2 columns worth of data containing Date on the index and Close price in another column. Hence, I am very puzzled by this.

      I have copy and pasted the code below. Can someone help please? Thank you vm in advance~!

      a6b8f18f-9f4f-4ade-a963-b5fcc97e3419-image.png

      code_text 
      
      class teststrat(bt.Strategy):
          
          params = (
              ('n',20),
              ('m',2),# Tuple of tuples containing any variable settings required by the strategy.
              ('printlog',False), # Stop printing the log of the trading strategy
              
          )
          
          def __init__(self):
              self.dataclose= self.datas[0].close    # Keep a reference to the "close" line in the data[0] dataseries
              self.order = None # Property to keep track of pending orders.  There are no orders when the strategy is initialized.
              self.buyprice = None
              self.buycomm = None
              self.redline = None
              self.blueline = None
              
              # Add Bband indicator for use in the trading strategy
              self.bband = bt.indicators.BBands( 
                  self.datas[0], period=self.params.n, devfactor=self.params.m)
          
          def log(self, txt, dt=None, doprint=False):
              if self.params.printlog or doprint: # Add if statement to only log of printlog or doprint is True
                  dt = dt or self.datas[0].datetime.date(0)
                  print('{0},{1}'.format(dt.isoformat(),txt))
          
          def notify_order(self, order):
              # 1. If order is submitted/accepted, do nothing 
              if order.status in [order.Submitted, order.Accepted]:
                  return
              # 2. If order is buy/sell executed, report price executed
              if order.status in [order.Completed]: 
                  if order.isbuy():
                      self.log('BUY EXECUTED, Price: {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm: {3:8.2f}'.format(
                          order.executed.price,
                          order.executed.size,
                          order.executed.value,
                          order.executed.comm))
                      
                      self.buyprice = order.executed.price
                      self.buycomm = order.executed.comm
                  else:
                      self.log('SELL EXECUTED, {0:8.2f}, Size: {1:8.2f} Cost: {2:8.2f}, Comm{3:8.2f}'.format(
                          order.executed.price, 
                          order.executed.size, 
                          order.executed.value,
                          order.executed.comm))
                  
                  self.bar_executed = len(self) #when was trade executed
              # 3. If order is canceled/margin/rejected, report order canceled
              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 {0:8.2f}, NET {1:8.2f}'.format(
                  trade.pnl, trade.pnlcomm))
          
      def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
      
              # Check if an order is pending ... if yes, we cannot send a 2nd one
              if self.order:
                  return
      
              if self.dataclose < self.bband.lines.bot and not self.position:
                  self.redline = True
      
              if self.dataclose > self.bband.lines.top and self.position:
                  self.blueline = True
      
              if self.dataclose > self.bband.lines.mid and not self.position and self.redline:        	
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose > self.bband.lines.top and not self.position:
                  # BUY, BUY, BUY!!! (with all possible default parameters)
                  self.log('BUY CREATE, %.2f' % self.dataclose[0])
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.buy()
      
              if self.dataclose < self.bband.lines.mid and self.position and self.blueline:
                  # SELL, SELL, SELL!!! (with all possible default parameters)
                  self.log('SELL CREATE, %.2f' % self.dataclose[0])
                  self.blueline = False
                  self.redline = False
                  # Keep track of the created order to avoid a 2nd order
                  self.order = self.sell()
      
      # Create a cerebro entity            
      cerebro = bt.Cerebro()
      
      # Add a strategy
      cerebro.addstrategy(teststrat)
      
      # Create a Data Feed
      data = bt.feeds.PandasData(dataname = df_daily)
                                  #, openinterest=False,open=False,high=False,low=False,close=-1,volume=False)
      
      # Add the Data Feed to Cerebro
      cerebro.adddata(data)
                  
      
      
      # Datas are in a subfolder of the samples. Need to find where the script is
      # because it could have been called from anywhere
      #modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
      #datapath = os.path.join(modpath, 'TSLA-USD.csv')
      
      
      strats = cerebro.optstrategy(
          teststrat,
          n=range(10,50),
          m=range(1,5),
          printlog=False)
      
      # Set our desired cash start
      cerebro.broker.setcash(10000.0)
      
      # Add a FixedSize sizer according to the stake
      cerebro.addsizer(bt.sizers.FixedSize, stake=5)
      
      # Set the commission
      cerebro.broker.setcommission(commission=0.002)
      
      # Print out the starting conditions
      print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Run over everything
      cerebro.run()
      
      # Print out the final result
      print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
      
      # Plot the result
      cerebro.plot()
      
      Starting Portfolio Value: 10000.00
      
      
      posted in General Code/Help
      C
      curious_one