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:
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:
Please tell me if there is a way to get all volatilities at once in a single .csv
file.
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: