< Return to Fixed Income

Fixed Income Volatility: Modified Duration

Education Hero Image

Python User Guide: Calculating Modified Duration

Introduction

This user guide will walk you through the process of calculating modified duration using Python, a powerful programming language. Modified duration is a crucial metric in bond analysis, helping you gauge the impact of interest rate changes on bond prices. Let's dive into the steps.

Step 1: Set Up Your Python Environment

Ensure you have Python installed on your computer. You can download Python from the official website: Python Downloads.

Step 2: Open a Python Environment

Open your preferred Python environment or IDE (Integrated Development Environment), such as Jupyter Notebook, VSCode, or Spyder.

Step 3: Input Bond Details

Define the bond details in your Python script:

# Bond details
face_value = 1000
coupon_rate = 0.05  # 5%
coupon_payment = face_value * coupon_rate
time_to_maturity = 5
yield_to_maturity = 0.04  # 4%

Step 4: Calculate Macaulay Duration

Write a function to calculate Macaulay Duration:

def calculate_macaulay_duration(face_value, coupon_rate, time_to_maturity, yield_to_maturity):
    cash_flows = [coupon_payment] * time_to_maturity
    cash_flows[-1] += face_value  # Add the face value at maturity
    macaulay_duration = sum([cf / (1 + yield_to_maturity) ** t * (t + 1) for t, cf in enumerate(cash_flows)]) / sum(cash_flows)
    return macaulay_duration

macaulay_duration = calculate_macaulay_duration(face_value, coupon_rate, time_to_maturity, yield_to_maturity)

Step 5: Calculate Modified Duration

Write a function to calculate Modified Duration:

def calculate_modified_duration(macaulay_duration, yield_to_maturity):
    modified_duration = macaulay_duration / (1 + yield_to_maturity)
    return modified_duration

modified_duration = calculate_modified_duration(macaulay_duration, yield_to_maturity)

Step 6: Interpret the Results

Print and interpret the calculated values:

print(f"Macaulay Duration: {macaulay_duration:.2f} years")
print(f"Modified Duration: {modified_duration:.2f} years")

Conclusion

Congratulations! You've successfully calculated Macaulay Duration and Modified Duration for a bond using Python. These metrics offer valuable insights into the bond's characteristics and its response to interest rate changes. Feel free to modify the bond details and experiment with different scenarios to enhance your understanding of modified duration in Python.

This article takes inspiration from a lesson found in FIN 4243 at the University of Florida.