Search code examples
rdataframezoorollapply

How to calculate sd(x) using 1 hour rolling window when I have irregular time series data?


Suppose I have the following zoo object:

 prices.zoo <- read.zoo(data.frame(tm = c(as.POSIXct('2000-05-10 07:50:00'), as.POSIXct('2000-05-10 08:55:00'), as.POSIXct('2000-05-10 09:00:00'), as.POSIXct('2000-05-10 09:10:00'), as.POSIXct('2000-05-10 09:20:00'), as.POSIXct('2000-05-10 09:55:00'), as.POSIXct('2000-05-10 11:35:00')), px = c(10,20,30,40,50,60,70)))
> prices.zoo
2000-05-10 07:50:00 2000-05-10 08:55:00 2000-05-10 09:00:00 2000-05-10 09:10:00 2000-05-10 09:20:00 2000-05-10 09:55:00 
                 10                  20                  30                  40                  50                  60 
2000-05-10 11:35:00 
                 70 

How can I calculate sd(px), i.e. historical vol, EVERY 5 MIN using a rolling window of 1-HOUR?

NOTE: I would prefer a base-R implementation using zoo or data.frame


Solution

  • The width in rollapplyr can be a vector indicating how many points to roll over. findInterval as used below gives the number of points less than one hour before the current time and if we subtract that from the current position we get the appropriate width.

    n <- length(prices.zoo)
    tt <- time(prices.zoo)
    w <- 1:n - findInterval(tt - 3600, tt)
    rollapplyr(prices.zoo, w, sd, fill = NA)
    ## 2000-05-10 07:50:00 2000-05-10 08:55:00 2000-05-10 09:00:00 2000-05-10 09:10:00 
    ##                  NA                  NA            7.071068           10.000000 
    ## 2000-05-10 09:20:00 2000-05-10 09:55:00 2000-05-10 11:35:00 
    ##           12.909944           12.909944                  NA 
    

    Another possibility is to forget about the 1 hour requirement and just use the last k points. e.g.

    rollapplyr(prices.zoo, 3, sd, fill = NA)
    ## 2000-05-10 07:50:00 2000-05-10 08:55:00 2000-05-10 09:00:00 2000-05-10 09:10:00 
    ##                  NA                  NA                  10                  10 
    ## 2000-05-10 09:20:00 2000-05-10 09:55:00 2000-05-10 11:35:00 
    ##                  10                  10                  10