[R] Writing output to a file in a loop
Wojtek Slusarski
slusek at o2.pl
Thu Feb 10 11:40:23 CET 2005
Hello,
My problem is, that I have to build hundreds of GARCH models to obtain
volatility forecasts. I would like to run a loop, that would build those
forecasts for me. There is no problem, with writing only the results of
the forecasts, but I'd like to have stored results of the models in some
file, that I could check later, what are the models like, to be able to
compare if I should use GARCH(1,1) or GARCH(0,4) or any other, that
suits the data best. The data file looks like that:
TICKER;DTYYYYMMDD;OPEN;HIGH;LOW;CLOSE;VOL
WIG20;19940414;1000,00;1000,00;1000,00;1000,00;71600
WIG20;19940418;1050,47;1050,47;1050,47;1050,47;99950
WIG20;19940419;1124,92;1124,92;1124,92;1124,92;138059
...
I wrote a script to do that, but when I use sink() to save the results
in a text file, after running the script files are empty. I read in FAQ,
that in a loop R only computes and prints only some warning messages,
but I don't know how to do that in any other way, to ommit this problem.
Below I enclose the code:
############################################################
library(tseries)
wig20 <- read.csv("wig20.txt", sep=";", dec=",")
m <- 2321 #upper bound of time series
niter <- 10 #length(wig20$CLOSE)- m
fcv <- 0
for (i in 1:niter){
m <- m + 1
r <- 100*diff(log(wig20$CLOSE[1:m]))
y <- r - mean(r)
fit <- garch(y, order = c(1,1))
sink("garch21.txt", append = TRUE)
summary(fit)
logLik(fit)
sink()
cv <- predict(fit, genuine=TRUE)
fcv <- c(fcv,cv[length(cv)/2,1])
postscript("garch21.ps",encoding="ISOLatin2",
title = paste("Day: ",wig20$DTYYYYMMDD[m]),
paper = "a4",
family = "URWTimes",
append = TRUE)
plot(fit, ask=FALSE)
dev.off()
}
sink("forecasts.txt")
fcv
sink()
###################################################
The most wondering thing for me is that, plots are stored in the ps
file, but only the ones from last iteration. In manuals there is:
append: logical; currently *disregarded*; just there for
compatibility reasons.
What does *disregarded* actually mean and when I will be able to add a
title before each set of plots, because now the option title is not
adding anything to file.
I will be very thankfull for any help.
Best regards,
Wojtek Slusarski
More information about the R-help
mailing list