見出し画像

日銀HPからマネタリーベースの時系列データを取得し、イザナミの環境データで使えるcsvにするpythonスクリプト(from ChatGPT)|イザナミ豆知識

ChatGPTに聞いて作ってもらいました。Python使える環境の方向けです。


コード

###日銀HPからマネタリーベースのデータを取得し、csvに変換するスクリプト###

import pandas as pd
import requests
from io import BytesIO

def download_and_convert(url, output_path):
    # Download the xlsx file from the URL
    response = requests.get(url)

    # Ensure the download was successful
    response.raise_for_status()

    # Use BytesIO to convert the downloaded bytes into a file-like object so it can be read into pandas
    with BytesIO(response.content) as fh:
        # Load the xlsx content
        xls = pd.ExcelFile(fh)

        # Load the specified sheet
        df_avg_outstanding = xls.parse('平残(Average amounts outstanding)')

        # Drop unnecessary rows and keep relevant columns
        df_cleaned = df_avg_outstanding.iloc[6:, [1, 2]].dropna().reset_index(drop=True)

        # Rename columns
        df_cleaned.columns = ["Date", "MonetaryBase"]

        # Convert the "Date" column to datetime type
        df_cleaned["Date"] = pd.to_datetime(df_cleaned["Date"])

        # Convert date to yyyymm format
        df_cleaned["Date"] = df_cleaned["Date"].dt.year * 100 + df_cleaned["Date"].dt.month

        # Save to csv
        df_cleaned.to_csv(output_path, index=False)

# Usage
url = "https://www.boj.or.jp/statistics/boj/other/mb/mblong.xlsx"
output_path = "monetary_base.csv"
download_and_convert(url, output_path)

環境データで利用するときの設定

注意点

最新月のデータはまだないので、上の画像では、データなし時の扱いを「前営業日」にしてます。
これなら最新月でも検証できますが、9月に入って8月の正しいデータが入ってくると検証結果が変わってしまうことになります。

ご利用方針によっては データなし時の扱いを「指標計算不可」にするほうがよい場合もありますので、検討の上ご利用ください。

ChatGPTへの聞いた流れ

Code Interpreterを利用。日銀HPからDLしたxlsxを渡して考えてもらう
過程のコードがゴチャってたので整理してもらう
xlsxファイルを直接ダウンロードする形に変更してもらう

お問合せ先

有限会社 ツクヨミ
URL https://www.izanami.jp
Mail support@izanami.jp
🔎イザナミnote内検索


この記事が気に入ったらサポートをしてみませんか?