attrix 0.1.1__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.

Potentially problematic release.


This version of attrix might be problematic. Click here for more details.

attrix-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.1
2
+ Name: attrix
3
+ Version: 0.1.1
4
+ Summary: A tool for portfolio attribution
5
+ Home-page: https://github.com/papasaidfine/attribution
6
+ Author: Larry Chen
7
+ Author-email: yatlik.chen@outlook.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.6
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: pandas>=2.2.2
14
+ Requires-Dist: scipy>=1.14.0
15
+ Requires-Dist: numpy>=2.0.0
16
+
17
+ # Attribution Library for Wolfe QES Risk Model
attrix-0.1.1/README.md ADDED
@@ -0,0 +1 @@
1
+ # Attribution Library for Wolfe QES Risk Model
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
attrix-0.1.1/setup.cfg ADDED
@@ -0,0 +1,29 @@
1
+ [metadata]
2
+ name = attrix
3
+ version = 0.1.1
4
+ author = Larry Chen
5
+ author_email = yatlik.chen@outlook.com
6
+ description = A tool for portfolio attribution
7
+ long_description = file: README.md
8
+ long_description_content_type = text/markdown
9
+ url = https://github.com/papasaidfine/attribution
10
+ classifiers =
11
+ Programming Language :: Python :: 3
12
+ License :: OSI Approved :: MIT License
13
+ Operating System :: OS Independent
14
+
15
+ [options]
16
+ packages = find:
17
+ python_requires = >=3.6
18
+ install_requires =
19
+ pandas>=2.2.2
20
+ scipy>=1.14.0
21
+ numpy>=2.0.0
22
+
23
+ [options.packages.find]
24
+ where = src
25
+
26
+ [egg_info]
27
+ tag_build =
28
+ tag_date = 0
29
+
@@ -0,0 +1,604 @@
1
+ from .TSCollector import TSCollector
2
+ import logging
3
+ import pandas as pd
4
+ import numpy as np
5
+ from scipy.sparse import csr_matrix, csc_matrix, hstack, vstack, diags
6
+ from .DAO import RiskModelReader, SecurityReturnDAO
7
+
8
+
9
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
10
+
11
+
12
+ class AttributionCore:
13
+ """
14
+ h: m x 1
15
+ E: m x k
16
+ Gamma: k x k
17
+ Lambda: m x m
18
+ f: k x 1
19
+ r: m x 1
20
+ G: k x g
21
+ """
22
+
23
+ def __init__(self, h, E, Gamma, Lambda, f, r, G):
24
+ self._cache = {}
25
+ self.h, self.E = h, E
26
+ self.Gamma, self.Lambda = Gamma, Lambda
27
+ self.f, self.r = f, r
28
+ self.G = G
29
+
30
+ def _add_group(self, factor_part, residual_part):
31
+ G = self.G
32
+ group_part = factor_part.dot(G)
33
+ systematic_part = csr_matrix(group_part.sum(axis=1))
34
+ total_part = systematic_part + residual_part
35
+ return hstack([factor_part, group_part, systematic_part, residual_part, total_part])
36
+
37
+ @property
38
+ def stock_exposure(self):
39
+ return self.E
40
+
41
+ @property
42
+ def stock_var(self):
43
+ if "stock_var" not in self._cache.keys():
44
+ E, Gamma, Lambda = self.E, self.Gamma, self.Lambda
45
+ X = E.dot(Gamma)
46
+ systematic_var = X.multiply(E)
47
+ residual_var = csr_matrix(Lambda.diagonal()).T
48
+ self._cache["stock_var"] = self._add_group(
49
+ systematic_var, residual_var)
50
+ return self._cache.get("stock_var")
51
+
52
+ @property
53
+ def stock_total_risk(self):
54
+ if "stock_total_risk" not in self._cache.keys():
55
+ total_var = self.stock_var.tocsr()[:, -1]
56
+ self._cache["stock_total_risk"] = np.sqrt(total_var)
57
+ return self._cache.get("stock_total_risk")
58
+
59
+ @property
60
+ def stock_risk(self):
61
+ if "stock_risk" not in self._cache.keys():
62
+ stock_var = self.stock_var
63
+ stock_total_risk = self.stock_total_risk
64
+ self._cache["stock_risk"] = stock_var.multiply(
65
+ stock_total_risk.power(-1))
66
+ return self._cache.get("stock_risk")
67
+
68
+ @property
69
+ def stock_return(self):
70
+ if "stock_return" not in self._cache.keys():
71
+ f, E, r = self.f, self.E, self.r
72
+ systematic_part = E.multiply(f.T)
73
+ residual_part = r - csr_matrix(systematic_part.sum(axis=1))
74
+ self._cache["stock_return"] = self._add_group(
75
+ systematic_part, residual_part)
76
+ return self._cache.get("stock_return")
77
+
78
+ @property
79
+ def stock_exposure_contri(self):
80
+ if "stock_exposure_contri" not in self._cache.keys():
81
+ h, E = self.h, self.E
82
+ self._cache["stock_exposure_contri"] = E.multiply(h)
83
+ return self._cache.get("stock_exposure_contri")
84
+
85
+ @property
86
+ def factor_risk(self):
87
+ Gamma = self.Gamma
88
+ return csr_matrix(np.sqrt(Gamma.diagonal())).T
89
+
90
+ @property
91
+ def stock_voladj_exposure_contri(self):
92
+ if "stock_voladj_exposure_contri" not in self._cache.keys():
93
+ stock_exposure_contri, factor_risk = self.stock_exposure_contri, self.factor_risk
94
+ self._cache["stock_voladj_exposure_contri"] = stock_exposure_contri.multiply(
95
+ factor_risk.T)
96
+ return self._cache.get("stock_voladj_exposure_contri")
97
+
98
+ @property
99
+ def stock_correlation(self):
100
+ pass
101
+ # if "stock_correlation" not in self._cache.keys():
102
+ # stock_voladj_exposure_contri = self.stock_voladj_exposure_contri
103
+ # stock_risk_contri = self.stock_risk_contri
104
+ # return self._cache.get("stock_correlation")
105
+
106
+ @property
107
+ def stock_var_contri(self):
108
+ if "stock_var_contri" not in self._cache.keys():
109
+ h, E, Gamma, Lambda = self.h, self.E, self.Gamma, self.Lambda
110
+ x = h.T.dot(E).dot(Gamma)
111
+ systematic_var_contri = E.multiply(x).multiply(h)
112
+ residual_var_contri = Lambda.dot(h).multiply(h)
113
+ self._cache["stock_var_contri"] = self._add_group(
114
+ systematic_var_contri, residual_var_contri)
115
+ return self._cache.get("stock_var_contri")
116
+
117
+ @property
118
+ def port_total_risk(self):
119
+ if "port_total_risk" not in self._cache.keys():
120
+ self._cache["port_total_risk"] = np.sqrt(
121
+ self.stock_var_contri.tocsr()[:, -1].sum())
122
+ return self._cache.get("port_total_risk")
123
+
124
+ @property
125
+ def stock_risk_contri(self):
126
+ if "stock_risk_contri" not in self._cache.keys():
127
+ self._cache["stock_risk_contri"] = self.stock_var_contri / \
128
+ self.port_total_risk
129
+ return self._cache.get("stock_risk_contri")
130
+
131
+ @property
132
+ def stock_return_contri(self):
133
+ if "stock_return_contri" not in self._cache.keys():
134
+ h = self.h
135
+ self._cache["stock_return_contri"] = self.stock_return.multiply(h)
136
+ return self._cache.get("stock_return_contri")
137
+
138
+ @property
139
+ def port_exposure(self):
140
+ if "port_exposure" not in self._cache.keys():
141
+ self._cache["port_exposure"] = csc_matrix(
142
+ self.stock_exposure_contri.sum(axis=0).T)
143
+ return self._cache.get("port_exposure")
144
+
145
+ @property
146
+ def port_voladj_exposure(self):
147
+ if "port_voladj_exposure" not in self._cache.keys():
148
+ self._cache["port_voladj_exposure"] = csc_matrix(
149
+ self.port_exposure.multiply(self.factor_risk))
150
+ return self._cache.get("port_voladj_exposure")
151
+
152
+ @property
153
+ def port_correlation(self):
154
+ if "port_correlation" not in self._cache.keys():
155
+ Gamma, port_exposure, factor_risk, port_total_risk = self.Gamma, self.port_exposure, self.factor_risk, self.port_total_risk
156
+ self._cache["port_correlation"] = Gamma.dot(
157
+ port_exposure).multiply((factor_risk*port_total_risk).power(-1))
158
+ return self._cache.get("port_correlation")
159
+
160
+ @property
161
+ def port_risk(self):
162
+ if "port_risk" not in self._cache.keys():
163
+ self._cache["port_risk"] = csc_matrix(
164
+ self.stock_risk_contri.sum(axis=0).T)
165
+ return self._cache.get("port_risk")
166
+
167
+ @property
168
+ def port_return(self):
169
+ if "port_return" not in self._cache.keys():
170
+ self._cache["port_return"] = csc_matrix(
171
+ self.stock_return_contri.sum(axis=0).T)
172
+ return self._cache.get("port_return")
173
+
174
+
175
+ def expand_matrix(df, index=None, columns=None, fillna=0):
176
+ """
177
+ Expand matrix dimensions.
178
+
179
+ This function expand matrix index and columns.
180
+
181
+ Parameters:
182
+ df (DataFrame): The matrix to be expanded.
183
+
184
+ Returns:
185
+ DataFrame: The expanded matrix.
186
+ """
187
+ if index is None:
188
+ index = df.index
189
+ if columns is None:
190
+ columns = df.columns
191
+ extra_columns = list(set(columns) - set(df.columns))
192
+ extra_index = list(set(index) - set(df.index))
193
+ return pd.concat([df, pd.DataFrame(index=extra_index, columns=extra_columns)], axis=0).fillna(fillna)
194
+
195
+ # v1 = weight_mat.iloc[:,0]
196
+ # v2 = weight_mat2.iloc[:,0]
197
+ # basket_weight = pd.concat([v1,v2], axis=1, keys=['PORTFOLIO','MYBENCHMARK'])
198
+ # rows=['extrarow1','MYBENCHMARK']
199
+ # cols=['extracol1','extracol2']
200
+ # expand_matrix(weight_mat, index=rows,columns=cols)
201
+
202
+
203
+ def _expand_basket_weight(basket_weight):
204
+ """
205
+ Expand basket holdings to bottom level.
206
+
207
+ This function expand baskets holdings to the bottom level that only holds equity securities.
208
+
209
+ Parameters:
210
+ basket_weight (DataFrame): The basket holdings matrix with holdings on the rows, basket names on the columns.
211
+
212
+ Returns:
213
+ DataFrame: The expanded holdings matrix.
214
+ """
215
+ basket_weight.fillna(0, inplace=True)
216
+ basket_ids = basket_weight.columns
217
+ non_basket_ids = list(set(basket_weight.index) - set(basket_ids))
218
+ basket_weight = expand_matrix(basket_weight, index=basket_ids)
219
+ logging.debug(
220
+ '{} baskets and {} non-basket equities.'.format(len(basket_ids), len(non_basket_ids)))
221
+
222
+ B = basket_weight.loc[basket_ids, :]
223
+ B.fillna(0, inplace=True)
224
+ if B.empty:
225
+ logging.info('No basket cross ownership.')
226
+ return basket_weight
227
+
228
+ e_B = np.linalg.eig(B)
229
+
230
+ if any(np.abs(e_B[0]) >= 1):
231
+ logging.error(
232
+ 'Absolute value of eigenvalue greater than 1 of holding matrix. ')
233
+ raise ValueError(
234
+ 'Absolute value of eigenvalue greater than 1 of holding matrix. ')
235
+ elif all(e_B[0] == 0):
236
+ # No cross ownership
237
+ A = basket_weight.loc[non_basket_ids]
238
+ I = np.eye(B.shape[0])
239
+ return pd.DataFrame(np.dot(A, np.linalg.inv(I - B)),
240
+ index=non_basket_ids,
241
+ columns=basket_ids)
242
+ else:
243
+ # Real part of \sum_{i=1}^inf B^i
244
+ B_sum = np.real(np.round(
245
+ np.dot(np.dot(e_B[1], np.diag(1/(1-e_B[0]))), np.linalg.inv(e_B[1])), 15))
246
+ B_sum = pd.DataFrame(B_sum, index=B.index, columns=B.index)
247
+ return pd.DataFrame(np.dot(basket_weight.loc[non_basket_ids], B_sum),
248
+ index=non_basket_ids,
249
+ columns=basket_ids)
250
+
251
+
252
+ class AttributionData:
253
+ def __init__(self, portfolio, rmd, security_return):
254
+ self._r = security_return
255
+ self.H, self.index_H = portfolio.H, portfolio.index_H
256
+ self.h, self.index_h = portfolio.h, portfolio.index_h
257
+ self.etf_ids = portfolio.get_etf_ids()
258
+ self._init_data(rmd)
259
+
260
+ def _init_data(self, rmd):
261
+ self._init_G(rmd)
262
+ self._init_E(rmd)
263
+ self._init_f(rmd)
264
+ self._init_Lambda(rmd)
265
+ self._init_Gamma(rmd)
266
+ self._init_idm(rmd)
267
+ self._init_r()
268
+
269
+ def _init_G(self, rmd):
270
+ category_col = 'Category'
271
+ df = rmd.get('ret')
272
+ factor_names = list(df.index)
273
+ factor_alias = list(df['FactorAlias'])
274
+ cates = list(df[category_col].unique())
275
+ df = df[[category_col]]
276
+ df.loc[:, ['Value']] = 1
277
+ df = df.pivot(columns=category_col, values='Value').fillna(0)
278
+ df = df.loc[factor_names, cates]
279
+ G = csr_matrix(df)
280
+ self.G = G
281
+ self.factor_names = factor_names
282
+ self.factor_alias = factor_alias
283
+ self.group_names = cates
284
+
285
+ def _init_E(self, rmd):
286
+ index_H = self.index_H
287
+ factor_names = self.factor_names
288
+ exp = rmd.get('exp').loc[index_H, factor_names]
289
+ self._E = csr_matrix(exp)
290
+
291
+ def _init_f(self, rmd):
292
+ _r = self._r
293
+ factor_names = self.factor_names
294
+ F = rmd.get('fmp').loc[:, factor_names]
295
+ _r = _r.loc[F.index]
296
+ f = F.T.dot(_r)
297
+ self.f = csr_matrix(f).T
298
+
299
+ def _init_Lambda(self, rmd):
300
+ index_H = self.index_H
301
+ id_map = {id: int(i) for i, id in enumerate(index_H)}
302
+ isc = rmd.get('isc')
303
+ isc = isc.loc[isc.SecurityId1.isin(
304
+ index_H) & isc.SecurityId2.isin(index_H)]
305
+ isc = csr_matrix((isc.Covariance, (isc.SecurityId1.map(
306
+ id_map), isc.SecurityId2.map(id_map))), shape=(len(index_H), len(index_H)))
307
+ rsk = diags(list(rmd.get('rsk').loc[index_H, 'SpecificRisk']/100))
308
+ _Lambda = rsk**2 + isc
309
+ self._Lambda = _Lambda
310
+
311
+ def _init_Gamma(self, rmd):
312
+ factor_names = self.factor_names
313
+ cov = rmd.get('cov').loc[factor_names, factor_names]
314
+ Gamma = csr_matrix(cov)
315
+ self.Gamma = Gamma
316
+
317
+ def _init_idm(self, rmd):
318
+ index_H = self.index_H
319
+ baskets = self.etf_ids
320
+
321
+ idm = rmd.get('idm')
322
+ meta = idm.columns # TODO: meta columns customization
323
+ idm = idm.loc[index_H, meta]
324
+
325
+ basket_idm = pd.DataFrame(index=baskets, columns=meta)
326
+ if 'comp_idm' in rmd.keys():
327
+ comp_idm = rmd.get('comp_idm')
328
+ comp_ids = list(set(baskets) & set(comp_idm.index))
329
+ basket_idm.loc[comp_ids, :] = comp_idm.loc[comp_ids, :].values
330
+
331
+ idm = pd.concat([idm, basket_idm], axis=0)
332
+ self.idm = idm
333
+
334
+ def _init_r(self):
335
+ _r = self._r
336
+ index_H = self.index_H
337
+ _r = csr_matrix(_r.loc[index_H]).T
338
+ self._r = _r
339
+
340
+ def _change_portfolio_tree(self, portfolio):
341
+ """
342
+ Transform portfolio to a specific layer.
343
+ """
344
+ self.H = portfolio.H
345
+ self.h, self.index_h = portfolio.h, portfolio.index_h
346
+
347
+
348
+ class AttributionOne:
349
+ config = {}
350
+ cache = {}
351
+ result = {}
352
+
353
+ def __init__(self, data, config={}):
354
+ """
355
+ Initialize an object.
356
+
357
+ Parameters:
358
+ data: An AttributionData instance.
359
+ config (dict): Attribution configurations.
360
+ """
361
+ self.data = data
362
+ self.config.update(config)
363
+ self._init_core()
364
+
365
+ @property
366
+ def h(self):
367
+ return self.data.h
368
+
369
+ @property
370
+ def E(self):
371
+ H, _E = self.data.H, self.data._E
372
+ E = H.T.dot(_E)
373
+ return E
374
+
375
+ @property
376
+ def Gamma(self):
377
+ return self.data.Gamma
378
+
379
+ @property
380
+ def Lambda(self):
381
+ H, _Lambda = self.data.H, self.data._Lambda
382
+ Lambda = H.T.dot(_Lambda).dot(H)
383
+ return Lambda
384
+
385
+ @property
386
+ def f(self):
387
+ return self.data.f
388
+
389
+ @property
390
+ def r(self):
391
+ H, _r = self.data.H, self.data._r
392
+ r = H.T.dot(_r)
393
+ return r
394
+
395
+ @property
396
+ def G(self):
397
+ return self.data.G
398
+
399
+ @property
400
+ def index_h(self):
401
+ return self.data.index_h
402
+
403
+ @property
404
+ def index_H(self):
405
+ return self.data.index_H
406
+
407
+ @property
408
+ def factor_names(self):
409
+ return self.data.factor_names
410
+
411
+ @property
412
+ def factor_alias(self):
413
+ return self.data.factor_alias
414
+
415
+ @property
416
+ def group_names(self):
417
+ return self.data.group_names
418
+
419
+ def _get_full_headers(self):
420
+ factor_alias, group_names = self.factor_alias, self.group_names
421
+ return factor_alias + group_names + ["Systematic", "Residual", "Total"]
422
+
423
+ def _init_core(self):
424
+ self.core = AttributionCore(
425
+ self.h, self.E, self.Gamma, self.Lambda, self.f, self.r, self.G)
426
+
427
+ def get_stock_exposure_contri(self):
428
+ return pd.DataFrame(self.core.stock_exposure_contri.todense(), index=self.index_h, columns=self.factor_alias)
429
+
430
+ def get_port_risk(self):
431
+ return self.core.port_risk
432
+
433
+ def get_stock_risk_contri(self):
434
+ return pd.DataFrame(self.core.stock_risk_contri.todense(), index=self.index_h, columns=self._get_full_headers())
435
+
436
+ def get_stock_exposure(self):
437
+ return pd.DataFrame(self.core.stock_exposure.todense(), index=self.index_h, columns=self.factor_alias)
438
+
439
+ def get_stock_risk(self):
440
+ return pd.DataFrame(self.core.stock_risk.todense(), index=self.index_h, columns=self._get_full_headers())
441
+
442
+ def get_stock_var(self):
443
+ return pd.DataFrame(self.core.stock_var.todense(), index=self.index_h, columns=self._get_full_headers())
444
+
445
+ def get_stock_return(self):
446
+ return pd.DataFrame(self.core.stock_return.todense(), index=self.index_h, columns=self._get_full_headers())
447
+
448
+ def get_stock_return_contri(self):
449
+ return pd.DataFrame(self.core.stock_return_contri.todense(), index=self.index_h, columns=self._get_full_headers())
450
+
451
+ def get_port_exposure(self):
452
+ return pd.Series(self.core.port_exposure.toarray().flatten(), index=self.factor_alias)
453
+
454
+ def get_port_voladj_exposure(self):
455
+ return pd.Series(self.core.port_voladj_exposure.toarray().flatten(), index=self.factor_alias)
456
+
457
+ def get_port_correlation(self):
458
+ return pd.Series(self.core.port_correlation.toarray().flatten(), index=self.factor_alias)
459
+
460
+ def get_port_risk(self):
461
+ return pd.Series(self.core.port_risk.toarray().flatten(), index=self._get_full_headers())
462
+
463
+ def get_port_risk_pct(self):
464
+ port_risk = self.get_port_risk()
465
+ return port_risk/port_risk.loc['Total']
466
+
467
+ def get_port_return(self):
468
+ return pd.Series(self.core.port_return.toarray().flatten(), index=self._get_full_headers())
469
+
470
+ def get_port_summary(self):
471
+ return pd.DataFrame({
472
+ 'Exposure': self.get_port_exposure(),
473
+ 'Exposure (Vol Adj.)': self.get_port_voladj_exposure(),
474
+ 'Correlation': self.get_port_correlation(),
475
+ 'Risk Contri.': self.get_port_risk(),
476
+ 'Risk Contri. (%).': self.get_port_risk_pct(),
477
+ 'Return Contri.': self.get_port_return()
478
+ }, index=self._get_full_headers())
479
+
480
+ def change_portfolio_tree(self, portfolio):
481
+ self.data._change_portfolio_tree(portfolio)
482
+ self._init_core()
483
+
484
+
485
+ class AttributionTS(TSCollector):
486
+ def __init__(self, portfolio_ts=None, config=None):
487
+ if config is None:
488
+ config = {
489
+ "path": "attribution_data",
490
+ "additional_t": None,
491
+ "meta_file": None,
492
+ "rmd_reader_config": {},
493
+ "return_dao_config": {}
494
+ }
495
+ super().__init__(config)
496
+ if portfolio_ts is not None:
497
+ self._setup_dao()
498
+ self.portfolio_ts = portfolio_ts
499
+ self._init_a1_list()
500
+
501
+ def _init_a1_list(self):
502
+ t_list = self.portfolio_ts.t_list
503
+ additional_t = self.config.get('additional_t')
504
+ if (additional_t is not None) and (additional_t > max(t_list)):
505
+ self.return_dao.set_t_list(t_list + [additional_t])
506
+ logging.debug(f'Set additional timestamp to {additional_t}')
507
+ else:
508
+ self.return_dao.set_t_list(t_list)
509
+ self._cache = {t: self._init_a1(t) for t in t_list}
510
+
511
+ def _init_a1(self, t):
512
+ logging.info('Initializing AttributionOne for {} ... '.format(t))
513
+ try:
514
+ reader = self.reader
515
+ return_dao = self.return_dao
516
+ p1 = self.portfolio_ts.load_one(t)
517
+ rmd = reader.get_risk_model_data(
518
+ t, ['idm', 'comp_idm', 'exp', 'cov', 'rsk', 'isc', 'fmp', 'ret'])
519
+ security_return = return_dao.get_forward_return(t)
520
+ data = AttributionData(p1, rmd, security_return)
521
+ logging.info('OK')
522
+ return AttributionOne(data)
523
+ except Exception as e:
524
+ logging.info(f'Failed: {e}')
525
+
526
+ def _setup_dao(self):
527
+ self._use_one_reader()
528
+ self.reader = RiskModelReader(self.config.get(
529
+ 'rmd_reader_config').get('meta_file'))
530
+ self.return_dao = SecurityReturnDAO(
531
+ self.config.get('return_dao_config'))
532
+
533
+ def _use_one_reader(self):
534
+ config = self.config
535
+ meta_file = config.get('meta_file')
536
+ if meta_file is not None:
537
+ config['rmd_reader_config']['meta_file'] = meta_file
538
+ logging.debug(f'Use {meta_file} for rmd_reader')
539
+ config['return_dao_config']['meta_file'] = meta_file
540
+ logging.debug(f'Use {meta_file} for security_return_dao')
541
+ self.config = config
542
+
543
+ def get_port_exposure_ts(self):
544
+ a1_dict = self.load()
545
+ df = pd.concat([a1.get_port_exposure()
546
+ for key, a1 in a1_dict.items()], axis=1).T
547
+ df.index = list(a1_dict.keys())
548
+ return df
549
+
550
+ def get_port_voladj_exposure_ts(self):
551
+ a1_dict = self.load()
552
+ df = pd.concat([a1.get_port_voladj_exposure()
553
+ for key, a1 in a1_dict.items()], axis=1).T
554
+ df.index = list(a1_dict.keys())
555
+ return df
556
+
557
+ def get_port_correlation_ts(self):
558
+ a1_dict = self.load()
559
+ df = pd.concat([a1.get_port_correlation()
560
+ for key, a1 in a1_dict.items()], axis=1).T
561
+ df.index = list(a1_dict.keys())
562
+ return df
563
+
564
+ def get_port_risk_ts(self):
565
+ a1_dict = self.load()
566
+ df = pd.concat([a1.get_port_risk()
567
+ for key, a1 in a1_dict.items()], axis=1).T
568
+ df.index = list(a1_dict.keys())
569
+ return df
570
+
571
+ def get_port_risk_pct_ts(self):
572
+ a1_dict = self.load()
573
+ df = pd.concat([a1.get_port_risk_pct()
574
+ for key, a1 in a1_dict.items()], axis=1).T
575
+ df.index = list(a1_dict.keys())
576
+ return df
577
+
578
+ def get_port_return_ts(self):
579
+ a1_dict = self.load()
580
+ df = pd.concat([a1.get_port_return()
581
+ for key, a1 in a1_dict.items()], axis=1).T
582
+ df.index = list(a1_dict.keys())
583
+ return df
584
+
585
+ def get_port_cum_return_ts(self):
586
+ total_col = 'Total'
587
+ return_mat = self.get_port_return_ts()
588
+ total_return = return_mat.loc[:, total_col]
589
+ total_wealth = (total_return + 1).cumprod().shift(1).fillna(1)
590
+ addable_return_mat = return_mat.mul(
591
+ total_wealth, axis=0).shift(1).fillna(0)
592
+ wealth_mat = addable_return_mat.cumsum(axis=0) + 1
593
+ return wealth_mat
594
+
595
+ def get_port_ts_data(self):
596
+ return {
597
+ "Exposure": self.get_port_exposure_ts(),
598
+ "Exposure (Vol Adj.)": self.get_port_voladj_exposure_ts(),
599
+ "Correlation": self.get_port_correlation_ts(),
600
+ "Risk Contri.": self.get_port_risk_ts(),
601
+ "Risk Contri. (%)": self.get_port_risk_pct_ts(),
602
+ "Return Contri.": self.get_port_return_ts(),
603
+ "Cum Return Contri.": self.get_port_cum_return_ts()
604
+ }