Use uniroot function to find YTM
Trial-and-error is a very cumbersome process. An alternative is to use an algorithm that does the work for you. In this particular case, the solution to the problem is the same as finding the root of a function.
In this exercise, you will use the unrioot() function to find the root.
The uniroot()
function requires us to setup a vector of cash flows, cf
, that begins with the price of the bond (as a negative number) as the first element and the cash flows you expect to receive from the bond (i.e., coupon and principal payments) as the remaining elements.
Recall that the price of the bond is $95.79 and the bond has a $100 par value, 5% coupon rate, and 5 years to maturity.
This is a part of the course
“Bond Valuation and Analysis in R”
Exercise instructions
- Create a vector of cash flows,
cf
, which includes the initial bond price (negative) and payments until maturity (positive). - Use the pre-written code to create a simple bond valuation function,
bval()
, which calculates the value of the bond at each time period. - Use the pre-written code to create the
ytm()
function usinguniroot()
. - Use
ytm()
with yourcf
vector to find the bond's yield to maturity.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create cash flow vector
cf <- c(___, ___, ___, ___, ___, ___)
# Create bond valuation function
bval <- function(i, cf,
t=seq(along = cf))
sum(cf / (1 + i)^t)
# Create ytm() function using uniroot
ytm <- function(cf) {
uniroot(bval, c(0, 1), cf = cf)$root
}
# Use ytm() function to find yield
This exercise is part of the course
Bond Valuation and Analysis in R
Learn to use R to develop models to evaluate and analyze bonds as well as protect them from interest rate changes.
Estimating Yield To Maturity - The YTM measures the expected return to bond investors if they hold the bond until maturity. This number summarizes the compensation investors demand for the risk they are bearing by investing in a particular bond. We will discuss how one can estimate YTM of a bond.
Exercise 1: Price-yield relationshipExercise 2: Credit ratingsExercise 3: The yield on the Moody's Baa indexExercise 4: Value the 5% bond using the Baa yield you foundExercise 5: Plotting the price/yield relationshipExercise 6: Components of yieldExercise 7: Risk-free yieldExercise 8: Plotting US Treasury yieldsExercise 9: Plotting the investment grade spreadExercise 10: Estimating the yield of a bondExercise 11: Finding a bond's yieldExercise 12: Use uniroot function to find YTMWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.