I am using intra-day data that starts at 9:50am and would like to convert it into 20 minute time intervals so the first period would be from 09:50 to 10:09:59 and the second tim
I had a similar challenge recently (splitting FX data by the 5pm day start). Starting with your test data:
library(xts)
set.seed(42)
x <- xts(rnorm(24*60*60), as.POSIXct(format(paste(Sys.Date(),'09:50')))-((24*60*60):1))
Move it back 10 minutes, do the split, then move the split data forward 10 minutes:
offset <- 600
index(x) <- index(x) - offset
x1 <- to.minutes(x, 20)
index(x1) <- index(x1) + offset
(NB. this corrupts x
; either work on a copy or also do index(x) <- index(x) + offset
afterwards). x1
looks like:
x.Open x.High x.Low x.Close
2012-10-06 10:09:59 1.3709584 3.495304 -3.371739 0.4408241
2012-10-06 10:29:59 -0.7465165 3.584659 -2.828475 0.5938161
2012-10-06 10:49:59 1.3275046 3.174520 -3.199558 -0.6273660
...
2012-10-07 09:09:59 -0.83742490 3.103466 -3.251721 -1.093380
2012-10-07 09:29:59 -0.48464537 3.228048 -3.113351 -1.572931
2012-10-07 09:49:59 1.90503697 3.420940 -3.505207 2.832325
The magic number of 600 came because your last tick was 600 seconds from the previous 20 minute boundary. Here is how you calculate it dynamically:
offset <- ( as.integer(last(index(x))) %% 1200 ) + 1
as.integer
converts the time of the last tick into secs-since-1970 form. (Use as.numeric
if you have milliseconds in your timestamps.) %%1200
rounds down to a 20 minute boundary. Finally, the +1
is because to.minutes
treats XX:XX:00 as the start of one bar, not the end of the previous bar.