wilsonfreitas / R-fixedincome

Fixed income tools for R
http://wilsonfreitas.github.io/R-fixedincome/
Other
51 stars 25 forks source link

Chalenges to create US Treasury Curve #23

Closed wilsonfreitas closed 2 years ago

wilsonfreitas commented 2 years ago

Create US Treasury Curve with data from Quandl.

Here we have the spot rate curve.

image

Issues to adress:

Here it shows the current state to build US Treasury Curve. The big issue relies on the creation of the term.

library(Quandl)

yc_all <- Quandl("USTREASURY/YIELD",
  api_key = "nJ1NhTYdEs2p3MsS4CVd"
)

library(purrr)
library(stringr)
library(fixedincome)
library(tidyverse)

yc <- yc_all |> filter(Date == "2008-12-31")

nx <- names(yc)
terms_names <- nx[-1]
terms_names <- str_replace(terms_names, "MO", "months") |>
  str_replace("YR", "years")
curve_terms <- map(terms_names, as.term)
dc <- daycount("actual/360")
terms <- curve_terms |>
  map_dbl(\(x) dib(dc) * toyears(dc, x)) |>
  term("days")

rates <- yc[1, -1] |>
  as.list() |>
  as.numeric()

rates <- rates / 100
ix <- !is.na(rates)

tr_curve <- spotratecurve(
  rates[ix], terms[ix],
  "simple", "actual/360", "actual"
)
wilsonfreitas commented 2 years ago

Done ea6263d2518bb794d4f0c9d1ade66f5a996b2684

wilsonfreitas commented 2 years ago

Now the code becomes

library(Quandl)
library(tidyverse)

yc_all <- Quandl("USTREASURY/YIELD")

refdate <- as.Date("2022-02-04")
yc <- yc_all |> filter(Date == refdate)
nx <- names(yc)
terms_names <- nx[-1]
terms_names <- terms_names |>
  str_replace("MO", "months") |>
  str_replace("YR", "years")

curve_terms <- as.term(terms_names)

rates <- yc[1, -1] |>
  as.list() |>
  as.numeric()
rates <- rates / 100
ix <- !is.na(rates)

tr_curve <- spotratecurve(
  rates[ix], curve_terms[ix],
  "simple", "actual/360", "actual",
  refdate = refdate
)