0
4

Pythonで為替レートの履歴でデータ分析してみた

Last updated at Posted at 2023-09-21

はじめに

ドル円レートはメディアで「円高で」「円高の影響で」という耳にタコができるくらい上昇しています
新発売のiPhohe15はアメリカドルで799ドルで14と変化ないですが、日本円だと14から値上がりして発売されます(2023/09/18時点)

一方で、対ユーロの為替はどうなのか見てみました
ここでユーロ円の為替レートを見れます

このサイトがXMLで日付毎の為替レートを提供しているのでこれを使用してデータ分析していきます

環境構築

pip install requests pandas matplotlib japanize-matplotlib beautifulsoup4

pyenv、pipenvなどの仮想環境内で開発するとローカルが汚れません

データ可視化

analysis.py
import requests
import pandas as pd
import matplotlib.pyplot as plt
import japanize_matplotlib
from bs4 import BeautifulSoup as bs

url = 'https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/jpy.xml'
res = requests.get(url)

# BeatutifulSoupでXMlを解析
soup = bs(res.content, 'xml')

# Datasetタグ要素を取得
dataset = soup.find('DataSet')
series = dataset.find('Series')
obs = series.findAll('Obs')

rate_list = []
for ob in obs:
    # 日付とレートをリストに追加
    time_period = ob.get('TIME_PERIOD')
    if '2023' in time_period:
        rate = ob.get('OBS_VALUE')
        rate_list.append((time_period, float(rate)))

# リストをデータフレームに変換
df = pd.DataFrame(rate_list, columns=['TIME_PERIOD', 'OBS_VALUE'])

# データの可視化
plt.figure()
plt.title('ユーロ為替レート')
plt.xlabel('日付')
plt.ylabel('為替')
plt.grid(True)
plt.tight_layout()
# X軸のメモリ
df['TIME_PERIOD'] = pd.to_datetime(df['TIME_PERIOD'])
# Y軸のメモリ
y_min = 5 * (df['OBS_VALUE'].min() // 5)  # //:5で割り切る
y_max = 5 * (df['OBS_VALUE'].max() // 5) + 5
plt.yticks(range(int(y_min), int(y_max), 5))
plt.plot(df['TIME_PERIOD'], df['OBS_VALUE'], marker=None, linestyle='-')
plt.savefig("rate.png")
plt.show()

Figure_2.png

前日との為替の増減を取得して、3軸で表示させると増減の変化が分かりやすいかもしれません

df['DIFF'] = df['OBS_VALUE'].diff()

統計情報を取得

analysis.py
# ... 先ほどのplt.show()に続けて
print(df['OBS_VALUE'].describe())
# count    182.000000
# mean     149.205330
# std        6.630735
# min      137.930000
# 25%      143.195000
# 50%      149.000000
# 75%      156.232500
# max      159.150000

統計情報を見ると
平均値が149.20円で
第一四分位数が143.19円
第三四分位数が156.23円なので
143円〜156円に長く推移していることになります
ドル円との統計情報を比べるとどちらが値動きが激しいか実感できると思います

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