[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**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 using the futile.paradigm for calculating the DV01 of a bond. The basic idea is to layout the type definitions and then create the functions to do the calculations.

require(futile.paradigm) create.Bond <- function(T, par, coupon, yield, periods, freq) { list(par=par, coupon=coupon, yield=yield, periods=periods, freq=freq) } # Inherit from the Bond type create.SemiBond <- function(T, par, coupon, yield, periods, freq=2) create(Bond, par, coupon, yield, periods, freq) price.bond %when% (bond %isa% Bond) price.bond <- function(bond) price(bond, bond$yield) price.bondy %when% (bond %isa% Bond) price.bondy <- function(bond, r) { r <- r / bond$freq n <- bond$periods coupon(bond) * (1 - (1+r)^-n) / r + bond$par * (1+r)^-n } dv01.bond %when% (bond %isa% Bond) dv01.bond <- function(bond) { y1 <- bond$yield - 0.0001 y2 <- bond$yield + 0.0001 p1 <- price(bond, y1) p2 <- price(bond, y2) - (p1 - p2) / (y1 - y2) / 100 }

The helper functions below show some of the power of guards. Depending on the value of a field, a different function variant can be called for the coupon calculation. (Note that this is used for illustrative purposes and would break down in the current ZIRP world.)

# When coupon is in percentage terms coupon.pct %when% (bond %isa% Bond && bond$coupon < 1) coupon.pct <- function(bond) bond$par * bond$coupon / bond$freq coupon.dollar %when% (bond %isa% Bond) coupon.dollar <- function(bond) bond$coupon / bond$freq

The code can be run by executing the below snippet.

> b <- create(SemiBond, 100,3.5, 0.035, 10) > dv01(b) [1] 8.376442

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.