How to obtain GARCH volatility for 100 firms in a single CSV in r?

236 views Asked by At

I am a newbie to R programming environment. Can anyone please help me with the following problem:

I have a .csv file with stock return data for 100 odd firms (207 days each). I need to estimate GARCH volatilities for each firm and save the output for all firms in a single .csv file. My data looks like this:

StockData

Below is the reproducible code I have tried so far but unsuccessfully:

library(fGarch)
stdata <- read.csv("StockData.csv", header = T)
out <- vector("list",c(437))
for(j in length(names(stdata[,-1]))) {
    fit = garchFit(~arma(1,0)+garch(1,1), data = stdata[,j], trace = F)
    volatility(fit)
    out = as.data.frame(volatility(fit))
}
write.csv(out, 'volatility.csv')

The output .csv file prints the volatility only for the last firm (the 100th firm). I also get the following warning message:

Warning message:
Using formula(x) is deprecated when x is a character vector of length > 1.
  Consider formula(paste(x, collapse = " ")) instead. 

My expected output will be as follows:

SampleVolatilityOutput

Please tell me if there is a way to get all volatilities at once in a single .csv file.

1

There are 1 answers

2
tester On

You get your output, because you overwrite "out" for each j in the loop. If you store it in a matrix, i.e. each column ist the volatility for one firm, you don't need a list:

library(fGarch)
stdata <- matrix(rnorm(100 * 207), ncol = 100)
out <- matrix(rep(NA, 100*207), ncol = 100)
for (j in 1:ncol(stdata)) {
  fit <-
    garchFit(
      formula = ~ arma(1, 0) + garch(1, 1),
      data = stdata[, j],
      trace = F
    )
  out[, j] = volatility(fit)
}

write.csv(out, 'volatility.csv')