Coverage for src/cvxmarkowitz/portfolios/min_var.py: 100%
14 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-10-27 05:46 +0000
« 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"""Minimum-variance portfolio builder."""
16from __future__ import annotations
18from dataclasses import dataclass
20import cvxpy as cp
22from cvxmarkowitz.builder import Builder
23from cvxmarkowitz.names import ConstraintName as C
26@dataclass(frozen=True)
27class MinVar(Builder):
28 """Construct a long-only, budget-constrained minimum-variance portfolio.
30 Example:
31 >>> import numpy as np
32 >>> from cvxmarkowitz.names import DataNames as D
33 >>> problem = MinVar(assets=4).build()
34 >>> problem.update(
35 ... **{
36 ... D.CHOLESKY: np.linalg.cholesky(np.array([[1.0, 0.5], [0.5, 2.0]])).T,
37 ... D.LOWER_BOUND_ASSETS: np.zeros(2),
38 ... D.UPPER_BOUND_ASSETS: np.ones(2),
39 ... D.VOLA_UNCERTAINTY: np.zeros(2),
40 ... }
41 ... )
42 >>> round(problem.solve(), 4)
43 0.9354
44 >>> round(float(problem.weights.sum()), 6)
45 1.0
46 """
48 @property
49 def objective(self) -> cp.Minimize:
50 """Return the CVXPY objective for minimizing portfolio risk."""
51 return cp.Minimize(self.risk.estimate(self.variables))
53 def __post_init__(self) -> None:
54 """Set up default constraints for the minimum-variance portfolio."""
55 super().__post_init__()
56 self.constraints[C.LONG_ONLY] = self.weights >= 0
57 self.constraints[C.BUDGET] = cp.sum(self.weights) == 1.0