For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:

Rebalance quarterly

  • 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 =, 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:
                            self.order_target_percent(data=d, target = -0.1)
                    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)'
                    if d.close[0] > self.entry[dn]*float(1 + self.params.losscut) == 1:
                        self.order_target_percent(data=d, target = 0)
                    elif d.close[0]<self.entry[dn]*(1 - self.params.profit):
                        self.order_target_percent(data=d, target = 0)

    If anyone knows something, please enlighten me!

    Thank you :D

  • administrators

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

    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

  • administrators

    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