diff --git a/docs/EfficientFrontier.rst b/docs/EfficientFrontier.rst index f737e7f0..67e5ddaf 100644 --- a/docs/EfficientFrontier.rst +++ b/docs/EfficientFrontier.rst @@ -333,6 +333,39 @@ provide a sample of data that is large enough to include tail events. :members: :exclude-members: max_sharpe, min_volatility, max_quadratic_utility +Efficient CDaR +============== + +The **conditional drawdown at risk** is a more exotic measure of tail risk. It tries to alleviate the problem +of above measure in that it takes into account the timespan of serious decreases in value. The CDaR can be +thought of as the average of losses that occur on "very bad periods", where "very bad" is quantified by the parameter +:math:`\beta`. The drawdown is defined as the difference in non-compounded return to the previous peak. + +Put differently, the CDaR is the average of all drawdowns so severe that they only occur +:math:`(1-\beta)\%` of the time. When :math:`\beta = 1` CDaR is simply the maximum drawdown. + +While drawdown is quite an intuitive concept, a lot of new notation is required to formulate it mathematically (see +`the wiki page `_ for more details). We will adopt the following +notation: + +- *w* for the vector of portfolio weights +- *r* for a vector of cumulative asset returns (daily), with probability distribution :math:`p(r(t))`. +- :math:`D(w, r, t) = \max_{\tau`_. .. [3] Markowitz, H.; Starer, D.; Fram, H.; Gerber, S. (2019). `Avoiding the Downside `_. .. [4] Rockafellar, R.; Uryasev, D. (2001). `Optimization of conditional value-at-risk `_ +.. [5] Chekhlov, A.; Rockafellar, R.; Uryasev, D. (2005). `Drawdown measure in portfolio optimization `_ diff --git a/pypfopt/__init__.py b/pypfopt/__init__.py index e73d2633..355cc2b8 100755 --- a/pypfopt/__init__.py +++ b/pypfopt/__init__.py @@ -5,7 +5,7 @@ ) from .cla import CLA from .discrete_allocation import get_latest_prices, DiscreteAllocation -from .efficient_frontier import EfficientFrontier, EfficientSemivariance, EfficientCVaR +from .efficient_frontier import EfficientFrontier, EfficientSemivariance, EfficientCVaR, EfficientCDaR from .hierarchical_portfolio import HRPOpt from .risk_models import CovarianceShrinkage diff --git a/pypfopt/efficient_frontier.py b/pypfopt/efficient_frontier.py index 8c498992..bb8b506d 100644 --- a/pypfopt/efficient_frontier.py +++ b/pypfopt/efficient_frontier.py @@ -12,7 +12,6 @@ class EfficientFrontier(base_optimizer.BaseConvexOptimizer): - """ An EfficientFrontier object (inheriting from BaseConvexOptimizer) contains multiple optimisation methods that can be called (corresponding to different objective @@ -53,13 +52,13 @@ class EfficientFrontier(base_optimizer.BaseConvexOptimizer): """ def __init__( - self, - expected_returns, - cov_matrix, - weight_bounds=(0, 1), - solver=None, - verbose=False, - solver_options=None, + self, + expected_returns, + cov_matrix, + weight_bounds=(0, 1), + solver=None, + verbose=False, + solver_options=None, ): """ :param expected_returns: expected returns for each asset. Can be None if @@ -256,7 +255,7 @@ def max_sharpe(self, risk_free_rate=0.02): if isinstance(constr, cp.constraints.nonpos.Inequality): # Either the first or second item is the expression if isinstance( - constr.args[0], cp.expressions.constants.constant.Constant + constr.args[0], cp.expressions.constants.constant.Constant ): new_constraints.append(constr.args[1] >= constr.args[0] * k) else: @@ -270,10 +269,10 @@ def max_sharpe(self, risk_free_rate=0.02): # Transformed max_sharpe convex problem: self._constraints = [ - (self.expected_returns - risk_free_rate).T @ self._w == 1, - cp.sum(self._w) == k, - k >= 0, - ] + new_constraints + (self.expected_returns - risk_free_rate).T @ self._w == 1, + cp.sum(self._w) == k, + k >= 0, + ] + new_constraints self._solve_cvxpy_opt_problem() # Inverse-transform @@ -455,15 +454,15 @@ class EfficientSemivariance(EfficientFrontier): """ def __init__( - self, - expected_returns, - returns, - frequency=252, - benchmark=0, - weight_bounds=(0, 1), - solver=None, - verbose=False, - solver_options=None, + self, + expected_returns, + returns, + frequency=252, + benchmark=0, + weight_bounds=(0, 1), + solver=None, + verbose=False, + solver_options=None, ): """ :param expected_returns: expected returns for each asset. Can be None if @@ -698,18 +697,18 @@ class EfficientCVaR(EfficientFrontier): """ def __init__( - self, - expected_returns, - returns, - beta=0.95, - weight_bounds=(0, 1), - solver=None, - verbose=False, - solver_options=None, + self, + expected_returns, + returns, + beta=0.95, + weight_bounds=(0, 1), + solver=None, + verbose=False, + solver_options=None, ): """ :param expected_returns: expected returns for each asset. Can be None if - optimising for semideviation only. + optimising for CVaR only. :type expected_returns: pd.Series, list, np.ndarray :param returns: (historic) returns for all your assets (no NaNs). See ``expected_returns.returns_from_prices``. @@ -771,7 +770,7 @@ def min_cvar(self, market_neutral=False): :rtype: OrderedDict """ self._objective = self._alpha + 1.0 / ( - len(self.returns) * (1 - self._beta) + len(self.returns) * (1 - self._beta) ) * cp.sum(self._u) for obj in self._additional_objectives: @@ -800,7 +799,7 @@ def efficient_return(self, target_return, market_neutral=False): :rtype: OrderedDict """ self._objective = self._alpha + 1.0 / ( - len(self.returns) * (1 - self._beta) + len(self.returns) * (1 - self._beta) ) * cp.sum(self._u) for obj in self._additional_objectives: @@ -823,7 +822,7 @@ def efficient_risk(self, target_cvar, market_neutral=False): The resulting portfolio will have a CVaR less than the target (but not guaranteed to be equal). - :param target_cvar: the desired maximum semideviation of the resulting portfolio. + :param target_cvar: the desired maximum CVaR of the resulting portfolio. :type target_cvar: float :param market_neutral: whether the portfolio should be market neutral (weights sum to zero), defaults to False. Requires negative lower weight bound. @@ -874,3 +873,226 @@ def portfolio_performance(self, verbose=False): print("Conditional Value at Risk: {:.2f}%".format(100 * cvar_val)) return mu, cvar_val + + +class EfficientCDaR(EfficientFrontier): + """ + The EfficientCDaR class allows for optimisation along the mean-CDaR frontier, using the + formulation of Chekhlov, Ursayev and Zabarankin (2005). + + Instance variables: + + - Inputs: + + - ``n_assets`` - int + - ``tickers`` - str list + - ``bounds`` - float tuple OR (float tuple) list + - ``returns`` - pd.DataFrame + - ``expected_returns`` - np.ndarray + - ``solver`` - str + - ``solver_options`` - {str: str} dict + + + - Output: ``weights`` - np.ndarray + + Public methods: + + - ``min_cdar()`` minimises the CDaR + - ``efficient_risk()`` maximises return for a given CDaR + - ``efficient_return()`` minimises CDaR for a given target return + - ``add_objective()`` adds a (convex) objective to the optimisation problem + - ``add_constraint()`` adds a (linear) constraint to the optimisation problem + + - ``portfolio_performance()`` calculates the expected return and CDaR of the portfolio + - ``set_weights()`` creates self.weights (np.ndarray) from a weights dict + - ``clean_weights()`` rounds the weights and clips near-zeros. + - ``save_weights_to_file()`` saves the weights to csv, json, or txt. + """ + + def __init__( + self, + expected_returns, + returns, + beta=0.95, + weight_bounds=(0, 1), + solver=None, + verbose=False, + solver_options=None, + ): + """ + :param expected_returns: expected returns for each asset. Can be None if + optimising for CDaR only. + :type expected_returns: pd.Series, list, np.ndarray + :param returns: (historic) returns for all your assets (no NaNs). + See ``expected_returns.returns_from_prices``. + :type returns: pd.DataFrame or np.array + :param beta: confidence level, defaults to 0.95 (i.e expected drawdown on the worst (1-beta) days). + :param weight_bounds: minimum and maximum weight of each asset OR single min/max pair + if all identical, defaults to (0, 1). Must be changed to (-1, 1) + for portfolios with shorting. + :type weight_bounds: tuple OR tuple list, optional + :param solver: name of solver. list available solvers with: `cvxpy.installed_solvers()` + :type solver: str + :param verbose: whether performance and debugging info should be printed, defaults to False + :type verbose: bool, optional + :param solver_options: parameters for the given solver + :type solver_options: dict, optional + :raises TypeError: if ``expected_returns`` is not a series, list or array + """ + super().__init__( + expected_returns=expected_returns, + cov_matrix=np.zeros((len(expected_returns),) * 2), # dummy + weight_bounds=weight_bounds, + solver=solver, + verbose=verbose, + solver_options=solver_options, + ) + + self.returns = self._validate_returns(returns) + self._beta = self._validate_beta(beta) + self._alpha = cp.Variable() + self._u = cp.Variable(len(self.returns)+1) + self._z = cp.Variable(len(self.returns)) + + def _validate_beta(self, beta): + if not (0 <= beta < 1): + raise ValueError("beta must be between 0 and 1") + if beta <= 0.2: + warnings.warn( + "Warning: beta is the confidence-level, not the quantile. Typical values are 80%, 90%, 95%.", + UserWarning, + ) + return beta + + def min_volatility(self): + raise NotImplementedError("Please use min_cvar instead.") + + def max_sharpe(self, risk_free_rate=0.02): + raise NotImplementedError("Method not available in EfficientCVaR.") + + def max_quadratic_utility(self, risk_aversion=1, market_neutral=False): + raise NotImplementedError("Method not available in EfficientCVaR.") + + def min_cdar(self, market_neutral=False): + """ + Minimise portfolio CDaR (see docs for further explanation). + + :param market_neutral: whether the portfolio should be market neutral (weights sum to zero), + defaults to False. Requires negative lower weight bound. + :param market_neutral: bool, optional + :return: asset weights for the volatility-minimising portfolio + :rtype: OrderedDict + """ + self._objective = self._alpha + 1.0 / ( + len(self.returns) * (1 - self._beta) + ) * cp.sum(self._z) + + for obj in self._additional_objectives: + self._objective += obj + + self._constraints += [ + self._z >= self._u[1:] - self._alpha, + self._u[1:] >= self._u[:-1] - self.returns.values @ self._w, + self._u[0] == 0, + self._z >= 0, + self._u[1:] >= 0, + ] + + self._make_weight_sum_constraint(market_neutral) + return self._solve_cvxpy_opt_problem() + + def efficient_return(self, target_return, market_neutral=False): + """ + Minimise CDaR for a given target return. + + :param target_return: the desired return of the resulting portfolio. + :type target_return: float + :param market_neutral: whether the portfolio should be market neutral (weights sum to zero), + defaults to False. Requires negative lower weight bound. + :type market_neutral: bool, optional + :raises ValueError: if ``target_return`` is not a positive float + :raises ValueError: if no portfolio can be found with return equal to ``target_return`` + :return: asset weights for the optimal portfolio + :rtype: OrderedDict + """ + self._objective = self._alpha + 1.0 / ( + len(self.returns) * (1 - self._beta) + ) * cp.sum(self._z) + + for obj in self._additional_objectives: + self._objective += obj + + self._constraints += [ + self._z >= self._u[1:] - self._alpha, + self._u[1:] >= self._u[:-1] - self.returns.values @ self._w, + self._u[0] == 0, + self._z >= 0, + self._u[1:] >= 0, + ] + + ret = self.expected_returns.T @ self._w + self._constraints.append(ret >= target_return) + + self._make_weight_sum_constraint(market_neutral) + return self._solve_cvxpy_opt_problem() + + def efficient_risk(self, target_cdar, market_neutral=False): + """ + Maximise return for a target CDaR. + The resulting portfolio will have a CDaR less than the target + (but not guaranteed to be equal). + + :param target_cdar: the desired maximum CDaR of the resulting portfolio. + :type target_cdar: float + :param market_neutral: whether the portfolio should be market neutral (weights sum to zero), + defaults to False. Requires negative lower weight bound. + :param market_neutral: bool, optional + :return: asset weights for the efficient risk portfolio + :rtype: OrderedDict + """ + self._objective = objective_functions.portfolio_return( + self._w, self.expected_returns + ) + for obj in self._additional_objectives: + self._objective += obj + + cdar = self._alpha + 1.0 / ( + len(self.returns) * (1 - self._beta) + ) * cp.sum(self._z) + self._constraints += [ + cdar <= target_cdar, + self._z >= self._u[1:] - self._alpha, + self._u[1:] >= self._u[:-1] - self.returns.values @ self._w, + self._u[0] == 0, + self._z >= 0, + self._u[1:] >= 0, + ] + + self._make_weight_sum_constraint(market_neutral) + return self._solve_cvxpy_opt_problem() + + def portfolio_performance(self, verbose=False): + """ + After optimising, calculate (and optionally print) the performance of the optimal + portfolio, specifically: expected return, CVaR + + :param verbose: whether performance should be printed, defaults to False + :type verbose: bool, optional + :raises ValueError: if weights have not been calcualted yet + :return: expected return, CVaR. + :rtype: (float, float) + """ + mu = objective_functions.portfolio_return( + self.weights, self.expected_returns, negative=False + ) + + cdar = self._alpha + 1.0 / ( + len(self.returns) * (1 - self._beta) + ) * cp.sum(self._z) + cdar_val = cdar.value + + if verbose: + print("Expected annual return: {:.1f}%".format(100 * mu)) + print("Conditional Drawdown at Risk: {:.2f}%".format(100 * cdar_val)) + + return mu, cdar_val diff --git a/tests/test_efficient_cdar.py b/tests/test_efficient_cdar.py new file mode 100644 index 00000000..5a179625 --- /dev/null +++ b/tests/test_efficient_cdar.py @@ -0,0 +1,457 @@ +import numpy as np +import pandas as pd +import pytest +from pypfopt import ( + risk_models, + expected_returns, + EfficientCDaR, + objective_functions, +) +from tests.utilities_for_tests import setup_efficient_cdar, get_data, setup_efficient_cdar +from pypfopt.exceptions import OptimizationError + + +def test_cdar_example(): + beta = 0.95 + df = get_data() + mu = expected_returns.mean_historical_return(df) + historical_rets = expected_returns.returns_from_prices(df).dropna() + + cd = EfficientCDaR(mu, historical_rets, beta=beta) + w = cd.min_cdar() + + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + assert all([i >= -1e-5 for i in w.values()]) + + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.21502, 0.056433), + rtol=1e-4, + atol=1e-4, + ) + + cdar = cd.portfolio_performance()[1] + portfolio_rets = historical_rets @ cd.weights + cum_rets = portfolio_rets.cumsum(0) + drawdown = cum_rets.cummax() - cum_rets + + dar_hist = drawdown.quantile(beta) + cdar_hist = drawdown[drawdown > dar_hist].mean() + np.testing.assert_almost_equal(cdar_hist, cdar, decimal=3) + + +def test_es_return_sample(): + df = get_data() + mu = expected_returns.mean_historical_return(df) + S = risk_models.sample_cov(df) + + # Generate a 1y sample of daily data + np.random.seed(0) + mu_daily = (1 + mu) ** (1 / 252) - 1 + S_daily = S / 252 + sample_rets = pd.DataFrame( + np.random.multivariate_normal(mu_daily, S_daily, 300), columns=mu.index + ) + + cd = EfficientCDaR(mu, sample_rets) + w = cd.efficient_return(0.2) + + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + assert all([i >= -1e-5 for i in w.values()]) + + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.20, 0.045414), + rtol=1e-4, + atol=1e-4, + ) + # Cover verbose param case + np.testing.assert_equal( + cd.portfolio_performance(verbose=True), cd.portfolio_performance() + ) + + +def test_cdar_example_weekly(): + beta = 0.90 + df = get_data() + df = df.resample("W").first() + mu = expected_returns.mean_historical_return(df, frequency=52) + historical_rets = expected_returns.returns_from_prices(df).dropna() + cd = EfficientCDaR(mu, historical_rets, beta=beta) + cd.efficient_return(0.21) + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.21, 0.045085), + rtol=1e-4, + atol=1e-4, + ) + + cdar = cd.portfolio_performance()[1] + portfolio_rets = historical_rets @ cd.weights + + cum_rets = portfolio_rets.cumsum(0) + drawdown = cum_rets.cummax() - cum_rets + + dar_hist = drawdown.quantile(beta) + cdar_hist = drawdown[drawdown > dar_hist].mean() + np.testing.assert_almost_equal(cdar_hist, cdar, decimal=3) + + +def test_cdar_example_monthly(): + beta = 0.90 + df = get_data() + df = df.resample("M").first() + mu = expected_returns.mean_historical_return(df, frequency=12) + historical_rets = expected_returns.returns_from_prices(df).dropna() + cd = EfficientCDaR(mu, historical_rets, beta=beta) + cd.efficient_return(0.23) + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.23, 0.035683), + rtol=1e-4, + atol=1e-4, + ) + + cdar = cd.portfolio_performance()[1] + portfolio_rets = historical_rets @ cd.weights + + cum_rets = portfolio_rets.cumsum(0) + drawdown = cum_rets.cummax() - cum_rets + + dar_hist = drawdown.quantile(beta) + cdar_hist = drawdown[drawdown > dar_hist].mean() + np.testing.assert_almost_equal(cdar_hist, cdar, decimal=3) + + +def test_cdar_beta(): + # cdar should decrease (i.e higher loss) as beta increases + cd = setup_efficient_cdar() + cd._beta = 0.5 + cd.min_cdar() + cdar = cd.portfolio_performance()[1] + + for beta in np.arange(0.55, 1, 0.05): + cd = setup_efficient_cdar() + cd._beta = beta + cd.min_cdar() + cdar_test = cd.portfolio_performance()[1] + assert cdar_test >= cdar + cdar = cdar_test + + +def test_cdar_example_short(): + df = get_data() + mu = expected_returns.mean_historical_return(df) + historical_rets = expected_returns.returns_from_prices(df).dropna() + cd = EfficientCDaR( + mu, + historical_rets, + weight_bounds=(-1, 1), + ) + w = cd.efficient_return(0.2, market_neutral=True) + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 0) + + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.2, 0.047152), + rtol=1e-4, + atol=1e-4, + ) + + +def test_min_cdar_extra_constraints(): + cd = setup_efficient_cdar() + w = cd.min_cdar() + assert w["GOOG"] < 0.02 and w["MA"] > 0.02 + + cd = setup_efficient_cdar() + cd.add_constraint(lambda x: x[0] >= 0.03) + cd.add_constraint(lambda x: x[16] <= 0.03) + w = cd.min_cdar() + assert w["GOOG"] >= 0.025 and w["MA"] <= 0.035 + + +def test_min_cdar_different_solver(): + cd = setup_efficient_cdar(solver="ECOS") + w = cd.min_cdar() + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + + assert all([i >= -1e-5 for i in w.values()]) + test_performance = (0.14798, 0.056433) + np.testing.assert_allclose( + cd.portfolio_performance(), test_performance, rtol=1e-2, atol=1e-2 + ) + + +def test_min_cdar_tx_costs(): + # Baseline + cd = setup_efficient_cdar() + cd.min_cdar() + w1 = cd.weights + + # Pretend we were initally equal weight + cd = setup_efficient_cdar() + prev_w = np.array([1 / cd.n_assets] * cd.n_assets) + cd.add_objective(objective_functions.transaction_cost, w_prev=prev_w) + cd.min_cdar() + w2 = cd.weights + + # TX cost should pull closer to prev portfolio + assert np.abs(prev_w - w2).sum() < np.abs(prev_w - w1).sum() + + +def test_min_cdar_L2_reg(): + cd = setup_efficient_cdar(solver="ECOS") + cd.add_objective(objective_functions.L2_reg, gamma=0.1) + weights = cd.min_cdar() + assert isinstance(weights, dict) + assert set(weights.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + assert all([i >= -1e-5 for i in weights.values()]) + + cd2 = setup_efficient_cdar() + cd2.min_cdar() + + # L2_reg should pull close to equal weight + equal_weight = np.full((cd.n_assets,), 1 / cd.n_assets) + assert ( + np.abs(equal_weight - cd.weights).sum() + < np.abs(equal_weight - cd2.weights).sum() + ) + + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.135105, 0.060849), + rtol=1e-4, + atol=1e-4, + ) + + +def test_min_cdar_sector_constraints(): + sector_mapper = { + "GOOG": "tech", + "AAPL": "tech", + "FB": "tech", + "AMZN": "tech", + "BABA": "tech", + "GE": "utility", + "AMD": "tech", + "WMT": "retail", + "BAC": "fig", + "GM": "auto", + "T": "auto", + "UAA": "airline", + "SHLD": "retail", + "XOM": "energy", + "RRC": "energy", + "BBY": "retail", + "MA": "fig", + "PFE": "pharma", + "JPM": "fig", + "SBUX": "retail", + } + + sector_upper = { + "tech": 0.2, + "utility": 0.1, + "retail": 0.2, + "fig": 0.4, + "airline": 0.05, + "energy": 0.2, + } + sector_lower = {"utility": 0.01, "fig": 0.02, "airline": 0.01} + + cd = setup_efficient_cdar() + cd.add_sector_constraints(sector_mapper, sector_lower, sector_upper) + weights = cd.min_cdar() + + for sector in list(set().union(sector_upper, sector_lower)): + sector_sum = 0 + for t, v in weights.items(): + if sector_mapper[t] == sector: + sector_sum += v + assert sector_sum <= sector_upper.get(sector, 1) + 1e-5 + assert sector_sum >= sector_lower.get(sector, 0) - 1e-5 + + +def test_efficient_risk(): + cd = setup_efficient_cdar() + w = cd.efficient_risk(0.08) + + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + assert all([i >= -1e-5 for i in w.values()]) + + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.261922, 0.08 ), + rtol=1e-4, + atol=1e-4, + ) + + +def test_efficient_risk_low_risk(): + cd = setup_efficient_cdar() + cd.min_cdar() + min_value = cd.portfolio_performance()[1] + + # Should fail below + with pytest.raises(OptimizationError): + cd = setup_efficient_cdar() + cd.efficient_risk(min_value - 0.01) + + cd = setup_efficient_cdar() + cd.efficient_risk(min_value + 0.01) + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.212772, min_value + 0.01), + rtol=1e-4, + atol=1e-4, + ) + + +def test_efficient_risk_market_neutral(): + cd = EfficientCDaR(*setup_efficient_cdar(data_only=True), weight_bounds=(-1, 1)) + w = cd.efficient_risk(0.025, market_neutral=True) + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 0) + assert (cd.weights < 1).all() and (cd.weights > -1).all() + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.219306, 0.025), + rtol=1e-4, + atol=1e-4, + ) + + +def test_efficient_risk_L2_reg(): + cd = setup_efficient_cdar() + cd.add_objective(objective_functions.L2_reg, gamma=1) + weights = cd.efficient_risk(0.18) + + assert isinstance(weights, dict) + assert set(weights.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + np.testing.assert_array_less(np.zeros(len(weights)), cd.weights + 1e-4) + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.288999, 0.178443), + rtol=1e-4, + atol=1e-4, + ) + + ef2 = setup_efficient_cdar() + cd.add_objective(objective_functions.L2_reg, gamma=1) + ef2.efficient_risk(0.18) + + # L2_reg should pull close to equal weight + equal_weight = np.full((cd.n_assets,), 1 / cd.n_assets) + assert ( + np.abs(equal_weight - cd.weights).sum() + < np.abs(equal_weight - ef2.weights).sum() + ) + + +def test_efficient_return(): + cd = setup_efficient_cdar() + w = cd.efficient_return(0.25) + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + assert all([i >= -1e-5 for i in w.values()]) + + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.25, 0.076193), + rtol=1e-4, + atol=1e-4, + ) + + +def test_efficient_return_short(): + cd = EfficientCDaR(*setup_efficient_cdar(data_only=True), weight_bounds=(-3.0, 3.0)) + w = cd.efficient_return(0.28) + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.28, 0.045999), + rtol=1e-4, + atol=1e-4, + ) + cdar = cd.portfolio_performance()[1] + + ef_long_only = EfficientCDaR( + *setup_efficient_cdar(data_only=True), weight_bounds=(0.0, 1.0) + ) + ef_long_only.efficient_return(0.26) + long_only_cdar = ef_long_only.portfolio_performance()[1] + + assert long_only_cdar > cdar + + +def test_efficient_return_L2_reg(): + cd = setup_efficient_cdar() + cd.add_objective(objective_functions.L2_reg, gamma=1) + w = cd.efficient_return(0.25) + assert isinstance(w, dict) + assert set(w.keys()) == set(cd.tickers) + np.testing.assert_almost_equal(cd.weights.sum(), 1) + assert all([i >= -1e-5 for i in w.values()]) + np.testing.assert_allclose( + cd.portfolio_performance(), + (0.25, 0.101115), + rtol=1e-4, + atol=1e-4, + ) + + +def test_cdar_errors(): + df = get_data() + mu = expected_returns.mean_historical_return(df) + historical_rets = expected_returns.returns_from_prices(df) + + with pytest.warns(UserWarning): + EfficientCDaR(mu, historical_rets) + + historical_rets = historical_rets.dropna(axis=0, how="any") + assert EfficientCDaR(mu, historical_rets) + + cd = setup_efficient_cdar() + + with pytest.raises(NotImplementedError): + cd.min_volatility() + + with pytest.raises(NotImplementedError): + cd.max_sharpe() + + with pytest.raises(NotImplementedError): + cd.max_quadratic_utility() + + with pytest.raises(ValueError): + # Beta must be between 0 and 1 + cd = EfficientCDaR(mu, historical_rets, 1) + + with pytest.raises(OptimizationError): + # Must be <= max expected return + cd = EfficientCDaR(mu, historical_rets) + cd.efficient_return(target_return=np.abs(mu).max() + 0.01) + + with pytest.raises(TypeError): + # list not supported. + EfficientCDaR(mu, historical_rets.to_numpy().tolist()) + + historical_rets = historical_rets.iloc[:, :-1] + with pytest.raises(ValueError): + EfficientCDaR(mu, historical_rets) diff --git a/tests/test_efficient_cvar.py b/tests/test_efficient_cvar.py index 7544996a..0fd72ec8 100644 --- a/tests/test_efficient_cvar.py +++ b/tests/test_efficient_cvar.py @@ -343,7 +343,7 @@ def test_efficient_risk_L2_reg(): ef2 = setup_efficient_cvar() cv.add_objective(objective_functions.L2_reg, gamma=1) - ef2.efficient_risk(0.19) + ef2.efficient_risk(0.03) # L2_reg should pull close to equal weight equal_weight = np.full((cv.n_assets,), 1 / cv.n_assets) diff --git a/tests/utilities_for_tests.py b/tests/utilities_for_tests.py index 3b3ebfbf..30b698ff 100644 --- a/tests/utilities_for_tests.py +++ b/tests/utilities_for_tests.py @@ -8,6 +8,7 @@ EfficientFrontier, EfficientSemivariance, EfficientCVaR, + EfficientCDaR, ) from pypfopt.cla import CLA from pypfopt.expected_returns import returns_from_prices @@ -52,7 +53,7 @@ def get_market_caps(): def setup_efficient_frontier( - data_only=False, solver=None, verbose=False, solver_options=None + data_only=False, solver=None, verbose=False, solver_options=None ): df = get_data() mean_return = expected_returns.mean_historical_return(df) @@ -80,7 +81,7 @@ def setup_efficient_semivariance(data_only=False, solver=None, verbose=False): def setup_efficient_cvar( - data_only=False, solver=None, verbose=False, solver_options=None + data_only=False, solver=None, verbose=False, solver_options=None ): df = get_data().dropna(axis=0, how="any") mean_return = expected_returns.mean_historical_return(df) @@ -96,6 +97,23 @@ def setup_efficient_cvar( ) +def setup_efficient_cdar( + data_only=False, solver=None, verbose=False, solver_options=None +): + df = get_data().dropna(axis=0, how="any") + mean_return = expected_returns.mean_historical_return(df) + historic_returns = returns_from_prices(df) + if data_only: + return mean_return, historic_returns + return EfficientCDaR( + mean_return, + historic_returns, + verbose=verbose, + solver=solver, + solver_options=solver_options, + ) + + def setup_cla(data_only=False): df = get_data() mean_return = expected_returns.mean_historical_return(df)