Frage

I have a Date object in R and would like to add 1 business day to this date. If the result is a holiday, I would like the date to be incremented to the next non-holiday date. Let's assume I mean NYSE holidays. How can I do this?

Example:

mydate = as.Date("2013-12-24")
mydate + 1 #this is a holiday so I want this to roll over to the 26th instead
War es hilfreich?

Lösung

I might use a combo of timeDate::nextBizDay() and roll=-Inf to set up a data.table lookup calendar, like this:

library(data.table)
library(timeDate)

## Set up a calendar for 2013 & 2014
cal <- data.table(date=seq(from=as.Date("2013-01-01"), by=1, length=730),
                  key="date")    
cal2 <- copy(cal)
cal2[,nextBizDay:=date+1]
cal2 <- cal2[isBizday(as.timeDate(nextBizDay)),]
cal <- cal2[cal,,roll=-Inf]

## Check that it works
x <- as.Date("2013-12-21")+1:10
cal[J(x),]
#           date nextBizDay
#  1: 2013-12-22 2013-12-23
#  2: 2013-12-23 2013-12-24
#  3: 2013-12-24 2013-12-26
#  4: 2013-12-25 2013-12-26
#  5: 2013-12-26 2013-12-27
#  6: 2013-12-27 2013-12-30
#  7: 2013-12-28 2013-12-30
#  8: 2013-12-29 2013-12-30
#  9: 2013-12-30 2013-12-31
# 10: 2013-12-31 2014-01-01

## Or perhaps:

lu <- with(cal, setNames(nextBizDay, date))
lu[as.character(x[1:6])]
#   2013-12-22   2013-12-23   2013-12-24   2013-12-25   2013-12-26   2013-12-27 
# "2013-12-23" "2013-12-24" "2013-12-26" "2013-12-26" "2013-12-27" "2013-12-30" 

Andere Tipps

Lubridate will not help you as it does not a notion of business days.

At least two packages do, and they both have a financial bent:

  • RQuantLib has exchange calendars for many exchanges (but it is a pretty large package)

  • timeDate also has calendars

Both packages have decent documentation which will permit you to set this up from working examples.

A third option (for simple uses) is to just store a local calendar out a few years and use that.

Edit: Here is a quick RQuantLib example:

R> library(RQuantLib)
R> adjust(calendar="TARGET", dates=Sys.Date()+2:6, bdc = 0)
  2013-12-22   2013-12-23   2013-12-24   2013-12-25   2013-12-26 
"2013-12-23" "2013-12-23" "2013-12-24" "2013-12-27" "2013-12-27" 
R> 

It just moves the given day (from argument dates) forward to the next biz day.

holidayNYSE(year = getRmetricsOptions("currentYear")) also check out isHoliday from timeDate package

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top