Zero rates with futile.paradigm

February 8, 2012
By

(This article was first published on Cartesian Faith » R, and kindly contributed to R-bloggers)

Here’s a short example of calculating zero rates and discount factors from cash rates using futile.paradigm. Of note is how type conversions are handled and how the core function implementation focuses strictly on the calculation while overloaded versions focus on the type conversions.

discount_factor %when% (day.count %isa% Act360)
discount_factor %also% is.character(spot.date)
discount_factor %also% is.character(maturity.date)
discount_factor %as% function(deposit.rate, spot.date, maturity.date, day.count)
{
  s <- as.Date(spot.date)
  m <- as.Date(maturity.date)
  discount_factor(deposit.rate, s, m, day.count)
}

discount_factor %when% (day.count %isa% Act360)
discount_factor %also% (spot.date %isa% Date)
discount_factor %also% (maturity.date %isa% Date)
discount_factor %as% function(deposit.rate, spot.date, maturity.date, day.count)
{
  days <- as.numeric(maturity.date - spot.date, units="days")
  discount_factor(deposit.rate, days, day.count)
}

discount_factor %when% (day.count %isa% Act360)
discount_factor %also% is.numeric(days)
discount_factor %as% function(deposit.rate, days, day.count)
{
  1 / (1 + deposit.rate * days / 360)
}

zero_rate %when% is.character(spot.date)
zero_rate %also% is.character(maturity.date)
zero_rate %as% function(discount.factor, spot.date, maturity.date)
{
  s <- as.Date(spot.date)
  m <- as.Date(maturity.date)
  zero_rate(discount.factor, s,m)
}

zero_rate %when% (spot.date %isa% Date)
zero_rate %also% (maturity.date %isa% Date)
zero_rate %as% function(discount.factor, spot.date, maturity.date)
{
  days <- as.numeric(maturity.date - spot.date, units="days")
  zero_rate(discount.factor, days)
}

zero_rate %when% is.numeric(days)
zero_rate %as% function(discount.factor, days)
{
  1 / df ^ (1/(days/365)) - 1
}

Also of note is how types can be used for polymorphism. These types can be created on the fly without a formal definition.

To call the functions,

df <- discount_factor(0.0123375,
  '2009-02-05', '2009-05-05', create(Act360))
zr <- zero_rate(df, '2009-02-05', '2009-05-05')


To leave a comment for the author, please follow the link and comment on his blog: Cartesian Faith » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,

Comments are closed.