goyiki
goyiki

Reputation: 45

ccf using ts object or xts object provide different lags

I am using R 3.1.3 and I have 2 time series that I would like to compare using ccf to see at which lag there is the maximum correlation. The time series are in a 15 minute interval.

I have tried this in two different ways:

After that I compute the cross-correlation using ccf command. The ACF graphic is the same in both cases but I get lags between (-31, 31) when I use a ts object, but the lags go between (-27900, 27900) when I use an xts object. I checked in the help and by default the maximum lag is 10*log10(N/m) which in this case would be: 10*log10(2688/2) = 31.28.

Therefore it seems that the first option displays the correct lags. However I would prefer to use xts as I have 8 series more to compare and they are all in the same data.frame. Besides, I am intrigued to know why this happens!

Here you can see the code:

# Generate data - Example:
set.seed(123)
x <- rnorm(2880,0,3)
y <- rnorm(2880,0,3)
# 1 month of data
dt <- seq(as.POSIXct('2014-01-01 00:00:00'), by='15 min', length.out=(60*24*30/15))

x <- data.frame (dt,x)
y <- data.frame(dt,y)
summary(x)
summary(y)
str(x)
str(y)

xy <- merge (x, y, by="dt", all=TRUE)
summary(xy)

# Time series objects (univariate):
x_ts <- ts(x)
y_ts <- ts(y)

# Using xts (multivariate):
library(xts)
xy_ts <- xts(xy[,-1], order.by = xy$dt)
summary(xy_ts)
str(xy_ts)
class(xy_ts)

xy_ts_x <- xy_ts[,1]
xy_ts_y <- xy_ts[,2]
summary(xy_ts_y)

# Cross-correlation fucntion from the univariate series:
ccf1 <- ccf(x_ts[,2], y_ts[,2])

# Cross-correlation fucntion from the multivariate series:
ccf2 <- ccf(drop(xy_ts_x), drop(xy_ts_y)) # drop extra dimensions in xts

As you can see, the x-axis of are different in both graphics. I have read many posts about ccf, xts, etc. but I couldn't find why this happens.

Upvotes: 2

Views: 1521

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176728

The acf and ccf functions convert their first argument to a ts object internally. As I've said in other places, xts does not currently handle conversion to/from ts very well at the moment.

A work-around for this specific problem is to manually set the frequency attribute to 1 after creating the xts object:

xy_ts <- xts(xy[,-1], order.by = xy$dt)
attr(xy_ts, "frequency") <- 1

xy_ts_x <- xy_ts[,1]
xy_ts_y <- xy_ts[,2]

ccf2 <- ccf(drop(xy_ts_x), drop(xy_ts_y))

Upvotes: 4

Related Questions