# Yield curve inversion

## Highlights

• Difficulty：★★☆☆☆

## Preface

when the United States 10Y Government Bond -United States 2Y Government Bond <0 ,we call it yield curve inversion 。

Usually longer-term bonds will have higher interest rates, but when the market have doubts about the economy ,yield cruve inversion happen! So in this article , we try to plot the Macroeconomic Index a year before it happened, and two years after it happened

## The Editing Environment and Modules Required

Window10 Spyder(anaconda31)

## Database

macroeconomic data :macroeconomic data database code (GLOBAL/ANMAR)

`#######################3from datetime import datetime, timedelta import pandas as pdimport numpy as npimport matplotlib.pyplot as plt #########################3import tejapiimport plotly.graph_objects as goimport plotly.io as pio##################pio.renderers.default = 'browser'       ##PLOT IN WEB`

# Data Processing

our bonds data is from Tej pro

`df=pd.read_excel("C:\\Users/user/Desktop/Tej/美國公債殖利率.xlsx")`

There is Nan in our data , so we should drop it ,After we reset index

`df.dropna(inplace=True)df.reset_index(drop=True,inplace=True)`

## step 1 set the indicator

`df["dif2Y"]=df.US10Y-df.US2Ydf["invertkeepday"]=df["dif2Y"].apply(lambda x : 1 if x < 0 else 0 )df["cross"]=np.nandf["notcross"]=np.nan`

calculate the 10y- 2y

find the inverse day and visualize it

`startday=[]endday  =[]keep = 0 df=df.copy()for i in range(len(df)):    if df["invertkeepday"][i]  >0 :        if keep == 0:                    df["cross"][i]=df["US10Y"][i]            startday.append(df["日期"][i])            keep = 1    elif  keep == 1 :        df["notcross"][i]=df["US10Y"][i]if  df["invertkeepday"][i] < 1 :            endday.append(df["日期"][i])            keep = 0`

and we want to see how long did it happen

`for start , end  in zip(startday,endday):print(start , end, end-start)`

We found that some times were really close ,so we make them in a group

`inverted=pd.DataFrame(endday,startday)inverted.reset_index(inplace=True)inverted["year"]=inverted["index"].dt.yeardatetime=inverted.groupby('year')datetime=list(datetime)getstart=[]getend  =[]for i  in datetime :    i[1].reset_index(drop=True,inplace=True)    start = i[1]["index"][0]    end = i[1][ 0][len(i[1])-1]    getstart.append(start)    getend.append(end)for start , end  in zip(getstart,getend):    print(start , end, end-start)`

Now we can see the approximately situation

Nearly three years we found that there have about 6 times yeild curve inverse

`df.set_index("日期",inplace=True)plt.figure(figsize=(12.2,4.5))plt.scatter(df.index,df['cross'],color='red', label='cross!',marker='x',alpha=1)plt.scatter(df.index,df['notcross'],color='green', label='Notcross',marker='o',alpha=1)plt.plot(df["US2Y"], label='2Y', alpha=0.35)plt.plot(df["US10Y"], label='10Y', alpha=0.35)plt.plot(df["dif2Y"], label='dif', alpha=0.35)plt.title('Close Price Buy & Sell Signals')plt.xticks(rotation=45)plt.xlabel('Date')  plt.ylabel('Price')plt.legend()plt.grid()`

# Step 2 visualize the stocks

we have the time so we can input the time into Tejapi to get the macroecnomic data

## Conclusion

From the perspective of various economic data, it may represent that the prosperity has passed its peak, so there are doubts about the future prosperity, selling short-term bonds and preferring longer-term bonds, which leads to the inversion of yield curves

Although every time an inversion occurs, it will be accompanied by an recession, but in these five expreience ,there was two times that the U.S. economy has not experienced a recession within two years

In 2019, the recesion happen because of the COVID-19 , yield curve can’t forecast it !

1, In the past 5 inversion ,stocks go up 4 time

2, When three recessions occurred, they were all in a rate-cut cycle, and when two recessions did not occur, the U.S. was in a rate-raising cycle