XTS:: 帮助我了解 period.apply() 和 to.period() 之间的用法和区别

XTS:: Help me on the usage & differences between period.apply() & to.period()

我正在用 R 学习时间序列分析,在学习的过程中遇到了这两个函数。我知道这两个的输出是由周期频率定义的周期性数据,我能看到的唯一区别是 to.period() 中的 OHLC 输出选项。

除了 OHLC 之外,当要使用这些功能中的特定功能时?

to.period 和所有 to.minutes、to.weekly、to.quarterly 确实适用于 OHLC 数据。

如果您采用函数 to.period,它将采用该期间第一天的开盘价、该期间最后一天的收盘价以及指定期间的最高价/最低价。这些函数与 quantmod / tidyquant / quantstrat 包一起工作得很好。请参阅代码示例 1。

如果您提供 to.period 非 OHLC 数据,但时间序列具有 1 个数据列,您仍然会得到某种 OHLC 返回。请参阅代码示例 2。

现在period.apply更有趣了。您可以在此处提供要应用于数据的自己的函数。特别是与端点结合使用时,如果您想将函数聚合到不同的时间段,这可能是时间序列数据中的一个强大函数。该索引主要由端点指定,因为使用端点您可以创建达到更高时间级别(从一天到一周等)所需的索引。请参阅代码示例 3 和 4。

如果您有超过 1 列的数据,请记住将矩阵函数与 period.apply 一起使用,因为 xts 基本上是一个矩阵和一个索引。请参阅代码示例 5。

有关 this data.camp course 的更多信息。

library(xts)

data(sample_matrix)
zoo.data <- zoo(rnorm(31)+10,as.Date(13514:13744,origin="1970-01-01"))


# code example 1
to.quarterly(sample_matrix)
        sample_matrix.Open sample_matrix.High sample_matrix.Low sample_matrix.Close
2007 Q1           50.03978           51.32342          48.23648            48.97490
2007 Q2           48.94407           50.33781          47.09144            47.76719

# same as to.quarterly
to.period(sample_matrix, period = "quarters")
        sample_matrix.Open sample_matrix.High sample_matrix.Low sample_matrix.Close
2007 Q1           50.03978           51.32342          48.23648            48.97490
2007 Q2           48.94407           50.33781          47.09144            47.76719


# code example 2
to.period(zoo.data, period = "quarters")
           zoo.data.Open zoo.data.High zoo.data.Low zoo.data.Close
2007-03-31      9.039875      11.31391     7.451139       10.35057
2007-06-30     10.834614      11.31391     7.451139       11.28427
2007-08-19     11.004465      11.31391     7.451139       11.30360

# code example 3 using base standard deviation in the chosen period
period.apply(zoo.data, endpoints(zoo.data, on = "quarters"), sd)
2007-03-31 2007-06-30 2007-08-19 
  1.026825   1.052786   1.071758 

# self defined function of summing x + x for the period
period.apply(zoo.data, endpoints(zoo.data, on = "quarters"), function(x) sum(x + x) )
2007-03-31 2007-06-30 2007-08-19 
 1798.7240  1812.4736   993.5729 

# code example 5
period.apply(sample_matrix, endpoints(sample_matrix, on = "quarters"), colMeans)
               Open     High      Low    Close
2007-03-31 50.15493 50.24838 50.05231 50.14677
2007-06-30 48.47278 48.56691 48.36606 48.45318