通过Quantmod软件包处理FRED数据时,我遇到了一个非常奇怪的问题。我正在从网站上下载SP500时间序列,并使用以下代码将其转换为指数的逐年逐年变化:
load_pkgs <- function(pkgs){
for(pkg in pkgs){
if(!(require(pkg, character.only=TRUE))){
install.packages(pkg)
library(pkg, character.only=TRUE)
}
}
}
load_fred_data <- function(series, new_names=NULL){
#' loads FRED data series specified in series and renames them to
#' new_names if given
#' if zoo object created does not have the same number of columns as
#' new_names' length, new_names is ignored
#' =================================================================
if(length(series) > 1){
z <- lapply(
series,
getSymbols,
src = 'FRED',
auto.assign = FALSE,
return.class = 'zoo'
) %>% do.call('merge', .)
} else {
z <- getSymbols(
series,
src = 'FRED',
auto.assign = FALSE,
return.class = 'zoo'
)
}
if(length(colnames(z) == length(new_names))){
colnames(z) <- new_names
}
return(z)
}
convert_monthly_level <- function(series){
#' takes as input a series of monthly values and returns a series of
#' quarterly YoY percent changes
#' geometric average of monthly YoY percent changes is used
#' =================================================================
series <- diff(series, lag = 12, arithmetic = F)
series <- (series * Lag(series, k = 1) * Lag(series, k = 2))^(1/3) - 1
index(series) <- index(series) %m-% months(3)
series <- series[month(index(series)) %in% c(1, 4, 7, 10)]
return(series)
}
load_pkgs(
c('downloader', 'dplyr', 'lubridate', 'quantmod', 'tseries', 'zoo')
)
sp <- load_fred_data('SP500') %>%
to.monthly
index(sp) <- as.Date(index(sp))
sp <- apply(sp, 2, function(x) zoo(x, order.by = index(sp)) %>% convert_monthly_level) %>%
zoo(order.by = as.Date(index(to.quarterly(sp))))
sp <- window(sp, start = core_st, end = core_end)
运行此代码时,我会获得季度动物园系列OHLC年度趋势,但2017-10-01的条目为NA,而本来不应该。我已验证这是在zoo(order.by = as.Date(index(to.quarterly(sp))))
中发生的。 apply语句的结果与我期望的完全一致,而我用来创建新的Zoo对象的索引的语句的结果与我期望的完全相同。翻译中有些失落。此外,至少在其他一个FRED系列CCSA(失业索赔)中也会发生这种情况。谁能帮我解决这个错误?