Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 17

Cubic Spline Interpolation for Bootstrapped Spot Rates in Python

Recommended resources

Introduction

In our previous lesson, we established the robust theoretical foundation for using cubic splines in yield curve construction. We saw that they are the "smoothest" possible interpolant, guaranteeing continuity for the spot curve, which in turn produces the smooth, continuous forward curve that is essential for reliable financial modeling.

Today, we transition from theory to practice. Our objective is to implement cubic spline interpolation in Python to fit a continuous curve to a discrete set of bootstrapped spot rates. You will learn how to use scipy, a cornerstone of scientific computing in Python, to perform this interpolation efficiently. This lesson will bridge the gap between the mathematical constraints we've discussed and the practical code required to generate a complete, continuous yield curve.


1. From Theory to a System of Equations

Before we use a high-level library function, it's insightful to understand the computational task it performs. As we learned, constructing a cubic spline involves solving for coefficients by setting up a system of linear equations based on our continuity and boundary conditions.

The following video provides an excellent walkthrough of this process for a small dataset. It demonstrates how the interpolation, slope continuity, curvature continuity, and "natural" boundary conditions are translated into a matrix equation, which can then be solved to find the coefficients of each cubic segment.

Natural Cubic Spline Interpolation Example | Numerical Methods

This video, "Natural Cubic Spline Interpolation Example," from the StudySession channel, shows how to build the system of equations from scratch.

Watch the following segments to see how the theoretical constraints become a solvable problem: Problem setup: This recap shows how n data points lead to n-1 splines and 4(n-1) unknown coefficients. Deriving constraints: Watch how the conditions for C^0 (passing through points), C^1 (first derivative continuity), and C^2 (second derivative continuity) are formulated into equations. Boundary conditions: See how the "natural spline" assumption (second derivatives at endpoints are zero) provides the final two equations needed to solve the system. You don't need to follow the matrix construction in detail; the key is to appreciate how the theoretical rules we discussed are methodically converted into a standard linear algebra problem, Ax=b. This is precisely what libraries like scipy automate for us.


2. Implementing Cubic Splines with SciPy

While solving the matrix system manually is instructive, it's not practical. The scipy library provides a powerful and optimized tool, scipy.interpolate.CubicSpline, that handles all of this complex algebra behind the scenes.

This next video demonstrates how to use scipy's interpolation functions. While it covers linear and quadratic methods as well, we will focus on its superior CubicSpline implementation.

Spline Interpolation In Python (Linear, Quadratic, Cubic, etc…) | Numerical Methods

In "Spline Interpolation In Python," the StudySession channel demonstrates how to use the scipy.interpolate module.

Please focus on these key parts: Setup and Imports: This shows the necessary libraries: numpy for data arrays, matplotlib for plotting, and scipy.interpolate. Basic Cubic Interpolation: Note how interp1d with kind='cubic' works, but as the video explains, it doesn't allow for control over boundary conditions. Advanced Cubic Spline: This is the most important section. Pay close attention to the use of the CubicSpline class and the bc_type='natural' argument. This argument directly implements the natural cubic spline we discussed, which assumes zero curvature at the curve's endpoints.

The key takeaway is that with just a few lines of code, you can instantiate a spline object that represents a continuous function. This object can then be queried at any point within its domain to get an interpolated value.


3. Practical Application: Fitting to Bootstrapped Rates

Now, let's bring everything together. We will take a discrete set of spot rates—the kind you would obtain from the bootstrapping algorithm we built in Module 3—and use scipy.interpolate.CubicSpline to create a continuous spot rate curve.

Below is a complete Python script that demonstrates this process. It performs the following steps:

  1. Defines a sample set of bootstrapped tenors and corresponding spot rates.
  2. Initializes a CubicSpline object using this data, specifying 'natural' boundary conditions.
  3. Generates a new, much denser set of tenor points to ensure a smooth plot.
  4. Uses the spline object to calculate the interpolated spot rate for each point in the dense set.
  5. Plots the original discrete points against the final continuous curve.
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline




# 1. Sample bootstrapped spot rates (tenor in years, rate as decimal)
bootstrapped_tenors = np.array([0.5, 1.0, 2.0, 3.0, 5.0, 7.0, 10.0])
bootstrapped_rates = np.array([0.0465, 0.0475, 0.0500, 0.0520, 0.0540, 0.0555, 0.0575])




# 2. Create the natural cubic spline interpolator
# bc_type='natural' sets the second derivatives at the endpoints to zero.
cs = CubicSpline(bootstrapped_tenors, bootstrapped_rates, bc_type='natural')




# 3. Generate a dense set of tenors for a smooth plot
plot_tenors = np.linspace(bootstrapped_tenors.min(), bootstrapped_tenors.max(), 500)




# 4. Calculate the interpolated rates on the dense grid
plot_rates = cs(plot_tenors)




# 5. Plot the results
plt.figure(figsize=(12, 7))
plt.plot(bootstrapped_tenors, bootstrapped_rates, 'o', label='Bootstrapped Points', markersize=8, color='darkblue')
plt.plot(plot_tenors, plot_rates, label='Cubic Spline (Continuous Curve)', color='red', linewidth=2)

plt.title('Cubic Spline Interpolation of Spot Rate Curve', fontsize=16)
plt.xlabel('Tenor (Years)', fontsize=12)
plt.ylabel('Spot Rate', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend(fontsize=12)
plt.show()

Run this code yourself. Observe how the red line creates a smooth, continuous curve that passes exactly through each of the discrete bootstrapped data points. This cs object is now a functional representation of your yield curve. You can query it for the spot rate at any maturity, for example cs(1.5) to get the 1.5-year spot rate. This is far more powerful than the discrete set of points we started with.

The implementation shown here is a simplified example. Professional libraries, such as the one described in the "Yield Curve Modeling" paper (ID: LINK), often encapsulate this logic within a dedicated YieldCurve class. This class would not only hold the spline object but also methods for calculating discount factors and forward rates, providing a complete and robust tool for fixed-income analysis. For our purposes, understanding the core scipy implementation is the crucial step.


Conclusion

In this lesson, you have successfully translated the mathematical theory of cubic splines into a working Python implementation. By leveraging the scipy library, you can now construct a smooth, continuous yield curve from a discrete set of bootstrapped market rates.

Key Takeaways:

  • From Constraints to Code: The theoretical constraints of continuity () and boundary conditions are computationally solved by setting up and solving a system of linear equations.
  • scipy.interpolate.CubicSpline: This is the primary tool for this task in Python. It automates the complex matrix algebra, allowing you to create a spline object with a single function call.
  • Boundary Conditions Matter: The bc_type='natural' parameter is a direct implementation of the natural cubic spline, which is a common and mathematically optimal choice for general-purpose interpolation.
  • Continuous Representation: The resulting spline object acts as a continuous function, enabling you to query the spot rate for any tenor within your curve's range, not just the tenors of the input instruments.

In our next lesson, we will put this all together. We will generate and plot the spot and forward rate curves derived from linear, polynomial, and cubic spline interpolation on the same dataset. This direct comparison will provide a definitive visual answer to why splines are the superior method for yield curve construction.