[This article was first published on Cartesian Faith » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: Cartesian Faith » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

# Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts.(You will not see this message again.)

Click here to close (This popup will not appear again)