0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JGBイールドカーブのアニメーション

Last updated at Posted at 2023-05-05

JGBイールドカーブのアニメーションとして、これまでRを使って描いた①とPythonによる②を参考にしてきた。
https://teramonagi.hatenablog.com/entry/20111110/1320936164
https://note.com/hippen/n/n47d7805bd5bb

これらを参考にしつつ、Chat GPTに頼ってGoogle ColabのPython上で動くものを作ったので備忘録として保存することにした。私のプログラミング能力の低さから①②より劣るコードで何の価値もないが、財務省のウェブページから取得するデータを、前処理の面倒な日本語版でなく英語版にしてるのだけがちょっと自慢。

まずは、作成したグラフをGoogleドライブ用に保存したいので、Googleドライブのマウント。

# Colaboratory 上で Google Drive をマウント
from google.colab import drive
drive.mount('/content/drive')

その上で、グラフを作成してGoogle Drive へmp4にして保存。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from urllib.request import urlretrieve
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
import os

# Download data
url = "https://www.mof.go.jp/english/policy/jgbs/reference/interest_rate/historical/jgbcme_all.csv"
file_path = "jgbcme_all.csv"
urlretrieve(url, file_path)

# Read data
data = pd.read_csv(file_path, index_col=0, skiprows=1)

# Convert index to DatetimeIndex
data.index = pd.to_datetime(data.index, format="%Y/%m/%d")

# Ensure all data are numeric
data = data.apply(pd.to_numeric, errors="coerce")

# Prepare data
monthly_data = data.resample("M").last()

# Remove columns if they exist
cols_to_remove = ["1wk", "2wk", "3wk", "4wk", "5wk", "6wk"]
yield_curve = monthly_data.drop(columns=[col for col in cols_to_remove if col in monthly_data.columns])

x_labels = yield_curve.columns.str.extract("(\d+)").astype(int).values.flatten()

# Set up plotting
fig, ax = plt.subplots()
ax.set_title("Japanese Government Bonds Yield Curve Time Series")
ax.set_xlabel("Maturity")
ax.set_ylabel("Yield")
ax.set_xlim(0, x_labels[-1])
ax.set_ylim(yield_curve.min().min(), yield_curve.max().max())
ax.set_xticks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40])

def update(i):
    ax.clear()
    ax.plot(x_labels, yield_curve.iloc[i].values)
    ax.set_title(f"JGB Yield Curve Time Series - {yield_curve.index[i].strftime('%Y-%m')}")
    ax.set_xlabel("Maturity")
    ax.set_ylabel("Yield(%)")
    ax.set_xlim(0, x_labels[-1])
    ax.set_ylim(yield_curve.min().min(), yield_curve.max().max())
    ax.set_xticks([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40])

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

# Ensure that FFmpeg is installed
os.system("apt-get install -y ffmpeg")

# Save the animation as an MP4 file in Google Drive
save_path = "/content/drive/MyDrive/yield_curve_animation.mp4"
ani.save(save_path, writer="ffmpeg", dpi=100)

# Display the animation in Google Colab
HTML(ani.to_jshtml())

とりあえず、以下のグラフが完成と言いたかったが、mp4でのアップはダメだった。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?