Jupyter Notebookは,コード,データ,コメントを単一の共有可能な文書に組み合わせたいアナリストや開発者にとって,好ましいツールです.このガイドは,FXMacroData Python SDKをインストールし,APIキーを設定し,マクロインジケーターシリーズを取得し,分析を行い,公開準備のチャートを作成します.すべて単一のノートブック内にあります.最後に,FX MacroDataが公開する80以上の指標で拡張できる機能的で再現可能なノートブックの所有となります.
あなた が 築く もの
A self-contained Jupyter Notebook that authenticates against the FXMacroData REST API, pulls policy rate and inflation time series for four G10 currencies, computes real rate spreads, and renders interactive multi-series charts — ready to share or schedule as a recurring report.
条件
- Python 3.9 以降
- Jupyter Notebook または JupytersLab をインストールする
pip install jupyterlab - 荷物は以下のとおりです
requestsほらpandasほらmatplotlibほらseaborn - 登録する / サブスクリプト 買える
You can install all dependencies in one command:
pip install requests pandas matplotlib seaborn jupyterlab
JupyterLab をプロジェクトフォルダから起動します.
jupyter lab
ステップ 1 API キーをセキュアにする
ノートブックファイルにハードコードの認証を入れないこと ノートブックは偶然共有されやすく,漏れたAPIキーが誤用される可能性があります.最も安全なアプローチは,環境変数に鍵を保存し,実行時に読み取ることです.
この行をあなたの ページに追加します ~/.bashrc ほら ~/.zshrc (その後,ターミナルを再起動するか実行します. source ~/.bashrcについて
export FXMD_API_KEY="your_actual_api_key_here"
Windows (PowerShell) で:
$env:FXMD_API_KEY = "your_actual_api_key_here"
セットアップセルに鍵を入力します.
import os
API_KEY = os.environ.get("FXMD_API_KEY")
if not API_KEY:
raise EnvironmentError(
"FXMD_API_KEY environment variable is not set. "
"See https://fxmacrodata.com/subscribe to get a key."
)
print("API key loaded ✓")
提示: python-dotenv プロジェクトレベルの秘密について
好きななら .env プロジェクトごとにファイル,インストール pip install python-dotenv 追加して
from dotenv import load_dotenv; load_dotenv() 前に os.environ.get() 連絡する .env ファイルに .gitignoreわかった
ステップ2 繰り返し利用可能な取得支援者を書き
FXMacroDataのすべてのエンドポイントは同じURL構造をたどります.
GET https://fxmacrodata.com/api/v1/announcements/{currency}/{indicator}?api_key=YOUR_API_KEY
JSON応答には data 列は,各オブジェクトが date フィールド,a val フィールド,そして (正確なタイミングのために) announcement_datetime 次のヘルパーは,その応答を直接パンダのデータフレームに変換します.
import requests
import pandas as pd
BASE_URL = "https://fxmacrodata.com/api/v1"
def fetch_indicator(currency: str, indicator: str,
start: str = None, end: str = None) -> pd.DataFrame:
"""Fetch a macro indicator time series from FXMacroData.
Parameters
----------
currency : ISO currency code, e.g. 'usd', 'eur', 'gbp'
indicator : Indicator slug, e.g. 'policy_rate', 'inflation', 'gdp'
start : Optional start date 'YYYY-MM-DD'
end : Optional end date 'YYYY-MM-DD'
Returns
-------
pd.DataFrame with columns: date (datetime64), val (float64),
announcement_datetime (datetime64, nullable),
currency (str), indicator (str)
"""
params = {"api_key": API_KEY}
if start:
params["start"] = start
if end:
params["end"] = end
url = f"{BASE_URL}/announcements/{currency}/{indicator}"
resp = requests.get(url, params=params, timeout=15)
resp.raise_for_status()
rows = resp.json().get("data", [])
if not rows:
return pd.DataFrame(columns=["date", "val", "announcement_datetime",
"currency", "indicator"])
df = pd.DataFrame(rows)
df["date"] = pd.to_datetime(df["date"])
df["val"] = pd.to_numeric(df["val"], errors="coerce")
if "announcement_datetime" in df.columns:
df["announcement_datetime"] = pd.to_datetime(
df["announcement_datetime"], errors="coerce", utc=True
)
df["currency"] = currency.upper()
df["indicator"] = indicator
return df.sort_values("date").reset_index(drop=True)
助手が 引き上げます HTTPError 返信の4xx/5xxで, 変換します date 列に適した datetime64 通貨と指標のラベルを貼り付け 下流接続を微不足道にする.
ステップ 3 初めてのシリーズ を 持って来 なさい
2022年以降のレート政策の決定を 調べてみましょう
usd_rate = fetch_indicator("usd", "policy_rate", start="2022-01-01")
usd_rate.head(10)
列が表示される DataFrame は,
date val announcement_datetime currency indicator
0 2022-03-16 0.25 2022-03-16T18:00:00+00:00 USD policy_rate
1 2022-05-04 0.75 2022-05-04T18:00:00+00:00 USD policy_rate
2 2022-06-15 1.50 2022-06-15T18:00:00+00:00 USD policy_rate
3 2022-07-27 2.25 2022-07-27T18:00:00+00:00 USD policy_rate
...
注目してください announcement_datetime column — this gives you second-level release precision
for event-driven strategies or backtests that depend on exact announcement timing. Explore the full
catalogue of available indicators at /api-data-docs/usd/policy_rate 税率についてわかった
ステップ4 複数の通貨を入手
One of the most powerful patterns is to pull the same indicator for several currencies simultaneously and stack the results. The loop below fetches policy rates for the USD, EUR, GBP, and AUD in one go:
currencies = ["usd", "eur", "gbp", "aud"]
START = "2022-01-01"
policy_rates = pd.concat(
[fetch_indicator(ccy, "policy_rate", start=START) for ccy in currencies],
ignore_index=True
)
print(f"Fetched {len(policy_rates)} rows across {policy_rates['currency'].nunique()} currencies")
policy_rates.groupby("currency").tail(2)
可能な指標スランプ
詳細はこちらから fxmacrodata.com/api-data-docs ファイルファイルは外国為替分析の主要シリーズには
policy_rateほら
inflationほら
gdpほら
unemploymentほら
pmiほら
trade_balance各シリーズが同じフォーチパターン スワップ通貨コードと指標スラグを使用します
ステップ5 複数の指標を組み合わせる
To compute real interest rates you need both the policy rate and headline inflation for each currency. Fetch inflation alongside policy rates, then concatenate into a single tidy DataFrame:
inflation = pd.concat(
[fetch_indicator(ccy, "inflation", start=START) for ccy in currencies],
ignore_index=True
)
# Stack all observations into one long-form DataFrame
macro = pd.concat([policy_rates, inflation], ignore_index=True)
print(macro.groupby(["currency", "indicator"]).size().to_string())
ステップ 6 形を変え,前向きに埋め込む
中央銀行の決定は稀だ. 年に6~12回起こる. 他の月間シリーズと一致させるには,月間日付の脊柱を作り,最後の既知の値を先送りします.
import numpy as np
# Floor each observation to month start for alignment
macro["month"] = macro["date"].dt.to_period("M").dt.to_timestamp()
# Pivot to wide: one column per currency+indicator combination
wide = (
macro
.groupby(["month", "currency", "indicator"])["val"]
.last() # latest reading within the month
.unstack(["currency", "indicator"])
)
# Build a complete monthly date spine and forward-fill
date_spine = pd.date_range(START, pd.Timestamp.today(), freq="MS")
wide = wide.reindex(date_spine).ffill()
wide.tail(3)
ステップ7 リアルレート・スプレッドを計算する
実質利率は,指名政策利率マイナス総インフレ率である.ポジティブなスプレッドは規制的な金融政策をシグナル化し,ネガティブなスプレーは,中央銀行が消費者価格成長に比べて依然として順調であることを意味する.EURUSDの実質利率差は,EUR/USDの中期最強のドライバーの一つです.
for ccy in [c.upper() for c in currencies]:
try:
wide[(ccy, "real_rate")] = (
wide[(ccy, "policy_rate")] - wide[(ccy, "inflation")]
)
except KeyError:
pass # skip if either series is missing
# EUR minus USD real rate differential
wide[("spread", "eur_usd")] = (
wide[("EUR", "real_rate")] - wide[("USD", "real_rate")]
)
wide[[("USD", "real_rate"), ("EUR", "real_rate"), ("spread", "eur_usd")]].tail(6)
ステップ8 Matplotlib で視覚化する
DataFrame が準備されていると,複数のパネルグラフは数行しか持たない. 政策率のステップグラフを使用します.
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig, axes = plt.subplots(3, 1, figsize=(13, 11), sharex=True)
fig.patch.set_facecolor("#F8FAFC")
COLORS = {"USD": "#2563EB", "EUR": "#16A34A", "GBP": "#7C3AED", "AUD": "#F97316"}
# Panel 1: Policy rates
ax1 = axes[0]
for ccy in [c.upper() for c in currencies]:
try:
series = wide[(ccy, "policy_rate")].dropna()
ax1.step(series.index, series.values, where="post",
label=ccy, color=COLORS[ccy], linewidth=1.8)
except KeyError:
pass
ax1.set_ylabel("Policy rate (%)")
ax1.set_title("Central Bank Policy Rates — G4", fontweight="bold")
ax1.legend(loc="upper left", fontsize=9)
ax1.grid(axis="y", alpha=0.3)
# Panel 2: Real rates
ax2 = axes[1]
for ccy in [c.upper() for c in currencies]:
try:
series = wide[(ccy, "real_rate")].dropna()
ax2.plot(series.index, series.values,
label=ccy, color=COLORS[ccy], linewidth=1.8)
except KeyError:
pass
ax2.axhline(0, color="#94A3B8", linewidth=0.8, linestyle="--")
ax2.set_ylabel("Real rate (%)")
ax2.set_title("Real Interest Rates (Policy Rate − Inflation)", fontweight="bold")
ax2.legend(loc="upper left", fontsize=9)
ax2.grid(axis="y", alpha=0.3)
# Panel 3: EUR–USD spread
ax3 = axes[2]
spread = wide[("spread", "eur_usd")].dropna()
ax3.fill_between(spread.index, spread.values, 0,
where=spread.values >= 0,
color="#16A34A", alpha=0.30, label="EUR favoured")
ax3.fill_between(spread.index, spread.values, 0,
where=spread.values < 0,
color="#2563EB", alpha=0.30, label="USD favoured")
ax3.plot(spread.index, spread.values, color="#374151", linewidth=1.6)
ax3.axhline(0, color="#94A3B8", linewidth=0.8, linestyle="--")
ax3.set_ylabel("Spread (pp)")
ax3.set_title("EUR−USD Real Rate Differential", fontweight="bold")
ax3.legend(loc="upper left", fontsize=9)
ax3.grid(axis="y", alpha=0.3)
ax3.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
ax3.xaxis.set_major_locator(mdates.MonthLocator(interval=4))
plt.setp(ax3.xaxis.get_majorticklabels(), rotation=30, ha="right")
fig.tight_layout(h_pad=1.6)
plt.savefig("macro_analysis.png", dpi=150, bbox_inches="tight")
plt.show()
ポイント: 政策金利シリーズにステップチャートを用いること
ax.step(..., where="post") 円滑な挿入線ではなく,分散した階段の動きとして中央銀行の決定を正しく表します.他のすべてのマクロシリーズ (インフレ,GDP,PMI) については標準です. ax.plot() 適当に
ステップ 9 発売日程 を 確認 する
繰り返し取得をスケジュールする前に,次のデータリリースがいつ予定されているか正確に知ることが役立ちます. リリースカレンダーエンドポイント 固定スケジュールで投票するのではなく,ノートブックリフレッシュを毎回のリリース後数分で実行する時間を作ることができます.
def fetch_calendar(currency: str) -> pd.DataFrame:
"""Fetch upcoming release dates for a currency from the FXMacroData calendar."""
url = f"{BASE_URL}/calendar/{currency}"
resp = requests.get(url, params={"api_key": API_KEY}, timeout=15)
resp.raise_for_status()
events = resp.json().get("data", [])
df = pd.DataFrame(events)
if df.empty:
return df
df["release_date"] = pd.to_datetime(df["release_date"], errors="coerce")
return df.sort_values("release_date").reset_index(drop=True)
# Upcoming USD releases
usd_calendar = fetch_calendar("usd")
upcoming = usd_calendar[usd_calendar["release_date"] >= pd.Timestamp.today()]
print(upcoming[["release_date", "indicator"]].head(10).to_string(index=False))
ステップ 10 保存し,スケジュールする
復習可能な分析のために,広いデータフレームを CSV にエクスポートし,ノートブックをスケジュールで実行できます. papermillパラメータインジェクションでコマンドラインからノートブックを実行します.
pip install papermill
# At the end of your notebook: persist the dataset
wide.to_csv("macro_data.csv")
print(f"Saved {wide.shape[0]} rows × {wide.shape[1]} columns to macro_data.csv")
# Execute the notebook from the command line (e.g. from cron or a CI job)
papermill macro_analysis.ipynb macro_analysis_output.ipynb \
-p START "2022-01-01"
リリースカレンダーと組み合わせて,新しい指標データが実際に期待されるときにのみ実行できるようにします.
Complete notebook in one place
セットします. セットの順番で,セットを
FXMD_API_KEY in your environment, and run all cells — you will have a fully
interactive macro analysis in under two minutes.
概要
Jupyter Notebook のワークフローを構成しました.
- 環境変数でFXMacroDataで安全に認証する
- 復元可能な
fetch_indicator()API の応答を pandas に変換するヘルパー DataFrames - 複数のG10通貨の政策金利とインフレシリーズを引いてスタックする
- 定期的な月間日付の回線に中央銀行の分散データを再構成します.
- リアルレート・スプレッドとクロス・通貨・ディフェリエンシャルを計算する
- Produces a three-panel Matplotlib chart ready for reports or sharing
- リリースカレンダーに問い合わせ 時間を再現してスマートにリフレッシュ
- 実行するノートブックとCSVへの輸出結果
papermill
次のステップとして,FXMacroDataシリーズなどの追加でノートブックを拡張します.
失業ほら
貿易バランスほら
PMI 完全なマクロスコアカードを構築する
fetch_indicator() 変更なしで適用されます 指示器スラグのみが更新する必要があります.