Plotting bond prices against yields
Being able to plot a graph of bond prices against yields can help to investigate what will happen to a bond or portfolio of bonds for different levels of interest rates in the market.
Now you are going to create a graph of bond prices against yields, but this time for two bonds of different maturities. You will do this by giving your pandas
DataFrame extra columns for each additional bond. The bonds you will consider will both pay a 5% coupon, but now you will plot a 5 year and a 10 year bond.
numpy
, numpy_financial
, pandas
, and matplotlib
have already been imported for you as np
, npf
, pd
, and plt
, respectively.
This exercise is part of the course
Bond Valuation and Analysis in Python
Exercise instructions
- Create an array of bond yields from 0 to 20 (not inclusive) in increments of 0.1.
- Convert this array into a
pandas
DataFrame and name the columnbond_yield
. - Add two more columns, one for each bond (5-year and 10-year), and find the price for a given level of yield.
- Plot a graph of these bonds, setting the x-axis label to
Yield (%)
and y-axis label toBond Price (USD)
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create an array of bond yields and convert to DataFrame
bond_yields = np.arange(____, ____, ____)
bond = pd.DataFrame(____, columns=['____'])
# Add columns for different bonds
bond['bond_price_5Y'] = -npf.pv(rate=bond['bond_yield'] / 100, nper=____, pmt=____, fv=____)
bond['bond_price_10Y'] = -npf.pv(rate=____, nper=____, pmt=____, fv=____)
# Plot graph of bonds
plt.plot(bond['bond_yield'], bond['bond_price_5Y'], label='5 Year Bond')
plt.plot(____, ____, label='10 Year Bond')
plt.xlabel(____)
plt.ylabel(____)
plt.legend()
plt.show()