attrix 0.1.1__py3-none-any.whl

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.

@@ -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
+ }
attrix/DAO.py ADDED
@@ -0,0 +1,293 @@
1
+ import pandas as pd
2
+ import datetime
3
+ from os.path import join
4
+ from functools import reduce
5
+ import json
6
+ import warnings
7
+ import logging
8
+
9
+ # Suppress FutureWarning
10
+ warnings.simplefilter(action='ignore', category=FutureWarning)
11
+
12
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
13
+
14
+ class RiskModelReader:
15
+ model_dates = [],
16
+ model_meta = {
17
+ 'model_id': None,
18
+ 'model_path': None,
19
+ 'model_folder': None,
20
+ 'file_path': None,
21
+ 'file_prefix': None,
22
+ 'file_suffix': None,
23
+ 'model_start_date': None,
24
+ 'model_desc': None,
25
+ 'model_calendar': None, # i.e. USA
26
+ 'file_folder': {},
27
+ 'file_structure': {},
28
+ 'model_calendar_path': None
29
+ }
30
+
31
+ def __init__(self, meta_file):
32
+ with open(meta_file) as f:
33
+ self.model_meta.update(json.load(f))
34
+ self.model_dates = self._get_model_dates()
35
+
36
+ @staticmethod
37
+ def _dated_to_yyyy_mm(dated):
38
+ dt = datetime.datetime.strptime(dated, '%Y-%m-%d')
39
+ return dt.strftime('%Y'), dt.strftime('%m')
40
+
41
+ @staticmethod
42
+ def _isc_to_dense(df_isc):
43
+ P, rows, cols = df_isc.set_index(('SecurityId1','SecurityId2'))['Covariance'].to_sparse().to_coo()
44
+ return pd.DataFrame(P.todense(), columns=cols, index= rows)
45
+
46
+ def _get_folder(self, dated, file):
47
+ yyyy, mm = self._dated_to_yyyy_mm(dated)
48
+ return self.model_meta.get('file_path').format(model_path=self.model_meta.get('model_path'),
49
+ model_folder=self.model_meta.get('model_folder'),
50
+ file_folder=self.model_meta.get('file_folder')[file],
51
+ yyyy=yyyy, mm=mm)
52
+
53
+ def _get_file_path(self, dated, file):
54
+ dt = datetime.datetime.strptime(dated, '%Y-%m-%d')
55
+ file_prefix = self.model_meta.get('file_prefix')
56
+ file_suffix = self.model_meta.get('file_suffix')
57
+ file_prefix = datetime.datetime.strftime(dt, file_prefix) if file_prefix is not None else ''
58
+ file_suffix = datetime.datetime.strftime(dt, file_suffix) if file_suffix is not None else ''
59
+ return join(self._get_folder(dated, file), file_prefix + file + file_suffix)
60
+
61
+ def _get_model_dates(self, end_date = datetime.date.today().strftime('%Y-%m-%d')):
62
+ model_dates = pd.bdate_range(start=self.model_meta.get('model_start_date'), end=end_date).strftime('%Y-%m-%d').to_list()
63
+ if self.model_meta.get('model_calendar') is not None:
64
+ with open(self.model_meta.get('model_calendar_path')) as holidaycal_file:
65
+ holidaycal = json.load(holidaycal_file)[self.model_meta.get('model_calendar')]
66
+ model_dates = [day for day in model_dates if day not in holidaycal]
67
+ return model_dates
68
+
69
+ def _read_files(self, file_type, files):
70
+ if file_type in ('idm', 'att', 'exp', 'zsc', 'cov', 'ret', 'fmp', 'comp_idm', 'comp_att', 'comp_exp'):
71
+ return reduce(lambda df_left, df_right: pd.merge(df_left, df_right, left_index=True, right_index=True, how='left'),
72
+ [pd.read_csv(x, index_col=0) for x in files])
73
+ elif file_type in ('rsk','comp_rsk'):
74
+ return reduce(lambda df_left, df_right: pd.merge(df_left, df_right, left_index=True, right_index=True, how='left'),
75
+ [pd.read_csv(x, index_col=0) for x in files])[['TotalRisk', 'SpecificRisk']]
76
+ elif file_type in ('isc','comp_weight'):
77
+ return pd.concat([pd.read_csv(x) for x in files], axis=0)
78
+ else:
79
+ logging.warning('File type not recognized.')
80
+ return pd.DataFrame()
81
+
82
+ def get_risk_model_data(self, dated, data_types=[]):
83
+ if dated not in self.model_dates:
84
+ dated_ = dated
85
+ dated = max([d for d in self.model_dates if d < dated])
86
+ logging.warning(f'The date {dated_} is not within the model dates, use {dated} instead')
87
+ logging.debug('Getting risk model data from flat files for {}.'.format(dated))
88
+ file_structure = self.model_meta.get('file_structure')
89
+ if len(data_types)>0:
90
+ file_structure = {key: file_structure.get(key) for key in data_types if key in file_structure.keys()}
91
+ files = self.model_meta.get('file_folder').keys()
92
+ rmd = {k: self._read_files(k, [self._get_file_path(dated, x) for x in fls if x in files])
93
+ for k, fls in file_structure.items()}
94
+ return rmd
95
+
96
+ class BaseDAO:
97
+ _reader = None
98
+
99
+ def __init__(self, config = None):
100
+ self.config = {
101
+ "meta_file": None,
102
+ }
103
+ if config is not None:
104
+ self.config.update(config)
105
+ if self.config.get('meta_file') is not None:
106
+ self.set_reader(self.config.get('meta_file'))
107
+
108
+ def set_reader(self, meta_file):
109
+ self.config['meta_file'] = meta_file
110
+ self._reader = RiskModelReader(meta_file)
111
+
112
+ def _get_concat_data(self, t, axis=0, reset_index=True):
113
+ if self._reader is None:
114
+ raise ValueError('Reader not set up yet!')
115
+ data_types = self.config.get('data_types')
116
+ data = self._reader.get_risk_model_data(t, data_types=data_types)
117
+ if reset_index:
118
+ return pd.concat(data.values(),axis=axis).reset_index()
119
+ else:
120
+ return pd.concat(data.values(),axis=axis)
121
+
122
+
123
+ class SecurityDAO(BaseDAO):
124
+ DEFAULT_CONFIG = {
125
+ 'meta_file': None,
126
+ 'mapping_cols': [],
127
+ 'time_col': 'Date',
128
+ 'id_col': 'SecurityID',
129
+ 'portfolio_col': 'Portfolio',
130
+ 'weight_col': 'Weight',
131
+ 'data_types': ['idm','comp_idm']
132
+ }
133
+ def __init__(self, config = None):
134
+ config_ = self.DEFAULT_CONFIG
135
+ if config is not None:
136
+ config_.update(config)
137
+ super().__init__(config_)
138
+ print('Available mappings: (Ticker,Country), (SEDOL7) or (CUSIP)')
139
+
140
+ def set_mapping_cols(self, mapping_cols):
141
+ self.config['mapping_cols'] = mapping_cols
142
+
143
+ def map(self, df):
144
+ time_col = self.config.get('time_col')
145
+ df_ = df.groupby([time_col])[df.columns].apply(self._map_one)
146
+ df_.reset_index(drop=True, inplace=True)
147
+ return(df_)
148
+
149
+ def _map_one(self, df):
150
+ config = self.config
151
+ id_col, time_col, portfolio_col, mapping_cols = config.get('id_col'), config.get('time_col'), config.get('portfolio_col'), config.get('mapping_cols')
152
+ init_id_col = mapping_cols[0]
153
+ t = df[time_col].iloc[0]
154
+
155
+ data = self._get_concat_data(t, axis=0, reset_index=True)
156
+ df_ = df.merge(data, how='left', on=mapping_cols)
157
+ df_['Status'] = 'Mapped'
158
+ df_.loc[df_[id_col].isna(),'Status'] = 'Unknown'
159
+ user_portfolios = list(df_[portfolio_col].unique())
160
+ df_.loc[df_[init_id_col].isin(user_portfolios),'Status'] = 'User Provided'
161
+ df_.loc[df_[id_col].isna(),id_col] = df_.loc[df_[id_col].isna(),init_id_col].values # let the unknown security be the initial id
162
+ return(df_)
163
+
164
+ def to_weight_list(self, df, t):
165
+ """
166
+ Convert a mapped dataframe to a dict of weights on one point-in-time (only include the covered assets)
167
+ """
168
+ config = self.config
169
+ time_col, id_col, portfolio_col, weight_col = config.get('time_col'), config.get('id_col'), config.get('portfolio_col'), config.get('weight_col')
170
+ df = df[(df[time_col]==t) & (df['Status']!='Unknown')]
171
+ portfolios = list(df[portfolio_col].unique())
172
+ return {p: df[df[portfolio_col]==p].set_index(id_col)[weight_col] for p in portfolios}
173
+
174
+
175
+ class ETFDAO(BaseDAO):
176
+ DEFAULT_CONFIG = {
177
+ "meta_file": None,
178
+ "data_types": ["comp_weight"],
179
+ "weight_col": "ConstituentWeight",
180
+ "id_col": "ConstituentID",
181
+ "composite_id_col": "CompositeID"
182
+ }
183
+
184
+ def __init__(self, config = None):
185
+ config_ = self.DEFAULT_CONFIG
186
+ if config is not None:
187
+ config_.update(config)
188
+ super().__init__(config_)
189
+
190
+ def get_etf_weight_list(self, ids, dated):
191
+ composite_id_col = self.config.get('composite_id_col')
192
+ data = self._get_concat_data(dated, reset_index=False)
193
+ data = data[data[composite_id_col].isin(ids)]
194
+ comp_ids = list(data.CompositeID.unique())
195
+ return {comp_id: self._get_weights(data[data[composite_id_col]==comp_id]) for comp_id in comp_ids}
196
+
197
+ def _get_weights(self, df):
198
+ weight_col = self.config.get('weight_col')
199
+ id_col = self.config.get('id_col')
200
+ return df.set_index(id_col)[weight_col]
201
+
202
+
203
+ class SecurityReturnDAO(BaseDAO):
204
+ DEFAULT_CONFIG = {
205
+ "meta_file": None,
206
+ "data_types": ["att","comp_att"],
207
+ "price_col": "Price"
208
+ }
209
+
210
+ def __init__(self, config = None):
211
+ config_ = self.DEFAULT_CONFIG
212
+ if config is not None:
213
+ config_.update(config)
214
+ super().__init__(config_)
215
+
216
+ def _get_price_at_t(self, t):
217
+ config = self.config
218
+ price_col = config.get('price_col')
219
+ data = self._get_concat_data(t, axis=0, reset_index=False)
220
+ return data.loc[:,price_col]
221
+
222
+ def get_forward_return_mat(self, t_list):
223
+ price_mat = pd.DataFrame({t: self._get_price_at_t(t) for t in t_list})
224
+ price_mat.ffill(axis=1, inplace=True)
225
+ return_mat = price_mat.pct_change(axis=1).shift(periods=-1,axis=1)
226
+ return return_mat
227
+
228
+ def get_forward_return(self, t):
229
+ next_t = self.get_next_t(t)
230
+ if next_t is not None:
231
+ return self.get_forward_return_mat([t,next_t]).iloc[:,0]
232
+ else:
233
+ return self.get_forward_return_mat([t]).iloc[:,0]
234
+
235
+ def set_t_list(self, t_list):
236
+ self.t_list = t_list
237
+
238
+ def get_next_t(self,t):
239
+ t_list = self.t_list
240
+ idx = t_list.index(t)
241
+ if idx >= len(t_list)-1:
242
+ return None
243
+ else:
244
+ return t_list[idx+1]
245
+
246
+
247
+ class FactorReturnDAO:
248
+ rmr = None
249
+ config = {
250
+ "meta_file": None,
251
+ "start_date": None,
252
+ "end_date": None,
253
+ "data_type": ["ret"],
254
+ "column": "Return"
255
+ }
256
+
257
+ def __init__(self, rmr = None, config = None):
258
+ if config is not None:
259
+ self.config.update(config)
260
+ if rmr is not None:
261
+ self.rmr = rmr
262
+ else:
263
+ self.rmr = RiskModelReader(self.config.get('meta_file'))
264
+
265
+ def set_start_date(self, dated):
266
+ self.config['start_date'] = dated
267
+
268
+ def set_end_date(self, dated):
269
+ self.config['end_date'] = dated
270
+
271
+ def _get_dates(self, start_date=None, end_date=None):
272
+ rmr = self.rmr
273
+ if start_date is None:
274
+ start_date = self.config.get("start_date")
275
+ if end_date is None:
276
+ end_date = self.config.get("end_date")
277
+ dates = rmr.model_dates
278
+ dates = [dated for dated in dates if (dated<=end_date) & (dated>=start_date)]
279
+ return dates
280
+
281
+ def _get_column_dated(self, dated):
282
+ rmr = self.rmr
283
+ config = self.config
284
+ data_dict = rmr.get_risk_model_data(dated, config.get("data_type"))
285
+ data = pd.concat(list(data_dict.values()), axis=0)
286
+ return data.loc[:,config.get("column")]
287
+
288
+ def get_forward_return(self, dates=None):
289
+ if dates is None:
290
+ dates = self._get_dates()
291
+ ts_mat = pd.DataFrame({dated: self._get_column_dated(dated)/100 for dated in dates})
292
+ ts_mat = ts_mat.shift(-1, axis=1)
293
+ return ts_mat
@@ -0,0 +1,273 @@
1
+ from .TSCollector import TSCollector
2
+ import logging
3
+ from os.path import join
4
+ from functools import reduce
5
+ import pandas as pd
6
+ import numpy as np
7
+ from scipy.sparse import csr_matrix, hstack, vstack, diags
8
+ from .DAO import SecurityDAO, ETFDAO
9
+
10
+ logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
11
+
12
+
13
+ def expand_df(df, index=None, columns=None, fillna=0):
14
+ """
15
+ Expand matrix dimensions.
16
+
17
+ This function expand matrix index and columns.
18
+
19
+ Parameters:
20
+ df (DataFrame): The matrix to be expanded.
21
+
22
+ Returns:
23
+ DataFrame: The expanded matrix.
24
+ """
25
+ if index is None:
26
+ index = df.index
27
+ if columns is None:
28
+ columns = df.columns
29
+ extra_columns = list(set(columns) - set(df.columns))
30
+ extra_index = list(set(index) - set(df.index))
31
+ return pd.concat([df, pd.DataFrame(index=extra_index, columns=extra_columns)], axis=0).fillna(fillna)
32
+
33
+
34
+ def expand_basket_weight(basket_weight):
35
+ """
36
+ Expand basket holdings to bottom level.
37
+
38
+ This function expand baskets holdings to the bottom level that only holds equity securities.
39
+
40
+ Parameters:
41
+ basket_weight (DataFrame): The basket holdings matrix with holdings on the rows, basket names on the columns.
42
+
43
+ Returns:
44
+ DataFrame: The expanded holdings matrix.
45
+ """
46
+ basket_weight.fillna(0, inplace=True)
47
+ basket_ids = list(basket_weight.columns)
48
+ non_basket_ids = list(set(basket_weight.index) - set(basket_ids))
49
+ non_basket_ids.sort()
50
+ basket_weight = expand_df(basket_weight, index=basket_ids)
51
+ logging.debug(
52
+ '{} baskets and {} non-basket equities.'.format(len(basket_ids), len(non_basket_ids)))
53
+
54
+ B = basket_weight.loc[basket_ids, :]
55
+ B.fillna(0, inplace=True)
56
+ if B.empty:
57
+ logging.debug('No basket cross ownership.')
58
+ return basket_weight.loc[non_basket_ids, :]
59
+
60
+ e_B = np.linalg.eig(B)
61
+
62
+ if any(np.abs(e_B[0]) >= 1):
63
+ logging.error(
64
+ 'Absolute value of eigenvalue greater than 1 of holding matrix. ')
65
+ raise ValueError(
66
+ 'Absolute value of eigenvalue greater than 1 of holding matrix. ')
67
+ elif all(e_B[0] == 0):
68
+ # No cross ownership
69
+ A = basket_weight.loc[non_basket_ids, :]
70
+ I = np.eye(B.shape[0])
71
+ return pd.DataFrame(np.dot(A, np.linalg.inv(I - B)),
72
+ index=non_basket_ids,
73
+ columns=basket_ids)
74
+ else:
75
+ # Real part of \sum_{i=1}^inf B^i
76
+ B_sum = np.real(np.round(
77
+ np.dot(np.dot(e_B[1], np.diag(1/(1-e_B[0]))), np.linalg.inv(e_B[1])), 15))
78
+ B_sum = pd.DataFrame(B_sum, index=B.index, columns=B.index)
79
+ return pd.DataFrame(np.dot(basket_weight.loc[non_basket_ids], B_sum),
80
+ index=non_basket_ids,
81
+ columns=basket_ids)
82
+
83
+
84
+ class PortfolioOne:
85
+ DEFAULT_CONFIG = {
86
+ "root_portfolio": "Main",
87
+ "basket_to_keep": ["ETF"]
88
+ }
89
+ portfolio_weight_list = None
90
+ etf_weight_list = None
91
+
92
+ def __init__(self, data, security_dao, etf_dao, config=None):
93
+ config_ = self.DEFAULT_CONFIG
94
+ if config is not None:
95
+ config_.update(config)
96
+ self.config = config_
97
+ # SecurityDAO(self.config.get('security_dao_config'))
98
+ self.security_dao = security_dao
99
+ self.etf_dao = etf_dao # ETFDAO(self.config.get('etf_dao_config'))
100
+ self.data = self.security_dao.map(data)
101
+ self._init_weight()
102
+
103
+ def _get_weight_one(self, df):
104
+ """
105
+ Get a weight series for one portfolio.
106
+ """
107
+ config = self.security_dao.config
108
+ id_col, weight_col = config.get('id_col'), config.get('weight_col')
109
+ return df.set_index(id_col)[weight_col]
110
+
111
+ def _get_weight_list(self):
112
+ """
113
+ Get the weight dict for multiple portfolios.
114
+ """
115
+ data = self.data
116
+ config = self.security_dao.config
117
+ id_col, portfolio_col = config.get(
118
+ 'id_col'), config.get('portfolio_col')
119
+ portfolios = list(data[portfolio_col].unique())
120
+ return {p: self._get_weight_one(data[data[portfolio_col] == p]) for p in portfolios}
121
+
122
+ def get_portfolio_weight_list(self):
123
+ if self.portfolio_weight_list is None:
124
+ self.portfolio_weight_list = self._get_weight_list()
125
+ return self.portfolio_weight_list
126
+
127
+ def get_etf_weight_list(self):
128
+ if self.etf_weight_list is None:
129
+ config = self.security_dao.config
130
+ time_col, id_col = config.get("time_col"), config.get("id_col")
131
+ data = self.data
132
+ dated = data[time_col].iloc[0]
133
+ ids = list(data[id_col].unique())
134
+ self.etf_weight_list = self.etf_dao.get_etf_weight_list(
135
+ ids=ids, dated=dated)
136
+ return self.etf_weight_list
137
+
138
+ def get_weight_list(self):
139
+ weight_list = self.get_portfolio_weight_list()
140
+ weight_list.update(self.get_etf_weight_list())
141
+ return weight_list
142
+
143
+ def get_weight_mat(self):
144
+ weight_list = self.get_weight_list()
145
+ return pd.DataFrame(weight_list).fillna(0)
146
+
147
+ def get_root_portfolio_weight(self):
148
+ root = self.config.get('root_portfolio')
149
+ return self.get_portfolio_weight_list().get(root)
150
+
151
+ def get_user_basket_ids(self):
152
+ """_summary_
153
+ Get user basket ids excluding root portfolio
154
+
155
+ Returns:
156
+ list: user basket ids
157
+ """
158
+ root = self.config.get('root_portfolio')
159
+ user_basket_ids = list(self.get_portfolio_weight_list().keys())
160
+ return list(set(user_basket_ids) - {root})
161
+
162
+ def get_etf_ids(self):
163
+ return list(self.get_etf_weight_list().keys())
164
+
165
+ def _get_basket_to_keep(self):
166
+ basket_to_keep = self.config.get('basket_to_keep')
167
+ user_basket_ids = self.get_user_basket_ids()
168
+ etf_ids = self.get_etf_ids()
169
+ all_basket_ids = user_basket_ids + etf_ids
170
+ basket_ids = [id for id in basket_to_keep if id in all_basket_ids]
171
+ if "ETF" in basket_to_keep:
172
+ basket_ids = basket_ids + etf_ids
173
+ if "BASKET" in basket_to_keep:
174
+ basket_ids = basket_ids + user_basket_ids
175
+ if "ALL" in basket_to_keep:
176
+ basket_ids = basket_ids + all_basket_ids
177
+ basket_ids = list(set(basket_ids))
178
+ logging.debug('Basket to keep: {}'.format(', '.join(basket_ids)))
179
+ return basket_ids
180
+
181
+ def set_basket_to_keep(self, basket_to_keep):
182
+ self.config['basket_to_keep'] = basket_to_keep
183
+ self._init_weight()
184
+
185
+ def _init_weight(self):
186
+ self._init_h()
187
+ self._init_H()
188
+
189
+ def _init_h(self):
190
+ """
191
+ Construct final holding matrix.
192
+ """
193
+ basket_to_keep = self._get_basket_to_keep()
194
+ all_ids = self.get_user_basket_ids() + self.get_etf_ids() + \
195
+ [self.config.get('root_portfolio')
196
+ ] # all basket ids including portfolio
197
+ basket_to_unfold = list(set(all_ids) - set(basket_to_keep))
198
+ root = self.config.get('root_portfolio')
199
+
200
+ # h: the final holdings in output
201
+ weight_mat = self.get_weight_mat()
202
+ weight_mat = weight_mat.loc[:, basket_to_unfold]
203
+ h = expand_basket_weight(weight_mat).loc[:, root]
204
+ h = h[h != 0]
205
+
206
+ self.index_h = list(h.index)
207
+ self.h = csr_matrix(h).T
208
+
209
+ def _init_H(self):
210
+ """
211
+ Construct the conversion matrix which is used to calculate composite attributes.
212
+ """
213
+ index_h = self.index_h
214
+ basket_to_keep = self._get_basket_to_keep()
215
+ equity_ids = list(set(index_h) - set(basket_to_keep))
216
+
217
+ weight_mat_underlying = expand_basket_weight(self.get_weight_mat())
218
+ basket_part = weight_mat_underlying.loc[:, basket_to_keep]
219
+ equity_part = pd.DataFrame(
220
+ np.diag(np.ones(len(equity_ids))), index=equity_ids, columns=equity_ids)
221
+ H = pd.concat([basket_part, equity_part], axis=1).fillna(
222
+ 0) # index are left-aligned
223
+ H = H.loc[:, index_h]
224
+
225
+ self.index_H = list(H.index)
226
+ self.H = csr_matrix(H)
227
+
228
+ def set_basket_to_keep(self, basket_to_keep):
229
+ self.config['basket_to_keep'] = basket_to_keep
230
+ self._init_weight()
231
+
232
+
233
+ class PortfolioTS(TSCollector):
234
+ def __init__(self, data=None, config=None):
235
+ default_config = {
236
+ "path": "portfolio_data",
237
+ "meta_file": None,
238
+ "root_portfolio": "Main",
239
+ "basket_to_keep": ["ALL_ETF"],
240
+ "security_dao_config": {},
241
+ "etf_dao_config": {}
242
+ }
243
+ if config is not None:
244
+ default_config.update(config)
245
+ super().__init__(default_config)
246
+ if data is not None:
247
+ self._setup_dao()
248
+ time_col = self.config.get("security_dao_config").get("time_col")
249
+ t_list = list(data[time_col].unique())
250
+ t_list.sort()
251
+
252
+ def _wrapper(t):
253
+ logging.info(f'Initializing PortfolioOne for {t}')
254
+ return self._init_p1(data[data[time_col] == t])
255
+ self._cache = {t: _wrapper(t) for t in t_list}
256
+
257
+ def _init_p1(self, data):
258
+ return PortfolioOne(data, self.security_dao, self.etf_dao, self.config)
259
+
260
+ def _setup_dao(self):
261
+ self._use_one_reader()
262
+ self.security_dao = SecurityDAO(self.config.get('security_dao_config'))
263
+ self.etf_dao = ETFDAO(self.config.get('etf_dao_config'))
264
+
265
+ def _use_one_reader(self):
266
+ config = self.config
267
+ meta_file = config.get('meta_file')
268
+ if meta_file is not None:
269
+ config['security_dao_config']['meta_file'] = meta_file
270
+ logging.debug(f'Use {meta_file} for security_dao')
271
+ config['etf_dao_config']['meta_file'] = meta_file
272
+ logging.debug(f'Use {meta_file} for etf_dao')
273
+ self.config = config
attrix/TSCollector.py ADDED
@@ -0,0 +1,108 @@
1
+ import pickle
2
+ import re
3
+ import os
4
+ import datetime
5
+
6
+ """
7
+ The class is able to achieve:
8
+ 1. Specify path and file name convention
9
+ 2. Create new objects in the memory
10
+ 3. Save the object to dated file
11
+ 4. Load the dated file to object dict
12
+ 5. Apply an operation to each object in the object dict
13
+ """
14
+
15
+ class TSCollector:
16
+ """
17
+ Time-series object collector.
18
+
19
+ Load objects from pickle data or save objects to pickle data.
20
+ """
21
+ def __init__(self, config=None):
22
+ default_config = {
23
+ "path": ".",
24
+ "file_format": "%Y-%m-%d",
25
+ "time_format": "%Y-%m-%d",
26
+ "pattern": "^[0-9-]{10}$"
27
+ }
28
+ if config is not None:
29
+ default_config.update(config)
30
+ self.config = default_config
31
+ self._cache = {}
32
+
33
+ @staticmethod
34
+ def _convert(x, format1, format2):
35
+ return datetime.datetime.strptime(x,format1).strftime(format2)
36
+
37
+ def _file_to_time(self, x):
38
+ file_format = self.config.get('file_format')
39
+ time_format = self.config.get('time_format')
40
+ return self._convert(x, file_format, time_format)
41
+
42
+ def _time_to_file(self, x):
43
+ file_format = self.config.get('file_format')
44
+ time_format = self.config.get('time_format')
45
+ return self._convert(x, time_format, file_format)
46
+
47
+ @property
48
+ def f_list(self):
49
+ """
50
+ List of existing files.
51
+ """
52
+ path, pattern = self.config.get('path'), self.config.get('pattern')
53
+ if os.path.exists(path):
54
+ regex = re.compile(pattern)
55
+ l = list(filter(regex.match, os.listdir(path)))
56
+ l.sort()
57
+ else:
58
+ l = []
59
+ return l
60
+
61
+ @property
62
+ def t_list(self):
63
+ """
64
+ Time list that corresponds to each existing file.
65
+ """
66
+ l = [self._file_to_time(f) for f in self.f_list]
67
+ l.sort()
68
+ return l
69
+
70
+ def load_one(self, t):
71
+ """
72
+ Load from 1. cache; 2. pickle file.
73
+ """
74
+ if t not in self._cache.keys():
75
+ f = self._time_to_file(t)
76
+ path = self.config.get('path')
77
+ with open(os.path.join(path,f), 'rb') as file:
78
+ self._cache[t] = pickle.load(file)
79
+ return self._cache.get(t)
80
+
81
+ def save_one(self, t):
82
+ """
83
+ Save the cached data to pickle file.
84
+ """
85
+ if t in self._cache.keys():
86
+ f = self._time_to_file(t)
87
+ path = self.config.get('path')
88
+ if not os.path.exists(path):
89
+ os.makedirs(path)
90
+ with open(os.path.join(path,f), 'wb') as file:
91
+ pickle.dump(self._cache.get(t), file)
92
+
93
+ def load(self, t_list=None):
94
+ if t_list is None:
95
+ t_list = self.t_list
96
+ return {t: self.load_one(t) for t in t_list}
97
+
98
+ def save(self, replace=False):
99
+ """
100
+ Save the cached dict of objects to a series of files.
101
+
102
+ Parameters:
103
+ data_dict (dict): Object dict tagged with time.
104
+ replace (bool): Replace existing file.
105
+ """
106
+ for t, data in self._cache.items():
107
+ if replace or (t not in self.t_list):
108
+ self.save_one(t)
attrix/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .AttributionTools import AttributionTS
2
+ from .DAO import SecurityDAO, ETFDAO, SecurityReturnDAO, RiskModelReader
3
+ from .PortfolioTools import PortfolioTS
4
+
5
+ __all__ = ['AttributionTS', 'SecurityDAO', 'ETFDAO', 'SecurityReturnDAO', 'RiskModelReader', 'PortfolioTS']
attrix/configs.py ADDED
@@ -0,0 +1,45 @@
1
+ SECURITYDAO_CONFIG = {
2
+ 'meta_file': None,
3
+ 'mapping_cols': ['Ticker', 'Country'],
4
+ 'time_col': 'Date',
5
+ 'id_col': 'SecurityID',
6
+ 'portfolio_col': 'Portfolio',
7
+ 'weight_col': 'Weight',
8
+ 'data_types': ['idm','comp_idm']
9
+ }
10
+
11
+ ETFDAO_CONFIG = {
12
+ "meta_file": None,
13
+ "data_types": ["comp_weight"],
14
+ "weight_col": "ConstituentWeight",
15
+ "id_col": "ConstituentID",
16
+ "composite_id_col": "CompositeID"
17
+ }
18
+
19
+ PORTFOLIOONE_CONFIG = {
20
+ "root_portfolio": "Main",
21
+ "basket_to_keep": ["ETF"],
22
+ }
23
+
24
+ PORTFOLIOTS_CONFIG = {
25
+ "path": "portfolio_data",
26
+ "root_portfolio": "Main",
27
+ "basket_to_keep": ["ETF"],
28
+ "meta_file": None,
29
+ "security_dao_config": SECURITYDAO_CONFIG,
30
+ "etf_dao_config": ETFDAO_CONFIG
31
+ }
32
+
33
+ ATTRIBUTIONTS_CONFIG = {
34
+ "path": "attribution_data",
35
+ "additional_t": None,
36
+ "meta_file": None,
37
+ "rmd_reader_config": {
38
+ "meta_file": None
39
+ },
40
+ "return_dao_config": {
41
+ "meta_file": None,
42
+ "data_types": ["att","comp_att"],
43
+ "price_col": "Price"
44
+ }
45
+ }
@@ -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
@@ -0,0 +1,10 @@
1
+ attrix/AttributionTools.py,sha256=-TooPAEiMTVfxPQrM235U0ipojLswSsjIjPtPJwUURI,21158
2
+ attrix/DAO.py,sha256=nXP6o1MP38ixWW3byusqi-ruY3-9PM5c0vMWA_Sagbo,11650
3
+ attrix/PortfolioTools.py,sha256=m1GZMR5NtjodXK2nkyDqicvwELynrb0dCXUAqFvgfb8,9893
4
+ attrix/TSCollector.py,sha256=3qO9wdOQ9k68YDmejzHCU-DIoyIY__P5JKSTY6c9vDk,3188
5
+ attrix/__init__.py,sha256=i2oIBYwwYDhRd5oTGi_yqj6aGfNgZJagv78CT1Mbbe0,265
6
+ attrix/configs.py,sha256=EHHV2eiNLMywdX5CQ9HicIQ8-BXWj4vhxBeUMMa07zM,1040
7
+ attrix-0.1.1.dist-info/METADATA,sha256=wBJs6UT9RBWPvcAe1YDrEp0AcQGv3jYxwY1WsnnQ4WI,550
8
+ attrix-0.1.1.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91
9
+ attrix-0.1.1.dist-info/top_level.txt,sha256=GQSwuOwvOWM8B7BOoyZQ-6b33F2VksEEVEVIC_XeoYQ,7
10
+ attrix-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (70.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ attrix