cvxcla 0.0.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cvxcla-0.0.4/LICENSE +176 -0
- cvxcla-0.0.4/PKG-INFO +108 -0
- cvxcla-0.0.4/README.md +90 -0
- cvxcla-0.0.4/cvx/cla/__init__.py +15 -0
- cvxcla-0.0.4/cvx/cla/claux.py +72 -0
- cvxcla-0.0.4/cvx/cla/first.py +142 -0
- cvxcla-0.0.4/cvx/cla/markowitz/__init__.py +13 -0
- cvxcla-0.0.4/cvx/cla/markowitz/cla.py +130 -0
- cvxcla-0.0.4/cvx/cla/types.py +230 -0
- cvxcla-0.0.4/pyproject.toml +39 -0
cvxcla-0.0.4/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
cvxcla-0.0.4/PKG-INFO
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: cvxcla
|
|
3
|
+
Version: 0.0.4
|
|
4
|
+
Summary: Critical line algorithm for the efficient frontier
|
|
5
|
+
Home-page: https://www.cvxgrp.org/cvxcla
|
|
6
|
+
Author: Thomas Schmelzer
|
|
7
|
+
Requires-Python: >=3.9,<3.12
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Requires-Dist: numpy
|
|
13
|
+
Requires-Dist: plotly
|
|
14
|
+
Requires-Dist: scipy (>=1.10.0)
|
|
15
|
+
Project-URL: Repository, https://github.com/cvxgrp/cvxcla
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# [cvxcla](https://www.cvxgrp.org/cvxcla/book)
|
|
19
|
+
|
|
20
|
+
[](https://badge.fury.io/py/cvxcla)
|
|
21
|
+
[](https://github.com/cvxgrp/cvxcla/blob/master/LICENSE)
|
|
22
|
+
[](https://pepy.tech/project/cvxcla)
|
|
23
|
+
[](https://coveralls.io/github/cvxgrp/cvxcla?branch=main)
|
|
24
|
+
|
|
25
|
+
[](https://codespaces.new/cvxgrp/cvxcla)
|
|
26
|
+
|
|
27
|
+
## Critical line algorithm
|
|
28
|
+
|
|
29
|
+
The critical line algorithm is a method to compute the efficient frontier of a
|
|
30
|
+
portfolio optimization problem.
|
|
31
|
+
|
|
32
|
+
The algorithm has been introduced by Markowitz in
|
|
33
|
+
[The Optimization of Quadratic Functions Subject to Linear Constraints](https://www.rand.org/pubs/research_memoranda/RM1438.html)
|
|
34
|
+
and subsequently described in his book [Portfolio Selection](https://www.wiley.com/en-us/Portfolio+Selection%3A+Efficient+Diversification+of+Investments%2C+2nd+Edition-p-9781557861085).
|
|
35
|
+
|
|
36
|
+
The algorithm is based on the observation that the efficient frontier is a piecewise
|
|
37
|
+
linear function if expected return is plotted over expected variance.
|
|
38
|
+
The critical line algorithm computes the turning points, e.g. the corners
|
|
39
|
+
of the efficient frontier.
|
|
40
|
+
|
|
41
|
+
## Literature
|
|
42
|
+
|
|
43
|
+
We are using the following sources
|
|
44
|
+
|
|
45
|
+
### Niedermayer and Niedermayer
|
|
46
|
+
|
|
47
|
+
They suggested a method to avoid the expensive inversion of the covariance matrix.
|
|
48
|
+
[Applying Markowitz's critical line algorithm](https://www.researchgate.net/publication/226987510_Applying_Markowitz%27s_Critical_Line_Algorithm)
|
|
49
|
+
It turns out that implementing their method in Python is not significantly faster
|
|
50
|
+
than the explicit inversion of the covariance matrix relying on LAPACK via `numpy.linalg.inv`.
|
|
51
|
+
|
|
52
|
+
### Bailey and Lopez de Prado
|
|
53
|
+
|
|
54
|
+
We have initially started with their code published in
|
|
55
|
+
[An Open-Source Implementation of the Critical-Line Algorithm for Portfolio Optimization](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2197616).
|
|
56
|
+
We have updated their original code and covered it in tests. We have made a few
|
|
57
|
+
noteworthy changes:
|
|
58
|
+
|
|
59
|
+
* Use a boolean numpy array to indicate whether a weight is free or blocked.
|
|
60
|
+
* Rewrote the computation of the first turning point.
|
|
61
|
+
* Isolated the computation of $\lambda$ and the update of weights to make them testable.
|
|
62
|
+
* Use modern and immutable dataclasses throughout.
|
|
63
|
+
|
|
64
|
+
The code is not part of the published package though.
|
|
65
|
+
It is only used for testing purposes. We recommend it for educational purposes only.
|
|
66
|
+
|
|
67
|
+
### Markowitz et al
|
|
68
|
+
|
|
69
|
+
In [Avoiding the Downside: A Practical Review of the Critical
|
|
70
|
+
Line Algorithm for Mean-Semivariance Portfolio Optimizatio](https://www.hudsonbaycapital.com/documents/FG/hudsonbay/research/599440_paper.pdf)
|
|
71
|
+
Markowitz and a team of researchers from Hudson Bay Capital Management and Constantia
|
|
72
|
+
Capital provide a step-by-step tutorial on how to implement the critical line algorithm.
|
|
73
|
+
|
|
74
|
+
We address a problem they oversaw: After finding the first starting point
|
|
75
|
+
all variables might be blocked. We need to enforce that one variable is labeled
|
|
76
|
+
as free even it sits on a boundary otherwise the matrix needed is singular.
|
|
77
|
+
|
|
78
|
+
Rather than using their involved construction of the sparse matrix
|
|
79
|
+
to estimate the weights we bisect the weights into a free and a blocked part.
|
|
80
|
+
We then use a linear solver to compute the weights only for the free part.
|
|
81
|
+
|
|
82
|
+
We alter some of their Python code. Our experiments to combine it with Niedermayer's
|
|
83
|
+
ideas to accelerate the computation of the matrix inverses did not yet justify
|
|
84
|
+
the additional complexity.
|
|
85
|
+
|
|
86
|
+
## Poetry
|
|
87
|
+
|
|
88
|
+
We assume you share already the love for [Poetry](https://python-poetry.org).
|
|
89
|
+
Once you have installed poetry you can perform
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
make install
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
to replicate the virtual environment we have defined in [pyproject.toml](pyproject.toml)
|
|
96
|
+
and locked in [poetry.lock](poetry.lock).
|
|
97
|
+
|
|
98
|
+
## Jupyter
|
|
99
|
+
|
|
100
|
+
We install [JupyterLab](https://jupyter.org) on fly within the aforementioned
|
|
101
|
+
virtual environment. Executing
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
make jupyter
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
will install and start the jupyter lab.
|
|
108
|
+
|
cvxcla-0.0.4/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# [cvxcla](https://www.cvxgrp.org/cvxcla/book)
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/py/cvxcla)
|
|
4
|
+
[](https://github.com/cvxgrp/cvxcla/blob/master/LICENSE)
|
|
5
|
+
[](https://pepy.tech/project/cvxcla)
|
|
6
|
+
[](https://coveralls.io/github/cvxgrp/cvxcla?branch=main)
|
|
7
|
+
|
|
8
|
+
[](https://codespaces.new/cvxgrp/cvxcla)
|
|
9
|
+
|
|
10
|
+
## Critical line algorithm
|
|
11
|
+
|
|
12
|
+
The critical line algorithm is a method to compute the efficient frontier of a
|
|
13
|
+
portfolio optimization problem.
|
|
14
|
+
|
|
15
|
+
The algorithm has been introduced by Markowitz in
|
|
16
|
+
[The Optimization of Quadratic Functions Subject to Linear Constraints](https://www.rand.org/pubs/research_memoranda/RM1438.html)
|
|
17
|
+
and subsequently described in his book [Portfolio Selection](https://www.wiley.com/en-us/Portfolio+Selection%3A+Efficient+Diversification+of+Investments%2C+2nd+Edition-p-9781557861085).
|
|
18
|
+
|
|
19
|
+
The algorithm is based on the observation that the efficient frontier is a piecewise
|
|
20
|
+
linear function if expected return is plotted over expected variance.
|
|
21
|
+
The critical line algorithm computes the turning points, e.g. the corners
|
|
22
|
+
of the efficient frontier.
|
|
23
|
+
|
|
24
|
+
## Literature
|
|
25
|
+
|
|
26
|
+
We are using the following sources
|
|
27
|
+
|
|
28
|
+
### Niedermayer and Niedermayer
|
|
29
|
+
|
|
30
|
+
They suggested a method to avoid the expensive inversion of the covariance matrix.
|
|
31
|
+
[Applying Markowitz's critical line algorithm](https://www.researchgate.net/publication/226987510_Applying_Markowitz%27s_Critical_Line_Algorithm)
|
|
32
|
+
It turns out that implementing their method in Python is not significantly faster
|
|
33
|
+
than the explicit inversion of the covariance matrix relying on LAPACK via `numpy.linalg.inv`.
|
|
34
|
+
|
|
35
|
+
### Bailey and Lopez de Prado
|
|
36
|
+
|
|
37
|
+
We have initially started with their code published in
|
|
38
|
+
[An Open-Source Implementation of the Critical-Line Algorithm for Portfolio Optimization](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2197616).
|
|
39
|
+
We have updated their original code and covered it in tests. We have made a few
|
|
40
|
+
noteworthy changes:
|
|
41
|
+
|
|
42
|
+
* Use a boolean numpy array to indicate whether a weight is free or blocked.
|
|
43
|
+
* Rewrote the computation of the first turning point.
|
|
44
|
+
* Isolated the computation of $\lambda$ and the update of weights to make them testable.
|
|
45
|
+
* Use modern and immutable dataclasses throughout.
|
|
46
|
+
|
|
47
|
+
The code is not part of the published package though.
|
|
48
|
+
It is only used for testing purposes. We recommend it for educational purposes only.
|
|
49
|
+
|
|
50
|
+
### Markowitz et al
|
|
51
|
+
|
|
52
|
+
In [Avoiding the Downside: A Practical Review of the Critical
|
|
53
|
+
Line Algorithm for Mean-Semivariance Portfolio Optimizatio](https://www.hudsonbaycapital.com/documents/FG/hudsonbay/research/599440_paper.pdf)
|
|
54
|
+
Markowitz and a team of researchers from Hudson Bay Capital Management and Constantia
|
|
55
|
+
Capital provide a step-by-step tutorial on how to implement the critical line algorithm.
|
|
56
|
+
|
|
57
|
+
We address a problem they oversaw: After finding the first starting point
|
|
58
|
+
all variables might be blocked. We need to enforce that one variable is labeled
|
|
59
|
+
as free even it sits on a boundary otherwise the matrix needed is singular.
|
|
60
|
+
|
|
61
|
+
Rather than using their involved construction of the sparse matrix
|
|
62
|
+
to estimate the weights we bisect the weights into a free and a blocked part.
|
|
63
|
+
We then use a linear solver to compute the weights only for the free part.
|
|
64
|
+
|
|
65
|
+
We alter some of their Python code. Our experiments to combine it with Niedermayer's
|
|
66
|
+
ideas to accelerate the computation of the matrix inverses did not yet justify
|
|
67
|
+
the additional complexity.
|
|
68
|
+
|
|
69
|
+
## Poetry
|
|
70
|
+
|
|
71
|
+
We assume you share already the love for [Poetry](https://python-poetry.org).
|
|
72
|
+
Once you have installed poetry you can perform
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
make install
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
to replicate the virtual environment we have defined in [pyproject.toml](pyproject.toml)
|
|
79
|
+
and locked in [poetry.lock](poetry.lock).
|
|
80
|
+
|
|
81
|
+
## Jupyter
|
|
82
|
+
|
|
83
|
+
We install [JupyterLab](https://jupyter.org) on fly within the aforementioned
|
|
84
|
+
virtual environment. Executing
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
make jupyter
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
will install and start the jupyter lab.
|
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
|
|
15
|
+
from cvx.cla.markowitz.cla import CLA
|
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
import logging
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import List
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from cvx.cla.first import init_algo
|
|
21
|
+
from cvx.cla.types import MATRIX, Frontier, FrontierPoint, TurningPoint
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class CLAUX:
|
|
26
|
+
mean: MATRIX
|
|
27
|
+
covariance: MATRIX
|
|
28
|
+
lower_bounds: MATRIX
|
|
29
|
+
upper_bounds: MATRIX
|
|
30
|
+
A: MATRIX
|
|
31
|
+
b: MATRIX
|
|
32
|
+
turning_points: List[TurningPoint] = field(default_factory=list)
|
|
33
|
+
tol: float = 1e-5
|
|
34
|
+
logger: logging.Logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
def __len__(self):
|
|
37
|
+
"""
|
|
38
|
+
Returns the number of turning points
|
|
39
|
+
"""
|
|
40
|
+
return len(self.turning_points)
|
|
41
|
+
|
|
42
|
+
def _first_turning_point(self):
|
|
43
|
+
first = init_algo(
|
|
44
|
+
mean=self.mean,
|
|
45
|
+
lower_bounds=self.lower_bounds,
|
|
46
|
+
upper_bounds=self.upper_bounds,
|
|
47
|
+
)
|
|
48
|
+
return first
|
|
49
|
+
|
|
50
|
+
def _append(self, tp: TurningPoint, tol=None):
|
|
51
|
+
tol = tol or self.tol
|
|
52
|
+
|
|
53
|
+
assert np.all(
|
|
54
|
+
tp.weights >= (self.lower_bounds - tol)
|
|
55
|
+
), f"{(tp.weights + tol) - self.lower_bounds}"
|
|
56
|
+
assert np.all(
|
|
57
|
+
tp.weights <= (self.upper_bounds + tol)
|
|
58
|
+
), f"{(self.upper_bounds + tol) - tp.weights}"
|
|
59
|
+
assert np.allclose(np.sum(tp.weights), 1.0), f"{np.sum(tp.weights)}"
|
|
60
|
+
|
|
61
|
+
self.turning_points.append(tp)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def frontier(self):
|
|
65
|
+
"""
|
|
66
|
+
Returns the frontier
|
|
67
|
+
"""
|
|
68
|
+
return Frontier(
|
|
69
|
+
covariance=self.covariance,
|
|
70
|
+
mean=self.mean,
|
|
71
|
+
frontier=[FrontierPoint(point.weights) for point in self.turning_points],
|
|
72
|
+
)
|
|
@@ -0,0 +1,142 @@
|
|
|
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
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import cvxpy as cp
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from cvx.cla.types import MATRIX, TurningPoint
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
#
|
|
23
|
+
def init_algo(mean: MATRIX, lower_bounds: MATRIX, upper_bounds: MATRIX) -> TurningPoint:
|
|
24
|
+
"""The key insight behind Markowitz’s CLA is to find first the
|
|
25
|
+
turning point associated with the highest expected return, and then
|
|
26
|
+
compute the sequence of turning points, each with a lower expected
|
|
27
|
+
return than the previous. That first turning point consists in the
|
|
28
|
+
smallest subset of assets with highest return such that the sum of
|
|
29
|
+
their upper boundaries equals or exceeds one.
|
|
30
|
+
|
|
31
|
+
We sort the expected returns in descending order.
|
|
32
|
+
This gives us a sequence for searching for the
|
|
33
|
+
first free asset. All weights are initially set to their lower bounds,
|
|
34
|
+
and following the sequence from the previous step, we move those
|
|
35
|
+
weights from the lower to the upper bound until the sum of weights
|
|
36
|
+
exceeds one. If possible the last iterated weight is then reduced
|
|
37
|
+
to comply with the constraint that the sum of weights equals one.
|
|
38
|
+
This last weight is the first free asset,
|
|
39
|
+
and the resulting vector of weights the first turning point.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
if np.any(lower_bounds > upper_bounds):
|
|
43
|
+
raise ValueError("Lower bounds must be less than or equal to upper bounds")
|
|
44
|
+
|
|
45
|
+
# Initialize weights to lower bounds
|
|
46
|
+
weights = np.copy(lower_bounds)
|
|
47
|
+
free = np.full_like(mean, False, dtype=np.bool_)
|
|
48
|
+
|
|
49
|
+
# Move weights from lower to upper bound
|
|
50
|
+
# until sum of weights hits or exceeds 1
|
|
51
|
+
for index in np.argsort(-mean):
|
|
52
|
+
weights[index] += np.min(
|
|
53
|
+
[upper_bounds[index] - lower_bounds[index], 1.0 - np.sum(weights)]
|
|
54
|
+
)
|
|
55
|
+
if np.sum(weights) >= 1:
|
|
56
|
+
free[index] = True
|
|
57
|
+
break
|
|
58
|
+
|
|
59
|
+
# free = _free(weights, lower_bounds, upper_bounds)
|
|
60
|
+
|
|
61
|
+
if not np.any(free):
|
|
62
|
+
# # We have not reached the sum of weights of 1...
|
|
63
|
+
raise ValueError("Could not construct a fully invested portfolio")
|
|
64
|
+
|
|
65
|
+
# Return first turning point, the point with the highest expected return.
|
|
66
|
+
return TurningPoint(free=free, weights=weights)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def init_algo_lp(
|
|
70
|
+
mean: MATRIX,
|
|
71
|
+
lower_bounds: MATRIX,
|
|
72
|
+
upper_bounds: MATRIX,
|
|
73
|
+
A_eq: MATRIX | None = None,
|
|
74
|
+
b_eq: MATRIX | None = None,
|
|
75
|
+
solver=cp.CLARABEL,
|
|
76
|
+
**kwargs
|
|
77
|
+
# A_ub: MATRIX | None = None,
|
|
78
|
+
# b_ub: MATRIX | None = None,
|
|
79
|
+
) -> TurningPoint:
|
|
80
|
+
if A_eq is None:
|
|
81
|
+
A_eq = np.atleast_2d(np.ones_like(mean))
|
|
82
|
+
|
|
83
|
+
if b_eq is None:
|
|
84
|
+
b_eq = np.array([1.0])
|
|
85
|
+
|
|
86
|
+
# if A_ub is None:
|
|
87
|
+
# A_ub = np.atleast_2d(np.zeros_like(mean))
|
|
88
|
+
|
|
89
|
+
# if b_ub is None:
|
|
90
|
+
# b_ub = np.array([0.0])
|
|
91
|
+
|
|
92
|
+
w = cp.Variable(mean.shape[0], "weights")
|
|
93
|
+
|
|
94
|
+
objective = cp.Maximize(mean.T @ w)
|
|
95
|
+
constraints = [
|
|
96
|
+
A_eq @ w == b_eq,
|
|
97
|
+
# A_ub @ w <= b_ub,
|
|
98
|
+
lower_bounds <= w,
|
|
99
|
+
w <= upper_bounds,
|
|
100
|
+
cp.sum(w) == 1.0,
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
problem = cp.Problem(objective, constraints)
|
|
104
|
+
problem.solve(solver=solver, **kwargs)
|
|
105
|
+
# check status of problem is optimal
|
|
106
|
+
if problem.status != cp.OPTIMAL:
|
|
107
|
+
raise ValueError("Could not construct a fully invested portfolio")
|
|
108
|
+
|
|
109
|
+
# assert problem.status == cp.OPTIMAL
|
|
110
|
+
# print(problem.status)
|
|
111
|
+
# print(status)
|
|
112
|
+
|
|
113
|
+
w = w.value
|
|
114
|
+
|
|
115
|
+
# compute the distance from the closest bound
|
|
116
|
+
# distance = np.min(
|
|
117
|
+
# np.array([np.abs(w - lower_bounds), np.abs(upper_bounds - w)]), axis=0
|
|
118
|
+
# )
|
|
119
|
+
|
|
120
|
+
# which element has the largest distance to any bound?
|
|
121
|
+
# Even if all assets are at their bounds,
|
|
122
|
+
# we get a (somewhat random) free asset.
|
|
123
|
+
# index = np.argmax(distance)
|
|
124
|
+
|
|
125
|
+
# free = np.full_like(mean, False, dtype=np.bool_)
|
|
126
|
+
# free[index] = True
|
|
127
|
+
|
|
128
|
+
free = _free(w, lower_bounds, upper_bounds)
|
|
129
|
+
|
|
130
|
+
return TurningPoint(free=free, weights=w)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _free(w, lower_bounds, upper_bounds):
|
|
134
|
+
distance = np.min(
|
|
135
|
+
np.array([np.abs(w - lower_bounds), np.abs(upper_bounds - w)]), axis=0
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
index = np.argmax(distance)
|
|
139
|
+
|
|
140
|
+
free = np.full_like(w, False, dtype=np.bool_)
|
|
141
|
+
free[index] = True
|
|
142
|
+
return free
|
|
@@ -0,0 +1,13 @@
|
|
|
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.
|
|
@@ -0,0 +1,130 @@
|
|
|
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
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from cvx.cla.claux import CLAUX
|
|
19
|
+
from cvx.cla.types import TurningPoint
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class CLA(CLAUX):
|
|
24
|
+
def __post_init__(self):
|
|
25
|
+
ns = self.mean.shape[0]
|
|
26
|
+
m = self.A.shape[0]
|
|
27
|
+
|
|
28
|
+
# --A08-- Initialize the portfolio.
|
|
29
|
+
first = self._first_turning_point()
|
|
30
|
+
self._append(first)
|
|
31
|
+
|
|
32
|
+
# --A10-- Set the P matrix.
|
|
33
|
+
P = np.block([self.covariance, self.A.T])
|
|
34
|
+
M = np.block([[self.covariance, self.A.T], [self.A, np.zeros((m, m))]])
|
|
35
|
+
|
|
36
|
+
# --A11 -- Initialize storage for quantities # to be computed in the main loop.
|
|
37
|
+
lam = np.inf
|
|
38
|
+
|
|
39
|
+
while lam > 0:
|
|
40
|
+
last = self.turning_points[-1]
|
|
41
|
+
|
|
42
|
+
blocked = ~last.free
|
|
43
|
+
assert not np.all(blocked), "Not all variables can be blocked"
|
|
44
|
+
|
|
45
|
+
# --A13-- Create the UP, DN, and IN
|
|
46
|
+
# sets from the current state vector.
|
|
47
|
+
UP = blocked & np.isclose(last.weights, self.upper_bounds)
|
|
48
|
+
DN = blocked & np.isclose(last.weights, self.lower_bounds)
|
|
49
|
+
|
|
50
|
+
# a variable is out if it is UP or DN
|
|
51
|
+
OUT = np.logical_or(UP, DN)
|
|
52
|
+
IN = ~OUT
|
|
53
|
+
|
|
54
|
+
up = np.zeros(ns)
|
|
55
|
+
up[UP] = self.upper_bounds[UP]
|
|
56
|
+
|
|
57
|
+
dn = np.zeros(ns)
|
|
58
|
+
dn[DN] = self.lower_bounds[DN]
|
|
59
|
+
|
|
60
|
+
top = np.copy(self.mean)
|
|
61
|
+
top[OUT] = 0
|
|
62
|
+
|
|
63
|
+
_IN = np.concatenate([IN, np.ones(m, dtype=np.bool_)])
|
|
64
|
+
|
|
65
|
+
bbb = np.array(
|
|
66
|
+
[np.block([up + dn, self.b]), np.block([top, np.zeros(m)])]
|
|
67
|
+
).T
|
|
68
|
+
|
|
69
|
+
alpha, beta = CLA._solve(M, bbb, _IN)
|
|
70
|
+
|
|
71
|
+
gamma = P @ alpha
|
|
72
|
+
delta = P @ beta - self.mean
|
|
73
|
+
|
|
74
|
+
# -A17-- Prepare the ratio matrix.
|
|
75
|
+
L = -np.inf * np.ones([ns, 4])
|
|
76
|
+
|
|
77
|
+
r_beta = beta[range(ns)]
|
|
78
|
+
r_alpha = alpha[range(ns)]
|
|
79
|
+
|
|
80
|
+
# --A18-- IN security possibly going UP.
|
|
81
|
+
i = IN & (r_beta < -self.tol)
|
|
82
|
+
L[i, 0] = (self.upper_bounds[i] - r_alpha[i]) / r_beta[i]
|
|
83
|
+
|
|
84
|
+
# --A19-- IN security possibly going DN.
|
|
85
|
+
i = IN & (r_beta > +self.tol)
|
|
86
|
+
L[i, 1] = (self.lower_bounds[i] - r_alpha[i]) / r_beta[i]
|
|
87
|
+
|
|
88
|
+
# --A20--UP security possibly going IN.
|
|
89
|
+
i = UP & (delta < -self.tol)
|
|
90
|
+
L[i, 2] = -gamma[i] / delta[i]
|
|
91
|
+
|
|
92
|
+
# --A21-- DN security possibly going IN.
|
|
93
|
+
i = DN & (delta > +self.tol)
|
|
94
|
+
L[i, 3] = -gamma[i] / delta[i]
|
|
95
|
+
|
|
96
|
+
# --A22--If all elements of ratio are negative,
|
|
97
|
+
# we have reached the end of the efficient frontier.
|
|
98
|
+
if np.max(L) < 0:
|
|
99
|
+
break
|
|
100
|
+
|
|
101
|
+
secchg, dirchg = np.unravel_index(np.argmax(L, axis=None), L.shape)
|
|
102
|
+
|
|
103
|
+
# --A25-- Set the new value of lambda_E.
|
|
104
|
+
lam = L[secchg, dirchg]
|
|
105
|
+
|
|
106
|
+
free = np.copy(last.free)
|
|
107
|
+
if dirchg == 0 or dirchg == 1:
|
|
108
|
+
free[secchg] = False
|
|
109
|
+
else:
|
|
110
|
+
free[secchg] = True
|
|
111
|
+
|
|
112
|
+
# --A27-- Compute the portfolio at this corner.
|
|
113
|
+
x = r_alpha + lam * r_beta
|
|
114
|
+
|
|
115
|
+
# --A28-- Save the data computed at this corner.
|
|
116
|
+
self._append(TurningPoint(lamb=lam, weights=x, free=free))
|
|
117
|
+
|
|
118
|
+
self._append(TurningPoint(lamb=0, weights=r_alpha, free=last.free))
|
|
119
|
+
|
|
120
|
+
@staticmethod
|
|
121
|
+
def _solve(A, b, IN):
|
|
122
|
+
OUT = ~IN
|
|
123
|
+
n = A.shape[1]
|
|
124
|
+
x = np.zeros((n, 2))
|
|
125
|
+
|
|
126
|
+
x[OUT, :] = b[OUT, :]
|
|
127
|
+
bbb = b[IN, :] - A[IN, :][:, OUT] @ x[OUT, :]
|
|
128
|
+
|
|
129
|
+
x[IN, :] = np.linalg.inv(A[IN, :][:, IN]) @ bbb
|
|
130
|
+
return x[:, 0], x[:, 1]
|
|
@@ -0,0 +1,230 @@
|
|
|
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
|
+
"""
|
|
15
|
+
types
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import plotly.express as px
|
|
23
|
+
from numpy.typing import NDArray
|
|
24
|
+
from scipy.optimize import minimize
|
|
25
|
+
from typing_extensions import TypeAlias
|
|
26
|
+
|
|
27
|
+
MATRIX: TypeAlias = NDArray[np.float64]
|
|
28
|
+
BOOLEAN_VECTOR: TypeAlias = NDArray[np.bool_]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class FrontierPoint:
|
|
33
|
+
weights: MATRIX
|
|
34
|
+
|
|
35
|
+
def __post_init__(self):
|
|
36
|
+
# check that the sum is close to 1
|
|
37
|
+
assert np.isclose(np.sum(self.weights), 1.0)
|
|
38
|
+
|
|
39
|
+
def mean(self, mean: MATRIX):
|
|
40
|
+
"""
|
|
41
|
+
Computes the expected return for a turning point
|
|
42
|
+
"""
|
|
43
|
+
return float(mean.T @ self.weights)
|
|
44
|
+
|
|
45
|
+
def variance(self, covariance: MATRIX):
|
|
46
|
+
"""
|
|
47
|
+
Computes the expected variance for a turning point
|
|
48
|
+
"""
|
|
49
|
+
return float(self.weights.T @ covariance @ self.weights)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class TurningPoint(FrontierPoint):
|
|
54
|
+
"""
|
|
55
|
+
A turning point is a vector of weights, a lambda value, and a boolean vector
|
|
56
|
+
indicating which assets are free. All assets that are not free are blocked.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
free: BOOLEAN_VECTOR
|
|
60
|
+
lamb: float = np.inf
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def free_indices(self):
|
|
64
|
+
"""
|
|
65
|
+
Returns the indices of the free assets
|
|
66
|
+
"""
|
|
67
|
+
return np.where(self.free)[0]
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def blocked_indices(self):
|
|
71
|
+
"""
|
|
72
|
+
Returns the indices of the blocked assets
|
|
73
|
+
"""
|
|
74
|
+
return np.where(~self.free)[0]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class Frontier:
|
|
79
|
+
"""
|
|
80
|
+
A frontier is a list of frontier points. Some of them might be turning points.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
mean: MATRIX
|
|
84
|
+
covariance: MATRIX
|
|
85
|
+
frontier: list[FrontierPoint] = field(default_factory=list)
|
|
86
|
+
|
|
87
|
+
def interpolate(self, num=100):
|
|
88
|
+
"""
|
|
89
|
+
Interpolate the frontier with num-1 points between adjacent frontier points
|
|
90
|
+
Args:
|
|
91
|
+
num: The number of new points in between each pair
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
A frontier with many new points
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def _interpolate():
|
|
98
|
+
for w_left, w_right in zip(self.weights[0:-1], self.weights[1:]):
|
|
99
|
+
for lamb in np.linspace(0, 1, num):
|
|
100
|
+
if lamb > 0:
|
|
101
|
+
yield FrontierPoint(
|
|
102
|
+
weights=lamb * w_left + (1 - lamb) * w_right
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
points = list(_interpolate())
|
|
106
|
+
return Frontier(frontier=points, mean=self.mean, covariance=self.covariance)
|
|
107
|
+
|
|
108
|
+
def __iter__(self):
|
|
109
|
+
"""
|
|
110
|
+
Iterator for all frontier points
|
|
111
|
+
"""
|
|
112
|
+
yield from self.frontier
|
|
113
|
+
|
|
114
|
+
def __len__(self):
|
|
115
|
+
"""
|
|
116
|
+
Number of frontier points
|
|
117
|
+
"""
|
|
118
|
+
return len(self.frontier)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def weights(self):
|
|
122
|
+
"""
|
|
123
|
+
Matrix of weights. One row per point
|
|
124
|
+
"""
|
|
125
|
+
return np.array([point.weights for point in self])
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def returns(self):
|
|
129
|
+
"""
|
|
130
|
+
Vector of expected returns.
|
|
131
|
+
"""
|
|
132
|
+
return np.array([point.mean(self.mean) for point in self])
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def variance(self):
|
|
136
|
+
"""
|
|
137
|
+
Vector of expected variances.
|
|
138
|
+
"""
|
|
139
|
+
return np.array([point.variance(self.covariance) for point in self])
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def sharpe_ratio(self):
|
|
143
|
+
"""
|
|
144
|
+
Vector of expected Sharpe ratios.
|
|
145
|
+
"""
|
|
146
|
+
return self.returns / self.volatility
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def volatility(self):
|
|
150
|
+
"""
|
|
151
|
+
Vector of expected volatilities.
|
|
152
|
+
"""
|
|
153
|
+
return np.sqrt(self.variance)
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def max_sharpe(self):
|
|
157
|
+
"""
|
|
158
|
+
Maximal Sharpe ratio on the frontier
|
|
159
|
+
|
|
160
|
+
Returns:
|
|
161
|
+
Tuple of maximal Sharpe ratio and the weights to achieve it
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
def neg_sharpe(alpha, w_left, w_right):
|
|
165
|
+
# convex combination of left and right weights
|
|
166
|
+
weight = alpha * w_left + (1 - alpha) * w_right
|
|
167
|
+
# compute the variance
|
|
168
|
+
var = weight.T @ self.covariance @ weight
|
|
169
|
+
returns = self.mean.T @ weight
|
|
170
|
+
return -returns / np.sqrt(var)
|
|
171
|
+
|
|
172
|
+
sharpe_ratios = self.sharpe_ratio
|
|
173
|
+
|
|
174
|
+
# in which point is the maximal Sharpe ratio?
|
|
175
|
+
sr_position_max = np.argmax(self.sharpe_ratio)
|
|
176
|
+
|
|
177
|
+
# np.min only there for security...
|
|
178
|
+
right = np.min([sr_position_max + 1, len(self) - 1])
|
|
179
|
+
left = np.max([0, sr_position_max - 1])
|
|
180
|
+
|
|
181
|
+
# Look to the left and look to the right
|
|
182
|
+
|
|
183
|
+
if right > sr_position_max:
|
|
184
|
+
out = minimize(
|
|
185
|
+
neg_sharpe,
|
|
186
|
+
0.5,
|
|
187
|
+
args=(self.weights[sr_position_max], self.weights[right]),
|
|
188
|
+
bounds=((0, 1),),
|
|
189
|
+
)
|
|
190
|
+
var = out["x"][0]
|
|
191
|
+
w_right = (
|
|
192
|
+
var * self.weights[sr_position_max] + (1 - var) * self.weights[right]
|
|
193
|
+
)
|
|
194
|
+
sharpe_ratio_right = -out["fun"]
|
|
195
|
+
else:
|
|
196
|
+
w_right = self.weights[sr_position_max]
|
|
197
|
+
sharpe_ratio_right = sharpe_ratios[sr_position_max]
|
|
198
|
+
|
|
199
|
+
if left < sr_position_max:
|
|
200
|
+
out = minimize(
|
|
201
|
+
neg_sharpe,
|
|
202
|
+
0.5,
|
|
203
|
+
args=(self.weights[left], self.weights[sr_position_max]),
|
|
204
|
+
bounds=((0, 1),),
|
|
205
|
+
)
|
|
206
|
+
var = out["x"][0]
|
|
207
|
+
w_left = (
|
|
208
|
+
var * self.weights[left] + (1 - var) * self.weights[sr_position_max]
|
|
209
|
+
)
|
|
210
|
+
sharpe_ratio_left = -out["fun"]
|
|
211
|
+
else:
|
|
212
|
+
w_left = self.weights[sr_position_max]
|
|
213
|
+
sharpe_ratio_left = sharpe_ratios[sr_position_max]
|
|
214
|
+
|
|
215
|
+
if sharpe_ratio_left > sharpe_ratio_right:
|
|
216
|
+
return sharpe_ratio_left, w_left
|
|
217
|
+
|
|
218
|
+
return sharpe_ratio_right, w_right
|
|
219
|
+
|
|
220
|
+
def plot(self):
|
|
221
|
+
"""
|
|
222
|
+
Plot the frontier
|
|
223
|
+
"""
|
|
224
|
+
fig = px.line(
|
|
225
|
+
x=self.variance,
|
|
226
|
+
y=self.returns,
|
|
227
|
+
markers=True,
|
|
228
|
+
labels={"x": "Expected variance", "y": "Expected Return"},
|
|
229
|
+
)
|
|
230
|
+
return fig
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "cvxcla"
|
|
3
|
+
version = "v0.0.4"
|
|
4
|
+
description = "Critical line algorithm for the efficient frontier"
|
|
5
|
+
authors = ["Thomas Schmelzer", "Philipp Schiele"]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
repository = "https://github.com/cvxgrp/cvxcla"
|
|
8
|
+
packages = [{include = "cvx"}]
|
|
9
|
+
homepage = "https://www.cvxgrp.org/cvxcla"
|
|
10
|
+
|
|
11
|
+
[tool.poetry.dependencies]
|
|
12
|
+
python = ">=3.9,<3.12"
|
|
13
|
+
numpy = "*"
|
|
14
|
+
scipy = ">=1.10.0"
|
|
15
|
+
plotly = "*"
|
|
16
|
+
|
|
17
|
+
[tool.poetry.dev-dependencies]
|
|
18
|
+
loguru = "*"
|
|
19
|
+
pandas = "*"
|
|
20
|
+
cvxpy = "*"
|
|
21
|
+
|
|
22
|
+
[tool.poetry.group.test.dependencies]
|
|
23
|
+
pytest = "*"
|
|
24
|
+
pytest-cov = "*"
|
|
25
|
+
cvxbson = "*"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["poetry-core"]
|
|
29
|
+
build-backend = "poetry.core.masonry.api"
|
|
30
|
+
|
|
31
|
+
[tool.ruff]
|
|
32
|
+
select = ["E", "F", "I"]
|
|
33
|
+
line-length = 120
|
|
34
|
+
target-version = "py310"
|
|
35
|
+
exclude = [
|
|
36
|
+
"*__init__.py",
|
|
37
|
+
".venv",
|
|
38
|
+
"experiments"
|
|
39
|
+
]
|