C

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!