Zero_rate function in python

Having trouble using the zero_rate function in python, trying to plot a basic zero yield curve.

The market yield curve works fine but not when I am using the zero_rate function, is there something I have missed here?

import ql
import datetime
import matplotlib.pyplot as plt
import numpy as np

def get_curve(bond, date):
    curve_obj = ql.curve(bond, date, "Bid")
    instruments = curve_obj.instruments()
    names = []
    maturities = []
    yields = []
    prices = []
    for instrument in instruments:
        names.append(instrument.name())
        maturities.append(instrument.maturity())
        yield_value = getattr(instrument, 'yield')()
        yields.append(yield_value * 100)
        prices.append(instrument.clean_price())
    return names, maturities, yields, prices

def plot_yield_curve_simple(bond, date):
    """
    Plottar den enkla yield kurva
    """
    names, maturities, yields, prices = get_curve(bond, date)
    
    # Konvertera maturities till år
    current_date = date if isinstance(date, datetime.date) else datetime.date(*map(int, date.split('-')))
    years_to_maturity = []
    
    for maturity in maturities:
        if isinstance(maturity, datetime.date):
            delta = maturity - current_date
            years = delta.days / 365.25
            years_to_maturity.append(years)
        else:
            years_to_maturity.append(maturity)
    
    plt.figure(figsize=(10, 6))
    plt.plot(years_to_maturity, yields, 'bo-', linewidth=2, markersize=6)
    plt.xlabel('Löptid (år)')
    plt.ylabel('Yield (%)')
    plt.title(f'{bond} Yield Kurva - {date}')
    plt.grid(True, alpha=0.3)
    plt.show()
    
    return years_to_maturity, yields, prices

def plot_zero_curve_simple(bond, date):

    try:
        # Skapa bootstrap kurva
        curve_obj = ql.curve(bond, date, "Bid")
        fit_result = ql.bootstrap(curve_obj)
        
        # Skapa punkter för kurvan
        maturities = np.arange(0.1, 10.1, 0.1)
        zero_rates = []
        
        for maturity in maturities:
            try:
                rate = fit_result.zero_rate(0, maturity)  #Beräknar ZERO rate - ERROR!!
                zero_rates.append(rate * 100)
            except:
                break
        
        if zero_rates:
            plt.figure(figsize=(10, 6))
            plt.plot(maturities[:len(zero_rates)], zero_rates, 'ro-', linewidth=2, markersize=4)
            plt.xlabel('Löptid (år)')
            plt.ylabel('Zero Coupon Rate (%)')
            plt.title(f'{bond} Zero Coupon Kurva - {date}')
            plt.grid(True, alpha=0.3)
            plt.show()
            
            return maturities[:len(zero_rates)], zero_rates
        else:
            print("Kunde inte skapa zero coupon data")
            return None, None
            
    except Exception as e:
        print(f"Bootstrap fel: {e}")
        return None, None

# Användning - exakt samma stil som du hade:
bond = "SEKGOVT"
date = datetime.date(2025, 8, 24)

# Yield kurva
print("Skapar yield kurva...")
years, yields, prices = plot_yield_curve_simple(bond, date)

# Zero coupon kurva
print("Skapar zero coupon kurva...")
zero_years, zero_rates = plot_zero_curve_simple(bond, date)

Hi,
a couple of issues:

  1. date = datetime.date(2025, 8, 24) is a Sunday. → Change to 25 i.e. today for there to be data.

  2. fit_result = ql.bootstrap(curve_obj, ql.ip_spline()). → I would use an explicit interpolator in the bootstrap so you know what you are getting as a result. (default might be set to ip_linear.)

  3. rate = fit_result.zero_rate(0, maturity, ql.rate_type.RT_EFFECTIVE) → the zero_rate function using argument from,to needs a third argument; namely the rate type of the rates to be extracted. Here ql.rate_type.RT_EFFECTIVE (or RT_CONT or RT_SIMPLE depending on usage.)

think thats it. See my screen below:

2 Likes

Adding that the correct syntax for an up-to-date quantlab library is found here:
disc_func.zero_rate( … )