Coverage for cvx/risk/sample/sample.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2025-01-09 10:59 +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"""Risk models based on the sample covariance matrix""" 

15 

16from __future__ import annotations 

17 

18from dataclasses import dataclass 

19 

20import cvxpy as cvx 

21import numpy as np 

22 

23from ..bounds import Bounds 

24from ..linalg import cholesky 

25from ..model import Model 

26 

27 

28@dataclass 

29class SampleCovariance(Model): 

30 """Risk model based on the Cholesky decomposition of the sample cov matrix""" 

31 

32 num: int = 0 

33 

34 def __post_init__(self): 

35 self.parameter["chol"] = cvx.Parameter( 

36 shape=(self.num, self.num), 

37 name="cholesky of covariance", 

38 value=np.zeros((self.num, self.num)), 

39 ) 

40 self.bounds = Bounds(m=self.num, name="assets") 

41 

42 def estimate(self, weights, **kwargs): 

43 """Estimate the risk by computing the Cholesky decomposition of self.cov""" 

44 return cvx.norm2(self.parameter["chol"] @ weights) 

45 

46 def update(self, **kwargs): 

47 cov = kwargs["cov"] 

48 n = cov.shape[0] 

49 

50 self.parameter["chol"].value[:n, :n] = cholesky(cov) 

51 self.bounds.update(**kwargs) 

52 

53 def constraints(self, weights): 

54 return self.bounds.constraints(weights)