public
Created

  • Download Gist
garchAuto.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
garchAutoTryFit = function(
ll,
data,
trace=FALSE,
forecast.length=1,
with.forecast=TRUE,
ic="AIC",
garch.model="garch" )
{
formula = as.formula( paste( sep="",
"~ arma(", ll$order[1], ",", ll$order[2], ")+",
garch.model,
"(", ll$order[3], ",", ll$order[4], ")" ) )
fit = tryCatch( garchFit( formula=formula,
data=data,
trace=FALSE,
cond.dist=ll$dist ),
error=function( err ) TRUE,
warning=function( warn ) FALSE )
 
pp = NULL
 
if( !is.logical( fit ) ) {
if( with.forecast ) {
pp = tryCatch( predict( fit,
n.ahead=forecast.length,
doplot=FALSE ),
error=function( err ) FALSE,
warning=function( warn ) FALSE )
if( is.logical( pp ) ) {
fit = NULL
}
}
} else {
fit = NULL
}
 
if( trace ) {
if( is.null( fit ) ) {
cat( paste( sep="",
" Analyzing (", ll$order[1], ",", ll$order[2],
",", ll$order[3], ",", ll$order[4], ") with ",
ll$dist, " distribution done.",
"Bad model.\n" ) )
} else {
if( with.forecast ) {
cat( paste( sep="",
" Analyzing (", ll$order[1], ",", ll$order[2], ",",
ll$order[3], ",", ll$order[4], ") with ",
ll$dist, " distribution done.",
"Good model. ", ic, " = ", round(fit@fit$ics[[ic]],6),
", forecast: ",
paste( collapse=",", round(pp[,1],4) ), "\n" ) )
} else {
cat( paste( sep="",
" Analyzing (", ll[1], ",", ll[2], ",", ll[3], ",", ll[4], ") with ",
ll$dist, " distribution done.",
"Good model. ", ic, " = ", round(fit@fit$ics[[ic]],6), "\n" ) )
}
}
}
 
return( fit )
}
 
garchAuto = function(
xx,
min.order=c(0,0,1,1),
max.order=c(5,5,1,1),
trace=FALSE,
cond.dists="sged",
with.forecast=TRUE,
forecast.length=1,
arma.sum=c(0,1e9),
cores=1,
ic="AIC",
garch.model="garch" )
{
require( fGarch )
require( parallel )
 
len = NROW( xx )
 
models = list( )
 
for( dist in cond.dists )
for( p in min.order[1]:max.order[1] )
for( q in min.order[2]:max.order[2] )
for( r in min.order[3]:max.order[3] )
for( s in min.order[4]:max.order[4] )
{
pq.sum = p + q
if( pq.sum <= arma.sum[2] && pq.sum >= arma.sum[1] )
{
models[[length( models ) + 1]] = list( order=c( p, q, r, s ), dist=dist )
}
}
 
res = mclapply( models,
garchAutoTryFit,
data=xx,
trace=trace,
ic=ic,
garch.model=garch.model,
forecast.length=forecast.length,
with.forecast=TRUE,
mc.cores=cores )
 
best.fit = NULL
 
best.ic = 1e9
for( rr in res )
{
if( !is.null( rr ) )
{
current.ic = rr@fit$ics[[ic]]
if( current.ic < best.ic )
{
best.ic = current.ic
best.fit = rr
}
}
}
 
if( best.ic < 1e9 )
{
return( best.fit )
}
 
return( NULL )
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.