run_var_ohlc: Calculate the trailing variance of streaming _OHLC_ price...

View source: R/RcppExports.R

run_var_ohlcR Documentation

Calculate the trailing variance of streaming OHLC price data using an online recursive formula.

Description

Calculate the trailing variance of streaming OHLC price data using an online recursive formula.

Usage

run_var_ohlc(ohlc, lambda)

Arguments

ohlc

A time series or a matrix with OHLC price data.

lambda

A decay factor which multiplies past estimates.

Details

The function run_var_ohlc() calculates a single-column matrix of variance estimates of streaming OHLC price data.

The function run_var_ohlc() calculates the variance from the differences between the Open, High, Low, and Close prices, using the Yang-Zhang range volatility estimator:

\sigma^2_t = (1-\lambda) ((O_t - C_{t-1})^2 + 0.134 (C_t - O_t)^2 + 0.866 ((H_i - O_i) (H_i - C_i) + (L_i - O_i) (L_i - C_i))) + \lambda \sigma^2_{t-1}

It recursively weighs the current variance estimate with the past estimates \sigma^2_{t-1}, using the decay factor \lambda.

The above recursive formula is convenient for processing live streaming data because it doesn't require maintaining a buffer of past data. The formula is equivalent to a convolution with exponentially decaying weights, but it's faster. Using exponentially decaying weights is more natural than using a sliding look-back interval, because it gradually "forgets" about the past data.

The function run_var_ohlc() does not calculate the logarithm of the prices. So if the argument ohlc contains dollar prices then run_var_ohlc() calculates the dollar variance. If the argument ohlc contains the log prices then run_var_ohlc() calculates the percentage variance.

The function run_var_ohlc() is implemented in RcppArmadillo C++ code, which makes it several times faster than R code.

Value

A single-column matrix of variance estimates, with the same number of rows as the input ohlc price data.

Examples

## Not run: 
# Extract the log OHLC prices of VTI
ohlc <- log(rutils::etfenv$VTI)
# Calculate the trailing variance
vart <- HighFreq::run_var_ohlc(ohlc, lambda=0.8)
# Calculate the rolling variance
varoll <- HighFreq::roll_var_ohlc(ohlc, lookb=5, method="yang_zhang", scale=FALSE)
datav <- cbind(vart, varoll)
colnames(datav) <- c("trailing", "rolling")
colnamev <- colnames(datav)
datav <- xts::xts(datav, index(ohlc))
# dygraph plot of VTI trailing versus rolling volatility
dygraphs::dygraph(sqrt(datav[-(1:111), ]), main="Trailing and Rolling Volatility of VTI") %>%
  dyOptions(colors=c("red", "blue"), strokeWidth=2) %>%
  dyLegend(show="always", width=300)
# Compare the speed of trailing versus rolling volatility
library(microbenchmark)
summary(microbenchmark(
  trailing=HighFreq::run_var_ohlc(ohlc, lambda=0.8),
  rolling=HighFreq::roll_var_ohlc(ohlc, lookb=5, method="yang_zhang", scale=FALSE),
  times=10))[, c(1, 4, 5)]

## End(Not run)

algoquant/HighFreq documentation built on Feb. 9, 2024, 8:15 p.m.