calc_lm: Perform multivariate linear regression using least squares...

View source: R/RcppExports.R

calc_lmR Documentation

Perform multivariate linear regression using least squares and return a named list of regression coefficients, their t-values, and p-values.

Description

Perform multivariate linear regression using least squares and return a named list of regression coefficients, their t-values, and p-values.

Usage

calc_lm(respv, predm)

Arguments

respv

A single-column time series or a vector of response data.

predm

A time series or a matrix of predictor data.

Details

The function calc_lm() performs the same calculations as the function lm() from package stats. It uses RcppArmadillo C++ code so it's several times faster than lm(). The code was inspired by this article (but it's not identical to it): http://gallery.rcpp.org/articles/fast-linear-model-with-armadillo/

Value

A named list with three elements: a matrix of coefficients (named "coefficients"), the z-score of the last residual (named "zscore"), and a vector with the R-squared and F-statistic (named "stats"). The numeric matrix of coefficients named "coefficients" contains the alpha and beta coefficients, and their t-values and p-values.

Examples

## Not run: 
# Calculate historical returns
retp <- na.omit(rutils::etfenv$returns[, c("XLF", "VTI", "IEF")])
# Response equals XLF returns
respv <- retp[, 1]
# Predictor matrix equals VTI and IEF returns
predm <- retp[, -1]
# Perform multivariate regression using lm()
regmod <- lm(respv ~ predm)
regsum <- summary(regmod)
# Add unit intercept column to the predictor matrix
predm <- cbind(rep(1, NROW(predm)), predm)
# Perform multivariate regression using calc_lm()
regarma <- HighFreq::calc_lm(respv=respv, predm=predm)
# Compare the outputs of both functions
all.equal(regarma$coefficients[, "coeff"], unname(coef(regmod)))
all.equal(unname(regarma$coefficients), unname(regsum$coefficients))
all.equal(unname(regarma$stats), c(regsum$r.squared, unname(regsum$fstatistic[1])))
# Compare the speed of RcppArmadillo with R code
summary(microbenchmark(
  Rcpp=HighFreq::calc_lm(respv=respv, predm=predm),
  Rcode=lm(respv ~ predm),
  times=10))[, c(1, 4, 5)]  # end microbenchmark summary

## End(Not run)


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