Coverage for src/cvxmarkowitz/portfolios/soft_risk.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-10-27 05:46 +0000

1# Copyright 2023 Stanford University Convex Optimization Group 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""Portfolio builder with soft risk penalty allowing target risk relaxation.""" 

15 

16from __future__ import annotations 

17 

18from dataclasses import dataclass, field 

19 

20import cvxpy as cp 

21 

22from cvxmarkowitz.builder import Builder 

23from cvxmarkowitz.models.expected_returns import ExpectedReturns 

24from cvxmarkowitz.names import ConstraintName as C 

25from cvxmarkowitz.names import ModelName as M 

26from cvxmarkowitz.names import ParameterName as P 

27 

28 

29@dataclass(frozen=True) 

30class SoftRisk(Builder): 

31 """Maximize w^T mu minus a soft penalty on excess risk. 

32 

33 The objective is maximize w^T mu - omega * (sigma - sigma_target)_+ 

34 subject to long-only, budget, and max-risk constraints. 

35 

36 Example: 

37 >>> import numpy as np 

38 >>> from cvxmarkowitz.names import DataNames as D 

39 >>> from cvxmarkowitz.names import ParameterName as P 

40 >>> builder = SoftRisk(assets=4) 

41 >>> builder.parameter[P.SIGMA_MAX].value = 1.0 

42 >>> builder.parameter[P.SIGMA_TARGET].value = 0.9 

43 >>> builder.parameter[P.OMEGA].value = 0.5 

44 >>> problem = builder.build() 

45 >>> problem.update( 

46 ... **{ 

47 ... D.CHOLESKY: np.linalg.cholesky(np.array([[1.0, 0.5], [0.5, 2.0]])).T, 

48 ... D.LOWER_BOUND_ASSETS: np.zeros(2), 

49 ... D.UPPER_BOUND_ASSETS: np.ones(2), 

50 ... D.VOLA_UNCERTAINTY: np.zeros(2), 

51 ... D.MU: np.array([0.25, 0.30]), 

52 ... D.MU_UNCERTAINTY: np.zeros(2), 

53 ... } 

54 ... ) 

55 >>> round(problem.solve(), 4) 

56 0.246 

57 >>> round(float(problem.weights.sum()), 6) 

58 1.0 

59 """ 

60 

61 _sigma: cp.Variable = field(default_factory=lambda: cp.Variable(nonneg=True, name="sigma")) 

62 _sigma_target_times_omega: cp.CallbackParam = field( 

63 default_factory=lambda: cp.CallbackParam( 

64 callback=lambda _p, _q: 0.0, nonneg=True, name="sigma_target_times_omega" 

65 ) 

66 ) 

67 

68 @property 

69 def objective(self) -> cp.Maximize: 

70 """Return the CVXPY objective for soft-risk maximization.""" 

71 expected_return = self.model[M.RETURN].estimate(self.variables) 

72 soft_risk = cp.pos(self.parameter[P.OMEGA] * self._sigma - self._sigma_target_times_omega) 

73 return cp.Maximize(expected_return - soft_risk) 

74 

75 def __post_init__(self) -> None: 

76 """Initialize models, parameters, and constraints for soft-risk portfolio.""" 

77 super().__post_init__() 

78 

79 self.model[M.RETURN] = ExpectedReturns(assets=self.assets) 

80 

81 self.parameter[P.SIGMA_MAX] = cp.Parameter(nonneg=True, name="limit volatility") 

82 

83 self.parameter[P.SIGMA_TARGET] = cp.Parameter(nonneg=True, name="target volatility") 

84 

85 self.parameter[P.OMEGA] = cp.Parameter(nonneg=True, name="risk priority") 

86 self._sigma_target_times_omega._callback = lambda: ( 

87 self.parameter[P.SIGMA_TARGET].value * self.parameter[P.OMEGA].value # ty: ignore[unsupported-operator] 

88 ) 

89 

90 self.constraints[C.LONG_ONLY] = self.weights >= 0 

91 self.constraints[C.BUDGET] = cp.sum(self.weights) == 1.0 

92 self.constraints[C.RISK] = self.risk.estimate(self.variables) <= self._sigma 

93 self.constraints["max_risk"] = self._sigma <= self.parameter[P.SIGMA_MAX]