【问题标题】:Collapse dates in RR中的折叠日期
【发布时间】:2014-05-22 10:46:03
【问题描述】:

我需要将 R 中的动物园对象从每日值折叠为每周、每月或每年。我已经尝试过 to.monthly() 等方法,但似乎没有奏效。

数据组织如下:

           CARL.B.CO.Adjusted COLOB.CO.Adjusted
2001-03-01             339.70              2.98
2001-03-02             358.57              3.03
2001-03-05             360.46              3.02
2001-03-06             360.46              3.00
2001-03-07             360.46              3.02
2001-03-08             360.46              3.02

这是一个矩阵,包含从 Yahoo.finance 通过 QuantMod 软件包下载的每日股票价格,并重新排列以仅使用调整后的收盘价。这应该是一个简单的操作,但我花了很多时间在谷歌上搜索,但没有任何运气。

提前致谢。

编辑:

输入输出:

> dput(head(data))
structure(c(339.7, 358.57, 360.46, 360.46, 360.46, 360.46, 2.98, 
3.03, 3.02, 3, 3.02, 3.02), .Dim = c(6L, 2L), .Dimnames = list(
c("2001-03-01", "2001-03-02", "2001-03-05", "2001-03-06", 
"2001-03-07", "2001-03-08"), c("CARL.B.CO.Adjusted", "COLOB.CO.Adjusted"
)), index = structure(c(11382, 11383, 11386, 11387, 11388, 
11389), class = "Date"), class = "zoo")

检索数据的代码:

GetData <- function(tickers, startdate, enddate, fillforward = TRUE)
            {
                getSymbols(tickers, from=startdate, to = enddate,src="yahoo")
                if (fillforward == TRUE) 
                    {
                        na.locf(zoo(do.call(merge, lapply(tickers, function(x) Ad(get(x))))))
                    }
                else 
                    {
                        do.call(merge, lapply(tickers, function(x) Ad(get(x))))
                    }
            }

我已经尝试过这里建议的 to.monthly():https://stat.ethz.ch/pipermail/r-sig-finance/2009q1/003704.html

但在检索多个符号时它不会起作用。

【问题讨论】:

  • 您能否发布至少部分数据的dput() 以及您尝试过的内容的 sn-p 吗?参考:minimum reproducible example
  • 请查看编辑 - 谢谢!

标签: r collapse zoo


【解决方案1】:

1) aggregate.zoo 假设 z 有一个 Date 类索引试试这个:

library(zoo)
aggregate(z, f, tail, 1)

其中函数f 是其中之一:

as.year <- function(x) as.numeric(format(x, "%Y"))

last.date.of.year <- function(x) as.Date(format(x, "%Y-12-31"))

as.yearmon

last.date.of.month <- function(x) as.Date(as.yearmon(x), frac = 1)

nextfri # Date of next Fri or same date if Fri

nextfri 函数是在zoo-quickref vignette 中定义的单行函数。

例如,aggregate(z, nextfri, tail, 1)

2) period.apply 另一种方法是在 xts 包中使用period.apply。见?period.apply

【讨论】:

    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2017-03-23
    相关资源
    最近更新 更多