简体   繁体   中英

How to get date of last business day of month in R

I need to get the last businessday of the previous month from the current date with R (eg today is 5th of January 2018 , so I should get 29th of December 2017 as a result)

Thanks in advance

You need a business day calculator. Here I use one from RQuantLib which is a CRAN package.

Given a date, you can test if it is a business day in a given (exchange) calendar. Then you just subset by the time period you want. This would be easier with, eg, data.table but I kept it simpler here so that we depend only on one package:

R> library(RQuantLib)
R> dateseq <- seq(as.Date("2017-12-01"), as.Date("2017-12-31"), by="1 day")
R> df <- data.frame(dates=dateseq, bizday=isBusinessDay("UnitedStates", dateseq))
R> tail(df[ df[,"bizday"], ], 1)
        dates bizday
29 2017-12-29   TRUE
R> 
R> tail(df[ df[,"bizday"], "dates"], 1)
[1] "2017-12-29"
R> 

You can write your own function to find out last working days. You need to define off days of a week to take decision.

# Off days
offdays <- c("Saturday", "Sunday")

# Say you want to find out last working date of December 2017
monthdates <- seq(as.Date("2017-12-01"), as.Date("2017-12-31"), by="1 day")

#Eliminate off days
monthdates<- monthdates[! weekdays(monthdates) %in% offdays]

#Find out max date in vector now
lastworkingday <- max(monthdates)

#> lastworkingday
#[1] "2017-12-29"

This one was difficult to vectorize and make fast given the interplay between weekends and holidays, ie

  • your holidays near month-end might push you into a weekend near monthend

  • a weekend that falls on monthend could push you into your holidays near monthend

# get these packages
 require(lubridate)
 require(tidyverse)


calc_business_monthends<- function(dates = NULL, 
                                   holidays = NULL, 
                                   prior_month = FALSE){

  # terminate early 
  if (length(dates) == 0) return(dates)

  # make dates into prior monthend dates
  in_dates<- rollback(dates)

  # or make dates into current monthend dates
  if(!prior_month) in_dates<- rollback((in_dates + 1) + months(1))


  # inner function to recursively check dates and step backward if monthend falls on a holiday or weekend
  step_back<- function(in_dates, holidays) {

    # correct for Sun or Sat
    out_dates<- 
      case_when(wday(in_dates) == 7 ~ in_dates - 1,
                wday(in_dates) == 1 ~ in_dates - 2,
                TRUE ~ in_dates)

    # correct for holidays
    if(!is.null(holidays)){
      out_dates<- 
        if_else(out_dates %in% holidays, out_dates - 1, false = out_dates)
    }

    # if no weekend or holiday changes, we're done; otherwise recurse
    if(identical(out_dates,in_dates)){

      out_dates

    } else {

      step_back(out_dates, holidays)

    }

  } # inner-function end


  # call inner-function 
  step_back(in_dates, holidays)

}

Then just pass the function any dates and holidays you want.

Here are some tests:

Some example dates:
dates<- seq(ymd(20190105), by='month', length.out = 24)

Some holidays near monthend:
holidays<- ymd(20190527,20200525,20210531,20220530,20230529,20240527)

Output:
> calc_business_monthends(dates, holidays)
 [1] "2019-01-31" "2019-02-28" "2019-03-29" "2019-04-30"
 [5] "2019-05-31" "2019-06-28" "2019-07-31" "2019-08-30"
 [9] "2019-09-30" "2019-10-31" "2019-11-29" "2019-12-31"
[13] "2020-01-31" "2020-02-28" "2020-03-31" "2020-04-30"
[17] "2020-05-29" "2020-06-30" "2020-07-31" "2020-08-31"
[21] "2020-09-30" "2020-10-30" "2020-11-30" "2020-12-31"

> calc_business_monthends(dates, holidays, prior_month = TRUE)
 [1] "2018-12-31" "2019-01-31" "2019-02-28" "2019-03-29"
 [5] "2019-04-30" "2019-05-31" "2019-06-28" "2019-07-31"
 [9] "2019-08-30" "2019-09-30" "2019-10-31" "2019-11-29"
[13] "2019-12-31" "2020-01-31" "2020-02-28" "2020-03-31"
[17] "2020-04-30" "2020-05-29" "2020-06-30" "2020-07-31"
[21] "2020-08-31" "2020-09-30" "2020-10-30" "2020-11-30"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM