Files
strategy-lab/to_explore/pyquantnews/30_AnimatedYieldCurve.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

8.0 KiB

No description has been provided for this image

This code retrieves U.S. Treasury bond yield data using the OpenBB SDK and visualizes the yield curve over time. It sets up the necessary imports, initializes plotting parameters, and configures the OpenBB SDK with a FRED API key. The script extracts treasury yield data for various maturities and indicates whether the yield curve is inverted. An animation is created to dynamically display the yield curve changes over time, highlighting inversions in red.

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
In [ ]:
from openbb_terminal.sdk import openbb

Define font properties for the plot

In [ ]:
font = {
    "family": "normal",
    "weight": "normal",
    "size": 12
}
In [ ]:
plt.rc('font', **font)

Configure OpenBB SDK with FRED API key

In [ ]:
openbb.keys.fred(
    key="3d20c1fcbb26ea21b9f78fafbbdce900",
    persist=True,
)

Define treasury bond maturities to be retrieved

In [ ]:
maturities = ['3m', '6m', '1y', '2y', '3y', '5y', '7y', '10y', '30y']

Retrieve treasury bond yield data from OpenBB SDK for specified maturities and time range

In [ ]:
data = openbb.economy.treasury(
    instruments=["nominal"],
    maturities=maturities,
    start_date="1985-01-01"
)

Rename columns to match maturities list

In [ ]:
data.columns = maturities

Add a column to indicate if yield curve is inverted (30y yield less than 3m yield)

In [ ]:
data["inverted"] = data["30y"] < data["3m"]

Initialize plot figure and axis

In [ ]:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot([], [])

Set x and y-axis limits for the plot

In [ ]:
ax.set_xlim(0, 7)
ax.set_ylim(0, 20)

Define tick locations and labels for both axes

In [ ]:
ax.set_xticks(range(8))
ax.set_yticks([2, 4, 6, 8, 10, 12, 14, 16, 18])
ax.set_xticklabels(["1m","3m","6m","1y","5y","10y","20y","30y"])
ax.set_yticklabels([2, 4, 6, 8, 10, 12, 14, 16, 18])

Force y-axis labels to appear on the left side

In [ ]:
ax.yaxis.set_label_position("left")
ax.yaxis.tick_left()

Add labels for both axes

In [ ]:
plt.ylabel("Yield (%)")
plt.xlabel("Time to maturty")
In [ ]:
def init_func():
    """Initialize plot with empty data and title"""
    line.set_data([], [])
    plt.title("U.S. Treasury Bond Yield Curve")
    return line
In [ ]:
def animate(i):
    """Update plot data for each frame in the animation
    
    Parameters
    ----------
    i : int
        Current frame index
    
    Returns
    -------
    line : Line2D object
    """
    x = range(0, len(maturities))
    y = data[maturities].iloc[i]
    dt_ = data.index[i].strftime("%Y-%m-%d")
    
    # Change line color based on yield curve inversion
    if data.inverted.iloc[i]:
        line.set_color("r")
    else:
        line.set_color("y")
    
    line.set_data(x, y)
    
    plt.title(f"U.S. Treasury Bond Yield Curve ({dt_})")
    return line,

Create animation for the yield curve using the animate function

In [ ]:
ani = animation.FuncAnimation(
    fig, animate, init_func=init_func, frames=len(data.index), interval=5, blit=True
)

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.