Friday, May 05, 2023

Calculating the Yield To Maturity (YTM) of a bond with Python coding

 


This equation is to calculate the present value of a bond based on the interest rate (r) which is usually fluctuating over years to calculate the present value of this bond.

The Yield To Maturity (YTM) is calculated under a given market price at the current time period which is substituted to the present value (PV). The Yield To Maturity (YTM) is the fixed value substituted to the interest rate (r).

It applies the built-in function of "newton" from "scripy.optimize" quoted from https://stackoverflow.com/questions/66431104/python-yield-to-maturity-finance-bonds to calculating the YTM. 

The following codes are the codes to calculate the YTM of the bond.

# The Newton Optimisation of calculating the Yield To Maturity (YTM) of bond.
import math
from scipy.optimize import newton
import matplotlib.pyplot as plt 

# Define a function to calculate the present value of a bond
F=1000 # The face value of bond
c=0.08 # The coupon payment payment rate per face value
M=F*c # The coupon payment value with the given payment rate
m=2 # Frequency of the coupon payment. E.g. Semi-annual payment so twice a year 
t=6 # The year from now to the maturity date
n=t*m
mktprc=980 # The market value 
Guess=0.28 # Just a randomly selected number, but don't make it too diverged from the estimated YTM

print('\033[1m --- \033[4m YTM calculation \033[0m --- \033[0m')
def pv_bond(ytm):
    pv = 0
    for i in range(n):
        # Calculate present value of each coupon payment
        pv += M/m*math.exp(-1*ytm/m*i)   # coupons present value
    # Add present value of face value to total present value
    return pv+F*math.exp(-1*ytm/m*i) # Define a function to calculate the difference between market price and calculated price
def diff(ytm):
    return market_price - pv_bond(ytm=ytm)
market_price=mktprc #put ur market price based on task #3 # Use Newton-Raphson method to find root of diff function (i.e., YTM)
ytm = newton(func=diff,x0=Guess) 
print(f'The yield to maturity (YTM) is: {ytm:.2%}') # showing to the 2nd decimal place 

# Caluculating the bond's present value based on the interest rate = the YTM
print('\033[1m --- \033[4m Bond value calculation \033[0m --- \033[0m')
pv=0
for i in range(n):
    # Calculate present value of each coupon payment
    pv += M/m*math.exp(-1*ytm/m*i)  # coupons present value
    print(i*15,'months',i/2,'th year Interest Rate:',round(ytm,3),'%','  Coupons:',round(pv,2))
# Add the present total values of coupons to the the present value of the bond
P=F*math.exp(-1*ytm/m*i)+pv
print(f'The bound price based on the constrant rate {ytm:.2%} is {round(P,2)} .')



The result will be shown as