Jupyter Notebook는 코드, 데이터 및 코멘트를 단일 공유 가능한 문서에 결합하고자하는 분석가 및 개발자에게 선택된 도구입니다. 이 가이드는 완전한 끝에서 끝까지 작업 흐름을 통해 안내합니다: FXMacroData Python SDK를 설치하고 API 키를 설정하고, 매크로 지표 시리즈를 가져오고, 분석을 수행하고, 출판 준비 된 차트를 생성합니다. 모두 하나의 메모장 안에 있습니다. 끝으로 당신은 작동하고 재생 가능한 메모장을 갖게 될 것입니다. FXMacrodata가 노출하는 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.
필수 조건
- 파이썬 3.9 이상
- Jupyter 노트북 또는 JupytersLab 설치
pip install jupyterlab - 다음 패키지:
requestspandasmatplotlibseaborn - FXMacroData API 키 등록 / 가입 한 번 구해
모든 의존성을 하나의 명령어로 설치할 수 있습니다.
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"
윈도우에서 (파워):
$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)
아래와 같은 열이 있는 데이터 프레임을 볼 수 있습니다.
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 열 이것은 이벤트에 기반한 전략이나 정확한 발표 시점에 의존하는 백테스트에 대한 두 번째 수준의 릴리스 정밀도를 제공합니다. /api-data-docs/usd/policy_rate 이고- 그래요
단계 4 여러 화폐를 가져오기
가장 강력한 패턴 중 하나는 여러 화폐에 대해 동일한 지표를 동시에 당겨서 결과를 쌓는 것입니다. 아래의 루프는 USD, EUR, GBP 및 AUD의 정책율을 한 번에 가져옵니다.
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 여러 표시기를 결합
실제 금리를 계산하려면 각 통화에 대한 정책금과 전체 인플레이션이 필요합니다. 정책금의 옆에 인플레이션을 가져와 하나의 깔끔한 데이터 프레임으로 연결합니다.
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 재구성 및 앞 으로 채우기
Central bank decisions are sparse — they happen 6–12 times a year. To align them with other monthly series, build a monthly date spine and forward-fill the last known value:
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 실제 금리 스프레드를 계산
실제 금리는 명목 정책금리 미제 총 인플레이션이다. 긍정적 인 스프레드는 제한적 인 통화 정책을 신호합니다. 부정적인 스프레이드는 중앙 은행이 소비자 가격 성장에 비해 여전히 수용적이라는 것을 의미합니다. EUR USD 실제 금리 차이는 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로 시각화
데이터 프레임이 준비되면, 멀티 패널 차트는 몇 줄만 걸립니다. 정책 비율에 대한 단계 차트를 사용하십시오. 그들은 연속적인 시리즈가 아닌 분리된 계단 결정입니다.
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"
이 작업을 릴리스 캘린더와 결합하여 새로운 지표 데이터가 실제로 예상될 때만 예정된 작업이 실행됩니다.
한 곳에서 전체 노트북
위의 모든 셀은 하나의 독립된 노트북을 형성합니다.
FXMD_API_KEY in your environment, and run all cells — you will have a fully
interactive macro analysis in under two minutes.
요약
다음의 Jupyter 노트북 작업 흐름을 구축했습니다.
- 환경 변수를 통해 FXMacroData로 안전하게 인증합니다
- 재사용 가능한
fetch_indicator()panda에 API 응답을 변환하는 보조자 - G10 여러 통화에 대한 정책금리 및 인플레이션 시리즈를 끌어당기고 쌓아
- 전속 채용으로 정규 월간 날짜 척추로 희박한 중앙 은행 데이터를 재구성합니다.
- 실제 금리 스프레드와 통화 간 미연수를 계산합니다.
- Produces a three-panel Matplotlib chart ready for reports or sharing
- 시간으로 출시 달력을 검색 반복 업데이트 지능적으로
- CSV에 결과를 수출하고 노트북 실행 스케줄
papermill
다음 단계로, 추가 FXMacroData 시리즈와 노트북을 확장
실업
무역 균형그리고
PMI 더 완전한 매크로 스코어카드를 만들기 위해서죠.
fetch_indicator() 지표 슬러그만 업데이트해야 합니다.