【问题标题】:In xts::to.period() how to get week boundaries在 xts::to.period() 如何获得周边界
【发布时间】:2016-09-18 23:28:13
【问题描述】:

to.period 的 xts 参考说: "请务必注意,默认情况下,所有日期都将与每个期间的末尾对齐"

在下面我希望看到输出显示 9/12 或 9/18 作为日期输出。但 显然我做的不对。那么“对齐”是什么意思,我怎样才能获得界限?

x1 = xts(1.23, as.Date("2016-09-15"))

x1
           [,1]
2016-09-15 1.23

to.period(x1, period="weeks", indexAt="firstof")
           x1.Open x1.High x1.Low x1.Close
2016-09-15    1.23    1.23   1.23     1.23

to.period(x1, period="weeks", indexAt="lastof")
                    x1.Open x1.High x1.Low x1.Close
2016-09-15 00:00:00    1.23    1.23   1.23     1.23

然而

to.period(x1, period="months", indexAt="lastof")
           x1.Open x1.High x1.Low x1.Close
2016-09-30    1.23    1.23   1.23     1.23

非常感谢。

我在 Windows 10 上使用 R 3.3.1

【问题讨论】:

  • 你试过to.weekly()
  • 是的,但to.weekly() 给出了相同的结果,而且它似乎没有indexAt 选项。

标签: r xts


【解决方案1】:

查看to.period() 的源代码,它调用firstof()lastof()。它对月、年、季度和日有特殊处理,但不是周:

    if (indexAt == "lastof") {
        ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
        if (period %in% c("years", "months", "quarters", 
            "days")) 
            index(xx) <- as.Date(lastof(ix$year + 1900, ix$mon + 
              1))
        else index(xx) <- lastof(ix$year + 1900, ix$mon + 
            1, ix$mday, ix$hour, ix$min, ix$sec)
    }

当您查看 lastof(或 firstof)的代码时,您会发现没有周处理,因为 POSIX 数据处理的工作方式(年、月、日、小时、分钟、秒 - 没有周的概念)。

似乎endpoints()(由to.period() 调用)是唯一有特殊周处理的地方。

我认为您可以自行制定每周向上/向下取整。例如。如果日期是 POSIXct 形式(自 1970 年以来的秒数),则除以 604800(7 天的秒数),调用 ceiling()floor(),然后乘以 604800。(呃,我认为你需要最后加上 259200(3 天内的第二个),因为 POSIXct 时间的基础 1970 年 1 月 1 日是星期四而不是星期日。)

【讨论】:

    【解决方案2】:

    根据 Darren Cook 的提示,我决定采用以下方法重新索引

    x1 = xts(1.23, as.Date("2016-09-15"))    
    x1
               [,1]
    2016-09-15 1.23
    index(x1) = index(x1) - .indexwday(x1) # day of week in [0,6]
    x1
               [,1]
    2016-09-12 1.23
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多