May cohort is now open: How to secure your spot:

Predict recessions with the yield curve

PQN #30: Predict recessions with the yield curve

Whether you trade your own small account, or manage hundreds of billions of dollars of investor money, the economy matters. The economy helps you know which way to be biased—bullish or bearish.

How do you form a view?

  • Buy an analyst report
  • Read “expert” commentary
  • Do what most people do, guess

None of these options sounds really great.

Unfortunately, small investors don’t have teams of economists to research and give guidance on the economic picture.

Today, I’m going to show you how to build an animated chart of the yield curve to form a view of state of the economy.

The yield curve is a plot of the yield of different key US treasuries against their maturity. The yield curve provides important insight into investors’ predictions about the economy. “Inverted” yield curves have been shown to reliably predict recessions.

Normally, longer-dated treasuries yield more than shorter-dated ones. This is because there is more risk in lending money for longer. When the yield curve inverts, longer-dated treasuries yield less than shorter-dated ones. This happens when the market expects the Fed to lower interest rates in the future in anticipation of a recession.

Investors use an inverted yield curve as a sign to reduce risk in their portfolios.

You can build an animated chart of the US yield curve to form a view of the macroeconomic state.

All without paying a thing.

Imports and set up

Start with importing NumPy, Matplotlib, and the OpenBB SDK. You can use the OpenBB SDK to get yield curve data for the St. Louis Fed’s data portal (FRED). To use the data, you need free FRED API keys.

%matplotlib notebook

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

from openbb_terminal.sdk import openbb

font = {
    "family": "normal",
    "weight": "normal",
    "size": 12
}

plt.rc('font', **font)

openbb.keys.fred(
    key="inert_your_api_key_here",
    persist=True,
)

Set up the bond maturities you want to use to build the yield curve. There are conventions about which maturities to use, but there is no “right” answer. The point is to get a good representation across the maturities.

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

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

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

Use the OpenBB SDK to acquire the rate data for all the maturities at once. Using the nominal instrument type returns the coupon rate (non-inflation adjusted) on the bond. Mark the yield curve as inverted if the yield on the 30-year maturity is less than the 3-month maturity. Some people use the 30-year and the 10-year, or the 10-year and the 3-month. Use what makes sense to you based on your analysis.

Build the animated chart

With Matplotlib, you can animate a chart. Animated charts offer a great way to visualize how data changes through time. First, set up the plots. This boilerplate code sets up the figure, creates the tick ranges and labels, and sets the axis labels. 

# Initialize figure
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot([], [])

# Set the range of ticks
ax.set_xlim(0, 7)
ax.set_ylim(0, 20)

# Set the tick locations
ax.set_xticks(range(8))
ax.set_yticks([2, 4, 6, 8, 10, 12, 14, 16, 18])

# Set the axis labels
ax.set_xticklabels(["1m","3m","6m","1y","5y","10y","20y","30y"])
ax.set_yticklabels([2, 4, 6, 8, 10, 12, 14, 16, 18])

# Foce the y-axis labels to the left
ax.yaxis.set_label_position("left")
ax.yaxis.tick_left()

# Add the axis lables
plt.ylabel("Yield (%)")
plt.xlabel("Time to maturty")

Next, build the animation functions.

def init_func():
    line.set_data([], [])
    plt.title("U.S. Treasury Bond Yield Curve")
    return line

def animate(i):
    x = range(0, len(maturities))
    y = data[maturities].iloc[i]
    dt_ = data.index[i].strftime("%Y-%m-%d")
    
    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,

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

The first function sets the initial state of the chart. The animate function grabs the data to plot, changes the curve color to red when the yield curve is inverted, and sets the data. The FuncAnimation function then does the work of looping through each row of data, creating the plot, and displaying it to you.

When you run the code, you’ll see how the yield curve evolves over time. When it flashes red, it’s inverted. You can also see the overall level of interest rates and how they rose and fell over the same time period.

Skip the paid research reports. Animate the yield curve with Python and build your own analysis of the macroeconomic situation to improve your investing.