【问题标题】:monthlyReturn and unequal month length每月返回和不等的月份长度
【发布时间】:2017-04-26 09:04:24
【问题描述】:

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

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))) 

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

当我使用

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

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

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

【问题讨论】:

    标签: r quantmod


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 这非常有用。我们如何得到一个月的最后一天? ceiling_date(index(x), "month") -1 ?
    • @R.S.是的,可以使用索引向量中的日期对象,但更安全的方法是使用索引向量中的 POSIXct 对象,index(x) &lt;- ceiling_date(index(x), "month") - days(1)
    • @FXQuantTrader 好的。谢谢。
    • 您可以使用yearmon 索引类 (?yearmon)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多