-
Notifications
You must be signed in to change notification settings - Fork 228
/
Copy path01_PortfolioFunction.R
359 lines (300 loc) · 10.2 KB
/
01_PortfolioFunction.R
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
#### FUNCTION FOR TURNING SIGNAL CSV TO K PORTFOLIOS
# this is mostly one big function. It's so big, it needs its own file otherwise
# I get lost.
import_signal = function(signalname,filterstr,Sign){
# this is useful to have outside of signalname_to_longports in case
# you just want to look at the signals
### LOAD SIGNAL DATA AND APPLY FILTERS
if (file.exists(paste0(pathPredictors,signalname,'.csv'))){
csvname = paste0(pathPredictors,signalname,'.csv')
} else if (file.exists(paste0(pathCRSPPredictors,signalname,'.csv'))){
csvname = paste0(pathCRSPPredictors,signalname,'.csv')
} else if (file.exists(paste0(pathPlacebos,signalname,'.csv'))){
csvname = paste0(pathPlacebos,signalname,'.csv')
} else if (file.exists(paste0(pathtemp,signalname,'.csv'))){
csvname = paste0(pathtemp,signalname,'.csv')
} else {
print('error: signalname csv not found')
stop('error: signalname csv not found')
}
## load signal data
# previously had problems with fread and memory leaks, but seems like upgrading
# R might have fixed it.
signal = fread(csvname) %>%
as_tibble() %>%
rename(signal = !!signalname) %>%
filter(!is.na(signal))
## add crsp prc exchcd me for implementation adjustments
# sometimes get the following error
# Error: cons memory exhausted (limit reached?)
# Error: no more error handlers available (recursive errors?); invoking 'abort' restart
gc()
signal = left_join(
signal
, crspinfo
, by = c('permno','yyyymm')
)
## apply filters and sign
# note the signal dataset is lagged further down, so
# filtering here does not look ahead
if (!is.na(filterstr)){
evalme = paste0('signal = signal %>% filter('
, filterstr
, ')')
eval(parse(text=evalme))
}
## sign
signal$signal = signal$signal*Sign
return(signal)
} # end sub function
# here's the big function
# the inner functions help with memory mgmt (no pass by value)
# while staying organized and allowing for extensions in the future
signalname_to_ports = function(
signalname
, Cat.Form = NA
, q_cut = NA
, sweight = NA
, Sign = NA
, longportname = NA
, shortportname = NA
, startmonth = NA
, portperiod = NA
, q_filt = NA
, filterstr = NA
, passive_gain = F
) {
# SETTINGS AND CHECKS ====
## settings
# we use NA as "function default" and then transform to real defaults here
# to keep the all defaults in this important function.
# Otherwise you need defaults in the loop over strategies function
if (is.na(sweight)) {sweight = 'EW'}
if (is.na(Sign)) {Sign = 1}
if (is.na(longportname[1])) {longportname = 'max'}
if (is.na(shortportname[1])) {shortportname = 'min'}
if (is.na(startmonth)) {startmonth = 6}
if (is.na(portperiod)) {portperiod = 1}
if (is.na(q_cut)) {q_cut=0.2}
if (is.na(Cat.Form)) {Cat.Form = 'continuous'}
## checks
if (!exists('crspret')){
print('error: crspret not in workspace. Please load Intermediate/crspmret.fst or crspdret.fst as crspret (see 11_ProcessCRSP.R)')
stop()
}
if (!exists('crspinfo')){
print('error: crspinfo not in workspace. Please load Intermediate/crspminfo.fst as crspinfo (see 11_ProcessCRSP.R)')
stop()
}
if (passive_gain){
if (!'passgain' %in% colnames(crspret)){
print('error: passive_gain = T but crspret does not have a passgain column')
print('please check the correct crspret is loaded')
stop()
}
}
if (sweight == 'VW'){
if (!'melag' %in% colnames(crspret)){
print('error: sweight == VW but crspret does not have melag column')
print('please check crsp processing')
stop()
}
}
# function for sorting portfolios if signal is not already a port assignment
single_sort = function(q_filt,q_cut){
## create breakpoints
# subset to firms used for breakpoints, right now only exclude based on q_filt
tempbreak = signal
if (!is.na(q_filt)) {
if (q_filt=='NYSE'){
tempbreak = tempbreak %>% filter(exchcd == 1)
}
} # if q_filt
## create breakpoints
# turn q_cut into a vector carefully
if (q_cut <= 1/3){
plist = c(seq(q_cut,1-2*q_cut,q_cut), 1-q_cut)
} else {
plist = unique(c(q_cut,1-q_cut))
}
# find breakpoints
temp = list()
for (pi in seq(1,length(plist))){
temp[[pi]] = tempbreak %>% group_by(yyyymm) %>%
summarize(
breakpoint = quantile(signal, probs = plist[pi])
) %>%
mutate(breaki = pi)
} # for pi
breaklist = do.call(rbind.data.frame, temp) %>%
pivot_wider(
names_from=breaki,
values_from=breakpoint,
names_prefix = 'break')
# remove degenerate breakpoints (at extremes only)
if (length(plist) > 1){
idgood = breaklist[,length(plist)+1] - breaklist[,2] > 0
breaklist = breaklist[idgood,]
}
## assign to portfolios
# the extreme portfolios get the 'benefit of the doubt' in the inequalities
# initialize
signal = signal %>%
left_join(breaklist, by = 'yyyymm') %>%
mutate(port = NA_integer_)
# assign lowest signal
signal = signal %>%
mutate(port = if_else(signal <= break1, as.integer(1), port) )
# assign middle
if (length(plist) >= 2) {
for (porti in seq(2,length(plist))){
breakstr = paste0('break',porti)
id = is.na(signal$port) & (signal$signal < signal[breakstr])
signal$port[id] = porti
} # for porti
}
# assign highest signal
breakstr = paste0('break',length(plist))
id = is.na(signal$port) & (signal$signal >= signal[breakstr])
signal$port[id] = length(plist) + as.integer(1)
signal = signal %>% select(-starts_with('break'))
return(signal)
} ## end sub function
# MAIN WORK ====
# Import signal ====
if (feed.verbose) {print('loading signal data and applying filters')}
signal = import_signal(signalname,filterstr,Sign)
# Assign stocks to portfolios ====
# (if necessary)
if (feed.verbose) {print('assigning stocks to portfolios')}
if (Cat.Form == 'continuous'){
signal = single_sort(q_filt,q_cut)
} else if (Cat.Form == 'discrete') {
# for custom categorical portfolios (e.g. Gov Index, PS, MS)
# by default we go long "largest" cat and short "smallest" cat
support = signal$signal %>% unique %>% sort
signal$port = NA_integer_
for (i in 1:length(support)) {
signal$port[signal$signal==support[i]] = i
}
} else if (Cat.Form == 'custom'){
# here we just say port = signal (port assigned in previous code)
# eventually useful for ff3 style, maybe
signal = signal %>% mutate(port = signal)
} # if Cat.Form
# == Portfolio Returns (stock weighting happens here) ====
# make all na except "rebalancing months", which is actually signal updating months
# and then fill na with stale data
# find months that portfolio assignements are updated
rebmonths = (
startmonth
+ seq(0,12)*portperiod
) %% 12
rebmonths[rebmonths == 0] = 12
rebmonths = sort(unique(rebmonths))
signal = signal %>%
mutate(
port = if_else(
(yyyymm %% 100) %in% rebmonths
, port
, NA_integer_
)
) %>%
arrange(permno,yyyymm) %>%
group_by(permno) %>%
fill(port) %>%
filter(!is.na(port))
### CREATE PORTFOLIOS
# this can be slow with daily data, about 20 sec per signal
### ASSIGN TO PORTFOLIOS AND SIGN
# lag signals: note port could by called portlag here
signallag = setDT(signal)[
, .(permno, yyyymm, signal, port)
][
, yyyymm := yyyymm + 1
][
, yyyymm := if_else(yyyymm %% 100 == 13, yyyymm+100-12,yyyymm)
]
setnames(signallag, old = 'signal', new = 'signallag')
if (feed.verbose) {print('joining lagged signals onto crsp returns')}
gc()
# scoping implies crspret in the big loop is not affected
crspret = crspret %>%
left_join(
signallag %>% select(permno,yyyymm,signallag, port)
, by = c('permno','yyyymm')
)
## stock weights
# equal vs value-weighting
if (sweight == 'VW'){
crspret$weight = crspret$melag
} else {
crspret$weight = 1
}
# adjustments for passive gains
# (this is only used for the daily ports right now)
if (passive_gain){
crspret$weight = crspret$weight*crspret$passgain
}
if (feed.verbose) {print('calculating portfolio returns')}
port = crspret[
!is.na(port) & !is.na(ret) & !is.na(weight)
][
, .(
ret = weighted.mean(ret, weight)
, signallag = weighted.mean(signallag, weight)
, Nlong = .N
)
, by = list(port,date)
]
port = port %>%
mutate(Nshort = 0) %>%
select(port,date,ret,signallag,Nlong,Nshort) %>%
ungroup()
if (feed.verbose){
print(paste0('end of signalname_to_ports memory used = '))
print(mem_used())
}
gc()
if (feed.verbose){print(gc(T))}
# Add long-short portfolio ====
# allows for ff3 style with something like
# longportname = c('SH','BH'), shortportname = c('SL','BL')
# longportname and shortportname come from the function call to signalname_to_ports
if (longportname[1] == 'max'){
longportname = max(port$port)
}
if (shortportname[1] == 'min'){
shortportname = min(port$port)
}
# equal-weight long portfolios
long = port %>%
filter(port %in% longportname) %>%
group_by(date) %>%
summarize(
retL = mean(ret), Nlong = sum(Nlong)
)
short = port %>%
filter(port %in% shortportname) %>%
group_by(date) %>%
summarize(
retS = - mean(ret), Nshort = sum(Nlong)
)
longshort = inner_join(long, short, by='date') %>%
mutate(
ret = retL + retS
, port = 'LS'
, signallag = NA_real_
) %>%
select(port,date,ret,signallag,Nlong,Nshort)
# convert port to 2-character string for ease of use
port = port %>% mutate(port = sprintf('%02d',port))
# bind long with longshort
port = rbind(port,longshort)
# clean up
port$signalname = signalname
port = port %>%
select(signalname,everything()) %>%
arrange(signalname,port,date)
return(port)
} ### end function