push_covar | R Documentation |
Update the trailing covariance matrix of streaming asset returns, with a row of new returns using an online recursive formula.
push_covar(retsn, covmat, meanv, lambdacov)
retsn |
A vector of new asset returns. |
covmat |
A trailing covariance matrix of asset returns. |
meanv |
A vector of trailing means of asset returns. |
lambdacov |
A decay factor which multiplies the past covariance. |
The function push_covar()
updates the trailing covariance matrix of
streaming asset returns, with a row of new returns. It updates the
covariance matrix in place, without copying the data in memory.
The streaming asset returns r_t
contain multiple columns and the
parameter retsn
represents a single row of r_t
- the asset
returns at time t
. The elements of the vectors retsn
and
meanv
represent single rows of data with multiple columns.
The function push_covar()
accepts pointers to the arguments
covmat
and meanv
,
and it overwrites the old values with the new values. It performs the
calculation in place, without copying the data in memory, which can
significantly increase the computation speed for large matrices.
First, the function push_covar()
updates the trailing means
\bar{r}_t
of the streaming asset returns r_t
by recursively
weighting present and past values using the decay factor \lambda
:
\bar{r}_t = \lambda \bar{r}_{t-1} + (1-\lambda) r_t
This recursive formula is equivalent to the exponentially weighted moving
average of the streaming asset returns r_t
.
It then calculates the demeaned returns:
\hat{r}_t = r_t - \bar{r}_t
Finally, it updates the trailing covariance matrix of the returns:
{cov}_t = \lambda {cov}_{t-1} + (1-\lambda) \hat{r}^T_t \hat{r}_t
The decay factor \lambda
determines the strength of the updates,
with smaller \lambda
values giving more weight to the new data. If
the asset returns are not stationary, then applying more weight to the new
returns reduces the bias of the trailing covariance matrix, but it also
increases its variance. Simulation can be used to find the value of the
\lambda
parameter to achieve the best bias-variance tradeoff.
The function push_covar()
is written in RcppArmadillo
C++
so it's much faster than R
code.
Void (no return value - modifies the trailing covariance matrix and the return means in place).
## Not run:
# Calculate a time series of returns
retp <- na.omit(rutils::etfenv$returns[, c("IEF", "VTI", "DBC")])
# Calculate the returns without last row
nrows <- NROW(retp)
retss <- retp[-nrows]
# Calculate the covariance of returns
meanv <- colMeans(retss)
covmat <- cov(retss)
# Update the covariance of returns
HighFreq::push_covar(retsn=retp[nrows], covmat=covmat, meanv=meanv, lambdacov=0.9)
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.