我正在用R学习时间序列分析,并在学习过程中遇到了这两个函数。我知道这两个函数的输出都是由周期频率定义的周期性数据,我能看到的唯一区别是to.period()中的OHLC输出选项。
除了OHLC之外,当使用这些函数中的特定函数时?
发布于 2018-08-29 01:22:38
to.period和所有的to.minutes、to.weekly、to.quarterly实际上都是针对OHLC数据的。
如果你使用to.period函数,它将从该期间的第一天开始开盘,该期间的最后一天收盘,以及指定期间的最高/最低低点。这些函数与quantmod / tidyquant / quantstrat包配合使用非常好。请参见代码示例1。
如果您给出的是to.period的非OHLC数据,而是一个包含1个数据列的时间序列,您仍然可以得到某种OHLC。请参见代码示例2。
现在period.apply更有趣了。在这里,您可以提供要应用于数据的您自己的函数。特别是在结合端点的情况下,如果您希望将函数聚合到不同的时间段,则这在timeseries数据中可能是一个强大的函数。索引主要是使用端点指定的,因为使用端点可以创建达到更高时间级别(从天到周/等等)所需的索引。请参见代码示例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.45318https://stackoverflow.com/questions/52056158
复制相似问题