import numpy_financial as npf
cash_flows = [-90, 2.5, 2.5, 2.5, 102.5]
r = npf.irr(cash_flows)
y = 2*r
print(f"The bond yield is {y:.2%}")
The bond yield is 10.69%
In this example, you are getting, roughly,
where $y=$ yield and $n=$ number of years to maturity.
years = 5
coupon = 1000 * 0.06 / 2
yld = 0.08
pv_factors = (1+yld/2)**np.arange(-1, -2*years-1, -1)
cash_flows = (coupon) * np.ones(2*years)
cash_flows[-1] += 1000
price = np.sum(PV_factors * cash_flows)
print(f"price is ${price:.2f}")
price is $918.89
# check yield
cash_flows = np.concatenate(([-price], cash_flows))
r = npf.irr(cash_flows)
print(f"yield is {2*r:.2%}")
yield is 8.00%
from pandas_datareader import DataReader as pdr
rates = pdr(["FEDFUNDS", "DGS10"], "fred", start=1900).dropna()
rates.columns = ["fedfunds", "10yr"]
sns.regplot(x="fedfunds", y="10yr", data=rates, ci=None, scatter_kws={"alpha": 0.5})
<AxesSubplot: xlabel='fedfunds', ylabel='10yr'>
yields = pdr(["DGS10", "DFII10"], "fred", start=1900).dropna()
yields.columns = ["Treasuries", "TIPS"]
yields.plot()
plt.ylabel("Yield in %")
plt.show()
(yields.Treasuries - yields.TIPS).plot()
plt.ylabel("Difference in yields in %")
plt.show()