fGarch/0000755000176200001440000000000014557030206011446 5ustar liggesusersfGarch/NAMESPACE0000644000176200001440000000751414556273410012701 0ustar liggesusersuseDynLib("fGarch", .registration=TRUE) ## imports importFrom("timeDate", timeDate, timeSequence) importFrom("timeSeries", as.timeSeries, timeSeries ##, dummyDailySeries # in Examples and tests , description , isUnivariate, isMultivariate) importFrom("fBasics", Heaviside, jarqueberaTest ##, teffectPlot # used in test , dsnig, qsnig , volatility # we will re-export, as we define an S3 method , distCheck, .sliderMenu) ## importFrom("fastICA", fastICA)# only used in R/mgarch-FitFromFormula.R .gogarchFit() importFrom("cvar", VaR, ES) importFrom(Matrix, Matrix) # only in R/garch-Hessian.R importFrom("graphics", abline, grid, hist, legend, lines, par, polygon, title) importFrom("methods", new, show, slot, slotNames, is) importFrom("stats", Box.test, acf, arima, as.formula, ccf, tsdiag, density, dnorm, dt, filter, integrate, lm, model.frame, na.omit, nlminb, optim, optimHess, pchisq, pgamma, pnorm, ppoints, printCoefmat, pt, qgamma, qnorm, qt, quantile, rgamma, rnorm, rt, runif, sd, shapiro.test, summary.lm, terms, var) importFrom("utils", capture.output, menu) ## Exports S3method(print, summary_fGARCH) S3method(print, tsdiag_fGARCH) S3method(tsdiag, fGARCH) S3method(volatility, fGARCH) S3method(VaR, fGARCH) S3method(ES, fGARCH) exportClasses("fGARCH", "fGARCHSPEC", "fUGARCHSPEC" ) exportMethods("coef", "fitted", "formula", "plot", "predict", "residuals", "show", "summary", "update" ) export(volatility) # we import it from fBasics export(VaR, ES) # we import them from cvar export( ## export these '.xxx' for now ".gogarchFit", ".ugarchFit", ".ugarchSpec", "absMoments", "dged", "pged", "qged", "rged", "gedFit", "gedSlider", "dsged", "psged", "qsged", "rsged", "sgedFit", "sgedSlider", "dsnorm", "psnorm", "qsnorm", "rsnorm", "snormFit", "snormSlider", "dsstd", "psstd", "qsstd", "rsstd", "sstdFit", "sstdSlider", "dstd", "pstd", "qstd", "rstd", "stdFit", "stdSlider", "garchFit", "garchFitControl", "garchKappa", "garchSim", "garchSpec" ) ## ".aparchLLH.filter", ".aparchLLH.internal", ".aparchLLH.testing", ## ".gedFit", ".gedCondDist", ## ".QMLECondDist", ## ".normCondDist", ## ".dsged", ".psged", ".qsged", ".rsged", ".sgedFit", ".sgedCondDist", ## ".dsnorm", ".psnorm", ".qsnorm",".rsnorm", ".snormFit", ".snormCondDist", ## ".dsstd", ".psstd", ".qsstd", ".rsstd", ".sstdFit", ".sstdCondDist", ## ".stdFit", ".stdCondDist", ## ".snigCondDist", ## ".garchArgsParser", ## ".garchFit", ## ".garchInitParameters", ## ".garchInitSeries", ## ".garchKappaFun", ## ".garchLLH", ## ".garchModelSeries", ## ".garchNames", ## ".garchOptimizeLLH", ## ".garchOptimizerControl", ## ".garchRCDAGradient", ## ".garchRCDAHessian", ## ".garchRlbfgsb", ## ".garchRnlminb", ## ".garchRnm", ## ".garchRoptimhess", ## ".garchSetCondDist", ## ".garchTSHessian", ## ".getfGarchEnv", ".setfGarchEnv", ## ".hessian2sided", ## ".interactiveGarchPlot", ## GNB: these two may be worth exporting ## ".multGarchPlot", ## ".plot.garch.1", ## ".plot.garch.10", ## ".plot.garch.11", ## ".plot.garch.12", ## ".plot.garch.13", ## ".plot.garch.2", ## ".plot.garch.3", ## ".plot.garch.4", ## ".plot.garch.5", ## ".plot.garch.6", ## ".plot.garch.7", ## ".plot.garch.8", ## ".plot.garch.9", ## ".qqDist", ".qqLine", ## ".truePersistence", fGarch/ChangeLog0000755000176200001440000001433014263246022013223 0ustar liggesusers2013-04-30 chalabi * DESCRIPTION, R/zzz.R, src/llhGarch.f: fix array bound warning in Fortran code 2012-09-18 chalabi * ChangeLog, DESCRIPTION: Updated ChangeLog and DESC files. * DESCRIPTION: Changed maintainer field to comply with the new CRAN policy. * inst/unitTests/runit.garchSolver.R: Removed superfluous unitTest. * NAMESPACE, R/loglik-aparch.R: Removed .filter2() to avoid external .Call calls. 2012-06-04 chalabi * R/garch-Hessian.R, inst/unitTests/runit.garchSolver.R: using now optimHess to calculate the Hessian * ChangeLog, DESCRIPTION: updated DESCRIPTION and ChangeLog files * DESCRIPTION, R/garch-Hessian.R: using now optimHess to calculate the Hessian 2011-09-23 mmaechler * DESCRIPTION: remove deprecated "LazyLoad" entry 2010-10-26 chalabi * NAMESPACE: updated NAMESPACE 2010-07-23 chalabi * inst/DocCopying.pdf: removed DocCopying.pdf license is already specified in DESCRIPTION file 2010-04-14 chalabi * NAMESPACE: updated NAMESPACE 2009-12-08 wuertz * inst/unitTests/runit.snorm.R: norm test obsolete * NAMESPACE, R/absMoments.R, R/dist-norm.R, R/dist-normFit.R, R/dist-snig.R, R/dist-snigFit.R, R/dist-stdSlider.R, man/absMoments.Rd, man/dist-absMoments.Rd, man/dist-ged.Rd, man/dist-gedFit.Rd, man/dist-gedSlider.Rd, man/dist-sged.Rd, man/dist-sgedFit.Rd, man/dist-sgedSlider.Rd, man/dist-snorm.Rd, man/dist-snormFit.Rd, man/dist-snormSlider.Rd, man/dist-sstd.Rd, man/dist-sstdFit.Rd, man/dist-sstdSlider.Rd, man/dist-std.Rd, man/dist-stdFit.Rd, man/dist-stdSlider.Rd: distribution functions updated * R/dist-stdSlider.R: stdslider added 2009-12-07 wuertz * R/dist-absMoments.R, R/dist-ged.R, R/dist-gedFit.R, R/dist-gedSlider.R, R/dist-norm.R, R/dist-normFit.R, R/dist-sged.R, R/dist-sgedFit.R, R/dist-sgedSlider.R, R/dist-snig.R, R/dist-snigFit.R, R/dist-snorm.R, R/dist-snormFit.R, R/dist-snormSlider.R, R/dist-sstd.R, R/dist-sstdFit.R, R/dist-sstdSlider.R, R/dist-std.R, R/dist-stdFit.R: distribution functions updated * man/dist-ged.Rd, man/dist-gedFit.Rd, man/dist-gedSlider.Rd, man/dist-sged.Rd, man/dist-sgedFit.Rd, man/dist-sgedSlider.Rd, man/dist-snorm.Rd, man/dist-sstd.Rd, man/sged.Rd, man/snorm.Rd, man/sstd.Rd: man pages updated 2009-11-09 chalabi * DESCRIPTION: updated version number * ChangeLog, DESCRIPTION: updated DESC and Changelog file 2009-11-05 chalabi * R/methods-predict.R: small changes in predict,fGARCH-method to correct its output when n.ahead=1 since addition of conditional errors. 2009-09-28 chalabi * DESCRIPTION: updated version number * ChangeLog, DESCRIPTION: updated DESCR and ChangeLog 2009-08-21 wuertz * DESCRIPTION, NAMESPACE, R/methods-plot.R, R/methods-show.R, R/mgarch-FitFromFormula.R: .gogarchFit function added, show and plot adapted, NAMESPACE and DESCRIPTION updated * R/methods-plot.R: Merge branch 'devel-fGarch' * man/methods-predict.Rd: cosmetic changes in help page * NAMESPACE: new NAMESPACE structure which should ease maintenance of packages. 2009-06-25 chalabi * DESCRIPTION, NAMESPACE: Merge branch 'devel-timeSeries' Conflicts: pkg/timeSeries/R/base-Extract.R pkg/timeSeries/R/timeSeries.R 2009-05-21 wuertz * NAMESPACE, R/garch-Distribution.R, R/garch-FitFromFormula.R, R/garch-FitFromSpec.R, R/garch-FitInternal.R, R/garch-LogLik.R, R/loglik-aparch.R, R/loglik-egarch.R, R/loglik.R, man/garchFit.Rd: working on new specification * DESCRIPTION, R/garch-Distribution.R, R/garch-FitFromFormula.R, R/garch-FitInternal.R, R/garch-Hessian.R, R/garch-LogLik.R, R/garch-Solver.R, man/garchFit.Rd: different recursion methods added, new method to calculate hessian added * R/garch-FitInternal.R, R/garch-LogLik.R: LLH function disentangled in shorter parts 2009-05-20 wuertz * R/garch-FitFromFormula.R, R/garch-FitFromSpec.R, R/garch-FitInternal.R: alternative garchFit interface (still hidden) now runs * NAMESPACE, R/fGarchEnv.R, R/garch-FitFromFormula.R: NAMESPACE updated * R/garch-FitFormula.R, R/garch-FitFromFormula.R, R/garch-FitInternal.R: R scripts disentangled and renamed * R/garch-FitFromFormula.R: script file renamed * R/garch-Fit.R, R/garch-FitControl.R, R/garch-FitFormula.R, R/garch-FitFromSpec.R, R/garch-FitInternal.R, R/garch-GlobalVars.R, R/garch-SolverControl.R: new interface for garchFit added, spec() based * NAMESPACE, R/garch-Distribution.R, R/garch-LogLik.R: some smaller fixes and NAMESPACE adapted * R/garch-Fit.R, R/garch-LogLik.R: garchLogLIk disentangled from script file garch-Fit.R * R/garch-Distribution.R, R/garch-Fit.R, R/garch-Initialization.R: Initialization disentangled from garch-Fit script file * R/dist-sged.R, R/dist-snig.R, R/dist-snorm.R, R/dist-sstd.R, R/garch-Distribution.R, R/garch-Fit.R, R/garch-FitControl.R, R/garch-Gradient.R, R/garch-Hessian.R, R/garch-Sim.R, R/garch-Solver.R, R/garch-Spec.R, R/garch-Stats.R, R/garchFit.R, R/garchFitControl.R, R/garchGradient.R, R/garchHessian.R, R/garchSim.R, R/garchSolver.R, R/garchSpec.R, R/garchStats.R, R/sged.R, R/snorm.R, R/sstd.R: script file renamed and disentangled 2009-05-15 chaussep * R/methods-predict.R, man/methods-predict.Rd: added a plot option to predict and adapted the manual 2009-05-15 chalabi * DESCRIPTION: added Pierre Chausse in DESC file for contribution 2009-05-14 chaussep * R/garchSim.R, man/garchSim.Rd: Just changed the definition of mu. It is the intercept, not the mean * R/methods-predict.R, man/methods-predict.Rd: Added conditional errors to predict and updated nthe manual 2009-04-19 chalabi * DESCRIPTION: added explicit version number in Depends field for key packages 2009-04-02 chalabi * DESCRIPTION: more explicit depends and suggests field in DESC file. 2009-04-01 chalabi * DESCRIPTION: updated DESC file 2009-01-30 chalabi * R/garchSpec.R: 2009-01-28 chalabi * DESCRIPTION: updated version number * DESCRIPTION: changed version number to match version on CRAN + 1 2009-01-12 chalabi * NAMESPACE, R/methods-update.R, man/class-fGARCH.Rd, man/class-fGARCHSPEC.Rd: added update method for fGARCH and fGARCHSPEC object 2009-01-07 chalabi * src/dist.f: fixed conditional distribution thanks to comments of Michal Miklovic. fGarch/README.md0000755000176200001440000000372114327154431012735 0ustar liggesusers [![CRANStatusBadge](http://www.r-pkg.org/badges/version/fGarch)](https://cran.r-project.org/package=fGarch) [![CRAN RStudio mirror downloads](https://cranlogs.r-pkg.org/badges/fGarch)](https://www.r-pkg.org/pkg/fGarch) [![CRAN RStudio mirror downloads](https://cranlogs.r-pkg.org/badges/grand-total/fGarch?color=blue)](https://r-pkg.org/pkg/fGarch) Analyze and model heteroskedastic behavior in financial time series with GARCH, APARCH and related models. Package `fGarch` is part of the Rmetrics suite of R packages and is developed on R-forge at [fGarch devel](https://r-forge.r-project.org/scm/viewvc.php/pkg/fGarch/?root=rmetrics). The root of Rmetrics is at [R-forge](https://r-forge.r-project.org/projects/rmetrics). # Installing fGarch Install the [latest stable version](https://cran.r-project.org/package=fGarch) of `fGarch` from CRAN: install.packages("fGarch") You can install the [development version](https://r-forge.r-project.org/scm/viewvc.php/pkg/fGarch/?root=rmetrics) of `fGarch` from R-forge: install.packages("fGarch", repos = "http://R-Forge.R-project.org") To report bugs visit [Rmetrics](https://r-forge.r-project.org/projects/rmetrics/). # Documentation You can view the documentation of `fGarch` at [fGarchDoc](https://geobosh.github.io/fGarchDoc/) or download the [reference manual](https://cran.r-project.org/package=fGarch/fGarch.pdf) of the latest release from CRAN. A comprehensive overview of the models and conditional distributions employed in package `fGarch`, along with worked examples, is available in the following paper by the original authors of the package: [WurtzEtAlGarch.pdf](https://github.com/GeoBosh/fGarchDoc/blob/master/WurtzEtAlGarch.pdf). (*This is an unpublished manuscript. Some online sources, confusingly, attribute it to JSS, vol 55, issue 2, but this seems to have taken the placeholders `VV` and `II` in the heading on the first page as being the Roman numbers 55 and 2.*) fGarch/data/0000755000176200001440000000000014556735643012377 5ustar liggesusersfGarch/data/sp500dge.csv.gz0000644000176200001440000016043414556735643015072 0ustar liggesuserslI$IEzD}4 Y27SUacR)[罼k]mc-~o{Ylѹmş}swh}y~w|j}rͿ}W99zr{}_n /⻭9g(wqgvㇷ\ݭ=V8m8vp!*pxNtosՎθ|~X ȖG(q",=5{45_qX:Θz,d.%;:7J *p7lV;\`ę̑=vj aG)V5%]("O\dgq=EvpX"RLZbZAHEj7]ys!d E\yv2q8ۂ@9% 7 q-{q'ii/)gSqlY{rHV~cwh1})UGiFi[fƤ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kbadNwKk@fGarch/man/0000755000176200001440000000000014556733064012234 5ustar liggesusersfGarch/man/garchFitControl.Rd0000755000176200001440000001603414327171013015604 0ustar liggesusers\name{garchFitControl} \alias{garchFitControl} \title{Control GARCH fitting algorithms} \description{ Control parameters for the GARCH fitting algorithms. } \usage{ garchFitControl( llh = c("filter", "internal", "testing"), nlminb.eval.max = 2000, nlminb.iter.max = 1500, nlminb.abs.tol = 1.0e-20, nlminb.rel.tol = 1.0e-14, nlminb.x.tol = 1.0e-14, nlminb.step.min = 2.2e-14, nlminb.scale = 1, nlminb.fscale = FALSE, nlminb.xscale = FALSE, sqp.mit = 200, sqp.mfv = 500, sqp.met = 2, sqp.mec = 2, sqp.mer = 1, sqp.mes = 4, sqp.xmax = 1.0e3, sqp.tolx = 1.0e-16, sqp.tolc = 1.0e-6, sqp.tolg = 1.0e-6, sqp.told = 1.0e-6, sqp.tols = 1.0e-4, sqp.rpf = 1.0e-4, lbfgsb.REPORT = 10, lbfgsb.lmm = 20, lbfgsb.pgtol = 1e-14, lbfgsb.factr = 1, lbfgsb.fnscale = FALSE, lbfgsb.parscale = FALSE, nm.ndeps = 1e-14, nm.maxit = 10000, nm.abstol = 1e-14, nm.reltol = 1e-14, nm.alpha = 1.0, nm.beta = 0.5, nm.gamma = 2.0, nm.fnscale = FALSE, nm.parscale = FALSE) } \arguments{ % In general: \item{llh}{ \code{llh = c("filter", "internal", "testing")[1]}, defaults to \code{"filter"}. } % nlminb: \item{nlminb.eval.max}{ maximum number of evaluations of the objective function, defaults to 200. } \item{nlminb.iter.max}{ maximum number of iterations, defaults to 150. } %\item{nlminb.trace}{ % The value of the objective function and the parameters is % printed every trace'th iteration. Defaults to 0 which % indicates no trace information is to be printed. % } \item{nlminb.abs.tol}{ absolute tolerance, defaults to 1e-20. } \item{nlminb.rel.tol}{ relative tolerance, defaults to 1e-10. } \item{nlminb.x.tol}{ X tolerance, defaults to 1.5e-8. } \item{nlminb.fscale}{ defaults to FALSE. } \item{nlminb.xscale}{ defaulkts to FALSE. } \item{nlminb.step.min}{ minimum step size, defaults to 2.2e-14. } \item{nlminb.scale}{ defaults to 1. } % sqp: %\item{sqp.iprnt}{ % as.integer(trace). Default to 1. % } \item{sqp.mit}{ maximum number of iterations, defaults to 200. } \item{sqp.mfv}{ maximum number of function evaluations, defaults to 500. } \item{sqp.met}{ specifies scaling strategy:\cr sqp.met=1 - no scaling,\cr sqp.met=2 - preliminary scaling in 1st iteration (default),\cr sqp.met=3 - controlled scaling,\cr sqp.met=4 - interval scaling,\cr sqp.met=5 - permanent scaling in all iterations. } \item{sqp.mec}{ correction for negative curvature:\cr sqp.mec=1 - no correction,\cr sqp.mec=2 - Powell correction (default). } \item{sqp.mer}{ restarts after unsuccessful variable metric updates:\cr sqp.mer=0 - no restarts,\cr sqp.mer=1 - standard restart. } \item{sqp.mes}{ interpolation method selection in a line search:\cr sqp.mes=1 - bisection,\cr sqp.mes=2 - two point quadratic interpolation,\cr sqp.mes=3 - three point quadratic interpolation,\cr sqp.mes=4 - three point cubic interpolation (default). } \item{sqp.xmax}{ maximum stepsize, defaults to 1.0e+3. } \item{sqp.tolx}{ tolerance for the change of the coordinate vector, defaults to 1.0e-16. } \item{sqp.tolc}{ tolerance for the constraint violation, defaults to 1.0e-6. } \item{sqp.tolg}{ tolerance for the Lagrangian function gradient, defaults to 1.0e-6. } \item{sqp.told}{ defaults to 1.0e-6. } \item{sqp.tols}{ defaults to 1.0e-4. } \item{sqp.rpf}{ value of the penalty coefficient, default to1.0D-4. The default velue may be relatively small. Therefore, larger value, say one, can sometimes be more suitable. } % optim[lbfgsb]: \item{lbfgsb.REPORT}{ the frequency of reports for the \code{"BFGS"} and \code{"L-BFGS-B"} methods if \code{control$trace} is positive. Defaults to every 10 iterations. } \item{lbfgsb.lmm}{ an integer giving the number of BFGS updates retained in the \code{"L-BFGS-B"} method, It defaults to 5. } \item{lbfgsb.factr}{ controls the convergence of the \code{"L-BFGS-B"} method. Convergence occurs when the reduction in the objective is within this factor of the machine tolerance. Default is 1e7, that is a tolerance of about 1.0e-8. } \item{lbfgsb.pgtol}{ helps control the convergence of the \code{"L-BFGS-B"} method. It is a tolerance on the projected gradient in the current search direction. This defaults to zero, when the check is suppressed. } \item{lbfgsb.fnscale}{ defaults to FALSE. } \item{lbfgsb.parscale}{ defaults to FALSE. } % optim[nm]: %\item{nm.trace}{ % Non-negative integer. If positive, tracing information on the % progress of the optimization is produced. Higher values may % produce more tracing information: for method "L-BFGS-B" there % are six levels of tracing. (To understand exactly what these % do see the source code: higher levels give more detail.) % } \item{nm.ndeps}{ a vector of step sizes for the finite-difference approximation to the gradient, on par/parscale scale. Defaults to 1e-3. } \item{nm.maxit}{ the maximum number of iterations. Defaults to 100 for the derivative-based methods, and 500 for \code{"Nelder-Mead"}. For \code{"SANN"} maxit gives the total number of function evaluations. There is no other stopping criterion. Defaults to 10000. } \item{nm.abstol}{ the absolute convergence tolerance. Only useful for non-negative functions, as a tolerance for reaching zero. } \item{nm.reltol}{ relative convergence tolerance. The algorithm stops if it is unable to reduce the value by a factor of \code{reltol * (abs(val) + reltol)} at a step. Defaults to \code{sqrt(.Machine$double.eps)}, typically about 1e-8. } \item{nm.alpha, nm.beta, nm.gamma}{ scaling parameters for the "Nelder-Mead" method. alpha is the reflection factor (default 1.0), beta the contraction factor (0.5), and gamma the expansion factor (2.0). } \item{nm.fnscale}{ an overall scaling to be applied to the value of fn and gr during optimization. If negative, turns the problem into a maximization problem. Optimization is performed on \code{fn(par) / nm.fnscale}. } \item{nm.parscale}{ a vector of scaling values for the parameters. Optimization is performed on par/parscale and these should be comparable in the sense that a unit change in any element produces about a unit change in the scaled value. } } \value{ a list } \author{ Diethelm Wuertz for the Rmetrics \R-port,\cr R Core Team for the 'optim' \R-port,\cr Douglas Bates and Deepayan Sarkar for the 'nlminb' \R-port,\cr Bell-Labs for the underlying PORT Library,\cr Ladislav Luksan for the underlying Fortran SQP Routine, \cr Zhu, Byrd, Lu-Chen and Nocedal for the underlying L-BFGS-B Routine. } \seealso{ \code{\link{garchFit}} } \examples{ ## } \keyword{models} fGarch/man/class-fGARCH.Rd0000755000176200001440000000751514327215302014615 0ustar liggesusers\name{fGARCH-class} \alias{fGARCH-class} \docType{class} \alias{show,fGARCH-method} \alias{update,fGARCH-method} \concept{GARCH model} \concept{APARCH model} \concept{ARMA-GARCH model} \concept{ARMA-APARCH model} \concept{AR-GARCH model} \concept{AR-APARCH model} \concept{MA-GARCH model} \concept{MA-APARCH model} \title{Class "fGARCH"} \description{ The class 'fGARCH' represents a model of an heteroskedastic time series process. } \section{Objects from the Class}{ Objects can be created by calls of the function \code{garchFit}. This object is a parameter estimate of an empirical GARCH process. } \section{Slots}{ \describe{ \item{\code{call}:}{Object of class \code{"call"}: the call of the \code{garch} function. } \item{\code{formula}:}{Object of class \code{"formula"}: a formula object specifying the mean and variance equations. } \item{\code{method}:}{Object of class \code{"character"}: a string denoting the optimization method, by default \code{"Max Log-Likelihood Estimation"}. } \item{\code{data}:}{Object of class \code{"list"}: a list with one entry named \code{x}, containing the data of the time series to be estimated, the same as given by the input argument \code{series}. } \item{\code{fit}:}{Object of class \code{"list"}: a list with the results from the parameter estimation. The entries of the list depend on the selected algorithm, see below. } \item{\code{residuals}:}{Object of class \code{"numeric"}: a numeric vector with the (raw, unstandardized) residual values. } \item{\code{fitted}:}{Object of class \code{"numeric"}: a numeric vector with the fitted values. } \item{\code{h.t}:}{Object of class \code{"numeric"}: a numeric vector with the conditional variances (\eqn{h_t = \sigma_t^\delta}{h.t = sigma.t^delta}). } \item{\code{sigma.t}:}{Object of class \code{"numeric"}: a numeric vector with the conditional standard deviations. } \item{\code{title}:}{Object of class \code{"character"}: a title string. } \item{\code{description}:}{Object of class \code{"character"}: a string with a brief description. } } } \section{Methods}{ \describe{ \item{plot}{\code{signature(x = "fGARCH", y = "missing")}: plots an object of class \code{"fGARCH"}. } \item{show}{\code{signature(object = "fGARCH")}: prints an object of class \code{"fGARCH"}. } \item{summary}{\code{signature(object = "fGARCH")}: summarizes an object of class \code{"fGARCH"}. } \item{predict}{\code{signature(object = "fGARCH")}: forecasts mean and volatility from an object of class \code{"fGARCH"}. } \item{fitted}{\code{signature(object = "fGARCH")}: extracts fitted values from an object of class \code{"fGARCH"}. } \item{residuals}{\code{signature(object = "fGARCH")}: extracts fresiduals from an object of class \code{"fGARCH"}. } \item{volatility}{\code{signature(object = "fGARCH")}: extracts conditional volatility from an object of class \code{"fGARCH"}. } \item{coef}{\code{signature(object = "fGARCH")}: extracts fitted coefficients from an object of class \code{"fGARCH"}. } \item{formula}{\code{signature(x = "fGARCH")}: extracts formula expression from an object of class \code{"fGARCH"}. } } } \author{ Diethelm Wuertz and Rmetrics Core Team } \seealso{ \code{\link{garchFit}}, \code{\link{garchSpec}}, \code{\link{garchFitControl}} } \examples{ ## simulate a time series, fit a GARCH(1,1) model, and show it: x <- garchSim( garchSpec(), n = 500) fit <- garchFit(~ garch(1, 1), data = x, trace = FALSE) fit # == print(fit) and also == show(fit) } \keyword{programming} \keyword{ts} fGarch/man/dist-sged.Rd0000755000176200001440000000540214437715560014411 0ustar liggesusers\name{sged} \alias{sged} \alias{dsged} \alias{psged} \alias{qsged} \alias{rsged} \concept{standardized skew GED distribution} \concept{skew GED distribution} \concept{skewed GED distribution} \concept{skew distribution} \concept{skewed distribution} \title{Skew generalized error distribution} \description{ Functions to compute density, distribution function, quantile function and to generate random variates for the skew generalized error distribution. } \usage{ dsged(x, mean = 0, sd = 1, nu = 2, xi = 1.5, log = FALSE) psged(q, mean = 0, sd = 1, nu = 2, xi = 1.5) qsged(p, mean = 0, sd = 1, nu = 2, xi = 1.5) rsged(n, mean = 0, sd = 1, nu = 2, xi = 1.5) } \arguments{ \item{mean, sd, nu, xi}{ location parameter \code{mean}, scale parameter \code{sd}, shape parameter \code{nu}, skewness parameter \code{xi}. } \item{n}{ the number of observations. } \item{p}{ a numeric vector of probabilities. } \item{x, q}{ a numeric vector of quantiles. } \item{log}{ a logical; if TRUE, densities are given as log densities. } } \details{ The distribution is standardized as discussed in the reference by Wuertz et al below. } \value{ \code{d*} returns the density, \code{p*} returns the distribution function, \code{q*} returns the quantile function, and \code{r*} generates random deviates, \cr all values are numeric vectors. } \references{ Nelson D.B. (1991); \emph{Conditional Heteroscedasticity in Asset Returns: A New Approach}, Econometrica, 59, 347--370. Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. Wuertz D., Chalabi Y. and Luksan L. (????); \emph{Parameter estimation of ARMA models with GARCH/APARCH errors: An R and SPlus software implementation}, Preprint, 41 pages, \url{https://github.com/GeoBosh/fGarchDoc/blob/master/WurtzEtAlGarch.pdf} } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{sgedFit}} (fit), \code{\link{sgedSlider}} (visualize), \code{\link{ged}} (symmetric GED) } \examples{ ## sged - par(mfrow = c(2, 2)) set.seed(1953) r = rsged(n = 1000) plot(r, type = "l", main = "sged", col = "steelblue") # Plot empirical density and compare with true density: hist(r, n = 25, probability = TRUE, border = "white", col = "steelblue") box() x = seq(min(r), max(r), length = 201) lines(x, dsged(x), lwd = 2) # Plot df and compare with true df: plot(sort(r), (1:1000/1000), main = "Probability", col = "steelblue", ylab = "Probability") lines(x, psged(x), lwd = 2) # Compute quantiles: round(qsged(psged(q = seq(-1, 5, by = 1))), digits = 6) } \keyword{distribution} fGarch/man/methods-fitted.Rd0000755000176200001440000000153214437605312015437 0ustar liggesusers\name{fitted-methods} \alias{fitted-methods} \docType{methods} \alias{fitted} \alias{fitted,fGARCH-method} \title{Extract GARCH model fitted values} \description{ Extracts fitted values from a fitted GARCH object. } \section{Methods}{ Methods for \code{fitted} defined in package \pkg{fGarch}: \describe{ \item{object = "fGARCH"}{ Extractor function for fitted values. } } } \details{ The method for \code{"fGARCH"} objects extracts the \code{@fitted} value slot from an object of class \code{"fGARCH"} as returned by the function \code{garchFit}. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{predict}}, \code{\link{residuals}}, \code{\link{garchFit}}, class \code{\linkS4class{fGARCH}}, \code{\link{plot}} } \examples{ ## see examples for 'residuals()' } \keyword{models} fGarch/man/dist-std.Rd0000644000176200001440000000607014523720236014250 0ustar liggesusers\name{std} \alias{std} \alias{dstd} \alias{pstd} \alias{qstd} \alias{rstd} \concept{t-distribution} \concept{Student-t distribution} \concept{standardized Student t distribution} \concept{standardized Student t-distribution} \title{Standardized Student-t distribution} \description{ Functions to compute density, distribution function, quantile function and to generate random variates for the standardized Student-t distribution. } \usage{ dstd(x, mean = 0, sd = 1, nu = 5, log = FALSE) pstd(q, mean = 0, sd = 1, nu = 5) qstd(p, mean = 0, sd = 1, nu = 5) rstd(n, mean = 0, sd = 1, nu = 5) } \arguments{ \item{x, q}{ a numeric vector of quantiles. } \item{p}{ a numeric vector of probabilities. } \item{n}{ number of observations to simulate. } \item{mean}{ location parameter. } \item{sd}{ scale parameter. } \item{nu}{ shape parameter (degrees of freedom). } \item{log}{ logical; if \code{TRUE}, densities are given as log densities. } } \details{ The standardized Student-t distribution is defined so that for a given \code{sd} it has the same variance, \code{sd^2}, for all degrees of freedom. For comparison, the variance of the usual Student-t distribution is \code{nu/(nu-2)}, where \code{nu} is the degrees of freedom. The usual Student-t distribution is obtained by setting \code{sd = sqrt(nu/(nu - 2))}. Argument \code{nu} must be greater than 2. Although there is a default value for \code{nu}, it is rather arbitrary and relying on it is strongly discouraged. \code{dstd} computes the density, \code{pstd} the distribution function, \code{qstd} the quantile function, and \code{rstd} generates random deviates from the standardized-t distribution with the specified parameters. } \value{ numeric vector } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. Wuertz D., Chalabi Y. and Luksan L. (2006); \emph{Parameter estimation of ARMA models with GARCH/APARCH errors: An R and SPlus software implementation}, Preprint, 41 pages, \url{https://github.com/GeoBosh/fGarchDoc/blob/master/WurtzEtAlGarch.pdf} } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{stdFit}} (fit). \code{\link{stdSlider}} (visualize), \code{\link{absMoments}} } \examples{ ## std - pstd(1, sd = sqrt(5/(5-2)), nu = 5) == pt(1, df = 5) # TRUE par(mfrow = c(2, 2)) set.seed(1953) r = rstd(n = 1000) plot(r, type = "l", main = "sstd", col = "steelblue") # Plot empirical density and compare with true density: hist(r, n = 25, probability = TRUE, border = "white", col = "steelblue") box() x = seq(min(r), max(r), length = 201) lines(x, dstd(x), lwd = 2) # Plot df and compare with true df: plot(sort(r), (1:1000/1000), main = "Probability", col = "steelblue", ylab = "Probability") lines(x, pstd(x), lwd = 2) # Compute quantiles: round(qstd(pstd(q = seq(-1, 5, by = 1))), digits = 6) } \keyword{distribution} fGarch/man/methods-plot.Rd0000755000176200001440000000407414441607514015143 0ustar liggesusers\name{plot-methods} \alias{plot-methods} \docType{methods} \alias{plot} \alias{plot,fGARCH,missing-method} \concept{GARCH diagnostics} \concept{GARCH goodness=of-fit} \title{GARCH plot methods} \description{ Plot methods for GARCH modelling. } \usage{ \S4method{plot}{fGARCH,missing}(x, which = "ask", \dots) } \arguments{ \item{x}{ an object of class \code{"fGARCH"}. } \item{which}{ a character string or a vector of positive denoting which plot should be displayed, see section \sQuote{Details}. } \item{\dots}{ optional arguments to be passed. } } \details{ The \code{plot} method for \code{"fGARCH"} objects offers a selection of diagnostic, exploratory, and presentation plots from a menu. Argument \code{which} can be used to request specific plots, which is particularly useful in scripts. The generic function \code{plot} allows to display 13 graphs: \tabular{l}{ Time SeriesPlot\cr Conditional Standard Deviation Plot\cr Series Plot with 2 Conditional SD Superimposed\cr Autocorrelation function Plot of Observations\cr Autocorrelation function Plot of Squared Observations\cr Cross Correlation Plot\cr Residuals Plot\cr Conditional Standard Deviations Plot\cr Standardized Residuals Plot\cr ACF Plot of Standardized Residuals\cr ACF Plot of Squared Standardized Residuals\cr Cross Correlation Plot between $r^2$ and r\cr Quantile-Quantile Plot of Standardized Residuals } } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link[=tsdiag.fGARCH]{fGARCH}} method for \code{tsdiag}, \code{\link{garchFit}}, class \code{\linkS4class{fGARCH}}, \code{\link{predict}}, \code{\link{fitted}}, \code{\link{residuals}} \code{\link{plot}} } \examples{ ## garchSim - # Default Garch(1,1) Model: x = garchSim(n = 200) head(x) ## garchFit - fit = garchFit(formula = ~ garch(1, 1), data = x, trace = FALSE) ## Batch Plot: plot(fit, which = 3) \dontrun{ ## Plot: # Interactive Plot: plot(fit) } } \keyword{models} fGarch/man/dist-snorm.Rd0000755000176200001440000000466314437715644014640 0ustar liggesusers\name{snorm} \alias{snorm} \alias{dsnorm} \alias{psnorm} \alias{qsnorm} \alias{rsnorm} \concept{skewed normal distribution} \concept{skew distribution} \concept{skewed distribution} \title{Skew normal distribution} \description{ Functions to compute density, distribution function, quantile function and to generate random variates for the skew normal distribution. The distribution is standardized as discussed in the reference by Wuertz et al below. } \usage{ dsnorm(x, mean = 0, sd = 1, xi = 1.5, log = FALSE) psnorm(q, mean = 0, sd = 1, xi = 1.5) qsnorm(p, mean = 0, sd = 1, xi = 1.5) rsnorm(n, mean = 0, sd = 1, xi = 1.5) } \arguments{ \item{x, q}{a numeric vector of quantiles.} \item{p}{a numeric vector of probabilities.} \item{n}{the number of observations.} \item{mean}{location parameter.} \item{sd}{scale parameter.} \item{xi}{skewness parameter.} \item{log}{a logical; if TRUE, densities are given as log densities.} } \details{ \code{dsnorm} computed the density, \code{psnorm} the distribution function, \code{qsnorm} the quantile function, and \code{rsnorm} generates random deviates. } \value{ numeric vector } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. Wuertz D., Chalabi Y. and Luksan L. (????); \emph{Parameter estimation of ARMA models with GARCH/APARCH errors: An R and SPlus software implementation}, Preprint, 41 pages, \url{https://github.com/GeoBosh/fGarchDoc/blob/master/WurtzEtAlGarch.pdf} } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{snormFit}} (fit), \code{\link{snormSlider}} (visualize), \code{\link{sstd}} (skew Student-t), \code{\link{sged}} (skew GED) } \examples{ ## snorm - # Ranbdom Numbers: par(mfrow = c(2, 2)) set.seed(1953) r = rsnorm(n = 1000) plot(r, type = "l", main = "snorm", col = "steelblue") # Plot empirical density and compare with true density: hist(r, n = 25, probability = TRUE, border = "white", col = "steelblue") box() x = seq(min(r), max(r), length = 201) lines(x, dsnorm(x), lwd = 2) # Plot df and compare with true df: plot(sort(r), (1:1000/1000), main = "Probability", col = "steelblue", ylab = "Probability") lines(x, psnorm(x), lwd = 2) # Compute quantiles: round(qsnorm(psnorm(q = seq(-1, 5, by = 1))), digits = 6) } \keyword{distribution} fGarch/man/methods-coef.Rd0000755000176200001440000000222214327207166015074 0ustar liggesusers\name{coef-methods} \alias{coef-methods} \docType{methods} \alias{coef} \alias{coef,fGARCH-method} \alias{coef,fGARCHSPEC-method} \title{GARCH coefficients methods} \description{ Coefficients methods \code{coef()} for GARCH Models. } \section{Methods}{ Methods for \code{coef} defined in package \pkg{fGarch}: \describe{ \item{object = "fGARCH"}{ Extractor function for coefficients from a fitted GARCH model. } \item{object = "fGARCHSPEC"}{ Extractor function for coefficients from a GARCH specification structure. } } } \note{ \code{\link{coef}} is a generic function which extracts coefficients from objects returned by modeling functions. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \examples{ ## garchSpec - # Use default parameters beside alpha: spec = garchSpec(model = list(alpha = c(0.05, 0.05))) spec coef(spec) ## garchSim - # Simulate an univariate "timeSeries" series from specification 'spec': x = garchSim(spec, n = 2000) x = x[,1] ## garchFit -- fit = garchFit( ~ garch(1, 1), data = x, trace = FALSE) ## coef - coef(fit) } \keyword{models} fGarch/man/methods-volatility.Rd0000755000176200001440000000567214440431152016362 0ustar liggesusers\name{volatility-methods} \docType{methods} \alias{volatility}% S3 method now \alias{volatility.fGARCH}% S3 method now \title{Extract GARCH model volatility} \description{ Extracts volatility from a fitted GARCH object. } \usage{ \S3method{volatility}{fGARCH}(object, type = c("sigma", "h"), \dots) } \arguments{ \item{object}{ an object of class \code{"fGARCH"} as returned by \code{\link{garchFit}()}. } \item{type}{ a character string denoting if the conditional standard deviations \code{"sigma"} or the variances \code{"h"} should be returned. } \item{\dots}{currently not used.} } \details{ \code{volatility} is an S3 generic function for computation of volatility, see \code{\link[fBasics]{volatility}} for the default method. The method for \code{"fGARCH"} objects, described here, extracts the volatility from slot \code{@sigma.t} or \code{@h.t} of an \code{"fGARCH"} object usually obtained from the function \code{\link{garchFit}()}. The class of the returned value depends on the input to the function \code{garchFit} who created the object. The returned value is always of the same class as the input object to the argument \code{data} in the function \code{garchFit}, i.e. if you fit a \code{"timeSeries"} object, you will get back from the function \code{fitted} also a \code{"timeSeries"} object, if you fit an object of class \code{"zoo"}, you will get back again a \code{"zoo"} object. The same holds for a \code{"numeric"} vector, for a \code{"data.frame"}, and for objects of class \code{"ts", "mts"}. In contrast, the slot itself always contains a numeric vector, independently of the class of the input data input, i.e. the function call \code{slot(object, "fitted")} will return a numeric vector. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \note{ (GNB) Contrary to the description of the returned value of the \code{"fGARCH"} method, it is always \code{"numeric"}. TODO: either implement the documented behaviour or fix the documentation. } \section{Methods}{ Methods for \code{volatility} defined in package \pkg{fGarch}: \describe{ \item{object = "fGARCH"}{ Extractor function for volatility or standard deviation from an object of class \code{"fGARCH"}. } } } \seealso{ \code{\link{garchFit}}, class \code{\linkS4class{fGARCH}} } \examples{ ## Swiss Pension fund Index - stopifnot(require("timeSeries")) # need package 'timeSeries' x = as.timeSeries(data(LPP2005REC, package = "timeSeries")) ## garchFit fit = garchFit(LPP40 ~ garch(1, 1), data = 100*x, trace = FALSE) fit ## volatility - # Standard Deviation: vola = volatility(fit, type = "sigma") head(vola) class(vola) # Variance: vola = volatility(fit, type = "h") head(vola) class(vola) ## slot - vola = slot(fit, "sigma.t") head(vola) class(vola) vola = slot(fit, "h.t") head(vola) class(vola) } \keyword{models} fGarch/man/dist-gedSlider.Rd0000755000176200001440000000201214326162521015351 0ustar liggesusers\name{gedSlider} \alias{gedSlider} \title{Generalized error distribution slider} \description{ Displays interactively the dependence of the GED distribution on its parameters. } \usage{ gedSlider(type = c("dist", "rand")) } \arguments{ \item{type}{ a character string denoting which interactive plot should be displayed. Either a distribution plot \code{type = "dist"}, the default value, or a random variates plot, \code{type = "rand"}. } } \value{ a Tcl object } \references{ Nelson D.B. (1991); \emph{Conditional Heteroscedasticity in Asset Returns: A New Approach}, Econometrica, 59, 347--370. Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{ged}}, \code{\link{gedFit}} } \examples{ \dontrun{ ## gedSlider - require(tcltk) gedSlider("dist") gedSlider("rand") } } \keyword{distribution} fGarch/man/dist-ged.Rd0000755000176200001440000000536314437715113014226 0ustar liggesusers\name{ged} \alias{ged} \alias{dged} \alias{pged} \alias{qged} \alias{rged} \concept{standardized GED distribution} \concept{GED distribution} \title{Standardized generalized error distribution} \description{ Functions to compute density, distribution function, quantile function and to generate random variates for the standardized generalized error distribution. } \usage{ dged(x, mean = 0, sd = 1, nu = 2, log = FALSE) pged(q, mean = 0, sd = 1, nu = 2) qged(p, mean = 0, sd = 1, nu = 2) rged(n, mean = 0, sd = 1, nu = 2) } \arguments{ \item{x, q}{ a numeric vector of quantiles. } \item{p}{ a numeric vector of probabilities. } \item{n}{ number of observations to simulate. } \item{mean}{ location parameter. } \item{sd}{ scale parameter. } \item{nu}{ shape parameter. } \item{log}{ logical; if \code{TRUE}, densities are given as log densities. } } \details{ The standardized GED is defined so that for a given \code{sd} it has the same variance, \code{sd^2}, for all values of the shape parameter, see the reference by Wuertz et al below. \code{dged} computes the density, \code{pged} the distribution function, \code{qged} the quantile function, and \code{rged} generates random deviates from the standardized-t distribution with the specified parameters. } \value{ numeric vector } \references{ Nelson D.B. (1991); \emph{Conditional Heteroscedasticity in Asset Returns: A New Approach}, Econometrica, 59, 347--370. Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. Wuertz D., Chalabi Y. and Luksan L. (????); \emph{Parameter estimation of ARMA models with GARCH/APARCH errors: An R and SPlus software implementation}, Preprint, 41 pages, \url{https://github.com/GeoBosh/fGarchDoc/blob/master/WurtzEtAlGarch.pdf} } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{gedFit}}, \code{\link{absMoments}}, \code{\link{sged}} (skew GED), \code{\link{gedSlider}} for visualization } \examples{ ## sged - par(mfrow = c(2, 2)) set.seed(1953) r = rsged(n = 1000) plot(r, type = "l", main = "sged", col = "steelblue") # Plot empirical density and compare with true density: hist(r, n = 25, probability = TRUE, border = "white", col = "steelblue") box() x = seq(min(r), max(r), length = 201) lines(x, dsged(x), lwd = 2) # Plot df and compare with true df: plot(sort(r), (1:1000/1000), main = "Probability", col = "steelblue", ylab = "Probability") lines(x, psged(x), lwd = 2) # Compute quantiles: round(qsged(psged(q = seq(-1, 5, by = 1))), digits = 6) } \keyword{distribution} fGarch/man/dist-sgedSlider.Rd0000755000176200001440000000201714326165267015553 0ustar liggesusers\name{sgedSlider} \alias{sgedSlider} \title{Skew GED distribution slider} \description{ Displays interactively the dependence of the skew GED distribution on its parameters. } \usage{ sgedSlider(type = c("dist", "rand")) } \arguments{ \item{type}{ a character string denoting which interactive plot should be displayed. Either a distribution plot \code{type="dist"}, the default value, or a random variates plot, \code{type="rand"}. } } \value{ a Tcl object } \references{ Nelson D.B. (1991); \emph{Conditional Heteroscedasticity in Asset Returns: A New Approach}, Econometrica, 59, 347--370. Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{sged}}, \code{\link{sgedFit}} } \examples{ \dontrun{ ## sgedSlider - require(tcltk) sgedSlider("dist") sgedSlider("rand") } } \keyword{distribution} fGarch/man/dist-stdSlider.Rd0000755000176200001440000000141414326156212015411 0ustar liggesusers\name{stdSlider} \alias{stdSlider} \title{Student-t distribution slider} \description{ Displays interactively the dependence of the Student-t distribution on its parameters. } \usage{ stdSlider(type = c("dist", "rand")) } \arguments{ \item{type}{ a character string denoting which interactive plot should be displayed. Either a distribution plot \code{type="dist"}, the default value, or a random variates plot, \code{type="rand"}. } } \value{ a Tcl object } %\references{ %} \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{std}}, \code{\link{stdFit}}, } \examples{ \dontrun{ ## stdSlider - require(tcltk) stdSlider("dist") stdSlider("rand") } } \keyword{distribution} fGarch/man/VaR.Rd0000644000176200001440000000247614556733064013224 0ustar liggesusers\name{VaR} \alias{VaR} \alias{VaR.fGARCH} \alias{ES} \alias{ES.fGARCH} \concept{VaR} \concept{value-at-risk} \concept{ES} \concept{expected shortfall} \title{Compute Value-at-Risk (VaR) and expected shortfall (ES)} \description{ Compute Value-at-Risk (VaR) and Expected Shortfall (ES) for a fitted GARCH-APARCH model. } \usage{ \method{VaR}{fGARCH}(dist, p_loss = 0.05, ..., tol) \method{ES}{fGARCH}(dist, p_loss = 0.05, ...) } \arguments{ \item{dist}{ an object from class \code{"fGARCH"}, obtained from \code{garchFit()}. } \item{p_loss}{level, default is 0.05.} \item{...}{not used.} \item{tol}{tollerance} } \details{ We provide methods for the generic functions \code{cvar::VaR} and \code{cvar::ES}. } \note{ We use the traditional definition of VaR as the negated lower quantile. For example, if \eqn{X} are returns on an asset, VAR\eqn{{}_\alpha}{_a} = \eqn{-q_\alpha}{-q_a}, where \eqn{q_\alpha}{-q_a} is the lower \eqn{\alpha}{a} quantile of \eqn{X}. Equivalently, VAR\eqn{{}_\alpha}{_a} is equal to the lower \eqn{1-\alpha}{1-a} quantile of \eqn{-X}. } \seealso{ \code{\link[cvar]{VaR}} and \code{\link[cvar]{ES}} in package \pkg{cvar} } \examples{ x <- garchSim( garchSpec(), n = 500) fit <- garchFit(~ garch(1, 1), data = x, trace = FALSE) head(VaR(fit)) head(ES(fit)) } fGarch/man/methods-summary.Rd0000755000176200001440000000574314327221435015663 0ustar liggesusers\name{summary-methods} \alias{summary-methods} \docType{methods} \alias{summary} %\alias{summary,ANY-method} \alias{summary,fGARCH-method} \title{GARCH summary methods} \description{ Summary methods for GARCH modelling. } \section{Methods}{ Methods for \code{summary} defined in package \pkg{fGarch}: \describe{ \item{object = "fGARCH"}{ Summary function for objects of class \code{"fGARCH"}. } } } \section{How to read a diagnostic summary report?}{ The first five sections return the title, the call, the mean and variance formula, the conditional distribution and the type of standard errors: \preformatted{ Title: GARCH Modelling Call: garchFit(~ garch(1, 1), data = garchSim(), trace = FALSE) Mean and Variance Equation: ~arch(0) Conditional Distribution: norm Std. Errors: based on Hessian } The next three sections return the estimated coefficients and an error analysis including standard errors, t values, and probabilities, as well as the log Likelihood values from optimization: \preformatted{ Coefficient(s): mu omega alpha1 beta1 -5.79788e-05 7.93017e-06 1.59456e-01 2.30772e-01 Error Analysis: Estimate Std. Error t value Pr(>|t|) mu -5.798e-05 2.582e-04 -0.225 0.822 omega 7.930e-06 5.309e-06 1.494 0.135 alpha1 1.595e-01 1.026e-01 1.554 0.120 beta1 2.308e-01 4.203e-01 0.549 0.583 Log Likelihood: -843.3991 normalized: -Inf } The next section provides results on standardized residuals tests, including statistic and p values, and on information criterion statistic including AIC, BIC, SIC, and HQIC: \preformatted{ Standardized Residuals Tests: Statistic p-Value Jarque-Bera Test R Chi^2 0.4172129 0.8117146 Shapiro-Wilk Test R W 0.9957817 0.8566985 Ljung-Box Test R Q(10) 13.05581 0.2205680 Ljung-Box Test R Q(15) 14.40879 0.4947788 Ljung-Box Test R Q(20) 38.15456 0.008478302 Ljung-Box Test R^2 Q(10) 7.619134 0.6659837 Ljung-Box Test R^2 Q(15) 13.89721 0.5333388 Ljung-Box Test R^2 Q(20) 15.61716 0.7400728 LM Arch Test R TR^2 7.049963 0.8542942 Information Criterion Statistics: AIC BIC SIC HQIC 8.473991 8.539957 8.473212 8.500687 } } \author{ Diethelm Wuertz for the Rmetrics \R-port } \examples{ ## garchSim - x = garchSim(n = 200) ## garchFit - fit = garchFit(formula = x ~ garch(1, 1), data = x, trace = FALSE) summary(fit) } fGarch/man/methods-residuals.Rd0000755000176200001440000000240714437616052016160 0ustar liggesusers\name{residuals-methods} \alias{residuals-methods} \docType{methods} \alias{residuals} \alias{residuals,fGARCH-method} \title{Extract GARCH model residuals} \description{ Extracts residuals from a fitted GARCH object. } \usage{ \S4method{residuals}{fGARCH}(object, standardize = FALSE) } \arguments{ \item{object}{ an object of class \code{"fGARCH"} as returned by \code{\link{garchFit}}. } \item{standardize}{ a logical, indicating if the residuals should be standardized. } } \details{ The \code{"fGARCH"} method extracts the \code{@residuals} slot from an object of class \code{"fGARCH"} as returned by the function \code{garchFit} and optionally standardizes them, using conditional standard deviations. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{fitted}}, \code{\link{predict}}, \code{\link{garchFit}}, class \code{\linkS4class{fGARCH}}, } \examples{ stopifnot(require("timeSeries")) ## Swiss Pension fund Index data(LPP2005REC, package = "timeSeries") x <- as.timeSeries(LPP2005REC) ## Fit LPP40 Bechmark: fit <- garchFit(LPP40 ~ garch(1, 1), data = 100*x, trace = FALSE) fit fitted <- fitted(fit) head(fitted) class(fitted) res <- residuals(fit) head(res) class(res) } \keyword{models} fGarch/man/dist-gedFit.Rd0000755000176200001440000000273214326164150014662 0ustar liggesusers\name{gedFit} \alias{gedFit} \title{Generalized error distribution parameter estimation} \description{ Function to fit the parameters of the generalized error distribution. } \usage{ gedFit(x, \dots) } \arguments{ \item{x}{ a numeric vector of quantiles. } \item{\dots}{ parameters parsed to the optimization function \code{nlm}. } } \value{ \code{gedFit} returns a list with the following components: \item{par}{ The best set of parameters found. } \item{objective}{ The value of objective corresponding to \code{par}. } \item{convergence}{ An integer code, 0 indicates successful convergence. } \item{message}{ A character string giving any additional information returned by the optimizer, or NULL. For details, see PORT documentation. } \item{iterations}{ Number of iterations performed. } \item{evaluations}{ Number of objective function and gradient function evaluations. } } \references{ Nelson D.B. (1991); \emph{Conditional Heteroscedasticity in Asset Returns: A New Approach}, Econometrica, 59, 347--370. Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{ged}}, \code{\link{sgedFit}} } \examples{ ## rged - set.seed(1953) r = rged(n = 1000) ## gedFit - gedFit(r) } \keyword{distribution} fGarch/man/00fGarch-package.Rd0000755000176200001440000001333414327227705015451 0ustar liggesusers\name{fGarch-package} \alias{fGarch-package} \docType{package} \alias{fGarch} \concept{GARCH model} \concept{APARCH model} \concept{skew distribution} \concept{fit skew distribution} \concept{volatility} \title{Modelling heterskedasticity in financial time series} \description{ The Rmetrics \pkg{fGarch} package is a collection of functions to analyze and model heteroskedastic behavior in financial time series. } \author{ Diethelm Wuertz [aut] (original code), Yohan Chalabi [aut], Tobias Setz [aut], Martin Maechler [ctb] (), Chris Boudt [ctb] Pierre Chausse [ctb], Michal Miklovac [ctb], Georgi N. Boshnakov [cre, ctb] Maintainer: Georgi N. Boshnakov } % \details{ % % } \section{1 Introduction}{ GARCH, Generalized Autoregressive Conditional Heteroskedastic, models have become important in the analysis of time series data, particularly in financial applications when the goal is to analyze and forecast volatility. For this purpose, the family of GARCH functions offers functions for simulating, estimating and forecasting various univariate GARCH-type time series models in the conditional variance and an ARMA specification in the conditional mean. The function \code{\link{garchFit}} is a numerical implementation of the maximum log-likelihood approach under different assumptions, Normal, Student-t, GED errors or their skewed versions. The parameter estimates are checked by several diagnostic analysis tools including graphical features and hypothesis tests. Functions to compute n-step ahead forecasts of both the conditional mean and variance are also available. The number of GARCH models is immense, but the most influential models were the first. Beside the standard ARCH model introduced by Engle [1982] and the GARCH model introduced by Bollerslev [1986], the function \code{garchFit} also includes the more general class of asymmetric power ARCH models, named APARCH, introduced by Ding, Granger and Engle [1993]. The APARCH models include as special cases the TS-GARCH model of Taylor [1986] and Schwert [1989], the GJR-GARCH model of Glosten, Jaganathan, and Runkle [1993], the T-ARCH model of Zakoian [1993], the N-ARCH model of Higgins and Bera [1992], and the Log-ARCH model of Geweke [1986] and Pentula [1986]. There exist a collection of review articles by Bollerslev, Chou and Kroner [1992], Bera and Higgins [1993], Bollerslev, Engle and Nelson [1994], Engle [2001], Engle and Patton [2001], and Li, Ling and McAleer [2002] which give a good overview of the scope of the research. } \section{2 Time series simulation}{ Functions to simulate artificial GARCH and APARCH time series processes. \tabular{ll}{ \code{\link{garchSpec}} \tab specifies an univariate GARCH time series model\cr \code{\link{garchSim}} \tab simulates a GARCH/APARCH process } } \section{3 Parameter estimation}{ Functions to fit the parameters of GARCH and APARCH time series processes. \tabular{ll}{ \code{\link{garchFit}} \tab fits the parameters of a GARCH process } \subsection{Extractor Functions:}{ \tabular{ll}{ \code{\link{residuals}} \tab extracts residuals from a fitted \code{"fGARCH"} object\cr \code{\link{fitted}} \tab extracts fitted values from a fitted \code{"fGARCH"} object\cr \code{\link{volatility}} \tab extracts conditional volatility from a fitted \code{"fGARCH"} object\cr \code{\link{coef}} \tab extracts coefficients from a fitted \code{"fGARCH"} object\cr \code{\link{formula}} \tab extracts formula expression from a fitted \code{"fGARCH"} object } } } \section{4 Forecasting}{ Functions to forcecast mean and variance of GARCH and APARCH processes. \tabular{ll}{ \code{\link{predict}} \tab forecasts from an object of class \code{"fGARCH"} } } \section{5 Standardized distributions}{ This section contains functions to model standardized distributions. \subsection{Skew normal distribution:}{ \tabular{ll}{ \code{\link[=dnorm]{[dpqr]norm}} \tab Normal distribution (base R)\cr \code{\link[=dsnorm]{[dpqr]snorm}} \tab Skew normal distribution\cr \code{\link[=snormFit]{snormFit}} \tab fits parameters of Skew normal distribution } } \subsection{Skew generalized error distribution:}{ \tabular{ll}{ \code{\link[=dged]{[dpqr]ged}} \tab Generalized error distribution\cr \code{\link[=psged]{[dpqr]sged}} \tab Skew Generalized error distribution\cr \code{\link[=gedFit]{gedFit}} \tab fits parameters of Generalized error distribution\cr \code{\link[=sgedFit]{sgedFit}} \tab fits parameters of Skew generalized error distribution } } \subsection{Skew standardized Student-t distribution:}{ \tabular{ll}{ \code{\link[=dstd]{[dpqr]std}} \tab Standardized Student-t distribution\cr \code{\link[=dsstd]{[dpqr]sstd}} \tab Skew standardized Student-t distribution\cr \code{\link[=stdFit]{stdFit}} \tab fits parameters of Standardized Student-t distribution\cr \code{\link[=sstdFit]{sstdFit}} \tab fits parameters of Skew standardized Student-t distribution } } \subsection{Absolute moments:}{ \tabular{ll}{ \code{\link{absMoments}} \tab computes absolute moments of these distribution } } } \section{About Rmetrics}{ The \code{fGarch} Rmetrics package is written for educational support in teaching "Computational Finance and Financial Engineering" and licensed under the GPL. } % Diethelm Wuertz and Yohan Chalabi, with contributions from % Michal Miklovac, Pierre Chausse, and Chris Boudt. \keyword{package} fGarch/man/class-fUGARCHSPEC.Rd0000644000176200001440000000153614512754502015415 0ustar liggesusers\name{fUGARCHSPEC-class} \alias{fUGARCHSPEC-class} \alias{.ugarchFit} \alias{.ugarchSpec} \docType{class} \title{Class 'fUGARCHSPEC'} \description{Class 'fUGARCHSPEC'.} \section{Objects from the Class}{ Objects can be created by calls of the form \code{new("fUGARCHSPEC", ...)}. } \section{Slots}{ \describe{ \item{\code{model}:}{Object of class \code{"list"} ~~ } \item{\code{distribution}:}{Object of class \code{"list"} ~~ } \item{\code{optimization}:}{Object of class \code{"list"} ~~ } \item{\code{documentation}:}{Object of class \code{"list"} ~~ } } } \section{Methods}{ No methods defined with class \code{"fUGARCHSPEC"} in the signature. } \note{ (GNB) This class seems to be meant for internal use by the package. } \seealso{ class \code{"\linkS4class{fGARCH}"} } \examples{ showClass("fUGARCHSPEC") } \keyword{classes} fGarch/man/dist-stdFit.Rd0000755000176200001440000000252714326164566014732 0ustar liggesusers\name{stdFit} \alias{stdFit} \title{Student-t distribution parameter estimation} \description{ Fits the parameters of the standardized Student-t distribution. } \usage{ stdFit(x, \dots) } \arguments{ \item{x}{ a numeric vector of quantiles. } \item{\dots}{ parameters parsed to the optimization function \code{nlm}. } } \value{ \code{stdFit} returns a list with the following components: \item{par}{ The best set of parameters found. } \item{objective}{ The value of objective corresponding to \code{par}. } \item{convergence}{ An integer code. 0 indicates successful convergence. } \item{message}{ A character string giving any additional information returned by the optimizer, or NULL. For details, see PORT documentation. } \item{iterations}{ Number of iterations performed. } \item{evaluations}{ Number of objective function and gradient function evaluations. } } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{std}}, \code{\link{stdSlider}} } \examples{ ## std - set.seed(1953) r = rstd(n = 1000) ## stdFit - stdFit(r) } \keyword{distribution} fGarch/man/methods-formula.Rd0000755000176200001440000000660414327213557015636 0ustar liggesusers\name{formula-methods} \alias{formula-methods} \docType{methods} \alias{formula} \alias{formula,fGARCH-method} \title{Extract GARCH model formula} \description{ Extracts formula from a formula GARCH object. } \section{Methods}{ Methods for \code{formula} defined in package \pkg{fGarch}: \describe{ \item{object = "fGARCH"}{ Extractor function for formula expression. } } } \details{ \code{formula} is a generic function which extracts the formula expression from objects returned by modeling functions. The \code{"fGARCH"} method extracts the \code{@formula} expression slot from an object of class \code{"fGARCH"} as returned by the function \code{garchFit}. The returned formula has always a left hand side. If the argument \code{data} was an univariate time series and no name was specified to the series, then the left hand side is assigned the name of the data.set. In the multivariate case the rectangular \code{data} object must always have column names, otherwise the fitting will be stopped with an error message The class of the returned value depends on the input to the function \code{garchFit} who created the object. The returned value is always of the same class as the input object to the argument \code{data} in the function \code{garchFit}, i.e. if you fit a \code{"timeSeries"} object, you will get back from the function \code{fitted} also a \code{"timeSeries"} object, if you fit an object of class \code{"zoo"}, you will get back again a \code{"zoo"} object. The same holds for a \code{"numeric"} vector, for a \code{"data.frame"}, and for objects of class \code{"ts", "mts"}. In contrast, the slot itself returns independent of the class of the data input always a numeric vector, i.e. the function call r\code{slot(object, "fitted")} will return a numeric vector. } \note{ (GNB) Contrary to the description of the returned value of the \code{"fGARCH"} method, it is always \code{"numeric"}. TODO: either implement the documented behaviour or fix the documentation. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{garchFit}}, class \code{\linkS4class{fGARCH}} } \examples{ ## garchFit - fit = garchFit(~garch(1, 1), data = garchSim(), trace = FALSE) ## formula - formula(fit) ## A Bivariate series and mis-specified formula: x = garchSim(n = 500) y = garchSim(n = 500) z = cbind(x, y) colnames(z) class(z) \dontrun{ garchFit(z ~garch(1, 1), data = z, trace = FALSE) } # Returns: # Error in .garchArgsParser(formula = formula, data = data, trace = FALSE) : # Formula and data units do not match. ## Doubled column names in data set - formula can't fit: colnames(z) <- c("x", "x") z[1:6,] \dontrun{ garchFit(x ~garch(1, 1), data = z, trace = FALSE) } # Again the error will be noticed: # Error in garchFit(x ~ garch(1, 1), data = z) : # Column names of data are not unique. ## Missing column names in data set - formula can't fit: z.mat <- as.matrix(z) colnames(z.mat) <- NULL z.mat[1:6,] \dontrun{ garchFit(x ~ garch(1, 1), data = z.mat, trace = FALSE) } # Again the error will be noticed: # Error in .garchArgsParser(formula = formula, data = data, trace = FALSE) : # Formula and data units do not match } \keyword{models} fGarch/man/stats-tsdiag.Rd0000755000176200001440000001041414441643321015122 0ustar liggesusers\name{stats-tsdiag} \alias{stats-tsdiag} \alias{tsdiag} \alias{tsdiag.fGARCH} \title{Diagnostic plots and statistics for fitted GARCH models} \description{ Produce diagnostics for fitted GARCH/APARCH models. The method offers several tests, plots of autocorrelations and partial autocorrelations of the standardised conditional residuals, ability to control which graphs are produced (including interactively), as well as their layout. } \usage{ \method{tsdiag}{fGARCH}(object, gof.lag = NULL, ask = FALSE, \dots, plot = c(4L, 5L, 7L), layout = NULL) } \arguments{ \item{object}{ an object from class \code{"fGARCH"}, as returned by \code{\link{garchFit}}. } \item{gof.lag}{maximal lag for portmanteau tests.} \item{ask}{if \code{TRUE} present a menu of available plots, see Details.} \item{\dots}{not used.} \item{plot}{ if \code{TRUE} all available plots; a vector of positive integers specifies a subset of the available plots. } \item{layout}{ a list with arguments for \code{graphics::layout} for the plots. The default plots the autocorrelations of the standardised conditional residuals and their squares, as well as a QQ-plot for the fitted conditional distribution. } } \details{ Compute and graph diagnostics for fitted ARMA-GARCH/APARCH models. % The method offers several portmanteau tests (including Ljung-Box, % Li-McLeod and Box-Pierce), plots of autocorrelations and partial % autocorrelations of the residuals, ability to control which graphs are % produced (including interactively), as well as their layout. % % The method always makes a correction of the degrees of freedom of the % portmanteau tests (roughly, subtracting the number of estimated ARMA % parameters). Note that \code{stats::tsdiag} doesn't do that. \code{plot} can be \code{TRUE} to ask for all plots or a vector of positive integers specifying which plots to consider. Currently the following options are available: \Sexpr[stage=build,results=rd]{paste0("\\\\tabular{rl}{", paste0(1:length(fGarch:::.tsdiag_choices), " \\\\tab ", fGarch:::.tsdiag_choices, collapse = " \\\\cr\n "), "}\n")} The default produces plots of autocorrelations and partial autocorrelations of the standardised conditional residuals, as well as a QQ-plot for the fitted conditional distribution. If \code{plot} is \code{TRUE}, you probably need also \code{ask = TRUE}. If argument \code{plot} is of length two the graphics window is split into 2 equal subwindows. Argument \code{layout} can still be used to change this. If argument \code{plot} is of length one the graphics window is not split at all. In interactive sessions, if the number of requested graphs (as specified by argument \code{plot}) is larger than the number of graphs specified by the layout (by default 3), the function makes the first graph and then presents a menu of the requested plots. Argument \code{layout} can be used to change the layout of the plot, for example to put two graphs per plot, see the examples. Currently it should be a list of arguments for \code{\link[graphics]{layout}}, see \code{?layout}. Don't call \code{layout} youself, as that will change the graphics device prematurely. The computed results are returned (invisibly). This is another difference from \code{stats::tsdiag} which doesn't return them. } \value{ (experimental, may change) a list with components: \item{residuals}{standardised conditional residuals,} \item{gof}{ goodness-of-fit tests, pretending parameters are known, } \item{gof_composite}{ goodness-of-fit tests taking into account that the parameters are estimated. } Only components that are actually computed are included, the rest are NULL or absent. } \author{Georgi N. boshnakov} \seealso{ \code{\link[=plot,fGARCH,missing-method]{fGARCH}} method for \code{plot}, \code{\link[stats]{tsdiag}} } \examples{ set.seed(20230612) x <- garchSim(n = 200) fit <- garchFit(formula = ~ garch(1, 1), data = x, trace = FALSE) fit_test <- tsdiag(fit) fit_test ## 2x2 matrix with acf of r, r^2 on diag, cor(r,r^2) below it, and qq-plot tsdiag(fit, plot = c(4, 6, 7, 5), layout = list(matrix(1:4, nrow = 2))) } \keyword{ts} \keyword{htest} \concept{diagnostics} \concept{diagnostic plots} fGarch/man/garchSim.Rd0000755000176200001440000001314014440433362014250 0ustar liggesusers\name{garchSim} \alias{garchSim} \concept{GARCH model} \concept{APARCH model} \concept{simulate GARCH} \concept{simulate APARCH} \title{Simulate univariate GARCH/APARCH time series} \description{ Simulates univariate GARCH/APARCH time series. } \usage{ garchSim(spec = garchSpec(), n = 100, n.start = 100, extended = FALSE) } \arguments{ \item{spec}{ a specification object of class \code{"\linkS4class{fGARCHSPEC}"} as returned by \code{\link{garchSpec}}. See also below for further details. } \item{n}{ length of the output series, an integer value, by default \code{n=100}. } \item{n.start}{ length of \sQuote{burn-in} period, by default 100. } \item{extended}{ logical parameter specifying what to return. If \code{FALSE}, return the univariate GARCH/APARCH time series. If \code{TRUE}, return a multivariate time series containing also the volatility and conditional innovations time series. } } \details{ \code{garchSim} simulates an univariate GARCH or APARCH time series process as specified by argument \code{spec}. The default model specifies Bollerslev's GARCH(1,1) model with normally distributed innovations. \code{spec} is an object of class \code{"fGARCHSPEC"} as returned by the function \code{\link{garchSpec}}. It comes with a slot \code{@model} which is a list of just the numeric parameter entries. These are recognized and extracted for use by the function \code{garchSim}. % (GB) commenting out since the return value is 'timeSeries'. % % By default the series will be returned as an object of class % \code{"ts"} or as a \code{"numeric"} vector. Having time/date % positions, e.g. from an empirical process the numeric vector can be % easily transformed into other time series objects like % \code{"timeSeries"} or \code{"zoo"}. So One can estimate the parameters of a GARCH process from empirical data using the function \code{garchFit} and then simulate statistically equivalent GARCH processes with the same set of model parameters using the function \code{garchSim}. % (GB) commenting out since there is no argument 'returnClass' % (apparently it is superseded by 'extend') % % The third entry in the argument \code{returnClass="mts"} allows to % return a trivariate time series, where the first column contains the % simulated \code{"garch"} process, the second column the conditional % standard deviations \code{"h"}, and the last column the innovations % named \code{"eps"}. } \value{ the simulated time series as an objects of class \code{"timeSeries"} with attribute \code{"spec"} containing the specification of the model. If \code{extended} is \code{TRUE}, then the time series is multivariate and contains also the volatility, \code{sigma}, and the conditional innovations, \code{eps}. } \note{ An undocumented feature (so, it should not be relied on) is that the returned time series is timed so that the last observation is the day before the date when the function is executed. This probably should be controlled by an additional argument in \code{garchSim}. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{garchSpec}}, \code{\link{garchFit}} } \examples{ ## garchSpec - spec = garchSpec() spec ## garchSim - # Simulate a "timeSeries" object: x = garchSim(spec, n = 50) class(x) print(x) ## More simulations ... # Default GARCH(1,1) - uses default parameter settings spec = garchSpec(model = list()) garchSim(spec, n = 10) # ARCH(2) - use default omega and specify alpha, set beta=0! spec = garchSpec(model = list(alpha = c(0.2, 0.4), beta = 0)) garchSim(spec, n = 10) # AR(1)-ARCH(2) - use default mu, omega spec = garchSpec(model = list(ar = 0.5, alpha = c(0.3, 0.4), beta = 0)) garchSim(spec, n = 10) # AR([1,5])-GARCH(1,1) - use default garch values and subset ar[.] spec = garchSpec(model = list(mu = 0.001, ar = c(0.5,0,0,0,0.1))) garchSim(spec, n = 10) # ARMA(1,2)-GARCH(1,1) - use default garch values spec = garchSpec(model = list(ar = 0.5, ma = c(0.3, -0.3))) garchSim(spec, n = 10) # GARCH(1,1) - use default omega and specify alpha/beta spec = garchSpec(model = list(alpha = 0.2, beta = 0.7)) garchSim(spec, n = 10) # GARCH(1,1) - specify omega/alpha/beta spec = garchSpec(model = list(omega = 1e-6, alpha = 0.1, beta = 0.8)) garchSim(spec, n = 10) # GARCH(1,2) - use default omega and specify alpha[1]/beta[2] spec = garchSpec(model = list(alpha = 0.1, beta = c(0.4, 0.4))) garchSim(spec, n = 10) # GARCH(2,1) - use default omega and specify alpha[2]/beta[1] spec = garchSpec(model = list(alpha = c(0.12, 0.04), beta = 0.08)) garchSim(spec, n = 10) # snorm-ARCH(1) - use defaults with skew Normal spec = garchSpec(model = list(beta = 0, skew = 0.8), cond.dist = "snorm") garchSim(spec, n = 10) # sged-GARCH(1,1) - using defaults with skew GED model = garchSpec(model = list(skew = 0.93, shape = 3), cond.dist = "sged") garchSim(model, n = 10) # Taylor Schwert GARCH(1,1) - this belongs to the family of APARCH Models spec = garchSpec(model = list(delta = 1)) garchSim(spec, n = 10) # AR(1)-t-APARCH(2, 1) - a little bit more complex specification ... spec = garchSpec(model = list(mu = 1.0e-4, ar = 0.5, omega = 1.0e-6, alpha = c(0.10, 0.05), gamma = c(0, 0), beta = 0.8, delta = 1.8, shape = 4, skew = 0.85), cond.dist = "sstd") garchSim(spec, n = 10) garchSim(spec, n = 10, extended = TRUE) } \keyword{models} \keyword{ts} fGarch/man/dist-sstdFit.Rd0000755000176200001440000000252614326164150015101 0ustar liggesusers\name{sstdFit} \alias{sstdFit} \title{Skew Student-t distribution parameter estimation} \description{ Fits the parameters of the skew Student-t distribution. } \usage{ sstdFit(x, \dots) } \arguments{ \item{x}{ a numeric vector of quantiles. } \item{\dots}{ parameters passed to the optimization function \code{nlm}. } } \value{ \code{sstdFit} returns a list with the following components: \item{par}{ The best set of parameters found. } \item{objective}{ The value of objective corresponding to \code{par}. } \item{convergence}{ An integer code. 0 indicates successful convergence. } \item{message}{ A character string giving any additional information returned by the optimizer, or NULL. For details, see PORT documentation. } \item{iterations}{ Number of iterations performed. } \item{evaluations}{ Number of objective function and gradient function evaluations. } } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{sstd}}, \code{\link{stdFit}} } \examples{ ## sstd - set.seed(1953) r = rsstd(n = 1000) ## sstdFit - sstdFit(r) } \keyword{distribution} fGarch/man/dist-sstd.Rd0000755000176200001440000000462514437715722014452 0ustar liggesusers\name{sstd} \alias{sstd} \alias{dsstd} \alias{psstd} \alias{qsstd} \alias{rsstd} \title{Skew Student-t distribution} \description{ Functions to compute density, distribution function, quantile function and to generate random variates for the skew Student-t distribution. } \usage{ dsstd(x, mean = 0, sd = 1, nu = 5, xi = 1.5, log = FALSE) psstd(q, mean = 0, sd = 1, nu = 5, xi = 1.5) qsstd(p, mean = 0, sd = 1, nu = 5, xi = 1.5) rsstd(n, mean = 0, sd = 1, nu = 5, xi = 1.5) } \arguments{ \item{x, q}{ a numeric vector of quantiles. } \item{p}{ a numeric vector of probabilities. } \item{n}{ number of observations to simulate. } \item{mean}{ location parameter. } \item{sd}{ scale parameter. } \item{nu}{ shape parameter (degrees of freedom). } \item{xi}{ skewness parameter. } \item{log}{ logical; if \code{TRUE}, densities are given as log densities. } } \details{ The distribution is standardized as discussed in the reference by Wuertz et al below. \code{dsstd} computes the density, \code{psstd} the distribution function, \code{qsstd} the quantile function, and \code{rsstd} generates random deviates. } \value{ numeric vector } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. Wuertz D., Chalabi Y. and Luksan L. (????); \emph{Parameter estimation of ARMA models with GARCH/APARCH errors: An R and SPlus software implementation}, Preprint, 41 pages, \url{https://github.com/GeoBosh/fGarchDoc/blob/master/WurtzEtAlGarch.pdf} } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{sstdFit}} (fit), \code{\link{sstdSlider}} (visualize) } \examples{ ## sstd - par(mfrow = c(2, 2)) set.seed(1953) r = rsstd(n = 1000) plot(r, type = "l", main = "sstd", col = "steelblue") # Plot empirical density and compare with true density: hist(r, n = 25, probability = TRUE, border = "white", col = "steelblue") box() x = seq(min(r), max(r), length = 201) lines(x, dsstd(x), lwd = 2) # Plot df and compare with true df: plot(sort(r), (1:1000/1000), main = "Probability", col = "steelblue", ylab = "Probability") lines(x, psstd(x), lwd = 2) # Compute quantiles: round(qsstd(psstd(q = seq(-1, 5, by = 1))), digits = 6) } \keyword{distribution} fGarch/man/dist-sstdSlider.Rd0000755000176200001440000000162514326165106015602 0ustar liggesusers\name{sstdSlider} \alias{sstdSlider} \title{Skew Student-t distribution slider} \description{ Displays interactively the dependence of the skew Student-t distribution on its parameters. } \usage{ sstdSlider(type = c("dist", "rand")) } \arguments{ \item{type}{ a character string denoting which interactive plot should be displayed. Either a distribution plot \code{type="dist"}, the default value, or a random variates plot, \code{type="rand"}. } } \value{ a Tcl object } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{sstd}}, \code{\link{sstdFit}} } \examples{ \dontrun{ ## sstdSlider - require(tcltk) sstdSlider("dist") sstdSlider("rand") } } \keyword{distribution} fGarch/man/dist-snormFit.Rd0000755000176200001440000000272114326164150015257 0ustar liggesusers\name{snormFit} \alias{snormFit} \concept{skew distribution} \concept{skewed distribution} \title{Skew normal distribution parameter estimation} \description{ Fits the parameters of the skew normal distribution. } \usage{ snormFit(x, \dots) } \arguments{ \item{x}{ a numeric vector of quantiles. } \item{\dots}{ parameters passed to the optimization function \code{nlm}. } } \value{ \code{snormFit} returns a list with the following components: \item{par}{ The best set of parameters found. } \item{objective}{ The value of objective corresponding to \code{par}. } \item{convergence}{ An integer code. 0 indicates successful convergence. } \item{message}{ A character string giving any additional information returned by the optimizer, or NULL. For details, see PORT documentation. } \item{iterations}{ Number of iterations performed. } \item{evaluations}{ Number of objective function and gradient function evaluations. } } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{snormFit}} (fit), \code{\link{snormSlider}} (visualize), \code{\link{absMoments}} } \examples{ ## rsnorm - set.seed(1953) r = rsnorm(n = 1000) ## snormFit - snormFit(r) } \keyword{distribution} fGarch/man/dist-snormSlider.Rd0000755000176200001440000000163514326164150015762 0ustar liggesusers\name{snormSlider} \alias{snormSlider} \title{Skew normal distribution slider} \description{ Displays interactively the dependence of the skew Normal distribution on its parameters. } \usage{ snormSlider(type = c("dist", "rand")) } \arguments{ \item{type}{ a character string denoting which interactive plot should be displayed. Either a distribution plot \code{type="dist"}, the default value, or a random variates plot, \code{type="rand"}. } } \value{ a Tcl object } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{snormFit}} (fit), \code{\link{snorm}}, } \examples{ \dontrun{ ## snormSlider - require(tcltk) snormSlider("dist") snormSlider("rand") } } \keyword{distribution} fGarch/man/dist-absMoments.Rd0000755000176200001440000000350114326164150015563 0ustar liggesusers\name{absMoments} \alias{absMoments} \title{Absolute moments of GARCH distributions} \description{ Computes absolute moments of the standard normal, standardized GED, and standardized skew Student-t distributions. } \usage{ absMoments(n, density = c("dnorm", "dged", "dstd"), \dots) } \arguments{ \item{n}{ the order of the absolute moment, can be a vector to compute several absolute moments at once. } \item{density}{ a character string naming a symmetric density function. } \item{\dots}{ parameters passed to the density function. } } \details{ \code{absMoments} returns a numeric vector of length \code{n} with the values of the absolute moments, as specified by \code{n}, of the selected probability density function (pdf). If \code{density} names one of the densities in the signature of \code{absMoments}, the moments are calculated from known formulas. Otherwise, numerical integration is used and an attribute is attached to the results to report an estimate of the error. Note that the density is assumed symmetric wihtout a check. } \value{ a numeric vector } \references{ Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{ged}}, \code{\link{std}} } \examples{ ## absMoment - absMoments(1, "dstd", nu = 6) absMoments(1, "dstd", nu = 600) absMoments(1, "dstd", nu = 60000) absMoments(1, "dstd", nu = 600000) absMoments(1, "dnorm") ## excess kurtosis of t_nu is 6/(nu - 4) nu <- 6 absMoments(2*2, "dstd", nu = nu) / absMoments(2*1, "dstd", nu = nu)^2 - 3 6/(nu-4) ## 4th moment for t_4 is infinite absMoments(4, "dstd", nu = 4) absMoments(1, "dged", nu = 4) } \keyword{distribution} fGarch/man/garchSpec.Rd0000755000176200001440000001625514326300623014420 0ustar liggesusers\name{garchSpec} \alias{garchSpec} \concept{GARCH model} \concept{APARCH model} \concept{asymmetric power ARCH model} \concept{ARMA-GARCH model} \concept{ARMA-APARCH model} \title{Univariate GARCH/APARCH time series specification} \description{ Specifies an univariate ARMA-GARCH or ARMA-APARCH time series model. } \usage{ garchSpec(model = list(), presample = NULL, cond.dist = c("norm", "ged", "std", "snorm", "sged", "sstd"), rseed = NULL) } \arguments{ \item{cond.dist}{ a character string naming the desired conditional distribution. Valid values are \code{"norm"}, \code{"ged"}, \code{"std"}, \code{"snorm"}, \code{"sged"}, \code{"sstd"}. The default value is \code{"norm"}, the standard normal distribution. } \item{model}{ a list of GARCH model parameters, see section \sQuote{Details}. The default \code{model=list()} specifies Bollerslev's GARCH(1,1) model with normal conditional distributed innovations. } \item{presample}{ a numeric three column matrix with start values for the series, for the innovations, and for the conditional variances. For an ARMA(m,n)-GARCH(p,q) process the number of rows must be at least max(m,n,p,q)+1, longer presamples are truncated. Note, all presamples are initialized by a normal-GARCH(p,q) process. } \item{rseed}{ single integer argument, the seed for the intitialization of the random number generator for the innovations. If \code{rseed=NULL}, the default, then the state of the random number generator is not touched by this function. } } \details{ The function \code{garchSpec} specifies a GARCH or APARCH time series process which we can use for simulating artificial GARCH and/or APARCH models. This is very useful for testing the GARCH parameter estimation results, since your model parameters are known and well specified. Argument \code{model} is a list of model parameters. For the GARCH part of the model they are: \describe{ \item{\code{omega}}{the constant coefficient of the variance equation, by default \code{1e-6};} \item{\code{alpha}}{the value or vector of autoregressive coefficients, by default 0.1, specifying a model of order 1;} \item{\code{beta}}{the value or vector of variance coefficients, by default 0.8, specifying a model of order 1.} } If the model is APARCH, then the following additional parameters are available: \describe{ \item{delta}{a positive number, the power of sigma in the volatility equation, it is 2 for GARCH models;} \item{gamma}{the leverage parameters, a vector of length \code{alpha}, containing numbers in the interval \eqn{(0,1)}.} } The values for the linear part (conditional mean) are: \describe{ \item{\code{mu}}{the mean value, by default NULL;} \item{\code{ar}}{the autoregressive ARMA coefficients, by default NULL;} \item{\code{ma}}{the moving average ARMA coefficients, by default NULL.} } The parameters for the conditional distributions are: \describe{ \item{\code{skew}}{the skewness parameter (also named "xi"), by default 0.9, effective only for the \code{"dsnorm"}, the \code{"dsged"}, and the \code{"dsstd"} skewed conditional distributions;} \item{\code{shape}}{the shape parameter (also named "nu"), by default 2 for the \code{"dged"} and \code{"dsged"}, and by default 4 for the \code{"dstd"} and \code{"dsstd"} conditional distributions.} } For example, specifying a subset AR(5[1,5])-GARCH(2,1) model with a standardized Student-t distribution with four degrees of freedom will return the following printed output: \preformatted{ garchSpec(model = list(ar = c(0.5,0,0,0,0.1), alpha = c(0.1, 0.1), beta = 0.75, shape = 4), cond.dist = "std") Formula: ~ ar(5) + garch(2, 1) Model: ar: 0.5 0 0 0 0.1 omega: 1e-06 alpha: 0.1 0.1 beta: 0.75 Distribution: std Distributional Parameter: nu = 4 Presample: time z h y 0 0 -0.3262334 2e-05 0 -1 -1 1.3297993 2e-05 0 -2 -2 1.2724293 2e-05 0 -3 -3 0.4146414 2e-05 0 -4 -4 -1.5399500 2e-05 0 } Its interpretation is as follows. \sQuote{Formula} describes the formula expression specifying the generating process, \sQuote{Model} lists the associated model parameters, \sQuote{Distribution} the type of the conditional distribution function in use, \sQuote{Distributional Parameters} lists the distributional parameter (if any), and the \sQuote{Presample} shows the presample input matrix. If we have specified \code{presample = NULL} in the argument list, then the presample is generated automatically by default as norm-AR()-GARCH() process. } \value{ an object of class \code{"\linkS4class{fGARCHSPEC}"} } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{garchSim}}, \code{\link{garchFit}} } \examples{ ## garchSpec - # Normal Conditional Distribution: spec = garchSpec() spec # Skewed Normal Conditional Distribution: spec = garchSpec(model = list(skew = 0.8), cond.dist = "snorm") spec # Skewed GED Conditional Distribution: spec = garchSpec(model = list(skew = 0.9, shape = 4.8), cond.dist = "sged") spec ## More specifications ... # Default GARCH(1,1) - uses default parameter settings garchSpec(model = list()) # ARCH(2) - use default omega and specify alpha, set beta=0! garchSpec(model = list(alpha = c(0.2, 0.4), beta = 0)) # AR(1)-ARCH(2) - use default mu, omega garchSpec(model = list(ar = 0.5, alpha = c(0.3, 0.4), beta = 0)) # AR([1,5])-GARCH(1,1) - use default garch values and subset ar[.] garchSpec(model = list(mu = 0.001, ar = c(0.5,0,0,0,0.1))) # ARMA(1,2)-GARCH(1,1) - use default garch values garchSpec(model = list(ar = 0.5, ma = c(0.3, -0.3))) # GARCH(1,1) - use default omega and specify alpha/beta garchSpec(model = list(alpha = 0.2, beta = 0.7)) # GARCH(1,1) - specify omega/alpha/beta garchSpec(model = list(omega = 1e-6, alpha = 0.1, beta = 0.8)) # GARCH(1,2) - use default omega and specify alpha[1]/beta[2] garchSpec(model = list(alpha = 0.1, beta = c(0.4, 0.4))) # GARCH(2,1) - use default omega and specify alpha[2]/beta[1] garchSpec(model = list(alpha = c(0.12, 0.04), beta = 0.08)) # snorm-ARCH(1) - use defaults with skew Normal garchSpec(model = list(beta = 0, skew = 0.8), cond.dist = "snorm") # sged-GARCH(1,1) - using defaults with skew GED garchSpec(model = list(skew = 0.93, shape = 3), cond.dist = "sged") # Taylor Schwert GARCH(1,1) - this belongs to the family of APARCH Models garchSpec(model = list(delta = 1)) # AR(1)-t-APARCH(2, 1) - a little bit more complex specification ... garchSpec(model = list(mu = 1.0e-4, ar = 0.5, omega = 1.0e-6, alpha = c(0.10, 0.05), gamma = c(0, 0), beta = 0.8, delta = 1.8, shape = 4, skew = 0.85), cond.dist = "sstd") } \keyword{models} \keyword{ts} fGarch/man/class-fGARCHSPEC.Rd0000755000176200001440000000335714440432031015264 0ustar liggesusers\name{fGARCHSPEC-class} \alias{fGARCHSPEC-class} \docType{class} \alias{show,fGARCHSPEC-method} \alias{update,fGARCHSPEC-method} \concept{GARCH model} \concept{APARCH model} \concept{ARMA-GARCH model} \concept{ARMA-APARCH model} \title{Class "fGARCHSPEC"} \description{ Specification structure for an univariate GARCH time series model. } \section{Objects from the Class}{ Objects can be created by calls of the function \code{garchSpec}. This object specifies the parameters of an empirical GARCH process. } \section{Slots}{ \describe{ \item{\code{call}:}{Object of class \code{"call"}: the call of the \code{garch} function. } \item{\code{formula}:}{Object of class \code{"formula"}: a list with two formula entries for the mean and variance equation. } \item{\code{model}:}{Object of class \code{"list"}: a list with the model parameters. } \item{\code{presample}:}{Object of class \code{"matrix"}: a numeric matrix with presample values. } \item{\code{distribution}:}{Object of class \code{"character"}: a character string with the name of the conditional distribution. } \item{\code{rseed}:}{Object of class \code{"numeric"}: an integer with the random number generator seed. } } } \section{Methods}{ \describe{ \item{show}{\code{signature(object = "fGARCHSPEC")}: prints an object of class 'fGARCHSPEC'. } } } \note{ With Rmetrics Version 2.6.1 the class has been renamed from \code{"garchSpec"} to \code{"fGARCHSPEC"}. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \examples{ ## garchSpec - spec = garchSpec() spec # print() or show() it } \keyword{programming} fGarch/man/fGarchData.Rd0000755000176200001440000000203114437613675014511 0ustar liggesusers\name{fGarchData} \alias{fGarchData} \alias{dem2gbp} \alias{sp500dge} \concept{exchange rates data} \concept{SP500 data} \title{Time series datasets} \description{ Datasets used in the examples, including DEM/GBP foreign exchange rates and data on SP500 index. } \format{ \code{dem2gbp} is a data frame with one column \code{"DEM2GBP"} and 1974 rows (observations). \code{sp500dge} is a data frame with one column \code{"SP500DGE"} and 17055 rows (observations). } \details{ The data represent retuns. No further details have been recorded. Further datasets are available in the packages that \pkg{fGarch} imports, see \code{\link[fBasics]{fBasicsData}} and \code{\link[timeSeries]{TimeSeriesData}}. } \seealso{ \code{data(package = "fBasics")} and \code{data(package = "timeSeries")} for related datasets } \examples{ data(dem2gbp) head(dem2gbp) tail(dem2gbp) str(dem2gbp) plot(dem2gbp[[1]]) data(sp500dge) head(sp500dge) tail(sp500dge) str(sp500dge) plot(sp500dge[[1]]) } \keyword{datasets} \keyword{ts} fGarch/man/garchFit.Rd0000755000176200001440000003224014327162154014246 0ustar liggesusers\name{garchFit} \alias{garchFit} \alias{garchKappa} \alias{.gogarchFit} \concept{GARCH model} \concept{APARCH model} \concept{ARMA-GARCH model} \concept{ARMA-APARCH model} \concept{AR-GARCH model} \concept{AR-APARCH model} \concept{MA-GARCH model} \concept{MA-APARCH model} \concept{fit GARCH model} \concept{fit APARCH model} \concept{fit ARMA-GARCH model} \concept{fit ARMA-APARCH model} \concept{fit AR-GARCH model} \concept{fit AR-APARCH model} \concept{fit MA-GARCH model} \concept{fit MA-APARCH model} \title{Univariate or multivariate GARCH time series fitting} \description{ Estimates the parameters of a univariate ARMA-GARCH/APARCH process, or --- experimentally --- of a multivariate GO-GARCH process model. The latter uses an algorithm based on \code{fastICA()}, inspired from Bernhard Pfaff's package \CRANpkg{gogarch}. } \usage{ garchFit(formula = ~ garch(1, 1), data, init.rec = c("mci", "uev"), delta = 2, skew = 1, shape = 4, cond.dist = c("norm", "snorm", "ged", "sged", "std", "sstd", "snig", "QMLE"), include.mean = TRUE, include.delta = NULL, include.skew = NULL, include.shape = NULL, leverage = NULL, trace = TRUE, %recursion = c("internal", "filter", "testing"), algorithm = c("nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), hessian = c("ropt", "rcd"), control = list(), title = NULL, description = NULL, \dots) garchKappa(cond.dist = c("norm", "ged", "std", "snorm", "sged", "sstd", "snig"), gamma = 0, delta = 2, skew = NA, shape = NA) .gogarchFit(formula = ~garch(1, 1), data, init.rec = c("mci", "uev"), delta = 2, skew = 1, shape = 4, cond.dist = c("norm", "snorm", "ged", "sged", "std", "sstd", "snig", "QMLE"), include.mean = TRUE, include.delta = NULL, include.skew = NULL, include.shape = NULL, leverage = NULL, trace = TRUE, algorithm = c("nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), hessian = c("ropt", "rcd"), control = list(), title = NULL, description = NULL, \dots) } \arguments{ %\item{recursion}{ % a string parameter that determines the recursion used for calculating % the maximum log-likelihood function. % Allowed values are ... %} \item{algorithm}{ a string parameter that determines the algorithm used for maximum likelihood estimation. % Allowed values are % \code{"nmfb"}, % \code{"sqp"}, % \code{"nlminb"}, and % \code{"bfgs"} where the third is the default % setting. \code{"mnfb"} is a fully Fortran implemented and extremely % fast version of the R-coded \code{"nlminb"} algorithm. } \item{cond.dist}{ a character string naming the desired conditional distribution. Valid values are \code{"dnorm"}, \code{"dged"}, \code{"dstd"}, \code{"dsnorm"}, \code{"dsged"}, \code{"dsstd"} and \code{"QMLE"}. The default value is the normal distribution. See Details for more information. } \item{control}{ control parameters, the same as used for the functions from \code{nlminb}, and 'bfgs' and 'Nelder-Mead' from \code{optim}. } \item{data}{ an optional timeSeries or data frame object containing the variables in the model. If not found in \code{data}, the variables are taken from \code{environment(formula)}, typically the environment from which \code{armaFit} is called. If \code{data} is an univariate series, then the series is converted into a numeric vector and the name of the response in the formula will be neglected. } \item{delta}{ a numeric value, the exponent \code{delta} of the variance recursion. By default, this value will be fixed, otherwise the exponent will be estimated together with the other model parameters if \code{include.delta=FALSE}. } \item{description}{optional character string with a brief description.} \item{formula}{ \code{\link{formula}} object describing the mean and variance equation of the ARMA-GARCH/APARCH model. A pure GARCH(1,1) model is selected e.g., for \code{formula = ~garch(1,1)}. To specify an ARMA(2,1)-APARCH(1,1) process, use \code{ ~ arma(2,1) + aparch(1,1)}. } \item{gamma}{ APARCH leverage parameter entering into the formula for calculating the expectation value. } \item{hessian}{ a string denoting how the Hessian matrix should be evaluated, either \code{hessian ="rcd"}, or \code{"ropt"}. The default, \code{"rcd"} is a central difference approximation implemented in \R and \code{"ropt"} uses the internal R function \code{optimhess}. } \item{include.delta}{a \code{\link{logical}} determining if the parameter for the recursion equation \code{delta} will be estimated or not. If false, the shape parameter will be kept fixed during the process of parameter optimization.} \item{include.mean}{ this flag determines if the parameter for the mean will be estimated or not. If \code{include.mean=TRUE} this will be the case, otherwise the parameter will be kept fixed durcing the process of parameter optimization. } \item{include.shape}{ a logical flag which determines if the parameter for the shape of the conditional distribution will be estimated or not. If \code{include.shape=FALSE} then the shape parameter will be kept fixed during the process of parameter optimization. } \item{include.skew}{ a logical flag which determines if the parameter for the skewness of the conditional distribution will be estimated or not. If \code{include.skew=FALSE} then the skewness parameter will be kept fixed during the process of parameter optimization. } \item{init.rec}{ a character string indicating the method how to initialize the mean and varaince recursion relation. } \item{leverage}{ a logical flag for APARCH models. Should the model be leveraged? By default \code{leverage=TRUE}. } \item{shape}{ a numeric value, the shape parameter of the conditional distribution. } \item{skew}{ a numeric value, the skewness parameter of the conditional distribution. } \item{title}{ a character string which allows for a project title. } \item{trace}{ a logical flag. Should the optimization process of fitting the model parameters be printed? By default \code{trace=TRUE}. } \item{\dots}{ additional arguments to be passed. } } \details{ \code{"QMLE"} stands for Quasi-Maximum Likelihood Estimation, which assumes normal distribution and uses robust standard errors for inference. Bollerslev and Wooldridge (1992) proved that if the mean and the volatility equations are correctly specified, the QML estimates are consistent and asymptotically normally distributed. However, the estimates are not efficient and \dQuote{the efficiency loss can be marked under asymmetric ... distributions} (Bollerslev and Wooldridge (1992), p. 166). The robust variance-covariance matrix of the estimates equals the (Eicker-White) sandwich estimator, i.e. \deqn{V = H^{-1} G^{\prime} G H^{-1},}{V = H^(-1) G' G H^(-1),} where \eqn{V}{V} denotes the variance-covariance matrix, \eqn{H}{H} stands for the Hessian and \eqn{G}{G} represents the matrix of contributions to the gradient, the elements of which are defined as \deqn{G_{t,i} = \frac{\partial l_{t}}{\partial \zeta_{i}},}{% G_{t,i} = derivative of l_{t} w.r.t. zeta_{i},} where \eqn{t_{t}}{l_{t}} is the log likelihood of the t-th observation and \eqn{\zeta_{i}}{zeta_{i}} is the i-th estimated parameter. See sections 10.3 and 10.4 in Davidson and MacKinnon (2004) for a more detailed description of the robust variance-covariance matrix. } \value{ for \code{garchFit}, an S4 object of class \code{"\linkS4class{fGARCH}"}. Slot \code{@fit} contains the results from the optimization. for \code{.gogarchFit()}: Similar definition for GO-GARCH modeling. Here, \code{data} must be \emph{multivariate}. Still \dQuote{preliminary}, mostly undocumented, and untested(!). At least mentioned here... } \references{ ATT (1984); \emph{PORT Library Documentation}, http://netlib.bell-labs.com/netlib/port/. Bera A.K., Higgins M.L. (1993); \emph{ARCH Models: Properties, Estimation and Testing}, J. Economic Surveys 7, 305--362. Bollerslev T. (1986); \emph{Generalized Autoregressive Conditional Heteroscedasticity}, Journal of Econometrics 31, 307--327. Bollerslev T., Wooldridge J.M. (1992); \emph{Quasi-Maximum Likelihood Estimation and Inference in Dynamic Models with Time-Varying Covariance}, Econometric Reviews 11, 143--172. Byrd R.H., Lu P., Nocedal J., Zhu C. (1995); \emph{A Limited Memory Algorithm for Bound Constrained Optimization}, SIAM Journal of Scientific Computing 16, 1190--1208. Davidson R., MacKinnon J.G. (2004); \emph{Econometric Theory and Methods}, Oxford University Press, New York. Engle R.F. (1982); \emph{Autoregressive Conditional Heteroscedasticity with Estimates of the Variance of United Kingdom Inflation}, Econometrica 50, 987--1008. Nash J.C. (1990); \emph{Compact Numerical Methods for Computers}, Linear Algebra and Function Minimisation, Adam Hilger. Nelder J.A., Mead R. (1965); \emph{A Simplex Algorithm for Function Minimization}, Computer Journal 7, 308--313. Nocedal J., Wright S.J. (1999); \emph{Numerical Optimization}, Springer, New York. } \author{ Diethelm Wuertz for the Rmetrics \R-port,\cr R Core Team for the 'optim' \R-port,\cr Douglas Bates and Deepayan Sarkar for the 'nlminb' \R-port,\cr Bell-Labs for the underlying PORT Library,\cr Ladislav Luksan for the underlying Fortran SQP Routine, \cr Zhu, Byrd, Lu-Chen and Nocedal for the underlying L-BFGS-B Routine. Martin Maechler for cleaning up; \emph{mentioning} \code{.gogarchFit()}. } \seealso{ \code{\link{garchSpec}}, \code{\link{garchFitControl}}, class \code{"\linkS4class{fGARCH}"} } \examples{ ## UNIVARIATE TIME SERIES INPUT: # In the univariate case the lhs formula has not to be specified ... # A numeric Vector from default GARCH(1,1) - fix the seed: N = 200 x.vec = as.vector(garchSim(garchSpec(rseed = 1985), n = N)[,1]) garchFit(~ garch(1,1), data = x.vec, trace = FALSE) # An univariate timeSeries object with dummy dates: stopifnot(require("timeSeries")) x.timeSeries = dummyDailySeries(matrix(x.vec), units = "GARCH11") garchFit(~ garch(1,1), data = x.timeSeries, trace = FALSE) \dontrun{ # An univariate zoo object: require("zoo") x.zoo = zoo(as.vector(x.vec), order.by = as.Date(rownames(x.timeSeries))) garchFit(~ garch(1,1), data = x.zoo, trace = FALSE) } # An univariate "ts" object: x.ts = as.ts(x.vec) garchFit(~ garch(1,1), data = x.ts, trace = FALSE) ## MULTIVARIATE TIME SERIES INPUT: # For multivariate data inputs the lhs formula must be specified ... # A numeric matrix binded with dummy random normal variates: X.mat = cbind(GARCH11 = x.vec, R = rnorm(N)) garchFit(GARCH11 ~ garch(1,1), data = X.mat) # A multivariate timeSeries object with dummy dates: X.timeSeries = dummyDailySeries(X.mat, units = c("GARCH11", "R")) garchFit(GARCH11 ~ garch(1,1), data = X.timeSeries) \dontrun{ # A multivariate zoo object: X.zoo = zoo(X.mat, order.by = as.Date(rownames(x.timeSeries))) garchFit(GARCH11 ~ garch(1,1), data = X.zoo) } # A multivariate "mts" object: X.mts = as.ts(X.mat) garchFit(GARCH11 ~ garch(1,1), data = X.mts) ## MODELING THE PERCENTUAL SPI/SBI SPREAD FROM LPP BENCHMARK: stopifnot(require("timeSeries")) X.timeSeries = as.timeSeries(data(LPP2005REC)) X.mat = as.matrix(X.timeSeries) \dontrun{X.zoo = zoo(X.mat, order.by = as.Date(rownames(X.mat)))} X.mts = ts(X.mat) garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.timeSeries) # The remaining are not yet supported ... # garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.mat) # garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.zoo) # garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.mts) ## MODELING HIGH/LOW RETURN SPREADS FROM MSFT PRICE SERIES: X.timeSeries = MSFT garchFit(Open ~ garch(1,1), data = returns(X.timeSeries)) garchFit(100*(High-Low) ~ garch(1,1), data = returns(X.timeSeries)) ## GO-GARCH Modelling (not yet!!) % FIXME ## data(DowJones30, package="fEcofin") # no longer exists ## X = returns(as.timeSeries(DowJones30)); head(X) ## N = 5; ans = .gogarchFit(data = X[, 1:N], trace = FALSE); ans ## ans@h.t } \keyword{models} fGarch/man/methods-predict.Rd0000644000176200001440000001111614556732764015624 0ustar liggesusers\name{predict-methods} \alias{predict-methods} \docType{methods} \alias{predict} \alias{predict,fGARCH-method} \concept{VaR} \concept{value-at-risk} \concept{ES} \concept{expected shortfall} \title{GARCH prediction function} \description{ Predicts a time series from a fitted GARCH object. } \usage{ \S4method{predict}{fGARCH}(object, n.ahead = 10, trace = FALSE, mse = c("cond","uncond"), plot=FALSE, nx=NULL, crit_val=NULL, conf=NULL, \dots, p_loss = NULL) } \arguments{ \item{n.ahead}{ an integer value, denoting the number of steps to be forecasted, by default 10.} \item{object}{ an object of class \code{"fGARCH"} as returned by the function \code{garchFit}.} \item{trace}{ a logical flag. Should the prediction process be traced? By default \code{trace=FALSE}.} \item{mse}{ If set to \code{"cond"}, \code{meanError} is defined as the conditional mean errors \eqn{\sqrt{E_t[x_{t+h}-E_t(x_{t+h})]^2}}. If set to \code{"uncond"}, it is defined as \eqn{\sqrt{E[x_{t+h}-E_t(x_{t+h})]^2}}.} \item{plot}{If set to \code{TRUE}, the confidence intervals are computed and plotted} \item{nx}{The number of observations to be plotted along with the predictions. The default is \code{round(n*0.25)}, where n is the sample size.} \item{crit_val}{The critical values for the confidence intervals when \code{plot} is set to \code{TRUE}. The intervals are defined as \eqn{\hat{x}_{t+h}} + \code{crit_val[2] * meanError} and \eqn{\hat{x}_{t+h}} + \code{crit_val[1] * meanError} if two critical values are provided and \eqn{\hat{x}_{t+h} \pm} \code{crit_val * meanError} if only one is given. If you do not provide critical values, they will be computed automatically. } \item{conf}{The confidence level for the confidence intervals if \code{crit_val} is not provided. By default it is set to 0.95. The critical values are then computed using the conditional distribution that was chosen to create the \code{object} with \code{garchFit} using the same \code{shape} and \code{skew} parameters. If the conditionnal distribution was set to \code{"QMLE"}, the critical values are computed using the empirical distribution of the standardized residuals. } \item{\dots}{ additional arguments to be passed. } \item{p_loss}{ if not null, compute predictions for VaR and ES for loss level \code{p_loss} (typically, 0.05 or 0.01). } } \details{ The predictions are returned as a data frame with columns \code{"meanForecast"}, \code{"meanError"}, and \code{"standardDeviation"}. Row \code{h} contains the predictions for horizon \code{h} (so, \code{n.ahead} rows in total). If \code{plot = TRUE}, the data frame contain also the prediction limits for each horizon in columns \code{lowerInterval} and \code{upperInterval}. If \code{p_loss} is not NULL, predictions of Value-at-Risk (VaR) and Expected Shortfall (ES) are returned in columns \code{VaR} and \code{ES}. The data frame has attribute \code{"p_loss"} containing \code{p_loss}. Typical values for \code{p_loss} are 0.01 and 0.05. These are somewhat experimental and the arguments and the returned values may change. } \value{ a data frame containing \code{n.ahead} rows and 3 to 7 columns, see section \sQuote{Details} } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link[stats]{predict}} in base R \code{\link{fitted}}, \code{\link{residuals}}, \code{\link{plot}}, \code{\link{garchFit}}, class \code{\linkS4class{fGARCH}}, } \examples{ ## Parameter Estimation of Default GARCH(1,1) Model set.seed(123) fit = garchFit(~ garch(1, 1), data = garchSim(), trace = FALSE) fit ## predict predict(fit, n.ahead = 10) predict(fit, n.ahead = 10, mse="uncond") ## predict with plotting: critical values = +/- 2 predict(fit, n.ahead = 10, plot=TRUE, crit_val = 2) ## include also VaR and ES at 5\% predict(fit, n.ahead = 10, plot=TRUE, crit_val = 2, p_loss = 0.05) ## predict with plotting: automatic critical values ## for different conditional distributions set.seed(321) fit2 = garchFit(~ garch(1, 1), data = garchSim(), trace=FALSE, cond.dist="sged") ## 95\% confidence level predict(fit2, n.ahead=20, plot=TRUE) set.seed(444) fit3 = garchFit(~ garch(1, 1), data = garchSim(), trace=FALSE, cond.dist="QMLE") ## 90\% confidence level and nx=100 predict(fit3, n.ahead=20, plot=TRUE, conf=.9, nx=100) } \keyword{models} \keyword{ts} fGarch/man/dist-sgedFit.Rd0000755000176200001440000000277214326164150015051 0ustar liggesusers\name{sgedFit} \alias{sgedFit} \title{Skew generalized error distribution parameter estimation} \description{ Function to fit the parameters of the skew generalized error distribution. } \usage{ sgedFit(x, \dots) } \arguments{ \item{x}{ a numeric vector of quantiles. } \item{\dots}{ parameters parsed to the optimization function \code{nlm}. } } \value{ \code{sgedFit} returns a list with the following components: \item{par}{ The best set of parameters found. } \item{objective}{ The value of objective corresponding to \code{par}. } \item{convergence}{ An integer code. 0 indicates successful convergence. } \item{message}{ A character string giving any additional information returned by the optimizer, or NULL. For details, see PORT documentation. } \item{iterations}{ Number of iterations performed. } \item{evaluations}{ Number of objective function and gradient function evaluations. } } \references{ Nelson D.B. (1991); \emph{Conditional Heteroscedasticity in Asset Returns: A New Approach}, Econometrica, 59, 347--370. Fernandez C., Steel M.F.J. (2000); \emph{On Bayesian Modelling of Fat Tails and Skewness}, Preprint, 31 pages. } \author{ Diethelm Wuertz for the Rmetrics \R-port } \seealso{ \code{\link{sged}}, \code{\link{sgedSlider}} } \examples{ ## rsged - set.seed(1953) r = rsged(n = 1000) ## sgedFit - sgedFit(r) } \keyword{distribution} fGarch/DESCRIPTION0000644000176200001440000000301314557030206013151 0ustar liggesusersPackage: fGarch Title: Rmetrics - Autoregressive Conditional Heteroskedastic Modelling Version: 4032.91 Authors@R: c(person("Diethelm", "Wuertz", role="aut", comment = "original code") , person("Yohan", "Chalabi", role = "aut") , person("Tobias", "Setz", role = c("aut"), email = "tobias.setz@live.com") , person("Martin","Maechler", role="aut", email="maechler@stat.math.ethz.ch", comment = c(ORCID = "0000-0002-8685-9910")) , person("Chris", "Boudt", role = "ctb") , person("Pierre", "Chausse", role = "ctb") , person("Michal", "Miklovac", role = "ctb") , person(given = c("Georgi", "N."), family = "Boshnakov", role = c("aut", "cre"), email = "georgi.boshnakov@manchester.ac.uk") ) Description: Analyze and model heteroskedastic behavior in financial time series. Imports: fBasics, timeDate, timeSeries, fastICA, Matrix (>= 1.5-0), cvar (>= 0.5), graphics, methods, stats, utils Suggests: RUnit, tcltk, goftest LazyData: yes License: GPL (>= 2) URL: https://www.rmetrics.org BugReports: https://r-forge.r-project.org/projects/rmetrics NeedsCompilation: yes Packaged: 2024-02-01 15:41:23 UTC; georgi Author: Diethelm Wuertz [aut] (original code), Yohan Chalabi [aut], Tobias Setz [aut], Martin Maechler [aut] (), Chris Boudt [ctb], Pierre Chausse [ctb], Michal Miklovac [ctb], Georgi N. Boshnakov [aut, cre] Maintainer: Georgi N. Boshnakov Repository: CRAN Date/Publication: 2024-02-02 00:00:06 UTC fGarch/build/0000755000176200001440000000000014556735643012565 5ustar liggesusersfGarch/build/partial.rdb0000644000176200001440000001544714556735643014725 0ustar liggesusers] WX.)Jmi :n|4jwPIATRD)ܿqŬKq* 'nV6U>G BWU*xwP(w:aw*3:l ]wW.}ZbNǮZ꧿|=^ЯzjC n).ՐW& קUK0B辒5z?{tSni]OA?].;Le*u-DgPu5m5O:oɵڲ1 u:;;;ffŮn4*}$dv--+:'5d:t_~ն9#1FN@uHcUs 6VH}!dP/'#x)Ond1yE prZ8=8CN[kNC>/[?iU6ڔl5ůldHކ|;WWT^Ǩ\f4xwɯ/F?ÀW _,T7,pxjcT6m6vd}LoBV7$pBa>D&ME<g2C7_Ǩ=  9+|6WbR{e9V$LU+AwzL/BmqʻBĕ>G { zQJ@ oH#qoforu@ad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", '', basename(dirname(wd))) library(package=pkg, character.only = TRUE) path <- system.file("unitTests", package = pkg) stopifnot(file.exists(path), file.info(path.expand(path))$isdir) source(file.path(path, "runTests.R"), echo = TRUE) } fGarch/src/0000755000176200001440000000000014556735643012255 5ustar liggesusersfGarch/src/math.f0000755000176200001440000000331314263246022013337 0ustar liggesusers C GAMMA FUNCTION: DOUBLE PRECISION FUNCTION DGAM(X) IMPLICIT NONE DOUBLE PRECISION X, G, PI, Z, R, GR INTEGER K, M1, M DIMENSION G(26) DATA G/1.0D0,0.5772156649015329D0, + -0.6558780715202538D0, -0.420026350340952D-1, + 0.1665386113822915D0,-.421977345555443D-1, + -.96219715278770D-2, .72189432466630D-2, + -.11651675918591D-2, -.2152416741149D-3, + .1280502823882D-3, -.201348547807D-4, + -.12504934821D-5, .11330272320D-5, + -.2056338417D-6, .61160950D-8, + .50020075D-8, -.11812746D-8, + .1043427D-9, .77823D-11, + -.36968D-11, .51D-12, + -.206D-13, -.54D-14, .14D-14, .1D-15/ PI = 3.141592653589793D0 DGAM = -99d0 ! -Wall IF (X .EQ. INT(X)) THEN IF (X .GT. 0.0D0) THEN DGAM = 1.0D0 M1 = INT(X)-1 DO K = 2, M1 DGAM = DGAM*K END DO ELSE DGAM = 1.0D+300 END IF ELSE IF (DABS(X) .GT. 1.0D0) THEN Z = DABS(X) M = INT(Z) R = 1.0D0 DO K = 1, M R = R*(Z-K) END DO Z = Z-M ELSE Z = X END IF GR = G(26) DO K = 25, 1, -1 GR = GR*Z + G(K) END DO DGAM = 1.0D0/(GR*Z) IF (DABS(X) .GT. 1.0D0) THEN DGAM = DGAM*R IF (X.LT.0.0D0) DGAM = -PI/(X*DGAM*DSIN(PI*X)) END IF END IF RETURN END C ------------------------------------------------------------------------------ fGarch/src/init.c0000755000176200001440000000120114263246022013340 0ustar liggesusers#include #include // for NULL #include /* in ./llhGarch.f : * SUBROUTINE GARCHLLH(N, Y, Z, H, NF, X, DPARM, MDIST, MYPAR, F) */ extern void F77_NAME(garchllh)(int *N, double *Y, double *Z, double *H, int *NF, double *X, double *DPARM, int *MDIST, int *MYPAR, double *F); static const R_FortranMethodDef FortranEntries[] = { {"garchllh", (DL_FUNC) &F77_NAME(garchllh), 10}, {NULL, NULL, 0} }; void R_init_fGarch(DllInfo *dll) { R_registerRoutines(dll, NULL, NULL, FortranEntries, NULL); R_useDynamicSymbols(dll, FALSE); } fGarch/src/llhGarch.f0000755000176200001440000001044714263246022014140 0ustar liggesusers SUBROUTINE GARCHLLH(N, Y, Z, H, NF, X, DPARM, MDIST, MYPAR, F) IMPLICIT NONE C DECLARATION OF ARGUMENTS INTEGER N DOUBLE PRECISION Y(N), Z(N), H(N) INTEGER NF DOUBLE PRECISION X(NF) DOUBLE PRECISION DPARM(3) INTEGER MDIST INTEGER MYPAR(11) DOUBLE PRECISION F C LOCAL VARIABLES INTEGER INITREC, LEVERAGE, INCMEAN, INCDELTA ,INCSKEW, INCSHAPE INTEGER NR, NS, NP, NQ, NORM DOUBLE PRECISION XMEAN, XOMEGA, XDELTA, XSKEW, XSHAPE INTEGER IAR, IMA, IOMEGA, IALPHA, IBETA, IDELTA, ISKEW, ISHAPE INTEGER I, NEXT, IP, IQ, IR DOUBLE PRECISION SUMALPHA, SUMBETA, PERSISTENCE DOUBLE PRECISION VAR, ZI, ZZ, HH, LLH, DD DOUBLE PRECISION XINVD C EXTERNAL FUNC DOUBLE PRECISION DLOG, DIST C MYPAR INITREC = MYPAR(1) LEVERAGE = MYPAR(2) INCMEAN = MYPAR(3) INCDELTA = MYPAR(4) INCSKEW = MYPAR(5) INCSHAPE = MYPAR(6) NR = MYPAR(7) NS = MYPAR(8) NP = MYPAR(9) NQ = MYPAR(10) NORM = MYPAR(11) C DPARM XDELTA = DPARM(1) XSKEW = DPARM(2) XSHAPE = DPARM(3) C VECTOR START POSITIONS: IAR = INCMEAN + 1 IMA = INCMEAN+NR + 1 IOMEGA = INCMEAN+NR+NS + 1 IALPHA = INCMEAN+NR+NS+1 + 1 IBETA = INCMEAN+NR+NS+1+NP*(1+LEVERAGE) + 1 IDELTA = INCMEAN+NR+NS+1+NP*(1+LEVERAGE)+NQ + 1 ISKEW = INCMEAN+NR+NS+1+NP*(1+LEVERAGE)+NQ+INCDELTA + 1 ISHAPE = INCMEAN+NR+NS+1+NP*(1+LEVERAGE)+NQ+INCDELTA+INCSKEW+1 C TODO C INCLUDE MEAN? IF (INCMEAN.EQ.1) THEN XMEAN = X(1) ELSE XMEAN = 0.0D0 END IF C INCLUDE DELTA ? IF (INCDELTA.EQ.1) THEN XDELTA = X(IDELTA) END IF XINVD = 1.0D0/XDELTA C INCLUDE SKEW ? IF (INCSKEW.EQ.1) THEN XSKEW = X(ISKEW) END IF C INCLUDE SHAPE ? IF (INCSHAPE.EQ.1) THEN XSHAPE = X(ISHAPE) END IF C POSTION OMEGA: XOMEGA = X(IOMEGA) C ARMA RECURSION: DO I = 1, MAX(NR,NS) Z(I) = 0.0D0 END DO DO I = MAX(NR,NS)+1, N Z(I) = Y(I) - XMEAN NEXT = IAR DO IR = 1, NR, 1 Z(I) = Z(I) - X(NEXT)*Y(I-IR) NEXT = NEXT + 1 END DO NEXT = IMA DO IR = 1, NS, 1 Z(I) = Z(I) - X(NEXT)*Z(I-IR) NEXT = NEXT + 1 END DO END DO C COMPUTE (UNLEVERAGED) PERSISTENCE: SUMALPHA = 0.0D0 NEXT = IALPHA DO IP = 1, NP, 1 SUMALPHA = SUMALPHA + X(NEXT) NEXT = NEXT + 1 END DO NEXT = IBETA SUMBETA = 0.0D0 DO IP = 1, NQ, 1 SUMBETA = SUMBETA + X(NEXT) NEXT = NEXT + 1 END DO PERSISTENCE = SUMALPHA + SUMBETA C INITIALZE RECURSION - 1 (FCP) | 2 (TSP) LIKE: VAR = -99.D0 ! -Wall IF (INITREC.EQ.1) THEN VAR = 0.0D0 DO I = 1, N VAR = VAR + Z(I)**2 END DO VAR = VAR/N END IF IF (INITREC.EQ.2) THEN VAR = XOMEGA/(1.0D0-PERSISTENCE) END IF C ITERATE H: DO I = 1, MAX(NP,NQ) H(I) = XOMEGA + PERSISTENCE*VAR END DO IF (LEVERAGE.EQ.1) THEN DO I = MAX(NP,NQ)+1, N H(I) = XOMEGA NEXT = IALPHA DO IP = 1, NP, 1 ZI = DABS(Z(I-IP))-X(NEXT+NP)*Z(I-IP) H(I) = H(I) + X(NEXT)*DABS(ZI)**XDELTA NEXT = NEXT + 1 END DO NEXT = IBETA DO IQ = 1, NQ, 1 H(I) = H(I) + X(NEXT)*H(I-IQ) NEXT = NEXT + 1 END DO END DO ELSE DO I = MAX(NP,NQ)+1, N H(I) = XOMEGA NEXT = IALPHA DO IP = 1, NP, 1 H(I) = H(I) + X(NEXT)*DABS(Z(I-IP))**XDELTA NEXT = NEXT + 1 END DO NEXT = IBETA DO IQ = 1, NQ, 1 H(I) = H(I) + X(NEXT)*H(I-IQ) NEXT = NEXT + 1 END DO END DO END IF C COMPUTE LIKELIHOOD: LLH = 0.0D0 DO I = 1, N ZZ = Z(I) HH = DABS(H(I))**XINVD DD = DLOG( DIST(ZZ, HH, XSKEW, XSHAPE, MDIST) ) LLH = LLH - DD END DO F = LLH RETURN END fGarch/src/Makevars0000755000176200001440000000005614263246022013734 0ustar liggesusersPKG_LIBS=$(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) fGarch/src/dist.f0000755000176200001440000001230114263246022013346 0ustar liggesusers C ------------------------------------------------------------------------------ C CONDITIONAL DISTRIBUTON: DOUBLE PRECISION FUNCTION DIST(Z, HH, SKEW, SHAPE, NDIST) c ---- IMPLICIT NONE INTEGER NDIST DOUBLE PRECISION Z, HH, SKEW, SHAPE c Local variables: DOUBLE PRECISION DNORM, DSNORM, DSTD, DSSTD, DGED, DSGED DIST = -99.d0 ! -Wall IF (NDIST.EQ.10) THEN C NORMAL: DIST = DNORM(Z/HH)/HH RETURN END IF IF (NDIST.EQ.11) THEN C SKEW NORMAL: DIST = DSNORM(Z/HH, SKEW)/HH RETURN END IF IF (NDIST.EQ.20) THEN C STUDENT-T: DIST = DSTD(Z/HH, SHAPE)/HH RETURN END IF IF (NDIST.EQ.21) THEN C SKEW STUDENT-T: DIST = DSSTD(Z/HH, SHAPE, SKEW)/HH RETURN END IF IF (NDIST.EQ.30) THEN C GED: DIST = DGED(Z/HH, SHAPE)/HH RETURN END IF IF (NDIST.EQ.31) THEN C SKEW GED: DIST = DSGED(Z/HH, SHAPE, SKEW)/HH RETURN END IF RETURN END C ------------------------------------------------------------------------------ C NORMAL: DOUBLE PRECISION FUNCTION DNORM(X) IMPLICIT NONE DOUBLE PRECISION X DOUBLE PRECISION PI, TWO PI = 3.141592653589793D0 TWO = 2.0D0 DNORM = DEXP(-X**2/TWO) / DSQRT(TWO*PI) RETURN END C ------------------------------------------------------------------------------ C SKEW NORMAL: DOUBLE PRECISION FUNCTION DSNORM(X, XI) IMPLICIT NONE DOUBLE PRECISION X, XI DOUBLE PRECISION ONE, TWO, PI, M1, MU, SIGMA DOUBLE PRECISION Z, XXI, G DOUBLE PRECISION DNORM ONE = 1.0D0 TWO = 2.0D0 PI = 3.141592653589793D0 M1 = TWO/DSQRT(TWO*PI) MU = M1*(XI-ONE/XI) SIGMA = DSQRT((ONE-M1**2)*(XI**2+ONE/XI**2)+TWO*M1**2-ONE) Z = X*SIGMA+MU XXI = XI**SIGN(ONE, Z) IF (Z.EQ.0.0D0) THEN XXI = XI**0.0D0 END IF G = TWO/(XI+ONE/XI) DSNORM = G*DNORM(Z/XXI)*SIGMA RETURN END C ------------------------------------------------------------------------------ C GED: DOUBLE PRECISION FUNCTION DGED(X, NU) IMPLICIT NONE DOUBLE PRECISION X, NU DOUBLE PRECISION HALF, ONE, TWO, THREE, LAMBDA, G DOUBLE PRECISION DGAM HALF = 0.50D0 ONE = 1.0D0 TWO = 2.0D0 THREE = 3.0D0 LAMBDA = DSQRT(TWO**(-TWO/NU)*DGAM(ONE/NU)/DGAM(THREE/NU)) G = NU/(LAMBDA*(TWO**(ONE+ONE/NU))*DGAM(ONE/NU)) DGED = G*DEXP(-HALF*(DABS(X/LAMBDA))**NU) RETURN END C ------------------------------------------------------------------------------ C SKEW GED: DOUBLE PRECISION FUNCTION DSGED(X, NU, XI) IMPLICIT NONE DOUBLE PRECISION X, NU, XI DOUBLE PRECISION HALF, ONE, TWO, THREE, LAMBDA, G, M1, MU DOUBLE PRECISION SIGMA, Z, XXI DOUBLE PRECISION DGAM, DGED HALF = 0.50D0 ONE = 1.0D0 TWO = 2.0D0 THREE = 3.0D0 LAMBDA = DSQRT(TWO**(-TWO/NU)*DGAM(ONE/NU)/DGAM(THREE/NU)) G = NU/(LAMBDA*(TWO**(ONE+ONE/NU))*DGAM(ONE/NU)) M1 = (TWO**(ONE/NU))*LAMBDA*DGAM(TWO/NU)/DGAM(ONE/NU) MU = M1*(XI-ONE/XI) SIGMA = (ONE-M1**2)*(XI**2+ONE/(XI**2))+TWO*(M1**2)-ONE SIGMA = DSQRT(SIGMA) Z = X*SIGMA+MU XXI = XI**SIGN(ONE, Z) IF (Z.EQ.0.0D0) THEN XXI = XI**0.0D0 END IF DSGED = (TWO/(XI+ONE/XI))*DGED(Z/XXI, NU)*SIGMA RETURN END C ------------------------------------------------------------------------------ C STUDENT T: DOUBLE PRECISION FUNCTION DT(X, NU) IMPLICIT NONE DOUBLE PRECISION X, NU DOUBLE PRECISION ONE, TWO, PI, A, B DOUBLE PRECISION DGAM ONE = 1.0D0 TWO = 2.0D0 PI = 3.141592653589793D0 A = DGAM((NU+ONE)/TWO)/DSQRT(PI*NU) B = DGAM(NU/TWO)*(ONE+(X*X)/NU)**((NU+ONE)/TWO) DT = A/B RETURN END C ------------------------------------------------------------------------------ C STANDARDIZED STUDENT T: DOUBLE PRECISION FUNCTION DSTD(X, NU) IMPLICIT NONE DOUBLE PRECISION X, NU DOUBLE PRECISION TWO, S DOUBLE PRECISION DT TWO = 2.0D0 S = DSQRT(NU/(NU-TWO)) DSTD = S*DT(X*S,NU) RETURN END C ------------------------------------------------------------------------------ C STANDARDIZED SKEW STUDENT T: DOUBLE PRECISION FUNCTION DSSTD(X, NU, XI) IMPLICIT NONE DOUBLE PRECISION X, NU, XI DOUBLE PRECISION ONE, TWO, A, B, BETA, M1, MU DOUBLE PRECISION SIGMA, Z, G, XXI DOUBLE PRECISION DSTD, DGAM ONE = 1.0D0 TWO = 2.0D0 A = ONE/TWO B = NU/TWO BETA = (DGAM(A)/DGAM(A+B))*DGAM(B) M1 = TWO*DSQRT(NU-TWO)/(NU-ONE)/BETA MU = M1*(XI-ONE/XI) SIGMA = DSQRT((ONE-M1**2)*(XI**2+ONE/XI**2)+TWO*M1**2-ONE) Z = X*SIGMA+MU XXI = XI**SIGN(ONE, Z) IF (Z.EQ.0.0D0) THEN XXI = XI**0.0D0 END IF G = TWO/(XI+ONE/XI) DSSTD = G*DSTD(Z/XXI,NU)*SIGMA RETURN END fGarch/R/0000755000176200001440000000000014556511050011647 5ustar liggesusersfGarch/R/loglik-aparch.R0000755000176200001440000004107114263246022014514 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .aparchLLH.internal Internal ARMA-APARCH recursion done by Fortran Code # .aparchLLH.filter Fast approach using the filter function in R # .aparchLLH.testing Simple double loops over time and order in R ################################################################################ .aparchLLH.internal <- function(params, trace = TRUE, fGarchEnv = TRUE) { # A function implemented by Diethelm Wuertz # Description: # Internal ARMA-APARCH recursion done by Fortran Code # Arguments: # params - a named numeric vector with the model parameters # to be optimized # trace - # fGarchEnv - # Value: # Returns the value of the max log-likelihood function. # Note: # The variables '.series' and '.params' must be global available # FUNCTION: # DEBUG: DEBUG = FALSE if (DEBUG) print("Entering Function .garchLLH.internal") # Get Global Variables: .series <- .getfGarchEnv(".series") .params <- .getfGarchEnv(".params") .garchDist <- .getfGarchEnv(".garchDist") .llh <- .getfGarchEnv(".llh") # How to calculate the LLH Function? if (DEBUG) print(.params$control$llh) if(.params$control$llh == "internal") { INDEX <- .params$index MDIST <- c(norm = 10, QMLE = 10, snorm = 11, std = 20, sstd = 21, ged = 30, sged = 31)[.params$cond.dist] if(.params$control$fscale) NORM <- length(.series$x) else NORM = 1 REC <- 1 if(.series$init.rec == "uev") REC <- 2 MYPAR <- c( REC = REC, # How to initialize LEV = as.integer(.params$leverage), # Include Leverage 0|1 MEAN = as.integer(.params$includes["mu"]), # Include Mean 0|1 DELTA = as.integer(.params$includes["delta"]),# Include Delta 0|1 SKEW = as.integer(.params$includes["skew"]), # Include Skew 0|1 SHAPE = as.integer(.params$includes["shape"]),# Include Shape 0|1 ORDER = .series$order, # Order of ARMA-GARCH NORM = as.integer(NORM)) # Now Estimate Parameters: MAX <- max(.series$order) NF <- length(INDEX) N <- length(.series$x) DPARM <- c(.params$delta, .params$skew, .params$shape) fit <- .Fortran( "garchllh", N = as.integer(N), Y = as.double(.series$x), # Z = as.double(rep(2, times = N)), # H = as.double(rep(0, times = N)), Z = as.double(.series$z), H = as.double(.series$h), NF = as.integer(NF), X = as.double(params), DPARM = as.double(DPARM), MDIST = as.integer(MDIST), MYPAR = as.integer(MYPAR), F = as.double(0), PACKAGE = "fGarch") llh <- fit[[10]] if(is.na(llh)) llh = .llh + 0.1*(abs(.llh)) if(!is.finite(llh)) llh = .llh + 0.1*(abs(.llh)) .setfGarchEnv(.llh = llh) if (fGarchEnv) { # Save h and z: .series$h <- fit[[4]] .series$z <- fit[[3]] .setfGarchEnv(.series = .series) } } else { stop("LLH is not internal!") } # Return Value: c(LogLikelihood = llh) } # ------------------------------------------------------------------------------ .aparchLLH.filter <- function(params, trace = TRUE, fGarchEnv = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Fast approach using the filter function in R for ARMA-APARCH models # Arguments: # params - a named numeric vector with the model parameters # to be optimized # trace - a logical, should the frunction output be traced ? # fGarchEnv - # Value: # Returns the value of the max log-likelihood function. # Note: # The variables '.series' and '.params' must be global available # FUNCTION: # DEBUG: DEBUG = FALSE if (DEBUG) print("Entering Function .garchLLH.filter") # Get Global Variables: .series <- .getfGarchEnv(".series") .params <- .getfGarchEnv(".params") .garchDist <- .getfGarchEnv(".garchDist") .llh <- .getfGarchEnv(".llh") # Which conditional distribution function should be used ? if(DEBUG) print(.garchDist) # How to calculate the LLH Function? if (DEBUG) print(c("testing ?", .params$control$llh)) if(.params$control$llh == "filter") { # Retrieve From Initialized Series: x = .series$x # Get Order: u = .series$order[1] v = .series$order[2] p = .series$order[3] q = .series$order[4] max.order = max(u, v, p, q) # Get Start Conditions: h.start = .series$h.start llh.start = .series$llh.start # Get the Index Values and Add Names - Just to be Sure: index = .params$index names(params) = names(.params$params[index]) Names = names(params) # Retrieve From Initialized Parameters: cond.dist = .params$cond.dist # Extracting the parameters by name ... alpha <- beta <- NULL mu = c(mu = .params$mu) delta = c(delta = .params$delta) skew = c(skew = .params$skew) shape = c(shape = .params$shape) leverage = c(leverage = .params$leverage) if(.params$includes["mu"]) mu = params["mu"] if(u > 0) ar = params[substr(Names, 1, 2) == "ar"] if(v > 0) ma = params[substr(Names, 1, 2) == "ma"] omega = params[substr(Names, 1, 5) == "omega"] if(p > 0) alpha = params[substr(Names, 1, 5) == "alpha"] if(p > 0 & leverage) gamma = params[substr(Names, 1, 5) == "gamma"] if(p > 0 & !leverage) gamma = rep(0, times = p) if(q > 0) beta = params[substr(Names, 1, 4) == "beta"] if(.params$includes["delta"]) delta = params["delta"] if(.params$includes["skew"]) skew = params["skew"] if(.params$includes["shape"]) shape = params["shape"] if(DEBUG) print(params) # Iterate z: N = length(x) z = rep(0, N) if(u > 0 & v > 0) for (i in (h.start):N) z[i] = x[i] - mu - sum(ar*x[i-(1:u)]) - sum(ma*z[i-(1:v)]) if(u > 0 & v == 0) for (i in (h.start):N) z[i] = x[i] - mu - sum(ar*x[i-(1:u)]) if(u == 0 & v > 0) for (i in (h.start):N) z[i] = x[i] - mu - sum(ma*z[i-(1:v)]) if(u == 0 & v == 0) z = x - mu # Initialize Variance Equation: deltainv = 1/delta if(.series$model[2] == "garch") { persistence = sum(alpha) + sum(beta) } else if(.series$model[2] == "aparch") { persistence = sum(beta) for (i in 1:p) persistence = persistence + alpha[i]*garchKappa(cond.dist, gamma[i], delta, skew, shape) } names(persistence) = "persistence" attr(persistence, "control") = NULL attr(persistence, "cond.dist") = NULL .params$persistence <- persistence .setfGarchEnv(.params = .params) mvar = mean(z^2) h = rep(omega + persistence*mvar, N) # Iterate Conditional Variances h: if(p == 0) { alpha = 0 p = 1 } if(q == 0) { beta = 0 q = 1 } # R Filter Representation: # Entirely written in S, and very effective ... # own filter method because as.ts and tsp time consuming... # Note, sometimes one of the beta's can become undefined # during optimization. if(!.params$leverage) gamma = rep(0, p) pq = max(p, q) edeltat = 0 for (j in 1:p) { Filter = rep(0, length = p+1) Filter[j+1] = alpha[j] edelta = (abs(z) - gamma[j]*z)^delta edelta = as.vector(filter(edelta, filter = Filter, sides = 1)) edeltat = edeltat + edelta } c.init = omega/(1-sum(beta)) h <- c(h[1:pq], c.init + as.vector(filter(edeltat[-(1:pq)], filter = beta, method = "recursive", init = h[q:1]-c.init))) ### ? remove ? ### DW: May be not . if( sum(is.na(h)) > 0 ) { # We use the testing Version ... warning("Problems in Filter Representation") if(!.params$leverage) { for (i in (h.start):N) { h[i] = omega + sum(alpha * ( abs(z[i-(1:p)])) ^ delta ) + sum(beta*h[i-(1:q)]) } } else { for (i in (h.start):N) { h[i] = omega + sum(alpha * ( abs(z[i-(1:p)]) - gamma * z[i-(1:p)])^delta ) + sum(beta*h[i-(1:q)]) } } } # Calculate Log Likelihood: hh = (abs(h[(llh.start):N]))^deltainv zz = z[(llh.start):N] llh = -sum(log(.garchDist(z = zz, hh = hh, skew = skew, shape = shape))) if(DEBUG) cat("DEBUG - LLH: ", llh, "\n") names(params) = names(.params$params[.params$index]) if(is.na(llh)) llh = .llh + 0.1*(abs(.llh)) if(!is.finite(llh)) llh = .llh + 0.1*(abs(.llh)) # Print if LLH has Improved: if(llh < .llh) { diff = (.llh - llh)/llh if(trace & diff > 1e-2) { # cat(" LLH: ", llh, " norm LLH: ", llh/N, "\n") # print(params) if(persistence > 1) cat("Warning - Persistence:", persistence, "\n") } .setfGarchEnv(.llh = llh) } if (fGarchEnv) { # Save h and z: .series$h <- h .series$z <- z .setfGarchEnv(.series = .series) } } else { stop("LLH is not filter!") } # Return Value: if (DEBUG) print("Entering Function .garchLLH.filter") c(LogLikelihood = llh) } # ------------------------------------------------------------------------------ .aparchLLH.testing <- function(params, trace = TRUE, fGarchEnv = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Compute Log-Likelihood Function for ARMA-APARCH models # Arguments: # params - a named numeric vector with the model parameters # to be optimized # trace - # fGarchEnv - # Value: # Returns the value of the max log-likelihood function. # Note: # The variables '.series' and '.params' must be global available # FUNCTION: # DEBUG: DEBUG = FALSE if (DEBUG) print("Entering Function .garchLLH.testing") # Get Global Variables: .series <- .getfGarchEnv(".series") .params <- .getfGarchEnv(".params") .garchDist <- .getfGarchEnv(".garchDist") .llh <- .getfGarchEnv(".llh") if(DEBUG) print(.garchDist) # How to calculate the LLH Function? if (DEBUG) print(.params$control$llh) if(.params$control$llh == "testing") { # Retrieve From Initialized Series: x = .series$x # Get Order: u = .series$order[1] v = .series$order[2] p = .series$order[3] q = .series$order[4] max.order = max(u, v, p, q) # Get Start Conditions: h.start = .series$h.start llh.start = .series$llh.start # Get the Index Values and Add Names - Just to be Sure: index = .params$index names(params) = names(.params$params[index]) Names = names(params) # Retrieve From Initialized Parameters: cond.dist = .params$cond.dist if(DEBUG) print(paste("Conditional Distribution:", cond.dist)) # Extracting the parameters by name ... alpha <- beta <- NULL mu = c(mu = .params$mu) delta = c(delta = .params$delta) skew = c(skew = .params$skew) shape = c(shape = .params$shape) leverage = c(leverage = .params$leverage) if(.params$includes["mu"]) mu = params["mu"] if(u > 0) ar = params[substr(Names, 1, 2) == "ar"] if(v > 0) ma = params[substr(Names, 1, 2) == "ma"] omega = params[substr(Names, 1, 5) == "omega"] if(p > 0) alpha = params[substr(Names, 1, 5) == "alpha"] if(p > 0 & leverage) gamma = params[substr(Names, 1, 5) == "gamma"] if(p > 0 & !leverage) gamma = rep(0, times = p) if(q > 0) beta = params[substr(Names, 1, 4) == "beta"] if(.params$includes["delta"]) delta = params["delta"] if(.params$includes["skew"]) skew = params["skew"] if(.params$includes["shape"]) shape = params["shape"] if(DEBUG) print(params) # Iterate z: N = length(x) z = rep(0, N) if(u > 0 & v > 0) for (i in (h.start):N) z[i] = x[i] - mu - sum(ar*x[i-(1:u)]) - sum(ma*z[i-(1:v)]) if(u > 0 & v == 0) for (i in (h.start):N) z[i] = x[i] - mu - sum(ar*x[i-(1:u)]) if(u == 0 & v > 0) for (i in (h.start):N) z[i] = x[i] - mu - sum(ma*z[i-(1:v)]) if(u == 0 & v == 0) z = x - mu # Initialize Variance Equation: deltainv = 1/delta if(.series$model[2] == "garch") { persistence = sum(alpha) + sum(beta) } else if(.series$model[2] == "aparch") { persistence = sum(beta) for (i in 1:p) persistence = persistence + alpha[i]*garchKappa(cond.dist, gamma[i], delta, skew, shape) } names(persistence) = "persistence" attr(persistence, "control") = NULL attr(persistence, "cond.dist") = NULL .params$persistence <- persistence .setfGarchEnv(.params = .params) mvar = mean(z^2) h = rep(omega + persistence*mvar, N) # Initial Values to Iterate Conditional Variances h: if(p == 0) { alpha = 0 p = 1 } if(q == 0) { beta = 0 q = 1 } # Test Version Just a Simple Double 'for' Loop: # As You Can Imagine, Slow Version But Very Useful for Testing: if(!.params$leverage) { for (i in (h.start):N) { h[i] = omega + sum(alpha * ( abs(z[i-(1:p)])) ^ delta ) + sum(beta*h[i-(1:q)]) } } else { for (i in (h.start):N) { h[i] = omega + sum(alpha * ( abs(z[i-(1:p)]) - gamma * z[i-(1:p)])^delta ) + sum(beta*h[i-(1:q)]) } } # Calculate Log Likelihood: hh = (abs(h[(llh.start):N]))^deltainv zz = z[(llh.start):N] llh = -sum(log(.garchDist(z = zz, hh = hh, skew = skew, shape = shape))) if(DEBUG) cat("DEBUG - LLH: ", llh, "\n") names(params) = names(.params$params[.params$index]) if(is.na(llh)) llh = .llh + 0.1*(abs(.llh)) if(!is.finite(llh)) llh = .llh + 0.1*(abs(.llh)) # Print if LLH has Improved: if(llh < .llh) { diff = (.llh - llh)/llh if(trace & diff > 1e-2) { # cat(" LLH: ", llh, " norm LLH: ", llh/N, "\n") # print(params) if(persistence > 1) cat("Warning - Persistence:", persistence, "\n") } .setfGarchEnv(.llh = llh) } if (fGarchEnv) { # Save h and z: .series$h <- h .series$z <- z .setfGarchEnv(.series = .series) } } else { stop("LLH is not testing!") } # Return Value: if (DEBUG) print("Leaving Function .garchLLH.testing") c(LogLikelihood = llh) } ################################################################################ fGarch/R/methods-plot.R0000755000176200001440000003607314263246022014424 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # plot Plot method for an object of class 'fGARCH' # .interactiveGarchPlot Plot interactively # .multGarchPlot Arrange multivariate Plots # .plot.garch.1 Plot Time Series # .plot.garch.2 Plot Conditional SD # .plot.garch.3 Plot Series with 2 Conditional SD Superimposed # .plot.garch.4 Plot ACF of Observations # .plot.garch.5 Plot ACF of Squared Observations # .plot.garch.6 Plot Cross Correlation # .plot.garch.7 Plot Residuals # .plot.garch.8 Plot Conditional SDs # .plot.garch.9 Plot Standardized Residuals # .plot.garch.10 Plot ACF of Standardized Residuals # .plot.garch.11 Plot ACF of Squared Standardized Residuals # .plot.garch.12 Plot Cross Correlation between r^2 and r # .plot.garch.13 Plot QQ-Plot of Standardized Residuals" # .qqDist Quantile-Quantile Points # .qqLine Quantile-Quantile Line ################################################################################ setMethod(f = "plot", signature(x = "fGARCH", y = "missing"), definition = function(x, which = "ask", ...) { # A function implemented by Diethelm Wuertz # Description: # Plot method for an object of class 'fGARCH' # Note: # This method can also be used for plotting graphs fitted by # the function 'garch' from the contributed R package 'tseries'. # FUNCTION: if (as.character(x@call[1]) == ".gogarchFit") { # Plot multivariate GO-Garch model: print("GO-Garch Plot Not Yet Implemented") } else { # Plot univariate Models: .interactiveGarchPlot( x, choices = c( "Time Series", "Conditional SD", "Series with 2 Conditional SD Superimposed", "ACF of Observations", "ACF of Squared Observations", "Cross Correlation", "Residuals", "Conditional SDs", "Standardized Residuals", "ACF of Standardized Residuals", "ACF of Squared Standardized Residuals", "Cross Correlation between r^2 and r", "QQ-Plot of Standardized Residuals"), plotFUN = paste(".plot.garch", 1:13, sep = "."), which = which, ...) } # Return Value: invisible(x) }) # ------------------------------------------------------------------------------ .interactiveGarchPlot <- function(x, choices, plotFUN, which, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # Arguments: # x - an object to be plotted # choices - the character string for the choice menu # plotFUN - the names of the plot functions # which - plot selection, which graph should be # displayed. If a character string named "ask" the # user is interactively asked which to plot, if # a logical vector of length N, those plots which # are set "TRUE" are displayed, if a character string # named "all" all plots are displayed. # FUNCTION: # Some cecks: if (length(choices) != length(plotFUN)) stop("Arguments choices and plotFUN must be of same length.") if (length(which) > length(choices)) stop("Arguments which has incorrect length.") if (length(which) > length(plotFUN)) stop("Arguments which has incorrect length.") # Plot: if (is.numeric(which)) { Which = rep(FALSE, times = length(choices)) Which[which] = TRUE } if (which[1] == "all") { Which = rep(TRUE, times = length(choices)) } if (which[1] == "ask") { .multGarchPlot(x, choices, plotFUN, ...) } else { for ( i in 1:length(choices) ) { FUN = match.fun(plotFUN[i]) if (Which[i]) FUN(x) } } # Return Value: invisible(x) } # ------------------------------------------------------------------------------ .multGarchPlot <- function (x, choices, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function pick = 1 while (pick > 0) { pick = menu ( ### choices = paste("plot:", choices), choices = paste(" ", choices), title = "\nMake a plot selection (or 0 to exit):") # up to 19 plot functions ... switch (pick, .plot.garch.1(x), .plot.garch.2(x), .plot.garch.3(x), .plot.garch.4(x), .plot.garch.5(x), .plot.garch.6(x), .plot.garch.7(x), .plot.garch.8(x), .plot.garch.9(x), .plot.garch.10(x), .plot.garch.11(x), .plot.garch.12(x), .plot.garch.13(x)) } } # ------------------------------------------------------------------------------ .plot.garch.1 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 1. Time Series: xseries = x@data plot(xseries, type = "l", col = "steelblue", ylab = "x", main = "Time Series") abline(h = 0, col = "grey", lty = 3) grid() } # ------------------------------------------------------------------------------ .plot.garch.2 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 2. Conditional SD: xcsd = volatility(x, "sigma") plot(xcsd, type = "l", col = "steelblue", ylab = "x", main = "Conditional SD") abline(h = 0, col = "grey", lty = 3) grid() } # ------------------------------------------------------------------------------ .plot.garch.3 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 3. Series with 2 Conditional SD Superimposed: xseries = x@data xcsd = volatility(x, "sigma") ci = 2 plot(xseries, type = "l", col = "steelblue", ylab = "x", main = "Series with 2 Conditional SD Superimposed") lines(mean(xseries) + ci * xcsd, col = "grey") # or simply xseries ? lines(mean(xseries) - ci * xcsd, col = "grey") abline(h = 0, col = "grey", lty = 3) grid() } # ------------------------------------------------------------------------------ .plot.garch.4 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 4. ACF of the Observations: xseries = as.vector(x@data) n = length(xseries) lag.max = as.integer(10*log10(n)) acf(xseries, lag.max = lag.max, xlab = "Lags", col = "steelblue", main = "ACF of Observations", plot = TRUE) } # ------------------------------------------------------------------------------ .plot.garch.5 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 5. ACF of the Squared Observations: xseries = as.vector(x@data) xseries2 = xseries^2 n = length(xseries) lag.max = as.integer(10*log10(n)) acf(xseries2, lag.max = lag.max, xlab = "Lags", col = "steelblue", main = "ACF of Squared Observations", plot = TRUE) } # ------------------------------------------------------------------------------ .plot.garch.6 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 6. Cross Correlation between x^2 and x: xseries = as.vector(x@data) xseries2 = xseries^2 n = length(xseries) lag.max = as.integer(10*log10(n)) ccf(xseries2, xseries, lag.max = lag.max, xlab = "Lags", main = "Cross Correlation", plot = TRUE, col = "steelblue") } # ------------------------------------------------------------------------------ .plot.garch.7 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 7. Residuals: res = residuals(x, standardize = FALSE) plot(res, type = "l", main = "Residuals", col = "steelblue", ...) abline(h = 0, lty = 3) grid() } # ------------------------------------------------------------------------------ .plot.garch.8 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 8. Conditional SDs: xcsd = volatility(x, "sigma") plot(xcsd, type = "l", main = "Conditional SD's", col = "steelblue", ...) abline(h = 0, lty = 3) grid() } # ------------------------------------------------------------------------------ .plot.garch.9 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 9. Standardized Residuals: sres = residuals(x, standardize = TRUE) plot(sres, type = "l", main = "Standardized Residuals", col = "steelblue", ...) abline(h = 0, lty = 3) grid() } # ------------------------------------------------------------------------------ .plot.garch.10 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 10. ACF of Standardized Residuals: sres = as.matrix(residuals(x, standardize = TRUE)) n = length(sres) lag.max = as.integer(10*log10(n)) acf(sres, lag.max = lag.max, xlab = "Lags", col = "steelblue", main = "ACF of Standardized Residuals", plot = TRUE) } # ------------------------------------------------------------------------------ .plot.garch.11 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 11. ACF of Squared Standardized Residuals: sres2 = as.matrix(residuals(x, standardize = TRUE)^2) n = length(sres2) lag.max = as.integer(10*log10(n)) acf(sres2, lag.max = lag.max, xlab = "Lags", col = "steelblue", main = "ACF of Squared Standardized Residuals", plot = TRUE) } # ------------------------------------------------------------------------------ .plot.garch.12 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 12. Cross Correlation between r^2 and r: sres = residuals(x, standardize = FALSE) sres2 = sres^2 n = length(sres) lag.max = as.integer(10*log10(n)) ccf(sres2, sres, lag.max = lag.max, xlab = "Lags", main = "Cross Correlation", plot = TRUE, col = "steelblue") } # ------------------------------------------------------------------------------ .plot.garch.13 <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Internal plot function # 13. QQ-Plot of Standardized Residuals: sres = residuals(x, standardize = TRUE) cond.dist = x@fit$params$cond.dist cond.dist = paste("q", cond.dist, sep = "") nc = nchar(x@fit$params$cond.dist) parNames <- names(x@fit$par) skew <- if ("skew" %in% parNames) x@fit$par["skew"] else x@fit$params$skew shape <- if ("shape" %in% parNames) x@fit$par["shape"] else x@fit$params$shape if (cond.dist == "qnorm" || cond.dist == "qQMLE") .qqDist(sres, dist = "qnorm") if (cond.dist == "qstd" | cond.dist == "qged") .qqDist(sres, dist = cond.dist, nu = shape) if (cond.dist == "qsnorm") .qqDist(sres, dist = cond.dist, xi = skew) if (cond.dist == "qsstd" | cond.dist == "qsged") .qqDist(sres, dist = cond.dist, xi = skew, nu = shape) if (cond.dist == "qsnig") .qqDist(sres, dist = ".qsnigC", rho = skew, zeta = shape) } # ------------------------------------------------------------------------------ .qqDist <- function (y, dist = "qnorm", ylim = NULL, main = paste(dist, "- QQ Plot"), xlab = "Theoretical Quantiles", ylab = "Sample Quantiles", doplot = TRUE, datax = FALSE, ...) { # A function implemented by Diethelm Wuertz # Description # QQ Plot for arbitray distribution # FUNCTION: # print(dist) # Match Function : qDist = match.fun(dist) # Check Arguments: # if (substr(dist, 1, 1) != "q") stop("dist is misspecified") # test = class(test = try(qDist(0.5, ...), silent = TRUE)) # if (test == "try-error") stop("dist does not exist") # Transform to Vector Mode: y = as.vector(y) # Compute Data: if (has.na <- any(ina <- is.na(y))) { yN = y y = y[!ina] } if (0 == (n <- length(y))) stop("y is empty or has only NAs") x <- qDist(ppoints(n,), ...)[order(order(y))] if (has.na) { y = x x = yN x[!ina] = y y = yN } # Create QQ Plot: if (doplot) { if (is.null(ylim)) ylim = range(y) if (datax) { plot(y, x, main = main, xlab = ylab, ylab = xlab, xlim = ylim, col = "steelblue", cex = 0.7) } else { plot(x, y, main = main, xlab = xlab, ylab = ylab, ylim = ylim, col = "steelblue", cex = 0.7) } .qqLine(y = y, dist = dist, datax = datax, ...) grid() } # Return Value: invisible(if (datax) list(x = y, y = x) else list(x = x, y = y)) } # ------------------------------------------------------------------------------ .qqLine <- function (y, dist = "qnorm", datax = FALSE, ...) { # A function implemented by Diethelm Wuertz # Description # Add slope to QQ Plot for arbitray distribution # FUNCTION: # Match Function : qDist = match.fun(dist) # Check Arguments: # if (substr(dist, 1, 1) != "q") stop("dist is misspecified") # test = class(test = try(qDist(0.5, ...), silent = TRUE)) # if (test == "try-error") stop("dist does not exist") # Transform to Vector Mode: y = as.vector(y) # Compute Data: y = quantile(y[!is.na(y)], c(0.25, 0.75)) x = qDist(c(0.25, 0.75), ...) # Add Slope: if (datax) { slope <- diff(x)/diff(y) int <- x[1] - slope * y[1] } else { slope <- diff(y)/diff(x) int <- y[1] - slope * x[1] } # Return Value: abline(int, slope) } ################################################################################ fGarch/R/fGarchEnv.R0000755000176200001440000000357514263246022013651 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .fGarchEnv Create GARCH Environment # .setfGarchEnv Set GARCH Environment # .getfGarchEnv Get GARCH Environment ################################################################################ .fGarchEnv <- new.env(hash = TRUE) # ------------------------------------------------------------------------------ .setfGarchEnv <- function(...) { x <- list(...) nm <- names(x) if (is.null(nm) || "" %in% nm) stop("all arguments must be named") sapply(nm, function(nm) assign(nm, x[[nm]], envir = .fGarchEnv)) invisible() } # ------------------------------------------------------------------------------ .getfGarchEnv <- function(x = NULL, unset = "") { if (is.null(x)) x <- ls(all.names = TRUE, envir = .fGarchEnv) ### unlist(mget(x, envir = .fGarchEnv, mode = "any", ### ifnotfound = as.list(unset)), recursive = FALSE) get(x, envir = .fGarchEnv, mode = "any") } ################################################################################ fGarch/R/methods-summary.R0000755000176200001440000002033714441114207015134 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # summary Summary method for an object of class 'fGARCH' ################################################################################ .fGARCH_summary_body_orig <- function(object) { ## A function implemented by Diethelm Wuertz ## modified by GNB: replaced [] indices with [[]] indices. ## ## With the [] indices the extracted elements remain lists, resulting in ## a matrix with list elements. The only change in the printed output ## though is that while formerly the numbers were aligned on the left, ## now they are aligned as numbers (on the decimal point). # Description: # Summary method for an object of class "fGARCH" # Arguments: # object - an object of class 'fGARCH' # FUNCTION: # same output as show method show(object) # Lagged Series: .tslagGarch = function (x, k = 1) { ans = NULL for (i in k) ans = cbind(ans, .tslag1Garch(x, i)) indexes = (1:length(ans[, 1]))[!is.na(apply(ans, 1, sum))] ans = ans[indexes, ] if (length(k) == 1) ans = as.vector(ans) ans } .tslag1Garch = function (x, k) { c(rep(NA, times = k), x[1:(length(x) - k)]) } # Statistical Tests: cat("\nStandardised Residuals Tests:\n") r.s = object@residuals/object@sigma.t ans = NULL # Normality Tests: jbtest = jarqueberaTest(r.s)@test ans = rbind(ans, c(jbtest[[1]], jbtest[[2]])) if (length(r.s) < 5000) { swtest = shapiro.test(r.s) if (swtest[[2]] < 2.6e-16) swtest[[2]] = 0 ans = rbind(ans, c(swtest[[1]], swtest[[2]])) } else { ans = rbind(ans, c(NA, NA)) } # Ljung-Box Tests: box10 = Box.test(r.s, lag = 10, type = "Ljung-Box") box15 = Box.test(r.s, lag = 15, type = "Ljung-Box") box20 = Box.test(r.s, lag = 20, type = "Ljung-Box") ans = rbind(ans, c(box10[[1]], box10[[3]])) ans = rbind(ans, c(box15[[1]], box15[[3]])) ans = rbind(ans, c(box20[[1]], box20[[3]])) box10 = Box.test(r.s^2, lag = 10, type = "Ljung-Box") box15 = Box.test(r.s^2, lag = 15, type = "Ljung-Box") box20 = Box.test(r.s^2, lag = 20, type = "Ljung-Box") ans = rbind(ans, c(box10[[1]], box10[[3]])) ans = rbind(ans, c(box15[[1]], box15[[3]])) ans = rbind(ans, c(box20[[1]], box20[[3]])) # Ljung-Box Tests - tslag required lag.n = 12 x.s = as.matrix(r.s)^2 n = nrow(x.s) tmp.x = .tslagGarch(x.s[, 1], 1:lag.n) tmp.y = x.s[(lag.n + 1):n, 1] fit = lm(tmp.y ~ tmp.x) stat = (n-lag.n) * summary.lm(fit)$r.squared ans = rbind(ans, c(stat, p.value = 1 - pchisq(stat, lag.n)) ) # Add Names: rownames(ans) = c( " Jarque-Bera Test R Chi^2 ", " Shapiro-Wilk Test R W ", " Ljung-Box Test R Q(10) ", " Ljung-Box Test R Q(15) ", " Ljung-Box Test R Q(20) ", " Ljung-Box Test R^2 Q(10) ", " Ljung-Box Test R^2 Q(15) ", " Ljung-Box Test R^2 Q(20) ", " LM Arch Test R TR^2 ") colnames(ans) = c("Statistic", "p-Value") print(ans) # Information Criterion Statistics: cat("\nInformation Criterion Statistics:\n") print(object@fit$ics) # Return Value: cat("\n") invisible() } .lm_arch_test <- function(r.s) { ## Lagged Series: .tslagGarch <- function (x, k = 1) { ans <- NULL for (i in k) ans <- cbind(ans, .tslag1Garch(x, i)) indexes <- (1:length(ans[, 1]))[!is.na(apply(ans, 1, sum))] ans <- ans[indexes, ] if (length(k) == 1) ans <- as.vector(ans) ans } .tslag1Garch <- function (x, k) c(rep(NA, times = k), x[1:(length(x) - k)]) ## LM Arch test - tslag required lag.n <- 12 x.s <- as.matrix(r.s)^2 n <- nrow(x.s) tmp.x <- .tslagGarch(x.s[, 1], 1:lag.n) tmp.y <- x.s[(lag.n + 1):n, 1] fit <- lm(tmp.y ~ tmp.x) stat <- (n-lag.n) * summary.lm(fit)$r.squared c(stat, p.value = 1 - pchisq(stat, lag.n)) } .fGARCH_show_stat_test <- function(object) { r.s <- object@residuals/object@sigma.t ans <- NULL ## Normality Tests: jbtest <- jarqueberaTest(r.s)@test ans <- rbind(ans, c(jbtest[[1]], jbtest[[2]])) if (length(r.s) < 5000) { swtest <- shapiro.test(r.s) if (swtest[[2]] < 2.6e-16) swtest[[2]] = 0 ans <- rbind(ans, c(swtest[[1]], swtest[[2]])) } else { ans <- rbind(ans, c(NA, NA)) } ## Ljung-Box Tests: ## residuals box10 <- Box.test(r.s, lag = 10, type = "Ljung-Box") box15 <- Box.test(r.s, lag = 15, type = "Ljung-Box") box20 <- Box.test(r.s, lag = 20, type = "Ljung-Box") ans <- rbind(ans, c(box10[[1]], box10[[3]])) ans <- rbind(ans, c(box15[[1]], box15[[3]])) ans <- rbind(ans, c(box20[[1]], box20[[3]])) ## squared residuals box10 <- Box.test(r.s^2, lag = 10, type = "Ljung-Box") box15 <- Box.test(r.s^2, lag = 15, type = "Ljung-Box") box20 <- Box.test(r.s^2, lag = 20, type = "Ljung-Box") ans <- rbind(ans, c(box10[[1]], box10[[3]])) ans <- rbind(ans, c(box15[[1]], box15[[3]])) ans <- rbind(ans, c(box20[[1]], box20[[3]])) ## LM Arch test - tslag required archtest <- .lm_arch_test(r.s) ans <- rbind(ans, archtest) ## Add Names: rownames(ans) <- c( " Jarque-Bera Test R Chi^2 ", " Shapiro-Wilk Test R W ", " Ljung-Box Test R Q(10) ", " Ljung-Box Test R Q(15) ", " Ljung-Box Test R Q(20) ", " Ljung-Box Test R^2 Q(10) ", " Ljung-Box Test R^2 Q(15) ", " Ljung-Box Test R^2 Q(20) ", " LM Arch Test R TR^2 ") colnames(ans) <- c("Statistic", "p-Value") ans } summary.fGARCH <- function(object) { res <- list( show = capture.output(show(object)), stat_tests = .fGARCH_show_stat_test(object), ics = object@fit$ics ) class(res) <- "summary_fGARCH" res } print.summary_fGARCH <- function(x, ..., classic = FALSE) { cat(x$show, sep = "\n") cat("\nStandardised Residuals Tests:\n") if(classic) print(x$stat_tests[1:9, ]) # cat() doesn't work, it's an odd matrix else ## TODO: at least put tests for the fitted distribution, ## rather than always giving the normality tests; ## see the qq-plot function .plot.garch.13 for a way to extract ## cond. dist. package 'goftest' seems suitable ## ## for now, same as for classic = TRUE print(x$stat_tests) cat("\nInformation Criterion Statistics:\n") print(x$ics) cat("\n") invisible(x) } setMethod(f = "summary", signature(object = "fGARCH"), function(object, ...) { ## original code by by Diethelm Wuertz, ## see .fGARCH_summary_body_orig() ## completely refactored and modified by Georgi Boshnakov (GNB) res <- summary.fGARCH(object, ...) ## For compatibility, show the old summary when computing the ## object Note that the print method has 'classic = FALSE' ## default, so if the object is assigned and then printed, the ## result will be with the new default. print(res, classic = TRUE) invisible(res) }) ################################################################################ fGarch/R/dist-snormFit.R0000755000176200001440000001023114263246022014533 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .snormFit Fit the parameters for a skew Normal distribution # snormFit Fit the parameters for a skew Normal distribution ################################################################################ .snormFit <- function(x, mean = 0, sd = 1, xi = 1.5, scale = NA, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE, title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description: # Fits parameters of a NIG using maximum log-likelihood # Example: # set.seed(4711); x = rsnorm(500); .snormFit(x)@fit$estimate # FUNCTION: # Settings: dist = dsnorm model = "SNORM Parameter Estimation" scale = "not used" x = x.orig = as.vector(x) # Parameter Estimation: obj = function(x, y = x, trace) { f <- tryCatch(-sum(log(dist(y, x[1], x[2], x[3]))), error=identity) if (is.na(f) || inherits(f, "error")) return(1e9) # Print Iteration Path: if (trace) { cat("\n Objective Function Value: ", -f) cat("\n Parameter Estimates: ", x, "\n") } f } r = nlminb( start = c(mean = 0, sd = 1, xi = 1.5), objective = obj, lower = c(-Inf, 0, 0), upper = c( Inf, Inf, Inf), y = x, trace = trace) names(r$par) <- c("mean", "sd", "xi") # Add Title and Description: if (is.null(title)) title = model if (is.null(description)) description = description() # Result: fit = list(estimate = r$par, minimum = -r$objective, code = r$convergence) # Optional Plot: if (doplot) { x = as.vector(x.orig) if (span == "auto") span = seq(min(x), max(x), length = 501) z = density(x, n = 100, ...) x = z$x[z$y > 0] y = z$y[z$y > 0] y.points = dist(span, r$par[1], r$par[2], r$par[3]) ylim = log(c(min(y.points), max(y.points))) if (add) { lines(x = span, y = log(y.points), col = "steelblue") } else { plot(x, log(y), xlim = c(span[1], span[length(span)]), ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...) title(main = model) lines(x = span, y = log(y.points), col = "steelblue") } } # Return Value: new("fDISTFIT", call = match.call(), model = model, data = as.data.frame(x.orig), fit = fit, title = title, description = description() ) } # ------------------------------------------------------------------------------ snormFit <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Fit the parameters for a skew Normal distribution # FUNCTION: # Start Value: start = c(mean = mean(x), sd = sqrt(var(x)), xi = 1) # Log-likelihood Function: loglik = function(x, y = x){ f = -sum(log(dsnorm(y, x[1], x[2], x[3]))) f } # Minimization: fit = nlminb( start = start, objective = loglik, lower = c(-Inf, 0, 0), upper = c( Inf, Inf, Inf), y = x, ...) # Add Names to $par names(fit$par) = c("mean", "sd", "xi") # Return Value: fit } ################################################################################ fGarch/R/class-fGARCH.R0000755000176200001440000000263614263246022014100 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # 'fGARCH' fGARCH Class representation ################################################################################ # Class Representation: setClass("fGARCH", representation( call = "call", formula = "formula", method = "character", data = "numeric", fit = "list", residuals = "numeric", fitted = "numeric", h.t = "numeric", sigma.t = "numeric", title = "character", description = "character") ) ################################################################################ fGarch/R/garch-Spec.R0000755000176200001440000001726114263246022013757 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: SPECIFICATION: # garchSpec Creates a 'garchSpec' object from scratch ############################################################################### garchSpec <- function (model = list(), presample = NULL, cond.dist = c("norm", "ged", "std", "snorm", "sged", "sstd"), rseed = NULL) { # A function implemented by Diethelm Wuertz # Description: # Creates a "garchSpec" object from scratch. # Arguments: # model - a list with the model parameters as entries # omega - the variance value for GARCH/APARCH # specification, # alpha - a vector of autoregressive coefficients # of length p for the GARCH/APARCH specification, # gamma - a vector of leverage coefficients of # length p for the APARCH specification, # beta - a vector of moving average coefficients of # length q for the GARCH/APARCH specification, # mu - the mean value for ARMA specification, # ar - a vector of autoregressive coefficients of # length m for the ARMA specification, # ma - a vector of moving average coefficients of # length n for the ARMA specification, # delta - the exponent value used in the variance equation. # skew - a numeric value listing the distributional # skewness parameter. # shape - a numeric value listing the distributional # shape parameter. # presample - either a multivariate "timeSeries", a # multivariate "ts", a "data.frame" object or a numeric # "matrix" with 3 columns and at least max(m,n,p,q) # rows. The first culumn are the innovations, the second # the conditional variances, and the last the time series. # condd.dist - a character string naming the distribution # function. # rseed - optional random seed. # Slots: # call - the function call. # formula - a formula object describing the model, e.g. # ARMA(m,n) + GARCH(p,q). ARMA can be missing or # specified as AR(m) or MA(n) in the case of pure # autoregressive or moving average models. GARCH may # alternatively specified as ARCH(p) or APARCH(p,q). # If formula is set to "NA", the formula is constructed # from the "model" list. # model - as declared in the input. # FUNCTION: # Match Arguments: cond.dist = match.arg(cond.dist) # Skewness Parameter Settings: skew = list( "norm" = NULL, "ged" = NULL, "std" = NULL, "snorm" = 0.9, "sged" = 0.9, "sstd" = 0.9) # Shape Parameter Settings: shape = list( "norm" = NULL, "ged" = 2, "std" = 4, "snorm" = NULL, "sged" = 2, "sstd" = 4) # Default Model: control = list( omega = 1.0e-6, alpha = 0.1, gamma = NULL, beta = 0.8, mu = NULL, ar = NULL, ma = NULL, delta = 2, skew = skew[[cond.dist]], shape = shape[[cond.dist]] ) # Update Control: control[names(model)] <- model model <- control # check if alpha and beta are well defined if (sum(c(model$alpha, model$beta))>1) warnings("sum(alpha)+sum(beta)>1") # Model Orders: order.ar = length(model$ar) order.ma = length(model$ma) order.alpha = length(model$alpha) if (sum(model$beta) == 0) { order.beta = 0 } else { order.beta = length(model$beta) } # Compose Mean Formula Object: if (order.ar == 0 && order.ma == 0) { formula.mean = "" } if (order.ar > 0 && order.ma == 0) { formula.mean = paste ("ar(", as.character(order.ar), ")", sep = "") } if (order.ar == 0 && order.ma > 0) { formula.mean = paste ("ma(", as.character(order.ma), ")", sep = "") } if (order.ar > 0 && order.ma > 0) { formula.mean = paste ("arma(", as.character(order.ar), ", ", as.character(order.ma), ")", sep = "") } # Compose Variance Formula Object: formula.var = "garch" if (order.beta == 0) formula.var = "arch" if (!is.null(model$gamma) != 0) formula.var = "aparch" if (model$delta != 2) formula.var = "aparch" if (order.beta == 0) { formula.var = paste(formula.var, "(", as.character(order.alpha), ")", sep = "") } else { formula.var = paste(formula.var, "(", as.character(order.alpha), ", ", as.character(order.beta), ")", sep = "") } # Compose Mean-Variance Formula Object: if (formula.mean == "") { formula = as.formula(paste("~", formula.var)) } else { formula = as.formula(paste("~", formula.mean, "+", formula.var)) } # Add NULL default entries: if (is.null(model$mu)) model$mu = 0 if (is.null(model$ar)) model$ar = 0 if (is.null(model$ma)) model$ma = 0 if (is.null(model$gamma)) model$gamma = rep(0, times = order.alpha) # print(unlist(model)) # Seed: if (is.null(rseed)) { rseed = 0 } else { set.seed(rseed) } # Define Missing Presample: order.max = max(order.ar, order.ma, order.alpha, order.beta) iterate = TRUE if (!is.matrix(presample)) { if (is.null(presample)) { iterate = FALSE n.start = order.max } else { n.start = presample } z = rnorm(n = n.start) # GARCH(p, q): h = rep(model$omega/(1-sum(model$alpha)-sum(model$beta)), times = n.start) y = rep(model$mu/(1-sum(model$ar)), times = n.start) # APARCH(p,q): # ... we initialize all models with norm-GARCH(p,q) processes } else { z = presample[, 1] h = presample[, 2] y = presample[, 3] } presample = cbind(z, h, y) # Presample Iteration: if (iterate) { n.iterate = length(z) - order.max deltainv = 1/model$delta for (i in n.iterate:1) { h[i] = model$omega + sum(model$alpha*(abs(abs(y[i+(1:order.alpha)]) - model$gamma*y[i+(1:order.alpha)])^model$delta)) + sum(model$beta*h[i+(1:order.beta)]) y[i] = model$mu + sum(model$ar*y[i+(1:order.ar)]) + sum(model$ma*(h[i+(1:order.ma)]**deltainv)) + h[i]^deltainv * z[i] } } # Result: new("fGARCHSPEC", call = match.call(), formula = formula, model = list(omega = model$omega, alpha = model$alpha, gamma = model$gamma, beta = model$beta, mu = model$mu, ar = model$ar, ma = model$ma, delta = model$delta, skew = model$skew, shape = model$shape), presample = as.matrix(presample), distribution = as.character(cond.dist), rseed = as.numeric(rseed) ) } ################################################################################ fGarch/R/dist-ged.R0000755000176200001440000000727114263246022013503 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: GED DISTRIBUTION: # dged Density for the Generalized Error Distribution # pged Probability function for the GED # qged Quantile function for the GED # rged Random Number Generator for the GED ################################################################################ dged <- function(x, mean = 0, sd = 1, nu = 2, log = FALSE) { # A function imlemented by Diethelm Wuertz # Description: # Compute the density for the # generalized error distribution. # FUNCTION: # Params: if (length(mean) == 3) { nu = mean[3] sd = mean[2] mean = mean[1] } # Compute Density: z = (x - mean ) / sd lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) g = nu / ( lambda * (2^(1+1/nu)) * gamma(1/nu) ) result = g * exp (-0.5*(abs(z/lambda))^nu) / sd # Log: if(log) result = log(result) # Return Value result } # ------------------------------------------------------------------------------ pged <- function(q, mean = 0, sd = 1, nu = 2) { # A function implemented by Diethelm Wuertz # Description: # Compute the probability for the # generalized error distribution. # FUNCTION: # Compute Probability: q = (q - mean ) / sd lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) g = nu / ( lambda * (2^(1+1/nu)) * gamma(1/nu) ) h = 2^(1/nu) * lambda * g * gamma(1/nu) / nu s = 0.5 * ( abs(q) / lambda )^nu result = 0.5 + sign(q) * h * pgamma(s, 1/nu) # Return Value: result } # ------------------------------------------------------------------------------ qged <- function(p, mean = 0, sd = 1, nu = 2) { # A function implemented by Diethelm Wuertz # Description: # Compute the quantiles for the # generalized error distribution. # FUNCTION: # Compute Quantiles: lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) q = lambda * (2*qgamma((abs(2*p-1)), 1/nu))^(1/nu) result = q*sign(2*p-1) * sd + mean # Return Value: result } # ------------------------------------------------------------------------------ rged <- function(n, mean = 0, sd = 1, nu = 2) { # A function implemented by Diethelm Wuertz # Description: # Generate GED random deviates. The function uses the # method based on the transformation of a Gamma random # variable. # FUNCTION: # Generate Random Deviates: lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) # print(lambda) r = rgamma(n, 1/nu) z = lambda * (2*r)^(1/nu) * sign(runif(n)-1/2) result = z * sd + mean # Return Value: result } ################################################################################ fGarch/R/zzz.R0000755000176200001440000000175414263246022012640 0ustar liggesusers## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS ## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . .onAttach <- function(libname, pkgname) { packageStartupMessage( "NOTE: Packages 'fBasics', 'timeDate', and 'timeSeries' are no longer\n", "attached to the search() path when 'fGarch' is attached.\n\n", "If needed attach them yourself in your R script by e.g.,\n", " require(\"timeSeries\")") } fGarch/R/dist-snormSlider.R0000755000176200001440000000705114263246022015241 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # snormSlider Displays Normal Distribution and RVS ################################################################################ snormSlider <- function(type = c("dist", "rand")) { # A function implemented by Diethelm Wuertz # Description: # Displays interactively skew Normal distribution # Note: # dsnorm(x, mean = 0, sd = 1, xi = 1.5) # FUNCTION: # Internal Function: refresh.code = function(...) { # Sliders: N = .sliderMenu(no = 1) mean = .sliderMenu(no = 2) sd = .sliderMenu(no = 3) xi = .sliderMenu(no = 4) invert = .sliderMenu(no = 5) # Compute Data: if (invert == 1) xi = 1/xi xmin = round(qsnorm(0.001, mean, sd, xi), digits = 2) xmax = round(qsnorm(0.999, mean, sd, xi), digits = 2) s = seq(xmin, xmax, length = N) y1 = dsnorm(s, mean, sd, xi) y2 = psnorm(s, mean, sd, xi) main1 = paste("Skew Normal Density\n", "mean = ", as.character(mean), " | ", "sd = ", as.character(sd), " | ", "xi = ", as.character(xi) ) main2 = paste("Skew Normal Probability\n", "xmin [0.001] = ", as.character(xmin), " | ", "xmax [0.999] = ", as.character(xmax) ) # Random Numbers: if (type[1] == "rand") { x = rsnorm(N, mean, sd, xi) } # Frame: par(mfrow = c(2, 1), cex = 0.7) # Density: if (type[1] == "rand") { hist(x, probability = TRUE, col = "steelblue", border = "white", breaks = "FD", xlim = c(xmin, xmax), ylim = c(0, 1.1*max(y1)), main = main1 ) lines(s, y1, col = "orange") } else { plot(s, y1, type = "l", xlim = c(xmin, xmax), col = "steelblue") abline (h = 0, lty = 3) title(main = main1) grid() } # Probability: plot(s, y2, type = "l", xlim = c(xmin, xmax), ylim = c(0, 1), col = "steelblue" ) abline (h = 0, lty = 3) title(main = main2) grid() # Frame: par(mfrow = c(1, 1), cex = 0.7) } # Open Slider Menu: .sliderMenu(refresh.code, names = c( "N", "mean", "sd", "xi", "xi.inv"), minima = c( 10, -5.0, 0.1, 1.0, 0 ), maxima = c( 500, +5.0, 5.0, 10.0, 1 ), resolutions = c( 10, 0.1, 0.1, 0.1, 1 ), starts = c( 100, 0.0, 1.0, 1.0, 0 ) ) } ################################################################################ fGarch/R/stats-tsdiag.R0000755000176200001440000002214614441643056014416 0ustar liggesusers## Author: Georgi Boshnakov ## based on tsdiag.Sarima from package 'sarima' .tsdiag_choices <- c( ## ## "classic (std. residuals, acf, portmanteau p-values)", ## "residuals", ## "acf of residuals", ## "p values for Ljung-Box statistic", ## "p values for Li-McLeod statistic", ## "p values for Box-Pierce statistic", ## "pacf of residuals" ## use 7-13; for consistency with the plot method we would like to keep the same numbers ## but this seems not possible with menu(). ## ## .plot.garch.1 Plot Time Series ## .plot.garch.2 Plot Conditional SD ## .plot.garch.3 Plot Series with 2 Conditional SD Superimposed ## .plot.garch.4 Plot ACF of Observations ## .plot.garch.5 Plot ACF of Squared Observations ## .plot.garch.6 Plot Cross Correlation "Residuals", # .plot.garch.7 "Conditional SDs", # .plot.garch.8 "Standardized Residuals", # .plot.garch.9 "ACF of Standardized Residuals", # .plot.garch.10 "ACF of Squared Standardized Residuals", # .plot.garch.11 "Cross Correlation between r^2 and r", # .plot.garch.12 "QQ-Plot of Standardized Residuals" # .plot.garch.13 ## TODO: pacf of r and r^2 ) ## tsdiag.Sarima: ## ## { # 1: "residuals", ## plot(stdres, type = "h", main = "Standardized Residuals", ylab = "") ## abline(h = 0) ## #acf(err, main = "ACF of residuals from model", lag.max = lag.max) ## #pacf(err, main = "PACF of residuals from model", lag.max = lag.max) ## }, ## { # 2: "ACF of residuals" ## ## acf ## acf(err, plot = TRUE, main = "ACF of Residuals", lag.max = lag.max, na.action = na.pass) ## # acf(cdf, main = "", lag.max = lag.max) ## # title("ACF of" ~U[t]) ## # pacf(cdf, main = "", lag.max = lag.max) ## # title("PACF of" ~U[t]) ## }, ## { # 3: "Ljung-Box p-values" ## acftest <- acfIidTest(sacf, npar = fitdf, nlags = 1:nlag, method = "LjungBox", ## interval = NULL) ## res[["LjungBox"]] <- acftest ## }, ## { # 4: "Li-McLeod p-values" ## acftest <- acfIidTest(sacf, npar = fitdf, nlags = 1:nlag, method = "LiMcLeod", ## interval = NULL) ## res[["LiMcLeod"]] <- acftest ## }, ## { # 5: "Box-Pierce p-values" ## acftest <- acfIidTest(sacf, npar = fitdf, nlags = 1:nlag, method = "BoxPierce", ## interval = NULL) ## res[["BoxPierce"]] <- acftest ## }, ## { # 6: "PACF of residuals" ## ## acf ## pacf(err, plot = TRUE, main = "PACF of Residuals", lag.max = lag.max, na.action = na.pass) ## }, ## # { # 4: "ACF/Histogram of tau_residuals" ## # acf(err2, main = "ACF of tau_residuals", lag.max = lag.max) ## # hist(err2, freq = FALSE, main = "Histogram of tau_residuals", xlab = "", ## # ylim = c(0, 0.5)) ## # lines(seq(-5, 5, .01), dnorm(seq(-5, 5, .01)), col = "red") ## # } tsdiag.fGARCH <- function(object, gof.lag = NULL, ask = FALSE, ..., plot = c(4L, 5L, 7L), layout = NULL) { ## Georgi Boshnakov n_per_page <- if(is.null(layout)) 3 else ## length(layout[[1]]) do.call("layout", layout) if(is.null(gof.lag)) gof.lag <- 20 # :TODO: NOTE: arbitrary value else if(!is.numeric(gof.lag)) stop("'gof.lag' must be numeric and contain positive integers") lag.max <- max(gof.lag) sres <- residuals(object, standardize = TRUE) sres2 <- sres^2 choices <- .tsdiag_choices chnum <- 1:length(choices) if(!isTRUE(plot)){ # plot is typically numeric index here; choices <- choices[plot] # FALSE or NULL give zero length result, so no plots chnum <- chnum[plot] if(anyNA(choices)){ warning("'plot' should be TRUE/FALSE or vector of positive integers <= ", length(.tsdiag_choices), ",\n", "ignoring non-existent values") chnum <- chnum[!is.na(choices)] choices <- choices[!is.na(choices)] } } if(length(choices) > 0){ old.par <- par(no.readonly = TRUE) on.exit(par(old.par)) # restore graphics parameters before exiting. ask_user <- interactive() && (ask || length(choices) > n_per_page) ## adjust n_per_page if 'layout' is missing if(is.null(layout)) { n_per_page <- if(ask_user) ## was: layout(matrix(1:3, ncol = 1)) layout(matrix(1:min(3, length(choices)), ncol = 1)) else layout(matrix(1:min(3, length(choices)), ncol = 1)) } choice_title <- "Select a plot number or 0 to exit" ch_index <- if(length(choices) == 1) 1 else if(ask) menu(choices, title = choice_title) else if(!identical(plot, FALSE)) 1 else integer(0) choice <- chnum[ch_index] ## ## precompute common stuff for portmanteau tests ## nlag <- gof.lag ## pval <- numeric(nlag) ## fitdf <- if(inherits(object, "Sarima")) ## length(object$internal$nonfixed) ## else if(inherits(object, "Arima")) ## sum(object$arma[1:4]) # object$arma is: p, q, p_s. q_s, s, d, d_s ## else ## 0 ## # for(i in 1L:nlag) ## # pval[i] <- Box.test(err, i, type="Ljung-Box", ## # fitdf = ifelse(i > fitdf, fitdf, i - 1))$p.value ## sacf <- autocorrelations(err, maxlag = nlag) # deal with NA's? res <- list(residuals = sres) while(length(choice) != 0){ switch(choice, .plot.garch.7 (object), # "Residuals", .plot.garch.8 (object), # "Conditional SDs", .plot.garch.9 (object), # "Standardized Residuals", .plot.garch.10(object), # "ACF of Standardized Residuals", .plot.garch.11(object), # "ACF of Squared Standardized Residuals", .plot.garch.12(object), # "Cross Correlation between r^2 and r", .plot.garch.13(object) # "QQ-Plot of Standardized Residuals" ) if(length(chnum) == 1) # length(choices) == 1 break if(ask_user) { # was: interactive() && (ask || length(choices) > n_per_page) ch_index <- menu(choices, title = choice_title) choice <- chnum[ch_index] } else{ ## just plot the next one ## Note: this doesn't update ch_index chnum <- chnum[-1] choice <- chnum[1] } } } .f <- function(x) c(statistic = as.vector(x$statistic), p.value = x$p.value) if(requireNamespace("goftest", quietly = TRUE)) { gofargs <- .resid_with_dist(object) res$gof <- rbind( "Anderson-Darling" = .f(do.call(goftest::ad.test, gofargs)), "Cramer-vonMises" = .f(do.call(goftest::cvm.test, gofargs)) ) gofargs$estimated <- FALSE res$gof_composite <- rbind( "Anderson-Darling" = .f(do.call(goftest::ad.test, gofargs)), "Cramer-vonMises" = .f(do.call(goftest::cvm.test, gofargs)) ) } else{ message("Please install package 'goftest' for additional tests") } class(res) <- "tsdiag_fGARCH" invisible(res) } print.tsdiag_fGARCH <- function(x, ...){ ## for now just drop the values of the residuals x <- x[names(x) != "residuals"] for(s in names(x)) { cat(paste0( "\n", s, ":", "\n")) print(x[[s]]) } } ## GNB, based on .plot.garch.13 ## for tests in 'goftest' .resid_with_dist <- function(x) { sres <- residuals(x, standardize = TRUE) cond_dist <- x@fit$params$cond.dist cond_cdf <- paste("p", cond_dist, sep = "") parNames <- names(x@fit$par) skew <- if ("skew" %in% parNames) x@fit$par["skew"] else x@fit$params$skew shape <- if ("shape" %in% parNames) x@fit$par["shape"] else x@fit$params$shape res <- list(x = sres) res$null <- if (cond_dist == "QMLE") "pnorm" else cond_cdf if (cond_dist == "std" || cond_dist == "ged") res$nu <- shape else if (cond_dist == "snorm") res$xi <- skew else if (cond_dist == "sstd" || cond_dist == "sged") { res$xi <- skew res$nu <- shape } else if (cond_dist == "snig") { res$rho <- skew res$zeta <- shape } res$estimated <- TRUE res$nullname <- cond_dist res } fGarch/R/loglik-egarch.R0000755000176200001440000000170714263246022014511 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .egarchLLH ARMA-EGARCH model ################################################################################ fGarch/R/methods-update.R0000755000176200001440000000431614263246022014723 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # METHOD: EXTRACTORS: # update,fGARCHSPEC Update Methods # update,fGARCH Update Methods ################################################################################ setMethod("update", "fGARCHSPEC", function(object, ... ) { # A function implemented by Yohan Chalabi # Description: # # Example: # # # FUNCTION: call <- object@call extras <- match.call(expand.dots = FALSE)$... if (length(extras)) { existing <- !is.na(match(names(extras), names(call))) for (a in names(extras)[existing]) call[[a]] <- extras[[a]] if (any(!existing)) { call <- c(as.list(call), extras[!existing]) call <- as.call(call) } } eval(call, parent.frame()) }) # ----------------------------------------------------------------------------- setMethod("update", "fGARCH", function(object, ... ) { # A function implemented by Yohan Chalabi # Description: # # Example: # # # FUNCTION: call <- object@call extras <- match.call(expand.dots = FALSE)$... if (length(extras)) { existing <- !is.na(match(names(extras), names(call))) for (a in names(extras)[existing]) call[[a]] <- extras[[a]] if (any(!existing)) { call <- c(as.list(call), extras[!existing]) call <- as.call(call) } } eval(call, parent.frame()) }) fGarch/R/methods-residuals.R0000755000176200001440000000344714263246022015440 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # METHOD: EXTRACTORS: # residuals.fGARCH S4 residuals method for an object of class 'fGARCH' ################################################################################ setMethod(f = "residuals", signature(object = "fGARCH"), definition = function(object, standardize = FALSE) { # A function implemented by Diethelm Wuertz # Description: # S4 Residuals method for an object of class fGARCH # Arguments: # object - an object of class fGarch as returned by the # function garchFit # ... - optional argument to be passed, this may be standardize=FALSE # to return the -non-standardized values of the residuals. # By default standardized residuals will be returned. # FUNCTION: # Residuals: if (standardize) { ans = object@residuals/object@sigma.t } else { ans = object@residuals } # Return Value: ans }) # ------------------------------------------------------------------------------ fGarch/R/methods-predict.R0000644000176200001440000002726514556511050015101 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # METHOD: PREDICTION: # predict.fGARCH Forecasts from an object of class 'fGARCH' ################################################################################ setMethod(f = "predict", signature(object = "fGARCH"), definition = function(object, n.ahead = 10, trace = FALSE, mse = c("cond","uncond"), plot=FALSE, nx=NULL, crit_val=NULL, conf=NULL, ..., p_loss = NULL # GNB: for ES and VaR ) { # A function implemented by Diethelm Wuertz # Description: # Prediction method for an object of class fGARCH # Arguments: # object an object of class fGARCH as returned by the # function garchFit(). # n.ahead number of steps to be forecasted, an integer # value, by default 10) # trace should the prediction be traced? A logical value, # by default FALSE) # mse should the mean squared errors be conditional or unconditional # plot should the predictions be plotted # nx The number of observations to be plotted with the predictions # (If plot is TRUE, the default value of nx is the sample # size times 0.25.) # crit_va If you want to set manually the critical values for # the confidence intervals # conf The confidence level for computing the critical values # of the confidence intervals # FUNCTION: mse <- match.arg(mse) # Retrieve "fit" from Parameter Estimation: fit = object@fit # Get ARMA(u,v)-GARCH(p,q) Order: u = fit$series$order[1] v = fit$series$order[2] p = fit$series$order[3] q = fit$series$order[4] max.order = max(u, v, p, q) # Get Start Conditions: h.start = fit$series$h.start llh.start = fit$series$llh.start index = fit$params$index params = fit$params$params par = fit$par Names = names(index) for (Name in Names) params[Name] = par[Name] Names = names(params) # Retrieve From Initialized Parameters: cond.dist = fit$params$cond.dist # Extract the Parameters by Name: leverage = fit$params$leverage mu = params["mu"] if (u > 0) { ar = params[substr(Names, 1, 2) == "ar"] } else { ar = c(ar1 = 0) } if (v > 0) { ma = params[substr(Names, 1, 2) == "ma"] } else { ma = c(ma1 = 0) } omega = params["omega"] if (p > 0) { alpha = params[substr(Names, 1, 5) == "alpha"] } else { alpha = c(alpha1 = 0) } if (p > 0 & leverage) { gamma = params[substr(Names, 1, 5) == "gamma"] } else { gamma = c(gamma1 = 0) } if (q > 0) { beta = params[substr(Names, 1, 4) == "beta"] } else { beta = c(beta1 = 0) } delta = params["delta"] skew = params["skew"] shape = params["shape"] # Trace Parameters: if (trace) { cat("\nModel Parameters:\n") print(c(mu, ar, ma, omega, alpha, gamma, beta, delta, skew, shape)) } # Retrieve Series Lengths: M = n.ahead N = length(object@data) # Get and Extend Series: x = c(object@data, rep(mu, M)) h = c(object@h.t, rep(0, M)) z = c(fit$series$z, rep(mu, M)) # Forecast and Optionally Trace Variance Model: var.model = fit$series$model[2] # Forecast GARCH Variance: if (var.model == "garch") { if (trace) cat("\nForecast GARCH Variance:\n") for (i in 1:M) { h[N+i] = omega + sum(beta*h[N+i-(1:q)]) for (j in 1:p) { if (i-j > 0) { s = h[N + i - j] } else { s = z[N + i - j]^2 } h[N+i] = h[N+i] + alpha[j] * s } } } # Forecast APARCH Variance: if (var.model == "aparch") { if (trace) cat("\nForecast APARCH Variance:\n") for (i in 1:M) { h[N+i] = omega + sum(beta*h[N+i-(1:q)]) for (j in 1:p) { ## 2024-01-30 GNB: TODO: ## it seems that kappa doesn't depend on i; ## so, kappa[1], ..., kappa[p] can be computed outside the i-loop ## and the formulas below use kappa[j] kappa = garchKappa(cond.dist = cond.dist, gamma = gamma[j], delta = delta, skew = skew, shape = shape) if (i-j > 0) { s = kappa * h[N + i - j] } else { s = (abs(z[N + i - j]) - gamma[j]*z[N + i - j])^delta } h[N+i] = h[N+i] + alpha[j] * s } } } # Forecast and Optionally Trace Mean Model: # Note we set maxit=0 to get an object of class Arima with fixed # init parameters ... mu <- mu/(1-sum(ar)) ARMA <- arima(x = object@data, order = c(max(u, 1), 0, max(v, 1)), init = c(ar, ma, mu), transform.pars = FALSE, optim.control = list(maxit = 0)) prediction = predict(ARMA, n.ahead) meanForecast = as.vector(prediction$pred) if(mse=="uncond") { meanError = as.vector(prediction$se) } else { # coefficients of h(t+1) a_vec <- rep(0,(n.ahead)) hhat <- h[-(1:N)]^(2/delta[[1]]) #-> [[1]] to omit name of delta u2 <- length(ar) meanError <- hhat[1] a_vec[1] = ar[1] + ma[1] meanError <- na.omit(c(meanError,sum(hhat[1:2]*c(a_vec[1]^2,1)))) if ((n.ahead - 1) > 1) { for( i in 2:(n.ahead - 1)) { a_vec[i] <- ar[1:min(u2,i-1)]*a_vec[(i-1):(i-u2)] + ifelse(i>u,0,ar[i]) + ifelse(i>v,0,ma[i]) meanError <- na.omit(c(meanError, sum(hhat[1:(i+1)]*c(a_vec[i:1]^2,1)))) } } meanError <- sqrt(meanError) } if (trace) { cat("\nForecast ARMA Mean:\n") print(ARMA) cat("\n") print(prediction) } # Standard Deviations: standardDeviation = h^(1/delta) # Plotting the predictions if (plot) { if(is.null(nx)) nx <- round(length(object@data)*.25) t <- length(object@data) x <- c(object@data[(t-nx+1):t],meanForecast) # Computing the appropriate critical values if (is.null(conf)) conf <- 0.95 if (is.null(crit_val)) { if (object@fit$params$cond.dist=="norm") { crit_valu <- qnorm(1-(1-conf)/2) crit_vald <- qnorm((1-conf)/2) } if (object@fit$params$cond.dist=="snorm") { crit_valu <- qsnorm(1-(1-conf)/2,xi=coef(object)["skew"]) crit_vald <- qsnorm((1-conf)/2,xi=coef(object)["skew"]) } if (object@fit$params$cond.dist=="ged") { crit_valu <- qged(1-(1-conf)/2,nu=coef(object)["shape"]) crit_vald <- qged((1-conf)/2,nu=coef(object)["shape"]) } if (object@fit$params$cond.dist=="sged") { crit_valu <- qsged(1-(1-conf)/2,nu=coef(object)["shape"], xi=coef(object)["skew"]) crit_vald <- qsged((1-conf)/2,nu=coef(object)["shape"], xi=coef(object)["skew"]) } if (object@fit$params$cond.dist=="std") { crit_valu <- qstd(1-(1-conf)/2,nu=coef(object)["shape"]) crit_vald <- qstd((1-conf)/2,nu=coef(object)["shape"]) } if (object@fit$params$cond.dist=="sstd") { crit_valu <- qsstd(1-(1-conf)/2,nu=coef(object)["shape"], xi=coef(object)["skew"]) crit_vald <- qsstd((1-conf)/2,nu=coef(object)["shape"], xi=coef(object)["skew"]) } if (object@fit$params$cond.dist=="snig") { crit_valu <- qsnig(1-(1-conf)/2,zeta=coef(object)["shape"], rho=coef(object)["skew"]) crit_vald <- qsnig((1-conf)/2,zeta=coef(object)["shape"], rho=coef(object)["skew"]) } if (object@fit$params$cond.dist=="QMLE") { e <- sort(object@residuals/object@sigma.t) crit_valu <- e[round(t*(1-(1-conf)/2))] crit_vald <- e[round(t*(1-conf)/2)] } } else { if (length(crit_val)==2) { crit_valu <- crit_val[2] crit_vald <- crit_val[1] } if (length(crit_val)==1) { crit_valu <- abs(crit_val) crit_vald <- -abs(crit_val) } } int_l <- meanForecast+crit_vald*meanError int_u <- meanForecast+crit_valu*meanError ylim_l <- min(c(x,int_l)*(.95)) ylim_u <- max(c(x,int_u)*(1.05)) plot(x,type='l',ylim=c(ylim_l,ylim_u)) title("Prediction with confidence intervals") lines((nx+1):(nx+n.ahead), meanForecast, col = 2, lwd = 2) lines((nx+1):(nx+n.ahead), int_l, col = 3, lwd = 2) lines((nx+1):(nx+n.ahead), int_u, col = 4, lwd = 2) polygon(c((nx+1):(nx+n.ahead),(nx+n.ahead):(nx+1)), c(int_l, int_u[n.ahead:1]), border = NA, density = 20, col = 5, angle = 90) es1 <- as.expression(substitute(hat(X)[t+h] + crit_valu*sqrt(MSE), list(crit_valu=round(crit_valu,3)))) es2 <- as.expression(substitute(hat(X)[t+h] - crit_vald*sqrt(MSE), list(crit_vald=abs(round(crit_vald,3))))) es3 <- expression(hat(X)[t+h]) legend("bottomleft",c(es3,es2,es1),col=2:4,lty=rep(1,3),lwd=rep(2,3)) grid() } ## Result: forecast <- data.frame( meanForecast = meanForecast, meanError = meanError, standardDeviation = standardDeviation[-(1:N)]) if(plot) forecast = data.frame( forecast, lowerInterval = int_l, upperInterval = int_u) ## if(plot) { ## forecast = data.frame( ## meanForecast = meanForecast, ## meanError = meanError, ## standardDeviation = standardDeviation[-(1:N)], ## lowerInterval = int_l, ## upperInterval = int_u) ## } else { ## forecast = data.frame( ## meanForecast = meanForecast, ## meanError = meanError, ## standardDeviation = standardDeviation[-(1:N)]) ## } ## 2024-01-31 GNB: VaR and ES - experimental if(!is.null(p_loss)) { cond_dist <- object@fit$params$cond.dist mu_t <- meanForecast sigma_t <- standardDeviation[-(1:N)] qf <- qfun_fGarch(cond_dist, coef(object)) predVaR <- cvar::VaR_qf(qf, p_loss, intercept = mu_t, slope = sigma_t) predES <- cvar::ES(qf, p_loss, intercept = mu_t, slope = sigma_t) forecast <- data.frame(forecast, VaR = predVaR, ES = predES) attr(forecast, "p_loss") <- p_loss } # Return Value: forecast }) ################################################################################ fGarch/R/dist-sgedFit.R0000755000176200001440000001023214263246022014320 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # sgedFit Fit the parameters for a skew GED distribution ################################################################################ .sgedFit <- function(x, mean = 0, sd = 1, nu = 2, xi = 1.5, scale = NA, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE, title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description: # Fits parameters of skewed GED using maximum log-likelihood # Example: # set.seed(4711); x = rsged(500); .sgedFit(x)@fit$estimate # FUNCTION: # Settings: dist = dsged model = "SGED Parameter Estimation" scale = "not used" x = x.orig = as.vector(x) # Parameter Estimation: obj = function(x, y = x, trace) { f <- tryCatch(-sum(log(dist(y, x[1], x[2], x[3], x[4]))), error=identity) if (is.na(f) || inherits(f, "error")) return(1e9) # Print Iteration Path: if (trace) { cat("\n Objective Function Value: ", -f) cat("\n Parameter Estimates: ", x, "\n") } f } r = nlminb( start = c(mean = 0, sd = 1, nu = 2, xi = 1.5), objective = obj, lower = c(-Inf, 0, 0, 0), upper = c( Inf, Inf, Inf, Inf), y = x, trace = trace) names(r$par) <- c("mean", "sd", "nu", "xi") # Add Title and Description: if (is.null(title)) title = model if (is.null(description)) description = description() # Result: fit = list(estimate = r$par, minimum = -r$objective, code = r$convergence) # Optional Plot: if (doplot) { x = as.vector(x.orig) if (span == "auto") span = seq(min(x), max(x), length = 501) z = density(x, n = 100, ...) x = z$x[z$y > 0] y = z$y[z$y > 0] y.points = dist(span, r$par[1], r$par[2], r$par[3], r$par[4]) ylim = log(c(min(y.points), max(y.points))) if (add) { lines(x = span, y = log(y.points), col = "steelblue") } else { plot(x, log(y), xlim = c(span[1], span[length(span)]), ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...) title(main = model) lines(x = span, y = log(y.points), col = "steelblue") } } # Return Value: new("fDISTFIT", call = match.call(), model = model, data = as.data.frame(x.orig), fit = fit, title = title, description = description() ) } # ------------------------------------------------------------------------------ sgedFit <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Fit the parameters for a skew Normal distribution # FUNCTION: # Start Value: start = c(mean = mean(x), sd = sqrt(var(x)), nu = 2, xi = 1) # Log-likelihood Function: loglik = function(x, y = x){ f = -sum(log(dsged(y, x[1], x[2], x[3], x[4]))) f } # Minimization: fit = nlminb( start = start, objective = loglik, lower = c(-Inf, 0, 0, 0), upper = c( Inf, Inf, Inf, Inf), y = x, ...) # Add Names to $par names(fit$par) = c("mean", "sd", "nu", "xi") # Return Value: fit } ################################################################################ fGarch/R/dist-sstd.R0000755000176200001440000001523314332476631013726 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # dsstd Density for the skewed Student-t Distribution # psstd Probability function for the skewed STD # qsstd Quantile function for the skewed STD # rsstd Random Number Generator for the skewed STD # FUNCTION: DESCRIPTION: # .dsstd Internal, density for the skewed Student-t Distribution # .psstd Internal, probability function for the skewed STD # .qsstd Internal, quantile function for the skewed STD # .rsstd Internal, random Number Generator for the skewed STD ################################################################################ dsstd <- function(x, mean = 0, sd = 1, nu = 5, xi = 1.5, log = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Compute the density function of the # skewed Student-t distribution # FUNCTION: # Params: if (length(mean) == 4) { xi = mean[4] nu = mean[3] sd = mean[2] mean = mean[1] } # Shift and Scale: result = .dsstd(x = (x-mean)/sd, nu = nu, xi = xi) / sd # Log: if(log) result = log(result) # Return Value: result } # ------------------------------------------------------------------------------ psstd <- function(q, mean = 0, sd = 1, nu = 5, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Compute the distribution function of the # skewed Student-t distribution # FUNCTION: # Shift and Scale: result = .psstd(q = (q-mean)/sd, nu = nu, xi = xi) # Return Value: result } # ------------------------------------------------------------------------------ qsstd <- function(p, mean = 0, sd = 1, nu = 5, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Compute the quantile function of the # skewed Student-t distribution # FUNCTION: # Shift and Scale: result = .qsstd(p = p, nu = nu, xi = xi) * sd + mean # Return Value: result } # ------------------------------------------------------------------------------ rsstd <- function(n, mean = 0, sd = 1, nu = 5, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Generate random deviates from the # skewed Student-t distribution # FUNCTION: # Shift and Scale: result = .rsstd(n = n, nu = nu, xi = xi) * sd + mean # Return Value: result } ################################################################################ .dsstd <- function(x, nu, xi) { # A function implemented by Diethelm Wuertz # Description: # Internal Function # FUNCTION: # For SPlus compatibility: if (!exists("beta")) beta <- function (a, b) exp( lgamma(a) + lgamma(b) -lgamma(a+b) ) # Standardize: m1 = 2 * sqrt(nu-2) / (nu-1) / beta(1/2, nu/2) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) z = x*sigma + mu # Compute: Xi = xi^sign(z) g = 2 / (xi + 1/xi) Density = g * dstd(x = z/Xi, nu = nu) # Return Value: Density * sigma } # ------------------------------------------------------------------------------ .psstd <- function(q, nu, xi) { # A function implemented by Diethelm Wuertz ## ## fixed by GNB, see section 'CHANGES in fGarch VERSION 4021.87, 2022-08-06', subsection ## 'BUG fixes' in NEWS.Rd. # Description: # Internal Function # FUNCTION: # For SPlus compatibility: if (!exists("beta")) beta <- function (a, b) exp( lgamma(a) + lgamma(b) -lgamma(a+b) ) # Standardize: m1 = 2 * sqrt(nu-2) / (nu-1) / beta(1/2, nu/2) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) z = q*sigma + mu # Compute: sig <- ifelse(z >= 0, 1, -1) # note: 1 for z = 0; was sign(z) Xi = xi^sig # not sign(z) g = 2 / (xi + 1/xi) # was: Probability = Heaviside(z) - sign(z) * g * Xi * pstd(q = -abs(z)/Xi, nu = nu) Probability = ifelse(z >= 0, 1, 0) - sig * g * Xi * pstd(q = -abs(z)/Xi, nu = nu) # Return Value: Probability } # ------------------------------------------------------------------------------ .qsstd <- function(p, nu, xi) { # A function implemented by Diethelm Wuertz ## ## fixed by GNB, see section 'CHANGES in fGarch VERSION 4021.87, 2022-08-06', subsection ## 'BUG fixes' in NEWS.Rd. # Description: # Internal Function # FUNCTION: # For SPlus compatibility: if (!exists("beta")) beta <- function (a, b) exp( lgamma(a) + lgamma(b) -lgamma(a+b) ) # Standardize: m1 = 2 * sqrt(nu-2) / (nu-1) / beta(1/2, nu/2) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) # Compute: g = 2 / (xi + 1/xi) pxi <- p - (1 / (1 + xi^2)) # not p - 1/2 sig <- sign(pxi) # not p - 1/2 Xi = xi^sig p = (Heaviside(pxi) - sig * p) / (g * Xi) # pxi, not p - 1/2 Quantile = (-sig*qstd(p = p, sd = Xi, nu = nu) - mu ) / sigma # Return Value: Quantile } # ------------------------------------------------------------------------------ .rsstd <- function(n, nu, xi) { # A function implemented by Diethelm Wuertz # Description: # Internal Function # FUNCTION: # For SPlus compatibility: if (!exists("beta")) beta <- function (a, b) exp( lgamma(a) + lgamma(b) -lgamma(a+b) ) # Generate Random Deviates: weight = xi / (xi + 1/xi) z = runif(n, -weight, 1-weight) Xi = xi^sign(z) Random = -abs(rstd(n, nu = nu))/Xi * sign(z) # Scale: m1 = 2 * sqrt(nu-2) / (nu-1) / beta(1/2, nu/2) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) Random = (Random - mu ) / sigma # Return value: Random } ################################################################################ fGarch/R/dist-sged.R0000755000176200001440000001550414332475530013671 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # dsged Density for the skewed GED # psged Probability function for the skewed GED # qsged Quantile function for the skewed GED # rsged Random Number Generator for the skewed GED # FUNCTION: DESCRIPTION: # .dsged Internal, density for the skewed GED # .psged Internal, probability function for the skewed GED # .qsged Internal, quantile function for the skewed GED # .rsged Internal, random Number Generator for the skewed GED ################################################################################ dsged <- function(x, mean = 0, sd = 1, nu = 2, xi = 1.5, log = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Compute the density function of the # skewed generalized error distribution # FUNCTION: # Params: if (length(mean) == 4) { xi = mean[4] nu = mean[3] sd = mean[2] mean = mean[1] } # Shift and Scale: result = .dsged(x = (x-mean)/sd, nu = nu, xi = xi) / sd # Log: if(log) result = log(result) # Return Value: result } # ------------------------------------------------------------------------------ psged <- function(q, mean = 0, sd = 1, nu = 2, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Compute the distribution function of the # skewed generalized error distribution # FUNCTION: # Shift and Scale: result = .psged(q = (q-mean)/sd, nu = nu, xi = xi) # Return Value: result } # ------------------------------------------------------------------------------ qsged <- function(p, mean = 0, sd = 1, nu = 2, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Compute the quantile function of the # skewed generalized error distribution # FUNCTION: # Shift and Scale: result = .qsged(p = p, nu = nu, xi = xi) * sd + mean # Return Value: result } # ------------------------------------------------------------------------------ rsged <- function(n, mean = 0, sd = 1, nu = 2, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Generate random deviates from the # skewed generalized error distribution # FUNCTION: # Shift and Scale: result = .rsged(n = n, nu = nu, xi = xi) * sd + mean # Return Value: result } ################################################################################ .dsged <- function(x, nu, xi) { # A function implemented by Diethelm Wuertz # Description: # Internal Function # FUNCTION: # Standardize: lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) g = nu / ( lambda * (2^(1+1/nu)) * gamma(1/nu) ) m1 = 2^(1/nu) * lambda * gamma(2/nu) / gamma(1/nu) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) z = x*sigma + mu # Compute: Xi = xi^sign(z) g = 2 / (xi + 1/xi) Density = g * dged(x = z/Xi, nu=nu) # Return Value: Density * sigma } # ------------------------------------------------------------------------------ .psged <- function(q, nu, xi) { # A function implemented by Diethelm Wuertz ## ## fixed by GNB, see section 'CHANGES in fGarch VERSION 4021.87, 2022-08-06', subsection ## 'BUG fixes' in NEWS.Rd. # Description: # Internal Function # FUNCTION: # Standardize: lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) g = nu / ( lambda * (2^(1+1/nu)) * gamma(1/nu) ) m1 = 2^(1/nu) * lambda * gamma(2/nu) / gamma(1/nu) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) z = q*sigma + mu # Compute: sig <- ifelse(z >= 0, 1, -1) # note: 1 for z = 0; was sign(z) Xi = xi^sig g = 2 / (xi + 1/xi) ## was Probability = Heaviside(z) - sign(z) * g * Xi * pged(q = -abs(z)/Xi, nu=nu) Probability = ifelse(z >= 0, 1, 0) - sig * g * Xi * pged(q = -abs(z)/Xi, nu=nu) # Return Value: Probability } # ------------------------------------------------------------------------------ .qsged <- function(p, nu, xi) { # A function implemented by Diethelm Wuertz ## ## fixed by GNB, see section 'CHANGES in fGarch VERSION 4021.87, 2022-08-06', subsection ## 'BUG fixes' in NEWS.Rd. # Description: # Internal Function # FUNCTION: # Standardize: lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) g = nu / ( lambda * (2^(1+1/nu)) * gamma(1/nu) ) m1 = 2^(1/nu) * lambda * gamma(2/nu) / gamma(1/nu) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) # Compute: g = 2 / (xi + 1/xi) pxi <- p - (1 / (1 + xi^2)) # not p - 1/2 sig <- sign(pxi) # not p - 1/2 Xi = xi^sig p = (Heaviside(pxi) - sig * p) / (g * Xi) # pxi, not p - 1/2 Quantile = (-sig*qged(p=p, sd=Xi, nu=nu) - mu ) / sigma # Return Value: Quantile } # ------------------------------------------------------------------------------ .rsged <- function(n, nu, xi) { # A function implemented by Diethelm Wuertz # Description: # Internal Function # FUNCTION: # Generate Random Deviates: weight = xi / (xi + 1/xi) z = runif(n, -weight, 1-weight) Xi = xi^sign(z) Random = -abs(rged(n, nu=nu))/Xi * sign(z) # Scale: lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) g = nu / ( lambda * (2^(1+1/nu)) * gamma(1/nu) ) m1 = 2^(1/nu) * lambda * gamma(2/nu) / gamma(1/nu) mu = m1*(xi-1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) Random = (Random - mu ) / sigma # Return value: Random } ################################################################################ fGarch/R/dist-sstdSlider.R0000755000176200001440000000716014263246022015061 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # sstdSlider Displays Variance-1 Student-t Distribution and RVS ################################################################################ sstdSlider <- function(type = c("dist", "rand")) { # A function implemented by Diethelm Wuertz # Description: # Displays interactively skew Student-t distribution # Note: # dsstd(x, mean = 0, sd = 1, nu = 5, xi = 1.5) # FUNCTION: # Internal Function: refresh.code = function(...) { # Sliders: N = .sliderMenu(no = 1) mean = .sliderMenu(no = 2) sd = .sliderMenu(no = 3) nu = .sliderMenu(no = 4) xi = .sliderMenu(no = 5) invert = .sliderMenu(no = 6) # Compute Data: if (invert == 1) xi = round(1/xi, digits = 4) xmin = round(qsstd(0.01, mean, sd, nu, xi), digits = 2) xmax = round(qsstd(0.99, mean, sd, nu, xi), digits = 2) s = seq(xmin, xmax, length = N) y1 = dsstd(s, mean, sd, nu, xi) y2 = psstd(s, mean, sd, nu, xi) main1 = paste("Skew Student-t Density\n", "mean = ", as.character(mean), " | ", "sd = ", as.character(sd), " | ", "nu = ", as.character(nu), " | ", "xi = ", as.character(xi) ) main2 = paste("Skew Student-t Probability\n", "xmin [0.01] = ", as.character(xmin), " | ", "xmax [0.99] = ", as.character(xmax) ) # Random Numbers: if (type[1] == "rand") { x = rsstd(N, mean, sd, nu, xi) } # Frame: par(mfrow = c(2, 1), cex = 0.7) # Density: if (type[1] == "rand") { hist(x, probability = TRUE, col = "steelblue", border = "white", breaks = "FD", xlim = c(xmin, xmax), ylim = c(0, 1.1*max(y1)), main = main1 ) lines(s, y1, col = "orange") } else { plot(s, y1, type = "l", xlim = c(xmin, xmax), col = "steelblue") abline (h = 0, lty = 3) title(main = main1) grid() } # Probability: plot(s, y2, type = "l", xlim = c(xmin, xmax), ylim = c(0, 1), col = "steelblue" ) abline (h = 0, lty = 3) title(main = main2) grid() # Frame: par(mfrow = c(1, 1), cex = 0.7) } # Open Slider Menu: .sliderMenu(refresh.code, names = c( "N", "mean", "sd", "nu", "xi", "xi.inv"), minima = c( 10, -5.0, 0.1, 2.1, 1.0, 0 ), maxima = c( 500, +5.0, 5.0, 10.0, 10.0, 1 ), resolutions = c( 10, 0.1, 0.1, 0.1, 0.1, 1 ), starts = c( 100, 0.0, 1.0, 5.0, 1.0, 0 ) ) } ################################################################################ fGarch/R/garch-Distribution.R0000755000176200001440000001327214263246022015542 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .garchSetCondDist Selects conditional density function # .garchDist Defines conditional density function # .normCondDist Normal Distribution # .QMLECondDist QMLE with Normal Distribution # .snormCondDist Skew Normal Distribution # .stdCondDist Student-t Distribution # .sstdCondDist Skew Student-t Distribution # .gedCondDist Generalized Error Distribution # .sgedCondDist Skew Generalized Error Distribution # .snigCondDist Normal Inverse Gaussian Distribution # .setfGarchEnv Set fGarch environment for conditional distribution ################################################################################ .garchSetCondDist <- function(cond.dist = "norm") { # A function implemented by Diethelm Wuertz # Description: # Select Conditional Density Function # Arguments: # cond.dist - a character string with the name of the # conditional distribution function. Valid strings are: # "norm", "snorm", "std", "sstd", "ged", "sged", "snig". # Value: # Returns the selection conditional distribution function # named uniquely '.garchDist'. # Details: # Implemented Distributions: # norm - Normal Distribution: nothing to estimate # snorm - Skew Normal Distribution: xi may be estimated # std - Student-t Distribution: nu may be estimated # sstd - Skew Student-t Distribution: nu and xi may be estimated # ged - Generalized Error Distribution: nu may be estimated # sged - Skew Generalized Error Distribution: nu and xi may be estimated # FUNCTION: # Compose Function: fun = paste(".", cond.dist, "CondDist", sep = "") .garchDist = match.fun(fun) # Trace the Result: if(FALSE) { cat("\n Distribution: ", cond.dist, "\n .garchDist = ") print(.garchDist) } # Return Value: .garchDist } # ------------------------------------------------------------------------------ .normCondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # Normal Distribution: # Use base::dnorm dnorm(x = z/hh, mean = 0, sd = 1) / hh } # ------------------------------------------------------------------------------ .QMLECondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # Normal Distribution: # Use base::dnorm dnorm(x = z/hh, mean = 0, sd = 1) / hh } # ------------------------------------------------------------------------------ .snormCondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # Skew Normal Distribution: # Use fGarch::dsnorm dsnorm(x = z/hh, mean = 0, sd = 1, xi = skew) / hh } # ------------------------------------------------------------------------------ .stdCondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # Standardized Student-t Distribution: # Use fGarch::dstd dstd(x = z/hh, mean = 0, sd = 1, nu = shape) / hh } # ------------------------------------------------------------------------------ .sstdCondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # Skew Standardized Student-t Distribution: # Use fGarch::dsstd dsstd(x = z/hh, mean = 0, sd = 1, nu = shape, xi = skew) / hh } # ------------------------------------------------------------------------------ .gedCondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # Generalized Error Distribution: # Use fGarch::dged dged(x = z/hh, mean = 0, sd = 1, nu = shape) / hh } # ------------------------------------------------------------------------------ .sgedCondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # Skew Generalized Error Distribution: # Use fGarch::dsged dsged(x = z/hh, mean = 0, sd = 1, nu = shape, xi = skew) / hh } # ------------------------------------------------------------------------------ .snigCondDist <- function(z, hh, skew, shape) { # A function implemented by Diethelm Wuertz # FUNCTION: # (Skew) Normal Inverse Gaussian Distribution: # Use fBasics::dsnig dsnig(x = z/hh, zeta = shape, rho = skew) / hh } # ------------------------------------------------------------------------------ .setfGarchEnv(.garchDist = .garchSetCondDist("norm")) ################################################################################ fGarch/R/methods-volatility.R0000755000176200001440000000424314263246022015640 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # METHOD: EXTRACTORS: # volatility.fGARCH Returns conditional volatilities for 'fGARCH' objects ################################################################################ volatility.fGARCH <- ## better to use S3 style because volatility is defined as a S3 generic ## setMethod(f = "volatility", signature(object = "fGARCH"), definition = function(object, type = c("sigma", "h"), ...) { # A function implemented by Diethelm Wuertz # Description: # Returns conditional volatilities for 'fGARCH' objects # Arguments: # object - an object of class 'fGarch' as returned by the function # garchFit # type - a character string denoting if the conditional standard # deviations "sigma" or the variances "h" should be returned. # ... - optional argument to be passed, not used. # Note: # "volatility" is a generic function. It's default method calculates # (x-mean(x))^2. # FUNCTION: # Match Arguments: type = match.arg(type) # Numeric vectors of conditional values: if (type == "sigma") { volatility = slot(object, "sigma.t") } else if (type == "h") { volatility = slot(object, "h.t") } attr(volatility, "type") <- type # Return Value: volatility } ##) ################################################################################ fGarch/R/dist-absMoments.R0000755000176200001440000000706414326146312015055 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: MOMENTS: # absMoments Compute absolute moments of a symmetric distribution ################################################################################ absMoments <- function(n, density = c("dnorm", "dged", "dstd"), ...) { # A function implemented by Diethelm Wuertz ## ## Georgi N. Boshnakov corrected the computation for std # Description: # Compute the absolute moments of a standardized # symmetric distribution function. # Arguments: # n - a vector of integers i, to compute M_i # density - a character denoting the density # "norm", "ged", "std" or any other # ... - parameters passed to the standardized # symmetric density function # Value: # Returns a numeric vector of moments M_i. # Stores globally errors in the variable absMoment.error # if the moments were computed numerically. # FUNCTION: # norm - Normal Distribution: if (density == "dnorm" | density == "norm") { return (sqrt(2)^n * gamma((n+1)/2) / sqrt(pi)) } # ged - Generalized Error Distribution: if (density == "dged" | density == "ged") { parm = function(n, nu) { lambda = sqrt ( 2^(-2/nu) * gamma(1/nu) / gamma(3/nu) ) return ((2^(1/nu)*lambda)^n * gamma((n+1)/nu) / gamma(1/nu)) } return(parm(n, ...)) } # std - Standardized Student-t Distribution: # Note: nu > 2*n if (density == "dstd" | density == "std") { parm = function(n, nu) { ## GNB: this is wrong, gives NaN's when it shouldn't: ## beta(1/2 + 2*n, nu/2 - 2*n) / beta(1/2, nu/2) * sqrt(nu-2) ## ## This is from the paper Wuertz at all (draft for JSS), eq. (14): ## ## r <- n / 2 ## beta(1/2 + r/2, nu/2 - r/2) / beta(1/2, nu/2) * (nu-2)^(r/2) ## ## but the results are not right. It looks like a typo/error in the ## formula and changing r/2 to n/2 gives a consistent result with ## the usual t-distribution ## beta(1/2 + n/2, nu/2 - n/2) / beta(1/2, nu/2) * (nu-2)^(n/2) } return(parm(n, ...)) } # Any other standardized symmetric Distribution ... fun = match.fun(density) moments = function(x, n, ...) { 2 * x^n * fun(x, ...) } M = .absMoments.error <- NULL for (i in n) { I = integrate(moments, 0, Inf, n = i, ...) M = c(M, I$value) .absMoments.error <- c(.absMoments.error, I$abs.error) } attr(M, "control") <- .absMoments.error return(M) # Return Value: invisible() } ################################################################################ fGarch/R/garch-Stats.R0000755000176200001440000001070414263246022014156 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # garchKappa Computes Expection for APARCH Models # .garchKappaFun Internal function used by garchKappa() # FUNCTION: DESCRIPTION: # .truePersistence Computes true persistence ################################################################################ garchKappa <- function(cond.dist = c("norm", "ged", "std", "snorm", "sged", "sstd", "snig"), gamma = 0, delta = 2, skew = NA, shape = NA) { # A function implemented by Diethelm Wuertz # Description: # Computes Expection for APARCH Models # FUNCTION: # Compute kappa: kappa = integrate(.garchKappaFun, lower = -Inf, upper = Inf, cond.dist = cond.dist[1], gamma = gamma, delta = delta, skew = skew, shape = shape)[[1]] names(kappa) = "kappa" attr(kappa, "control") = c(gamma = gamma, delta = delta, skew = skew, shape = shape) attr(kappa, "cond.dist") = cond.dist[1] # Return Value: kappa } # ------------------------------------------------------------------------------ .garchKappaFun <- function(x, cond.dist = c("norm", "ged", "std", "snorm", "sged", "sstd", "snig"), gamma = 0, delta = 2, skew = NA, shape = NA) { # A function implemented by Diethelm Wuertz # Description: # Internal function used by kappa() # FUNCTION: # Compute Expectation Value for ... funcE = (abs(x) - gamma*x)^delta # Select Appropriate Conditional Density: cond.dist = cond.dist[1] if (cond.dist == "norm") { fun = funcE * dnorm(x) } if (cond.dist == "ged") { fun = funcE * dged(x, nu = shape) } if (cond.dist == "std") { fun = funcE * dstd(x, nu = shape) } if (cond.dist == "snorm") { fun = funcE * dsnorm(x, xi = skew) } if (cond.dist == "sged") { fun = funcE * dsged(x, nu = shape, xi = skew) } if (cond.dist == "sstd") { fun = funcE * dsstd(x, nu = shape, xi = skew) } if (cond.dist == "snig") { fun = funcE * dsnig(x, zeta = shape, rho = skew) } # Return Value: fun } ################################################################################ .truePersistence <- function(fun = "norm", alpha = 1, gamma = 0, beta = 0, delta = 1, ...) { # A function implemented by Diethelm Wuertz # Description: # Computes persistence for an APARCH process # Arguments: # fun - name of density functions of APARCH innovations # alpha, gamma - numeric value or vector of APARCH coefficients, # must be of same length # beta - numeric value or vector of APARCH coefficients # delta - numeric value of APARCH exponent # Note: # fun is one of: norm, snorn, std, sstd, ged, sged, snig # FUNCTION: # Match Density Function: fun = match.fun(fun) # Persisgtence Function: E(|z|-gamma z)^delta e = function(x, gamma, delta, ...) { (abs(x)-gamma*x)^delta * fun(x, ...) } # Compute Persistence by Integration: persistence = sum(beta) for (i in 1:length(alpha)) { I = integrate(e, -Inf, Inf, subdivisions = 1000, rel.tol = .Machine$double.eps^0.5, gamma = gamma[i], delta = delta, ...) persistence = persistence + alpha[i] * I[[1]] } # Warning: if (persistence >= 1) { p = as.character(round(persistence, digits = 3)) warning(paste("Divergent persistence p =", p)) } # Return Value: persistence } ################################################################################ fGarch/R/garch-FitInternal.R0000755000176200001440000003356014263246022015304 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .garchFit Internal GARCH Fit # .garchArgsParser Parses formula and data for garchFit # .garchModelSeries Composes model series like in lm fits # .garchOptimizerControl Sets default values for Garch Optimizer # .garchNames Slot names, @fit slot, parameters and controls ################################################################################ ## called from garchFit() and .ugarchFit() .garchFit <- function( formula.mean = ~arma(0, 0), formula.var = ~garch(1, 1), series, init.rec = c("mci", "uev"), delta = 2, skew = 1, shape = 4, cond.dist = c("norm", "snorm", "ged", "sged", "std", "sstd", "QMLE"), include.mean = TRUE, include.delta = NULL, include.skew = NULL, include.shape = NULL, leverage = NULL, trace = TRUE, algorithm = c("sqp", "nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), hessian = c("ropt", "rcd"), robust.cvar, control = list(), title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description # Fit parameters to a ARMA-GARCH model # Arguments: # formula.mean - ARMA(m,n) mean specification # formula.var - GARCH/APARCH(p,q) variance specification # series - time series # init.rec - names type of initialization of recurrence # mci = mu-current-iteration, or # uev = unconditional-expected-variances # delta - numeric value of the exponent delta # skew - optional skewness parameter # shape - optional shape parameter # cond.dist - name of the conditional distribution # include.mean - should the mean value be estimated ? # include.delta - should the exponent be estimated ? # leverage - should the leverage factors be estimated ? # trace - should the optimization be traced ? # algorithm - # control - list of additional control parameters for solver # title - an optional title string # description - an optional project description string # Note: # This is the old version of garchFit, we keep it for backward # compatibility. # FUNCTION: # Debug Mode: DEBUG <- FALSE # Allow only full formula specification: if(DEBUG) print("Formula Specification ...") fcheck = rev(all.names(formula.mean))[1] if (fcheck == "ma") { stop("Use full formula: arma(0,q) for ma(q)") } else if (fcheck == "ar") { stop("Use full formula expression: arma(p,0) for ar(p)") } # Check for Recursion Initialization: if(DEBUG) print("Recursion Initialization ...") if(init.rec[1] != "mci" & algorithm[1] != "sqp") { stop("Algorithm only supported for mci Recursion") } # Get Start Time: .StartFit <- Sys.time() # Generate Control List - Define Default Settings: if(DEBUG) print("Generate Control List ...") con <- .garchOptimizerControl(algorithm, cond.dist) con[(namc <- names(control))] <- control # Initialize Time Series Information - Save Globally: # keep copy of input data if(DEBUG) print("Initialize Time Series ...") data <- series # scale time series scale <- if (con$xscale) sd(series) else 1 series <- series/scale .series <- .garchInitSeries( formula.mean = formula.mean, formula.var = formula.var, cond.dist = cond.dist[1], series = series, scale = scale, init.rec = init.rec[1], h.start = NULL, llh.start = NULL, trace = trace) .setfGarchEnv(.series = .series) # Initialize Model Parameters - Save Globally: if(DEBUG) print("Initialize Model Parameters ...") .params <- .garchInitParameters( formula.mean = formula.mean, formula.var = formula.var, delta = delta, skew = skew, shape = shape, cond.dist = cond.dist[1], include.mean = include.mean, include.delta = include.delta, include.skew = include.skew, include.shape = include.shape, leverage = leverage, algorithm = algorithm[1], control = con, trace = trace) .setfGarchEnv(.params = .params) # Select Conditional Distribution Function: if(DEBUG) print("Select Conditional Distribution ...") .setfGarchEnv(.garchDist = .garchSetCondDist(cond.dist[1])) # Estimate Model Parameters - Minimize llh, start from big value: if(DEBUG) print("Estimate Model Parameters ...") .setfGarchEnv(.llh = 1.0e99) .llh <- .getfGarchEnv(".llh") fit = .garchOptimizeLLH(hessian, robust.cvar, trace) # Add to Fit: if (DEBUG) print("Add to fit ...") .series <- .getfGarchEnv(".series") .params <- .getfGarchEnv(".params") names(.series$h) <- NULL fit$series = .series fit$params = .params # Retrieve Residuals and Fitted Values: if (DEBUG) print("Retrieve Residuals and Fitted Values ...") residuals = .series$z fitted.values = .series$x - residuals h.t = .series$h deltainv <- 1/(if(.params$includes["delta"]) fit$par["delta"] else fit$params$delta) sigma.t = (.series$h)^deltainv # Standard Errors and t-Values: if (DEBUG) print("Standard Errors and t-Values ...") fit$cvar <- if (robust.cvar) (solve(fit$hessian) %*% (t(fit$gradient) %*% fit$gradient) %*% solve(fit$hessian)) else - solve(fit$hessian) fit$se.coef = sqrt(diag(fit$cvar)) fit$tval = fit$coef/fit$se.coef fit$matcoef = cbind(fit$coef, fit$se.coef, fit$tval, 2*(1-pnorm(abs(fit$tval)))) dimnames(fit$matcoef) = list(names(fit$tval), c(" Estimate", " Std. Error", " t value", "Pr(>|t|)")) # Add Title and Description: if (DEBUG) print("Add Title and Description ...") if(is.null(title)) title = "GARCH Modelling" if(is.null(description)) description = description() # {timeSeries} # Total Execution Time: Time = Sys.time() - .StartFit if(trace) { cat("\nTime to Estimate Parameters:\n ") print(Time) } # Return Value: new("fGARCH", call = as.call(match.call()), formula = formula(paste("~", formula.mean, "+", formula.var, collapse = " ")), method = "Max Log-Likelihood Estimation", data = data, fit = fit, residuals = residuals, fitted = fitted.values, h.t = h.t, sigma.t = as.vector(sigma.t), title = as.character(title), description = as.character(description) ) } # ------------------------------------------------------------------------------ .garchArgsParser <- function(formula, data, trace = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Parses formula and data for garchFit # Arguments: # formula - ARMA(m,n) + GARCH/APARCH(p,q) mean and variance # specification # data - time series input as a timeSeries # Note: # This function returns the input formula and input data in # proper formats. Two cases are deistinguished # FUNCTION: # Get Data: allVars = unique(sort(all.vars(formula))) allVarsTest = mean(allVars %in% colnames(data)) if (allVarsTest != 1) { print(allVars) print(colnames(data)) stop ("Formula and data units do not match.") } formula.lhs = as.character(formula)[2] # Model frame: mf = match.call(expand.dots = FALSE) if(trace) { cat("\nMatched Function Call:\n ") print(mf) } m = match(c("formula", "data"), names(mf), 0) mf = mf[c(1, m)] # Model the timeSeries - Have a look on the function .garchModelSeries() ... # here we cant use "model/frame" ! mf[[1]] = as.name(".garchModelSeries") mf$fake = FALSE mf$lhs = TRUE if(trace) { cat("\nModelSeries Call:\n ") print(mf) } x = eval(mf, parent.frame()) if(trace) print(x) # Now extract the modelled series ... x = as.vector(x[, 1]) names(x) = rownames(data) if(trace) print(x) # Compose Mean and Variance Formula: allLabels = attr(terms(formula), "term.labels") if(trace) { cat("\nAll Term Labels:\n ") print(allLabels) } if(length(allLabels) == 2) { formula.mean = as.formula(paste("~", allLabels[1])) formula.var = as.formula(paste("~", allLabels[2])) } else if(length(allLabels) == 1) { formula.mean = as.formula("~ arma(0, 0)") formula.var = as.formula(paste("~", allLabels[1])) } if(trace) { cat("\nMean Formula:\n ") print(formula.mean) cat("\nVariance Formula:\n ") print(formula.var) } # Result: ans <- list( formula.mean = formula.mean, formula.var = formula.var, formula.lhs = formula.lhs, series = x) # Return Value: ans } # ------------------------------------------------------------------------------ .garchModelSeries <- function (formula, data, fake = FALSE, lhs = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Composes model series like in lm fits # Arguments: # Note: # ... have a look on model.frame() # FUNCTION: # Formula: if (length(formula) == 2) { formula = as.formula(paste("x", formula[1], formula[2], collapse = "")) stopifnot(!missing(data)) } # Missing Data ? if (missing(data)) { data = eval(parse(text = search()[2]), parent.frame()) } # Numeric Data ? if (is.numeric(data)) { data = data.frame(data) colnames(data) = all.vars(formula)[1] lhs = TRUE } # Faked Formula ? if (fake) { response = as.character(formula)[2] Call = as.character(match.call()[[2]][[3]]) method = Call[1] predictors = Call[2] formula = as.formula(paste(response, "~", predictors)) } # Left-Hand-Side Formula ? if (lhs) { response = as.character(formula)[2] formula = as.formula(paste(response, "~", 1)) } # Compose Model Frame: x = model.frame(formula, data) # timeSeries ? if (inherits(data, "timeSeries")) x = timeSeries(x) # Add control atrribute: if (fake) { attr(x, "control") <- method } # Return Value: x } # ------------------------------------------------------------------------------ .garchOptimizerControl <- function(algorithm, cond.dist) # function(algorithm, cond.dist) { # A function implemented by Diethelm Wuertz # Description: # Sets default values for Garch Optimizer # Arguments: # none # FUNCTION: # Check llh for the standardized NIG Distribution: llh = "internal" if (cond.dist == "snig") llh = "filter" # Generate Control List with Default Settings: con <- list( # In General: fscale = TRUE, xscale = TRUE, algorithm = algorithm, llh = llh, # BFGS - NLMINB Algorithm: tol1 = 1, tol2 = 1, # SQP Algorithm: MIT = 2000, # maximum number of iterations (200) MFV = 5000, # maximum number of function evaluations (500) MET = 5, # specifies scaling strategy: # MET=1 - no scaling # MET=2 - preliminary scaling in 1st iteration (default) # MET=3 - controlled scaling # MET=4 - interval scaling # MET=5 - permanent scaling in all iterations MEC = 2, # correction for negative curvature: # MEC=1 - no correction # MEC=2 - Powell correction (default) MER = 1, # restarts after unsuccessful variable metric updates: # MER=0 - no restarts # MER=1 - standard restart MES = 4, # interpolation method selection in a line search: # MES=1 - bisection # MES=2 - two point quadratic interpolation # MES=3 - three point quadratic interpolation # MES=4 - three point cubic interpolation (default) XMAX = 1.0e3, TOLX = 1.0e-10, TOLC = 1.0e-6, TOLG = 1.0e-6, TOLD = 1.0e-6, TOLS = 1.0e-4, RPF = 1.0e-2) # 1.0e-4) # Return Value: con } # ------------------------------------------------------------------------------ .garchNames <- function(object) { # A function implemented by Diethelm Wuertz # Description: # Print slot names, @fit slot, parameters and controls # Arguments: # object - an object of class 'fGARCH' # FUNCTION: # Slot Names: cat("\nNames - @ \n") print(slotNames(object)) # @fit Slot: cat("\nNames - @fit \n") print(names(object@fit)) # Parameters: cat("\nNames - @fit$params \n") print(names(object@fit$params)) # Control: cat("\nNames - @fit$params$control \n") print(names(object@fit$params$control)) # Return Value: invisible() } ################################################################################ fGarch/R/dist-gedFit.R0000755000176200001440000001011614263246022014136 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # .gedFit New: Fit the parameters for a GED distribution # gedFit Fit the parameters for a GED distribution ################################################################################ .gedFit <- function(x, mean = 0, sd = 1, nu = 2, scale = NA, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE, title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description: # Fits parameters of a NIG using maximum log-likelihood # Example: # set.seed(4711); x = rged(500); .gedFit(x)@fit$estimate # FUNCTION: # Settings: dist = dged model = "GED Parameter Estimation" scale = "not used" x = x.orig = as.vector(x) # Parameter Estimation: obj = function(x, y = x, trace) { f <- tryCatch(-sum(log(dist(y, x[1], x[2], x[3]))), error=identity) if (is.na(f) || inherits(f, "error")) return(1e9) # Print Iteration Path: if (trace) { cat("\n Objective Function Value: ", -f) cat("\n Parameter Estimates: ", x, "\n") } f } r = nlminb( start = c(mean = 0, sd = 1, nu = 2), objective = obj, lower = c(-Inf, 0, 0), upper = c( Inf, Inf, Inf), y = x, trace = trace) names(r$par) <- c("mean", "sd", "nu") # Add Title and Description: if (is.null(title)) title = model if (is.null(description)) description = description() # Result: fit = list(estimate = r$par, minimum = -r$objective, code = r$convergence) # Optional Plot: if (doplot) { x = as.vector(x.orig) if (span == "auto") span = seq(min(x), max(x), length = 501) z = density(x, n = 100, ...) x = z$x[z$y > 0] y = z$y[z$y > 0] y.points = dist(span, r$par[1], r$par[2], r$par[3]) ylim = log(c(min(y.points), max(y.points))) if (add) { lines(x = span, y = log(y.points), col = "steelblue") } else { plot(x, log(y), xlim = c(span[1], span[length(span)]), ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...) title(main = model) lines(x = span, y = log(y.points), col = "steelblue") } } # Return Value: new("fDISTFIT", call = match.call(), model = model, data = as.data.frame(x.orig), fit = fit, title = title, description = description() ) } # ------------------------------------------------------------------------------ gedFit <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Fit the parameters for a generalized error distribution # FUNCTION: # Start Value: start = c(mean = mean(x), sd = sqrt(var(x)), nu = 2) # Log-likelihood Function: loglik = function(x, y = x){ f = -sum(log(dged(y, x[1], x[2], x[3]))) f } # Minimization: fit = nlminb( start = start, objective = loglik, lower = c(-Inf, 0, 0), upper = c( Inf, Inf, Inf), y = x, ...) # Add Names to $par names(fit$par) = c("mean", "sd", "nu") # Return Value: fit } ################################################################################ fGarch/R/garch-FitFromFormula.R0000755000176200001440000001445114263246022015757 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # garchFit Fits the parameters of GARCH process # .garchArgsParser Parses formula and data for garchFit # .garchOptimizerControl Sets default values for Garch Optimizer # .garchFit ... old Version, still in use by garchFit() # .garchNames Slot names, @fit slot, parameters and controls ################################################################################ garchFit <- function(formula = ~ garch(1,1), data, init.rec = c("mci", "uev"), delta = 2, skew = 1, shape = 4, cond.dist = c("norm", "snorm", "ged", "sged", "std", "sstd", "snig", "QMLE"), include.mean = TRUE, include.delta = NULL, include.skew = NULL, include.shape = NULL, leverage = NULL, trace = TRUE, algorithm = c("nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), hessian = c("ropt", "rcd"), control = list(), title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description: # Fit parameters to a ARMA-GARCH model by Formula Specification # Arguments: # formula - ARMA(m,n) + GARCH/APARCH(p,q) mean and variance # specification # data - any univariate time series which can be converted # into a timeSeries using the generic function as.timeSeries # init.rec - names type of initialization of recurrence # mci = mu-current-iteration, or # uev = unconditional-expected-variances # delta - numeric value of the exponent delta # skew - optional skewness or skewness related parameter # shape - optional shape parameter # cond.dist - name of the conditional distribution, one of # norm, snorm, ged, sged, std, sstd, snig, QMLE # include.mean - a logical, should the mean value be estimated ? # include.delta - should the exponent be estimated ? # leverage - should the leverage factors be estimated ? # trace - should the optimization be traced ? # control - list of additional control parameters for the solver # title - an optional title string # description - an optional project description string # Example: # garchFit() # FUNCTION: # DEBUG: DEBUG = FALSE # Match arguments: init.rec = match.arg(init.rec) cond.dist = match.arg(cond.dist) hessian = match.arg(hessian) algorithm = match.arg(algorithm) # Call: CALL = match.call() # Parse formula and data for garchFit ... # Note in the new version we are working with timeSeries ... Name = capture.output(substitute(data)) if(is.character(data)) { eval(parse(text = paste("data(", data, ")"))) data = eval(parse(text = data)) } # data <- if (inherits(data, "timeSeries") data else as.timeSeries(data) data <- as.data.frame(data) # Column Names: if (isUnivariate(data)) { colnames(data) <- "data" } else { # Check unique column Names: uniqueNames = unique(sort(colnames(data))) if (is.null(colnames(data))) { stop("Column names of data are missing.") } if (length(colnames(data)) != length(uniqueNames)) { stop("Column names of data are not unique.") } } # Handle if we have no left-hand-side for the formula ... # Note in this case the length of the formula is 2 (else 3): if (length(formula) == 3 && isUnivariate(data) ) formula[2] <- NULL if (length(formula) == 2) { if (isUnivariate(data)) { # Missing lhs -- we substitute the data file name as lhs ... formula = as.formula(paste("data", paste(formula, collapse = " "))) } else { stop("Multivariate data inputs require lhs for the formula.") } } # Robust Covariance ? robust.cvar <- (cond.dist == "QMLE") # Parse Arguments: args = .garchArgsParser(formula = formula, data = data, trace = FALSE) # DEBUG - Print Arguments: if (DEBUG) print(list( formula.mean = args$formula.mean, formula.var = args$formula.var, series = args$series, init.rec = init.rec, delta = delta, skew = skew, shape = shape, cond.dist = cond.dist, include.mean = include.mean, include.delta = include.delta, include.skew = include.skew, include.shape = include.shape, leverage = leverage, trace = trace, algorithm = algorithm, hessian = hessian, robust.cvar = robust.cvar, control = control, title = title, description = description)) # Fit: ans = .garchFit( formula.mean = args$formula.mean, formula.var = args$formula.var, series = args$series, init.rec, delta, skew, shape, cond.dist, include.mean, include.delta, include.skew, include.shape, leverage, trace, algorithm, hessian, robust.cvar, control, title, description, ...) ans@call = CALL attr(formula, "data") <- paste("data = ", Name, sep = "") ans@formula = formula # Return Value: ans } ################################################################################ fGarch/R/garch-FitFromSpec.R0000755000176200001440000002011714263246022015240 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # fUGARCHSPEC Fits the parameters of GARCH process # .ugarchSpec Specifies a univariate GARCH model # .ugarchFit Fits a univariate GARCH model ################################################################################ ## MM: FIXME .ugarchFit() & .ugarchSpec() are entirely ## ===== *un*documented and *un*tested .setfGarchEnv(.llh = 1e99) .setfGarchEnv(.garchDist = NA) .setfGarchEnv(.params = NA) .setfGarchEnv(.series = NA) .setfGarchEnv(.trace = NA) # ------------------------------------------------------------------------------ setClass("fUGARCHSPEC", representation( model = "list", distribution = "list", optimization = "list", documentation = "list") ) # ------------------------------------------------------------------------------ .ugarchSpec <- function( model = list( formula = ~ garch(1,1), mean = 0, include.mean = TRUE, delta = 2, include.delta = NULL, leverage = NULL, recursion = c("internal", "filter", "testing")[1], init.rec = c("mci", "uev")[1]), distribution = list( cond.dist = c("norm", "snorm", "ged", "sged", "std", "sstd", "snig", "QMLE")[1], skew = 1, include.skew = NULL, shape = 4, include.shape = NULL), optimization = list( algorithm = c("nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm")[1], hessian = c("ropt", "rcd", "rts")[1], trace = TRUE, control = list(), status = NA), documentation = list( call = match.call(), title = NULL, description = NULL ) ) { # Description: # Specifies a garch model to be fitted # Example: # .garchSpec()) # FUNCTION: # Model Slot: Model = list( formula = ~ garch(1,1), mean = 0, include.mean = TRUE, delta = 2, include.delta = NULL, leverage = NULL, recursion = c("internal", "filter", "testing")[1], init.rec = c("mci", "uev")[1]) Model[(Names <- names(model))] <- model # Distribution Slot: Distribution = list( cond.dist = c("norm", "snorm", "ged", "sged", "std", "sstd", "snig", "QMLE")[1], skew = 1, include.skew = NULL, shape = 4, include.shape = NULL) Distribution[(Names <- names(distribution))] <- distribution # Optimization Slot: Optimization = list( algorithm = c("nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm")[1], hessian = c("ropt", "rcd", "rst")[1], trace = TRUE, control = list(), status = NA) Optimization[(Names <- names(optimization))] <- optimization # Documentation Slot: Documentation = list( call = match.call(), title = NULL, description = NULL ) Documentation[(Names <- names(documentation))] <- documentation # Return Value: new("fUGARCHSPEC", model = Model, distribution = Distribution, optimization = Optimization, documentation = Documentation) } # ------------------------------------------------------------------------------ .ugarchFit <- function(data, spec = .ugarchSpec()) { # Description: # Fit parameters to a ARMA-GARCH model by GARCH Specification # Arguments: # data - time series or vector of data # spec - garch specification object # Example: # .ugarchFit(dem2gbp[, 1]) # FUNCTION: DEBUG = FALSE # Set Call: CALL <- spec@documentation$call <- match.call() # Parse Data: Name = capture.output(substitute(data)) if(is.character(data)) { eval(parse(text = paste("data(", data, ")"))) data = eval(parse(text = data)) } data <- as.data.frame(data) # Column Names: if (isUnivariate(data)) { colnames(data) <- "data" } else { # Check unique column Names: uniqueNames = unique(sort(colnames(data))) if (is.null(colnames(data))) { stop("Column names of data are missing.") } if (length(colnames(data)) != length(uniqueNames)) { stop("Column names of data are not unique.") } } # Handle if we have no left-hand-side for the formula ... formula <- spec@model$formula # Note in this case the length of the formula is 2 (else 3): if (length(formula) == 3 && isUnivariate(data) ) formula[2] <- NULL if (length(formula) == 2) { if (isUnivariate(data)) { # Missing lhs -- we substitute the data file name as lhs ... formula = as.formula(paste("data", paste(formula, collapse = " "))) } else { stop("Multivariate data inputs require lhs for the formula.") } } # Robust Formula ? robust.cvar <- (spec@distribution$cond.dist == "QMLE") # Parse Arguments: args = .garchArgsParser(formula = formula, data = data, trace = FALSE) # DEBUG - Print Arguments: if(DEBUG) print(list( formula.mean = args$formula.mean, formula.var = args$formula.var, series = args$series, init.rec = spec@model$init.rec, delta = spec@model$delta, skew = spec@distribution$skew, shape = spec@distribution$shape, cond.dist = spec@distribution$cond.dist, include.mean = spec@model$include.mean, include.delta = spec@model$include.delta, include.skew = spec@distribution$include.skew, include.shape = spec@distribution$include.shape, leverage = spec@model$leverage, trace = spec@optimization$trace, ## recursion = spec@model$recursion, algorithm = spec@optimization$algorithm, hessian = spec@optimization$hessian, robust.cvar = robust.cvar, control = spec@optimization$control, title = spec@documentation$title, description = spec@documentation$description)) # Fit: ans = .garchFit( formula.mean = args$formula.mean, formula.var = args$formula.var, series = args$series, init.rec = spec@model$init.rec, delta = spec@model$delta, skew = spec@distribution$skew, shape = spec@distribution$shape, cond.dist = spec@distribution$cond.dist, include.mean = spec@model$include.mean, include.delta = spec@model$include.delta, include.skew = spec@distribution$include.skew, include.shape = spec@distribution$include.shape, leverage = spec@model$leverage, trace = spec@optimization$trace, ## recursion = spec@model$recursion, algorithm = spec@optimization$algorithm, hessian = spec@optimization$hessian, robust.cvar = robust.cvar, control = spec@optimization$control, title = spec@documentation$title, description = spec@documentation$description) ans@call = CALL attr(formula, "data") <- paste("data = ", Name, sep = "") ans@formula = formula # Return Value: ans } ################################################################################ fGarch/R/fGarch-package.R0000755000176200001440000000144314263246022014561 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ fGarch/R/garch-Hessian.R0000755000176200001440000001333714263246022014457 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # .garchRoptimhess Uses R internal optimhess function # .garchRCDAHessian Computes R coded CDA Hessian matrix # .garchRTSHessian Computes R coded Two Sided Hessian matrix # .hessian2sided Function called from .garchRTSHessian # REQUIRED: # Matrix ################################################################################ ## These are called from .garchOptimizeLLH() -->> ./loglik.R .garchRoptimhess <- function(par, .params, .series, eps = 1.0e-4) { # A function implemeted by Diethelm Wuertz # Description: # Compute Hessian via R's function optimHess() # Arguments: # par - # .params - # .series - # eps - # FUNCTION: # Take Time: .StartHessian <- Sys.time() # Compute Hessian: H <- optimHess(par, .garchLLH) H <- 0.5 * (H + t(H)) nm <- names(par) dimnames(H) <- list(nm, nm) # Elapsed Time: time = Sys.time() - .StartHessian attr(H, "time") = time # Return Value: H } # ------------------------------------------------------------------------------ .garchRCDAHessian <- function(par, .params, .series, eps = 1.0e-4) { # A function implemented by Diethelm Wuertz # Description: # Compute CDA (central difference approximated) Hessian # Arguments: # par - # .params - # .series - # eps - # Reference: # http://status.sph.umich.edu/computing/manuals/sas8/stat/chap46/sect26.htm # FUNCTION: # Take start time .StartHessian <- Sys.time() # Algorithm: algorithm = .params$control$algorithm[1] .trace = FALSE # Compute Hessian: eps = eps * par n = length(par) H = matrix(0, ncol = n, nrow = n) for (i in 1:n) { for (j in 1:n) { x1 = x2 = x3 = x4 = par x1[i] = x1[i] + eps[i] x1[j] = x1[j] + eps[j] x2[i] = x2[i] + eps[i] x2[j] = x2[j] - eps[j] x3[i] = x3[i] - eps[i] x3[j] = x3[j] + eps[j] x4[i] = x4[i] - eps[i] x4[j] = x4[j] - eps[j] H[i, j] = ( .garchLLH(x1, .trace) - .garchLLH(x2, .trace) - .garchLLH(x3, .trace) + .garchLLH(x4, .trace) ) / (4*eps[i]*eps[j]) } } colnames(H) = rownames(H) = names(par) # Attribute execution time: time = Sys.time() - .StartHessian attr(H, "time") = time # Return Value: H } # ------------------------------------------------------------------------------ .garchTSHessian <- function(par, .params, .series, eps = NA) { # A function implemented by Diethelm Wuertz # Description: # Compute two sided (TS) approximated Hessian # Arguments: # par - # .params - # .series - # eps - not used # FUNCTION: # Take start time .StartHessian <- Sys.time() # Algorithm: algorithm = .params$control$algorithm[1] # Compute Hessian: H <- .hessian2sided(f = .garchLLH, x = par, trace = FALSE, fGarchEnv = FALSE) colnames(H) = rownames(H) = names(par) # Attribute execution time: time = Sys.time() - .StartHessian attr(H, "time") = time # Return Value: H } # ------------------------------------------------------------------------------ .hessian2sided <- function(f, x, ...) { # A function adapted from Kevin Sheppard's Matlab garch toolbox # ... implemented by Alexios Ghalanos in his rgarch package # ... R port for Rmetrics' fGarch by Diethelm Wuertz # Description: # Computes two sided (TS) approximated Hessian # Arguments: # f - # x - # Notes: # requires package Matrix (added as suggestion) # FUNCTION: # Settings: n <- length(x) fx <- f(x, ...) eps <- .Machine$double.eps # Compute the stepsize (h) h = eps^(1/3) * apply( as.data.frame(x), 1, FUN = function(z) max(abs(z), 1.0e-2)) xh = x + h h = xh - x ee <- Matrix(diag(h), sparse = TRUE) # Compute forward and backward steps: gm <- gp <- numeric(n) for(i in 1:n) { e.i <- ee[,i] gp[i] <- f(x + e.i, ...) gm[i] <- f(x - e.i, ...) } H = h %*% t(h) Hm = H Hp = H # Compute "double" forward and backward steps: for(i in 1:n){ ## FIXME (speedup!) -- vectorize or even work with FULL n x n matrices H, Hp, Hm e.i <- ee[,i] for(j in i:n){ e.j <- ee[,j] Hp[j, i] <- Hp[i, j] <- f(x + e.i + e.j, ...) Hm[j, i] <- Hm[i, j] <- f(x - e.i - e.j, ...) } } # Compute the hessian: for(i in 1:n) { ## FIXME (speedup!) -- vectorize or even work with FULL n x n matrices H, Hp, Hm for(j in i:n) { ## 1 <= i <= j <= n H[j, i] = H[i, j] = .5* ((Hp[i, j] - gp[i] - gp[j] + fx + fx - gm[i] - gm[j] + Hm[i, j]) / H[i, j]) } } # Return the Hessian matrix: H } fGarch/R/garch-SolverControl.R0000755000176200001440000000745714263246022015706 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ############################################################################## # FUNCTION: DESCRIPTION: # garchFitControl Sets default values for Garch Optimizer ############################################################################## garchFitControl <- function( llh = c("filter", "internal", "testing"), nlminb.eval.max = 2000, nlminb.iter.max = 1500, nlminb.abs.tol = 1.0e-20, nlminb.rel.tol = 1.0e-14, nlminb.x.tol = 1.0e-14, nlminb.step.min = 2.2e-14, nlminb.scale = 1, nlminb.fscale = FALSE, nlminb.xscale = FALSE, sqp.mit = 200, sqp.mfv = 500, sqp.met = 2, sqp.mec = 2, sqp.mer = 1, sqp.mes = 4, sqp.xmax = 1.0e3, sqp.tolx = 1.0e-16, sqp.tolc = 1.0e-6, sqp.tolg = 1.0e-6, sqp.told = 1.0e-6, sqp.tols = 1.0e-4, sqp.rpf = 1.0e-4, lbfgsb.REPORT = 10, lbfgsb.lmm = 20, lbfgsb.pgtol = 1e-14, lbfgsb.factr = 1, lbfgsb.fnscale = FALSE, lbfgsb.parscale = FALSE, nm.ndeps = 1e-14, nm.maxit = 10000, nm.abstol = 1e-14, nm.reltol = 1e-14, nm.alpha = 1.0, nm.beta = 0.5, nm.gamma = 2.0, nm.fnscale = FALSE, nm.parscale = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Sets default values for Garch Optimizer # FUNCTION: # Generate Control List with Default Settings: control <- list( llh = llh, nlminb.eval.max = nlminb.eval.max, nlminb.iter.max = nlminb.iter.max, nlminb.abs.tol = nlminb.abs.tol, nlminb.rel.tol = nlminb.rel.tol, nlminb.x.tol = nlminb.x.tol, nlminb.step.min = nlminb.step.min, nlminb.scale = nlminb.scale, nlminb.fscale = nlminb.fscale, nlminb.xscale = nlminb.xscale, sqp.mit = sqp.mit, sqp.mfv = sqp.mfv, sqp.met = sqp.met, sqp.mec = sqp.mec, sqp.mer = sqp.mer, sqp.mes = sqp.mes, sqp.xmax = sqp.xmax, sqp.tolx = sqp.tolx, sqp.tolc = sqp.tolc, sqp.tolg = sqp.tolg, sqp.told = sqp.told, sqp.tols = sqp.tols, sqp.rpf = sqp.rpf, lbfgsb.REPORT = lbfgsb.REPORT, lbfgsb.lmm = lbfgsb.lmm, lbfgsb.pgtol = lbfgsb.pgtol, lbfgsb.factr = lbfgsb.factr, lbfgsb.fnscale = lbfgsb.fnscale, lbfgsb.parscale = lbfgsb.parscale, nm.ndeps = nm.ndeps, nm.maxit = nm.maxit, nm.abstol = nm.abstol, nm.reltol = nm.reltol, nm.alpha = nm.alpha, nm.beta = nm.beta, nm.gamma = nm.gamma, nm.fnscale = nm.fnscale, nm.parscale = nm.parscale ) # Return Value: control } ################################################################################ fGarch/R/dist-std.R0000755000176200001440000000604714263246022013536 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # dstd Density for the Student-t Distribution # pstd Probability function for the Student-t Distribution # qstd Quantile function for the Student-t Distribution # rstd Random Number Generator for the Student-t ################################################################################ dstd <- function(x, mean = 0, sd = 1, nu = 5, log = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Compute the density for the # Student-t distribution. # FUNCTION: # Params: if (length(mean) == 3) { nu = mean[3] sd = mean[2] mean = mean[1] } # Compute Density: s = sqrt(nu/(nu-2)) z = (x - mean) / sd result = dt(x = z*s, df = nu) * s / sd # Log: if(log) result = log(result) # Return Value: result } # ------------------------------------------------------------------------------ pstd <- function (q, mean = 0, sd = 1, nu = 5) { # A function implemented by Diethelm Wuertz # Description: # Compute the probability for the # Student-t distribution. # FUNCTION: # Compute Probability: s = sqrt(nu/(nu-2)) z = (q - mean) / sd result = pt(q = z*s, df = nu) # Return Value: result } # ------------------------------------------------------------------------------ qstd <- function (p, mean = 0, sd = 1, nu = 5) { # A function implemented by Diethelm Wuertz # Description: # Compute the quantiles for the # Student-t distribution. # FUNCTION: # Compute Quantiles: s = sqrt(nu/(nu-2)) result = qt(p = p, df = nu) * sd / s + mean # Return Value: result } # ------------------------------------------------------------------------------ rstd <- function(n, mean = 0, sd = 1, nu = 5) { # A function implemented by Diethelm Wuertz # Description: # Generate random deviates from the # Student-t distribution. # FUNCTION: # Generate Random Deviates: s = sqrt(nu/(nu-2)) result = rt(n = n, df = nu) * sd / s + mean # Return Value: result } ################################################################################ fGarch/R/garch-GlobalVars.R0000755000176200001440000000274114263246022015116 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .setfGarchEnv Set Global Vars # .garchArgsParser Parses formula and data for garchFit # .garchOptimizerControl Sets default values for Garch Optimizer # .garchFit ... old Version, still in use by garchFit() # .garchNames Slot names, @fit slot, parameters and controls ################################################################################ .setfGarchEnv(.llh = 1e99) .setfGarchEnv(.garchDist = NA) .setfGarchEnv(.params = NA) .setfGarchEnv(.series = NA) .setfGarchEnv(.trace = NA) ################################################################################ fGarch/R/dist-gedSlider.R0000755000176200001440000000661514263246022014647 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # gedSlider Displays Generalized Error Distribution and RVS ################################################################################ gedSlider <- function(type = c("dist", "rand")) { # A function implemented by Diethelm Wuertz # Description: # Displays interactively skew GED distribution # Note: # dged(x, mean = 0, sd = 1, nu = 5) # FUNCTION: # Internal Function: refresh.code = function(...) { # Sliders: N = .sliderMenu(no = 1) mean = .sliderMenu(no = 2) sd = .sliderMenu(no = 3) nu = .sliderMenu(no = 4) # Compute Data: xmin = round(qged(0.01, mean, sd, nu), digits = 2) xmax = round(qged(0.99, mean, sd, nu), digits = 2) s = seq(xmin, xmax, length = N) y1 = dged(s, mean, sd, nu) y2 = pged(s, mean, sd, nu) main1 = paste("GED Density\n", "mean = ", as.character(mean), " | ", "sd = ", as.character(sd), " | ", "nu = ", as.character(nu) ) main2 = paste("GED Probability\n", "xmin [0.01] = ", as.character(xmin), " | ", "xmax [0.99] = ", as.character(xmax) ) # Random Numbers: if (type[1] == "rand") { x = rged(N, mean, sd, nu) } # Frame: par(mfrow = c(2, 1), cex = 0.7) # Density: if (type[1] == "rand") { hist(x, probability = TRUE, col = "steelblue", border = "white", breaks = "FD", xlim = c(xmin, xmax), ylim = c(0, 1.1*max(y1)), main = main1 ) lines(s, y1, col = "orange") } else { plot(s, y1, type = "l", xlim = c(xmin, xmax), col = "steelblue") abline (h = 0, lty = 3) title(main = main1) grid() } # Probability: plot(s, y2, type = "l", xlim = c(xmin, xmax), ylim = c(0, 1), col = "steelblue" ) abline (h = 0, lty = 3) title(main = main2) grid() # Frame: par(mfrow = c(1, 1), cex = 0.7) } # Open Slider Menu: .sliderMenu(refresh.code, names = c( "N", "mean", "sd", "nu"), minima = c( 10, -5.0, 0.1, 2.1), maxima = c( 1000, +5.0, 5.0, 10.0), resolutions = c( 10, 0.1, 0.1, 0.1), starts = c( 100, 0.0, 1.0, 5.0) ) } ################################################################################ fGarch/R/cvar-VaR.R0000644000176200001440000000253114556274203013422 0ustar liggesusers## GNB TODO: this is to get thing going qfun_fGarch <- function(dist, parameters){ skew <- parameters["skew"] shape <- parameters["shape"] switch(dist, norm = qnorm, snorm = function(p, ...) qsnorm(p, xi = skew, ...), # TODO: do we need '...'? ged = function(p, ...) qged(p, nu = shape, ...), sged = function(p, ...) qsged(p, nu = shape, xi = skew, ...), std = function(p, ...) qstd(p, nu = shape, ...), sstd = function(p, ...) qsstd(p, nu = shape, xi = skew, ...), snig = function(p, ...) qsnig(p, zeta = shape, rho = skew, ...), ## default stop("distribution 'dist' not implemented here") ) } VaR.fGARCH <- function(dist, p_loss = 0.05, ..., tol = .Machine$double.eps^0.5) { stopifnot(inherits(dist, "fGARCH")) mu_t <- dist@fitted sigma_t <- dist@sigma.t cond_dist <- dist@fit$params$cond.dist qf <- qfun_fGarch(cond_dist, coef(dist)) cvar::VaR_qf(qf, p_loss, intercept = mu_t, slope = sigma_t, tol = tol) } ES.fGARCH <- function (dist, p_loss = 0.05, ...) { stopifnot(inherits(dist, "fGARCH")) mu_t <- dist@fitted sigma_t <- dist@sigma.t cond_dist <- dist@fit$params$cond.dist qf <- qfun_fGarch(cond_dist, coef(dist)) cvar::ES(qf, p_loss, intercept = mu_t, slope = sigma_t) } fGarch/R/dist-sstdFit.R0000755000176200001440000001043614263246022014361 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # sstdFit Fit the parameters for a skew Sudent-t distribution ################################################################################ .sstdFit <- function(x, mean = 0, sd = 1, xi = 1.5, scale = NA, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE, title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description: # Fits parameters of a Skew Student-t using maximum log-likelihood # Example: # set.seed(4711); x = rsnorm(500); .snormFit(x)@fit$estimate # FUNCTION: # Settings: dist = dsstd model = "SSTD Parameter Estimation" scale = "not used" x = x.orig = as.vector(x) # Parameter Estimation: obj = function(x, y = x, trace) { f <- tryCatch(-sum(log(dist(y, x[1], x[2], x[3], x[4]))), error=identity) if (is.na(f) || inherits(f, "error")) return(1e9) # Print Iteration Path: if (trace) { cat("\n Objective Function Value: ", -f) cat("\n Parameter Estimates: ", x, "\n") } f } r = nlminb( start = c(mean = 0, sd = 1, nu = 5, xi = 1.5), objective = obj, lower = c(-Inf, 0, 2, 0), upper = c( Inf, Inf, Inf, Inf), y = x, trace = trace) names(r$par) <- c("mean", "sd", "nu", "xi") # Add Title and Description: if (is.null(title)) title = model if (is.null(description)) description = description() # Result: fit = list(estimate = r$par, minimum = -r$objective, code = r$convergence) # Optional Plot: if (doplot) { x = as.vector(x.orig) if (span == "auto") span = seq(min(x), max(x), length = 501) z = density(x, n = 100, ...) x = z$x[z$y > 0] y = z$y[z$y > 0] y.points = dist(span, r$par[1], r$par[2], r$par[3], r$par[4]) ylim = log(c(min(y.points), max(y.points))) if (add) { lines(x = span, y = log(y.points), col = "steelblue") } else { plot(x, log(y), xlim = c(span[1], span[length(span)]), ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...) title(main = model) lines(x = span, y = log(y.points), col = "steelblue") } } # Return Value: new("fDISTFIT", call = match.call(), model = model, data = as.data.frame(x.orig), fit = fit, title = title, description = description() ) } # ------------------------------------------------------------------------------ sstdFit <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Fit the parameters for a skew Sudent-t distribution # with unit variance # FUNCTION: # For S-Plus compatibility: if (!exists("nlm")) nlm = function (f, p, ...) nlminb(start = p, objective = f, ...) # Start Value: p = c(mean = mean(x), sd = sqrt(var(x)), nu = 4, xi = 1) # Log-likelihood Function: loglik = function(x, y = x){ f = -sum(log(dsstd(y, x[1], x[2], x[3], x[4]))) f } # Minimization: fit = nlm( f = loglik, p = p, y = x, ...) Names = c("mean", "sd", "nu", "xi") names(fit$estimate) = Names names(fit$gradient) = Names # Return Value: fit } ################################################################################# ------------------------------------------------------------------------------ fGarch/R/dist-stdFit.R0000755000176200001440000001003114263246022014165 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # stdFit Fit the parameters for a Sudent-t distribution ################################################################################ .stdFit <- function(x, mean = 0, sd = 1, xi = 1.5, scale = NA, doplot = TRUE, add = FALSE, span = "auto", trace = TRUE, title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description: # Fits parameters of a Student-t using maximum log-likelihood # Example: # set.seed(4711); x = rstd(500); .stdFit(x)@fit$estimate # FUNCTION: # Settings: dist = dstd model = "STD Parameter Estimation" scale = "not used" x = x.orig = as.vector(x) # Parameter Estimation: obj = function(x, y = x, trace) { f <- tryCatch(-sum(log(dist(y, x[1], x[2], x[3]))), error=identity) if (is.na(f) || inherits(f, "error")) return(1e9) # Print Iteration Path: if (trace) { cat("\n Objective Function Value: ", -f) cat("\n Parameter Estimates: ", x, "\n") } f } r = nlminb( start = c(mean = 0, sd = 1, nu = 5), objective = obj, lower = c(-Inf, 0, 2), upper = c( Inf, Inf, Inf), y = x, trace = trace) names(r$par) <- c("mean", "sd", "nu") # Add Title and Description: if (is.null(title)) title = model if (is.null(description)) description = description() # Result: fit = list(estimate = r$par, minimum = -r$objective, code = r$convergence) # Optional Plot: if (doplot) { x = as.vector(x.orig) if (span == "auto") span = seq(min(x), max(x), length = 501) z = density(x, n = 100, ...) x = z$x[z$y > 0] y = z$y[z$y > 0] y.points = dstd(span, r$par[1], r$par[2], r$par[3]) ylim = log(c(min(y.points), max(y.points))) if (add) { lines(x = span, y = log(y.points), col = "steelblue") } else { plot(x, log(y), xlim = c(span[1], span[length(span)]), ylim = ylim, type = "p", xlab = "x", ylab = "log f(x)", ...) title(main = model) lines(x = span, y = log(y.points), col = "steelblue") } } # Return Value: new("fDISTFIT", call = match.call(), model = model, data = as.data.frame(x.orig), fit = fit, title = title, description = description() ) } # ------------------------------------------------------------------------------ stdFit <- function(x, ...) { # A function implemented by Diethelm Wuertz # Description: # Fit the parameters for a skew Normal distribution # FUNCTION: # Start Value: start = c(mean = mean(x), sd = sqrt(var(x)), nu = 4) # Log-likelihood Function: loglik = function(x, y = x){ f = -sum(log(dstd(y, x[1], x[2], x[3]))) f } # Minimization: fit = nlminb( start = start, objective = loglik, lower = c(-Inf, 0, 2), upper = c(Inf, Inf, Inf), y = x, ...) # Add Names to $par names(fit$par) = c("mean", "sd", "nu") # Return Value: fit } ################################################################################ fGarch/R/garch-Initialization.R0000755000176200001440000002575514263246022016063 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .garchInitSeries Initializes Series # .garchInitParameters Initializes Parameters ################################################################################ .garchInitSeries <- function(formula.mean, formula.var, cond.dist, series, scale, init.rec, h.start, llh.start, trace) { # A function implemented by Diethelm Wuertz # Description: # Initialize time series # Arguments: # see function garchFit() # FUNCTION: # Check Mean Formula ARMA - Is it Valid ? mm = length(formula.mean) if(mm != 2) stop("Mean Formula misspecified") end = regexpr("\\(", as.character(formula.mean[mm])) - 1 model.mean = substr(as.character(formula.mean[mm]), 1, end) if(!any( c("ar", "ma", "arma") == model.mean)) stop("formula.mean must be one of: ar, ma, arma") # Check Variance Formula GARCH - Is it Valid ? mv = length(formula.var) if(mv != 2) stop("Variance Formula misspecified") end = regexpr("\\(", as.character(formula.var[mv])) - 1 model.var = substr(as.character(formula.var[mv]), 1, end) if(!any( c("garch", "aparch") == model.var)) stop("formula.var must be one of: garch, aparch") # Determine Mean Order from ARMA Formula: model.order = as.numeric(strsplit(strsplit(strsplit(as.character( formula.mean), "\\(")[[2]][2], "\\)")[[1]], ",")[[1]]) u = model.order[1] v = 0 if(length(model.order) == 2) v = model.order[2] maxuv = max(u, v) if(u < 0 | v < 0) stop("*** ARMA orders must be positive.") # Determine Variance Order from GARCH Formula: model.order = as.numeric(strsplit(strsplit(strsplit(as.character( formula.var), "\\(")[[2]][2], "\\)")[[1]], ",")[[1]]) p = model.order[1] q = 0 if(length(model.order) == 2) q = model.order[2] if(p+q == 0) stop("Misspecified GARCH Model: Both Orders are zero!") maxpq = max(p, q) if(p < 0 | q < 0) stop("*** GARCH orders must be positive.") # Fix Start Position of Series "h" and for Likelihood Calculation: max.order = max(maxuv, maxpq) if(is.null(h.start)) h.start = max.order + 1 if(is.null(llh.start)) llh.start = 1 # Check for Recursion Initialization: if(init.rec != "mci" & model.var != "garch") { stop("Algorithm only supported for mci Recursion") } # Trace the Result: if(trace) { cat("\nSeries Initialization:") cat("\n ARMA Model: ", model.mean) cat("\n Formula Mean: ", as.character(formula.mean)) cat("\n GARCH Model: ", model.var) cat("\n Formula Variance: ", as.character(formula.var)) cat("\n ARMA Order: ", u, v) cat("\n Max ARMA Order: ", maxuv) cat("\n GARCH Order: ", p, q) cat("\n Max GARCH Order: ", maxpq) cat("\n Maximum Order: ", max.order) cat("\n Conditional Dist: ", cond.dist) cat("\n h.start: ", h.start) cat("\n llh.start: ", llh.start) cat("\n Length of Series: ", length(series)) cat("\n Recursion Init: ", init.rec) cat("\n Series Scale: ", scale) cat("\n\n") } # Result: ans = list( model = c(model.mean, model.var), order = c(u = u, v = v, p = p, q = q), max.order = max.order, z = rep(0, times = length(series)), h = rep(var(series), times = length(series)), x = series, scale = scale, init.rec = init.rec, h.start = h.start, llh.start = llh.start) # Return Value: ans } # ------------------------------------------------------------------------------ .garchInitParameters <- function(formula.mean, formula.var, delta, skew, shape, cond.dist, include.mean, include.delta, include.skew, include.shape, leverage, algorithm, control, trace) { # A function implemented by Diethelm Wuertz # Description: # Initialize model parameters # Arguments: # see function garchFit() # FUNCTION: # DEBUG: .DEBUG = FALSE # global variables .series <- .getfGarchEnv(".series") # Determine Mean Order from ARMA Formula: model.order = as.numeric(strsplit(strsplit(strsplit(as.character( formula.mean), "\\(")[[2]][2], "\\)")[[1]], ",")[[1]]) u = model.order[1] v = 0 if(length(model.order) == 2) v = model.order[2] # Determine Variance Order from GARCH Formula: model.order = as.numeric(strsplit(strsplit(strsplit(as.character( formula.var), "\\(")[[2]][2], "\\)")[[1]], ",")[[1]]) p = model.order[1] if (p == 0) stop("The order p must be > 0 in GARCH/APARCH(p,q)") q = 0 if(length(model.order) == 2) q = model.order[2] # Includes: model.var = .series$model[2] if(is.null(include.delta)) { if(model.var == "garch") { include.delta = FALSE } else { include.delta = TRUE } } if(is.null(leverage)) { if(model.var == "garch") { leverage = FALSE } else { leverage = TRUE } } # Distributional Includes: if(cond.dist == "t") cond.dist = "std" skewed.dists = c("snorm", "sged", "sstd", "snig") if(is.null(include.skew)) { if(any(skewed.dists == cond.dist)) { include.skew = TRUE } else { include.skew = FALSE } } shaped.dists = c("ged", "sged", "std", "sstd", "snig") if(is.null(include.shape)) { if(any(shaped.dists == cond.dist)) { include.shape = TRUE } else { include.shape = FALSE } } # Set Names for Parameters: Names = c( "mu", if(u > 0) paste("ar", 1:u, sep = ""), if(v > 0) paste("ma", 1:v, sep = ""), "omega", if(p > 0) paste("alpha", 1:p, sep = ""), if(p > 0) paste("gamma", 1:p, sep = ""), if(q > 0) paste("beta", 1:q, sep = ""), "delta", "skew", "shape") if(.DEBUG) { cat("\nDEBUG - Names: \n"); print(Names) } # Initialize Model Parameters to be Estimated: fit.mean = arima(.series$x, order = c(u, 0, v), include.mean = include.mean)$coef alpha.start = 0.1 beta.start = 0.8 ## if(include.delta) delta = 1.5 params = c( if(include.mean) fit.mean[length(fit.mean)] else 0, if(u > 0) fit.mean[1:u], if(v > 0) fit.mean[(u+1):(length(fit.mean)-as.integer(include.mean))], var(.series$x, na.rm = TRUE)*(1-alpha.start-beta.start), if(p > 0) rep(alpha.start/p, times = p), if(p > 0) rep(0.1, times = p), if(q > 0) rep(beta.start/q, times = q), delta, skew, shape) names(params) = Names if(.DEBUG) { cat("\nDEBUG - params: \n"); print(params) } # Set Lower Limits of Parameters to be Estimated: TINY = 1.0e-8 USKEW = 1/10; USHAPE = 1 if (cond.dist == "snig") USKEW = -0.99 U = c( -10*abs(mean(.series$x)), if(u > 0) rep(-1+TINY, times = u), if(v > 0) rep(-1+TINY, times = v), 1.0e-6*var(.series$x), if(p > 0) rep( 0+TINY, times = p), if(p > 0) rep(-1+TINY, times = p), if(q > 0) rep( 0+TINY, times = q), 0, # delta USKEW, # skew USHAPE) # shape names(U) = Names if(.DEBUG) { cat("\nDEBUG - U: \n"); print(U) } # Set Upper Limits of Parameters to be Estimated: VSKEW = 10; VSHAPE = 10 if (cond.dist == "snig") VSKEW = 0.99 V = c( 10*abs(mean(.series$x)), if(u > 0) rep(1-TINY, times = u), if(v > 0) rep(1-TINY, times = v), 100*var(.series$x), if(p > 0) rep(1-TINY, times = p), if(p > 0) rep(1-TINY, times = p), if(q > 0) rep(1-TINY, times = q), 2, # delta VSKEW, # skew VSHAPE) # shape names(V) = Names if(.DEBUG) { cat("\nDEBUG - V: \n"); print(V) } # Includes: includes = c( include.mean, if(u > 0) rep(TRUE, times = u), if(v > 0) rep(TRUE, times = v), TRUE, if(p > 0) rep(TRUE, times = p), if(p > 0) rep(leverage, times = p), if(q > 0) rep(TRUE, times = q), include.delta, include.skew, include.shape) names(includes) = Names if(.DEBUG) { cat("\nDEBUG - V: \n"); print(includes) } # Index List of Parameters to be Optimized: index = (1:length(params))[includes == TRUE] names(index) = names(params)[includes == TRUE] if(.DEBUG) { cat("\nDEBUG - fixed: \n"); print(index) } # Persistence: alpha <- beta <- NULL if(p > 0) alpha = params[substr(Names, 1, 5) == "alpha"] if(p > 0 & leverage) gamma = params[substr(Names, 1, 5) == "gamma"] if(p > 0 & !leverage) gamma = rep(0, times = p) if(q > 0) beta = params[substr(Names, 1, 4) == "beta"] if(.series$model[2] == "garch") { persistence = sum(alpha) + sum(beta) } else if(.series$model[2] == "aparch") { persistence = sum(beta) for (i in 1:p) persistence = persistence + alpha[i]*garchKappa(cond.dist, gamma[i], params["delta"], params["skew"], params["shape"]) } names(persistence) = "persistence" # Trace the Result: if(trace) { cat("Parameter Initialization:") cat("\n Initial Parameters: $params") cat("\n Limits of Transformations: $U, $V") cat("\n Which Parameters are Fixed? $includes") cat("\n Parameter Matrix:\n") ans = data.frame(U, V, params, includes) rownames(ans) = paste(" ", names(params)) print(ans) cat(" Index List of Parameters to be Optimized:\n") print(index) cat(" Persistence: ", persistence, "\n") } # Return Value: list(params = params, U = U, V = V, includes = includes, index = index, mu = params[1], delta = delta, skew = skew, shape = shape, cond.dist = cond.dist, leverage = leverage, persistence = persistence, control = control) } ################################################################################ fGarch/R/methods-fitted.R0000755000176200001440000000625214437602103014720 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # METHOD: EXTRACTORS: # fitted.fGARCH S3 fitted values for an object of class 'fGARCH' ################################################################################ setMethod(f = "fitted", signature(object = "fGARCH"), definition = function(object) { # A function implemented by Diethelm Wuertz # Description: # S3 Fitted values method for an object of class fGARCH # Arguments: # object - an object of class fGarch as returned by the function # garchFit # FUNCTION: ## GNB: this was the previous code (before v4022.90). Clearly, it assumes ## that 'data' is from class \code{"timeSeries"} and, to return an ## object from the same class, gets 'data' and replaces the data values ## with the fitted ones. ... Except that it doesn't do the latter, so ## returns the data! ## ## # Get numeric vector of fitted, optionally standardized ## fitted = object@fitted ## ## Get original time series class: (!! GNB: Nope, slot 'data' is numeric!) ## ans = slot(object, "data") ## Name = as.character(object@formula[2]) ## attr(ans, "Name") <- Name ## # Return Value: ## ans ## ## GNB: the following code is in the spirit of the above, assuming that ## 'ans' is indeed the original time series. For example (todo?) this ## could be achieved if garchFit sets object@fit$data to the original ## time series, using 'ans <- object@fit$data'. Changing the class of ## slot 'data' instead doesn't seem practical. ## ## fitted <- object@fitted ## if(is(ans, "timeSeries")){ ## Name <- as.character(object@formula[2]) ## attr(ans, "Name") <- Name ## ans@.Data <- if(is.matrix(fitted)) fitted else matrix(fitted, ncol = 1) ## } else if(inherits(ans, "ts") || is.numeric(ans)) { ## ans[] <- fitted ## } else { ## message(paste0("conversion to class '", class(ans), "' not supported yet,\n", ## "returning slot fitted asis.")) ## ans <- fitted ## } ans <- object@fitted # Return Value: ans }) ################################################################################ fGarch/R/dist-snorm.R0000755000176200001440000002136214332476411014103 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # dsnorm Density for the skew normal Distribution # psnorm Probability function for the skew NORM # qsnorm Quantile function for the skew NORM # rsnorm Random Number Generator for the skew NORM # FUNCTION: DESCRIPTION: # .dsnorm Internal, density for the skew normal Distribution # .psnorm Internal, probability function for the skew NORM # .qsnorm Internal, quantile function for the skew NORM # .rsnorm Internal, random Number Generator for the skew NORM ################################################################################ dsnorm <- function(x, mean = 0, sd = 1, xi = 1.5, log = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Compute the density function of the skew normal distribution # Arguments: # x - a numeric vector of quantiles. # mean, sd, xi - location parameter, scale parameter, and # skewness parameter. # FUNCTION: # Params: if (length(mean) == 3) { xi = mean[3] sd = mean[2] mean = mean[1] } # Shift and Scale: result = .dsnorm(x = (x-mean)/sd, xi = xi) / sd # Log: if(log) result = log(result) # Return Value: result } # ------------------------------------------------------------------------------ psnorm <- function(q, mean = 0, sd = 1, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Compute the distribution function of the # skew normal distribution # Arguments: # q - a numeric vector of quantiles. # mean, sd, xi - location parameter, scale parameter, and # skewness parameter. # FUNCTION: # Shift and Scale: result = .psnorm(q = (q-mean)/sd, xi = xi) # Return Value: result } # ------------------------------------------------------------------------------ qsnorm <- function(p, mean = 0, sd = 1, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Compute the quantile function of the # skew normal distribution # Arguments: # p - a numeric vector of probabilities. # mean, sd, xi - location parameter, scale parameter, and # skewness parameter. # FUNCTION: # Shift and Scale: result = .qsnorm(p = p, xi = xi) * sd + mean # Return Value: result } # ------------------------------------------------------------------------------ rsnorm <- function(n, mean = 0, sd = 1, xi = 1.5) { # A function implemented by Diethelm Wuertz # Description: # Generate random deviates from the # skew normal distribution # Arguments: # n - an integer value giving the number of observation. # mean, sd, xi - location parameter, scale parameter, and # skewness parameter. # FUNCTION: # Shift and Scale: result = .rsnorm(n = n, xi = xi) * sd + mean # Return Value: result } ################################################################################ .dsnorm <- function(x, xi) { # A function implemented by Diethelm Wuertz # Description: # Compute the density function of the "normalized" skew # normal distribution # FUNCTION: # Standardize: m1 = 2/sqrt(2*pi) mu = m1 * (xi - 1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) z = x*sigma + mu # Compute: Xi = xi^sign(z) g = 2 / (xi + 1/xi) Density = g * dnorm(x = z/Xi) # Return Value: Density * sigma } # ------------------------------------------------------------------------------ .psnorm <- function(q, xi) { # A function implemented by Diethelm Wuertz ## ## fixed by GNB, see section 'CHANGES in fGarch VERSION 4021.87, 2022-08-06', subsection ## 'BUG fixes' in NEWS.Rd. # Description: # Internal Function # FUNCTION: # Standardize: m1 = 2/sqrt(2*pi) mu = m1 * (xi - 1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) z = q*sigma + mu # Compute: sig <- ifelse(z >= 0, 1, -1) # note: 1 for z = 0; was sign(z) Xi = xi^sig # not sign(z) g = 2 / (xi + 1/xi) ## was: Probability = Heaviside(z) - sig * g * Xi * pnorm(q = -abs(z)/Xi) Probability = ifelse(z >= 0, 1, 0) - sig * g * Xi * pnorm(q = -abs(z)/Xi) # Return Value: Probability } .qsnorm <- function(p, xi) { ## A function implemented by Diethelm Wuertz ## ## Corrected at the centre part by Georgi N. Boshnakov on 2022-07-27 to fix ## bug [#6061], see section 'CHANGES in fGarch VERSION 4021.87, 2022-08-06', ## subsection 'BUG fixes' in NEWS.Rd. ## ## The old version of this and similar functions were temporarilly kept with ## suffix '_orig' but removed after the release of 4022.89, due to lack of ## (reported) problems with the fix. The examples below are kept for reference. ## ## ## Compare ## plot(function(p) .qsnorm(p, xi = 1.5), from = 0, to = 1) ## plot(function(p) .qsnorm_orig(p, xi = 1.5), from = 0, to = 1, ## col = "blue", add = TRUE) ## ## Create a quantile function by numerically inverting psnorm: ## f <- function(x, ...){ sapply(x, function(p) ## gbutils::cdf2quantile(p, cdf = psnorm, ...))} ## It agrees with the fixed qsnorm (the 2nd is right over the first, 3rd is the orig.): ## plot(function(p) .qsnorm(p, xi = 1.5), from = 0.49, to = 0.51) ## plot(f, from = 0.49, to = 0.51, add = TRUE, col = "red") ## plot(function(p) .qsnorm_orig(p, xi = 1.5), from = 0.49, to = 0.51, add = TRUE) ## ## plot(function(p) .qsnorm(p, xi = 1.5), from = 0, to = 1) ## plot(f, from = 0, to = 1, add = TRUE, col = "red") ## plot(function(p) .qsnorm_orig(p, xi = 1.5), from = 0, to = 1, add = TRUE) ## Description: ## Internal Function ## FUNCTION: ## Standardize: m1 = 2/sqrt(2*pi) mu = m1 * (xi - 1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) ## Compute: g = 2 / (xi + 1/xi) pxi <- p - (1 / (1 + xi^2)) # not p - 1/2 sig <- sign(pxi) # not p - 1/2 Xi = xi^sig p = (Heaviside(pxi) - sig * p) / (g * Xi) # pxi, not p - 1/2 ## GNB: ## Fixed: BUG [#6061] fGarch::qsnorm() incorrect around p=0.5 ## ## This has, in general, discontinuity for p = 1/2, since then sig = 0. ## Note that the original p = 1/2 is transformed above to 1/(2*g*Xi), ## so qnorm() doesn't necessarilly give 1/2 when p = 1/2. ## ## Note also that p can be a vector. ## ## Further note: the issue at p = 0.5 is a separate problem. Zooming in ## shows that the quantile is not continuous at p = 0.5 and to the right of ## 0.5 the values are smaller than just to the left of 0.5 up to around 0.51. ## ## SOLUTION(?): The error seems to be that sign() and Heaviside should compare to ## 1/(1+1/xi^2), not 0.5 which is correct only for xi = 1. ## Quantile = (-sig * qnorm(p = p, sd = Xi) - mu ) / sigma ## Return Value: Quantile } # ------------------------------------------------------------------------------ .rsnorm <- function(n, xi) { # A function implemented by Diethelm Wuertz # Description: # Internal Function # FUNCTION: # Generate Random Deviates: weight = xi / (xi + 1/xi) z = runif(n, -weight, 1-weight) Xi = xi^sign(z) Random = -abs(rnorm(n))/Xi * sign(z) # Scale: m1 = 2/sqrt(2*pi) mu = m1 * (xi - 1/xi) sigma = sqrt((1-m1^2)*(xi^2+1/xi^2) + 2*m1^2 - 1) Random = (Random - mu ) / sigma # Return value: Random } ################################################################################ fGarch/R/loglik.R0000755000176200001440000001703714263246022013265 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # .garchLLH Computes log-likelihood function # .garchOptimizeLLH Opimizes log-likelihood function ################################################################################ .garchLLH <- function(params, trace = TRUE, fGarchEnv = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Compute Log-Likelihood Function # Arguments: # params - a named numeric vector with the model parameters # to be optimized # Value: # Returns the value of the max log-likelihood function. # Note: # The variables '.series' and '.params' must be global available # FUNCTION: # DEBUG: DEBUG = FALSE if (DEBUG) print("Entering Function .garchLLH") # Get Global Variables: .series <- .getfGarchEnv(".series") .params <- .getfGarchEnv(".params") .garchDist <- .getfGarchEnv(".garchDist") .llh <- .getfGarchEnv(".llh") # How to calculate the LLH Function? if (DEBUG) print(.params$control$llh) if(.params$control$llh == "internal") { if (DEBUG) print("internal") return(.aparchLLH.internal(params, trace = trace, fGarchEnv = fGarchEnv)) } else if (.params$control$llh == "filter") { if (DEBUG) print("filter") return(.aparchLLH.filter(params, trace = trace, fGarchEnv = fGarchEnv)) } else if (.params$control$llh == "testing") { if (DEBUG) print("testing") return(.aparchLLH.testing(params, trace = trace, fGarchEnv = fGarchEnv)) } else { stop("LLH is neither internal, testing, nor filter!") } } # ------------------------------------------------------------------------------ ## Called from .garchFit() in ./garch-FitInternal.R -- itself called from garchFit() and .ugarchFit() .garchOptimizeLLH <- function(hessian = hessian, robust.cvar, trace) { # A function implemented by Diethelm Wuertz # Description: # Opimizes the Log-Likelihood Function # Arguments: # hessian - the Hessian matrix # robust.cvar - a logical # trace - a logical # FUNCTION: # DEBUG: DEBUG = FALSE if (DEBUG) print("Entering Function .garchOptimizeLLH") # get global variables .series <- .getfGarchEnv(".series") .params <- .getfGarchEnv(".params") # Initialization: INDEX = .params$index # Algorithm: algorithm = .params$control$algorithm[1] TOL1 = .params$control$tol1 TOL2 = .params$control$tol2 if(trace) { cat("\n\n--- START OF TRACE ---") cat("\nSelected Algorithm:", algorithm, "\n") } # First Method: # Two Step Apparoach > Trust Region + Nelder-Mead Simplex if(algorithm == "nlminb" | algorithm == "nlminb+nm") { fit <- .garchRnlminb(.params, .series, .garchLLH, trace) .params$llh = fit$llh .params$params[INDEX] = fit$par .setfGarchEnv(.params = .params) } if(algorithm == "nlminb+nm") { fit <- .garchRnm(.params, .series, .garchLLH, trace) .params$llh = fit$llh .params$params[INDEX] = fit$par .setfGarchEnv(.params = .params) } # Second Method: # Two Step Approach > BFGS + Nelder-Mead Simplex if(algorithm == "lbfgsb" | algorithm == "lbfgsb+nm") { fit <- .garchRlbfgsb(.params, .series, .garchLLH, trace) .params$llh = fit$llh .params$params[INDEX] = fit$par .setfGarchEnv(.params = .params) } if(algorithm == "lbfgsb+nm") { fit <- .garchRnm(.params, .series, .garchLLH, trace) .params$llh = fit$llh .params$params[INDEX] = fit$par .setfGarchEnv(.params = .params) } # Save parameters: .params$llh = fit$llh .params$params[INDEX] = fit$par .setfGarchEnv(.params = .params) # Compute the Hessian: if (hessian == "ropt") { fit$hessian <- - .garchRoptimhess(par = fit$par, .params = .params, .series = .series) titleHessian = "R-optimhess" } else if (hessian == "rcd") { fit$hessian <- - .garchRCDAHessian(par = fit$par, .params = .params, .series = .series) titleHessian = "Central" } else if (hessian == "rts") { fit$hessian <- - .garchTSHessian(par = fit$par, .params = .params, .series = .series) titleHessian = "Two Sided" } # Rescale Parameters: if (.params$control$xscale) { .series$x <- .series$x * .series$scale if (.params$include["mu"]) fit$coef["mu"] <- fit$par["mu"] <- .params$params["mu"] <- .params$params["mu"]*.series$scale if (.params$include["omega"]) fit$coef["omega"] <- fit$par["omega"] <- .params$params["omega"] <- .params$params["omega"]*.series$scale^(.params$params["delta"]) # save changes .setfGarchEnv(.params = .params) .setfGarchEnv(.series = .series) } # Rescale Hessian Matrix: if (.params$control$xscale) { if (.params$include["mu"]) { fit$hessian[,"mu"] <- fit$hessian[,"mu"] / .series$scale fit$hessian["mu",] <- fit$hessian["mu",] / .series$scale } if (.params$include["omega"]) { fit$hessian[,"omega"] <- fit$hessian[,"omega"] / .series$scale^(.params$params["delta"]) fit$hessian["omega",] <- fit$hessian["omega",] / .series$scale^(.params$params["delta"]) } } # Recalculate llh, h, z with Rescaled Parameters: .llh <- fit$llh <- fit$value <- .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE) .series <- .getfGarchEnv(".series") # Compute the Gradient: # YC: needs to be after the calculation of h, z ! if (robust.cvar) fit$gradient <- - .garchRCDAGradient( par = fit$par, .params = .params, .series = .series) # Compute Information Criterion Statistics: N = length(.series$x) NPAR = length(fit$par) fit$ics = c( AIC = c((2*fit$value)/N + 2 * NPAR/N), BIC = (2*fit$value)/N + NPAR * log(N)/N, SIC = (2*fit$value)/N + log((N+2*NPAR)/N), HQIC = (2*fit$value)/N + (2*NPAR*log(log(N)))/N ) names(fit$ics) <- c("AIC", "BIC", "SIC", "HQIC") # Print LLH if we trace: if(trace) { cat("\nFinal Estimate of the Negative LLH:\n") cat(" LLH: ", .llh, " norm LLH: ", .llh/N, "\n") print(fit$par) } # Print Hessian Matrix if we trace: if(trace) { cat("\n", titleHessian, " Difference Approximated Hessian Matrix:\n", sep = "") print(fit$hessian) cat("\n--- END OF TRACE ---\n\n") } # Return Value: if (DEBUG) print("Entering Function .garchOptimizeLLH") fit } ################################################################################ fGarch/R/garch-Sim.R0000755000176200001440000001142014263246022013604 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: SIMULATION: # garchSim Simulates a GARCH/APARCH process ################################################################################ garchSim <- function(spec = garchSpec(), n = 100, n.start = 100, extended = FALSE) { # A function implemented by Diethelm Wuertz # Description: # Simulates a time series process from the GARCH family # Arguments: # model - a specification object of class 'fGARCHSPEC' as # returned by the function \code{garchSpec}: # ar - a vector of autoregressive coefficients of # length m for the ARMA specification, # ma - a vector of moving average coefficients of # length n for the ARMA specification, # omega - the variance value for GARCH/APARCH # specification, # alpha - a vector of autoregressive coefficients # of length p for the GARCH/APARCH specification, # gamma - a vector of leverage coefficients of # length p for the APARCH specification, # beta - a vector of moving average coefficients of # length q for the GARCH/APARCH specification, # mu - the intercept for ARMA specification (mean=mu/(1-sum(ar))), # delta - the exponent value used in the variance # equation. # skew - a numeric value for the skew parameter. # shape - a numeric value for the shape parameter. # n - an integer, the length of the series # n.start - the length of the warm-up sequence to reduce the # effect of initial conditions. # FUNCTION: # Specification: stopifnot(inherits(spec, "fGARCHSPEC")) model = spec@model # Random Seed: if (spec@rseed != 0) set.seed(spec@rseed) # Enlarge Series: n = n + n.start # Create Innovations: if (spec@distribution == "norm") z = rnorm(n) if (spec@distribution == "ged") z = rged(n, nu = model$shape) if (spec@distribution == "std") z = rstd(n, nu = model$shape) if (spec@distribution == "snorm") z = rsnorm(n, xi = model$skew) if (spec@distribution == "sged") z = rsged(n, nu = model$shape, xi = model$skew) if (spec@distribution == "sstd") z = rsstd(n, nu = model$shape, xi = model$skew) # Expand to whole Sample: delta = model$delta z = c(rev(spec@presample[, 1]), z) h = c(rev(spec@presample[, 2]), rep(NA, times = n)) y = c(rev(spec@presample[, 3]), rep(NA, times = n)) m = length(spec@presample[, 1]) names(z) = names(h) = names(y) = NULL # Determine Coefficients: mu = model$mu ar = model$ar ma = model$ma omega = model$omega alpha = model$alpha gamma = model$gamma beta = model$beta deltainv = 1/delta # Determine Orders: order.ar = length(ar) order.ma = length(ma) order.alpha = length(alpha) order.beta = length(beta) # Iterate GARCH / APARCH Model: eps = h^deltainv*z for (i in (m+1):(n+m)) { h[i] = omega + sum(alpha*(abs(eps[i-(1:order.alpha)]) - gamma*(eps[i-(1:order.alpha)]))^delta) + sum(beta*h[i-(1:order.beta)]) eps[i] = h[i]^deltainv * z[i] y[i] = mu + sum(ar*y[i-(1:order.ar)]) + sum(ma*eps[i-(1:order.ma)]) + eps[i] } # Sample: data = cbind( z = z[(m+1):(n+m)], sigma = h[(m+1):(n+m)]^deltainv, y = y[(m+1):(n+m)]) rownames(data) = as.character(1:n) data = data[-(1:n.start),] # Return Values: from <- timeDate(format(Sys.time(), format = "%Y-%m-%d")) - NROW(data)*24*3600 charvec <- timeSequence(from = from, length.out = NROW(data)) ans <- timeSeries(data = data[, c(3,2,1)], charvec = charvec) colnames(ans) <- c("garch", "sigma", "eps") ans <- if (extended) ans else ans[,"garch"] attr(ans, "control") <- list(garchSpec = spec) # Return Value: ans } ################################################################################ fGarch/R/mgarch-FitFromFormula.R0000755000176200001440000001126314263246022016132 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # .gogarchFit Fits the parameters of a GO-GARCH process ################################################################################ .gogarchFit <- function(formula = ~ garch(1, 1), data, init.rec = c("mci", "uev"), delta = 2, skew = 1, shape = 4, cond.dist = c("norm", "snorm", "ged", "sged", "std", "sstd", "snig", "QMLE"), include.mean = TRUE, include.delta = NULL, include.skew = NULL, include.shape = NULL, leverage = NULL, trace = TRUE, algorithm = c("nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), hessian = c("ropt", "rcd"), control = list(), title = NULL, description = NULL, ...) { # A function implemented by Diethelm Wuertz # Description: # Fits a GO-Garch Model using Independent Component Analysis # Arguments: # The arguments are the same as for the univariate case. # formula - formula for all marginal models # data - multivariate timeSeries object # ... # Value: # S4 Object of class (univariate) fGARCH ... # Notes: # This function has still a preliminary status ... # This function was inspired from the contributed gogarch # package of Bernhard Pfaff. # Example: # require(fEcofin); data(DowJones30) # X = returns(as.timeSeries(DowJones30)); head(X) # N = 5; ans = .gogarchFit(data = X[, 1:N], trace = FALSE); ans # ans@h.t # FUNCTION: # Multivariate ? stopifnot(isMultivariate(data)) # Data: X = data # Marginal Garch Models: garchControl = list( init.rec = init.rec, delta = delta, skew = skew, shape = shape, cond.dist = cond.dist, include.mean = include.mean, include.delta = include.delta, include.skew = include.skew, include.shape = include.shape, leverage = leverage, trace = trace, algorithm = algorithm, hessian = hessian, control = control, title = title, description = description) # Compute fastICA: # ... the following lines of code were borrowed from # Bernhard Pfaff's contributed package gogarch V <- t(X) %*% X / nrow(X) svd <- svd(V) P <- svd$u Dsqr <- diag(sqrt(svd$d)) # set.seed(4711) ica <- fastICA::fastICA(X, n.comp = ncol(X)) Z <- P %*% Dsqr %*% t(P) %*% ica$W colnames(Z) = rownames(Z) = colnames(data) Y <- X %*% solve(Z) # Fit Marginal Garch Models: fit <- apply(Y, 2, function(x) do.call("garchFit", c(list(formula = formula, data = x), garchControl))) # Compute Conditional Variances: # ... the following lines of code were borrowed from # Bernhard Pfaff's contributed package gogarch H <- matrix(unlist(lapply(fit, function(x) x@h.t)), ncol = ncol(X), nrow = nrow(X)) Hdf <- data.frame(t(H)) rownames(Hdf) <- colnames(data) colnames(Hdf) <- rownames(data) H.t <- lapply(Hdf, function(x) Z %*% diag(x) %*% t(Z)) # Add Title and Description: if(is.null(title)) title = "ICA GO-GARCH Modelling" if(is.null(description)) description = description() # Result: ans <- new("fGARCH", call = as.call(match.call()), formula = formula, method = "ICA go-Garch Parmeter Estimation", data = c(Records = nrow(data), Instruments = ncol(data)), fit = fit, residuals = numeric(), fitted = numeric(), h.t = c(Records = length(H.t), Dimension =dim(H.t[[1]])), sigma.t = numeric(), title = title, description = description ) # Multivariate Series: attr(ans@data, "data") <- data attr(ans@h.t, "H.t") <- H.t # Return Value: ans } ################################################################################ fGarch/R/class-fGARCHSPEC.R0000755000176200001440000000242214263246022014544 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: SPECIFICATION: # fGARCHSPEC S4 fGARCHSPEC Class representation ################################################################################ setClass("fGARCHSPEC", representation( call = "call", formula = "formula", model = "list", presample = "matrix", distribution = "character", rseed = "numeric") ) ################################################################################ fGarch/R/methods-formula.R0000755000176200001440000000275514263246022015113 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # formula.fGARCH Extracts 'fGarch' Model formulaficients ################################################################################ setMethod(f = "formula", signature(x = "fGARCH"), definition = function(x) { # A function implemented by Diethelm Wuertz # Description: # Extracts 'fGarch' Model formula # Arguments: # x - an object of class fGarch as returned by the function # garchFit # FUNCTION: # Numeric vector of fitted values: ans = slot(x, "formula") # Return Value: ans }) ################################################################################ fGarch/R/methods-coef.R0000755000176200001440000000414614263246022014356 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # METHOD: EXTRACTORS: # coef.fGARCH Extracts 'fGarch' Model Coefficients ################################################################################ setMethod(f = "coef", signature(object = "fGARCH"), definition = function(object) { # A function implemented by Diethelm Wuertz # Description: # Extracts 'fGarch' Model Coefficients # Arguments: # object - an object of class fGarch as returned by the function # garchFit # FUNCTION: # Numeric vector of fitted values: ans = slot(object, "fit")$coef # Return Value: ans }) # ------------------------------------------------------------------------------ setMethod(f = "coef", signature(object = "fGARCHSPEC"), definition = function(object) { # A function implemented by Diethelm Wuertz # Description: # Extracts 'fGarch' Model Coefficients # Arguments: # object - an object of class fGarch as returned by the function # garchFit # FUNCTION: # Numeric vector of fitted values: ans = unlist(slot(object, "model")) attr(ans, "distribution") <- slot(object, "distribution") # Return Value: ans }) ################################################################################ fGarch/R/dist-stdSlider.R0000755000176200001440000000646614263246022014706 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # stdSlider Displays Variance-1 Student-t Distribution and RVS ################################################################################ stdSlider <- function(type = c("dist", "rand")) { # A function implemented by Diethelm Wuertz # Description: # Displays interactively Student-t distribution # Note: # dstd(x, mean = 0, sd = 1, nu = 5) # FUNCTION: # Internal Function: refresh.code = function(...) { # Sliders: N = .sliderMenu(no = 1) mean = .sliderMenu(no = 2) sd = .sliderMenu(no = 3) nu = .sliderMenu(no = 4) # Compute Data: xmin = round(qstd(0.01, mean, sd, nu), digits = 2) xmax = round(qstd(0.99, mean, sd, nu), digits = 2) s = seq(xmin, xmax, length = N) y1 = dstd(s, mean, sd, nu) y2 = pstd(s, mean, sd, nu) main1 = paste("Student-t Density\n", "mean = ", as.character(mean), " | ", "sd = ", as.character(sd), " | ", "nu = ", as.character(nu)) main2 = paste("Student-t Probability\n", "xmin [0.01] = ", as.character(xmin), " | ", "xmax [0.99] = ", as.character(xmax) ) # Random Numbers: if (type[1] == "rand") { x = rstd(N, mean, sd, nu) } # Frame: par(mfrow = c(2, 1), cex = 0.7) # Density: if (type[1] == "rand") { hist(x, probability = TRUE, col = "steelblue", border = "white", breaks = "FD", xlim = c(xmin, xmax), ylim = c(0, 1.1*max(y1)), main = main1 ) lines(s, y1, col = "orange") } else { plot(s, y1, type = "l", xlim = c(xmin, xmax), col = "steelblue") abline (h = 0, lty = 3) title(main = main1) grid() } # Probability: plot(s, y2, type = "l", xlim = c(xmin, xmax), ylim = c(0, 1), col = "steelblue" ) abline (h = 0, lty = 3) title(main = main2) grid() # Frame: par(mfrow = c(1, 1), cex = 0.7) } # Open Slider Menu: .sliderMenu(refresh.code, names = c( "N", "mean", "sd", "nu"), minima = c( 10, -5.0, 0.1, 2.1), maxima = c( 500, +5.0, 5.0, 10.0), resolutions = c( 10, 0.1, 0.1, 0.1), starts = c( 100, 0.0, 1.0, 5.0) ) } ################################################################################ fGarch/R/methods-show.R0000755000176200001440000001311014441056437014420 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # show.fGARCH S4 Show method for an object of class 'fGARCH' # show.fGARCHSPEC S4 Show method for an object of class 'fGARCHSPEC' ################################################################################ .show_orig_body <- function(object) { ## A function implemented by Diethelm Wuertz # Description: # Print method for an object of class "fGARCH" # Arguments: # object - an object of class 'fGARCH' # FUNCTION: # Title: cat("\nTitle:\n ") cat(object@title, "\n") # Call: cat("\nCall:\n ") cat(paste(deparse(object@call), sep = "\n", collapse = "\n"), "\n") # Mean and Variance Equation: cat("\nMean and Variance Equation:\n ") Name = unclass(attr(object@formula, "data")) Formula = object@formula attr(Formula, "data") <- NULL print(Formula) cat(" [", Name, "]\n", sep = "") # Univariate or Multivariate Modeling ? if (as.character(object@call[1]) == ".gogarchFit") { # For multivariate Garch Models ... # extract information from first fitted instrument. object@fit[[1]]@fit$params$cond.dist # Conditional Distribution: cat("\nConditional Distribution:\n ") cat(object@fit[[1]]@fit$params$cond.dist, "\n") # Number of Margins: cat("\nNumber of Margins:\n ") cat(length(object@fit), "\n") } else { # For univariate Garch Models ... # Conditional Distribution: cat("\nConditional Distribution:\n ") cat(object@fit$params$cond.dist, "\n") # Coefficients: cat("\nCoefficient(s):\n") digits = max(5, getOption("digits") - 4) print.default(format(object@fit$par, digits = digits), print.gap = 2, quote = FALSE) # Std. Errors: cat("\nStd. Errors:\n ") if (object@fit$params$cond.dist == "QMLE") { cat("robust", "\n") } else { cat("based on Hessian", "\n") } # Error Analysis: digits = max(4, getOption("digits") - 5) fit = object@fit signif.stars = getOption("show.signif.stars") cat("\nError Analysis:\n") printCoefmat(fit$matcoef, digits = digits, signif.stars = signif.stars) # Log Likelihood: cat("\nLog Likelihood:\n ") LLH = - object@fit$value N = NROW(object@data) cat(LLH, " normalized: ", LLH/N, "\n") } # Description: cat("\nDescription:\n ") cat(object@description, "\n") # Return Value: cat("\n") invisible() } setMethod(f = "show", signature(object = "fGARCH"), definition = function(object) { .show_orig_body(object) }) # ------------------------------------------------------------------------------ setMethod(f = "show", signature(object = "fGARCHSPEC"), definition = function(object) { # A function implemented by Diethelm Wuertz # Description: # S4 Print Method for objects of class 'fGARCHSPEC' # Arguments: # object - Object of class 'fGARCHSPEC' # FUNCTION: # Formula: x = object cat("\nFormula: \n ") cat(as.character(x@formula)) # Model: cat("\nModel:") if (sum(abs(x@model$ar)) != 0) cat("\n ar: ", x@model$ar) if (sum(abs(x@model$ma)) != 0) cat("\n ma: ", x@model$ma) if (x@model$mu != 0) cat("\n mu: ", x@model$mu) if (x@model$omega != 0) cat("\n omega:", x@model$omega) if (sum(abs(x@model$alpha)) != 0) cat("\n alpha:", x@model$alpha) if (sum(abs(x@model$gamma)) != 0) cat("\n gamma:", x@model$gamma) if (sum(abs(x@model$beta)) != 0) cat("\n beta: ", x@model$beta) if (x@model$delta != 2) cat("\n delta:", x@model$delta) # Distribution: cat("\nDistribution: \n ") cat(x@distribution) if (x@distribution != "norm") { if (x@distribution == "snorm") { cat("\nDistributional Parameters: \n") cat(" xi =", x@model$skew) } if (x@distribution == "ged" | x@distribution == "std") { cat("\nDistributional Parameter: \n") cat(" nu =", x@model$shape) } if (x@distribution == "sged" | x@distribution == "sstd") { cat("\nDistributional Parameters: \n") cat(" nu =", x@model$shape, " xi =", x@model$skew) } } # Seed: if (x@rseed != 0) { cat("\nRandom Seed: \n ") cat(x@rseed) } # Presample: cat("\nPresample: \n") n = -(length(x@presample[, 1])-1) time = n:0 print(data.frame(cbind(time, x@presample))) # Return Value: invisible() }) ################################################################################ fGarch/R/garch-Solver.R0000755000176200001440000001233214263246022014331 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: SOLVER: # .garchRnlminb R coded solver nlmin # .garchRlbgfsb R coded solver optim using method lbgfsb # .garchRnm R coded solver nm as hybrid addon ################################################################################ .garchRnlminb <- function(.params, .series, .garchLLH, trace) { # A function implemented by Diethelm Wuertz # Description: # Port3 nlminb R-code Solver # Arguments: # FUNCTION: # Port3 nlminb R-code Solver: if(trace) cat("\nR coded nlminb Solver: \n\n") # Scale Function and Parameters: INDEX = .params$index parscale = rep(1, length = length(INDEX)) names(parscale) = names(.params$params[INDEX]) parscale["omega"] = var(.series$x)^(.params$delta/2) parscale["mu"] = abs(mean(.series$x)) # Control: TOL1 = .params$control$tol1 # Fit Parameters - par | objective: fit <- nlminb( start = .params$params[INDEX], objective = .garchLLH, lower = .params$U[INDEX], upper = .params$V[INDEX], scale = 1/parscale, control = list( eval.max = 2000, iter.max = 1500, rel.tol = 1.0e-14 * TOL1, x.tol = 1.0e-14 * TOL1, trace = as.integer(trace)), fGarchEnv = FALSE) # to speed up .garchLLH fit$value <- fit.llh <- fit$objective names(fit$par) = names(.params$params[INDEX]) # make sure to save new h and z (important to speed up code) .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE) # Result: fit$coef <- fit$par fit$llh <- fit$objective # Return Value: fit } # ------------------------------------------------------------------------------ .garchRlbfgsb <- function(.params, .series, .garchLLH, trace) { # A function implemented by Diethelm Wuertz # Description: # optim[L-BFGS-B] Solver # Arguments: # FUNCTION: # optim[L-BFGS-B] Solver: if(trace) cat("\nR coded optim[L-BFGS-B] Solver: \n\n") # Scale Function and Parameters: INDEX = .params$index parscale = rep(1, length = length(INDEX)) names(parscale) = names(.params$params[INDEX]) parscale["omega"] = var(.series$x)^((.params$params["delta"])/2) # Control: TOL1 = .params$control$tol1 # Fit Parameters - par, value: fit <- optim( par = .params$params[INDEX], fn = .garchLLH, lower = .params$U[INDEX], upper = .params$V[INDEX], method = "L-BFGS-B", control = list( parscale = parscale, lmm = 20, pgtol = 1.0e-11 * TOL1, factr = 1.0 * TOL1, trace = as.integer(trace)), fGarchEnv = FALSE) # to speed up .garchLLH names(fit$par) = names(.params$params[INDEX]) # make sure to save new h and z (important to speed up code) .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE) # Print Hessian Matrix: # print(fit$hessian) # Add to Result: fit$coef = fit$par fit$llh = fit$value # Return Value: fit } # ------------------------------------------------------------------------------ .garchRnm <- function(.params, .series, .garchLLH, trace) { # A function implemented by Diethelm Wuertz # Description: # Nelder-Mead as Hybrid Solver # Arguments: # FUNCTION: # Nelder-Mead as Hybrid Solver: if(trace) cat("\nR coded Nelder-Mead Hybrid Solver: \n\n") # Scale Function and Parameters: INDEX = .params$index fnscale = abs(.params$llh) parscale = abs(.params$params[INDEX]) # Control: TOL2 = .params$control$tol2 # Fit Parameters: fit = optim( par = .params$params[INDEX], fn = .garchLLH, method = "Nelder-Mead", control = list( ndeps = rep(1e-14*TOL2, length = length(INDEX)), maxit = 10000, reltol = 1.0e-11 * TOL2, fnscale = fnscale, parscale = c(1, abs((.params$params[INDEX])[-1])), trace = as.integer(trace)), hessian = TRUE, fGarchEnv = FALSE) # to speed up .garchLLH names(fit$par) = names(.params$params[INDEX]) # Make sure to save new h and z: (important to speed up code) .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE) # Result: fit$coef = fit$par fit$llh = fit$value # Return Value: fit } ################################################################################ fGarch/R/garch-Gradient.R0000755000176200001440000000602014263246022014611 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # .garchRCDAGradient Computes R coded CDA matrix of contributions # to the Gradient ################################################################################ .garchRCDAGradient <- function(par, .params, .series, eps = 1.0e-4) { # A function implemented by Michal Miklovic & Yohan Chalabi # Description: # Compute R coded CDA (central difference approximated) Gradient # Reference: # http://status.sph.umich.edu/computing/manuals/sas8/stat/chap46/sect26.htm # FUNCTION: # Starttime .StartGradient <- Sys.time() # Algorithm algorithm = .params$control$algorithm[1] .trace = FALSE # LLH for the computation of matrix of contributions to the Gradient skew <- .params$skew shape <- .params$shape delta <- .params$delta deltainv = 1/delta llh.start = .series$llh.start N <- length(.series$x) .garchDist <- .getfGarchEnv(".garchDist") # Compute matrix of contributions to the Gradient: eps = eps * par n = N - llh.start + 1 K = length(par) G = matrix(0, nrow = n, ncol = K) for (i in 1:K) { x1 = x2 = par x1[i] = x1[i] + eps[i] x2[i] = x2[i] - eps[i] # .garchLLH(x1, .trace, TRUE) h1 <- .getfGarchEnv(".series")$h z1 <- .getfGarchEnv(".series")$z hh1 = (abs(h1[(llh.start):N]))^deltainv zz1 = z1[(llh.start):N] llh.grad1 <- log(.garchDist(z = zz1, hh = hh1, skew = skew, shape = shape)) # .garchLLH(x2, .trace, TRUE) h2 <- .getfGarchEnv(".series")$h z2 <- .getfGarchEnv(".series")$z hh2 = (abs(h2[(llh.start):N]))^deltainv zz2 = z2[(llh.start):N] llh.grad2 <- log(.garchDist(z = zz2, hh = hh2, skew = skew, shape = shape)) # G[,i] = (llh.grad1 - llh.grad2) / (2*eps[i]) } rownames(G) = c(1:n) colnames(G) = names(par) # make sure that h and z are ok .setfGarchEnv(.series = .series) time = Sys.time() - .StartGradient # Attribute Exdecution time attr(G, "time") = time # Return Value: G } ################################################################################ fGarch/R/dist-sgedSlider.R0000755000176200001440000000727414263246022015034 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA ################################################################################ # FUNCTION: DESCRIPTION: # sgedSlider Displays Generalized Error Distribution and RVS ################################################################################ sgedSlider <- function(type = c("dist", "rand")) { # A function implemented by Diethelm Wuertz # Description: # Displays interactively skew GED distribution # Note: # dsged(x, mean = 0, sd = 1, nu = 5, xi = 1.5) # FUNCTION: # Internal Function: refresh.code = function(...) { # Sliders: N = .sliderMenu(no = 1) mean = .sliderMenu(no = 2) sd = .sliderMenu(no = 3) nu = .sliderMenu(no = 4) xi = .sliderMenu(no = 5) invert = .sliderMenu(no = 6) # Compute Data: if (invert == 1) xi = round(1/xi, digits = 4) xmin = round(qsged(0.01, mean, sd, nu, xi), digits = 2) xmax = round(qsged(0.99, mean, sd, nu, xi), digits = 2) s = seq(xmin, xmax, length = N) y1 = dsged(s, mean, sd, nu, xi) y2 = psged(s, mean, sd, nu, xi) main1 = paste("Skew GED Density\n", "mean = ", as.character(mean), " | ", "sd = ", as.character(sd), " | ", "nu = ", as.character(nu), " | ", "xi = ", as.character(xi) ) main2 = paste("Skew GED Probability\n", "xmin [0.01] = ", as.character(xmin), " | ", "xmax [0.99] = ", as.character(xmax) ) # Random Numbers: if (type[1] == "rand") { x = rsged(N, mean, sd, nu, xi) } # Frame: par(mfrow = c(2, 1), cex = 0.7) # Density: if (type[1] == "rand") { hist(x, probability = TRUE, col = "steelblue", border = "white", breaks = "FD", xlim = c(xmin, xmax), ylim = c(0, 1.1*max(y1)), main = main1 ) lines(s, y1, col = "orange") } else { plot(s, y1, type = "l", xlim = c(xmin, xmax), col = "steelblue") abline (h = 0, lty = 3) title(main = main1) grid() } # Probability: plot(s, y2, type = "l", xlim = c(xmin, xmax), ylim = c(0, 1), col = "steelblue" ) abline (h = 0, lty = 3) title(main = main2) grid() # Frame: par(mfrow = c(1, 1), cex = 0.7) } # Open Slider Menu: .sliderMenu(refresh.code, names = c( "N", "mean", "sd", "nu", "xi", "xi.inv"), minima = c( 10, -5.0, 0.1, 2.1, 1.0, 0 ), maxima = c( 1000, +5.0, 5.0, 10.0, 10.0, 1 ), resolutions = c( 10, 0.1, 0.1, 0.1, 0.1, 1 ), starts = c( 100, 0.0, 1.0, 5.0, 1.0, 0 ) ) } ################################################################################ fGarch/NEWS.md0000755000176200001440000001736714513027727012573 0ustar liggesusers## CHANGES in fGarch VERSION 4022.90 (2023-10-15, svn r6333–r6435) - added `"fGARCH"` method for 'stats::tsdiag'. The method produces diagnostic plot for fitted GARCH/APARCH models and computes some diagnostic tests. The plots can be chosen iteractively and/or via arguments. The test results are in the returned value. The method is in development in that more plots may be made available and additional tests included in the returned value. - refactored the `"fGARCH"` method for 'summary' to return an object from S3 class 'summary\_fGARCH' equipped with a 'print' method. The printout is the same as before, except that now the numbers in the statistics column for the residual diagnostics are aligned on the decimal point (previously they were left-aligned due to a buglet). - the `"fGARCH"` method for `fitted` was returning the data, not the fitted values. Fixes issue 6789, reported by Kouhei Hashinokuchi (hakoshie). - the help pages for the `"fGARCH"` methods for `fitted()` and `residuals()` were stating that the returned results have the same class as the input time series. Actually, they return numeric vectors. (todo?: to make the returned values as previously documented, `garchFit()` would need to put the original data or the necessary information in the fitted object, e.g., `object@fit$data`. - some tests were using deprecated `fBasics::.distCheck()` (notice the leading dot). Replaced such calls with the equivalent `fBasics::distCheck()`. ## CHANGES in fGarch VERSION 4022.89 (2022-11-05, from svn r6316–r6326) - in `absMoments`, the absolute moments for the standardized Student-t distribution were wrong. - in README, linked to the paper by Wuertz et al. - substantially revised the documentation and filled gaps in it. - removed the functions with suffix '\_orig' which were kept temporarilly after the bug fix in v4021.87 since there were no reported problems with the fix. ## CHANGES in fGarch VERSION 4021.88 (2022-09-28, svn r6276) - require Matrix (>= 1.5-0) to avoid problems for users who have earlier versions of Matrix on their devices (thanks to Mikael Jagan for checking for not strict enough dependency on Matrix and alerting the maintainer). ## CHANGES in fGarch VERSION 4021.87 (2022-08-06, svn r6215–r6265) ### NEW MAINTAINER - Georgi N. Boshnakov ### BUG FIXES Fixed issue 6061 raised by William Scott, who also supplied examples. - The quantile function, `qsnorm`, was wrong around 0.5. The error was in `.qsnorm`. For now its version before the fix is kept as `.qsnorm_orig`. Basically, branching was done w.r.t. `p = 0.5`, which is correct only for the symmetric case, `\xi = 1`, and should be `1/(1+\xi^2)` instead. More details in the source code. The error was affecting the central part of the distrbution with the interval becoming larger for `\xi` further away from 1. - The cdf, `psnorm`, had an error at a single point, coinciding with the wrong value for `p = 0.5` returned by `qsnorm(0.5)` before the fix. The result was that `psnorm(qsnorm(0.5))` was returning 0.5, falsely giving reassurance that `qsnorm(0.5)` was correct. - Not mentioned in issue 6061 but the same problems held for the other skewed distributions: `qsstd`, `psstd`, `qsged`, `psged`. The original versions of the relevant internal functions are kept for now with a suffix `_orig`, as above: `qsstd_orig`, `psstd_orig`, `qsged_orig`, `psged_orig`. ### Documentation - Edited the documentation of `"garchSpec"` and `garchSim`. It was somewhat incomplete and contained leftovers, apparently from old versions of the functions. - Documented the datasets. Previously the help page for them was a placeholder, without the names of the available datasets. There is no information about the time span of the data or how the returns were calculated. ## CHANGES in fGarch VERSION 4021.86 (2022-06-23, svn r6188) ### NEW MAINTAINER - Tobias Setz ### Notes - This is a CRAN release of version 4001.1, with trivial changes in ‘DESCRIPTION’. ## CHANGES in fGarch VERSION 4001.1 (2022-06-23, svn r6184–r6185) ### NEW MAINTAINER - ad interim: Martin Maechler ### NEW FEATURES - Packages [timeSeries](https://CRAN.R-project.org/package=timeSeries), [timeDate](https://CRAN.R-project.org/package=timeDate) and [fBasics](https://CRAN.R-project.org/package=fBasics) are no longer in `Depends`, but only in `Imports` and hence no longer automatically attached to the `search()` path whenever fGarch is. This may require updates in your code, e.g., adding stopifnot(require("timeSeries")) as it has been done in our own fGarch's examples and tests. - `.gogarchFit()` is at least *mentioned* in the documentation. ### BUG FIXES - Added registration of compiled functionality for speed up and as good practice. - Removed all `Depends:` entries and checked exactly which parts of packages, notably fBasics, timeDate, and timeSeries, are needed and imported only these. - Eliminated warning about 'length > 1' character formula in `garchFit()`, i.e., `.garchFit()`. - Replaced the error-prone checking for 'class()' equality by 'inherits(\*, <class>)'. ### Misc - Exporting practically everything seems “wrong” (according to MM): Several `.` functions have *no* documentation and hence should either be (renamed and) documented or no longer be exported. - a `data` argument should never have a default: hence removed from `garchFit()`. ## CHANGES in fGarch, VERSION 3042.83.2 (2020-03-07, CRAN team) ### Misc - in ‘dist-norm.Rd’, removed the description of argument `...`, which is not in the argument list of any function described there. ## CHANGES in fGarch, VERSION 3042.83.1 (2019-01-31, CRAN team) ### Misc - in ‘NAMESPACE’ and ‘R/methods-plot.R’ renamed functions `.plot.garch.1`, ..., `.plot.garch.13` to `.plot.garch_1`, ..., `.plot.garch_13`. - compressed datasets ‘data/dem2gbp.csv’ and ‘data/sp500dge.csv’ to ‘data/dem2gbp.csv.bz2’ ‘data/sp500dge.csv.bz2’, respectively. ## CHANGES in fGarch, VERSION 3042.83 (2017-11-16, svn r...) ### Misc - Startup message removed - Incorporate fixes by CRAN team (Brian Ripley?) - Checks and adaptions for R 3.4.2, e.g., ‘DESCRIPTION’, ... ## CHANGES in fGarch, VERSION 3010.82.1 (2016-08-14, CRAN team.) ### Misc - in ‘NAMESPACE’, import (selectively) from utils. - changed a couple of calls to `Matrix()` from package Matrix and `fastICA()` from fastICA to the fully qualified forms `Matrix::Matrix()` and `fastICA::fastICA`. - removed some flag settings in ‘Makevars’. - in ‘math.f’, move a `DATA` command out of the body of an `"if"` block putting it towards the beginning of the file. ## CHANGES in fGarch, VERSION 3010.82 (2013-04-30, svn r5509) – and earlier ### ChangeLog - Changes up to April 2013, by Yohan Chalabi, Diethelm Wuertz, Pierre Chausse and Martin Maechler are all in file ‘ChangeLog’. fGarch/MD50000644000176200001440000001522714557030206011765 0ustar liggesusers8ddf42e368503fb9cb47500e2e44adab *ChangeLog 7041dd209ae73651d1a6074f916d5802 *DESCRIPTION a4833f5183b01601117d1607395de3ee *NAMESPACE 5fc4a923ca3593fd57199033aaa0a490 *NEWS.md c7a13a689bb6a905b6bbd9d191c7f0df *R/class-fGARCH.R 0eb2fa2612486d6e24b7ca89f27003c2 *R/class-fGARCHSPEC.R aaf7406e83fe74c1c684f7ae6d43f9e7 *R/cvar-VaR.R 97a094a106805ce33f4621ed5082266b *R/dist-absMoments.R 7b40285ba3f868b015ff905335f6d1df *R/dist-ged.R c4703f63fc51a3420476e610ab77c7b2 *R/dist-gedFit.R d35be82ca2b203f6e3ecb0678d6f2fb1 *R/dist-gedSlider.R 63642d3ad7536e4fa55e82e7eaa0593e *R/dist-sged.R cd5ff5e91cc2ed186ec0e60cabb16661 *R/dist-sgedFit.R f4b5d342a48c57b36f4a98a08f637e56 *R/dist-sgedSlider.R 485ae781212f3a00ffefd12dc1659815 *R/dist-snorm.R ec77009ba98b3bc98362da3e9812d7e0 *R/dist-snormFit.R 0c71233088546c742adfa6de041994d1 *R/dist-snormSlider.R 2835e2bd72ebd6989b091bd0a6f13347 *R/dist-sstd.R 2a8ac9d4ac150fa20428fdaf62281ab7 *R/dist-sstdFit.R 7e19de8d0b578ea3171bc050fd81784a *R/dist-sstdSlider.R 97fbe5d8149c1a0ff7cca075826c4c5f *R/dist-std.R de9f483be2041746c02cf755fd367145 *R/dist-stdFit.R d06897dd68e8f25e9678913e4bd4fa90 *R/dist-stdSlider.R 224624b554b51119fc6e56b3d489277c *R/fGarch-package.R 9741bff5bd063d83445d8457cbfb9f28 *R/fGarchEnv.R 049762f686f27bcb47b7838830e277d1 *R/garch-Distribution.R 2ac7c7d170ecd4434eb201e4d04ec7bf *R/garch-FitFromFormula.R d399b6182fe861dfef382d8428f56256 *R/garch-FitFromSpec.R c0e91199a1630adf9eff532496639380 *R/garch-FitInternal.R fff4d1f43e02a27c8dbb7f3a878158a7 *R/garch-GlobalVars.R 9556d8f69fddef06228e47462fbe19ea *R/garch-Gradient.R f96e311db2917aeb3c44f482bf31b620 *R/garch-Hessian.R e1b1fa3c676e0da11af6333cdaba9361 *R/garch-Initialization.R 2e36274f7c8891fc1c72083717a3d327 *R/garch-Sim.R d02bb65ed394232775cc7a65bec1c7a3 *R/garch-Solver.R effee1524457176e544a4159f06f9e65 *R/garch-SolverControl.R cdf7d994bb67c2c35e6f571e731daf48 *R/garch-Spec.R b4c216db11d187be7b33a1b9208abcb5 *R/garch-Stats.R a0af43ada8cf98ae21ff931574f48317 *R/loglik-aparch.R 85dbb41d543618dd30d9b0514794a3b0 *R/loglik-egarch.R 6377dd1ccf33c655fd9163dd5511a4d0 *R/loglik.R 39efcefff0257a13ba13c2807d1c0b6c *R/methods-coef.R 1b8a1beeea7a7a993a169b0baf7e09f0 *R/methods-fitted.R 7f19cf78ce22bbab0b2322e96def3b39 *R/methods-formula.R fd9a4a9bea168c7e37df25deb8efae28 *R/methods-plot.R 4e940d8bba28b0a04f043c87b5fc7b28 *R/methods-predict.R c46ae3e7eb3ca4eaffbf35b6be00ab35 *R/methods-residuals.R afea658b538a1109b7cfa7eb6b8a8f7d *R/methods-show.R fc3a9006f5cc8824d6e6be7e77565063 *R/methods-summary.R 2a8962e41ed5a4de63d2fe649a9e12e3 *R/methods-update.R 1b223cf816ecee7b9fe1d26245fe9baa *R/methods-volatility.R 8da3513457c3bc1ac9d1edd0ef14d5c1 *R/mgarch-FitFromFormula.R 9edf9566b34ba6611b26b3639b8c4c04 *R/stats-tsdiag.R 5ba9ac762a4cd5bae7ed6ed15ea799f5 *R/zzz.R d8364b110e5b84a9ecb161a00ff5d882 *README.md 60f937a344b90a2278f1a9702924b10b *build/partial.rdb fe75772d65e05a3b189023e372d3d1a2 *data/dem2gbp.csv.gz 58bbdc46c698bc7b97657229e8de1277 *data/sp500dge.csv.gz 8e9297291e827ede2b4fc8331cb337a1 *inst/NEWS.Rd 70a0d93bc75a19be75bdab2f50fc48a0 *inst/THANKS af9f62af061782e1693f99642b349698 *inst/_pkgdown.yml 36cd085ff7519fff741f051ae130d83b *inst/pkgdown.yml 665e719c6c9360340268b2e6ac891515 *inst/unitTests/Makefile 6daf0e9de9a62ce7c24edd2e9cd2f7e1 *inst/unitTests/runTests.R 8fa067e349485ddf6c94644cde5e3767 *inst/unitTests/runit.bugfix_6061.R 464451cc881cb5d016b445a5aa1dafb0 *inst/unitTests/runit.formula-methods.R 34ce038d4e5a9b92efb5c01751078296 *inst/unitTests/runit.garch-methods.R 14316d3164dc2ef549773a1197e97f34 *inst/unitTests/runit.garchFit.R 1bbc596063ca7584964b89c23608cb83 *inst/unitTests/runit.garchFit.algorithm.R 3107d6eaf4651d41432ccc76fbf01c6a *inst/unitTests/runit.garchFit.aparch.R e2e025242284f7379f314d39fe81e7ef *inst/unitTests/runit.garchFit.dist.R 5d9915d560e060cbfda0b531129f167d *inst/unitTests/runit.garchFit.faked.R b3764d2f99905a0c9d787c1f79484742 *inst/unitTests/runit.garchFit.garch.R cc8a22d3718b70390d1ad14e36e4ac11 *inst/unitTests/runit.garchFit.init.R 1807810452bb1abf15dd3ea36eedb5d8 *inst/unitTests/runit.garchHessian.R 0cd0ecf3aebbea146c02c31b3f517af1 *inst/unitTests/runit.garchSim.R 9fd027295b05fa559e7db79b2cb01be0 *inst/unitTests/runit.garchSolver.R d0df67b7fcd6fd58444049b69c29c2ec *inst/unitTests/runit.garchSpec.R 2db651c11a011446c606514d5022edbc *inst/unitTests/runit.plot-methods.R afeb0877a73a8b55095082caca3a9f40 *inst/unitTests/runit.predict-methods.R 37173cf965fe63542466f8af50a12fbd *inst/unitTests/runit.sged.R c5d4c5fc8f4880e61c1a3880e79bfba3 *inst/unitTests/runit.snorm.R dff8337ddb27e8865b4eb21996feff85 *inst/unitTests/runit.sstd.R 437fc7d0fbac23ce7ba0bdaebb73a847 *man/00fGarch-package.Rd f5b7b472313f68ffcf82405d2c7a53e3 *man/VaR.Rd f8f05b5482d5970e8b32aace9fbbd656 *man/class-fGARCH.Rd 44f8dc5fc2581a0afc54913d7f356db3 *man/class-fGARCHSPEC.Rd c3534669939f0e8c3afec7b6cc42f80f *man/class-fUGARCHSPEC.Rd 1dac03c2ba6538440092201bb3a946fe *man/dist-absMoments.Rd a397fc96da1c67556ffb02343c573f24 *man/dist-ged.Rd a15c86d80a269719ccfdd013f7a6c0bb *man/dist-gedFit.Rd f11e2ca34b0499ae0cf516cc47b2289b *man/dist-gedSlider.Rd 910123f5a7e461989a3aa32ebcca9e6a *man/dist-sged.Rd 4f71620a9daf1358b6fcbfddf0c11a1e *man/dist-sgedFit.Rd 682333d38703b3159848842a58b54edc *man/dist-sgedSlider.Rd ca3e163a0f0652ac885966b136b44d91 *man/dist-snorm.Rd b2fc232941e92b5429df42afe3fab73e *man/dist-snormFit.Rd 8ba18a18e5cb115ccc94225701dfc708 *man/dist-snormSlider.Rd 2185a76bcd87138d8ccc2797b5bfa3c9 *man/dist-sstd.Rd 386eff289baadc2ace3bce1b5b0b5d1f *man/dist-sstdFit.Rd 7e426c3077b9869f872441bfd82309ea *man/dist-sstdSlider.Rd 8b5ef8609a6165b452fe9d314ac36e45 *man/dist-std.Rd 0ef52b07b7ed6863facee06e328040df *man/dist-stdFit.Rd 49feff080bc3a26acf903605a27c6d4f *man/dist-stdSlider.Rd 9b30944f18aa44177f839db277e54717 *man/fGarchData.Rd 0403f11b3cad9e9f99c4538f600a13fa *man/garchFit.Rd 6c03acfcf84fa8c1cb0804a0299657d3 *man/garchFitControl.Rd 09f6db1c0be4ec9c7224613c69fd21b2 *man/garchSim.Rd 18243b448927ae910e31c67be8ecdcdb *man/garchSpec.Rd 5def4f56e3cff93c02616b38bf202a5e *man/methods-coef.Rd e877368b273d1e1bd371b8848ed5fac0 *man/methods-fitted.Rd 9bf9bec752d183b340fe9ef3d7f0dc00 *man/methods-formula.Rd cfbc39c57b8bbc2515d4463c9bd1e754 *man/methods-plot.Rd 4dd9a93782b34638ffc62b0ca8ac4ad8 *man/methods-predict.Rd eeed6ad45deab1e23d6fea0e42fbb2f0 *man/methods-residuals.Rd 1462ed06a16ff011cb2438b732e49337 *man/methods-summary.Rd 0cd9f3f2146beca42b58855d54fcac3a *man/methods-volatility.Rd 35d8fdda60e66294a99cf4cb39776aae *man/stats-tsdiag.Rd 3996e7c16bfb96fad295ee425815cb4d *src/Makevars 4276e1893140fa52dab90c5f041511b0 *src/dist.f fce86d34d35e081f121901a423fc4bf1 *src/init.c ef9c63dfb10dc8f4460e339354e73ce5 *src/llhGarch.f 39ec04391b2bb400783da91b890d064c *src/math.f ca566e590ec30abd0718c5375e1a446f *tests/doRUnit.R fGarch/inst/0000755000176200001440000000000014556735624012442 5ustar liggesusersfGarch/inst/pkgdown.yml0000644000176200001440000000032314513030552014611 0ustar liggesuserspandoc: 2.9.2.1 pkgdown: 2.0.7 pkgdown_sha: ~ articles: {} last_built: 2023-10-15T18:37Z urls: reference: https://geobosh.github.io/fGarchDoc/reference article: https://geobosh.github.io/fGarchDoc/articles fGarch/inst/THANKS0000755000176200001440000000035514263246022013343 0ustar liggesusersThe Rmetrics core team would like to thank the following people for ideas, testing and feedback regarding fGarch: Michal Miklovic Kris Kris Spencer Graves fGarch/inst/_pkgdown.yml0000755000176200001440000000351114441605410014756 0ustar liggesusersurl: https://geobosh.github.io/fGarchDoc/ deploy: install_metadata: true template: bootstrap: 5 search: exclude: ['news/index.html'] reference: - title: "Overview of package fGarch" contents: - "fGarch-package" - fGarch - fGarchData - garchSim - dem2gbp - sp500dge - title: "Fit models" contents: - garchFit - tsdiag.fGARCH - .gogarchFit - garchKappa - garchSpec - garchFitControl - title: "Classes" contents: - "fGARCH-class" - "show,fGARCH-method" - "fGARCHSPEC-class" - "show,fGARCHSPEC-method" - title: "Exploring and computing on 'fGARCH' objects" contents: - "plot,fGARCH,missing-method" - "summary-methods" - "summary,fGARCH-method" - "coef-methods" - "coef,fGARCH-method" - "coef,fGARCHSPEC-method" - "fitted-methods" - "fitted,fGARCH-method" - "formula-methods" - "formula,fGARCH-method" - "predict,fGARCH-method" - "residuals,fGARCH-method" - volatility - title: "Standardized distributions" contents: - absMoments - dstd - pstd - qstd - rstd - dged - pged - qged - rged - title: "Skewed standardized distributions" contents: - dsnorm - psnorm - qsnorm - rsnorm - dsstd - psstd - qsstd - rsstd - dsged - psged - qsged - rsged - title: "Fit standardized distributions" contents: - stdFit - gedFit - snormFit - sstdFit - sgedFit - title: "Visualize standardized distributions" contents: - stdSlider - gedSlider - snormSlider - sstdSlider - sgedSlider - title: "Internal functions and classes" contents: - "fUGARCHSPEC-class" fGarch/inst/unitTests/0000755000176200001440000000000014512742325014430 5ustar liggesusersfGarch/inst/unitTests/runit.garchSolver.R0000755000176200001440000002402014263246022020167 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: SOLVER: # .garchRnlminb R coded solver nlmin # .garchRlbgfsb R coded solver optim using method lbgfsb # .garchRnm R coded solver nm as hybrid addon # .garchFsqp Fortran coded solver sqp # .garchRdonlp2 R coded solver donlp2 # .garchFmnfb Fortran coded solver mnfb ################################################################################ ## test.garchSolver.dem2gbp <- ## function() ## { ## # Note, Default has changed: "cda" -> "fda" ## # Loda Data ## data(dem2gbp) ## garchFit(~ garch(1,1), dem2gbp, hessian = "fda", algorithm = "nlminb") ## # Time difference of 2.969 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu -0.006190 0.008464 -0.731 0.464545 ## # omega 0.010761 0.003081 3.492 0.000479 *** ## # alpha1 0.153134 0.027720 5.524 3.31e-08 *** ## # beta1 0.805974 0.035761 22.537 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 1106.608 normalized: 0.5605916 ## garchFit(~ garch(1,1), dem2gbp, hessian = "cda", algorithm = "nlminb") ## garchFit(~ garch(1,1), dem2gbp, algorithm = "lbfgsb") ## # Time difference of 4.75 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu -0.006187 0.008462 -0.731 0.464720 ## # omega 0.010785 0.002860 3.771 0.000163 *** ## # alpha1 0.153306 0.026556 5.773 7.79e-09 *** ## # beta1 0.805706 0.033612 23.971 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 1106.608 normalized: 0.5605916 ## garchFit(~ garch(1,1), dem2gbp, hessian = "cda", algorithm = "nlminb+nm") ## # Time difference of 6.094 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu -0.006190 0.008462 -0.732 0.464447 ## # omega 0.010761 0.002853 3.772 0.000162 *** ## # alpha1 0.153134 0.026523 5.774 7.76e-09 *** ## # beta1 0.805974 0.033553 24.021 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 1106.608 normalized: 0.5605916 ## # ## garchFit(~ garch(1,1), dem2gbp, hessian = "cda", algorithm = "lbfgsb+nm") ## garchFit(~ garch(1,1), dem2gbp, hessian = "cda", algorithm = "donlp2") ## # Time difference of 7.094 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu -0.006190 0.008462 -0.732 0.464447 ## # omega 0.010761 0.002853 3.772 0.000162 *** ## # alpha1 0.153134 0.026523 5.774 7.76e-09 *** ## # beta1 0.805973 0.033553 24.021 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 1106.608 normalized: 0.5605916 ## # ## garchFit(~ garch(1,1), dem2gbp, hessian = "cda", algorithm = "sqp") ## # Time difference of 1.906 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu -0.006190 0.008462 -0.732 0.464437 ## # omega 0.010761 0.002853 3.772 0.000162 *** ## # alpha1 0.153134 0.026523 5.774 7.76e-09 *** ## # beta1 0.805974 0.033553 24.021 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 0.5605916 normalized: 0.0002839877 ## # ## garchFit(~ garch(1,1), dem2gbp, hessian = "cda", algorithm = "mnfb") ## # Time difference of 1.344 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu -0.006190 0.008461 -0.732 0.464384 ## # omega 0.010761 0.002853 3.772 0.000162 *** ## # alpha1 0.153134 0.026523 5.774 7.75e-09 *** ## # beta1 0.805974 0.033552 24.021 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 0.5605916 normalized: 0.0002839877 ## # Return Value: ## return() ## } # ------------------------------------------------------------------------------ test.garchSolver2.dem2gbp <- function() { # Note, Default has changed: "cda" -> "fda" # Loda Data data(dem2gbp) ## garchFit(~ garch(1,1), dem2gbp, hessian = "fcd", algorithm = "nlminb") garchFit(~ garch(1,1), dem2gbp, hessian = "rcd", algorithm = "nlminb") garchFit(~ garch(1,1), dem2gbp, algorithm = "lbfgsb") ## garchFit(~ garch(1,1), dem2gbp, hessian = "fcd", algorithm = "nlminb+nm") garchFit(~ garch(1,1), dem2gbp, hessian = "rcd", algorithm = "lbfgsb+nm") # garchFit(~ garch(1,1), dem2gbp, hessian = "fcd", algorithm = "donlp2") # garchFit(~ garch(1,1), dem2gbp, hessian = "rcd", algorithm = "sqp") ## garchFit(~ garch(1,1), dem2gbp, hessian = "fcd", algorithm = "mnfb") # Return Value: return() } # ------------------------------------------------------------------------------ ## test.garchSolver.sp500dge <- ## function() ## { ## # Loda Data: ## data(sp500dge) ## sp500dge = 100 * sp500dge ## garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "cda", ## algorithm = "lbfgsb") # garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "cda", # algorithm = "sqp") ## # Time difference of 48.954 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu 0.020646 0.006350 3.251 0.00115 ** ## # ma1 0.144745 0.008358 17.319 < 2e-16 *** ## # omega 0.009988 0.001085 9.201 < 2e-16 *** ## # alpha1 0.083803 0.004471 18.742 < 2e-16 *** ## # gamma1 0.373092 0.027997 13.326 < 2e-16 *** ## # beta1 0.919401 0.004093 224.614 < 2e-16 *** ## # delta 1.435124 0.067203 21.355 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 1.264345 normalized: 7.413338e-05 ## # # garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "fda", # algorithm = "sqp") # garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "cda", # algorithm = "mnfb") ## # Time difference of 35.156 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu 0.020646 0.006351 3.251 0.00115 ** ## # ma1 0.144745 0.008358 17.319 < 2e-16 *** ## # omega 0.009988 0.001086 9.201 < 2e-16 *** ## # alpha1 0.083803 0.004472 18.741 < 2e-16 *** ## # gamma1 0.373092 0.027997 13.326 < 2e-16 *** ## # beta1 0.919401 0.004093 224.606 < 2e-16 *** ## # delta 1.435124 0.067204 21.355 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 1.264345 normalized: 7.413338e-05 ## # # garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "fda", # algorithm = "mnfb") ## # Time difference of 31.516 secs ## # Error Analysis: ## # Estimate Std. Error t value Pr(>|t|) ## # mu 0.020646 0.006342 3.255 0.00113 ** ## # ma1 0.144745 0.008363 17.307 < 2e-16 *** ## # omega 0.009988 0.001113 8.975 < 2e-16 *** ## # alpha1 0.083803 0.004534 18.485 < 2e-16 *** ## # gamma1 0.373092 0.027798 13.422 < 2e-16 *** ## # beta1 0.919401 0.004102 224.141 < 2e-16 *** ## # delta 1.435124 0.066283 21.652 < 2e-16 *** ## # --- ## # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1 ## # ## # Log Likelihood: ## # 1.264345 normalized: 7.413338e-05 ## # ## # Return Value: ## return() ## } # ------------------------------------------------------------------------------ test.garchSolver.sp500dge <- function() { # Loda Data: data(sp500dge) sp500dge = 100 * sp500dge # garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "fcd", # algorithm = "lbfgsb") ### garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "fcd", ### algorithm = "sqp") ### garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "rcd", ### algorithm = "sqp") # garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "fcd", # algorithm = "mnfb") # garchFit(~ arma(0,1) + aparch(1,1), sp500dge, hessian = "rcd", # algorithm = "mnfb") garchFit(~ arma(0,1) + aparch(1,1), sp500dge) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.formula-methods.R0000755000176200001440000001411014263246022021015 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ test.formula.methods.univariate <- function() { # Numeric Vector RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Simulate normal GARCH(1, 1) numeric Vector: spec = garchSpec() N = 250 # Univariate Data Simulation: x.vec = 100*garchSim(spec, N) print(head(x.vec)) x.tS = timeSeries::dummyDailySeries(matrix(x.vec), units = "GARCH11") print(head(x.tS)) # x.zoo = zoo(as.vector(x.vec), order.by = as.Date(rownames(x.tS))) # print(head(x.zoo)) x.ts = as.ts(x.vec) print(head(x.ts)) # Univariate Modeling: # A numeric Vector: fit = garchFit(~ garch(1,1), data = x.vec, trace = FALSE) print(formula(fit)) fit = garchFit(x.vec ~ garch(1,1), data = x.vec, trace = FALSE) print(formula(fit)) # An univariate timeSeries object with dummy dates: fit = garchFit(~ garch(1,1), data = x.tS, trace = FALSE) print(formula(fit)) fit = garchFit(x.tS ~ garch(1,1), data = x.tS, trace = FALSE) print(formula(fit)) ### # An univariate zoo object with dummy dates: ### fit = garchFit(~ garch(1,1), data = x.zoo, trace = FALSE) ### print(formula(fit)) ### fit = garchFit(x.zoo ~ garch(1,1), data = x.zoo, trace = FALSE) ### print(formula(fit)) # An univariate "ts" object: fit = garchFit(~ garch(1,1), data = x.ts, trace = FALSE) print(formula(fit)) fit = garchFit(x.ts ~ garch(1,1), data = x.ts, trace = FALSE) print(formula(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.formula.methods.multivariate <- function() { # Numeric Vector RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Simulate normal GARCH(1, 1) numeric Vector: spec = garchSpec() N = 250 # Univariate Data Simulation: x.vec = 100*garchSim(spec, N) print(head(x.vec)) x.tS = timeSeries::dummyDailySeries(matrix(x.vec), units = "GARCH11") print(head(x.tS)) # Multivariate Data Simulation: X.mat = cbind(GARCH11 = x.vec, R = rnorm(N)) colnames(X.mat) <- c("GARCH11", "R") print(head(X.mat)) X.tS = timeSeries::dummyDailySeries(X.mat, units = c("GARCH11", "R")) print(head(X.tS)) # X.zoo = zoo(X.mat, order.by = as.Date(rownames(x.tS))) # print(head(X.zoo)) X.mts = as.ts(X.mat) print(head(X.mts)) # head doesn't wor for mts !!! # Multivariate Modeling: # A numeric matrix: fit = garchFit(GARCH11 ~ garch(1,1), data = X.mat, trace = FALSE) print(formula(fit)) fit = garchFit(100*GARCH11 ~ garch(1,1), data = X.mat, trace = FALSE) print(formula(fit)) # A multivariate timeSeries object with dummy dates: fit = garchFit(GARCH11 ~ garch(1,1), data = X.tS, trace = FALSE) print(formula(fit)) fit = garchFit(100*GARCH11 ~ garch(1,1), data = X.tS, trace = FALSE) print(formula(fit)) ### # A multivariate zoo object without column names: ### fit = garchFit(GARCH11 ~ garch(1,1), data = X.zoo, trace = FALSE) ### print(formula(fit)) ### fit = garchFit(100*GARCH11 + R/100 ~ garch(1,1), data = X.zoo, trace = FALSE) ### print(formula(fit)) # A multivariate "mts" object without column names: fit = garchFit(GARCH11 ~ garch(1,1), data = X.mts, trace = FALSE) print(formula(fit)) fit = garchFit(100*GARCH11 + R/100 ~ garch(1,1), data = X.mts, trace = FALSE) print(formula(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.formula.methods.spread <- function() { # MODELING THE PERCENTUAL SPI/SBI SPREAD FROM LPP BENCHMARK: # Series: stopifnot(require("timeSeries")) # for the data() and as.timeS.. X.tS = as.timeSeries(data(LPP2005REC)) print(head(X.tS)) X.mat = as.matrix(X.tS) print(head(X.mat)) # X.zoo = zoo(X.mat, order.by = as.Date(rownames(X.tS))) # print(head(X.zoo)) X.mts = ts(X.mat) print(head(X.mts)) # Fit: fit = garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.tS, trace = FALSE) print(formula(fit)) ## fit = garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.mat, trace = FALSE) ## print(formula(fit)) ## fit = garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.zoo, trace = FALSE) ## print(formula(fit)) ## fit = garchFit(100*(SPI - SBI) ~ garch(1,1), data = X.mts, trace = FALSE) ## print(formula(fit)) # MODELING HIGH/LOW SPREADS FROM MSFT PRICE SERIES: # Series: X.tS = MSFT # Fit: fit = garchFit(Open ~ garch(1,1), data = returns(X.tS), trace = FALSE) print(formula(fit)) fit = garchFit(100*(High-Low) ~ garch(1,1), data = returns(X.tS), trace = FALSE) print(formula(fit)) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garch-methods.R0000755000176200001440000000524514263246022020445 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # METHODS: DESCRIPTION: # show.fGARCH S4 print method for an object of class 'fGARCH' # summary.fGARCH S3 summary method for an object of class 'fGARCH' # plot.fGARCH S3 plot method for an object of class 'fGARCH' # residuals.fGARCH S3 residuals method for an object of class 'fGARCH' # fitted.fGARCH S3 fitted values for an object of class 'fGARCH' # predict.fGARCH S3 prediction method for an object of class 'fGARCH' # STATISTICS: Description: # .truePersistence Compute persistence ################################################################################ test.garch.methods.show <- function() { # show.fGARCH - S4 print method for an object of class 'fGARCH' # Garch(1,1) Default Model: x = garchSim(n = 250) # Fit: fit = garchFit( ~ garch(1,1), data = x, trace = FALSE) # Note: # Does also work: # fit = garchFit(dem2gbp ~garch(1,1), data = dem2gbp, trace = FALSE) # Note: # fit = garchFit(DEM2GBP ~garch(1,1), data = dem2gbp, trace = FALSE) # [1] "DEM2GBP" # [1] "dem2gbp" # Error in .garchArgsParser(formula = formula, data = data, trace = FALSE) : # Formula and data units do not match. # Print: print(fit) show(fit) # Summary: summary(fit) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.plot-methods.R0000755000176200001440000001423214263246022020333 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ test.plot.methods1 <- function() { # Load data: data(dem2gbp) dem2gbp = as.vector(dem2gbp[, 1]) # Fit to normal Conditional Distribution: fit = garchFit( ~ garch(1, 1), data = dem2gbp, trace = FALSE) print(fit) # garchFit 1: # 1: # 2: # Graph Frame: par(mfrow = c(2, 1)) # Plot 1: plot(fit, which = 1) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 2: plot(fit, which = 2) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Return Value: return() } # ------------------------------------------------------------------------------ test.plot.methods2 <- function() { # Load data: data(dem2gbp) # Fit to normal Conditional Distribution: fit = garchFit( ~ garch(1, 1), data = dem2gbp, trace = FALSE) print(fit) # garchFit 2: # Graph Frame: par(mfrow = c(1, 1)) # Plot 3: plot(fit, which = 3) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Return Value: return() } # ------------------------------------------------------------------------------ test.plot.methods3 <- function() { # Load data: data(dem2gbp) # Fit to normal Conditional Distribution: fit = garchFit( ~ garch(1, 1), data = dem2gbp, trace = FALSE) print(fit) # garchFit3: # 3: # 4: # 5: # Graph Frame: par(mfrow = c(2, 1)) # Plot 4: plot(fit, which = 4) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 5: plot(fit, which = 5) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Return Value: return() } # ------------------------------------------------------------------------------ test.plot.methods4 <- function() { # Load data: data(dem2gbp) # Fit to normal Conditional Distribution: fit = garchFit( ~ garch(1, 1), data = dem2gbp, trace = FALSE) print(fit) # garchFit4: # 6: Cross Correlation # 7: Residuals # 8: Conditional SDs # 9: Standardized Residuals # Graph Frame: par(mfrow = c(2, 2)) # Plot 6: plot(fit, which = 6) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 7: plot(fit, which = 7) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 8: plot(fit, which = 8) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 9: plot(fit, which = 9) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Return Value: return() } # ------------------------------------------------------------------------------ test.plot.methods5 <- function() { # Load data: data(dem2gbp) # Fit to normal Conditional Distribution: fit = garchFit( ~ garch(1, 1), data = dem2gbp, trace = FALSE) print(fit) # garchFit5: # 10: ACF of Standardized Residuals # 11: ACF of Squared Standardized Residuals # 12: Cross Correlation between r^2 and r # 13: QQ-Plot of Standardized Residuals # Graph Frame: par(mfrow = c(2, 2)) # Plot 10: plot(fit, which = 10) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 11: plot(fit, which = 11) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 12: plot(fit, which = 12) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Plot 13: plot(fit, which = 13) mtext("norm-GARCH(1,1) Modeling", line = 0.5, cex = 0.8) mtext("DEM2GBP Data Vector", side = 4, adj = 0, cex = 0.7, col = "darkgrey") # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchFit.faked.R0000755000176200001440000001401014263246022020506 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # 'fGARCH' S4: fGARCH Class representation # garchFit Fits GARCH and APARCH processes ################################################################################ test.garchFit.faked <- function() { # Numeric Vector RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Simulate normal GARCH(1, 1) numeric Vector: model = list(omega = 1e-06, alpha = 0.1, beta = 0.8) spec = garchSpec(model) print(spec) N = 250 # UNIVARIATE: x.vec = as.vector(100*garchSim(spec, N)) print(head(x.vec)) x.tS = timeSeries::dummyDailySeries(matrix(x.vec), units = "GARCH11") print(head(x.tS)) # x.zoo = zoo(as.vector(x.vec), order.by = as.Date(rownames(x.tS))) # print(head(x.zoo)) x.ts = ts(x.vec) print(head(x.ts)) # FIT FROM UNIVARIATE DATA SERIES: fit = garchFit( ~ garch(1,1), data = x.tS, trace = FALSE) print(fit) formula(fit) fit = garchFit( ~ garch(1,1), data = as.vector(x.tS), trace = FALSE) print(fit) formula(fit) a = 2 b = 2 fit = garchFit( ~ garch(1,1), data = a*as.vector(0+b*x.tS), trace = FALSE) print(fit) formula(fit) # WHAT HAPPENS WHEN WE (MIS)SPECIFY LHS ? # ... lhs will be ignored for the univariate case: fit = garchFit(any ~ garch(1,1), data = x.vec, trace = FALSE) print(fit) formula(fit) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.mult.faked <- function() { # Numeric Vector RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Simulate normal GARCH(1, 1) numeric Vector: model = list(omega = 1e-06, alpha = 0.1, beta = 0.8) spec = garchSpec(model) print(spec) N = 250 # UNIVARIATE: x.vec = as.vector(100*garchSim(spec, N)) print(head(x.vec)) x.tS = timeSeries::dummyDailySeries(matrix(x.vec), units = "GARCH11") print(head(x.tS)) # x.zoo = zoo(as.vector(x.vec), order.by = as.Date(rownames(x.tS))) # print(head(x.zoo)) x.ts = ts(x.vec) print(head(x.ts)) # MULTIVARIATE: X.mat = cbind(GARCH11 = x.vec, R = rnorm(N)/1000) print(head(X.mat)) X.tS = timeSeries::dummyDailySeries(X.mat, units = c("GARCH11", "R")) print(head(X.tS)) # X.zoo = zoo(X.mat, order.by = as.Date(rownames(x.tS))) # print(head(X.zoo)) X.mts = ts(X.mat) print(head(X.mts)) # FIT FROM MULTIVARIATE DATA SET: fit = garchFit(GARCH11 ~ garch(1,1), data = X.tS, trace = FALSE) print(fit) formula(fit) fit = garchFit(GARCH11 ~ garch(1,1), data = as.matrix(X.tS), trace = FALSE) print(fit) formula(fit) a = 2 b = 2 fit = garchFit(GARCH11 ~ garch(1,1), data = a*as.matrix(0+b*X.tS), trace = FALSE) print(fit) formula(fit) a = 2 b = 2 fit = garchFit(GARCH11 ~ garch(1,1), data = a*as.matrix(0+b*X.tS), trace = FALSE) print(fit) formula(fit) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.mult.lhs.faked <- function() { # Numeric Vector RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Simulate normal GARCH(1, 1) numeric Vector: model = list(omega = 1e-06, alpha = 0.1, beta = 0.8) spec = garchSpec(model) print(spec) N = 250 # UNIVARIATE: x.vec = as.vector(100*garchSim(spec, N)) print(head(x.vec)) x.tS = timeSeries::dummyDailySeries(matrix(x.vec), units = "GARCH11") print(head(x.tS)) # x.zoo = zoo(as.vector(x.vec), order.by = as.Date(rownames(x.tS))) # print(head(x.zoo)) x.ts = ts(x.vec) print(head(x.ts)) # MULTIVARIATE: X.mat = cbind(GARCH11 = x.vec, R = rnorm(N)/1000) print(head(X.mat)) X.tS = timeSeries::dummyDailySeries(X.mat, units = c("GARCH11", "R")) print(head(X.tS)) # X.zoo = zoo(X.mat, order.by = as.Date(rownames(x.tS))) # print(head(X.zoo)) X.mts = ts(X.mat) print(head(X.mts)) # LEFT HAND SIDE FORMULA FAKED FIT: fit = garchFit(GARCH11 + R ~ garch(1,1), data = X.tS, trace = FALSE) print(fit) formula(fit) ### head(fit@data$data) ### head(fit@data$Data) ### head(rowSums(fit@data$Data)) # LEFT HAND SIDE FORMULA FAKED AND DATA FAKED FIT: fit = garchFit(GARCH11 + R ~ garch(1,1), data = as.matrix(X.tS), trace = FALSE) print(fit) formula(fit) ### head(fit@data$data) ### head(fit@data$Data) ### head(rowSums(fit@data$Data)) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runTests.R0000755000176200001440000000452614263246022016410 0ustar liggesuserspkg <- "fGarch" if(require("RUnit", quietly = TRUE)) { library(package=pkg, character.only = TRUE) if(!(exists("path") && file.exists(path))) path <- system.file("unitTests", package = pkg) ## --- Testing --- ## Define tests testSuite <- defineTestSuite(name = paste(pkg, "unit testing"), dirs = path) if(interactive()) { cat("Now have RUnit Test Suite 'testSuite' for package '", pkg, "' :\n", sep='') str(testSuite) cat('', "Consider doing", "\t tests <- runTestSuite(testSuite)", "\nand later", "\t printTextProtocol(tests)", '', sep = "\n") } else { ## run from shell / Rscript / R CMD Batch / ... ## Run tests <- runTestSuite(testSuite) if(file.access(path, 02) != 0) { ## cannot write to path -> use writable one tdir <- tempfile(paste(pkg, "unitTests", sep="_")) dir.create(tdir) pathReport <- file.path(tdir, "report") cat("RUnit reports are written into ", tdir, "/report.(txt|html)", sep = "") } else { pathReport <- file.path(path, "report") } ## Print Results: printTextProtocol(tests, showDetails = FALSE) printTextProtocol(tests, showDetails = FALSE, fileName = paste(pathReport, "Summary.txt", sep = "")) printTextProtocol(tests, showDetails = TRUE, fileName = paste(pathReport, ".txt", sep = "")) ## Print HTML Version to a File: ## printHTMLProtocol has problems on Mac OS X if (Sys.info()["sysname"] != "Darwin") printHTMLProtocol(tests, fileName = paste(pathReport, ".html", sep = "")) ## stop() if there are any failures i.e. FALSE to unit test. ## This will cause R CMD check to return error and stop tmp <- getErrors(tests) if(tmp$nFail > 0 | tmp$nErr > 0) { stop(paste("\n\nunit testing failed (#test failures: ", tmp$nFail, ", R errors: ", tmp$nErr, ")\n\n", sep="")) } } } else { cat("R package 'RUnit' cannot be loaded -- no unit tests run\n", "for package", pkg,"\n") } ################################################################################ fGarch/inst/unitTests/runit.sstd.R0000644000176200001440000001071514512742325016674 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: VARIANCE-1 STUDENT-T DISTRIBUTION: # dstd Density for the Student-t Distribution # pstd Probability function for the Student-t Distribution # qstd Quantile function for the Student-t Distribution # rstd Random Number Generator for the Student-t # FUNCTION: SKEW VARIANCE-1 STUDENT-T DISTRIBUTION: # dsstd Density for the skewed Student-t Distribution # psstd Probability function for the skewed STD # qsstd Quantile function for the skewed STD # rsstd Random Number Generator for the skewed STD # stdSlider Displays Variance-1 Student-t Distribution and RVS # FUNCTION: PARAMETER ESTIMATION: # stdFit Fit the parameters for a Sudent-t distribution # sstdFit Fit the parameters for a skew Sudent-t distribution ################################################################################ test.sstdDist <- function() { # Standardized Student-t Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Test: test = fBasics::distCheck("std", mean = 0, sd = 1, nu = 5, robust = FALSE) print(test) # Skew Standardized Student-t Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Test: test = fBasics::distCheck("sstd", mean = 0, sd = 1, nu = 5, xi = 1.5, robust = FALSE) print(test) # Return Value: return() } # ------------------------------------------------------------------------------ test.stdFit <- function() { # Fit the parameters for a Student-t distribution # stdFit - Fit the parameters for a Sudent-t distribution # Standardized Student-t Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Series: x = rstd(n = 2500, mean = 0, sd = 1, nu = 5) # Fit: fit = stdFit(x) print(fit) # Fit the parameters for a skew Sudent-t distribution # sstdFit - Fit the parameters for a Sudent-t distribution # Skew Standardized Student-t Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Series: x = rsstd(n = 2500, mean = 0, sd = 1, nu = 5, xi = 1.5) # Fit: fit = sstdFit(x) print(fit) # Return Value: return() } # ------------------------------------------------------------------------------ test.sstdSlider <- function() { # Try Distribution: # sstdSlider(type = "dist") NA # Try Random Variates: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # sstdSlider(type = "rand") NA # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchFit.algorithm.R0000755000176200001440000001050114263246022021423 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # 'fGARCH' S4: fGARCH Class representation # garchFit Fits GARCH and APARCH processes ################################################################################ test.garchFit.nlminb <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Load Data: x = garchSim(n = 100) # Algorithms: # "nlminb", "sqp", "lbfgsb", "nlminb+nm", "lbfgsb+nm" # nlminb: fit = garchFit( ~ garch(1,1), data = x, algorithm = "nlminb", trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.sqp <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Load Data: x = garchSim(n = 100) # Algorithms: # "nlminb", "sqp", "lbfgsb", "nlminb+nm", "lbfgsb+nm" ### # sqp: ### fit = garchFit( ~ garch(1,1), data = x, ### algorithm = "sqp", trace = FALSE) ### print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.lbfgsb <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Load Data: x = garchSim(n = 100) # Algorithms: # "nlminb", "sqp", "lbfgsb", "nlminb+nm", "lbfgsb+nm" # lbfgsb: fit = garchFit( ~ garch(1,1), data = x, algorithm = "lbfgsb", trace = FALSE) coef(fit) # nlminb+nm: fit = garchFit( ~ garch(1,1), data = x, algorithm = "nlminb+nm", trace = FALSE) coef(fit) # lbfgsb+nm: fit = garchFit( ~ garch(1,1), data = x, algorithm = "lbfgsb+nm", trace = FALSE) coef(fit) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.nlmin.nm <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Load Data: x = garchSim(n = 100) # Algorithms: # "nlminb", "sqp", "lbfgsb", "nlminb+nm", "lbfgsb+nm" # nlminb+nm: fit = garchFit( ~ garch(1,1), data = x, algorithm = "nlminb+nm", trace = FALSE) coef(fit) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.lbfgsb.nm <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Load Data: x = garchSim(n = 100) # Algorithms: # "nlminb", "sqp", "lbfgsb", "nlminb+nm", "lbfgsb+nm" # lbfgsb+nm: fit = garchFit( ~ garch(1,1), data = x, algorithm = "lbfgsb+nm", trace = FALSE) coef(fit) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchFit.init.R0000755000176200001440000000427414263246022020412 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # 'fGARCH' S4: fGARCH Class representation # garchFit Fits GARCH and APARCH processes ################################################################################ test.garchFit.init <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Simulate Garch(1,1) Series: x = garchSim(n = 250) # Modify Start Values - mci default: fit = garchFit( ~ garch(1,1), x, init.rec = "mci", trace = FALSE) # default print(coef(fit)) # Modify Start Values - uev alternative: # fit = garchFit( ~ garch(1,1), x, init.rec = "uev", trace = FALSE) # Error in .garchFit(formula.mean = args$formula.mean, formula.var = args$formula.var, : # Algorithm only supported for mci Recursion # coef(fit) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/Makefile0000755000176200001440000000041714556735643016112 0ustar liggesusersPKG=fGarch TOP=../.. SUITE=doRUnit.R R=R all: inst test inst: # Install package -- but where ?? -- will that be in R_LIBS ? cd ${TOP}/..;\ ${R} CMD INSTALL ${PKG} test: # Run unit tests export RCMDCHECK=FALSE;\ cd ${TOP}/tests;\ ${R} --vanilla --slave < ${SUITE} fGarch/inst/unitTests/runit.sged.R0000644000176200001440000001075114512742264016643 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: GED DISTRIBUTION: # dged Density for the Generalized Error Distribution # pged Probability function for the GED # qged Quantile function for the GED # rged Random Number Generator for the GED # FUNCTION: SKEW GED DISTRIBUTION: # dsged Density for the skewed GED # psged Probability function for the skewed GED # qsged Quantile function for the skewed GED # rsged Random Number Generator for the skewed GED # FUNCTION: GED DISTRIBUTION SLIDER: # sgedSlider Displays Generalized Error Distribution and RVS # FUNCTION: PARAMETER ESTIMATION: # gedFit Fit the parameters for a GED distribution # sgedFit Fit the parameters for a skew GED distribution # FUNCTION: MOMENTS: ################################################################################ test.sgedDis <- function() { # Generalized Error Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Test: test = fBasics::distCheck("ged", mean = 0, sd = 1, nu = 2, robust = FALSE) print(test) # Skew Generalized Error Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(1953, kind = "Marsaglia-Multicarry") test = fBasics::distCheck("sged", mean = 0, sd = 1, nu = 2, xi = 0.8, robust = FALSE) print(test) ## 2022-07-27 GB check fixes related to issue #6061, see NEWS and the source code stopifnot( all( diff(qsged(c(0.49, 0.5, 0.51))) > 0) ) stopifnot( all( diff(psged(qsged(c(0.49, 0.5, 0.51)))) > 0) ) # Return Value: return() } # ------------------------------------------------------------------------------ test.sgedFit <- function() { # Parameter Estimation: # gedFit - Fit the parameters for a GED distribution # Generalized Error Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Series: x = rged(1000, mean = 0, nu = 2) # Fit: fit = gedFit(x) print(fit) # Fit the parameters for a skew GED distribution # sgedFit - Fit the parameters for a skew GED distribution # Skew Generalized Error Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") x = rsged(1000, mean = 0, sd = 1, nu = 2, xi = 1.5) fit = sgedFit(x) print(fit) # Return Value: return() } # ------------------------------------------------------------------------------ test.sgedSlider <- function() { # Try Distribution: # sgedSlider(type = "dist") NA # Try Random Variates: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # sgedSlider(type = "rand") NA # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchSpec.R0000755000176200001440000000777214263246022017626 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: SPECIFICATION: # 'garchSpec' S4: garchSpec Class representation # garchSpec S4: Creates a 'garchSpec' object from scratch # show.garchSpec S4: Print method for an object of class 'garchSpec' ################################################################################ test.garchSpec = function() { # ARCH(1) - use default omega and default alpha[1] garchSpec(model = list()) # ARCH(1) - use default omega and specify alpha garchSpec(model = list(alpha = 0.2)) # ARCH(1) - specify omega and alpha garchSpec(model = list(omega = 3.0e-6, alpha = 0.3)) # AR(1)-ARCH(1) - use default omega/alpha and specify alpha[1] garchSpec(model = list(ar = 0.5)) # AR([1,5])-ARCH(1) - use default omega, specify alpha and subset ar[.] garchSpec(model = list(ar = c(0.5,0,0,0,0.1), alpha = 0.25)) # ARMA(1,2)-ARCH(1) - use default omega/alpha and specify ar[1]/ma[2] garchSpec(model = list(ar = 0.5, ma = c(0.3, -0.3))) # ARMA(2,2)-ARCH(1) use default omega/alpha and specify ar[2]/ma[2] garchSpec(model = list(ar = c(0.5, -0.5), ma = c(0.3,-0.3))) # ARCH(2) - use default omega and specify alpha[2] garchSpec(model = list(alpha = c(0.12, 0.04))) # GARCH(1,1) - use just defaults garchSpec() # GARCH(1,1) - use default omega and specify alpha/beta garchSpec(model = list(alpha = 0.2, beta = 0.7)) # GARCH(1,1) - specify omega/alpha/beta garchSpec(model = list(omega = 1e-6, alpha = 0.1, beta = 0.8)) # GARCH(1,2) - use default omega and specify alpha[1]/beta[2] garchSpec(model = list(alpha = 0.1, beta = c(0.4, 0.4))) # GARCH(2,1) - use default omega and specify alpha[2]/beta[1] garchSpec(model = list(alpha = c(0.12, 0.04), beta = 0.08)) # rsnorm-ARCH(1) - use defaults with skew Normal garchSpec(model = list(dist = 2), cond.dist = "snorm") # rged-ARCH(1) using default omega and alpha[1] garchSpec(model = list(dist = 4), cond.dist = "ged") # rsged-ARCH(1) using default omega and alpha[1] garchSpec(model = list(dist = c(4, 2)), cond.dist = "sged") # rstd-ARCH(1) using default omega and alpha[1] garchSpec(model = list(dist = 4), cond.dist = "std") # rsstd-ARCH(1) using default omega and alpha[1] garchSpec(model = list(dist = c(4, 2)), cond.dist = "sstd") # TS-GARCH(1,1) garchSpec(model = list(delta = 1)) # AR(1)-t-APARCH(2, 1) garchSpec(model = list(mu = 1.0e-4, ar = 0.5, omega = 1.0e-6, alpha = c(0.10, 0.05), gamma = c(0, 0), beta = 0.8, delta = 1.8, dist = c(nu = 4, xi = 0.5)), cond.dist = "sstd") # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.bugfix_6061.R0000755000176200001440000000105614270236345017661 0ustar liggesuserstest.bugfix_6061 <- function() { ## 2022-07-27 GB check fixes related to issue #6061, see NEWS and the source code stopifnot( all( diff(qsnorm(c(0.49, 0.5, 0.51))) > 0) ) stopifnot( all( diff(psnorm(qsged(c(0.49, 0.5, 0.51)))) > 0) ) stopifnot( all( diff(qsstd(c(0.49, 0.5, 0.51))) > 0) ) stopifnot( all( diff(psstd(qsged(c(0.49, 0.5, 0.51)))) > 0) ) stopifnot( all( diff(qsged(c(0.49, 0.5, 0.51))) > 0) ) stopifnot( all( diff(psged(qsged(c(0.49, 0.5, 0.51)))) > 0) ) # Return Value: return() } fGarch/inst/unitTests/runit.garchFit.garch.R0000755000176200001440000000735214263246022020533 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # 'fGARCH' S4: fGARCH Class representation # garchFit Fits GARCH and APARCH processes ################################################################################ # garchFit( # formula, # data, # init.rec = c("mci", "uev"), # delta = 2, # skew = 1, # shape = 4, # cond.dist = c("dnorm", "dsnorm", "dged", "dsged", "dstd", "dsstd"), # include.mean = TRUE, # include.delta = NULL, # include.skew = NULL, # include.shape = NULL, # leverage = NULL, # trace = TRUE, # algorithm = c("sqp", "nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), # control = list(), # title = NULL, # description = NULL, # ...) # ------------------------------------------------------------------------------ test.garchFit.garch11 <- function() { # Use Simulated Series - an Object of class 'ts' ... # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Normal GARCH(1, 1) x = garchSim(n = 250) # Fit: fit = garchFit( ~ garch(1,1), data = x, trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.garch21 <- function() { # Use Simulated Series - an Object of class 'ts' ... # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Normal-GARCH(2, 1) model = list(omega = 1e-06, alpha = c(0.1, 0.2), beta = 0.6) spec = garchSpec(model) x = garchSim(spec = spec, n = 250) # Fit fit = garchFit( ~ garch(2,1), data = x, trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.ar1garch11 <- function() { # Use Simulated Series - an Object of class 'ts' ... # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Normal AR(1)-GARCH(1,1): model = list(omega = 1e-06, ar = -0.1, alpha = c(0.1, 0.2), beta = 0.6) spec = garchSpec(model) x = garchSim(spec = spec, n = 250) # Fit: fit = garchFit(~ arma(1,0) + garch(1,1), data = x, trace = FALSE) print(coef(fit)) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchSim.R0000755000176200001440000001224614263246022017454 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: SIMULATION: # garchSim Simulates a GARCH/APARCH process ################################################################################ test.garchSim.arch = function() { # Simulation of ARCH Models: # ARCH(1) - default omega and alpha spec = garchSpec(model = list()) garchSim(n = 10, spec = spec) # ARCH(1) - default omega spec = garchSpec(model = list(alpha = 0.1)) garchSim(n = 10, spec = spec) # ARCH(1) spec = garchSpec(model = list(omega = 1e-6, alpha = 0.1)) garchSim(n = 10, spec = spec) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchSim.arma.arch = function() { # Simulation of ARMA-ARCH Models: # AR(1)-ARCH(1) spec = garchSpec(model = list(ar = 0.5)) garchSim(n = 10, spec = spec) # AR([1,5])-ARCH(1) spec = garchSpec(model = list(ar = c(0.5, 0, 0, 0 ,0.1))) garchSim(n = 10, spec = spec) # ARMA(1,2)-ARCH(1) spec = garchSpec(model = list(ar = 0.5, ma = c(0.3,-0.3))) garchSim(n = 10, spec = spec) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchSim.dist.arch = function() { # Simulation of non-normal ARCH Models: # rsnorn-ARCH(2) spec = garchSpec(model = list(alpha = c(0.12, 0.04), dist = 2/3), cond.dist = "snorm") garchSim(n = 10, spec = spec) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchSim.garch = function() { # Simulation of GARCH Models: # GARCH(1,1) spec = garchSpec() garchSim(n = 10, spec = spec) # GARCH(1,1) spec = garchSpec(model = list(alpha = 0.1, beta = 0.8)) garchSim(n = 10, spec = spec) # GARCH(1,1) spec = garchSpec(model = list(omega = 1e-6, alpha = 0.1, beta = 0.8)) garchSim(n = 10, spec = spec) # GARCH(1,2) spec = garchSpec(model = list(alpha = 0.1, beta = c(0.4, 0.4))) garchSim(n = 10, spec = spec) # GARCH(2,1) spec = garchSpec(model = list(alpha = c(0.12, 0.04), beta = 0.08)) garchSim(n = 10, spec = spec) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchSim.dist.garch = function() { # Simulation of non-normal GARCH Models: # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Normal - GARCH(1,1) spec = garchSpec(model = list(), cond.dist = "norm") garchSim(n = 10, spec = spec) # Skewed Normal - GARCH(1,1) spec = garchSpec(model = list(parm = 2), cond.dist = "snorm") garchSim(n = 10, spec = spec) # GED - GARCH(1,1) spec = garchSpec(model = list(parm = 4), cond.dist = "ged") garchSim(n = 10, spec = spec) # Skewed GED - GARCH(1,1) spec = garchSpec(model = list(parm = c(4, 2)), cond.dist = "sged") garchSim(n = 10, spec = spec) # Normalized Student t - GARCH(1,1) spec = garchSpec(model = list(parm = 4), cond.dist = "std") garchSim(n = 10, spec = spec) # Skewed Normalized Student t - GARCH(1,1) spec = garchSpec(model = list(parm = c(4, 2)), cond.dist = "sstd") garchSim(n = 10, spec = spec) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchSim.aparch = function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Taylor Schwert Normal GARCH(1,1) spec = garchSpec(list(alpha = 0.1, delta = 1)) garchSim(n = 10, spec = spec) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchHessian.R0000755000176200001440000000302214263246022020306 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # .garchRCDAHessian Computes R coded CDA Hessian matrix # .garchFCDAHessian Computes Fortran coded CDA Hessian matrix # .garchFFDAHessian Computes Fortran coded FDA Hessian matrix ################################################################################ fGarch/inst/unitTests/runit.snorm.R0000644000176200001440000000707214512742310017051 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: SKEW NORMAL DISTRIBUTION: # dsnorm Density for the skew normal Distribution # psnorm Probability function for the skew NORM # qsnorm Quantile function for the skew NORM # rsnorm Random Number Generator for the skew NORM # FUNCTION: PARAMETER ESTIMATION: # snormFit Fit the parameters for a skew Normal distribution # FUNCTION: SLIDER: # snormSlider Displays Normal Distribution and RVS ################################################################################ test.snormDist <- function() { # Normal Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Test: test = fBasics::distCheck("norm", mean = 0, sd = 1, robust = FALSE) print(test) checkTrue(sum(test) == 3) # Skew Normal Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Test: test = fBasics::distCheck("snorm", mean = 0, sd = 1, xi = 1.5, robust = FALSE) print(test) checkTrue(sum(test) == 3) # Return Value: return() } # ------------------------------------------------------------------------------ test.snormFit <- function() { # Parameter Estimation: # snormFit - Fit the parameters for a skew Normal distribution # Skew Normal Distribution: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Series: x = rsnorm(n = 1000, mean = 0, sd = 1, xi = 1.5) # Fit: fit = snormFit(x) print(fit) # Return Value: return() } # ------------------------------------------------------------------------------ test.snormSlider <- function() { # Try Distribution: # snormSlider(type = "dist") NA # Try Random Variates: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # snormSlider(type = "rand") NA # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchFit.dist.R0000755000176200001440000001356314263246022020413 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # 'fGARCH' S4: fGARCH Class representation # garchFit Fits GARCH and APARCH processes ################################################################################ test.garchFit.snorm <- function() { # Conditional Densities: # "norm", "snorm", "ged", "sged", "std", "sstd" # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # skewed normal GARCH(1, 1) model = list(omega = 1e-04, alpha = 0.1, beta = 0.8, skew = 0.9) spec = garchSpec(model, cond.dist = "snorm") x = garchSim(spec = spec, n = 250) # Fit: fit = garchFit( ~ garch(1,1), data = x, include.skew = TRUE, cond.dist = "snorm", trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.snorm.fixed <- function() { # Conditional Densities: # "norm", "snorm", "ged", "sged", "std", "sstd" # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # skewed normal GARCH(1, 1) model = list(omega = 1e-04, alpha = 0.1, beta = 0.8, skew = 0.9) spec = garchSpec(model, cond.dist = "snorm") x = garchSim(spec = spec, n = 250) # Fit: Skewed Normal GARCH(1, 1) with fixed skew ... fit = garchFit(~garch(1,1), data = x, skew = 0.9, include.skew = FALSE, cond.dist = "snorm", trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.ged <- function() { # Conditional Densities: # "norm", "snorm", "ged", "sged", "std", "sstd" # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # GED-GARCH(1, 1) model = list(omega = 1e-06, alpha = 0.1, beta = 0.8, shape = 2) spec = garchSpec(model, cond.dist = "ged") x = garchSim(spec = spec, n = 250) # Fit: fit = garchFit(~garch(1,1), data = x, include.shape = TRUE, cond.dist = "ged", trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.sged <- function() { # Conditional Densities: # "norm", "snorm", "ged", "sged", "std", "sstd" # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Skewed GED-GARCH(1, 1) model = list(omega = 1e-05, alpha = 0.1, beta = 0.8, shape = 4, skew = 0.9) spec = garchSpec(model, cond.dist = "sged") x = garchSim(spec = spec, n = 250) # Fit fit = garchFit( ~ garch(1,1), data = x, include.shape = TRUE, include.skew = TRUE, cond.dist = "sged", trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.std <- function() { # Conditional Densities: # "norm", "snorm", "ged", "sged", "std", "sstd" # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Student t-GARCH(1, 1) model = list(omega = 1e-06, alpha = 0.1, beta = 0.8, shape = 5) spec = garchSpec(model, cond.dist = "std") x = garchSim(spec = spec, n = 250) # Fi fit = garchFit( ~ garch(1,1), data = x, include.shape = TRUE, cond.dist = "std", trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchFit.sstd <- function() { # Conditional Densities: # "norm", "snorm", "ged", "sged", "std", "sstd" # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Skewed Student t-GARCH(1, 1) model = list(omega = 1e-06, alpha = 0.1, beta = 0.8, shape = 5, skew = 0.9) spec = garchSpec(model, cond.dist = "std") x = garchSim(spec = spec, n = 250) # Fit: fit = garchFit( ~ garch(1,1), data = x, include.shape = TRUE, include.skew = TRUE, cond.dist = "sstd", trace = FALSE) print(coef(fit)) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchFit.aparch.R0000755000176200001440000001023614263246022020700 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # 'fGARCH' S4: fGARCH Class representation # garchFit Fits GARCH and APARCH processes ################################################################################ # garchFit( # formula, # data, # init.rec = c("mci", "uev"), # delta = 2, # skew = 1, # shape = 4, # cond.dist = c("dnorm", "dsnorm", "dged", "dsged", "dstd", "dsstd"), # include.mean = TRUE, # include.delta = NULL, # include.skew = NULL, # include.shape = NULL, # leverage = NULL, # trace = TRUE, # algorithm = c("sqp", "nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), # control = list(), # title = NULL, # description = NULL, # ...) # ------------------------------------------------------------------------------ test.aparch11 <- function() { # Use Simulated Series - an Object of class 'ts' ... # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Leveraged normal APARCH(1, 1) model = list(omega = 1e-06, alpha = 0.1, beta = 0.8, gamma = 0.1) spec = garchSpec(model) x = garchSim(spec, n = 250) # Fit: fit = garchFit(x ~ garch(1,1), data = x, leverage = TRUE, trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.aparch11delta <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Leveraged normal APARCH(1, 1) delta = 1.5 model = list(omega = 1e-05, alpha = 0.1, beta = 0.8, gamma = 0.1, delta = 1.5) spec = garchSpec(model) x = garchSim(spec, n = 250) print(var(x)) # Fit: fit = garchFit(x ~ garch(1,1), data = x, leverage = TRUE, include.delta = TRUE, delta = 2, trace = FALSE) print(coef(fit)) # Return Value: return() } # ------------------------------------------------------------------------------ test.ar1aparch21 <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Leveraged normal AR(1)-APARCH(2, 1) delta = 1 model = list(omega = 1e-06, ar = -0.1, alpha = c(0.1, 0.2), beta = 0.6, delta = 1) spec = garchSpec(model) x = garchSim(spec, n = 250) # Taylor Plot: taylor <- fBasics::teffectPlot(x) init.delta = mean(taylor$maxDelta) init.delta ## fit = garchFit(x ~ ar(1) + garch(2,1), data = x, include.delta = TRUE, ## delta = init.delta, trace = FALSE) ## print(coef(fit)) ## Error in solve.default(fit$hessian) : ## Lapack routine dgesv: system is exactly singular ## CHECK !!! # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.garchFit.R0000755000176200001440000000625514263246022017451 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: PARAMETER ESTIMATION: # 'fGARCH' S4: fGARCH Class representation # garchFit Fits GARCH and APARCH processes ################################################################################ # garchFit( # formula, # data, # init.rec = c("mci", "uev"), # delta = 2, # skew = 1, # shape = 4, # cond.dist = c("dnorm", "dsnorm", "dged", "dsged", "dstd", "dsstd"), # include.mean = TRUE, # include.delta = NULL, # include.skew = NULL, # include.shape = NULL, # leverage = NULL, # trace = TRUE, # algorithm = c("sqp", "nlminb", "lbfgsb", "nlminb+nm", "lbfgsb+nm"), # control = list(), # title = NULL, # description = NULL, # ...) # ------------------------------------------------------------------------------ test.garchInputSeries <- function() { # Numeric Vector RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") # Simulate normal GARCH(1, 1) numeric Vector: model = list(omega = 1e-06, alpha = 0.1, beta = 0.8) spec = garchSpec(model) print(spec) N = 10 # UNIVARIATE: # A numeric Vector: x.vec = as.vector(100*garchSim(spec, N)) print(head(x.vec)) x.tS = timeSeries::dummyDailySeries(matrix(x.vec), units = "GARCH11") print(head(x.tS)) # x.zoo = zoo(as.vector(x.vec), order.by = as.Date(rownames(x.tS))) # print(head(x.zoo)) x.ts = ts(x.vec) print(head(x.ts)) # MULTIVARIATE: # A numeric matrix: X.mat = cbind(GARCH11 = x.vec, R = rnorm(N)) print(head(X.mat)) X.tS = timeSeries::dummyDailySeries(X.mat, units = c("GARCH11", "R")) print(head(X.tS)) # X.zoo = zoo(X.mat, order.by = as.Date(rownames(x.tS))) # print(head(X.zoo)) X.mts = ts(X.mat) print(head(X.mts)) # Return Value: return() } ################################################################################ fGarch/inst/unitTests/runit.predict-methods.R0000755000176200001440000000435214263246022021011 0ustar liggesusers # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU Library General # Public License along with this library; if not, write to the # Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # Copyrights (C) # for this R-port: # 1999 - 2008, Diethelm Wuertz, Rmetrics Foundation, GPL # Diethelm Wuertz # info@rmetrics.org # www.rmetrics.org # for the code accessed (or partly included) from other R-ports: # see R's copyright and license files # for the code accessed (or partly included) from contributed R-ports # and other sources # see Rmetrics's copyright file ################################################################################ # FUNCTION: FORECASTING: # garchKappa Computes Expection for APARCH Models # .funE Internal function used by kappa() ################################################################################ test.predict.methods <- function() { # RVs: RNGkind(kind = "Marsaglia-Multicarry", normal.kind = "Inversion") set.seed(4711, kind = "Marsaglia-Multicarry") print(NA) # Return Value: return() } # ------------------------------------------------------------------------------ test.garchKappa <- function() { # garchKappa( # cond.dist = c("norm", "ged", "std", "snorm", "sged", "sstd"), # gamma = 0, delta = 2, skew = NA, shape = NA) garchKappa() garchKappa("norm", gamma = 0.3) garchKappa("ged", skew = 0.95, shape = 1) # CHECK !!! garchKappa("dstd", skew = 0.95, shape = 1) # Return Value: return() } ################################################################################ fGarch/inst/NEWS.Rd0000644000176200001440000002724314556735624013515 0ustar liggesusers% Convert this to NEWS.md: % 1. inst/NEWS.Rd to NEWS.html: % tools:::Rd2HTML("inst/NEWS.Rd", "NEWS.html") % % 2. NEWS.html to NEWS.md (https://www.r-bloggers.com/2018/12/rstudio-pandoc-html-to-markdown/) % rmarkdown::pandoc_convert("NEWS.html", to = "markdown_strict", output = "NEWS.md") % % 3. Manually remove everything up to the first line containing: % ## CHANGES in fGarch VERSION ... % % 4. Bring the markdown sections one level up, i.e. remove one '#' from % each section level. For example using regex ^#\(#+\) with replacement value \1 \name{NEWS} \title{News for \R Package \pkg{fGarch}} \encoding{UTF-8} \section{CHANGES in fGarch VERSION 4032.91 (2024-02-02, svn r6436--r????)}{ \itemize{ \item added computation of Value-at-Risk (VaR) and expected shortfall (ES) for fitted GARCH and APARCH models (in-sample and in the predict method). Just use something like `Var(fitted_object)`, `ES(fitted_object)` or `predict(fitted_object, ..., p_loss = 0.05)`. } } \section{CHANGES in fGarch VERSION 4022.90 (2023-10-15, svn r6333--r6435)}{ \itemize{ \item added \code{"fGARCH"} method for `stats::tsdiag`. The method produces diagnostic plot for fitted GARCH/APARCH models and computes some diagnostic tests. The plots can be chosen interactively and/or via arguments. The test results are in the returned value. The method is in development in that more plots may be made available and additional tests included in the returned value. \item refactored the \code{"fGARCH"} method for 'summary' to return an object from S3 class 'summary_fGARCH' equipped with a 'print' method. The printout is the same as before, except that now the numbers in the statistics column for the residual diagnostics are aligned on the decimal point (previously they were left-aligned due to a buglet). \item the \code{"fGARCH"} method for \code{fitted} was returning the data, not the fitted values. Fixes issue 6789, reported by Kouhei Hashinokuchi (hakoshie). \item the help pages for the \code{"fGARCH"} methods for \code{fitted()} and \code{residuals()} were stating that the returned results have the same class as the input time series. Actually, they return numeric vectors. (todo?: to make the returned values as previously documented, \code{garchFit()} would need to put the original data or the necessary information in the fitted object, e.g., \code{object@fit$data}. \item some tests were using deprecated \code{fBasics::.distCheck()} (notice the leading dot). Replaced such calls with the equivalent \code{fBasics::distCheck()}. } } \section{CHANGES in fGarch VERSION 4022.89 (2022-11-05, from svn r6316--r6326)}{ \itemize{ \item in \code{absMoments}, the absolute moments for the standardized Student-t distribution were wrong. \item in README, linked to the paper by Wuertz et al. \item substantially revised the documentation and filled gaps in it. \item removed the functions with suffix `_orig` which were kept temporarilly after the bug fix in v4021.87 since there were no reported problems with the fix. } } \section{CHANGES in fGarch VERSION 4021.88 (2022-09-28, svn r6276)}{ \itemize{ \item require Matrix (>= 1.5-0) to avoid problems for users who have earlier versions of Matrix on their devices (thanks to Mikael Jagan for checking for not strict enough dependency on Matrix and alerting the maintainer). } } \section{CHANGES in fGarch VERSION 4021.87 (2022-08-06, svn r6215--r6265)}{ \subsection{NEW MAINTAINER}{ \itemize{ \item Georgi N. Boshnakov } } \subsection{VERSION NUMBERS}{ \itemize{ \item We continue to use the traditional Rmetrics scheme for numbering the versions of the package as Mmmr.n, where 'M' is the current major R version at the time of submission of the package to CRAN, 'mm' is the minor one and 'r' is the revision. 'n' is the sequential number of the CRAN submission of the package. For example, this release has version 4021.87 since it was released when R 4.2.1 was current and 'n' in the previous version was 86. } } \subsection{BUG FIXES}{ Fixed issue 6061 raised by William Scott, who also supplied examples. \itemize{ \item The quantile function, \code{qsnorm}, was wrong around 0.5. The error was in \code{.qsnorm}. For now its version before the fix is kept as \code{.qsnorm_orig}. Basically, branching was done w.r.t. \eqn{p = 0.5}, which is correct only for the symmetric case, \eqn{\xi = 1}, and should be \eqn{1/(1+\xi^2)} instead. More details in the source code. The error was affecting the central part of the distrbution with the interval becoming larger for \eqn{\xi} further away from 1. \item The cdf, \code{psnorm}, had an error at a single point, coinciding with the wrong value for \eqn{p = 0.5} returned by \code{qsnorm(0.5)} before the fix. The result was that \code{psnorm(qsnorm(0.5))} was returning 0.5, falsely giving reassurance that \code{qsnorm(0.5)} was correct. \item Not mentioned in issue 6061 but the same problems held for the other skewed distributions: \code{qsstd}, \code{psstd}, \code{qsged}, \code{psged}. The original versions of the relevant internal functions are kept for now with a suffix \code{_orig}, as above: \code{qsstd_orig}, \code{psstd_orig}, \code{qsged_orig}, \code{psged_orig}. } } \subsection{Documentation}{ \itemize{ \item Edited the documentation of \code{"garchSpec"} and \code{garchSim}. It was somewhat incomplete and contained leftovers, apparently from old versions of the functions. \item Documented the datasets. Previously the help page for them was a placeholder, without the names of the available datasets. There is no information about the time span of the data or how the returns were calculated. } } } \section{CHANGES in fGarch VERSION 4021.86 (2022-06-23, svn r6188)}{ \subsection{NEW MAINTAINER}{ \itemize{ \item Tobias Setz } } \subsection{Notes}{ \itemize{ \item This is a CRAN release of version 4001.1, with trivial changes in \file{DESCRIPTION}. } } } \section{CHANGES in fGarch VERSION 4001.1 (2022-06-23, svn r6184--r6185)}{ \subsection{NEW MAINTAINER}{ \itemize{ \item ad interim: Martin Maechler } } \subsection{NEW FEATURES}{ \itemize{ \item Packages \CRANpkg{timeSeries}, \CRANpkg{timeDate} and \CRANpkg{fBasics} are no longer in \code{Depends}, but only in \code{Imports} and hence no longer automatically attached to the \code{search()} path whenever \pkg{fGarch} is. This may require updates in your code, e.g., adding \preformatted{ stopifnot(require("timeSeries"))} as it has been done in our own \pkg{fGarch}'s examples and tests. \item \code{.gogarchFit()} is at least \emph{mentioned} in the documentation. } } \subsection{BUG FIXES}{ \itemize{ \item Added registration of compiled functionality for speed up and as good practice. \item Removed all \code{Depends:} entries and checked exactly which parts of packages, notably \pkg{fBasics}, \pkg{timeDate}, and \pkg{timeSeries}, are needed and imported only these. \item Eliminated warning about 'length > 1' character formula in \code{garchFit()}, i.e., \code{.garchFit()}. \item Replaced the error-prone checking for `class()` equality by `inherits(*, )`. } } \subsection{Misc}{ \itemize{ \item Exporting practically everything seems \dQuote{wrong} (according to MM): Several \code{.} functions have \emph{no} documentation and hence should either be (renamed and) documented or no longer be exported. \item a \code{data} argument should never have a default: hence removed from \code{garchFit()}. } } } \section{CHANGES in fGarch, VERSION 3042.83.2 (2020-03-07, CRAN team)}{ \subsection{Misc}{ \itemize{ % MM: add by comparing the directory trees (after "untar") % GNB: added by looking at the commit at https://github.com/cran/fGarch/ % \item in \file{dist-norm.Rd}, removed the description of argument \code{...}, which is not in the argument list of any function described there. } } } %% CRAN Versions of fGarch .../CRAN/src/contrib/Archive/fGarch -- 22.Jun 2022 %% Size Date tarball-filename %% ------ ------------ ---------------------- %% 143455 7. Mar 2020 fGarch_3042.83.2.tar.gz Packaged: 2020-03-07 10:25:26 UTC; hornik %% - - - - - - - - - - - - - - - - - - - - - - %% 145810 31. Jan 2019 fGarch_3042.83.1.tar.gz Packaged: 2019-01-31 16:42:21 UTC; hornik %% 160314 16. Nov 2017 fGarch_3042.83.tar.gz Packaged: 2017-11-16 17:28:34 UTC; Tobias Setz %% 160484 15. Aug 2016 fGarch_3010.82.1.tar.gz Packaged: 2016-08-15 09:24:21 UTC; ripley %% 152081 1. May 2013 fGarch_3010.82.tar.gz Packaged: 2013-04-30 20:07:14 UTC; yankee (Yohan Ch) \section{CHANGES in fGarch, VERSION 3042.83.1 (2019-01-31, CRAN team)}{ \subsection{Misc}{ % MM: add by comparing the directory trees (after "untar") % GNB: added by looking at the commit at https://github.com/cran/fGarch/ % \itemize{ \item in \file{NAMESPACE} and \file{R/methods-plot.R} renamed functions \code{.plot.garch.1}, \ldots, \code{.plot.garch.13} to \code{.plot.garch_1}, \ldots, \code{.plot.garch_13}. \item compressed datasets \file{data/dem2gbp.csv} and \file{data/sp500dge.csv} to \file{data/dem2gbp.csv.bz2} \file{data/sp500dge.csv.bz2}, respectively. } } } \section{CHANGES in fGarch, VERSION 3042.83 (2017-11-16, svn r...)}{ \subsection{Misc}{ \itemize{ \item Startup message removed \item Incorporate fixes by CRAN team (Brian Ripley?) \item Checks and adaptions for R 3.4.2, e.g., \file{DESCRIPTION}, ... } } } \section{CHANGES in fGarch, VERSION 3010.82.1 (2016-08-14, CRAN team.)}{ \subsection{Misc}{ \itemize{ \item in \file{NAMESPACE}, import (selectively) from \pkg{utils}. \item changed a couple of calls to \code{Matrix()} from package \pkg{Matrix} and \code{fastICA()} from \pkg{fastICA} to the fully qualified forms \code{Matrix::Matrix()} and \code{fastICA::fastICA}. \item removed some flag settings in \file{Makevars}. \item in \file{math.f}, move a \code{DATA} command out of the body of an \code{"if"} block putting it towards the beginning of the file. } } } \section{CHANGES in fGarch, VERSION 3010.82 (2013-04-30, svn r5509) -- and earlier}{ \subsection{ChangeLog}{ \itemize{ \item Changes up to April 2013, by Yohan Chalabi, Diethelm Wuertz, Pierre Chausse and Martin Maechler are all in file \file{ChangeLog}. % = ../ChangeLog } } } %% CRAN-Archive for fGarch -- older ones %% Size Date tarball-filename %% ------ ------------ ---------------------- %% 152081 1. Mai 2013 fGarch_3010.82.tar.gz %% 151484 18. Sep 2012 fGarch_2150.81.tar.gz %% 199196 4. Jun 2012 fGarch_2110.80.1.tar.gz %% 198030 10. Nov 2009 fGarch_2110.80.tar.gz %% 190133 28. Sep 2009 fGarch_2100.79.tar.gz %% 183635 20. Apr 2009 fGarch_2100.78.tar.gz %% 183616 16. Apr 2009 fGarch_290.77.tar.gz %% 178881 28. Jan 2009 fGarch_290.76.tar.gz %% 177761 27. Okt 2008 fGarch_280.75.tar.gz %% 177703 25. Okt 2008 fGarch_280.74.tar.gz %% 177695 23. Okt 2008 fGarch_280.73.tar.gz %% 127399 8. Okt 2007 fGarch_260.72.tar.gz %% 127396 2. Okt 2007 fGarch_260.71.tar.gz