roll_sum | R Documentation |
Calculate the rolling sums over a time series or a matrix using Rcpp.
roll_sum(tseries, lookb = 1L, weightv = 0L)
tseries |
A time series or a matrix. |
lookb |
The length of the look-back interval, equal to the
number of data points included in calculating the rolling sum (the default
is |
weightv |
A single-column matrix of weights (the default
is |
The function roll_sum()
calculates the rolling weighted sums
over the columns of the data tseries
.
If the argument weightv
is equal to zero (the default), then the
function roll_sum()
calculates the simple rolling sums of the
time series data p_t
over the look-back interval \Delta
:
\bar{p}_t = \sum_{j=(t-\Delta+1)}^{t} p_j
If the weightv
argument has the same number of rows as the argument
tseries
, then the function roll_sum()
calculates rolling
weighted sums of the time series data p_t
in two steps.
It first calculates the rolling sums of the products of the weights
w_t
times the time series data p_t
over the look-back
interval \Delta
:
\bar{w}_t = \sum_{j=(t-\Delta+1)}^{t} w_j
\bar{p}^w_t = \sum_{j=(t-\Delta+1)}^{t} w_j p_j
It then calculates the rolling weighted sums \bar{p}_t
as the
ratio of the sum products of the weights and the data, divided by the sums
of the weights:
\bar{p}_t = \frac{\bar{p}^w_t}{\bar{w}_t}
The function roll_sum()
returns a matrix with the same
dimensions as the input argument tseries
.
The function roll_sum()
is written in C++
Armadillo
code, so it's much faster than equivalent R
code.
A matrix with the same dimensions as the input argument
tseries
.
## Not run:
# Calculate historical returns
retp <- na.omit(rutils::etfenv$returns[, c("VTI", "IEF")])
# Define parameters
lookb <- 11
# Calculate rolling sums and compare with rutils::roll_sum()
sumc <- HighFreq::roll_sum(retp, lookb)
sumr <- rutils::roll_sum(retp, lookb)
all.equal(sumc, coredata(sumr), check.attributes=FALSE)
# Calculate rolling sums using R code
sumr <- apply(zoo::coredata(retp), 2, cumsum)
sumlag <- rbind(matrix(numeric(2*lookb), nc=2), sumr[1:(NROW(sumr) - lookb), ])
sumr <- (sumr - sumlag)
all.equal(sumc, sumr, check.attributes=FALSE)
# Calculate weights equal to the trading volumes
weightv <- quantmod::Vo(rutils::etfenv$VTI)
weightv <- weightv[zoo::index(retp)]
# Calculate rolling weighted sums
sumc <- HighFreq::roll_sum(retp, lookb, 1/weightv)
# Plot dygraph of the weighted sums
datav <- cbind(retp$VTI, sumc[, 1])
colnames(datav) <- c("VTI", "Weighted")
endd <- rutils::calc_endpoints(datav, interval="weeks")
dygraphs::dygraph(cumsum(datav)[endd], main=colnames(datav)) %>%
dyOptions(colors=c("blue", "red"), strokeWidth=2) %>%
dyLegend(width=300)
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.