I have an xts object in R, myticks_xts, which consists of tick data from a financial security and looks as below:
myticks_xts[1:10,]
V3 V4 V5
2014-01-01 21:55:34.378 1.37622 1.37693 1.37666900000
2014-01-01 21:55:40.410 1.37624 1.37698 1.37673727273
2014-01-01 21:55:47.210 1.37619 1.37696 1.37673702703
2014-01-01 21:55:57.963 1.37616 1.37696 1.37673702703
2014-01-01 21:56:03.117 1.37616 1.37694 1.37670529412
2014-01-01 21:56:07.253 1.37616 1.37692 1.37665407407
2014-01-01 21:56:16.911 1.37620 1.37695 1.37673411765
2014-01-01 21:56:19.433 1.37615 1.37692 1.37665407407
2014-01-01 21:56:24.970 1.37615 1.37691 1.37668466667
2014-01-01 21:56:24.971 1.37615 1.37689 1.37667203390
I can convert this tick data into 10 second bars (OHLC data) by using:
to.period(myticks_xts,'seconds',10)
I would however like to have an extra column representing 'Volume' which counts the number of ticks inside each bar. For example in the above, the bar 21:55:30-21:55:40 would have 1 tick, the bar 21:55:40-21:55:50 would have 2 ticks, and so on. Is there a simple way to do this?
The easiest way is to create a column called Volume
. Then to.period
will magically do it for you.
x <- cbind(myticks_xts$V5, Volume=1)
to.period(x, "seconds", 10)
# x.Open x.High x.Low x.Close x.Volume
#2014-01-01 21:55:34.378 1.376669000 1.376669000 1.376669000 1.376669000 1
#2014-01-01 21:55:47.210 1.376737273 1.376737273 1.376737027 1.376737027 2
#2014-01-01 21:55:57.963 1.376737027 1.376737027 1.376737027 1.376737027 1
#2014-01-01 21:56:07.253 1.376705294 1.376705294 1.376654074 1.376654074 2
#2014-01-01 21:56:19.433 1.376734118 1.376734118 1.376654074 1.376654074 2
#2014-01-01 21:56:24.970 1.376684667 1.376684667 1.376672034 1.376672034 2
Otherwise, you'd need to use period.apply