forked from dcajasn/Riskfolio-Lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstraintsFunctions.py
executable file
·541 lines (448 loc) · 20.3 KB
/
ConstraintsFunctions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import numpy as np
import pandas as pd
def assets_constraints(constraints, asset_classes):
r"""
Create the linear constraints matrixes A and B of the constraint
:math:`Aw \geq B`.
Parameters
----------
constraints : DataFrame of shape (n_constraints, n_fields)
Constraints matrix, where n_constraints is the number of constraints
and n_fields is the number of fields of constraints matrix, the fields
are:
- Disabled: (bool) indicates if the constraint is enable.
- Type: (str) can be: 'Assets', 'Classes', 'All Assets', 'Each asset in a class' and 'All Classes'.
- Set: (str) if Type is 'Classes', 'Each asset in a class' or 'All Classes'specified the name of the asset's classes set.
- Position: (str) the name of the asset or asset class of the constraint.
- Sign: (str) can be '>=' or '<='.
- Weight: (scalar) is the maximum or minimum weight of the absolute constraint.
- Type Relative: (str) can be: 'Assets' or 'Classes'.
- Relative Set: (str) if Type Relative is 'Classes' specified the name of the set of asset classes.
- Relative: (str) the name of the asset or asset class of the relative constraint.
- Factor: (scalar) is the factor of the relative constraint.
asset_classes : DataFrame of shape (n_assets, n_cols)
Asset's classes matrix, where n_assets is the number of assets and
n_cols is the number of columns of the matrix where the first column
is the asset list and the next columns are the different asset's
classes sets.
Returns
-------
A : nd-array
The matrix A of :math:`Aw \geq B`.
B : nd-array
The matrix B of :math:`Aw \geq B`.
Raises
------
ValueError when the value cannot be calculated.
Examples
--------
::
import riskfolio.ConstraintsFunctions as cf
asset_classes = {'Assets': ['FB', 'GOOGL', 'NTFX', 'BAC', 'WFC', 'TLT', 'SHV'],
'Class 1': ['Equity', 'Equity', 'Equity', 'Equity', 'Equity',
'Fixed Income', 'Fixed Income'],
'Class 2': ['Technology', 'Technology', 'Technology',
'Financial', 'Financial', 'Treasury', 'Treasury'],}
asset_classes = pd.DataFrame(asset_classes)
constraints = {'Disabled': [False, False, False, False, False, False, False],
'Type': ['Classes', 'Classes', 'Assets', 'Assets', 'Classes',
'All Assets', 'Each asset in a class'],
'Set': ['Class 1', 'Class 1', '', '', 'Class 2', '', 'Class 1'],
'Position': ['Equity', 'Fixed Income', 'BAC', 'WFC', 'Financial',
'', 'Equity'],
'Sign': ['<=', '<=', '<=', '<=', '>=', '>=', '>='],
'Weight': [0.6, 0.5, 0.1, '', '', 0.02, ''],
'Type Relative': ['', '', '', 'Assets', 'Classes', '', 'Assets'],
'Relative Set': ['', '', '', '', 'Class 1', '', ''],
'Relative': ['', '', '', 'FB', 'Fixed Income', '', 'TLT'],
'Factor': ['', '', '', 1.2, 0.5, '', 0.4]}
constraints = pd.DataFrame(constraints)
The constraint looks like this:
.. image:: images/Constraints.png
It is easier to construct the constraints in excel and then upload to a
dataframe.
To create the matrixes A and B we use the following command:
::
A, B = cf.assets_constraints(constraints, asset_classes)
The matrixes A and B looks like this (all constraints were converted to a linear
constraint):
.. image:: images/AxB.png
"""
if not isinstance(constraints, pd.DataFrame) and not isinstance(
asset_classes, pd.DataFrame
):
raise ValueError("constraints and asset_classes must be DataFrames")
if constraints.shape[1] != 10:
raise ValueError("constraints must have ten columns")
n = len(constraints)
m = len(asset_classes)
data = constraints.fillna("")
data = data.values.tolist()
assetslist = asset_classes.iloc[:, 0].values.tolist()
A = []
B = []
for i in range(0, n):
if data[i][0] == False:
if data[i][1] == "Assets":
item = assetslist.index(data[i][3])
if data[i][4] == ">=":
d = 1
elif data[i][4] == "<=":
d = -1
if data[i][5] != "":
A1 = [0] * m
A1[item] = d
A.append(A1)
B.append([data[i][5] * d])
else:
A1 = [0] * m
A1[item] = 1
if data[i][6] == "Assets":
item2 = assetslist.index(data[i][8])
A2 = [0] * m
A2[item2] = 1
elif data[i][6] == "Classes":
A2 = np.where(
asset_classes[data[i][7]].values == data[i][8], 1, 0
)
A1 = ((np.array(A1) + np.array(A2) * data[i][9] * -1) * d).tolist()
A.append(A1)
B.append([0])
elif data[i][1] == "All Assets":
item = len(assetslist)
if data[i][4] == ">=":
d = 1
elif data[i][4] == "<=":
d = -1
if data[i][5] != "":
A1 = np.identity(item) * d
A1 = A1.tolist()
B1 = np.ones((item, 1)) * d * data[i][5]
for i in range(0, item):
A.append(A1[i])
B.append(B1.tolist()[0])
else:
A1 = np.identity(item)
if data[i][6] == "Assets":
item2 = assetslist.index(data[i][8])
A2 = np.zeros((item, item - 1))
A2 = np.insert(A2, item2 - 1, 1, axis=1)
elif data[i][6] == "Classes":
A1 = np.identity(item)
A2 = np.where(
asset_classes[data[i][7]].values == data[i][8], 1, 0
)
A2 = np.ones((item, item)) * np.array(A2)
A1 = ((np.array(A1) + np.array(A2) * data[i][9] * -1) * d).tolist()
for i in range(0, item):
A.append(A1[i])
B.append([0])
elif data[i][1] == "Classes":
if data[i][4] == ">=":
d = 1
elif data[i][4] == "<=":
d = -1
if data[i][5] != "":
A1 = np.where(asset_classes[data[i][2]].values == data[i][3], 1, 0)
A1 = np.array(A1) * d
A1 = A1.tolist()
A.append(A1)
B.append([data[i][5] * d])
else:
A1 = np.where(asset_classes[data[i][2]].values == data[i][3], 1, 0)
if data[i][6] == "Assets":
item2 = assetslist.index(data[i][8])
A2 = [0] * m
A2[item2] = 1
elif data[i][6] == "Classes":
A2 = np.where(
asset_classes[data[i][7]].values == data[i][8], 1, 0
)
A1 = ((np.array(A1) + np.array(A2) * data[i][9] * -1) * d).tolist()
A.append(A1)
B.append([0])
elif data[i][1] == "Each asset in a class":
if data[i][4] == ">=":
d = 1
elif data[i][4] == "<=":
d = -1
if data[i][5] != "":
A1 = np.where(asset_classes[data[i][2]].values == data[i][3], 1, 0)
l = 0
for k in A1:
if k == 1:
A3 = [0] * m
A3[l] = 1 * d
A.append(A3)
B.append([data[i][5] * d])
l = l + 1
else:
A1 = np.where(asset_classes[data[i][2]].values == data[i][3], 1, 0)
l = 0
for k in A1:
if k == 1:
A3 = [0] * m
A3[l] = 1
if data[i][6] == "Assets":
item2 = assetslist.index(data[i][8])
A2 = [0] * m
A2[item2] = 1
elif data[i][6] == "Classes":
A2 = np.where(
asset_classes[data[i][7]].values == data[i][8], 1, 0
)
A3 = (
(np.array(A3) + np.array(A2) * data[i][9] * -1) * d
).tolist()
A.append(A3)
B.append([0])
l = l + 1
elif data[i][1] == "All Classes":
if data[i][4] == ">=":
d = 1
elif data[i][4] == "<=":
d = -1
if data[i][5] != "":
for k in np.unique(asset_classes[data[i][2]].values):
A1 = np.where(asset_classes[data[i][2]].values == k, 1, 0) * d
A1 = A1.tolist()
A.append(A1)
B.append([data[i][5] * d])
else:
for k in np.unique(asset_classes[data[i][2]].values):
A1 = np.where(asset_classes[data[i][2]].values == k, 1, 0)
if data[i][6] == "Assets":
item2 = assetslist.index(data[i][8])
A2 = [0] * m
A2[item2] = 1
elif data[i][6] == "Classes":
A2 = np.where(
asset_classes[data[i][7]].values == data[i][8], 1, 0
)
A3 = (
(np.array(A1) + np.array(A2) * data[i][9] * -1) * d
).tolist()
A.append(A3)
B.append([0])
A = np.array(A, ndmin=2)
B = np.array(B, ndmin=2)
return A, B
def factors_constraints(constraints, loadings):
r"""
Create the factors constraints matrixes C and D of the constraint
:math:`Cw \geq D`.
Parameters
----------
constraints : DataFrame of shape (n_constraints, n_fields)
Constraints matrix, where n_constraints is the number of constraints
and n_fields is the number of fields of constraints matrix, the fields
are:
- Disabled: (bool) indicates if the constraint is enable.
- Factor: (str) the name of the factor of the constraint.
- Sign: (str) can be '>=' or '<='.
- Value: (scalar) is the maximum or minimum value of the factor.
loadings : DataFrame of shape (n_assets, n_features)
The loadings matrix.
Returns
-------
C : nd-array
The matrix C of :math:`Cw \geq D`.
D : nd-array
The matrix D of :math:`Cw \geq D`.
Raises
------
ValueError when the value cannot be calculated.
Examples
--------
::
loadings = {'const': [0.0004, 0.0002, 0.0000, 0.0006, 0.0001, 0.0003, -0.0003],
'MTUM': [0.1916, 1.0061, 0.8695, 1.9996, 0.0000, 0.0000, 0.0000],
'QUAL': [0.0000, 2.0129, 1.4301, 0.0000, 0.0000, 0.0000, 0.0000],
'SIZE': [0.0000, 0.0000, 0.0000, 0.4717, 0.0000, -0.1857, 0.0000],
'USMV': [-0.7838, -1.6439, -1.0176, -1.4407, 0.0055, 0.5781, 0.0000],
'VLUE': [1.4772, -0.7590, -0.4090, 0.0000, -0.0054, -0.4844, 0.9435]}
loadings = pd.DataFrame(loadings)
constraints = {'Disabled': [False, False, False],
'Factor': ['MTUM', 'USMV', 'VLUE'],
'Sign': ['<=', '<=', '>='],
'Value': [0.9, -1.2, 0.3],}
constraints = pd.DataFrame(constraints)
The constraint looks like this:
.. image:: images/Constraints2.png
It is easier to construct the constraints in excel and then upload to a
dataframe.
To create the matrixes C and D we use the following command:
::
C, D = cf.factors_constraints(constraints, loadings)
The matrixes C and D looks like this (all constraints were converted to a linear
constraint):
.. image:: images/CxD.png
"""
if not isinstance(constraints, pd.DataFrame) and not isinstance(
loadings, pd.DataFrame
):
raise ValueError("constraints and loadings must be DataFrames")
if constraints.shape[1] != 4:
raise ValueError("constraints must have four columns")
n = len(constraints)
data = constraints.fillna("")
data = data.values.tolist()
C = []
D = []
for i in range(0, n):
if data[i][0] == False:
if data[i][2] == ">=":
d = 1
elif data[i][2] == "<=":
d = -1
C1 = loadings[data[i][1]].values
C.append(C1 * d)
D.append([data[i][3] * d])
C = np.array(C, ndmin=2)
D = np.array(D, ndmin=2)
return C, D
def assets_views(views, asset_classes):
r"""
Create the assets views matrixes P and Q of the views :math:`Pw = Q`.
Parameters
----------
views : DataFrame of shape (n_views, n_fields)
Constraints matrix, where n_views is the number of views
and n_fields is the number of fields of views matrix, the fields
are:
- Disabled: (bool) indicates if the constraint is enable.
- Type: (str) can be: 'Assets' or 'Classes'.
- Set: (str) if Type is 'Classes' specified the name of the set of asset classes.
- Position: (str) the name of the asset or asset class of the view.
- Sign: (str) can be '>=' or '<='.
- Return: (scalar) is the return of the view.
- Type Relative: (str) can be: 'Assets' or 'Classes'.
- Relative Set: (str) if Type Relative is 'Classes' specified the name of the set of asset classes.
- Relative: (str) the name of the asset or asset class of the relative view.
asset_classes : DataFrame of shape (n_assets, n_cols)
Asset's classes matrix, where n_assets is the number of assets and
n_cols is the number of columns of the matrix where the first column
is the asset list and the next columns are the different asset's
classes sets.
Returns
-------
P : nd-array
The matrix P that shows the relation among assets in each view.
Q : nd-array
The matrix Q that shows the expected return of each view.
Raises
------
ValueError when the value cannot be calculated.
Examples
--------
::
asset_classes = {'Assets': ['FB', 'GOOGL', 'NTFX', 'BAC', 'WFC', 'TLT', 'SHV'],
'Class 1': ['Equity', 'Equity', 'Equity', 'Equity', 'Equity',
'Fixed Income', 'Fixed Income'],
'Class 2': ['Technology', 'Technology', 'Technology',
'Financial', 'Financial', 'Treasury', 'Treasury'],}
asset_classes = pd.DataFrame(asset_classes)
views = {'Disabled': [False, False, False, False],
'Type': ['Assets', 'Classes', 'Classes', 'Assets'],
'Set': ['', 'Class 2','Class 1', ''],
'Position': ['WFC', 'Financial', 'Equity', 'FB'],
'Sign': ['<=', '>=', '>=', '>='],
'Return': [ 0.3, 0.1, 0.05, 0.03 ],
'Type Relative': [ 'Assets', 'Classes', 'Assets', ''],
'Relative Set': [ '', 'Class 1', '', ''],
'Relative': ['FB', 'Fixed Income', 'TLT', '']}
views = pd.DataFrame(views)
The constraint looks like this:
.. image:: images/Views.png
It is easier to construct the constraints in excel and then upload to a
dataframe.
To create the matrixes P and Q we use the following command:
::
P, Q = cf.assets_views(views, asset_classes)
The matrixes P and Q looks like this:
.. image:: images/PxQ.png
"""
if not isinstance(views, pd.DataFrame) and not isinstance(
asset_classes, pd.DataFrame
):
raise ValueError("constraints and asset_classes must be DataFrames")
if views.shape[1] != 9:
raise ValueError("constraints must have nine columns")
n = len(views)
m = len(asset_classes)
data = views.fillna("")
data = data.values.tolist()
assetslist = asset_classes.iloc[:, 0].values.tolist()
P = []
Q = []
for i in range(0, n):
valid = False
if data[i][0] == False:
if data[i][1] == "Assets":
item = assetslist.index(data[i][3])
if data[i][4] == ">=":
d = 1
elif data[i][4] == "<=":
d = -1
if data[i][5] != "":
P1 = [0] * m
P1[item] = 1
if data[i][6] == "Assets" and data[i][8] != "":
item2 = assetslist.index(data[i][8])
P2 = [0] * m
P2[item2] = 1
valid = True
elif (
data[i][6] == "Classes"
and data[i][7] != ""
and data[i][8] != ""
):
P2 = np.where(
asset_classes[data[i][7]].values == data[i][8], 1, 0
)
P2 = P2 / np.sum(P2)
valid = True
elif data[i][6] == "" and data[i][7] == "" and data[i][8] == "":
P2 = [0] * m
valid = True
if valid == True:
P1 = ((np.array(P1) - np.array(P2)) * d).tolist()
P.append(P1)
Q.append([data[i][5] * d])
elif data[i][1] == "Classes":
if data[i][4] == ">=":
d = 1
else:
d = -1
if data[i][5] != "":
P1 = np.where(asset_classes[data[i][2]].values == data[i][3], 1, 0)
P1 = P1 / np.sum(P1)
if data[i][6] == "Assets" and data[i][8] != "":
item2 = assetslist.index(data[i][8])
P2 = [0] * m
P2[item2] = 1
valid = True
elif (
data[i][6] == "Classes"
and data[i][7] != ""
and data[i][8] != ""
):
P2 = np.where(
asset_classes[data[i][7]].values == data[i][8], 1, 0
)
P2 = P2 / np.sum(P2)
valid = True
elif data[i][6] == "" and data[i][7] == "" and data[i][8] == "":
P2 = [0] * m
valid = True
if valid == True:
P1 = ((np.array(P1) - np.array(P2)) * d).tolist()
P.append(P1)
Q.append([data[i][5] * d])
P = np.array(P, ndmin=2)
Q = np.array(Q, ndmin=2)
for i in range(len(Q)):
if Q[i, 0] < 0:
P[i, :] = -1 * P[i, :]
Q[i, :] = -1 * Q[i, :]
return P, Q