使用'xts'包中的'to.weekly'函数错误的周结束日期

时间:2011-09-09 18:36:16

标签: r xts zoo

我有一个非常奇怪的问题......我使用to.weeklyto.period函数将每日xts对象转换为每周数据。在大多数情况下,我将星期结束日期视为星期五(day.of.week函数将返回5)(例如"2010-01-08""2011-02-11"),但在某些情况下我会得到一些东西除了星期五(星期六/星期日/星期四等)

我尝试了to.weeklyto.period(x, period = 'weeks'),两者都返回了相同的问题。

为什么会这样?有解决办法吗?

谢谢!

[编辑:以下示例]

test.dates <- as.Date(c("2010-04-27","2010-04-28","2010-04-29","2010-04-30","2010-05-03","2010-05-04","2010-05-05","2010-05-06","2010-05-07","2010-05-10","2010-05-11","2010-05-12","2010-05-13","2010-05-14","2010-05-17","2010-05-18","2010-05-19","2010-05-20","2010-05-21","2010-05-22","2010-05-24","2010-05-25","2010-05-26","2010-05-27","2010-05-28","2010-06-01","2010-06-02","2010-06-03","2010-06-04"))

test.data <- rnorm(length(test.dates),mean=1,sd=2)

test.xts <- xts(x=test.data,order.by=test.dates)

#Function that takes in a vector of zoo/xts objects (e.g. "2010-01-08") and returns the day of the week for each
dayofweek <- function(x) {
 placeholder <- vector("list",length=length(x))
 names(placeholder) <- x

 for(i in 1:length(x)) {placeholder[[i]] <- month.day.year(x[i])}
 placeholder2 <- rep(NA,times=length(x))

 for(i in 1:length(x)) {placeholder2[i] <- day.of.week(placeholder[[i]][[1]],placeholder[[i]][[2]],placeholder[[i]][[3]])}
 return(placeholder2)}

这将返回非星期五的日期:time(to.weekly(test.xts))[dayofweek(time(to.weekly(test.xts))) != 5]

1 个答案:

答案 0 :(得分:2)

您的示例有两个问题:

  1. 您的dayofweek函数有点麻烦,结果可能不正确。
  2. 您的示例日期缺少某些日期,例如05-23-2010。
  3. 以下是代码的清理版本:

    library(xts)
    test.dates <- as.Date(c("2010-04-27","2010-04-28","2010-04-29","2010-04-30","2010-05-03","2010-05-04","2010-05-05","2010-05-06","2010-05-07","2010-05-10","2010-05-11","2010-05-12","2010-05-13","2010-05-14","2010-05-17","2010-05-18","2010-05-19","2010-05-20","2010-05-21","2010-05-22","2010-05-24","2010-05-25","2010-05-26","2010-05-27","2010-05-28","2010-06-01","2010-06-02","2010-06-03","2010-06-04"))
    test.data <- rnorm(length(test.dates),mean=1,sd=2)
    test.xts <- xts(x=test.data,order.by=test.dates)
    test.weekly <- to.weekly(test.xts)
    
    library(lubridate)
    test.weekly[wday(test.weekly, label = TRUE, abbr = TRUE) != "Fri"]
    

    此功能的唯一结果是

               test.xts.Open test.xts.High test.xts.Low test.xts.Close
    2010-05-22     -1.705749      1.273982    -2.084203      -1.502611
    

    问题当然是本周结束于05-23-2010,但该日期并未出现在时间序列中。因此,to.weekly使用下一个最接近的日期作为结束点,即05-22-2010。这是你问题的根源。

    这是一个更好的示例,它显示to.weekly函数没有问题。

    library(lubridate); library(xts)   
    test.dates <- seq(as.Date("1900-01-01"),as.Date("2011-10-01"),by='days')
    test.dates <- test.dates[wday(test.dates)!=1 & wday(test.dates)!=7] #Remove weekends
    test.data <- rnorm(length(test.dates),mean=1,sd=2)
    test.xts <- xts(x=test.data,order.by=test.dates)
    test.weekly <- to.weekly(test.xts)
    test.weekly[wday(test.weekly, label = TRUE, abbr = TRUE) != "Fri"]