LoginSignup
0
1

米国債イールドカーブのアニメーション

Last updated at Posted at 2023-05-19

はじめに

FREDからデータを取得して米国財務省証券のイールドカーブを描くことにした。

データ

例えば、10年債利回りの場合は、Market Yield on U.S. Treasury Securities at 10-Year Constant Maturity, Quoted on an Investment Basisの月次データを利用する。
同様のデータがあるのが、1・3・6ヶ月、1・2・3・5・7・10・20・30年。
もっともデータが古くからいるのが1・3・5・10・20年で、1953年4月からのデータがある。

コード

まずは、データの再利用の可能性も考えて、いったんGoogleドライブに'treasury_yield.csv'という名前で保存。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
from google.colab import drive
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
import pandas_datareader as pdr
from datetime import datetime

# Googleドライブをマウント
drive.mount('/content/gdrive')

# FREDからデータを取得
series = ['GS1M', 'GS3M', 'GS6M', 'GS1', 'GS2', 'GS3', 'GS5', 'GS7', 'GS10', 'GS20', 'GS30']
start_date = '1950-01-01'  # 実際のデータは1,3,5,10,20年は1953年4月より開始
end_date = datetime.now().strftime('%Y-%m-%d')  # 終了日を現在の日付に設定
df = pdr.get_data_fred(series, start_date, end_date)  # データ取得

# データを整形
df = df.rename(columns={'GS1M': '1M', 'GS3M': '3M', 'GS6M': '6M', 'GS1': '1Y', 'GS2': '2Y', 'GS3': '3Y', 'GS5': '5Y', 'GS7': '7Y', 'GS10': '10Y', 'GS20': '20Y', 'GS30': '30Y'})

# ここでデータをCSVとしてGoogle Driveに保存
df.to_csv('/content/gdrive/MyDrive/treasury_yield.csv')

そのまま使うのだから必要はないが、やはり再利用のときを考えて読み込み直して、イールドカーブのアニメーションを作成し、'us_treasury_yield.mp4'という名前でGoogle Driveに保存する。

# CSVを読み込み直し、列名を数値に変更
df = pd.read_csv('/content/gdrive/MyDrive/treasury_yield.csv', index_col=0)
df.index = pd.to_datetime(df.index)  # <- インデックスを日付型に変換
new_columns = {col: float(col[:-1])/12 if 'M' in col else float(col[:-1]) for col in df.columns}
df = df.rename(columns=new_columns)

x_ticks_labels = {v: k for k, v in new_columns.items()}

# 短期のラベルを削減
reduced_labels = {k: v for k, v in x_ticks_labels.items() if v in ['6M', '1Y', '2Y', '3Y', '5Y', '7Y', '10Y', '20Y', '30Y']}

# イールドカーブのアニメーションを作成
fig, ax = plt.subplots()

def update(num):
    ax.clear()
    df.iloc[num].dropna().plot(style='-', ax=ax)  # Original data with solid line
    ax.set_xticks(list(reduced_labels.keys()))  # set x-axis ticks
    ax.set_xticklabels(list(reduced_labels.values()), rotation=90)  # set x-axis tick labels with 90 degree rotation
    ax.set_title('U.S. Treasury yield curve ' + df.index[num].strftime('%Y-%m'))
    ax.set_ylim([df.min().min(), df.max().max()])  # Set y-axis range to include all data
    ax.set_xlim([min(new_columns.values()), max(new_columns.values())])  # Set x-axis range to include all data
    ax.set_xlabel('Maturity')  # set x-axis label
    ax.set_ylabel('Yield (%)')  # set y-axis label

ani = FuncAnimation(fig, update, frames=range(len(df)), repeat=False)

# アニメーションをHTMLにして表示
HTML(ani.to_jshtml())

# GoogleドライブのMyDriveにアニメーションをmp4にして保存
ani.save('/content/gdrive/MyDrive/us_treasury_yield.mp4', writer='ffmpeg', fps=30)

おわりに

描いてみると、JGBイールドカーブの場合と違って逆イールドも結構登場する。まあ、それだけ市場が健全なのだろう。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1