Skip to content

Instantly share code, notes, and snippets.

@mgei
Created January 16, 2021 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgei/9d5861de60d54aceabaf8f9633934c98 to your computer and use it in GitHub Desktop.
Save mgei/9d5861de60d54aceabaf8f9633934c98 to your computer and use it in GitHub Desktop.
library(tidyquant)
ty10 <- tq_get("DGS10", get = "economic.data", from = as.Date("1950-01-01"))
mod_dur <- function(yield) {
# out <- (1-(1/(1+0.5*yield/100)^(2*10)))/(yield/100)
out <- (1-(1/(1+0.5*yield)^(2*10)))/(yield)
return(out)
}
convexity <- function(yield) {
# out <- (2/(yield/100)^2)*(1-(1/(1+yield/200)^(20)))-20/((yield/100)*(1+yield/200)^(21))
out <- (2/(yield)^2)*(1-(1/(1+yield/2)^(20)))-20/((yield)*(1+yield/2)^(21))
return(out)
}
return_m <- function(yield, yield_lag, mdur = mod_dur(yield), convex = convexity(yield), scale = 252) {
if (is.na(yield_lag)) {
return(NA_real_)
}
# out <- -mdur*(yield/100-yield_lag/100) + 0.5*convex*(yield/100-yield_lag/100)^2 + ((1+yield_lag/100)^(1/12)-1)
out <- -mdur*(yield-yield_lag) + 0.5*convex*(yield-yield_lag)^2 + ((1+yield_lag)^(1/scale)-1)
return(out)
}
convexity_m_V <- Vectorize(convexity)
return_m_V <- Vectorize(return_m)
mod_dur(4)
convexity(4)
ty10 %>%
group_by(m = floor_date(date, "months")) %>%
filter(date == max(date)) %>%
ungroup() %>%
select(-m) %>%
mutate(r = return_m_V(yield = price/100, yield_lag = lag(price)/100), scale = 12) %>%
filter(!is.na(r)) %>%
mutate(p = cumprod(1+r)*100) %>%
group_by(m = floor_date(date, "months")) %>%
filter(date == max(date))
ty10 %>%
mutate(r = return_m_V(yield = price/100, yield_lag = lag(price)/100))
return_m(yield = 3.86, yield_lag = 3.86)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment