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

More Backtrader way to calculate covariance matrix



  • I am trying to calculate the covariance matrix of a multiple asset portfolio at every period with N lookback period. My current implementation uses a counter to wait out the lookback period and then runs all calculations in the def next() method.

     def next(self):
            if (self.counter < self.p.rperiod):
                self.counter += 1
            else:
                # stack the closes together into a numpy array for ease of calculation
                closes = np.stack(([d.close.get(0,self.p.rperiod).tolist() for d in self.datas]))
                rets = np.diff(np.log(closes))
                # covariance matrix. will be shoved somewhere else for records
                cov = np.cov(rets)
    

    While it 'works', what is the more backtrader way of doing the same thing?

    For example, there's the PctChange indicator for calculating percentage change that is defined at __init__.

    def __init__(self):
        rets = [bt.ind.PctChange(d, period=self.p.rperiod) for d in self.datas]
    

    But how do I access the value of N periods of indicators, run calculations, and then construct cross-asset indicators? And would it be possible to have, say, an indicator that contains multidimensional matrices?

    Much thanks!


  • administrators

    @cnimativ said in More Backtrader way to calculate covariance matrix:

    My current implementation uses a counter to wait out the lookback period and then runs all calculations in the def next() method.

    You should be using the addminperiod API or subclassing from the indicator PeriodN.

    @cnimativ said in More Backtrader way to calculate covariance matrix:

    While it 'works', what is the more backtrader way of doing the same thing?

    You calculate something in next using numpy. What would you be looking for?

    @cnimativ said in More Backtrader way to calculate covariance matrix:

    But how do I access the value of N periods of indicators, run calculations, and then construct cross-asset indicators?

    You are already using get

    @cnimativ said in More Backtrader way to calculate covariance matrix:

    And would it be possible to have, say, an indicator that contains multidimensional matrices?

    Not a clue what you mean. Indicator have lines. You may of course store anything in a member attribute.