将不规则数据变为规则

在 R 中导入与管理金融数据

Joshua Ulrich

Quantitative Analyst & quantmod Co-Author and Maintainer

规则日期时间序列

  • 时间观测等间隔
  • seq() 方法创建规则日期时间序列:
    • seq.Date()
    • seq.POSIXt()POSIXctPOSIXlt
from_date <- as.Date("2017-01-01")
to_date <- as.Date("2017-01-03")
date_seq <- seq(from = from_date, to = to_date, by = "day")
在 R 中导入与管理金融数据
  • start() 首个索引值
  • end() 最后一个索引值
regular_xts <- xts(seq_along(date_seq), order.by = date_seq)
start(regular_xts)
"2017-01-01"
end(regular_xts)
"2017-01-03"
seq(from = start(regular_xts), to = end(regular_xts), by = "day")
"2017-01-01" "2017-01-02" "2017-01-03"
在 R 中导入与管理金融数据

零宽 xts 对象

  • 仅含索引、无数据的 xts 对象
zero_width_xts <- xts(, order.by = date_seq)
zero_width_xts
Data:
numeric(0)
Index:
 Date[1:3], format: "2017-01-01" "2017-01-02" "2017-01-03"
str(zero_width_xts)
An 'xts' object of zero-width
在 R 中导入与管理金融数据

由不规则数据生成规则数据

  • 在规则序列的每个日期时间添加观测
  • 结果含 NA
在 R 中导入与管理金融数据

将不规则 xts 与规则零宽 xts 合并

irregular
           Price
2017-01-02 20.01
2017-01-04 20.02
2017-01-10 20.05
date_seq <- seq(from = start(irregular),
                to = end(irregular),
                by = "day")
regular_xts <- xts(, date_seq)
在 R 中导入与管理金融数据

将不规则 xts 与规则零宽 xts 合并

merge(irregular, regular_xts)
           Price
2017-01-02 20.01
2017-01-03    NA
2017-01-04 20.02
2017-01-05    NA
2017-01-06    NA
2017-01-07    NA
2017-01-08    NA
2017-01-09    NA
2017-01-10 20.05
在 R 中导入与管理金融数据

填充缺失值

merged_xts <- merge(irregular, regular_xts)

na.locf(merged_xts)
           Price
2017-01-02 20.01
2017-01-03 20.01
2017-01-04 20.02
2017-01-05 20.02
2017-01-06 20.02
2017-01-07 20.02
2017-01-08 20.02
2017-01-09 20.02
2017-01-10 20.05
在 R 中导入与管理金融数据

填充缺失值

merge(irregular, regular_xts, fill = na.locf)
           Price
2017-01-02 20.01
2017-01-03 20.01
2017-01-04 20.02
2017-01-05 20.02
2017-01-06 20.02
2017-01-07 20.02
2017-01-08 20.02
2017-01-09 20.02
2017-01-10 20.05
在 R 中导入与管理金融数据

让我们来练习!

在 R 中导入与管理金融数据

Preparing Video For Download...