Skip to content

Instantly share code, notes, and snippets.

@msperlin
Created April 9, 2022 11:48
Show Gist options
  • Save msperlin/831bb1e509c6cbe5879bd2f0deb5e6b9 to your computer and use it in GitHub Desktop.
Save msperlin/831bb1e509c6cbe5879bd2f0deb5e6b9 to your computer and use it in GitHub Desktop.
yc BR
yc_get <- function(first_date, last_date) {
first_date <- as.Date(first_date)
last_date <- as.Date(last_date)
# find biz days in between
br_cal <- get_calendar()
date_vec <- bizdays::bizseq(first_date, last_date, br_cal)
df_yc <- dplyr::bind_rows(
purrr::map(date_vec, get_single_yc)
)
return(df_yc)
}
get_calendar <- function() {
br_cal <- bizdays::create.calendar("Brazil/ANBIMA",
bizdays::holidaysANBIMA,
weekdays=c("saturday", "sunday"))
return(br_cal)
}
get_single_yc <- function(ref_date) {
cli::cli_alert_info('Fetching Yield Curve for {ref_date}' )
base_url <- stringr::str_glue(
"https://www2.bmf.com.br/pages/portal/bmfbovespa/lumis/lum-taxas-referenciais-bmf-ptBR.asp?",
"Data={format(ref_date, '%d/%m/%Y')}&Data1={format(ref_date,'%Y%m%d')}&slcTaxa=PRE"
)
char_vec <- rvest::read_html(base_url) |>
rvest::html_nodes("td") |>
rvest::html_text()
len_char_vec <- length(char_vec)
if (len_char_vec == 0) {
cli::cli_alert('can\'t find data for this date..')
return(dplyr::tibble())
} else {
cli::cli_alert_success('\tsucess, got {len_char_vec} data points')
}
idx1 <- seq(1, length(char_vec), by = 3)
idx2 <- seq(2, length(char_vec), by = 3)
idx3 <- seq(3, length(char_vec), by = 3)
biz_days <- char_vec[idx1]
r_252 <- char_vec[idx2]
r_360 <- char_vec[idx3]
my_locale <- readr::locale(decimal_mark = ',')
br_cal <- get_calendar()
df_single_yc <- dplyr::tibble(
ref_date,
biz_days = as.integer(biz_days),
forward_date = bizdays::add.bizdays(ref_date, biz_days, br_cal),
r_252 = readr::parse_double(r_252, locale = my_locale)/100,
r_360 = readr::parse_double(r_360, locale = my_locale)/100
)
return(df_single_yc)
}
first_date <- Sys.Date() - 10
last_date <- Sys.Date()
df_yc <- yc_get(first_date, last_date)
library(tidyverse)
graphics.off()
p <- ggplot(df_yc,
aes(x = biz_days,
y = r_360,
color = factor(ref_date))) +
geom_line()
x11() ; p
p <- ggplot(df_yc,
aes(x = biz_days,
y = r_252,
color = factor(ref_date))) +
geom_line()
x11() ; p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment