Rime
Rime

Reputation: 942

How to subset xts by Date sequence that considers business days

I am subsetting an xts object by using an as.Date sequence:

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)]

If you take a look at the last 2 rows in SELECT, I see that it jumps from 2016-06-06 to 2016-08-01 which is not 4 weeks. It is missing 2016-07-04 but since that is not a business day it skips it. How can I return SELECT that will return the next available business day if indx is not a business day? in this example it should return 2016-07-05...

Upvotes: 1

Views: 347

Answers (1)

FXQuantTrader
FXQuantTrader

Reputation: 6891

By business day, I guess you mean a trading day for AAPL, in which case your business days are really the time indices of the AAPL security.

First principles kind of approach using the fact dates can increment by 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

You might also find solutions via timeDate package useful more generally for business date type subsetting. e.g. http://stackoverflow.com/questions/13673895/r-time-series-data-daily-only-working-days

Upvotes: 1

Related Questions