# Create Tick Bars with R

How do I get OHLC bars with tick count (i.e. 500 ticks) instead of time?

I prefer quantmod. Currently I have tick data and can already convert to minute bars using xts.

# I'd like this to be 500 ticks, instead of 5 seconds
CL.x <- to.period(CL.tick, "seconds", k=5)


I don't use quantmod, but you can aggregate the data using R's tapply. Assume you have your tick data, and these are sorted in time. Let's make up some data.

ticks <- cumprod(1 + rnorm(100020, sd = 0.001))


Compute the number of bars.

n <- ceiling(length(ticks)/500)
bars <- rep(1:n, each = 500)[seq_along(ticks)]


Compute open, high, low close for each bar and combine them into a matrix.

ohlc.list <- tapply(ticks, bars,
function(x) c(x, max(x), min(x), x[length(x)]))
ohlc <- do.call(rbind, ohlc.list)
colnames(ohlc) <- c("open", "high", "low", "close")


You may now process these bars as you like; perhaps attach a timestamp to each bar, and plot them.

Here's what I ended up using, thanks to Enrico.

My data had CL.ticks (DateTime and Open) e.g. CL.ticks <- CL[c("DateTime", "Open")]

Where DateTime is POSIXct

# Combine -----
tickCount = 500
ticks = CL.ticks$Open ## get num bars n <- ceiling(length(ticks)/tickCount) bars <- rep(1:n, each = tickCount)[seq_along(ticks)] ## make a bar ohlc.list <- tapply(ticks, bars, function(x) c(x, max(x), min(x), x[length(x)])) ohlc <- do.call(rbind, ohlc.list) colnames(ohlc) <- c("open", "high", "low", "close") # Grab the opening time bars.dt <- CL$DateTime[seq(1, length(CL$DateTime), tickCount)] ohlc.df <- data.frame(ohlc) ## Add time to rows ohlc.df$DateTime <- bars.dt
ohlc.df$DateTime <- make.time.unique(bars.dt, eps=0.00001) rownames(ohlc.df) = ohlc.df$DateTime
ohlc.df\$DateTime = NULL

## Plot
chartSeries(ohlc.df)