Convert your code into a function

Bond Valuation and Analysis in R

Clifford Ang

Senior Vice President, Compass Lexecon

Bond valuation function

  • We will value many bonds in this course
  • Steps described in prior chapter will be repeated
  • We will create the bondprc() function to simplify calculations
Bond Valuation and Analysis in R

Steps in bond valuation

  • Generalize these inputs:
    • p for par value
    • r for coupon rate
    • ttm for time to maturity
    • y for yield
  • We also make some of the code more generic
Bond Valuation and Analysis in R

Steps in bond valuation

cf <- c(rep(p * r, ttm - 1), p * (1 + r))
  • rep(x, y) - repeats y times the value of x
  • x = p * r = coupon payment
  • y = ttm - 1 = bond's time to maturity minus one year
  • p * (1 + r) = principal + final coupon payment
Bond Valuation and Analysis in R

Steps in bond valuation

cf <- data.frame(cf)
  • Convert to data frame so we can add variables to the data (same as last section)
cf$t <- as.numeric(rownames(cf))
  • Create time index used for discounting
    • rownames() of cf vector is equal to 1, 2, 3, 4, until the ttm of bond
    • as.numeric() needed to ensure values are read as numbers
Bond Valuation and Analysis in R

Steps in bond valuation

cf$pv_factor <- 1 / (1 + y)^cf$t
  • Calculate PV factor
cf$pv <- cf$cf * cf$pv_factor
  • Calculate PV of each cash flow
sum(cf$pv)
  • Sum PV to arrive at bond's value
Bond Valuation and Analysis in R

Wrap the code

  • Create the bondprc() function
  • This will take as inputs p, r, ttm, and y
bondprc <- function(p, r, ttm, y){
   cf <- c(rep(p * r, ttm - 1), p * (1 + r))
   cf <- data.frame(cf)
   cf$t <- as.numeric(rownames(cf))
   cf$pv_factor <- 1 / (1 + y)^cf$t
   cf$pv <- cf$cf * cf$pv_factor
   sum(cf$pv)
}
Bond Valuation and Analysis in R

Let's practice!

Bond Valuation and Analysis in R

Preparing Video For Download...