Financial Calculations & Valuation
Intermediate
Calculate Bond Yield to Maturity (YTM) & Macaulay Duration in Python
Solve exact Bond Yield to Maturity (YTM), Macaulay Duration, and Modified Duration for fixed-income bonds using SciPy in Python.
#numpy#scipy
Problem Statement
Bond YTM has no closed-form algebraic solution and requires iterative numerical root-finding alongside duration sensitivity metrics to measure interest rate risk.
Formula / Core Logic
Price = Sum [ Coupon / (1 + YTM/f)^t ] + Face / (1 + YTM/f)^N
Modified Duration = Macaulay_Duration / (1 + YTM/f)
Installation
pip install numpy scipy
bond-yield-to-maturity-ytm-duration-calculator-python.py
import numpy as np
from scipy.optimize import newton
def bond_ytm_and_duration(price, face_val, coupon_rate, years, freq=2):
periods = int(years * freq)
coupon = (coupon_rate / freq) * face_val
times = np.arange(1, periods + 1)
def price_diff(ytm):
r = ytm / freq
pv_coupons = np.sum(coupon / ((1 + r) ** times))
pv_face = face_val / ((1 + r) ** periods)
return (pv_coupons + pv_face) - price
ytm = newton(price_diff, coupon_rate)
r = ytm / freq
cfs = np.array([coupon] * (periods - 1) + [coupon + face_val])
pv_cfs = cfs / ((1 + r) ** times)
mac_dur = np.sum((times / freq) * pv_cfs) / price
mod_dur = mac_dur / (1 + r)
return {'YTM_Pct': round(ytm * 100, 3), 'Macaulay_Duration_Yrs': round(mac_dur, 2), 'Modified_Duration': round(mod_dur, 2)}
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: What does Modified Duration of 4.5 mean?
It means if interest rates rise by 1% (100 bps), the bond's market price will fall by approximately 4.5%.