monthlyReturn 和不等月长度

monthlyReturn and unequal month length

我有 300 多家公司,需要为他们每月计算 return,然后将其用作我的数据集中的变量之一。 我从 Yahoo 下载价格并使用 quantmod 包每月 return 计算:

require(quantmod)    
stockData <- lapply(symbols,function(x) getSymbols(x,auto.assign=FALSE, src='yahoo', from = '2000-01-01'))
    stockDataReturn <- lapply(stockData,function(x) monthlyReturn(Ad(x))) 

我遇到的问题是一些公司有不同的月末(由于交易暂停等),这反映在输出列表中:公司 AAA 为 2013-12-30,公司为 2013-12-31 BBB 和样本的其余部分。

当我使用

合并列表时
returns <- do.call(merge.xts, stockDataReturn)

它为 2013-12-30 创建了一个单独的行,其中包含除 AAA 公司之外的所有 NA。 我该如何解决这个问题?我的理解是我需要坚持月-年格式,我需要在合并之前将其用作索引。

理想情况下,我想要的是在 monthlyReturn 阶段,它使用月初日期而不是月末。

您可以使用 lubridatefloor_date 在相同的月初时间戳而不是月末时间戳上合并。或者在合并前使用 ceiling date 为所有证券四舍五入到相同的月末时间戳。

library(lubridate)
stockDataReturn <- lapply(stockDataReturn,
                              function(x) {
                                  index(x) <- floor_date(index(x), "month")
                                  # Or if you want to round to end of month change to:
                                  # index(x) <- ceiling_date(index(x), "month")
                                  x
                              })
returns <- do.call(merge, stockDataReturn)
colnames(returns) <- symbols