Hi! This is the code I wrote for my first assignment in Mathematical Theory of Finance (APM466) for Prof. Luis Seco. The goal was to build a term structure model from scratch using real market data for Canadian Government Bonds.
Instead of just plugging numbers into a black box, I implemented the algorithms manually to really understand how the math works—from bootstrapping spot rates to running Principal Component Analysis (PCA) on the yield curves.
- Data Processing: Takes raw historical bond prices (from Jan 2026), cleans them, and calculates the "dirty price" by accounting for accrued interest.
- Curve Construction:
- YTM Curve: Solved for the Yield to Maturity using a root-finding algorithm (Newton-Raphson).
- Spot Curve: Built a bootstrapping algorithm to strip coupons and derive zero-coupon spot rates.
- Forward Curve: Calculated 1-year forward rates from the spot curve.
- Risk Analysis (PCA): I calculated the covariance matrices for daily log-returns and performed PCA.
- Result: I found that the first principal component explains 93.7% of the variance, confirming that the "Level" factor (parallel shift) is the main driver of the Canadian yield curve.
Here is what each script does:
Question-4a-YTM_Curve.py: Calculates YTMs and plots the 5-year Yield Curve.Question-4b-Spot_Curve.py: Runs the bootstrapping logic to generate the Spot Rate Curve.Question-4c-Forward_Curve.py: Derives the 1-year Forward Rate curve (1yr-1yr to 1yr-4yr).Question5_Question6.py: Handles the heavy statistics—calculating log-returns, covariance matrices, and extracting Eigenvalues/Eigenvectors for PCA.bond_data.xlsx: The dataset I compiled containing 10 selected bonds and their daily close prices.APM466 Assignment 1 Answers.pdf: My full written report explaining the math and economic theory behind the code.
- Python
- Pandas (Data manipulation)
- NumPy (Linear Algebra)
- SciPy (Optimization & Interpolation)
- Matplotlib (Visualization)
You just need the standard data science libraries installed.
pip install pandas numpy scipy matplotlib openpyxl
python Question-4a-YTM_Curve.py
python Question-4b-Spot_Curve.py
python Question-4c-Forward_Curve.py
python Question5_Question6.py