Book Image

Mastering Python for Finance

Book Image

Mastering Python for Finance

Overview of this book

Table of Contents (17 chapters)
Mastering Python for Finance
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Calculating the price of a bond


When the YTM is known, we can get back the bond price in the same way we used the pricing equation investigated earlier. Save the code as bond_price.py:

""" Get bond price from YTM """
def bond_price(par, T, ytm, coup, freq=2):
    freq = float(freq)
    periods = T*freq
    coupon = coup/100.*par/freq
    dt = [(i+1)/freq for i in range(int(periods))]
    price = sum([coupon/(1+ytm/freq)**(freq*t) for t in dt]) + \
            par/(1+ytm/freq)**(freq*T)
    return price

Plugging in the same values from the earlier example, we get the following result:

>>> from bond_price import bond_price
>>> bond_price(100, 1.5, ytm, 5.75, 2)
95.0428

This gives us the same original bond price discussed in the earlier example. Using the bond_ytm and bond_price functions, we can use them for further uses in bond pricing, such as finding the bond's modified duration and convexity. These two characteristics of bonds are of importance to bond traders to help them...