问题
如果我想用 rollapply 计算我的 39 只股票在 stock_returns (xts 对象)和 market_return (单独的 xts 对象,只有一列有市场回报)列中的滚动相关性:
rolling_3yearcor <- rollapply(stock_returns,width=750,FUN=cor,y=market_return)
我收到此错误:
Error in FUN(.subset_xts(data, (i - width + 1):i, j), ...) :
incompatible dimensions
即使我将market_return中的单个列子集为
rolling_3yearcor <- rollapply(stock_returns,width=750,FUN=cor,y=market_return$market)
我也得到了错误,即使它们具有相同的尺寸?!(1 列,相同的行数)。
我想拥有的:
我想要一个 xts 对象,其中股票 [i] 与滚动 750 天窗口中 39 个股票列中的每一列的市场相关,而不是stock_returns 中的每日回报。
rollapply 不应该那样做吗?
编辑 1:一天后移问题的数据样本
Returns StockA
1997-01-03 -0.0054065397
1997-01-06 0.0024139001
1997-01-07 -0.0030085614
1997-01-08 0.0054329941
1997-01-09 -0.0005990317
1997-01-10 -0.0102205387
...
带代码:
ind <- market_return
ind[] <- seq_along(market_return)
rolling_3yearcor <- function(x,y,ind){
rollapply(ind,width=5,function(i) cor(x[i],y[i]))
}
rollcor_3year <- lapply(stock_returns,rolling_3yearcor,market_return,ind)
rollcor_3year <- as.data.frame(rollcor_3year,col.names=names(stock_returns))
colnames(rollcor_3year) <- colnames(stock_returns)
rollcor_3year <- as.xts(rollcor_3year)
给我:
dput(head(rollcor_3year$StockA.N))
structure(c(NA, NA, NA, NA, 0.30868769358199, 0.576490782746284
), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct",
"POSIXt"), .indexTZ = "", tzone = "", class = c("xts", "zoo"), index =
structure(c(852246000,
852505200, 852591600, 852678000, 852764400, 852850800), tzone = "", tclass =
c("POSIXct",
"POSIXt")), .Dim = c(6L, 1L), .Dimnames = list(NULL, "StockA.N"))
然后:
indexTZ(rollcor_3year) <- "UTC"
dput(head(rollcor_3year$StockA.N))
structure(c(NA, NA, NA, NA, 0.30868769358199, 0.576490782746284
), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct",
"POSIXt"), .indexTZ = c(TZ = "UTC"), tzone = c(TZ = "UTC"), class = c("xts",
"zoo"), index = structure(c(852246000, 852505200, 852591600,
852678000, 852764400, 852850800), tzone = c(TZ = "UTC"), tclass =
c("POSIXct",
"POSIXt")), .Dim = c(6L, 1L), .Dimnames = list(NULL, "StockA.N"))
它给了我:
head(rollcor_3year$StockA.N)
1997-01-02 23:00:00 NA
1997-01-05 23:00:00 NA
1997-01-06 23:00:00 NA
1997-01-07 23:00:00 NA
1997-01-08 23:00:00 0.3086877
1997-01-09 23:00:00 0.5764908