5
$\begingroup$

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)
$\endgroup$

2 Answers 2

2
$\begingroup$

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[1], 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.

$\endgroup$
1
$\begingroup$

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[1], 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)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.