Convert your code into a bond valuation function
In the prior exercises, you worked through in a step-by-step fashion how to calculate the value of a bond. However, performing all those steps repeatedly to value many bonds will be cumbersome. Fortunately, you can create a function to perform those same calculations repeatedly for different bonds.
The function you create must have the flexibility to allow you to input key features of the bond. Specific to our prior example, you'll need the function to be able to incorporate a bond's par value, coupon rate, time to maturity, and yield.
In this exercise, you'll create the function bondprc that takes these four inputs to calculate the value of a bond. Recall that to create a function you can use function(input 1, input 2, ...) { [lines of code] }.
Diese Übung ist Teil des Kurses
Bond Valuation and Analysis in R
Anleitung zur Übung
- A partially built function,
bondprc, has been generated in your workspace. Complete the function by constructing thefunction()command and providing the names of four inputs:pfor par value,rfor coupon rate,ttmfor time to maturity, andyfor yield. - Verify that the
bondprcfunction gives us a price of $95.79 for the value of a bond with a $100 par value, 5% coupon rate, 5 years to maturity, and 6% yield to maturity.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
# Create function
bondprc <- ___(___, ___, ___, ___) {
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)
}
# Verify prior result
bondprc(___, ___, ___, ___)