# Zero\_rate function in python

**URL:** <https://quantlab.discourse.group/t/zero-rate-function-in-python/113>\
**Category:** Qlang Financial Libraries\
**Created:** [August 25, 2025, 1:20pm UTC](https://quantlab.discourse.group/t/zero-rate-function-in-python/113 "2025-08-25T13:20:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Carlkong](https://avatars.discourse-cdn.com/v4/letter/c/6f9a4e/32.png) [@Carlkong](https://quantlab.discourse.group/u/Carlkong)\
**Post date:** [August 25, 2025, 1:20pm UTC](https://quantlab.discourse.group/t/zero-rate-function-in-python/113/1 "2025-08-25T13:20:12Z")

</div>

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?

```auto
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)

```

---

<div class="post-metadata">

**Author:** ![QuantlabAdmin](https://yyz1.discourse-cdn.com/flex003/user_avatar/quantlab.discourse.group/quantlabadmin/32/10_2.png) [@QuantlabAdmin](https://quantlab.discourse.group/u/QuantlabAdmin)\
**Post date:** [August 25, 2025, 1:47pm UTC](https://quantlab.discourse.group/t/zero-rate-function-in-python/113/2 "2025-08-25T13:47:58Z")

</div>

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:

 ![image](https://canada1.discourse-cdn.com/flex003/uploads/quantlab/original/1X/d6ec1cf407343dfdd56507ef08af080b51339ea8.png)

---

<div class="post-metadata">

**Author:** ![QuantlabAdmin](https://yyz1.discourse-cdn.com/flex003/user_avatar/quantlab.discourse.group/quantlabadmin/32/10_2.png) [@QuantlabAdmin](https://quantlab.discourse.group/u/QuantlabAdmin)\
**Post date:** [August 25, 2025, 2:00pm UTC](https://quantlab.discourse.group/t/zero-rate-function-in-python/113/3 "2025-08-25T14:00:54Z")

</div>

Adding that the correct syntax for an up-to-date quantlab library is found here:  
disc\_func.zero\_rate( … )

> **[Quantlab Function Library](https://www.quantlab.eu/quantlab-function-library/memfunc/function-disc_func-zero_rate.htm)**
>
> Web site created using create-react-app
