Question

here i have the data like this:

time        price   volume  price*volume
14:56:42    31.15   173 540327
14:56:36    31.15   100 311500
14:56:27    31.16   4   12464
14:56:24    31.16   1   3116
14:56:21    31.16   46  143336
14:56:18    31.15   32  99680
14:56:15    31.16   6   18696
14:56:12    31.16   12  37392
14:56:06    31.16   15  46740
14:56:03    31.16   54  168264
14:55:57    31.19   1   3119
14:55:54    31.19   10  31190

when i use to.period(), it just return a xts object with ohlc of price ,the volume and price*volume missing, how would I go about converting data like this to 5min OHLCV

Was it helpful?

Solution 2

Borrowing the data from agstudy's answer (and therefore making 1 min bars, not 5-mins), I would use this:

dat.xts <- as.xts(dat.xts)   ## otherwise you get an error align.time 
                             ## since (dat.xts is a zoo object)
bars <- period.apply(dat.xts, 
                    endpoints(dat.xts,"secs",60),
                    function(xx){
                      ticks=coredata(xx$price)
                      c( first(ticks),max(ticks), min(ticks),
                         last(ticks), sum(xx$volume), sum(xx$price_volume) )
                    })
colnames(bars) <- c("Open","High","Low","Close","Volume","Price*Volume")
align.time(bars,60)

I.e. period.apply() is given an xts object holding the ticks for a given 1 minute period. I use first, max, min and last to make the OHLC data. (I have to use coredata otherwise those functions complain.)

Then volume and price_volume are summed for each period.

After the main loop I assign column headings, and round up the timestamps. The output is:

                     Open  High   Low Close Volume Price*Volume
2013-11-11 14:56:00 31.19 31.19 31.19 31.19     11        34309
2013-11-11 14:57:00 31.16 31.16 31.15 31.15    443      1381515

OTHER TIPS

Here a custom function :

period.apply.ohlc <- function(x,FUN= 'mean',INDEX=endpoints(x,"mins",k=1)){
  ll <- sapply(1:(length(INDEX) - 1), function(y) {
    xi <- x[(INDEX[y] + 1):INDEX[y + 1]]
    sapply(xi,FUN)
  })
  xts(t(ll),order.by=index(dat.xts[INDEX]))
}

period.apply.ohlc(dat.xts)
#                     price volume price_volume
# 2013-11-10 14:55:57 31.190    5.5      17154.5
# 2013-11-10 14:56:42 31.157   44.3     138151.5

where dat.xts:

dat.xts <- read.zoo(text='time            price   volume  price_volume
14:56:42    31.15   173 540327
14:56:36    31.15   100 311500
14:56:27    31.16   4   12464
14:56:24    31.16   1   3116
14:56:21    31.16   46  143336
14:56:18    31.15   32  99680
14:56:15    31.16   6   18696
14:56:12    31.16   12  37392
14:56:06    31.16   15  46740
14:56:03    31.16   54  168264
14:55:57    31.19   1   3119
14:55:54    31.19   10  31190',tz="",index=1,format="%H:%M:%S",header=TRUE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top