如何按考虑工作日的日期序列对 xts 进行子集化
How to subset xts by Date sequence that considers business days
我正在使用 as.Date 序列对 xts
对象进行子集化:
library("quantmod")
getSymbols("AAPL",from="2003-01-01")
# indx sequence
indx <- seq(as.Date('2003-03-31'), length.out=200, by='4 weeks')
SELECT <- AAPL[paste(indx)]
如果您查看 SELECT
中的最后两行,我发现它从 2016-06-06
跳到 2016-08-01
,这不是 4 周。它缺少 2016-07-04
,但由于那不是工作日,因此它会跳过它。如果 indx
不是工作日,我如何 return SELECT
将 return 下一个可用的工作日?在这个例子中它应该 return 2016-07-05
...
工作日,我猜你指的是 AAPL
的交易日,在这种情况下,你的工作日实际上是 AAPL 证券的时间指数。
使用事实日期的第一原则类方法可以递增 1 :
indx <- seq(as.Date('2003-03-31'), length.out=200, by='4 weeks')
indx <- indx[indx < as.Date(end(AAPL))]
while(!all(indx %in% as.Date(index(AAPL)))) {
# You ask for the next available business day:
indx[!indx %in% as.Date(index(AAPL))] <- indx[!indx %in% as.Date(index(AAPL))] + 1
# Careful that the last indx value does not go past as.Date(end(AAPL))
if (indx[length(indx)] > as.Date(end(AAPL))) {
indx[length(indx)] <- as.Date(end(AAPL))
}
}
SELECT <- AAPL[indx]
tail(SELECT)
# AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
# 2016-03-14 101.91 102.91 101.78 102.52 25076100 101.35055
# 2016-04-11 108.97 110.61 108.83 109.02 29407500 107.77640
# 2016-05-09 93.00 93.77 92.59 92.79 32936400 92.29005
# 2016-06-06 97.99 101.89 97.55 98.63 23292500 98.09858
# 2016-07-05 95.39 95.40 94.46 94.99 27705200 94.47819
# 2016-08-01 104.41 106.15 104.41 106.05 38167900 105.47860
我正在使用 as.Date 序列对 xts
对象进行子集化:
library("quantmod")
getSymbols("AAPL",from="2003-01-01")
# indx sequence
indx <- seq(as.Date('2003-03-31'), length.out=200, by='4 weeks')
SELECT <- AAPL[paste(indx)]
如果您查看 SELECT
中的最后两行,我发现它从 2016-06-06
跳到 2016-08-01
,这不是 4 周。它缺少 2016-07-04
,但由于那不是工作日,因此它会跳过它。如果 indx
不是工作日,我如何 return SELECT
将 return 下一个可用的工作日?在这个例子中它应该 return 2016-07-05
...
工作日,我猜你指的是 AAPL
的交易日,在这种情况下,你的工作日实际上是 AAPL 证券的时间指数。
使用事实日期的第一原则类方法可以递增 1 :
indx <- seq(as.Date('2003-03-31'), length.out=200, by='4 weeks')
indx <- indx[indx < as.Date(end(AAPL))]
while(!all(indx %in% as.Date(index(AAPL)))) {
# You ask for the next available business day:
indx[!indx %in% as.Date(index(AAPL))] <- indx[!indx %in% as.Date(index(AAPL))] + 1
# Careful that the last indx value does not go past as.Date(end(AAPL))
if (indx[length(indx)] > as.Date(end(AAPL))) {
indx[length(indx)] <- as.Date(end(AAPL))
}
}
SELECT <- AAPL[indx]
tail(SELECT)
# AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
# 2016-03-14 101.91 102.91 101.78 102.52 25076100 101.35055
# 2016-04-11 108.97 110.61 108.83 109.02 29407500 107.77640
# 2016-05-09 93.00 93.77 92.59 92.79 32936400 92.29005
# 2016-06-06 97.99 101.89 97.55 98.63 23292500 98.09858
# 2016-07-05 95.39 95.40 94.46 94.99 27705200 94.47819
# 2016-08-01 104.41 106.15 104.41 106.05 38167900 105.47860