🦔

日本国債金利データを取得するPythonのコード

2022/11/13に公開約1,300字

この記事について

財務省のページから国債金利データを取得します。

Pythonのコード

import numpy as np
import pandas as pd

jgbcm = pd.read_csv("https://www.mof.go.jp/jgbs/reference/interest_rate/jgbcm.csv", skiprows=1, encoding="shift-jis")
jgbcm_all = pd.read_csv("https://www.mof.go.jp/jgbs/reference/interest_rate/data/jgbcm_all.csv",  skiprows=1, encoding="shift-jis")
interest_rate = pd.concat([jgbcm_all, jgbcm], axis=0).replace('-', np.nan)
shr = interest_rate["基準日"].str.extract("([SHR])(\d+).(\d+).(\d+)", expand=True)
shr[1] = shr[1].astype(int)
shr[1] = shr[1].mask(shr[0]=="S", shr[1] + 25 + 1900)
shr[1] = shr[1].mask(shr[0]=="H", shr[1] - 12 + 2000)
shr[1] = shr[1].mask(shr[0]=="R", shr[1] + 18 + 2000)
shr[1] = shr[1].astype(str)
interest_rate["基準日"] = pd.to_datetime(shr[1] + "-" + shr[2] + "-" + shr[3])
interest_rate = interest_rate.set_index("基準日").stack().reset_index()
interest_rate.columns = ["基準日", "年限", "金利"]
interest_rate["年限"] = interest_rate["年限"].str.replace("年", "").astype(int)
interest_rate["金利"] = interest_rate["金利"].astype(float) / 100

interest_rate

Plotlyで可視化

import plotly.express as px

px.line(interest_rate,
    x="基準日",
    y="金利",
    color="年限"
)

Discussion

ログインするとコメントできます