Calculating DV01 using futile.paradigm

April 25, 2011
By

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

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 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.