Hi Sabir, bt.DivByZero
is what you're looking for. Here's an example where I use it
class WeighInverseVol(bt.Strategy):
params = (
('period', 30),
)
def __init__(self):
rs = [bt.ind.PctChange(d, period=1) for d in self.datas]
vs = [bt.ind.StdDev(ret, period=self.params.period) for ret in rs]
inv = [bt.DivByZero(bt.LineNum(1), v) for v in vs]
invsum = bt.LineNum(0)
for inv_ in inv:
invsum += inv_
# self.weights is an array of asset allocation weights
# one weight per asset in self.datas
self.weights = [inv_ / invsum for inv_ in inv]
Here's the source code for bt.DivByZero
: https://github.com/mementum/backtrader/blob/master/backtrader/functions.py#L43