使用RStudio調試(debug)基礎學習(二)和fGarch包中的garchFit函數估計GARCH模型的原理和源碼



一、 garchFit 函數的參數---------------------------------------------
algorithm
a string parameter that determines the algorithm used for maximum likelihood estimation.
設定最大似然估計所用的算法
cond.dist
a character string naming the desired conditional distribution. Valid values are "dnorm", "dged", "dstd", "dsnorm", "dsged", "dsstd" and "QMLE". The default value is the normal distribution. See Details for more information.
條件擾動(新息)的分布
control
control parameters, the same as used for the functions from nlminb, and 'bfgs' and 'Nelder-Mead' from optim.

data
an optional timeSeries or data frame object containing the variables in the model. If not found in data, the variables are taken from environment(formula), typically the environment from which armaFit is called. If 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(被忽略).
包含變量的 timeSeries或者數據框類型,如果打他中沒有這些變量,則將去環境( formula )中找, armaFit的環境通常也會被調用。如果是單變量序列,則序列被轉為數值向量, formula那些就被忽略。

delta
a numeric value, the exponent 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 include.delta=FALSE.
變量定義的delta指數?

description
a character string which allows for a brief description.
簡短描述

formula
formula object describing the mean and variance equation of the ARMA-GARCH/APARCH model. A pure GARCH(1,1) model is selected when e.g. formula=~garch(1,1). To specify for example an ARMA(2,1)-APARCH(1,1) use formula = ~arma(2,1)+apaarch(1,1).
描述 ARMA-GARCH/APARCH模型的均值方程和波動率方程的對象
~garch(1,1)  ——表示 GARCH(1,1)  模型
~arma(2,1)+apaarch(1,1) ——表示 ARMA(2,1)-APARCH(1,1)模型


gamma
APARCH leverage parameter entering into the formula for calculating the expectation value.
杠桿參數

hessian
a string denoting how the Hessian matrix should be evaluated, either hessian ="rcd", or "ropt", the default, "rcd" is a central difference approximation implemented in R and "ropt" use the internal R function optimhess.
海賽矩陣被計算的方式,默認為 rcd(中心差分近似?)

include.delta
a logical flag which determines if the parameter for the recursion equation delta will be estimated or not. If include.delta=FALSE then the shape parameter will be kept fixed during the process of parameter optimization.
邏輯標志,表示迭代法處delta參數是否被估計

include.mean
this flag determines if the parameter for the mean will be estimated or not. If include.mean=TRUE this will be the case, otherwise the parameter will be kept fixed durcing(應該是during) the process of parameter optimization.
include.mean=TRUE表示均值是否被估計,否則均值參數在參數最優化過程中將是固定的


include.shape
a logical flag which determines if the parameter for the shape of the conditional distribution will be estimated or not. If include.shape=FALSE then the shape parameter will be kept fixed during the process of parameter optimization.
一個參數,決定條件分布的自由度shape是否被估計
include.shape=FALSE則在參數最優化過程中, t分布的自由度shape是固定的


include.skew
a logical flag which determines if the parameter for the skewness of the conditional distribution will be estimated or not. If include.skew=FALSE then the skewness parameter will be kept fixed during the process of parameter optimization.
skew=FALSE則shew(偏度)在參數最優化過程中是固定的

init.rec
a character string indicating the method how to initialize the mean and varaince recursion relation.
一個字符串,指明如何初始化均值和方差迭代關系。
取值呢?
"mci",  "uev"

leverage
a logical flag for APARCH models. Should the model be leveraged? By default leverage=TRUE.
是否帶杠桿

shape
a numeric value, the shape parameter of the conditional distribution.
條件分布的自由度值

skew
a numeric value, the skewness parameter of the conditional distribution.
條件分布的偏度

title
a character string which allows for a project title.
標題

trace
a logical flag. Should the optimization process of fitting the model parameters be printed? By default trace=TRUE.
參數最優化過程是否被打印出來。
...
additional arguments to be passed.

二、查看數據----------------------------------------------
雙擊da(相當於View(da)),可以看到數據是這樣的

經過對數轉化后的收益率,是我們建模用的原始數據。
   
   
   
           
  1. intc=log(da$intc+1)
  2. intc
  3.   [1]  0.0099998346 -0.1500127529  0.0670640792
  4.   [4]  0.0829486352 -0.1103484905  0.1251628488
  5.   [7]  0.4855078158  0.1112255825  0.2109235908
  6. ..........

     
     
     
             
  1. library(fGarch)
  2. da=read.table("m-intcsp7309.txt",header=T)
  3. intc=log(da$intc+1)
  4. m4=garchFit(~1+garch(1,1),data=intc)
  5. summary(m4)
  6. Title:
  7.  GARCH Modelling 
  8. Call:
  9.  garchFit(formula = ~1 + garch(1, 1), data = intc) 
  10. Mean and Variance Equation:
  11.  data ~ 1 + garch(1, 1)
  12. <environment: 0x000000001d475658>
  13.  [data = intc]
  14. Conditional Distribution:
  15.  norm 
  16. Coefficient(s):
  17.         mu       omega      alpha1       beta1  
  18. 0.01126568  0.00091902  0.08643831  0.85258554  
  19. Std. Errors:
  20.  based on Hessian 
  21. Error Analysis:
  22.         Estimate  Std. Error  t value Pr(>|t|)    
  23. mu     0.0112657   0.0053931    2.089  0.03672 *  
  24. omega  0.0009190   0.0003888    2.364  0.01808 *  
  25. alpha1 0.0864383   0.0265439    3.256  0.00113 ** 
  26. beta1  0.8525855   0.0394322   21.622  < 2e-16 ***
  27. ---
  28. Signif. codes:  
  29. 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 1
  30. Log Likelihood:
  31.  312.3307    normalized:  0.7034475 
  32. Description:
  33.  Fri Jan 27 21:49:06 2017 by user: xuan 
  34. Standardised Residuals Tests:
  35.                                 Statistic p-Value     
  36.  Jarque-Bera Test   R    Chi^2  174.904   0           
  37.  Shapiro-Wilk Test  R    W      0.9709615 1.030282e-07
  38.  Ljung-Box Test     R    Q(10)  8.016844  0.6271916   
  39.  Ljung-Box Test     R    Q(15)  15.5006   0.4159946   
  40.  Ljung-Box Test     R    Q(20)  16.41549  0.6905368   
  41.  Ljung-Box Test     R^2  Q(10)  0.8746345 0.9999072   
  42.  Ljung-Box Test     R^2  Q(15)  11.35935  0.7267295   
  43.  Ljung-Box Test     R^2  Q(20)  12.55994  0.8954573   
  44.  LM Arch Test       R    TR^2   10.51401  0.5709617   
  45. Information Criterion Statistics:
  46.       AIC       BIC       SIC      HQIC 
  47. -1.388877 -1.351978 -1.389037 -1.374326 


三、主要的函數結構 ----------------------------------------------
garchFit函數
         match.xxx函數....
         各種判斷可以忽略
         .garchArgsParser
         .garchFit函數    
         ans最終的返回結果
         
         .garchFit函數
                       .garchInitSeries函數
                       .garchInitParameters函數
                       .garchOptimizeLLH函數
                                    .garchRnlminb函數
                                              nlminb函數
                                    .garchLLH函數
                                              .Fortran("garchllh")


四、調試 ----------------------------------------------

(4.0)garchFit函數
    
    
    
            
  1. function (formula = ~garch(1, 1), data = dem2gbp, init.rec = c("mci", 
  2.   "uev"), delta = 2, skew = 1, shape = 4, cond.dist = c("norm", 
  3.   "snorm", "ged", "sged", "std", "sstd", "snig", "QMLE"), 
  4.   include.mean = TRUE, include.delta = NULL, include.skew = NULL, 
  5.   include.shape = NULL, leverage = NULL, trace = TRUE, algorithm = c("nlminb", 
  6.     "lbfgsb", "nlminb+nm", "lbfgsb+nm"), hessian = c("ropt", 
  7.     "rcd"), control = list(), title = NULL, description = NULL, 
  8.   ...) 
  9. {
  10.   DEBUG = FALSE
  11.   init.rec = match.arg(init.rec)
  12.   cond.dist = match.arg(cond.dist)
  13.   hessian = match.arg(hessian)
  14.   algorithm = match.arg(algorithm)
  15.   CALL = match.call()
  16.   Name = capture.output(substitute(data))
  17.   if (is.character(data)) {
  18.     eval(parse(text = paste("data(", data, ")")))
  19.     data = eval(parse(text = data))
  20.   }
  21.   data <- as.data.frame(data)
  22.   if (isUnivariate(data)) {
  23.     colnames(data) <- "data"
  24.   }
  25.   else {
  26.     uniqueNames = unique(sort(colnames(data)))
  27.     if (is.null(colnames(data))) {
  28.       stop("Column names of data are missing.")
  29.     }
  30.     if (length(colnames(data)) != length(uniqueNames)) {
  31.       stop("Column names of data are not unique.")
  32.     }
  33.   }
  34.   if (length(formula) == 3 && isUnivariate(data)) 
  35.     formula[2] <- NULL
  36.   if (length(formula) == 2) {
  37.     if (isUnivariate(data)) {
  38.       formula = as.formula(paste("data", paste(formula, 
  39.         collapse = " ")))
  40.     }
  41.     else {
  42.       stop("Multivariate data inputs require lhs for the formula.")
  43.     }
  44.   }
  45.   robust.cvar <- (cond.dist == "QMLE")
  46.   args = .garchArgsParser(formula = formula, data = data, 
  47.     trace = FALSE)
  48.   if (DEBUG) 
  49.     print(list(formula.mean = args$formula.mean, formula.var = args$formula.var, 
  50.       series = args$series, init.rec = init.rec, delta = delta, 
  51.       skew = skew, shape = shape, cond.dist = cond.dist, 
  52.       include.mean = include.mean, include.delta = include.delta, 
  53.       include.skew = include.skew, include.shape = include.shape, 
  54.       leverage = leverage, trace = trace, algorithm = algorithm, 
  55.       hessian = hessian, robust.cvar = robust.cvar, control = control, 
  56.       title = title, description = description))
  57.   ans = .garchFit(formula.mean = args$formula.mean, formula.var = args$formula.var, 
  58.     series = args$series, init.rec, delta, skew, shape, 
  59.     cond.dist, include.mean, include.delta, include.skew, 
  60.     include.shape, leverage, trace, algorithm, hessian, 
  61.     robust.cvar, control, title, description, ...)
  62.   ans@call = CALL
  63.   attr(formula, "data") <- paste("data = ", Name, sep = "")
  64.   ans@formula = formula
  65.   ans
  66. }

以下四句都是對傳入的參數是否math(合法、規范)做檢驗的
    
    
    
            
  1.   init.rec = match.arg(init.rec)
  2.   cond.dist = match.arg(cond.dist)
  3.   hessian = match.arg(hessian)
  4.   algorithm = match.arg(algorithm)
  5.   CALL = match.call()
我們可以按下 進入 函數查看
截取match.arg函數中的幾句作說明:
       
       
       
               
  1. formal.args <- formals(sys.function(sys.parent()))
  2. .......................................
  3. if (identical(arg, choices)) 
  4.       return(arg[1L])
formal argument形參
如果傳入和默認的一樣,說明沒有傳入,就返回第一個作為默認值
可以點擊 跳出函數
 

(4.0.1) .garchArgsParser函數
     
     
     
             
  1. args = .garchArgsParser(formula = formula, data = data, trace = FALSE)
      
      
      
              
  1. function (formula, data, trace = FALSE)
  2. {
  3. allVars = unique(sort(all.vars(formula)))
  4. allVarsTest = mean(allVars %in% colnames(data))
  5. if (allVarsTest != 1) {
  6. print(allVars)
  7. print(colnames(data))
  8. stop("Formula and data units do not match.")
  9. }
  10. formula.lhs = as.character(formula)[2]
  11. mf = match.call(expand.dots = FALSE)
  12. if (trace) {
  13. cat("\nMatched Function Call:\n ")
  14. print(mf)
  15. }
  16. m = match(c("formula", "data"), names(mf), 0)
  17. mf = mf[c(1, m)]
  18. mf[[1]] = as.name(".garchModelSeries")
  19. mf$fake = FALSE
  20. mf$lhs = TRUE
  21. if (trace) {
  22. cat("\nModelSeries Call:\n ")
  23. print(mf)
  24. }
  25. x = eval(mf, parent.frame())
  26. if (trace)
  27. print(x)
  28. x = as.vector(x[, 1])
  29. names(x) = rownames(data)
  30. if (trace)
  31. print(x)
  32. allLabels = attr(terms(formula), "term.labels")
  33. if (trace) {
  34. cat("\nAll Term Labels:\n ")
  35. print(allLabels)
  36. }
  37. if (length(allLabels) == 2) {
  38. formula.mean = as.formula(paste("~", allLabels[1]))
  39. formula.var = as.formula(paste("~", allLabels[2]))
  40. }
  41. else if (length(allLabels) == 1) {
  42. formula.mean = as.formula("~ arma(0, 0)")
  43. formula.var = as.formula(paste("~", allLabels[1]))
  44. }
  45. if (trace) {
  46. cat("\nMean Formula:\n ")
  47. print(formula.mean)
  48. cat("\nVariance Formula:\n ")
  49. print(formula.var)
  50. }
  51. ans <- list(formula.mean = formula.mean, formula.var = formula.var,
  52. formula.lhs = formula.lhs, series = x)
  53. ans
  54. }
提下這個函數里面的一些信息:
data是數據
%in%運算符就是math的作用 ?' %in% '
x就是原始數據
(需要特別說明的是,x是從data里取出來后as.vector的,被轉化為向量后,會四舍五入顯示了,所以如果直接在environment pane中查看有點不橡原始數據,比如intc的第一個值是 0.0099998346 ,而這里x的值顯示是0.01)
函數運行到最后一行的時候, environment pane中的部分信息。
(方程的基本形式已經被解析出來了)

(4.0.2) .garchFit函數
    
    
    
            
  1. ans = .garchFit(formula.mean = args$formula.mean, formula.var = args$formula.var, 
  2.     series = args$series, init.rec, delta, skew, shape, 
  3.     cond.dist, include.mean, include.delta, include.skew, 
  4.     include.shape, leverage, trace, algorithm, hessian, 
  5.     robust.cvar, control, title, description, ...)
我們為什么分析了 .garchArgsParser 這個解析函數,就是因為 .garchFit 函數用到的許多參數都是從args中取出的。
另外提到一下,帶.開頭的函數和變量都是內部的,不會直接顯示出來的。
如果是變量名.xxx,這樣的形式,那么需要我們自己在控制台輸入 .xxx查看,不能在envir pane中查看。
如果要查看內部函數,則
單擊可以切換到對應的源代碼和變量
可以選擇環境,一般情況是在global environment
.garchFit函數的源碼
     
     
     
             
  1. function (formula.mean = ~arma(0, 0), formula.var = ~garch(1,
  2. 1), series, init.rec = c("mci", "uev"), delta = 2, skew = 1,
  3. shape = 4, cond.dist = c("norm", "snorm", "ged", "sged",
  4. "std", "sstd", "QMLE"), include.mean = TRUE, include.delta = NULL,
  5. include.skew = NULL, include.shape = NULL, leverage = NULL,
  6. trace = TRUE, algorithm = c("sqp", "nlminb", "lbfgsb", "nlminb+nm",
  7. "lbfgsb+nm"), hessian = c("ropt", "rcd"), robust.cvar,
  8. control = list(), title = NULL, description = NULL, ...)
  9. {
  10. DEBUG <- FALSE
  11. if (DEBUG)
  12. print("Formula Specification ...")
  13. fcheck = rev(all.names(formula.mean))[1]
  14. if (fcheck == "ma") {
  15. stop("Use full formula: arma(0,q) for ma(q)")
  16. }
  17. else if (fcheck == "ar") {
  18. stop("Use full formula expression: arma(p,0) for ar(p)")
  19. }
  20. if (DEBUG)
  21. print("Recursion Initialization ...")
  22. if (init.rec[1] != "mci" & algorithm[1] != "sqp") {
  23. stop("Algorithm only supported for mci Recursion")
  24. }
  25. .StartFit <- Sys.time()
  26. if (DEBUG)
  27. print("Generate Control List ...")
  28. con <- .garchOptimizerControl(algorithm, cond.dist)
  29. con[(namc <- names(control))] <- control
  30. if (DEBUG)
  31. print("Initialize Time Series ...")
  32. data <- series
  33. scale <- if (con$xscale)
  34. sd(series)
  35. else 1
  36. series <- series/scale
  37. .series <- .garchInitSeries(formula.mean = formula.mean,
  38. formula.var = formula.var, cond.dist = cond.dist[1],
  39. series = series, scale = scale, init.rec = init.rec[1],
  40. h.start = NULL, llh.start = NULL, trace = trace)
  41. .setfGarchEnv(.series = .series)
  42. if (DEBUG)
  43. print("Initialize Model Parameters ...")
  44. .params <- .garchInitParameters(formula.mean = formula.mean,
  45. formula.var = formula.var, delta = delta, skew = skew,
  46. shape = shape, cond.dist = cond.dist[1], include.mean = include.mean,
  47. include.delta = include.delta, include.skew = include.skew,
  48. include.shape = include.shape, leverage = leverage,
  49. algorithm = algorithm[1], control = con, trace = trace)
  50. .setfGarchEnv(.params = .params)
  51. if (DEBUG)
  52. print("Select Conditional Distribution ...")
  53. .setfGarchEnv(.garchDist = .garchSetCondDist(cond.dist[1]))
  54. if (DEBUG)
  55. print("Estimate Model Parameters ...")
  56. .setfGarchEnv(.llh = 1e+99)
  57. .llh <- .getfGarchEnv(".llh")
  58. fit = .garchOptimizeLLH(hessian, robust.cvar, trace)
  59. if (DEBUG)
  60. print("Add to fit ...")
  61. .series <- .getfGarchEnv(".series")
  62. .params <- .getfGarchEnv(".params")
  63. names(.series$h) <- NULL
  64. fit$series = .series
  65. fit$params = .params
  66. if (DEBUG)
  67. print("Retrieve Residuals and Fitted Values ...")
  68. residuals = .series$z
  69. fitted.values = .series$x - residuals
  70. h.t = .series$h
  71. if (.params$includes["delta"])
  72. deltainv = 1/fit$par["delta"]
  73. else deltainv = 1/fit$params$delta
  74. sigma.t = (.series$h)^deltainv
  75. if (DEBUG)
  76. print("Standard Errors and t-Values ...")
  77. fit$cvar <- if (robust.cvar)
  78. (solve(fit$hessian) %*% (t(fit$gradient) %*% fit$gradient) %*%
  79. solve(fit$hessian))
  80. else -solve(fit$hessian)
  81. fit$se.coef = sqrt(diag(fit$cvar))
  82. fit$tval = fit$coef/fit$se.coef
  83. fit$matcoef = cbind(fit$coef, fit$se.coef, fit$tval, 2 *
  84. (1 - pnorm(abs(fit$tval))))
  85. dimnames(fit$matcoef) = list(names(fit$tval), c(" Estimate",
  86. " Std. Error", " t value", "Pr(>|t|)"))
  87. if (DEBUG)
  88. print("Add Title and Description ...")
  89. if (is.null(title))
  90. title = "GARCH Modelling"
  91. if (is.null(description))
  92. description = description()
  93. Time = Sys.time() - .StartFit
  94. if (trace) {
  95. cat("\nTime to Estimate Parameters:\n ")
  96. print(Time)
  97. }
  98. new("fGARCH", call = as.call(match.call()), formula = as.formula(paste("~",
  99. formula.mean, "+", formula.var)), method = "Max Log-Likelihood Estimation",
  100. data = data, fit = fit, residuals = residuals, fitted = fitted.values,
  101. h.t = h.t, sigma.t = as.vector(sigma.t), title = as.character(title),
  102. description = as.character(description))
  103. }

在正式分析函數的源碼之前
先看一下模型變量m4的結構:
> str(m4)
Formal class 'fGARCH' [package "fGarch"] with 11 slots
  ..@ call       : language garchFit(formula = ~1 + garch(1, 1), data = intc,      trace = F)
  ..@ formula    :Class 'formula'  language data ~ 1 + garch(1, 1)
  .. .. ..- attr(*, ".Environment")=<environment: 0x0000000003e60360> 
  .. .. ..- attr(*, "data")= chr "data = intc"
  ..@ method     : chr "Max Log-Likelihood Estimation"
  ..@ data       : Named num [1:444] 0.01 -0.15 0.0671 0.0829 -0.1103 ...
  .. ..- attr(*, "names")= chr [1:444] "1" "2" "3" "4" ...
  ..@ fit        :List of 17
  .. ..$ par        : Named num [1:4] 0.011266 0.000919 0.086438 0.852586  #參數
  .. .. ..- attr(*, "names")= chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. ..$ objective  : num 604 
  .. ..$ convergence: int 1
  .. ..$ iterations : int 19
  .. ..$ evaluations: Named int [1:2] 36 105
  .. .. ..- attr(*, "names")= chr [1:2] "function" "gradient"
  .. ..$ message    : chr "singular convergence (7)"
  .. ..$ value      : Named num -312            (為什么顯示是負的,而輸出是正的?,因為nlminb是取最小值的)
  .. .. ..- attr(*, "names")= chr "LogLikelihood"
  .. ..$ coef       : Named num [1:4] 0.011266 0.000919 0.086438 0.852586
  .. .. ..- attr(*, "names")= chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. ..$ llh        : Named num -312                  #似然函數的最大值取負數
  .. .. ..- attr(*, "names")= chr "LogLikelihood"
  .. ..$ hessian    : num [1:4, 1:4] -35115 108140 -253 919 108140 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. .. .. ..$ : chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. .. ..- attr(*, "time")=Class 'difftime'  atomic [1:1] 0.021
  .. .. .. .. ..- attr(*, "units")= chr "secs"
  .. ..$ ics        : Named num [1:4] -1.39 -1.35 -1.39 -1.37
  .. .. ..- attr(*, "names")= chr [1:4] "AIC" "BIC" "SIC" "HQIC"
  .. ..$ series     :List of 10
  .. .. ..$ model    : chr [1:2] "arma" "garch"
  .. .. ..$ order    : Named num [1:4] 0 0 1 1
  .. .. .. ..- attr(*, "names")= chr [1:4] "u" "v" "p" "q"
  .. .. ..$ max.order: num 1
  .. .. ..$ z        : num [1:444] -0.00127 -0.16128 0.0558 0.07168 -0.12161 ...  殘差
  .. .. ..$ h        : num [1:444] 0.016 0.0146 0.0156 0.0145 0.0137 ...
  .. .. ..$ x        : Named num [1:444] 0.01 -0.15 0.0671 0.0829 -0.1103 ...
  .. .. .. ..- attr(*, "names")= chr [1:444] "1" "2" "3" "4" ...
  .. .. ..$ scale    : num 0.127
  .. .. ..$ init.rec : chr "mci"
  .. .. ..$ h.start  : num 2
  .. .. ..$ llh.start: num 1
  .. ..$ params     :List of 14
  .. .. ..$ params     : Named num [1:8] 0.011266 0.000919 0.086438 0.1 0.852586 ...
  .. .. .. ..- attr(*, "names")= chr [1:8] "mu" "omega" "alpha1" "gamma1" ...
  .. .. ..$ U          : Named num [1:8] -1.13 1.00e-06 1.00e-08 -1.00 1.00e-08 ...
  .. .. .. ..- attr(*, "names")= chr [1:8] "mu" "omega" "alpha1" "gamma1" ...
  .. .. ..$ V          : Named num [1:8] 1.13 100 1 1 1 ...
  .. .. .. ..- attr(*, "names")= chr [1:8] "mu" "omega" "alpha1" "gamma1" ...
  .. .. ..$ includes   : Named logi [1:8] TRUE TRUE TRUE FALSE TRUE FALSE ...
  .. .. .. ..- attr(*, "names")= chr [1:8] "mu" "omega" "alpha1" "gamma1" ...
  .. .. ..$ index      : Named int [1:4] 1 2 3 5
  .. .. .. ..- attr(*, "names")= chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. .. ..$ mu         : Named num 0.113
  .. .. .. ..- attr(*, "names")= chr "mu"
  .. .. ..$ delta      : num 2           #默認是2
  .. .. ..$ skew       : num 1
  .. .. ..$ shape      : num 4
  .. .. ..$ cond.dist  : chr "norm"
  .. .. ..$ leverage   : logi FALSE
  .. .. ..$ persistence: Named num 0.9
  .. .. .. ..- attr(*, "names")= chr "persistence"
  .. .. ..$ control    :List of 19
  .. .. .. ..$ fscale   : logi TRUE
  .. .. .. ..$ xscale   : logi TRUE
  .. .. .. ..$ algorithm: chr "nlminb"
  .. .. .. ..$ llh      : chr "internal"
  .. .. .. ..$ tol1     : num 1
  .. .. .. ..$ tol2     : num 1
  .. .. .. ..$ MIT      : num 2000
  .. .. .. ..$ MFV      : num 5000
  .. .. .. ..$ MET      : num 5
  .. .. .. ..$ MEC      : num 2
  .. .. .. ..$ MER      : num 1
  .. .. .. ..$ MES      : num 4
  .. .. .. ..$ XMAX     : num 1000
  .. .. .. ..$ TOLX     : num 1e-10
  .. .. .. ..$ TOLC     : num 1e-06
  .. .. .. ..$ TOLG     : num 1e-06
  .. .. .. ..$ TOLD     : num 1e-06
  .. .. .. ..$ TOLS     : num 1e-04
  .. .. .. ..$ RPF      : num 0.01
  .. .. ..$ llh        : num 604
  .. ..$ cvar       : num [1:4, 1:4] 2.91e-05 1.06e-07 -1.51e-05 6.60e-06 1.06e-07 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. .. .. ..$ : chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. ..$ se.coef    : Named num [1:4] 0.005393 0.000389 0.026544 0.039432
  .. .. ..- attr(*, "names")= chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. ..$ tval       : Named num [1:4] 2.09 2.36 3.26 21.62
  .. .. ..- attr(*, "names")= chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. ..$ matcoef    : num [1:4, 1:4] 0.011266 0.000919 0.086438 0.852586 0.005393 ...
  .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. ..$ : chr [1:4] "mu" "omega" "alpha1" "beta1"
  .. .. .. ..$ : chr [1:4] " Estimate" " Std. Error" " t value" "Pr(>|t|)"
  ..@ residuals  : num [1:444] -0.00127 -0.16128 0.0558 0.07168 -0.12161 ...
  ..@ fitted     : Named num [1:444] 0.0113 0.0113 0.0113 0.0113 0.0113 ...  
         #是 .series$x - residuals   其實這個x就是r(i),
        #那么fitted就是mu了(只不過這里的值是被四舍五入處理了不明顯)
代碼                      fitted.values = .series$x - residuals
                            fitted = fitted.values
  .. ..- attr(*, "names")= chr [1:444] "1" "2" "3" "4" ...
  ..@ h.t        : num [1:444] 0.016 0.0146 0.0156 0.0145 0.0137 ...  #條件方差
  ..@ sigma.t    : num [1:444] 0.127 0.121 0.125 0.12 0.117 ...         #是條件標准差,等於volatility(m4)
 代碼                          deltainv = 1/fit$par["delta"]=0.
                              sigma.t = (.series$h)^deltainv
  ..@ title      : chr "GARCH Modelling"
  ..@ description: chr "Sun Jan 22 10:09:46 2017 by user: xuan"

 ?'@'
Extract or replace the contents of a slot in a object with a formal (S4) class structure.
從S4類里取出slot可以適應@運算符
hessian
a string denoting how the Hessian matrix should be evaluated, either hessian ="rcd", or "ropt", the default, "rcd" is a central difference approximation implemented in R and "ropt" use the internal R function optimhess.
黑塞矩陣(Hessian Matrix),又譯作海森矩陣、海瑟矩陣、海塞矩陣等,是一個多元函數的二階偏導數構成的方陣,描述了函數的局部曲率
Details
"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 “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.
V = H^(-1) G' G H^(-1),
where V denotes the variance-covariance matrix, H stands for the Hessian and G represents the matrix of contributions to the gradient(傾斜度), the elements of which are defined as
G_{t,i} = derivative of l_{t} w.r.t. zeta_{i},
where l_{t} is the log likelihood of the t-th observation and 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
garchFit 
returns a S4 object of class "fGARCH" with the following slots:
@call
the call of the garch function.
@formula
a list with two formula entries, one for the mean and the other one for the variance equation.
@method
a string denoting the optimization method, by default the returneds string is "Max Log-Likelihood Estimation".
@data
a list with one entry named x, containing the data of the time series to be estimated, the same as given by the input argument series.
@fit
a list with the results from the parameter estimation. The entries of the list depend on the selected algorithm, see below.
@residuals
a numeric vector with the (raw, unstandardized) residual values.
@fitted
a numeric vector with the fitted values.
@h.t
a numeric vector with the conditional variances (h.t = sigma.t^delta).
@sigma.t
a numeric vector with the conditional standard deviation.
@title
a title string.
@description
a string with a brief description.
The entries of the @fit slot show the results from the optimization.

其中1
    
    
    
            
  1. scale <- if (con$xscale) 
  2.     sd(series)
  3. series <- series/scale
是對數據進行標准化
(注意,標准化之后,數據和原始數據不同啦,在后面運算時,不要忘了~)
我們可以在調試界面的控制台直接輸入命令,來查看變量在當前環境和一定語句代運行完后的值
這個所謂的標准化,並沒有減去均值的,要注意!

其中2
      
      
      
              
  1. .series <- .garchInitSeries(formula.mean = formula.mean, 
  2.     formula.var = formula.var, cond.dist = cond.dist[1], 
  3.     series = series, scale = scale, init.rec = init.rec[1], 
  4.     h.start = NULL, llh.start = NULL, trace = trace)
  5. .setfGarchEnv(.series = .series)
注意這種.setfGarchEnv的做法,就是對環境變量中的變量賦值
還有.getfGarchEnv,可以提高自己的編程能力。
.garchInitSeries函數
          
          
          
                  
  1. function (formula.mean, formula.var, cond.dist, series, scale, 
  2.   init.rec, h.start, llh.start, trace) 
  3. {
  4.   mm = length(formula.mean)
  5.   if (mm != 2) 
  6.     stop("Mean Formula misspecified")
  7.   end = regexpr("\\(", as.character(formula.mean[mm])) - 1
  8.   model.mean = substr(as.character(formula.mean[mm]), 1, end)
  9.   if (!any(c("ar", "ma", "arma") == model.mean)) 
  10.     stop("formula.mean must be one of: ar, ma, arma")
  11.   mv = length(formula.var)
  12.   if (mv != 2) 
  13.     stop("Variance Formula misspecified")
  14.   end = regexpr("\\(", as.character(formula.var[mv])) - 1
  15.   model.var = substr(as.character(formula.var[mv]), 1, end)
  16.   if (!any(c("garch", "aparch") == model.var)) 
  17.     stop("formula.var must be one of: garch, aparch")
  18.   model.order = as.numeric(strsplit(strsplit(strsplit(as.character(formula.mean), 
  19.     "\\(")[[2]][2], "\\)")[[1]], ",")[[1]])
  20.   u = model.order[1]
  21.   v = 0
  22.   if (length(model.order) == 2) 
  23.     v = model.order[2]
  24.   maxuv = max(u, v)
  25.   if (u < 0 | v < 0) 
  26.     stop("*** ARMA orders must be positive.")
  27.   model.order = as.numeric(strsplit(strsplit(strsplit(as.character(formula.var), 
  28.     "\\(")[[2]][2], "\\)")[[1]], ",")[[1]])
  29.   p = model.order[1]
  30.   q = 0
  31.   if (length(model.order) == 2) 
  32.     q = model.order[2]
  33.   if (p + q == 0) 
  34.     stop("Misspecified GARCH Model: Both Orders are zero!")
  35.   maxpq = max(p, q)
  36.   if (p < 0 | q < 0) 
  37.     stop("*** GARCH orders must be positive.")
  38.   max.order = max(maxuv, maxpq)
  39.   if (is.null(h.start)) 
  40.     h.start = max.order + 1
  41.   if (is.null(llh.start)) 
  42.     llh.start = 1
  43.   if (init.rec != "mci" & model.var != "garch") {
  44.     stop("Algorithm only supported for mci Recursion")
  45.   }
  46.  
  47.   ans = list(model = c(model.mean, model.var), order = c(u = u, 
  48.     v = v, p = p, q = q), max.order = max.order,
  49.     z = rep(0, times = length(series)),   #這里的0,長度為444
  50.     h = rep(var(series), times = length(series)),  #h是方差是1(因為此時的series是被標准化過的),長度為444
  51.     x = series, scale = scale, init.rec = init.rec, h.start = h.start, 
  52.     llh.start = llh.start)
  53.   ans
  54. }

其結果
 
 
 
這個函數的作用,主要是形成z、h之類的存儲容器


其中3
    
    
    
            
  1. .params <- .garchInitParameters(formula.mean = formula.mean, 
  2.     formula.var = formula.var, delta = delta, skew = skew, 
  3.     shape = shape, cond.dist = cond.dist[1], include.mean = include.mean, 
  4.     include.delta = include.delta, include.skew = include.skew, 
  5.     include.shape = include.shape, leverage = leverage, 
  6.     algorithm = algorithm[1], control = con, trace = trace)
  7.   .setfGarchEnv(.params = .params)

.garchInitParameters函數
      
      
      
              
  1. function (formula.mean, formula.var, delta, skew, shape, cond.dist, 
  2.   include.mean, include.delta, include.skew, include.shape, 
  3.   leverage, algorithm, control, trace) 
  4. {
  5.   .DEBUG = FALSE
  6.   .series <- .getfGarchEnv(".series")
  7.   model.order = as.numeric(strsplit(strsplit(strsplit(as.character(formula.mean), 
  8.     "\\(")[[2]][2], "\\)")[[1]], ",")[[1]])
  9.   u = model.order[1]
  10.   v = 0
  11.   if (length(model.order) == 2) 
  12.     v = model.order[2]
  13.   model.order = as.numeric(strsplit(strsplit(strsplit(as.character(formula.var), 
  14.     "\\(")[[2]][2], "\\)")[[1]], ",")[[1]])
  15.   p = model.order[1]
  16.   q = 0
  17.   if (length(model.order) == 2) 
  18.     q = model.order[2]
  19.   model.var = .series$model[2]
  20.   if (is.null(include.delta)) {
  21.     if (model.var == "garch") {
  22.       include.delta = FALSE
  23.     }
  24.     else {
  25.       include.delta = TRUE
  26.     }
  27.   }
  28.   if (is.null(leverage)) {
  29.     if (model.var == "garch") {
  30.       leverage = FALSE
  31.     }
  32.     else {
  33.       leverage = TRUE
  34.     }
  35.   }
  36.   if (cond.dist == "t") 
  37.     cond.dist = "std"
  38.   skewed.dists = c("snorm", "sged", "sstd", "snig")
  39.   if (is.null(include.skew)) {
  40.     if (any(skewed.dists == cond.dist)) {
  41.       include.skew = TRUE
  42.     }
  43.     else {
  44.       include.skew = FALSE
  45.     }
  46.   }
  47.   shaped.dists = c("ged", "sged", "std", "sstd", "snig")
  48.   if (is.null(include.shape)) {
  49.     if (any(shaped.dists == cond.dist)) {
  50.       include.shape = TRUE
  51.     }
  52.     else {
  53.       include.shape = FALSE
  54.     }
  55.   }
  56.   Names = c("mu", 
  57.                      if (u > 0) paste("ar", 1:u, sep = ""), 
  58.                      if (v > 0) paste("ma", 1:v, sep = ""), "omega", 
  59.                      if (p > 0) paste("alpha", 1:p, sep = ""), 
  60.                      if (p > 0) paste("gamma", 1:p, sep = ""), 
  61.                      if (q > 0) paste("beta", 1:q, sep = ""), 
  62.                      "delta", "skew", "shape")
  63.   fit.mean = arima(.series$x, order = c(u, 0, v), include.mean = include.mean)$coef
  64.   alpha.start = 0.1
  65.   beta.start = 0.8
  66.   params = c(
  67.     if (include.mean) fit.mean[length(fit.mean)] else 0,      #最后一項就是intercept,所以就是mu啊!
  68.     if (u > 0) fit.mean[1:u], 
  69.     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), 
  70.     if (p > 0) rep(alpha.start/p, times = p), 
  71.     if (p > 0) rep(0.1, times = p), 
  72.     if (q > 0) rep(beta.start/q, times = q), 
  73.     delta, skew, shape)
  74.   names(params) = Names
  75.   TINY = 1e-08
  76.   USKEW = 1/10
  77.   USHAPE = 1
  78.   if (cond.dist == "snig") 
  79.     USKEW = -0.99
  80.   U = c(-10 * abs(mean(.series$x)), if (u > 0) rep(-1 + TINY, 
  81.     times = u), if (v > 0) rep(-1 + TINY, times = v), 1e-06 * 
  82.     var(.series$x), if (p > 0) rep(0 + TINY, times = p), 
  83.     if (p > 0) rep(-1 + TINY, times = p), if (q > 0) rep(0 + 
  84.       TINY, times = q), 0, USKEW, USHAPE)
  85.   names(U) = Names
  86.   VSKEW = 10
  87.   VSHAPE = 10
  88.   if (cond.dist == "snig") 
  89.     VSKEW = 0.99
  90.   V = c(10 * abs(mean(.series$x)), if (u > 0) rep(1 - TINY, 
  91.     times = u), if (v > 0) rep(1 - TINY, times = v), 100 * 
  92.     var(.series$x), if (p > 0) rep(1 - TINY, times = p), 
  93.     if (p > 0) rep(1 - TINY, times = p), if (q > 0) rep(1 - 
  94.       TINY, times = q), 2, VSKEW, VSHAPE)
  95.   names(V) = Names
  96.   includes = c(include.mean, if (u > 0) rep(TRUE, times = u), 
  97.     if (v > 0) rep(TRUE, times = v), TRUE, if (p > 0) rep(TRUE, 
  98.       times = p), if (p > 0) rep(leverage, times = p), 
  99.     if (q > 0) rep(TRUE, times = q), include.delta, include.skew, 
  100.     include.shape)
  101.   names(includes) = Names
  102.   index = (1:length(params))[includes == TRUE]
  103.   names(index) = names(params)[includes == TRUE]
  104.   alpha <- beta <- NULL
  105.   if (p > 0) 
  106.     alpha = params[substr(Names, 1, 5) == "alpha"]
  107.   if (p > 0 & leverage) 
  108.     gamma = params[substr(Names, 1, 5) == "gamma"]
  109.   if (p > 0 & !leverage) 
  110.     gamma = rep(0, times = p)
  111.   if (q > 0) 
  112.     beta = params[substr(Names, 1, 4) == "beta"]
  113.   if (.series$model[2] == "garch") {
  114.     persistence = sum(alpha) + sum(beta)
  115.   }
  116.   else if (.series$model[2] == "aparch") {
  117.     persistence = sum(beta)
  118.     for (i in 1:p) 
  119.           persistence = persistence + alpha[i] * garchKappa(cond.dist, gamma[i], params["delta"], params["skew"], params["shape"])
  120.   }
  121.   names(persistence) = "persistence"
  122.   list(params = params, U = U, V = V, includes = includes, 
  123.     index = index, mu = params[1], delta = delta, skew = skew, 
  124.     shape = shape, cond.dist = cond.dist, leverage = leverage, 
  125.     persistence = persistence, control = control)
  126. }
這個函數的作用,主要是形成參數的初始值吧
      
      
      
              
  1. fit.mean = arima(.series$x, order = c(u, 0, v), include.mean = include.mean)$coef
  2. params = c(
  3.     if (include.mean) fit.mean[length(fit.mean)] else 0
include.mean默認是T,fit.mean就相當於是對原始數據標准化后的序列進行arima建模,只不過ar和ma的階數都是0,只剩下截距項,作為mu的初始值,其中length(fit.mean)就是模型的截距項intercept。
此時的mu是 0.1128933


事實上,如果是到底為止,那么就參數的值其實還是沒有被求出,為什么后面在 .garchFit 函數中卻直接開始賦值了呢?這是因為后面的.garchOptimizeLLH函數借助.get/.setfGarchEnv()函數,取得了.series和.prameter


其中4 (4.0.2.4).garchOptimizeLLH函數
.garchOptimizeLLH函數(刪去了一些用不到的代碼)
    
    
    
            
  1. function (hessian = hessian, robust.cvar, trace)
  2. {
  3. .series <- .getfGarchEnv(".series")
  4. .params <- .getfGarchEnv(".params")
  5. INDEX = .params$index
  6. algorithm = .params$control$algorithm[1] #algorithm是nlminb
  7. TOL1 = .params$control$tol1
  8. TOL2 = .params$control$tol2
  9. if (algorithm == "nlminb" | algorithm == "nlminb+nm") {
  10. fit <- .garchRnlminb(.params, .series, .garchLLH, trace)
  11. .params$llh = fit$llh
  12. .params$params[INDEX] = fit$par
  13. .setfGarchEnv(.params = .params)
  14. }
  15. .params$llh = fit$llh
  16. .params$params[INDEX] = fit$par
  17. .setfGarchEnv(.params = .params)
  18. if (hessian == "ropt") {
  19. fit$hessian <- -.garchRoptimhess(par = fit$par, .params = .params,
  20. .series = .series)
  21. titleHessian = "R-optimhess"
  22. }
  23. ...............
  24. if (.params$control$xscale) {
  25. .series$x <- .series$x * .series$scale #將標准化后的值還原為原始的數值了
  26. if (.params$include["mu"])
  27. fit$coef["mu"] <- fit$par["mu"] <- .params$params["mu"] <- .params$params["mu"] *
  28. .series$scale
  29. if (.params$include["omega"])
  30. fit$coef["omega"] <- fit$par["omega"] <- .params$params["omega"] <- .params$params["omega"] *
  31. .series$scale^(.params$params["delta"])
  32. .setfGarchEnv(.params = .params)
  33. .setfGarchEnv(.series = .series)
  34. }
  35. if (.params$control$xscale) {
  36. if (.params$include["mu"]) {
  37. fit$hessian[, "mu"] <- fit$hessian[, "mu"]/.series$scale
  38. fit$hessian["mu", ] <- fit$hessian["mu", ]/.series$scale
  39. }
  40. if (.params$include["omega"]) {
  41. fit$hessian[, "omega"] <- fit$hessian[, "omega"]/.series$scale^(.params$params["delta"])
  42. fit$hessian["omega", ] <- fit$hessian["omega", ]/.series$scale^(.params$params["delta"])
  43. }
  44. }
  45. .llh <- fit$llh <- fit$value <- .garchLLH(fit$par, trace = FALSE,
  46. fGarchEnv = TRUE)
  47. .series <- .getfGarchEnv(".series")
  48. if (robust.cvar)
  49. fit$gradient <- -.garchRCDAGradient(par = fit$par, .params = .params,
  50. .series = .series)
  51. N = length(.series$x)
  52. NPAR = length(fit$par)
  53. fit$ics = c(AIC = c((2 * fit$value)/N + 2 * NPAR/N), BIC = (2 *
  54. fit$value)/N + NPAR * log(N)/N, SIC = (2 * fit$value)/N +
  55. log((N + 2 * NPAR)/N), HQIC = (2 * fit$value)/N + (2 *
  56. NPAR * log(log(N)))/N)
  57. names(fit$ics) <- c("AIC", "BIC", "SIC", "HQIC")
  58. fit
  59. }

其中4 (4.0.2.4.1) .garchRnlminb函數
.garchRnlminb函數
    
    
    
            
  1. function (.params, .series, .garchLLH, trace) 
  2. {
  3.   if (trace) 
  4.     cat("\nR coded nlminb Solver: \n\n")
  5.   INDEX = .params$index
  6.   parscale = rep(1, length = length(INDEX))
  7.   names(parscale) = names(.params$params[INDEX])
  8.   parscale["omega"] = var(.series$x)^(.params$delta/2)
  9.   parscale["mu"] = abs(mean(.series$x)) #這個並非mu的初始值
  10.   TOL1 = .params$control$tol1
  11.   fit <- nlminb(start = .params$params[INDEX], objective = .garchLLH, 
  12.     lower = .params$U[INDEX], upper = .params$V[INDEX], 
  13.     scale = 1/parscale, control = list(eval.max = 2000, 
  14.       iter.max = 1500, rel.tol = 1e-14 * TOL1, x.tol = 1e-14 * 
  15.         TOL1, trace = as.integer(trace)), fGarchEnv = FALSE)
  16.   fit$value <- fit.llh <- fit$objective
  17.   names(fit$par) = names(.params$params[INDEX])
  18.   .garchLLH(fit$par, trace = FALSE, fGarchEnv = TRUE)
  19.   fit$coef <- fit$par
  20.   fit$llh <- fit$objective
  21.   fit
  22. }
關於nlminb函數,請看筆記:
.params$params[INDEX]是初始值
 objective = .garchLLH是被優化的函數
數據呢?怎么沒見傳入數據?

.garchRnlminb函數函數運行完,則會估計出參數:
fit$par
        mu      omega     alpha1      beta1 
0.08876900 0.05705989 0.08643831 0.85258554 
這個值呢,是別標准化后的參數值
    
    
    
            
  1. fit$coef["mu"] <- fit$par["mu"] <- .params$params["mu"] <- .params$params["mu"] * .series$scale
通過上述語句轉化為原始序列對應的參數即可!
Browse[4]> fit$coef
          mu        omega       alpha1        beta1 
0.0112656813 0.0009190163 0.0864383140 0.8525855370 
這就是模型最終輸出的參數!


運行到.llh <- fit$llh <- fit$value <- .garchLLH(fit$par, trace = FALSE, 
    fGarchEnv = TRUE)
這里跳進去
得到其中用到的參數.garchLLH函數
    
    
    
            
  1. .garchLLH
  2. function (params, trace = TRUE, fGarchEnv = FALSE) 
  3. {
  4.     DEBUG = FALSE
  5.     if (DEBUG) 
  6.         print("Entering Function .garchLLH")
  7.     .series <- .getfGarchEnv(".series")
  8.     .params <- .getfGarchEnv(".params")
  9.     .garchDist <- .getfGarchEnv(".garchDist")   #概率密度函數
  10.     .llh <- .getfGarchEnv(".llh")  #對數似然函數
  11.     if (DEBUG) 
  12.         print(.params$control$llh)
  13.     if (.params$control$llh == "internal") {
  14.         if (DEBUG) 
  15.             print("internal")
  16.         return(.aparchLLH.internal(params, trace = trace, fGarchEnv = fGarchEnv)) #結束
  17.     }
  18.     else if (.params$control$llh == "filter") {
  19.         if (DEBUG) 
  20.             print("filter")
  21.         return(.aparchLLH.filter(params, trace = trace, fGarchEnv = fGarchEnv))
  22.     }
  23.     else if (.params$control$llh == "testing") {
  24.         if (DEBUG) 
  25.             print("testing")
  26.         return(.aparchLLH.testing(params, trace = trace, fGarchEnv = fGarchEnv))
  27.     }
  28.     else {
  29.         stop("LLH is neither internal, testing, nor filter!")
  30.     }
  31. }
  32. <environment: namespace:fGarch>
.aparchLLH.internal函數
其中我進去看了下
     
     
     
             
  1. function (params, trace = TRUE, fGarchEnv = TRUE) 
  2. {
  3.     DEBUG = FALSE
  4.     if (DEBUG) 
  5.         print("Entering Function .garchLLH.internal")
  6.     .series <- .getfGarchEnv(".series")
  7.     .params <- .getfGarchEnv(".params")
  8.     .garchDist <- .getfGarchEnv(".garchDist")
  9.     .llh <- .getfGarchEnv(".llh")
  10.     if (DEBUG) 
  11.         print(.params$control$llh)
  12.     if (.params$control$llh == "internal") {
  13.         INDEX <- .params$index
  14.         MDIST <- c(norm = 10, QMLE = 10, snorm = 11, std = 20, 
  15.             sstd = 21, ged = 30, sged = 31)[.params$cond.dist]
  16.         if (.params$control$fscale) 
  17.             NORM <- length(.series$x)
  18.         else NORM = 1
  19.         REC <- 1
  20.         if (.series$init.rec == "uev") 
  21.             REC <- 2
  22.         MYPAR <- c(REC = REC, LEV = as.integer(.params$leverage), 
  23.             MEAN = as.integer(.params$includes["mu"]), DELTA = as.integer(.params$includes["delta"]), 
  24.             SKEW = as.integer(.params$includes["skew"]), SHAPE = as.integer(.params$includes["shape"]), 
  25.             ORDER = .series$order, NORM = as.integer(NORM))
  26.         MAX <- max(.series$order)
  27.         NF <- length(INDEX)
  28.         N <- length(.series$x)
  29.         DPARM <- c(.params$delta, .params$skew, .params$shape)
  30.         fit <- .Fortran("garchllh", N = as.integer(N), Y = as.double(.series$x), 
  31.             Z = as.double(.series$z), H = as.double(.series$h), 
  32.             NF = as.integer(NF), X = as.double(params), DPARM = as.double(DPARM), 
  33.             MDIST = as.integer(MDIST), MYPAR = as.integer(MYPAR), 
  34.             F = as.double(0), PACKAGE = "fGarch")
  35.         llh <- fit[[10]] #此時llh就是-312
  36.         if (is.na(llh)) 
  37.             llh = .llh + 0.1 * (abs(.llh))
  38.         if (!is.finite(llh)) 
  39.             llh = .llh + 0.1 * (abs(.llh))
  40.         .setfGarchEnv(.llh = llh)
  41.         if (fGarchEnv) {
  42.             .series$h <- fit[[4]]
  43.             .series$z <- fit[[3]] #直到這里,z才從444個0被替換為殘差
  44.             .setfGarchEnv(.series = .series)
  45.         }
  46.     }
  47.     else {
  48.         stop("LLH is not internal!")
  49.     }
  50.     c(LogLikelihood = llh)
  51. }
.Fortran是調用Fortran代碼的,真是我擦!

    
    
    
            
  1. Browse[5]> .garchDist
  2. function (z, hh, skew, shape) 
  3. {
  4.     dnorm(x = z/hh, mean = 0, sd = 1)/hh
  5. }
  6. <environment: namespace:fGarch>


寫在2017年1月28日00:54:55
農歷新年凌晨,新的一年要更加努力~






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM