我从09:30到下午4:00开始每天1分钟的价格,我需要计算每日日志退货,即日志(当日收盘价/当日开盘价)?如何使用R?
我的数据看起来像
2014-02-03 09:30:00 10.450000
2014-02-03 09:31:00 10.450000
2014-02-03 09:32:00 10.326600
2014-02-03 09:33:00 10.290000
.
.
2014-02-03 04:00:00 10.326500
...
2014-07-31 09:30:00 15.8500
2014-07-31 09:31:00 15.8600
2014-07-31 09:32:00 15.8600
.
2014-07-31 03:50:00 15.9101
2014-07-31 04:00:00 15.9300
你可以使用apply.daily()
。这是一个在日常数据上使用apply.monthly()
的示例。这个概念是一样的。
data(sample_matrix)
x <- as.xts(sample_matrix[,"Close"])
apply.monthly(x, function(p) log(last(p)/as.numeric(first(p))))
[,1]
2007-01-31 0.002152642
2007-02-28 0.008169076
2007-03-31 -0.032065389
2007-04-30 0.009559690
2007-05-31 -0.035670840
2007-06-30 0.002430626
您需要as.numeric()
调用,因为xts / zoo对象上的算术运算始终首先按索引对齐。 as.numeric()
删除了索引。