1

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?

Spy_Lord
  • 133
  • 4

1 Answers1

1

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

GSee
  • 48,880
  • 13
  • 125
  • 145
  • [This `to_secBATV` function](https://r-forge.r-project.org/scm/viewvc.php/pkg/FinancialInstrument/R/Tick2Sec.R?view=markup&root=blotter) that is sort of related – GSee May 04 '14 at 13:29
  • Magic indeed! Wow. Is that feature of to.period actually documented in the xts reference? – Spy_Lord May 04 '14 at 16:58
  • @Spy_Lord Yes, `?to.period` says "If volume for a period was available, the new volume will also be calculated." – GSee May 04 '14 at 17:01
  • Ah, I did read that but wasn't able to interpret its helpfulness in this context ;) – Spy_Lord May 04 '14 at 17:04