-
Notifications
You must be signed in to change notification settings - Fork 1
/
No param.R
398 lines (297 loc) · 8.59 KB
/
No param.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
## Librerias
library(tidyverse)
library(lubridate)
library(janitor)
library(TTR)
library(plotly)
##Parametros
TD=20
p_val=0.3
etfs=c(
'MCHI US Equity', #china
'EWH US Equity', #hong kong
'EWY US Equity' #korea
)
etfs=c(
'SPY US Equity', #US general
'INDA US Equity',#India
'IEV US Equity',#Francia
'XLF US Equity',#Financial
'MCHI US Equity'#China
)### Selecciono etfs a usar
## Funciones
get_pair_ret=function(raw,etfs){
## Function to get addition ino from te price using technicals
etf1=raw%>%
filter(etf==etfs[1])%>%
dplyr::select(date,tri)%>%
rename(etf1=tri)
etf2=raw%>%
filter(etf==etfs[2])%>%
dplyr::select(date,tri)%>%
rename(etf2=tri)
pair=etf1%>%
inner_join(etf2,by='date')%>%
dplyr::select(date,etf1,etf2)%>%
mutate(pair=paste0(etfs[1],'_',etfs[2]))
pair_tecnical=pair%>%
mutate(r1 = c(NA,ROC(etf1,n=1,type = 'discrete')[-1]),
r2= c(NA,ROC(etf2,n=1,type = 'discrete')[-1]))%>%
filter(!is.na(r1))%>%
dplyr::select(pair,date,r1,r2)
return(pair_tecnical)
}
game=function(v1,v2, pv=0.3){
a=wilcox.test(v1,v2,alternative = "greater",paired = TRUE)
if (a$p.value<pv){
return(1)
}
a=wilcox.test(v2,v1,alternative = "greater",paired = TRUE)
if (a$p.value<pv){
return(3)
}
return(2)
}
game2=function(v1,v2, pv=0.3){
if(median(v1)>median(v2)){
return(1)
}else{
return(3)
}
return(2)
}
game3=function(v1,v2, pv=0.3){
if(mean(v1)>mean(v2)){
return(1)
}else{
return(3)
}
return(2)
}
get_strategy=function(df,dates,delta,game,pv=0.3){
res=data.frame()
for (d in dates){
res=df%>%
filter(date<=d)%>%
arrange(date)%>%
do(tail(.,delta))%>%### me coge los ultimo delta datos
summarise(g=game(r1,r2,pv),date=max(date))%>%
rbind(res)
}
return(res)
}
get_bt=function(raw,etfs,TD,p_val,game_fun){
game=game_fun
all_pairs=data.frame(combn(unique(etfs),2),stringsAsFactors = FALSE)
all_pairs=lapply(all_pairs, c) ### Estas dos lineas me crea todas la parejas de los etfs
all_tecs=lapply(all_pairs,get_pair_ret,raw=raw) #### traer dataframe con retornos por pareja
pair_ret=do.call(rbind,all_tecs) ##hago append en un solo dataframe
aux=pair_ret%>%
group_by(pair)%>%
summarise(d=min(date))%>%
ungroup()%>%
summarise(max(d))%>%
pull()### ver fecha desde cuando tengo info de todos
pair_ret=pair_ret%>%
filter(date>"2010-01-01")%>%
filter(date>=aux) ## filtro desde la fecha que quiero
meses=pair_ret%>%
mutate(m=week(date),y=year(date))%>%
group_by(m,y)%>%
summarise(date=max(date))%>%
ungroup()%>%
select(date)%>%
arrange(date)%>%
pull()%>%
unique()
meses=meses[-(1:3)]
strategy=pair_ret%>%
group_by(pair)%>%
do(get_strategy(.,meses,TD,game_fun,pv=p_val))%>%
ungroup() #### modficar
portfolio=strategy%>%
separate(pair,c('etf1','etf2'),'_')%>%
mutate(vote1=ifelse(g==1,2,ifelse(g==3,0,1)),
vote2=ifelse(g==3,2,ifelse(g==1,0,1)))%>%
group_by(etf1,date)%>%
summarise(votos=sum(vote1))%>%
ungroup()%>%
rename(etf=etf1)
portfolio_tidy=strategy%>%
separate(pair,c('etf1','etf2'),'_')%>%
mutate(vote1=ifelse(g==1,2,ifelse(g==3,0,1)),
vote2=ifelse(g==3,2,ifelse(g==1,0,1)))%>%
group_by(etf2,date)%>%
summarise(votos=sum(vote2))%>%
ungroup()%>%
rename(etf=etf2)%>%
rbind(portfolio)%>%
group_by(etf,date)%>%
summarise(votos=sum(votos))%>%
ungroup()%>%
group_by(date)%>%
mutate(w=votos/sum(votos))
portfolio_wide=portfolio_tidy%>%
select(date,etf,w)%>%
spread(key = etf,value=w,fill=0) ## Check
retornos_tidy_1m=raw%>%#el retorno del periodo siguiente
dplyr::select(date,etf,tri)%>%
filter(date%in%portfolio_tidy$date)%>%
group_by(etf)%>%
mutate(ret=c(ROC(tri,n=1,type = 'discrete')[-1],NA))%>%
ungroup()%>%
dplyr::select(date,etf,ret)
retorno_portafolio=portfolio_tidy%>%
inner_join(retornos_tidy_1m,by=c('etf','date'))%>%
mutate(ret=ifelse(is.na(ret),0,ret))%>%
group_by(date)%>%
summarise(ret_stat=sum(w*ret),ret_ew=mean(ret))%>%
ungroup()%>%
mutate(stat=cumprod(1+ret_stat),ew=cumprod(1+ret_ew))
ret_per=retorno_portafolio%>%
select(date,ret_stat)
retorno_final=portfolio_tidy%>%
inner_join(retornos_tidy_1m,by=c('etf','date'))%>%
inner_join(ret_per,by=c('date'))%>%
mutate(wf=w*(1+ret)/(1+ret_stat))%>%
group_by(etf)%>%
mutate(dw=delta_w(wf,w))%>%
ungroup()%>%
group_by(date)%>%
summarise(ret_stat=sum(w*ret)-0.0001*sum(dw),ret_ew=mean(ret))%>%
ungroup()%>%
mutate(stat=cumprod(1+ret_stat),ew=cumprod(1+ret_ew))
return(retorno_final)
}
## funcional
raw=read.csv('all_info.csv',stringsAsFactors = FALSE)%>%
clean_names()%>%
mutate(date=as.Date(date))%>%
rename(tri=tot_return_index_net_dvds) ### Leo todo
wilcon=get_bt(raw,etfs,20,p_val=0.05,game)%>%
select(date,stat,ew)%>%
rename(Wilcox=stat)
mediana=get_bt(raw,etfs,20,p_val=0.05,game2)%>%
select(date,stat,ew)%>%
rename(Mediana=stat)
media=get_bt(raw,etfs,20,p_val=0.05,game3)%>%
select(date,stat)%>%
rename(Media=stat)
gather(wilcon,strategy,index,-date)%>%
rbind(gather(mediana,strategy,index,-date))%>%
rbind(gather(media,strategy,index,-date))%>%
plot_ly(x=~date,y=~index,color=~strategy,mode='lines')%>%
layout(title="Backtest de la estrategia")
gather(wilcon,strategy,index,-date)%>%
rbind(gather(mediana,strategy,index,-date))%>%
rbind(gather(media,strategy,index,-date))%>%
rename(Estrategia=strategy)%>%
ggplot(aes(date,index,color=Estrategia))+
geom_line()+
ylab('Indice')+
xlab('Fecha')+
ggthemes::theme_hc()
gather(wilcon,strategy,index,-date)%>%
rbind(gather(mediana,strategy,index,-date))%>%
rbind(gather(media,strategy,index,-date))%>%
rename(Estrategia=strategy)%>%
filter(Estrategia%in%c('Wilcox','ew'))%>%
ggplot(aes(date,index,color=Estrategia))+
geom_line()+
ylab('Indice')+
xlab('Fecha')+
ggthemes::theme_hc()
wilconR=get_bt(raw,etfs,20,p_val=0.05,game)%>%
select(date,ret_stat,ret_ew)%>%
rename(Wilcox=ret_stat)
medianaR=get_bt(raw,etfs,20,p_val=0.05,game2)%>%
select(date,ret_stat)%>%
rename(Mediana=ret_stat)
mediaR=get_bt(raw,etfs,20,p_val=0.05,game3)%>%
select(date,ret_stat)%>%
rename(Media=ret_stat)
all=gather(wilconR,strategy,index,-date)%>%
rbind(gather(medianaR,strategy,index,-date))%>%
rbind(gather(mediaR,strategy,index,-date))
bm=all%>%
filter(strategy=='ret_ew')%>%
rename(bmi=index)%>%
select(date,bmi)
all%>%
filter(strategy!='ret_ew')%>%
inner_join(bm,by='date')%>%
mutate(alpha=index-bmi)%>%
filter(!is.na(alpha))%>%
mutate(Estrategia=strategy)%>%
group_by(Estrategia)%>%
summarise(alpha_mean=mean(alpha),
alpha_median=median(alpha),
IR=alpha_mean/sd(alpha))%>%
ggplot(aes(Estrategia,IR,fill=Estrategia))+
geom_col()+
ylab('Information Ratio')+
ggthemes::theme_hc()
##### GRID
df=data.frame()
horiz=as.list(seq(10,60,10))
p<-0.05
resultados=lapply(horiz,get_bt,raw=raw,etfs=etfs,p_val=p,game=game)
for (i in 1:length(horiz)){
df=resultados[[i]]%>%
select(date,ret_stat)%>%
mutate(h=horiz[[i]],pv=p)%>%
rbind(df)
}
p<-0.1
resultados=lapply(horiz,get_bt,raw=raw,etfs=etfs,p_val=p,game=game)
for (i in 1:length(horiz)){
df=resultados[[i]]%>%
select(date,ret_stat)%>%
mutate(h=horiz[[i]],pv=p)%>%
rbind(df)
}
p<-0.2
resultados=lapply(horiz,get_bt,raw=raw,etfs=etfs,p_val=p,game=game)
for (i in 1:length(horiz)){
df=resultados[[i]]%>%
select(date,ret_stat)%>%
mutate(h=horiz[[i]],pv=p)%>%
rbind(df)
}
p<-0.3
resultados=lapply(horiz,get_bt,raw=raw,etfs=etfs,p_val=p,game=game)
for (i in 1:length(horiz)){
df=resultados[[i]]%>%
select(date,ret_stat)%>%
mutate(h=horiz[[i]],pv=p)%>%
rbind(df)
}
bm=resultados[[1]]%>%
select(date,ret_ew)
df_bm=df%>%
inner_join(bm,by='date')
alpha_ir=df_bm%>%
mutate(alpha=ret_stat-ret_ew)%>%
filter(!is.na(alpha))%>%
group_by(h,pv)%>%
summarise(alpha_mean=mean(alpha),
alpha_median=median(alpha),
IR=alpha_mean/sd(alpha))
alpha_ir%>%
mutate(Horizonte=factor(h))%>%
ggplot(aes(h,IR,fill=Horizonte))+
geom_col()+
facet_wrap(~pv)+
ylab('Information Ratio')+
xlab('Horizonte')+
ggthemes::theme_hc()
alpha_ir%>%
mutate(Horizonte=factor(h),
alpha_mean=(1+alpha_mean)^52-1)%>%
ggplot(aes(Horizonte,alpha_mean,fill=Horizonte))+
geom_col()+
facet_wrap(~pv)+
scale_y_continuous(labels = scales::percent_format(accuracy = 1))+
ylab('Alpha')+
xlab('Horizonte')+
ggthemes::theme_hc()