自国と各国の経済指標とかをまとめて可視化
為替れーと、原油とか金、ビットコインの推移を見れることが
できるものを作成する
GPTで調べると
以下の要件に基づいて、経済指標や各種市場データをまとめて可視化するツールを作成する方法を提案します。
—
### **プロジェクト概要**
#### **目的**
– 各国の経済指標や市場データをまとめて可視化。
– 為替レート、原油価格、金価格、ビットコイン価格の推移をリアルタイムで確認可能。
#### **必要な機能**
1. **データ取得**
– 経済指標(GDP、失業率、インフレ率など)
– 為替レート(主要通貨ペア: USD/JPY、EUR/USDなど)
– 原油価格(WTI、ブレント)
– 金価格(トロイオンス単位)
– 仮想通貨(ビットコイン、イーサリアムなど)
2. **データの可視化**
– 時系列グラフ(過去の推移)
– ダッシュボード形式でのリアルタイム表示
3. **通知機能(任意)**
– 為替レートや価格の変動が大きい場合にアラートを送信。
4. **多言語対応(日本語/英語)**
—
### **開発環境**
#### **プログラミング言語**
– Python(データ取得、可視化に適切)
#### **使用ライブラリ・API**
– **データ取得**
– 為替レート: [ExchangeRate-API](https://www.exchangerate-api.com/) or [Alpha Vantage](https://www.alphavantage.co/)
– 原油・金価格: [Yahoo Finance API](https://rapidapi.com/apidojo/api/yahoo-finance1/)
– 仮想通貨: [CoinGecko API](https://www.coingecko.com/) or [CoinMarketCap API](https://coinmarketcap.com/api/)
– 経済指標: [OECD API](https://data.oecd.org/) or [World Bank API](https://data.worldbank.org/)
– **データ可視化**
– `Plotly`(インタラクティブなグラフ)
– `Dash`(ダッシュボード作成)
– `matplotlib`(簡易な静的グラフ)
– **バックエンド**
– Flask または FastAPI(Webアプリケーションのベース)
– **フロントエンド**
– Dash(Pythonのみで作成可能)
#### **サーバー**
– ローカル開発: PCまたはRaspberry Pi(Pi 5が最適)
– デプロイ: AWS、GCP、Heroku、またはVPS
—
### **基本的な実装手順**
1. **データ取得モジュールの作成**
– 各APIからデータを取得するPythonモジュールを作成。
– 必要に応じて取得データをCSVまたはデータベース(SQLiteなど)に保存。
2. **データ処理**
– Pandasを使用してデータを加工(例: 日付フォーマットの統一、不要な列の削除)。
– 過去1年分などの期間を指定してデータをフィルタリング。
3. **可視化**
– Plotlyでインタラクティブなグラフを作成。
– 例: 為替レートの時系列推移を折れ線グラフで表示。
4. **ダッシュボードの作成**
– Dashを使い、リアルタイムにデータが更新されるダッシュボードを構築。
– 各市場データをカード形式やグラフで整理。
5. **通知機能(オプション)**
– 適当な閾値を設定し、変動が大きい場合にLINE Notifyやメールでアラート送信。
—
### **プロジェクトの初期設計例**
#### **ディレクトリ構造**
“`
economy_dashboard/
├── app.py # メインスクリプト
├── data_fetcher/
│ ├── forex.py # 為替データ取得
│ ├── commodities.py # 原油/金価格取得
│ ├── crypto.py # 仮想通貨データ取得
│ └── indicators.py # 経済指標取得
├── templates/ # DashやFlaskのHTMLテンプレート
├── static/ # CSS/JSファイル
└── requirements.txt # 必要ライブラリ
“`
#### **ダッシュボードイメージ**
– **ヘッダー**
– 今日の日付と最新の市場状況(例: USD/JPY、ビットコイン価格など)。
– **メインセクション**
– 為替レート推移グラフ
– 原油価格と金価格の時系列データ
– 仮想通貨の市場状況
– **サイドバー**
– 通知の設定や期間選択。
—
### **サンプルコード(Dashを使った可視化)**
```python
import dash
from dash import dcc, html
import pandas as pd
import plotly.graph_objects as go
# サンプルデータ
data = {
"Date": pd.date_range(start="2024-01-01", periods=10, freq="D"),
"USD_JPY": [130 + i for i in range(10)],
"Bitcoin": [30000 + i * 500 for i in range(10)],
}
df = pd.DataFrame(data)
# Dashアプリ
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1("経済指標ダッシュボード"),
dcc.Graph(
id="forex_chart",
figure={
"data": [
go.Scatter(x=df["Date"], y=df["USD_JPY"], mode="lines", name="USD/JPY"),
go.Scatter(x=df["Date"], y=df["Bitcoin"], mode="lines", name="Bitcoin"),
],
"layout": go.Layout(title="為替とビットコインの推移", xaxis_title="日付", yaxis_title="価格"),
},
),
])
if __name__ == "__main__":
app.run_server(debug=True)
```
—
### **今後の拡張案**
1. **AI活用**
– 市場予測モデルを構築し、将来のトレンドを予測。
2. **モバイル対応**
– スマホで見やすいUIを設計。
3. **ユーザー設定**
– 関心のある国や通貨ペアを選択可能に。
作成を進める中で質問や具体的な実装サポートが必要であれば、ぜひお知らせください!
となった
まずはWTIからやるので
commodities.py
を作成する
import requests
import datetime
def fetch_commodities_data(api_key, symbol, interval="1d", range="1mo"):
"""
Fetch commodity prices such as crude oil (WTI/Brent) or gold.
Parameters:
api_key (str): API key for the Yahoo Finance or similar API.
symbol (str): Symbol of the commodity (e.g., CL=F for WTI Crude Oil, GC=F for Gold).
interval (str): Data interval (e.g., '1d', '1wk').
range (str): Data range (e.g., '1mo', '3mo', '1y').
Returns:
dict: Parsed JSON response containing commodity price data.
"""
base_url = "https://query1.finance.yahoo.com/v8/finance/chart/"
url = f"{base_url}{symbol}"
params = {
"region": "US",
"lang": "en",
"interval": interval,
"range": range,
}
headers = {
"x-api-key": api_key
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
return data
except requests.exceptions.RequestException as e:
print(f"Error fetching commodity data: {e}")
return None
# Example usage
if __name__ == "__main__":
API_KEY = "your_api_key_here" # Replace with your actual API key
symbol_wti = "CL=F" # WTI Crude Oil
symbol_gold = "GC=F" # Gold
# Fetch WTI data
wti_data = fetch_commodities_data(API_KEY, symbol_wti)
if wti_data:
print("WTI Data:", wti_data)
# Fetch Gold data
gold_data = fetch_commodities_data(API_KEY, symbol_gold)
if gold_data:
print("Gold Data:", gold_data)
というコードが提示された
しかし確かAPIキーなしでも動作する
yfinance API を使って株のデータを取得する
も参考にする
Python で過去の株価データを CSVデータで取得する
でもキーは不要で動く
Pythonでリアルタイムな株価を取得する方法
でも同じ
[解説]Pythonを用いた株価・経済データの取得方法をまとめてみた
でもキーは不要
ということで
原油/金価格取得のため yfinance を使い python で取得したい
というように変更
import yfinance as yf
def fetch_commodities_data(symbol, start_date, end_date):
"""
Fetch commodity prices such as crude oil (WTI/Brent) or gold using yfinance.
Parameters:
symbol (str): Symbol of the commodity (e.g., 'CL=F' for WTI Crude Oil, 'GC=F' for Gold).
start_date (str): Start date for historical data in 'YYYY-MM-DD' format.
end_date (str): End date for historical data in 'YYYY-MM-DD' format.
Returns:
DataFrame: Pandas DataFrame containing the historical price data.
"""
try:
data = yf.download(symbol, start=start_date, end=end_date)
return data
except Exception as e:
print(f"Error fetching commodity data: {e}")
return None
# Example usage
if __name__ == "__main__":
symbol_wti = "CL=F" # WTI Crude Oil
symbol_gold = "GC=F" # Gold
# Define the date range
start_date = "2023-01-01"
end_date = "2023-12-31"
# Fetch WTI data
wti_data = fetch_commodities_data(symbol_wti, start_date, end_date)
if wti_data is not None:
print("WTI Data:")
print(wti_data)
# Fetch Gold data
gold_data = fetch_commodities_data(symbol_gold, start_date, end_date)
if gold_data is not None:
print("Gold Data:")
print(gold_data)
となって実行すると
[*********************100%***********************] 1 of 1 completed
WTI Data:
Price Close High Low Open Volume
Ticker CL=F CL=F CL=F CL=F CL=F
Date
2023-01-03 76.930000 81.500000 76.599998 80.570000 338520
2023-01-04 72.839996 77.419998 72.730003 77.250000 352434
2023-01-05 73.669998 74.919998 72.459999 73.250000 300731
2023-01-06 73.769997 75.470001 73.239998 73.970001 258128
2023-01-09 74.629997 76.739998 73.470001 73.470001 329290
... ... ... ... ... ...
2023-12-22 73.559998 74.980003 73.389999 73.910004 222600
2023-12-26 75.570000 76.180000 73.129997 73.559998 208715
2023-12-27 74.110001 75.660004 73.769997 75.320000 253323
2023-12-28 71.769997 74.400002 71.720001 73.800003 262748
2023-12-29 71.650002 72.620003 71.250000 71.989998 214486
[250 rows x 5 columns]
[*********************100%***********************] 1 of 1 completed
Gold Data:
Price Close High Low Open Volume
Ticker GC=F GC=F GC=F GC=F GC=F
Date
2023-01-03 1839.699951 1839.699951 1836.199951 1836.199951 29
2023-01-04 1852.800049 1859.099976 1845.599976 1845.599976 25
2023-01-05 1834.800049 1855.199951 1834.800049 1855.199951 24
2023-01-06 1864.199951 1868.199951 1835.300049 1838.400024 26
2023-01-09 1872.699951 1880.000000 1867.000000 1867.000000 62
... ... ... ... ... ...
2023-12-22 2057.100098 2068.699951 2052.199951 2055.699951 202
2023-12-26 2058.199951 2060.800049 2054.199951 2060.000000 64
2023-12-27 2081.899902 2081.899902 2064.800049 2067.300049 586
2023-12-28 2073.899902 2087.300049 2066.500000 2081.600098 338
2023-12-29 2062.399902 2068.899902 2062.100098 2068.000000 47
[250 rows x 5 columns]
となる
さらにデータをCSVに保存するので
import yfinance as yf
def fetch_commodities_data(symbol, start_date, end_date):
"""
Fetch commodity prices such as crude oil (WTI/Brent) or gold using yfinance.
Parameters:
symbol (str): Symbol of the commodity (e.g., 'CL=F' for WTI Crude Oil, 'GC=F' for Gold).
start_date (str): Start date for historical data in 'YYYY-MM-DD' format.
end_date (str): End date for historical data in 'YYYY-MM-DD' format.
Returns:
DataFrame: Pandas DataFrame containing the historical price data.
"""
try:
data = yf.download(symbol, start=start_date, end=end_date)
return data
except Exception as e:
print(f"Error fetching commodity data: {e}")
return None
# Example usage
if __name__ == "__main__":
symbol_wti = "CL=F" # WTI Crude Oil
symbol_gold = "GC=F" # Gold
# Define the date range
start_date = "2023-01-01"
end_date = "2023-12-31"
# Fetch WTI data
wti_data = fetch_commodities_data(symbol_wti, start_date, end_date)
if wti_data is not None:
print("WTI Data:")
print(wti_data)
wti_data.to_csv("wti_data.csv")
# Fetch Gold data
gold_data = fetch_commodities_data(symbol_gold, start_date, end_date)
if gold_data is not None:
print("Gold Data:")
print(gold_data)
gold_data.to_csv("gold_data.csv")
として実行
とりあえず問題なし
次は経済指標だが
カレンダーは
メルマガから取得するより
Browser use で経済指標カレンダーを取得した方が早いかもしれない
https://fx.minkabu.jp/indicators
へアクセスし、今日の経済指標カレンダーの日程を取得
これで一応は取得できてるみたい
結果を保存したいので
https://fx.minkabu.jp/indicators
へアクセスし、今日の経済指標カレンダーの日程を取得。結果をcalendar.txt へ保存
としたけどできなかった