R:dccfit错误:'dimnames'[2]的长度不等于数组范围

时间:2019-01-06 15:09:22

标签: r

我正在尝试对某些股票收益运行dccfit函数,以对协方差矩阵建模。

在模型文档中,建议使用xts对象。 我找到了一个如何在波纹管链接下使用数据框运行该函数的示例,该示例有效。 但是,当我尝试使用自己的数据集运行它时,却无法正常工作。 http://www.unstarched.net/2013/01/03/the-garch-dcc-model-and-2-stage-dccmvt-estimation/ https://faculty.washington.edu/ezivot/econ589/DCCgarchPowerpoint.pdf

我试图更改暗号和行名而没有结果

library(zoo)
library(rugarch)
library(xts)
library(rmgarch)

getSymbols(Symbols = c("^GSPC", "SPN"), 
       env = parent.frame(),
       reload.Symbols = FALSE,
       verbose = FALSE,
       warnings = TRUE,
       src = "yahoo",
       symbol.lookup = TRUE,
       auto.assign = getOption('getSymbols.auto.assign',TRUE),
       from = "1927-01-01",
       to = "2018-04-28")

GSPC_dataframe <- data.frame(date=index(GSPC), coredata(GSPC))

## SPECIFYING DCC GARCH
# univariate normal GARCH(1,1) for each series
garch11.spec = ugarchspec(mean.model = list(armaOrder = c(0,0)),variance.model = list(garchOrder = c(1,1),model = "sGARCH"),distribution.model = "norm")
# dcc specification - GARCH(1,1) for conditional correlations
dcc.garch11.spec = dccspec(uspec = multispec( replicate(2, garch11.spec) ),dccOrder = c(1,1),distribution = "mvnorm")
dcc.garch11.spec

## ESTIMATE DCC GARCH data needs to be a dataframe
# I have tried to see if idderent options work
dcc.fit = dccfit(dcc.garch11.spec, data = GSPC$LogReturn)
dcc.fit = dccfit(dcc.garch11.spec, data = GSPC_dataframe$LogReturn)
dcc.fit = dccfit(dcc.garch11.spec, data = GSPC)
dcc.fit = dccfit(dcc.garch11.spec, data = GSPC_dataframe)

我试图同时使用其对象和数据框架运行该函数,但出现了相同的错误:

"Error in dimnames(x) <- dn : length of 'dimnames' [2] not equal to array extent"

感谢您的帮助或指导!

2 个答案:

答案 0 :(得分:0)

我不确定“ dccfit函数”是什么,并且看来您的方法不必要地复杂。无论如何,如果您需要基本的相关矩阵和协方差矩阵,下面的脚本将为您完成。

library(quantmod)
library(tidyverse)
library(lubridate)

symbols <- c("AAPL", "MSFT", "GOOG")
getSymbols(symbols)
stocks <- data.frame(as.xts(merge(AAPL, MSFT, GOOG)))
stocks$date <- row.names(stocks)
row.names(stocks) <- NULL

# head(stocks)

jan31 <- ymd("2018-01-31")
days_to_keep <- jan31 %m+% months(0:11)
# days_to_keep

res <- stocks %>%
  select(ends_with("Close"), date) %>%
  mutate(date = ymd(date)) %>%
  filter(date %in% days_to_keep)

# correlation matrix:
res %>% select(-date) %>% cor()

#            AAPL.Close MSFT.Close GOOG.Close
# AAPL.Close  1.0000000  0.9198357  0.9313001
# MSFT.Close  0.9198357  1.0000000  0.9103830
# GOOG.Close  0.9313001  0.9103830  1.0000000

# Or more visually...
res %>% select(-date) %>% pairs()


# covariance matrix:
res %>% select(-date) %>% cov()

答案 1 :(得分:0)

代替此行:

GSPC_dataframe <- data.frame(date=index(GSPC), coredata(GSPC))

您应该从两个数据集中提取收盘价并将其合并为一个xts时间序列:

data <- cbind(Cl(GSPC), Cl(SPN))

比您可以像这样运行dccfit

dcc.fit = dccfit(dcc.garch11.spec, data)

使用head(GSPC)head(SPN)查看您的数据将使您知道为什么它不起作用。