Adding 15 Business Days in Lubridate

Adding 15 business days in lubridate

There's a nifty function isBizday in the timeDate package that made this more fun than it seemed on first glance.

date.in <- dmy(c("30-8-2001", "12-1-2003", "28-2-2003", "20-5-2004"))

Here's a function to do the work. It seemed reasonable to choose 1:10 for the days to look ahead, but that can be adjusted of course.

deadline <- function(x) {
days <- x + 1:10
Deadline <- days[isBizday(as.timeDate(days))][6]
data.frame(DateIn = x, Deadline, DayOfWeek = weekdays(Deadline),
TimeDiff = difftime(Deadline, x))
}

And here's the result:

library(timeDate)
Reduce(rbind, Map(deadline, as.Date(date.in)))
# DateIn Deadline DayOfWeek TimeDiff
# 1 2001-08-30 2001-09-07 Friday 8 days
# 2 2003-01-12 2003-01-20 Monday 8 days
# 3 2003-02-28 2003-03-10 Monday 10 days
# 4 2004-05-20 2004-05-28 Friday 8 days

Calculating Business Days

Updated your function a bit so holidays can be added...

Nweekdays <- function(a, b, holidays, weekend) { 
possible_days <- seq(a, b, "days")
# Count all days that are not weekend and
# are not holidays
sum(!weekdays(possible_days) %in% weekend & !possible_days %in% holidays)
}

weekend <- c("Saturday", "Sunday")
holidays <- as.Date(c("2017-12-31", "2017-12-24", "2017-07-04"))
Nweekdays(as.Date("2017-08-01"), as.Date("2017-12-31"), holidays, weekend)
[1] 109

While the Gregorian calendar is pretty global, the definition of weekend and holidays is dependent on country, region, etc.

how can I add trading days?

Is this what you are looking for?

Create data:

library(chron)
dates <- seq.dates("07/03/2015", by = "day", length = 30)

Generate weekdays:

dates <- weekdays(as.Date(dates))

Extract the days of the week:

remove <- c('Saturday', 'Sunday')
dates [! dates %in% remove]

R adding days to a date

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"

Adding a new column days

The following works:

library(dplyr)
xYMW %>% dplyr::mutate(day = lubridate::wday(date))

If you input option label = TRUE, you can also turn this into abbreviated or non-abbreviated labels of Monday, Tuesday, ...

Calculate the number of weekdays between 2 dates in R

Date1 <- as.Date("2011-01-30")
Date2 <- as.Date("2011-02-04")
sum(!weekdays(seq(Date1, Date2, "days")) %in% c("Saturday", "Sunday"))

EDIT: And Zach said, let there be Vectorize :)

Dates1 <- as.Date("2011-01-30") + rep(0, 10)
Dates2 <- as.Date("2011-02-04") + seq(0, 9)
Nweekdays <- Vectorize(function(a, b)
sum(!weekdays(seq(a, b, "days")) %in% c("Saturday", "Sunday")))
Nweekdays(Dates1, Dates2)


Related Topics



Leave a reply



Submit