简体   繁体   中英

How to rolling calculate in tidyverse?

I encounter a problem in calculate some variable in R.

It is about the volatility model (GARCH).

The formula I need to apply is this:

在此处输入图片说明

For the first sigma, I use some default value I calculated before. From the second, I need to quote the previous one and add another column's value.

The tibble is like this: 在此处输入图片说明

I want to create a new column called sigma_forecast.

sigma_forecast 1 = sigma2

sigma_forecast 2 = 0.96 * sigma_forecast 1 + 0.04 * r2_lag_1

sigma_forecast 3 = 0.96 * sigma_forecast 2 + 0.04 * r2_lag_1

r2 <- 1:10
sigma_init <- 10
lambda <- 0.5

Reduce(function(x, y) lambda*x + (1 - lambda)*y, r2, sigma_init,
       accumulate = TRUE)
#>  [1] 10.000000  5.500000  3.750000  3.375000  3.687500  4.343750  5.171875
#>  [8]  6.085938  7.042969  8.021484  9.010742

library(purrr)
accumulate(r2, ~ lambda*.y + (1 - lambda)*.x, .init = sigma_init)
#>  [1] 10.000000  5.500000  3.750000  3.375000  3.687500  4.343750  5.171875
#>  [8]  6.085938  7.042969  8.021484  9.010742

Created on 2021-10-27 by the reprex package (v2.0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM