I had a similar task recently (sharing FX data at the beginning of 5pm). Starting from 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, split it, 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
(this damages x , either working on the copy, or then index(x) <- index(x) + offset ). x1 as follows:
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 600 happened because the last tick was 600 seconds from the previous 20-minute border. Here's how you calculate it dynamically:
offset <- ( as.integer(last(index(x))) %% 1200 ) + 1
as.integer converts the last tick time to secs-from-1970. (Use as.numeric if you have milliseconds at timestamps.) %%1200 rounds to a 20-minute border. Finally, +1 is that to.minutes treats XX: XX: 00 as the beginning of one bar, not the end of the previous bar.
source share