我想知道是否可以聚合自定义时段。
我尝试使用to.period(x,"day",3,OHLC=FALSE)
进行汇总,但由于它刚刚返回最新阶段,因此无效。
例如,让x
为具有OHLC数据的2天xts对象。
Open High Low Close Volume
1999-11-18 30.65656 33.68852 26.95082 28.80369 66392936
1999-11-19 28.93002 28.97213 26.82449 27.45615 16173015
任何xts工具都允许我聚合到单行吗?
所以我想要的结果如下:
Open High Low Close Volume
1999-11-19 30.65656 33.68852 26.82449 27.45615 82565951
打开的地方,是开放的第一天,高点是两天的最高点,低点是两天的低点,而收盘点是最后几天的收盘价。成交量只是两天成交量的总和。我希望这个解决方案能够被推广和扩展,因为我想为整个N×M xts对象做这个。我将指定k
。在上面的例子中,k=2
....所以每隔2天,我会聚合到一个。
答案 0 :(得分:1)
使用OHLC=TRUE
可以帮助您解决问题。
AAPL1 <- to.period(AAPL,"days",k = 2,OHLC=TRUE)
head(AAPL1)
# AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
# 2007-01-04 86.29 86.58 81.90 85.66 521395000 11.14619
# 2007-01-05 85.77 86.20 84.40 85.05 208685400 11.06681
# 2007-01-08 85.96 86.53 85.28 85.47 199276700 11.12147
# 2007-01-10 86.45 97.80 85.15 97.00 1575544600 12.62176
# 2007-01-12 95.94 96.78 93.23 94.62 688235800 12.31207
# 2007-01-16 95.68 97.25 95.45 97.10 311019100 12.63477
但是to.period
每2天计算的方式可能不适合你(由于周末等问题,一些聚合期仍会返回1条数据)。如果速度对您来说不是一个大问题,您可以在R中从头开始创建条形图(to.period
使用引擎盖下的C代码更快。这种方法可以让您更灵活地汇总数据。
getSymbols("AAPL")
head(AAPL, 12)
#AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
#2007-01-03 86.29 86.58 81.90 83.80 309579900 10.90416
#2007-01-04 84.05 85.95 83.82 85.66 211815100 11.14619
#2007-01-05 85.77 86.20 84.40 85.05 208685400 11.06681
#2007-01-08 85.96 86.53 85.28 85.47 199276700 11.12147
#2007-01-09 86.45 92.98 85.15 92.57 837324600 12.04533
#2007-01-10 94.75 97.80 93.45 97.00 738220000 12.62176
#2007-01-11 95.94 96.78 95.10 95.80 360063200 12.46562
#2007-01-12 94.59 95.06 93.23 94.62 328172600 12.31207
#2007-01-16 95.68 97.25 95.45 97.10 311019100 12.63477
#2007-01-17 97.56 97.60 94.82 94.95 411565000 12.35501
#2007-01-18 92.10 92.11 89.05 89.07 591151400 11.58990
#2007-01-19 88.63 89.65 88.12 88.50 341118400 11.51573
# You want to aggregate every 2 full trading days of data, so have the endpoints of each aggregation period simply increment by 2.
ep2d <- seq(0, NROW(ep), by = 2)
m2 <- period.apply(AAPL,INDEX=ep2d,FUN=
function(x) {
xts(x = matrix(c(coredata(Op(x))[1], max(coredata(Hi(x))), min(coredata(Lo(x))), coredata(Cl(x))[NROW(x)],
sum(coredata(Vo(x)))), nrow =1), order.by= index(x)[NROW(x)],
dimnames = list(NULL, c("Open", "High", "Low", "Close", "Volume")))
})
head(m2)
# Open High Low Close Volume
# 2007-01-04 86.29 86.58 81.90 85.66 521395000
# 2007-01-08 85.77 86.53 84.40 85.47 407962100
# 2007-01-10 86.45 97.80 85.15 97.00 1575544600
# 2007-01-12 95.94 96.78 93.23 94.62 688235800
# 2007-01-17 95.68 97.60 94.82 94.95 722584100
# 2007-01-19 92.10 92.11 88.12 88.50 932269800