How to compute the daily avg correlation on intraday data using the xts package?

陌路散爱 提交于 2019-12-05 02:31:33

问题


I have intra-day history for a bunch of stocks. I am trying to compute the 1-minute correlation between stocks on a daily basis. My aim is to use the daily average per pair over a period to identify optimal pairs for a specific trading strategy.

My idea is to loop through the trading days, compute intra-day 1-minute correlation, compute avg over all trading days, next pair.

However, I am getting stuck at looping through the trading days.

my.xts.A <- xts(A_Frame[,-1], order.by=A_Frame[,1])
my.xts.B <- xts(B_Frame[,-1], order.by=B_Frame[,1])

my.min.A <- to.minutes(my.xts.A[,1],1,'minutes')
my.min.B <- to.minutes(my.xts.B[,1],1,'minutes')

my.day <- to.daily(my.xts.A[,1],1)

my.index <- index(my.day)

I get the trading days in my.index, could someone please give me some guidance as to how to select a subset of my.min.A where my.index[i] == day(my.min.A)?

thanks

edit:

dput(head(my.min.A, 20))
structure(c(3575, 3630, 3649, 3630, 3614, 3612, 3612, 3616, 3615, 
3602, 3602, 3602, 3605, 3605, 3605, 3605, 3605, 3604, 3604, 3605, 
3682, 3630, 3649, 3630, 3614, 3612, 3612, 3616, 3615, 3602, 3602, 
3606, 3605, 3605, 3605, 3605, 3605, 3605, 3604, 3608, 3575, 3630, 
3649, 3630, 3612, 3612, 3610, 3616, 3615, 3602, 3602, 3601, 3604, 
3603, 3604, 3604, 3604, 3604, 3604, 3604, 3682, 3630, 3649, 3630, 
3612, 3612, 3610, 3616, 3615, 3602, 3602, 3604, 3604, 3604, 3604, 
3604, 3605, 3604, 3604, 3605), tclass = c("POSIXct", "POSIXt"
), tzone = "", class = c("xts", "zoo"), .indexCLASS = c("POSIXct", 
"POSIXt"), .indexTZ = "", index = structure(c(1352790059, 1352790290, 
1352790306, 1352790467, 1352790521, 1352790547, 1352790757, 1352791124, 
1352791222, 1352791466, 1352791576, 1352791750, 1352791859, 1352791891, 
1352791970, 1352792006, 1352792041, 1352792149, 1352792181, 1352792227
), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(20L, 
4L), .Dimnames = list(NULL, c("minutes.Open", "minutes.High", 
"minutes.Low", "minutes.Close")))

回答1:


Here's a reproducible example, using daily data and calculating monthly correlations between prices.

library(quantmod)
getSymbols("KO;PEP")
apply.monthly(merge(Cl(KO),Cl(PEP)), function(x) cor(x[,1],x[,2]))

In your case, you would want something like:

apply.daily(merge(Cl(my.min.A), Cl(my.min.B)), function(x) cor(x[,1],x[,2]))


来源:https://stackoverflow.com/questions/14234636/how-to-compute-the-daily-avg-correlation-on-intraday-data-using-the-xts-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!