I am trying to calculate rolling daily correlations on 2 stock prices (type xts), AGL and BIL (OHLC data below):
library(RODBC)
library(quantmod)
library(xts)
library(TTR)
dput(my.AGL)
structure(c(28500, 27800, 28699, 28440, 28569, 28600, 26650,
27250, 26910, 27450, 28814, 27950, 28950, 28740, 29250, 28765,
27429, 27584, 27534, 28072, 27122, 27050, 28406, 28030, 28211,
27349, 26618, 26509, 26560, 27200, 27203, 27900, 28665, 28694,
28836, 27698, 27090, 26600, 27079, 27206), .Dim = c(10L, 4L), .Dimnames = list(
NULL, c("days.Open", "days.High", "days.Low", "days.Close"
)), index = structure(c(1312988460, 1313074860, 1313420460,
1313506860, 1313593260, 1313679660, 1314025260, 1314111660, 1314198060,
1314284460), tzone = "", tclass = c("POSIXt", "POSIXct")), class = c("xts",
"zoo"), .indexCLASS = c("POSIXt", "POSIXct"), .indexTZ = "", tclass = c("POSIXct",
"POSIXt"))
my.AGL
days.Open days.High days.Low days.Close
2011-08-10 17:01:00 28500 28814 27122 27203
2011-08-11 17:01:00 27800 27950 27050 27900
2011-08-15 17:01:00 28699 28950 28406 28665
2011-08-16 17:01:00 28440 28740 28030 28694
2011-08-17 17:01:00 28569 29250 28211 28836
2011-08-18 17:01:00 28600 28765 27349 27698
2011-08-22 17:01:00 26650 27429 26618 27090
2011-08-23 17:01:00 27250 27584 26509 26600
2011-08-24 17:01:00 26910 27534 26560 27079
2011-08-25 17:01:00 27450 28072 27200 27206
I then create a series using ROC:
my.AGL.roc <- ROC(my.AGL[,4])
From the feedback below, I gathered that ROC is not compatible with 2.13.1, so, to create log returns I replaced the ROC function with:
my.AGL.lret <- log(my.AGL[,4]) - log(lag(my.AGL[,4], 1)
replacing the first NA observation with:
my.AGL.lret[ is.na(my.AGL.lret) ] <- 0
my.AGL.lret
days.Close
2011-08-10 17:01:00 0.000000000
2011-08-11 17:01:00 0.025299427
2011-08-15 17:01:00 0.027050178
2011-08-16 17:01:00 0.001011175
2011-08-17 17:01:00 0.004936565
2011-08-18 17:01:00 -0.040264398
2011-08-22 17:01:00 -0.022195552
2011-08-23 17:01:00 -0.018253440
2011-08-24 17:01:00 0.017847304
2011-08-25 17:01:00 0.004679017
However, both suggestions yield the same result in terms of the error. The reason I am using xts, is that I want to merge my resulting rolling correlation with my original price series.
> rollapply(my.AGL.lret, 30, mean)
Error in `colnames<-`(`*tmp*`, value = "days.Close") :
attempt to set colnames on object with less than two dimensions
> rollmean(my.AGL.lret, 30)
Error in `colnames<-`(`*tmp*`, value = "days.Close") :
attempt to set colnames on object with less than two dimensions
I am sure I am doing something silly, but I would appreciate it if someone could please explain how the dimensions are handled? With my limited knowledge I have created a return series, which is still a time series.
dim(my.AGL.roc)
[1] 406 1
Thanks in advance Ed