-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHXLFactors.py
389 lines (300 loc) · 13.6 KB
/
HXLFactors.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
"""
@author: Vitor Eller - @VFermat
"""
import pandas as pd
import numpy as np
from pandas.tseries.offsets import MonthEnd
class HXLFactors(object):
high_ROE = ['BHIAHR', 'BMIAHR', 'BLIAHR', 'SHIAHR', 'SMIAHR', 'SLIAHR']
low_ROE = ['BHIALR', 'BMIALR', 'BLIALR', 'SHIALR', 'SMIALR', 'SLIALR']
high_IA = ['BHIAHR', 'BHIAMR', 'BHIALR', 'SHIAHR', 'SHIAMR', 'SHIALR']
low_IA = ['BLIAHR', 'BLIAMR', 'BLIALR', 'SLIAHR', 'SLIAMR', 'SLIALR']
def calculate_factors(self, prices, dividends, assets, ROE, marketcap):
# Lining up dates to end of month
prices.columns = prices.columns + MonthEnd(0)
dividends.columns = dividends.columns + MonthEnd(0)
assets.columns = assets.columns + MonthEnd(0)
ROE.columns = ROE.columns + MonthEnd(0)
marketcap.columns = marketcap.columns + MonthEnd(0)
# Padronizing columns
dividends, assets, ROE = self._padronize_columns(prices.columns,
dividends,
assets,
ROE)
# Basic information
self.securities = {
'assets': assets,
'ROE': ROE,
'price': prices,
'marketcap': marketcap,
'dividends': dividends
}
# Gathering info
self.securities = self._get_IA_info(self.securities)
self.securities = self._get_return(self.securities)
self.securities = self._get_benchmarks(self.securities)
self.securities['sizecls'] = self._get_sizecls(self.securities)
self.securities['iacls'] = self._get_iacls(self.securities)
self.securities['ROEcls'] = self._get_ROEcls(self.securities)
self.securities['cls'] = self.securities['sizecls'] + self.securities['iacls'] + self.securities['ROEcls']
# Calculating factors
self.HXLInvestment = self.get_investment()
self.HXLProfit = self.get_profit()
def get_profit(self):
lreturns = self.securities['lreturn']
stocks_cls = self.securities['cls']
marketcap = self.securities['marketcap']
HXLProfit = pd.Series(index=stocks_cls.columns)
for c in stocks_cls.columns:
phigh_returns = []
plow_returns = []
for scls in self.high_ROE:
high_investment = stocks_cls[stocks_cls[c] == scls].index
high_returns = lreturns.loc[high_investment, c]
phigh_returns.append(np.sum(high_returns*marketcap.loc[high_investment, c])/np.sum(marketcap.loc[high_investment, c]))
for scls in self.low_ROE:
low_investment = stocks_cls[stocks_cls[c] == scls].index
low_returns = lreturns.loc[low_investment, c]
plow_returns.append(np.sum(low_returns*marketcap.loc[low_investment, c])/np.sum(marketcap.loc[low_investment, c]))
factor = np.mean(phigh_returns) - np.mean(plow_returns)
HXLProfit.at[c] = factor
return HXLProfit
def get_investment(self):
lreturns = self.securities['lreturn']
stocks_cls = self.securities['cls']
marketcap = self.securities['marketcap']
HXLInvestment = pd.Series(index=stocks_cls.columns)
for c in stocks_cls.columns:
phigh_returns = []
plow_returns = []
for scls in self.high_IA:
high_investment = stocks_cls[stocks_cls[c] == scls].index
high_returns = lreturns.loc[high_investment, c]
phigh_returns.append(np.sum(high_returns*marketcap.loc[high_investment, c])/np.sum(marketcap.loc[high_investment, c]))
for scls in self.low_IA:
low_investment = stocks_cls[stocks_cls[c] == scls].index
low_returns = lreturns.loc[low_investment, c]
plow_returns.append(np.sum(low_returns*marketcap.loc[low_investment, c])/np.sum(marketcap.loc[low_investment, c]))
factor = np.mean(phigh_returns) - np.mean(plow_returns)
HXLInvestment.at[c] = factor
return HXLInvestment
@staticmethod
def _get_ROEcls(securities):
"""
Divides the securities in High, Medium and Low, based on the percentiles of the
ROE (30% and 70%).
Parameters
----------
securities : Dict like
A dict containing the information on stocks.
Return
----------
ROEcls : DataFrame
A DataFrame containing the stocks classification.
"""
ROEcls = pd.DataFrame(index=securities['ROE'].index,
columns=securities['ROE'].columns)
ROE30 = securities['ROE30']
ROE70 = securities['ROE70']
for i in securities['ROE'].index:
indicator = np.nan
for c in securities['ROE'].columns:
benchmark30 = ROE30[c]
benchmark70 = ROE70[c]
stock_ROE = securities['ROE'].loc[i, c]
if stock_ROE == np.nan or stock_ROE == 0:
indicator = ROEcls.loc[i][-1]
elif stock_ROE <= benchmark30:
indicator = 'LR'
elif stock_ROE <= benchmark70:
indicator = 'MR'
else:
indicator = 'HR'
ROEcls.at[i, c] = indicator
return ROEcls
@staticmethod
def _get_iacls(securities):
"""
Divides the securities in High, Medium and Low, based on the percentiles of the
Investment over Assets ratio (30% and 70%).
Parameters
----------
securities : Dict like
A dict containing the information on stocks.
Return
----------
iacls : DataFrame
A DataFrame containing the stocks classification.
"""
iacls = pd.DataFrame(index=securities['I/A'].index,
columns=securities['I/A'].columns)
ia30 = securities['IA30']
ia70 = securities['IA70']
for i in securities['I/A'].index:
indicator = np.nan
for c in securities['I/A'].columns:
benchmark30 = ia30[c]
benchmark70 = ia70[c]
stock_ia = securities['I/A'].loc[i, c]
if c.month == 6:
if stock_ia == np.nan or stock_ia == 0:
indicator = np.nan
elif stock_ia <= benchmark30:
indicator = 'LIA'
elif stock_ia <= benchmark70:
indicator = 'MIA'
else:
indicator = 'HIA'
iacls.at[i, c] = indicator
return iacls
@staticmethod
def _get_sizecls(securities):
"""
Divides the securities in Big and Small, based on the median of the
marketcap.
Parameters
----------
securities : Dict like
A dict containing the information on stocks.
Return
----------
sizecls : DataFrame
A DataFrame containing the stocks classification.
"""
sizecls = pd.DataFrame(index=securities['marketcap'].index,
columns=securities['marketcap'].columns)
sizemedian = securities['mkmedian']
for i in sizecls.index:
indicator = np.nan
for c in sizecls.columns:
benchmark = sizemedian[c]
stock_size = securities['marketcap'].loc[i, c]
if c.month == 6:
if stock_size == np.nan or stock_size == 0:
indicator = np.nan
elif stock_size <= benchmark:
indicator = 'S'
else:
indicator = 'B'
sizecls.at[i, c] = indicator
return sizecls
@staticmethod
def _get_benchmarks(securities):
"""
Calculates the benchmarks that will be used to sort the securities.
Parameters
----------
securities : Dict like
A dict containing the information on stocks.
Return
----------
n_securities : Dict
Updated dict containing the benchmarks.
"""
iaratio = securities['I/A']
marketcap = securities['marketcap']
ROE = securities['ROE']
iapercentiles = iaratio.describe(percentiles=[0.3, 0.7]).loc[['30%', '70%']]
ia30 = iapercentiles.loc['30%']
ia70 = iapercentiles.loc['70%']
marketcapmedian = marketcap.describe().loc['50%']
ROEpercentiles = ROE.describe(percentiles=[0.3, 0.7]).loc[['30%', '70%']]
ROE30 = ROEpercentiles.loc['30%']
ROE70 = ROEpercentiles.loc['70%']
n_securities = securities.copy()
n_securities['IA30'] = ia30
n_securities['IA70'] = ia70
n_securities['mkmedian'] = marketcapmedian
n_securities['ROE30'] = ROE30
n_securities['ROE70'] = ROE70
return n_securities
@staticmethod
def _get_return(securities):
"""
Calculates the return for each security over time and related information.
Parameters
----------
securities : Dict like
A dictionary containing the information on stocks.
Return
----------
n_securities : Dict
Updated dict containing the return for each security over time.
"""
n_securities = securities.copy()
n_securities['lprice'] = n_securities['price'].shift(1, axis=1)
n_securities['pdifference'] = n_securities['price'] - n_securities['lprice']
n_securities['gain'] = n_securities['dividends'] + n_securities['pdifference']
n_securities['return'] = n_securities['gain']/n_securities['lprice']
# Creates a return field which is shifted one month back. Will be used
# when calculating the factors
n_securities['lreturn'] = n_securities['return'].shift(-1, axis=1)
return n_securities
@staticmethod
def _get_IA_info(securities):
"""
Calculates the Investment over Assets ratio and related information
Parameters
----------
securities : Dict like
A dict containing the information on stocks.
Return
----------
n_securities : Dict
Updated dict containing Investment over Assets ratio and related information.
"""
n_securities = securities.copy()
# Calculates 1-year-lagged-assets
n_securities['lassets'] = n_securities['assets'].shift(12, axis=1)
# Calculates Investment
n_securities['investment'] = n_securities['assets'] - n_securities['lassets']
# Calculates Investment over Assets ratio
n_securities['I/A'] = n_securities['investment']/n_securities['lassets']
return n_securities
@staticmethod
def _padronize_columns(pattern, dividends, assets, ROE):
"""
Padronizes information that is not released monthly. In that way, we do not
encounter problems while manipulating data.
Parameters
----------
pattern : Array like
Array containing the pattern for the columns
dividends : DataFrame like
Dataframe containing information on dividends
assets : DataFrame like
Dataframe containing information on assets
ROE : DataFrame like
Dataframe containing information on ROE
Return
----------
ndividends : Dataframe like
Updated Dataframe containing information on dividends
nassets : Dataframe like
Updated Dataframe containing information on assets
nROE : Dataframe like
Updated Dataframe containing information on ROE
"""
ndividends = pd.DataFrame(index=dividends.index)
nassets = pd.DataFrame(index=assets.index)
nROE = pd.DataFrame(index=ROE.index)
for date in pattern:
if date in dividends.columns:
ndividends[date] = dividends[date]
else:
ndividends[date] = 0
if date in assets.columns:
nassets[date] = assets[date]
nROE[date] = ROE[date]
else:
nassets[date] = 0
nROE[date] = 0
return ndividends, nassets, nROE
"""
TO DO:
IA cls is rebalancing every month. Need to change it so it rebalances only at the end of June.
Same thing is happening to Size cls.
Write the description of get_profit and get_investment functions.
Write the description of the calculate_factors function.
Write the description of the Class.
"""