From 1543f111cb662f17733f8a96ed77c8306d448b25 Mon Sep 17 00:00:00 2001 From: Divasco Date: Wed, 9 Oct 2024 00:15:17 -0300 Subject: [PATCH] More testing --- garpar/optimize/mean_variance.py | 8 ++++---- tests/optimize/test_mean_variance.py | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/garpar/optimize/mean_variance.py b/garpar/optimize/mean_variance.py index 8a02d51..399e187 100644 --- a/garpar/optimize/mean_variance.py +++ b/garpar/optimize/mean_variance.py @@ -62,13 +62,13 @@ def _coerce_target_return(self, pf): def _coerce_target_volatility(self, pf): if self.target_risk is None: - return np.min(np.std(pf.as_prices())) + return np.min(np.std(pf.as_prices(), axis=0)) return self.target_risk def _calculate_weights(self, pf): optimizer = self._get_optimizer(pf) method = self.method - + optimization_methods = { "min_volatility": self._min_volatility, "max_sharpe": self._max_sharpe, @@ -77,10 +77,10 @@ def _calculate_weights(self, pf): "efficient_return": self._efficient_return, "portfolio_performance": self._portfolio_performance, } - + if method not in optimization_methods: raise ValueError(f"Unknown optimization method: {method}") - + return optimization_methods[method](optimizer, pf) def _min_volatility(self, optimizer, pf): diff --git a/tests/optimize/test_mean_variance.py b/tests/optimize/test_mean_variance.py index da19720..e4e12a0 100644 --- a/tests/optimize/test_mean_variance.py +++ b/tests/optimize/test_mean_variance.py @@ -15,6 +15,8 @@ from garpar.optimize.mean_variance import MVOptimizer, Markowitz +import pypfopt + from garpar import datasets import numpy as np @@ -69,6 +71,26 @@ def test_MVOptimizer_coerce_target_return(risso_portfolio, price_distribution): coerced_return = optimizer._coerce_target_return(pf) assert coerced_return == 0.05 # The minimum absolute return from mock portfolio +@pytest.mark.parametrize("price_distribution", pytest.DISTRIBUTIONS) +def test_MVOptimizer_get_optimizer(risso_portfolio, price_distribution): + pf = risso_portfolio(random_state=42, distribution=price_distribution) + optimizer = MVOptimizer() + assert type(optimizer._get_optimizer(pf)) == pypfopt.efficient_frontier.EfficientFrontier + +@pytest.mark.parametrize( + "volatiliy, price_distribution", + [ + (0.03313144315467211, pytest.DISTRIBUTIONS['levy-stable']), + (0.8509377578214843, pytest.DISTRIBUTIONS['normal']), + (13.383798092382262, pytest.DISTRIBUTIONS['uniform']) + ] +) +def test_MVOptimizer_coerce_volatiliy(volatiliy, price_distribution): + pf = price_distribution(random_state=43) + optimizer = MVOptimizer(method="max-sharpe") + coerced_volatility = optimizer._coerce_target_volatility(pf) + assert coerced_volatility == pytest.approx(volatiliy, 1e-9) + # ============================================================================= # MARKOWITZ TEST # =============================================================================