【问题标题】:apply lag on xts data from yahoo not working对来自雅虎的 xts 数据应用延迟不起作用
【发布时间】:2021-05-29 05:30:34
【问题描述】:

我正在尝试对 xts 数据应用延迟,但由于某种原因它不想工作!

library(quantmod)
mystock <- c("GOOG")
getSymbols(mystock, src = "yahoo", from = "2020-01-01", to = "2021-01-01")
Google <- (GOOG)

Google <- subset(GOOG, select = GOOG.Adjusted)

googlets <- ts(Google)
head(googlets)

window5 <- data.frame(x5=Lag(googlets,5), x4=Lag(googlets,4), x3=Lag(googlets,3), 
                      x2=Lag(googlets,2), x1=Lag(googlets,1), googlets)
names(window5) <- c('x5','x4','x3', 'x2', 'x1', 'x')
window5

我可以在转换为 ts 之前对数据应用滞后。结果显示每一行都有一个非滞后数字。

谁能给我指个方向

【问题讨论】:

  • 请始终按照 R 标签信息中的说明提供library 调用,这次我帮助了你。

标签: r lag


【解决方案1】:

使用cbind 有效!

window5 <- cbind(x5=Lag(googlets,5), x4=Lag(googlets,4), x3=Lag(googlets,3), 
                 x2=Lag(googlets,2), x1=Lag(googlets,1), googlets)
colnames(window5) <- c('x5','x4','x3', 'x2', 'x1', 'x')
head(window5)
#           x5      x4      x3      x2      x1       x
# [1,] 1367.37      NA      NA      NA      NA      NA
# [2,] 1360.66 1367.37      NA      NA      NA      NA
# [3,] 1394.21 1360.66 1367.37      NA      NA      NA
# [4,] 1393.34 1394.21 1360.66 1367.37      NA      NA
# [5,] 1404.32 1393.34 1394.21 1360.66 1367.37      NA
# [6,] 1419.83 1404.32 1393.34 1394.21 1360.66 1367.37

【讨论】:

    【解决方案2】:

    您似乎想关闭 Adjusted ,删除时间,执行一些滞后并转换为 ts。这可以使用 Ad 在一行中完成,它将选择 Adjusted 列和 Lag 支持动物园对象的滞后向量。另请注意,我们已经颠倒了问题中使用的列的非标准顺序,但如果您希望无论如何使用 5:0 代替 0:5 。

    ts(Lag(zoo(Ad(GOOG)), 0:5))
    

    或通过管道:

    library(magrittr)
    GOOG %>% Ad %>% zoo %>% Lag(0:5) %>% ts
    

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 2019-01-15
      • 2018-07-14
      相关资源
      最近更新 更多