Google Ad sense



All source codes in this blog are also available in Gregory Choi's Github Source code Repository


  

Friday, March 4, 2016

How to calculate the bond duration in R (Updated)

[Concept of the bond duration]


















As you can see above picture, the bond duration tells you the balance point of total cash flow. If the bond duration is larger, it means that the bond's cash flow is focused on its maturity, implying that it has more exposure to the risk (uncertainty)


It also can be explained by the first derivative of the bond yield-price curve. Long time ago, there was no computing power to calculate the bond price corresponding to the yield rate. (That's no longer case) In order to estimate the bond price corresponding to changing interest rate, investors came up with the concept of "duration"

It's formula is like below.



[Codes]

#This function allows you to get the macaulay duration of the bond
#Maturity = maturity of the bond i.e., 1yr, 2yr
#par = par value of the bond i.e., 100
#coupon = coupon rate i.e. if it is 8% -> 100*0.8=8
#discount = discount rate or YTM i.e., 0.03, 0.04
#k = how often coupon is given in a year. i.e. semiannual=> k=2
#Example: f.duration(maturity=2, par=100, coupon=8, discount=0.08, k=2)

f.duration = function(maturity, par, coupon, discount, k=1)
{
    duration = NULL
    coupon_payment <- k*maturity
    if(coupon == 0) {
      #zero coupon bond
      return(maturity)
    }
 
    for(i in 1:coupon_payment) {
        if(i==coupon_payment) {
          duration[i] <- ((i/k) * ((coupon/k)+par))/(1+(discount/k))^i
        } else {
          duration[i] <- ((i/k) * (coupon/k))/(1+(discount/k))^i
        }
    }

    return(sum(duration)/par)
}


No comments:

Post a Comment