From 47acde5c8a9f4d1acd41cb0562489850c79e4d9b Mon Sep 17 00:00:00 2001 From: danilogalisteu Date: Fri, 14 May 2021 12:46:32 -0300 Subject: [PATCH 1/2] Allow different target volatilities for each asset Allow different target volatilities for each asset, by passing a dict of values instead of a single one. --- bt/algos.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/bt/algos.py b/bt/algos.py index 16d632ca..77516eb2 100644 --- a/bt/algos.py +++ b/bt/algos.py @@ -1538,18 +1538,13 @@ def __call__(self, target): np.matmul(weights.values.T, np.matmul(covar.values, weights.values)) * self.annualization_factor ) - - # vol is too high - if vol > self.target_volatility: - mult = self.target_volatility / vol - # vol is too low - elif vol < self.target_volatility: - mult = self.target_volatility / vol - else: - mult = 1 + + if isinstance(self.target_volatility, (float, int)): + self.target_volatility = {k : self.target_volatility for k in target.temp["weights"].keys()} for k in target.temp["weights"].keys(): - target.temp["weights"][k] = target.temp["weights"][k] * mult + if k in self.target_volatility.keys(): + target.temp["weights"][k] = target.temp["weights"][k] * self.target_volatility[k] / vol return True From 3fc29d419c54c19c3ac3a72559422a47172f7ec6 Mon Sep 17 00:00:00 2001 From: Tim Paine Date: Sat, 15 May 2021 14:41:29 -0400 Subject: [PATCH 2/2] fix lint --- bt/algos.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/bt/algos.py b/bt/algos.py index 029e8094..55464d94 100644 --- a/bt/algos.py +++ b/bt/algos.py @@ -1538,13 +1538,17 @@ def __call__(self, target): np.matmul(weights.values.T, np.matmul(covar.values, weights.values)) * self.annualization_factor ) - + if isinstance(self.target_volatility, (float, int)): - self.target_volatility = {k : self.target_volatility for k in target.temp["weights"].keys()} + self.target_volatility = { + k: self.target_volatility for k in target.temp["weights"].keys() + } for k in target.temp["weights"].keys(): if k in self.target_volatility.keys(): - target.temp["weights"][k] = target.temp["weights"][k] * self.target_volatility[k] / vol + target.temp["weights"][k] = ( + target.temp["weights"][k] * self.target_volatility[k] / vol + ) return True