R/download-yields.R

#' Download Treasury bill and bond yields from Bank of Canada website.
#'
#' @param years_span 	A positive integer
#'
#' @return dt 		    Data.table of yields for the last \code{years_span} years
#'
#' @export
#'
#' @examples
#' # For the last year of bond yields data
#' download_yields(1)
#'
#' # For the last 10 years of bond yields data
#' download_yields(10)
#'
download_yields <- function( years_span = 10 ){
  datatable_loaded <- requireNamespace( "data.table", quietly = TRUE )
  stopifnot( datatable_loaded )
  # Download bills and bonds, then merge
  bonds <- download_bondyields( years_span = years_span )
  bills <- download_billyields( years_span = years_span )
  overnight <- download_overnight( years_span = years_span )
  dt <- merge( bills, bonds, by = "dates" , all = TRUE )
  dt <- merge( overnight, dt, by = "dates" , all = TRUE )
  # Convert to data.table
  data.table::setDT( dt )
  # Clean up/remove holidays (contains strings)
  is_bill_holiday <- stringr::str_detect( dt$MONTH1, '[[:alpha:]]+' )
  is_bond_holiday <- stringr::str_detect( dt$MONTH24, '[[:alpha:]]+' )
  is_overnight_holiday <- stringr::str_detect( dt$OVERNIGHT, '[[:alpha:]]+' )
  keep_rows <- !( is_bill_holiday | is_bond_holiday | is_overnight_holiday )
  dt <- dt[ keep_rows, ]
  # Convert strings to numeric for rates
  ratecols <- names( dt )[ !stringr::str_detect( names( dt ), 'date' ) ]
  dt[ , ( ratecols ) := lapply( .SD, as.numeric ), .SDcols = ratecols ]
  return( dt )
}
vathymut/bondyields documentation built on May 3, 2019, 4:35 p.m.