Coverage for src / cvx / risk / random / rand_cov.py: 100%

6 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2025-12-15 12:21 +0000

1"""Random covariance matrix generation utilities. 

2 

3This module provides functions for generating random positive semi-definite 

4covariance matrices. These are useful for testing and simulation purposes. 

5 

6Example: 

7 Generate a random covariance matrix: 

8 

9 >>> import numpy as np 

10 >>> from cvx.risk.random import rand_cov 

11 >>> # Generate a 5x5 random covariance matrix 

12 >>> cov = rand_cov(5, seed=42) 

13 >>> cov.shape 

14 (5, 5) 

15 >>> # Verify it's symmetric 

16 >>> bool(np.allclose(cov, cov.T)) 

17 True 

18 >>> # Verify it's positive semi-definite 

19 >>> bool(np.all(np.linalg.eigvals(cov) >= -1e-10)) 

20 True 

21 

22""" 

23 

24# Copyright 2023 Stanford University Convex Optimization Group 

25# 

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

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

28# You may obtain a copy of the License at 

29# 

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

31# 

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

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

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

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

36# limitations under the License. 

37from __future__ import annotations 

38 

39import numpy as np 

40 

41 

42def rand_cov(n: int, seed: int | None = None) -> np.ndarray: 

43 """Construct a random positive semi-definite covariance matrix of size n x n. 

44 

45 The matrix is constructed as A^T @ A where A is a random n x n matrix with 

46 elements drawn from a standard normal distribution. This ensures the result 

47 is symmetric and positive semi-definite. 

48 

49 Args: 

50 n: Size of the covariance matrix (n x n). 

51 seed: Random seed for reproducibility. If None, uses the current 

52 random state. 

53 

54 Returns: 

55 A random positive semi-definite n x n covariance matrix. 

56 

57 Example: 

58 Generate a reproducible random covariance matrix: 

59 

60 >>> import numpy as np 

61 >>> from cvx.risk.random import rand_cov 

62 >>> cov1 = rand_cov(3, seed=42) 

63 >>> cov2 = rand_cov(3, seed=42) 

64 >>> np.allclose(cov1, cov2) 

65 True 

66 

67 Use in portfolio optimization: 

68 

69 >>> from cvx.risk.sample import SampleCovariance 

70 >>> import cvxpy as cp 

71 >>> model = SampleCovariance(num=4) 

72 >>> cov = rand_cov(4, seed=42) 

73 >>> model.update( 

74 ... cov=cov, 

75 ... lower_assets=np.zeros(4), 

76 ... upper_assets=np.ones(4) 

77 ... ) 

78 >>> weights = cp.Variable(4) 

79 >>> risk = model.estimate(weights) 

80 >>> isinstance(risk, cp.Expression) 

81 True 

82 

83 Note: 

84 The generated matrix is guaranteed to be positive semi-definite because 

85 it is constructed as A^T @ A. In practice, it will typically be positive 

86 definite (all eigenvalues strictly positive) unless n is very large. 

87 

88 """ 

89 rng = np.random.default_rng(seed) 

90 a = rng.standard_normal((n, n)) 

91 return np.transpose(a) @ a