EWMA volatility in a data.frame

5
I have a data.frame base_retorno_diario , 3560 observations in 110 actions (daily returns), I want to create another data.frame from that with Volatility ewma with decay_factor = 0.97

Data.frame example

  Data       IBOV         ABEV3       AEDU3   ALLL3 BBAS3        BBDC3        BBDC4
1 2000-01-04 -0.063756245 0.00000000  0       0     -0.029935852 -0.080866107 -0.071453347
2 2000-01-05 0.024865308  -0.03762663 0       0     -0.008082292 0.043269231 0.060889055
3 2000-01-06 -0.008510238 -0.03157895 0       0      0.014074074 0.014285714 0.008098592
4 2000-01-07 0.012557359  -0.02484472 0       0     -0.022644266 0.017719219 0.000000000
5 2000-01-10 0.043716564  0.00000000  0       0     0.050074738 0.005357143 0.006985679
6 2000-01-11 -0.026401514 -0.02388535 0       0    -0.008540925 -0.059058615 -0.046479362

The first line I created with the following code ( n_row and n_col are the number of rows and columns in base_retorno_diario )

EWMA_VARIANCE = as.data.frame(base_retorno_diario[1,2:n_col]^2)

Then I created the following loop

i = 2
DECAY_FACTOR = 0.97
while(i<=n_row){EWMA_VARIANCE = rbind(EWMA_VARIANCE,EWMA_VARIANCE[(i-1),1:(n_col-1)]*DECAY_FACTOR +(1-DECAY_FACTOR)*base_retorno_diario[i,2:n_col]^2)
i=i+1
}

It works and creates the new data.frame with the volatility of all actions in the database, but it takes a long time, is there any more efficient way to code the same situation?

    
asked by anonymous 21.05.2014 / 20:47

1 answer

2

Follow the code with the answer

The second function variance.ewma receives an array with the stock returns and the EWMA decay factor value, for each matrix column it calls the ewma.func function and passes the decay factor by applying the ewma formula to each column, when you finish applying the formula in each column it returns an array with the results.

ewma.func <- function(rets, lambda) {
rets[is.infinite(rets)] = 0
rets[is.nan(rets)] = 0
ewma.ant <- rets[1]^2
ewma <- vapply(rets, function(r) ewma.ant <<- ewma.ant *lambda + (r^2)*(1 - lambda), 0)
return(ewma)
}

variance.ewma <- function(bancodados,decayfactor){
EWMA = bancodados
for (i in 1:ncol(EWMA)){
EWMA[, i] = ewma.func(EWMA[, i], decayfactor) }
return(EWMA)}
    
10.06.2014 / 23:07