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/

    Rebalance quarterly

    General Code/Help
    2
    3
    907
    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.
    • C
      Crespecular last edited by

      Hi, I want to sell (cover for shorting) all the current long(short) holdings on my portfolio every quarter and replace them with the new stocks.

      class Short(bt.Strategy):
          
       
          params = (
          ('losscut', 0.05),
          ('profit', 0.05),
          ('max_stock', 5),
          )
      
          
          
          def __init__(self):
              self.inds = dict()
              self.entry = {}
              self.loss_cut = {}
              self.profit_realisation = {}
              self.shorting_list = []
              self.shorted_list = []
      
          def next(self):
              
              for i, d in enumerate(self.datas):
                  dt, dn = self.datetime.date(), d._name
                  pos = self.getposition(d).size
                  if pos == 0: 
                      if dn not in self.shorted_list:
                          if len(self.shorting_list) == self.params.max_stock:
                              return
                          else:
                              self.order_target_percent(data=d, target = -0.1)
                              self.entry.update({dn:d.close[0]})
                              self.shorted_list.append(dn)
                              self.shorting_list.append(dn)
                              
                  else:
                      if dt.month in [3,6,9,12]:
                         # I need the codes that clears the whole position in the beginning (or at the end) of every quarter (ex: 1st of March or 28th of March)'
                          pass
                      
                      if d.close[0] > self.entry[dn]*float(1 + self.params.losscut) == 1:
                          self.order_target_percent(data=d, target = 0)
                          self.loss_cut.update({dn:d.close[0]})
                          self.shorting_list.remove(dn)
                          
                      elif d.close[0]<self.entry[dn]*(1 - self.params.profit):
                          self.order_target_percent(data=d, target = 0)
                          self.profit_realisation.update({dn:d.close[0]})
                          self.shorting_list.remove(dn)
                          
      
      
                      pass
      

      If anyone knows something, please enlighten me!

      Thank you :D

      1 Reply Last reply Reply Quote 0
      • B
        backtrader administrators last edited by

        This post in reddit shows how rebalancing is done on each next iteration.

        • https://www.reddit.com/r/algotrading/comments/8f658v/the_conservative_formula_in_python_quantitative/

        In your case you want only to execute rebalancing once at the beginning of each quarter. To do so:

        • Keep a variable which holds what the next quarter will be in format YYYYMM for example
        • When the components of the current date match the quarter, you can rebalance.
        • Update the variable to the next quarter, which will be either: YYYY(MM + 3) or (YYYY + 1)03
        1 Reply Last reply Reply Quote 1
        • B
          backtrader administrators last edited by backtrader

          There is an additional path: use Docs - Timers

          You can watch day 1 of each month and only take action if the month is 3, 6, 9 or 12 or implement a callable which does the calculation and pass it to allow

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