# [R] predict and arima

bdp palmer.bryan at gmail.com
Sun Jan 30 04:15:35 CET 2011

```Some code I have been playing with to do this follows ...

get.best.arima <- function(x.ts, minord=c(0,0,0,0,0,0),
maxord=c(2,1,1,2,1,1))
{
# function based on 'Introductory Time Series with R'
best.aic <- 1e8 # a big number
n <- length(x.ts)
for(p in minord[1]:maxord[1]) for(d in minord[2]:maxord[2]) for(q in
minord[3]:maxord[3])
{
for(P in minord[4]:maxord[4]) for(D in minord[5]:maxord[5]) for(Q in
minord[6]:maxord[6])
{
fit <- arima(x.ts, order=c(p,q,d), seas=list(order=c(P,D,Q),
frequency(x.ts)), method='CSS')
fit.aic <- -2 * fit\$loglik + (log(n) + 1) * length(fit\$coef)
if(fit.aic < best.aic) # probably should  do other tests here before
accepting
{
best.aic <- fit.aic
best.fit <- fit
best.model <- c(p,d,q,P,D,Q)
}
}
}
#print(best.aic)
#print(best.model)
return(best.fit)
}

extend.series <- function(series.ts, extend.by=1)
{
log.series.ts <- log(series.ts)

best.log <- get.best.arima(log.series.ts)

prediction.log <- predict( best.log,

reverse.log.series.ts <- ts( data=rev(as.vector(log.series.ts)),
frequency=frequency(series.ts) )

best.log.reverse <- get.best.arima(reverse.log.series.ts)

prediction.log.reverse <- predict( best.log.reverse,

start.series.ts <- start(series.ts)
end.series.ts <- end(series.ts)

extended.vector <- append(rev(exp(as.vector(prediction.log.reverse\$pred))),
as.vector(series.ts) )
extended.vector <- append( extended.vector,
exp(as.vector(prediction.log\$pred)) )

extended.ts <- ts(data=extended.vector, frequency=frequency(series.ts),
start=c(start.series.ts[1]-extend.by, 1))
}

--
View this message in context: http://r.789695.n4.nabble.com/R-predict-and-arima-tp813419p3246820.html
Sent from the R help mailing list archive at Nabble.com.

```