【概要】

1. Python のインストールと必要なPythonライブラリのインストール(Windows上)

  1. Python のインストール

    注:既にPython(バージョン3.12を推奨)がインストール済みの場合は,この手順は不要である.

    winget(Windowsパッケージマネージャー)を使用してインストールを行う

    1. Windowsで,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
    2. winget(Windowsパッケージマネージャー)が利用可能か確認する:
      winget --version
      
    3. Pythonのインストール(下のコマンドにより Python 3.12 がインストールされる).
      winget install --scope machine Python.Launcher
      winget install --scope machine Python.Python.3.12
      
  2. 必要なPythonライブラリのインストール
    1. Windowsで,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
    2. 以下のコマンドを実行し,必要なライブラリをインストールする.
      pip install -U pandas requests datetime
      

【関連する外部ページ】

【サイト内の関連ページ】

Python ソースコードと説明

日本円基準の為替レートデータ取得プログラム(CSV形式で取得)(欧州中央銀行(ECB)からダウンロード)

主要機能

プログラムの使用法

出力結果

活用方法

ソースコード

import pandas as pd
import requests
from datetime import datetime
import io

def fetch_ecb_daily_rates():
    """
    欧州中央銀行(ECB)から日次為替レートデータを取得し、
    日本円を基準とした為替レートに変換します。
    返却値:
        pandas.DataFrame: 日本円基準の為替レートデータフレーム
    """
    url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.zip"
    try:
        df = pd.read_csv(url, compression='zip')
        df['Date'] = pd.to_datetime(df['Date'])
        df.set_index('Date', inplace=True)
        # EUR基準のレートからJPY基準への変換
        jpy_eur_rate = df['JPY']
        result_df = pd.DataFrame(index=df.index)
        for column in df.columns:
            if column != 'JPY':
                # 例:EUR/JPY=150, EUR/USD=1.1の場合、USD1=136.36円
                result_df[f'JPY_per_{column}'] = jpy_eur_rate / df[column]
        return result_df
    except Exception as e:
        print(f"ECBデータ取得エラー: {e}")
        return None

if __name__ == "__main__":
    exchange_rates = fetch_ecb_daily_rates()
    if exchange_rates is not None and not exchange_rates.empty:
        now = datetime.now().strftime("%Y%m%d")
        filename = f"daily_exchange_rates_{now}.csv"
        exchange_rates.to_csv(filename)
        print(f"日次為替レートデータを {filename} に保存しました")
        print("\nデータサンプル(直近5日分):")
        print(exchange_rates.tail(5))
    else:
        print("データの取得に失敗しました")