O'Reilly logo

Mastering Python for Finance by James Ma Weiming

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required