Coverage for src / cvx / markowitz / portfolios / utils.py: 100%

6 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-12-08 13:49 +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"""Utility helpers for portfolio builders.""" 

15 

16from collections.abc import Generator 

17from typing import Any 

18 

19import cvxpy as cp 

20 

21 

22def approx( 

23 name: str, x: cp.Variable, target: Any, pm: cp.Expression 

24) -> Generator[tuple[str, cp.Expression], None, None]: 

25 """Yield linear upper and lower approximation constraints. 

26 

27 Args: 

28 name: Base name used for constraint identifiers. 

29 x: Variable to be approximated. 

30 target: Target value or expression. 

31 pm: Symmetric tolerance (plus/minus) expression. 

32 

33 Yields: 

34 Pairs of (constraint_name, constraint_expression). 

35 """ 

36 yield f"{name}_approx_upper", x - target <= pm 

37 yield f"{name}_approx_lower", x - target >= -pm