Coverage for src/cvx/core/parameter.py: 100%
13 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-22 10:34 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-22 10:34 +0000
1# Copyright (c) 2025 Jebel Quant Research
2#
3# Licensed under the MIT License. See the LICENSE file in the project root
4# for the full license text.
5"""Parameter class for risk models.
7This module provides a simple parameter class that stores a named numpy array
8value that can be updated without reconstructing the optimization problem.
10Example:
11 Create a parameter and update its value:
13 >>> import numpy as np
14 >>> from cvx.core.parameter import Parameter
15 >>> p = Parameter(shape=3, name="weights")
16 >>> p.value
17 array([0., 0., 0.])
18 >>> p.value = np.array([0.5, 0.3, 0.2])
19 >>> p.value
20 array([0.5, 0.3, 0.2])
22"""
24from __future__ import annotations
26from dataclasses import dataclass, field
28import numpy as np
31@dataclass
32class Parameter:
33 """A named parameter holding a mutable numpy array value.
35 Parameters are used in risk models to store matrices and vectors
36 (such as Cholesky factors, factor exposures, and bounds) that can
37 be updated between solver calls without rebuilding the problem structure.
39 Attributes:
40 shape: The shape of the parameter. Use an integer for 1-D parameters
41 and a tuple for 2-D parameters.
42 name: A human-readable name for the parameter.
43 value: The numpy array holding the current parameter value.
45 Example:
46 1-D parameter (e.g., lower bounds):
48 >>> import numpy as np
49 >>> from cvx.core.parameter import Parameter
50 >>> p = Parameter(shape=4, name="lower_assets")
51 >>> p.value.shape
52 (4,)
53 >>> p.value = np.array([0.0, 0.1, 0.0, 0.2])
54 >>> p.value[1]
55 np.float64(0.1)
57 2-D parameter (e.g., Cholesky factor):
59 >>> p2 = Parameter(shape=(3, 3), name="chol")
60 >>> p2.value.shape
61 (3, 3)
62 >>> import numpy as np
63 >>> p2.value = np.eye(3)
64 >>> p2.value[0, 0]
65 np.float64(1.0)
67 """
69 shape: int | tuple[int, ...]
70 """Shape of the parameter (int for 1-D, tuple for 2-D)."""
72 name: str = ""
73 """Human-readable name for the parameter."""
75 value: np.ndarray = field(init=False)
76 """Current value of the parameter as a numpy array."""
78 def __post_init__(self) -> None:
79 """Initialise the value array to zeros."""
80 self.value = np.zeros(self.shape)