Search code examples
rtidyversefgarch

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:

enter image description here

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: enter image description here

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


Solution

  • 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)