roll_conv | R Documentation |
Calculate the rolling convolutions (weighted sums) of a time series with a single-column matrix of weights.
roll_conv(tseries, weightv)
tseries |
A time series or a matrix of data. |
weightv |
A single-column matrix of weights. |
The function roll_conv()
calculates the convolutions of the
matrix columns with a single-column matrix of weights. It
performs a loop over the matrix rows and multiplies the past
(higher) values by the weights. It calculates the rolling weighted sums
of the past data.
The function roll_conv()
uses the Armadillo
function
arma::conv2()
. It performs a similar calculation to the standard
R
function filter(x=tseries, filter=weightv,
method="convolution", sides=1)
, but it's over 6
times faster, and
it doesn't produce any leading NA
values.
A matrix with the same dimensions as the input argument
tseries
.
## Not run:
# First example
# Calculate a time series of returns
retp <- na.omit(rutils::etfenv$returns[, c("IEF", "VTI")])
# Create simple weights equal to a 1 value plus zeros
weightv <- c(1, rep(0, 10))
# Calculate rolling weighted sums
retf <- HighFreq::roll_conv(retp, weightv)
# Compare with original
all.equal(coredata(retp), retf, check.attributes=FALSE)
# Second example
# Calculate exponentially decaying weights
weightv <- exp(-0.2*(1:11))
weightv <- weightv/sum(weightv)
# Calculate rolling weighted sums
retf <- HighFreq::roll_conv(retp, weightv)
# Calculate rolling weighted sums using filter()
retc <- filter(x=retp, filter=weightv, method="convolution", sides=1)
# Compare both methods
all.equal(retc[-(1:11), ], retf[-(1:11), ], check.attributes=FALSE)
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.