0

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

Denis
  • 11,796
  • 16
  • 88
  • 150

1 Answers1

1

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 
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • is there a way to change this so this produces a sd(x) every 5-minutes? – Denis Nov 29 '19 at 15:57
  • I mean, we should have an sd(x) value for "2000-05-10 07:50:00", "2000-05-10 07:55:00", "2000-05-10 08:00:00", "2000-05-10 08:05:00", etc. – Denis Nov 29 '19 at 15:58
  • I think your first solution is excellent! Thinking about it more, it would work just fine since I am graphing the result. Your 2nd solution won't work for me because a fixed width window won't always work and this is the reason for this question as I am accustomed to fixed windows but I never knew about the first way of doing it. Thanks! – Denis Nov 29 '19 at 16:08