매크로 대시보드는 가장 중요한 중앙 은행 및 경제 지표를 한 곳에 배치하여 데이터 터미널 사이에 반등하는 대신 몇 초 만에 시장 조건을 스캔 할 수 있습니다. 이 가이드는 파이썬에서 완전히 인터랙티브, 멀티 패널 대시 보드를 구축하는 과정을 안내합니다. 다, 그리고 을 음모로모든 패널은 하나의 API 키와 몇 개의 함수 호출에서 업데이트됩니다.
당신 이 건축 할 것
A self-contained Python script that pulls policy rates, inflation, unemployment, and PMI for four major FX currencies (USD, EUR, GBP, AUD), assembles a clean pandas DataFrame for each indicator, and renders a four-panel Plotly dashboard — all in under 150 lines of code.
필수 조건
시작 하기 전 에 다음 과 같은 것 들 이 필요 합니다.
- 파이썬 3.9+
- FXMacroData API 키 등록하세요 / 가입 그리고 대시보드에서 키를 복사
- 파이썬 패키지
requestspandasplotly
하나의 명령어로 의존성을 설치합니다:
pip install requests pandas plotly
환경 변수로 API 키를 저장합니다. 스크립트에서 하드 코드 인증서를 절대 저장하지 마십시오.
export FXMD_API_KEY="YOUR_API_KEY"
단계 1 지표 최종점 형태를 이해
모든 FXMacroData 지표는 동일한 REST 패턴을 따르고, 이는 단일 가져오는 함수로 일반화하는 것이 사소한 것으로 보입니다. USD에 대한 정책율 요청은 다음과 같습니다:
GET https://fxmacrodata.com/api/v1/announcements/usd/policy_rate?api_key=YOUR_API_KEY&start=2020-01-01
JSON 응답은 와 같은 평면 객체입니다. data 배열:
{
"data": [
{ "date": "2025-03-19", "val": 4.25, "announcement_datetime": "2025-03-19T18:00:00Z" },
{ "date": "2025-01-29", "val": 4.25, "announcement_datetime": "2025-01-29T19:00:00Z" },
{ "date": "2024-12-18", "val": 4.25, "announcement_datetime": "2024-12-18T19:00:00Z" }
]
}
모든 레코드는 date (YYY-MM-DD), 숫자 val, 그리고 가능한 경우 두 번째 수준의 UTC announcement_datetime모든 지표의 일관된 형태가 하나의 기능이 대시보드의 모든 패널에 서비스를 제공하도록 합니다.
단계 2 재사용 가능한 가져오기 함수를 작성
란 모듈을 만들자 macro_fetch.py아래 함수는 어떤 통화에 대한 모든 지표를 요청하고, 응답을 판다 시리즈로 변환하고, 날짜에 의해 인덱스 된 것을 반환합니다.
import os
import requests
import pandas as pd
BASE_URL = "https://fxmacrodata.com/api/v1"
API_KEY = os.environ["FXMD_API_KEY"]
def fetch_indicator(currency: str, indicator: str, start: str = "2020-01-01") -> pd.Series:
"""
Fetch a single indicator series from FXMacroData and return it as a
pandas Series with a DatetimeIndex, named '{currency.upper()}_{indicator}'.
"""
url = f"{BASE_URL}/announcements/{currency}/{indicator}"
resp = requests.get(url, params={"api_key": API_KEY, "start": start}, timeout=15)
resp.raise_for_status()
records = resp.json().get("data", [])
if not records:
return pd.Series(name=f"{currency.upper()}_{indicator}", dtype=float)
series = (
pd.DataFrame(records)
.assign(date=lambda df: pd.to_datetime(df["date"]))
.set_index("date")["val"]
.sort_index()
.rename(f"{currency.upper()}_{indicator}")
)
return series
왜 하나의 지표에 따라 시리즈를 선택해야 할까요?
다른 통화에서 표시자는 다른 날짜에 출시됩니다. 그래서 그들은 절대 완벽하게 정렬 된 인덱스를 공유하지 않습니다. 각각의 별도의 시리즈로 저장하고 와 함께 결합 pd.concat(..., axis=1) 칸다가 날짜 정렬을 자동으로 처리하도록 합니다. NaN 아직 보고되지 않은 통화입니다.
단계 3 대시보드에 있는 모든 지표를 가져오
가져오기 보조자가 설치되어 있으면, 네 개의 통화에 대한 네 개의 지표를 뽑는 것은 간결한 루프입니다. 일시적인 네트워크 고개를 처리하기 위해 작은 재시험 포장을 추가합니다:
import time
CURRENCIES = ["usd", "eur", "gbp", "aud"]
INDICATORS = {
"policy_rate": "Policy Rate (%)",
"inflation": "CPI Inflation (% YoY)",
"unemployment": "Unemployment Rate (%)",
"pmi": "Manufacturing PMI",
}
def fetch_all(start: str = "2020-01-01", retries: int = 3) -> dict[str, pd.DataFrame]:
"""
Return a dict mapping each indicator slug to a wide DataFrame where
each column is one currency (e.g. USD_policy_rate, EUR_policy_rate).
"""
frames: dict[str, list[pd.Series]] = {ind: [] for ind in INDICATORS}
for currency in CURRENCIES:
for indicator in INDICATORS:
for attempt in range(retries):
try:
s = fetch_indicator(currency, indicator, start=start)
frames[indicator].append(s)
break
except requests.HTTPError as exc:
if attempt == retries - 1:
print(f"Warning: could not fetch {currency}/{indicator}: {exc}")
else:
time.sleep(1.5 ** attempt)
return {ind: pd.concat(series, axis=1) for ind, series in frames.items() if series}
렌더링 전에 데이터의 모양을 확인하기 위해 어떤 데이터 프레임을 상호 작용적으로 검사할 수 있습니다:
data = fetch_all(start="2021-01-01")
print(data["policy_rate"].tail())
# Output (example):
# USD_policy_rate EUR_policy_rate GBP_policy_rate AUD_policy_rate
# date
# 2025-01-29 4.25 NaN NaN NaN
# 2025-02-06 NaN NaN 4.50 NaN
# 2025-02-18 NaN NaN NaN 4.10
# 2025-03-06 NaN 2.50 NaN NaN
# 2025-03-19 4.25 NaN NaN NaN
단계 4 차트 작성 자료를 구성
음모가 가장 잘 작동합니다 전면 채우기 라인 차트에 대한 시리즈, 그래서 가장 최근에 알려진 값은 다음 출시까지 전진합니다. 차트 만들기 전에 전진 채우는 단계를 추가합니다:
def prepare_for_chart(df: pd.DataFrame) -> pd.DataFrame:
"""
Forward-fill each column so lines in the chart step at each release date
rather than showing gaps between announcements.
Resample to a monthly frequency for a cleaner visual.
"""
return (
df
.ffill()
.resample("ME") # month-end
.last()
.dropna(how="all")
)
월간 지표인 PMI의 경우, 전속 채우는 것이 덜 중요하지만, 기능은 이미 달별 데이터를 변경하지 않고 단순히 전달함으로써 우아하게 처리합니다.
5단계 플롯리 대시보드를 구축
리 make_subplots 이 유틸리티는 하나의 도형 객체에 여러 도표를 배치할 수 있습니다. 브라우저에서 표시하거나 HTML로 내보낼 수 있습니다
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Palette aligned with FXMacroData brand colours
COLORS = {
"usd": "#3B82F6", # finance blue
"eur": "#D97706", # gold
"gbp": "#16A34A", # green
"aud": "#7C3AED", # purple
}
SUBPLOT_TITLES = list(INDICATORS.values())
def build_dashboard(data: dict[str, pd.DataFrame]) -> go.Figure:
fig = make_subplots(
rows=2, cols=2,
subplot_titles=SUBPLOT_TITLES,
shared_xaxes=False,
vertical_spacing=0.12,
horizontal_spacing=0.08,
)
positions = [(1, 1), (1, 2), (2, 1), (2, 2)]
for (indicator, label), (row, col) in zip(INDICATORS.items(), positions):
df = prepare_for_chart(data[indicator])
for col_name in df.columns:
currency = col_name.split("_")[0].lower()
fig.add_trace(
go.Scatter(
x=df.index,
y=df[col_name],
mode="lines",
name=currency.upper(),
line=dict(color=COLORS[currency], width=2),
legendgroup=currency,
showlegend=(indicator == "policy_rate"), # one legend entry per currency
hovertemplate=f"%{{x|%b %Y}}: %{{y:.2f}}{통화.올라기 (upper)) } ",
),
row=row, col=col,
)
fig.update_layout(
title=dict(
text="G4 Central Bank Macro Dashboard",
font=dict(size=22, color="#1e3a5f"),
x=0.5,
),
paper_bgcolor="#f8fafc",
plot_bgcolor="#f1f5f9",
font=dict(family="Inter, system-ui, sans-serif", size=12, color="#334155"),
legend=dict(
orientation="h",
yanchor="bottom",
y=1.04,
xanchor="center",
x=0.5,
),
height=700,
margin=dict(t=100, b=50, l=60, r=40),
)
fig.update_xaxes(showgrid=True, gridcolor="#e2e8f0", zeroline=False)
fig.update_yaxes(showgrid=True, gridcolor="#e2e8f0", zeroline=False)
return fig
단계 6 대시보드를 실행
모든 것을 연결시켜 dashboard.py 입력 포인트 스크립트 fig.show()
기본 브라우저에서 대시보드를 열고, fig.write_html() 자율적인 HTML 파일을 저장하여 어디서나 공유하거나 임베스트할 수 있습니다.
if __name__ == "__main__":
print("Fetching macro data …")
data = fetch_all(start="2021-01-01")
print("Building dashboard …")
fig = build_dashboard(data)
# Option A: open in browser
fig.show()
# Option B: save as portable HTML file
fig.write_html("macro_dashboard.html", include_plotlyjs="cdn")
print("Saved macro_dashboard.html")
터미널에서 실행해
python dashboard.py
플롯리는 네 개의 라이브 패널과 함께 두 줄, 두 열의 대시보드를 보여주는 브라우저 창을 열 것입니다. 각 지표에 한 개의 색상 코딩을 통해 통화로 표시됩니다.
더 많은 지표를 초 내에 추가합니다.
대시보드는 확장할 수 있도록 설계되었습니다. INDICATORS 예를 들어,
"core_inflation": "Core CPI (% YoY)" 아니면 "gdp_quarterly": "GDP Growth (% QoQ)" 및 검색, 모양 및 차트 단계 모두 자동으로 검색합니다. 전체 지표 카탈로그는 API 문서-
단계 7 출시 시간 에 대한 설명 을 추가 (선택)
가장 유용한 대시보드 개선 중 하나는 겹치는 것입니다. 방출 표시기 각 발표가 정확히 언제 이루어졌는지 보여주는 수직선이나 점. FXMacroData는 두 번째 레벨을 가지고 있습니다.
announcement_datetime 시간표, 그래서 당신은 어떤 추측없이 그들을 추가 할 수 있습니다:
def fetch_release_datetimes(currency: str, indicator: str, start: str) -> pd.Series:
"""Return a Series of UTC announcement datetimes for a given indicator."""
url = f"{BASE_URL}/announcements/{currency}/{indicator}"
resp = requests.get(url, params={"api_key": API_KEY, "start": start}, timeout=15)
resp.raise_for_status()
records = resp.json().get("data", [])
if not records:
return pd.Series(dtype="datetime64[ns, UTC]")
df = pd.DataFrame(records)
if "announcement_datetime" not in df.columns:
return pd.Series(dtype="datetime64[ns, UTC]")
return pd.to_datetime(df["announcement_datetime"], utc=True)
def add_release_markers(fig: go.Figure, currency: str, indicator: str,
start: str, row: int, col: int) -> None:
"""Overlay vertical dashed lines on a subplot at each release datetime."""
datetimes = fetch_release_datetimes(currency, indicator, start)
for dt in datetimes:
fig.add_vline(
x=dt.timestamp() * 1000, # Plotly uses ms since epoch for datetime axes
line_width=1,
line_dash="dot",
line_color=COLORS[currency],
opacity=0.35,
row=row, col=col,
)
전화해 add_release_markers 그 후 build_dashboard 그리고 그 전에도 fig.show()
분석에 가장 관련 있는 패널을 설명할 수 있습니다. 릴리스 마커는 정책금리 패널에서 특히 유용합니다. 결정 날짜가 드물지만 큰 영향을 미치는 경우입니다.
단계 8 개별 이미지로 패널을 내보낼 수 있습니다
만약 당신이 보고 또는 슬라이드 데크에 개별 차트를 포함하고 싶다면, 플롯리는 각 하위 플롯을 PNG로 엑스포트할 수 있습니다. 카레이도
pip install kaleido
fig.write_image("macro_dashboard.png", width=1400, height=700, scale=2)
패널별 수출에 대해 각 지표가 독립적으로 만들어집니다. go.Figure 같은 것을 사용해서
go.Scatter 추적하고 전화 write_image 이전 단계에서 개발 된 가져와 모양 기능은 단일 패널 인자에 대해 변경되지 않습니다.
전체 스크립트 참조
아래는 전체, 자율적인 스크립트입니다. 위의 모든 단계를 결합합니다.
dashboard.py FXMD_API_KEY그리고 실행해
"""
macro_dashboard.py — G4 Central Bank Macro Dashboard
Requires: requests, pandas, plotly
Usage: FXMD_API_KEY=your_key python macro_dashboard.py
"""
import os
import time
import requests
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
BASE_URL = "https://fxmacrodata.com/api/v1"
API_KEY = os.environ["FXMD_API_KEY"]
CURRENCIES = ["usd", "eur", "gbp", "aud"]
INDICATORS = {
"policy_rate": "Policy Rate (%)",
"inflation": "CPI Inflation (% YoY)",
"unemployment": "Unemployment Rate (%)",
"pmi": "Manufacturing PMI",
}
COLORS = {"usd": "#3B82F6", "eur": "#D97706", "gbp": "#16A34A", "aud": "#7C3AED"}
def fetch_indicator(currency: str, indicator: str, start: str = "2020-01-01") -> pd.Series:
url = f"{BASE_URL}/announcements/{currency}/{indicator}"
resp = requests.get(url, params={"api_key": API_KEY, "start": start}, timeout=15)
resp.raise_for_status()
records = resp.json().get("data", [])
if not records:
return pd.Series(name=f"{currency.upper()}_{indicator}", dtype=float)
return (
pd.DataFrame(records)
.assign(date=lambda df: pd.to_datetime(df["date"]))
.set_index("date")["val"]
.sort_index()
.rename(f"{currency.upper()}_{indicator}")
)
def fetch_all(start: str = "2020-01-01", retries: int = 3) -> dict[str, pd.DataFrame]:
frames: dict[str, list[pd.Series]] = {ind: [] for ind in INDICATORS}
for currency in CURRENCIES:
for indicator in INDICATORS:
for attempt in range(retries):
try:
frames[indicator].append(fetch_indicator(currency, indicator, start))
break
except requests.HTTPError as exc:
if attempt == retries - 1:
print(f"Warning: {currency}/{indicator}: {exc}")
else:
time.sleep(1.5 ** attempt)
return {ind: pd.concat(series, axis=1) for ind, series in frames.items() if series}
def prepare_for_chart(df: pd.DataFrame) -> pd.DataFrame:
return df.ffill().resample("ME").last().dropna(how="all")
def build_dashboard(data: dict[str, pd.DataFrame]) -> go.Figure:
fig = make_subplots(
rows=2, cols=2,
subplot_titles=list(INDICATORS.values()),
vertical_spacing=0.12,
horizontal_spacing=0.08,
)
for (indicator, _), (row, col) in zip(INDICATORS.items(), [(1,1),(1,2),(2,1),(2,2)]):
df = prepare_for_chart(data[indicator])
for col_name in df.columns:
currency = col_name.split("_")[0].lower()
fig.add_trace(
go.Scatter(
x=df.index, y=df[col_name], mode="lines",
name=currency.upper(),
line=dict(color=COLORS[currency], width=2),
legendgroup=currency,
showlegend=(indicator == "policy_rate"),
hovertemplate=f"%{{x|%b %Y}}: %{{y:.2f}}{통화.올라기 (upper)) } ",
),
row=row, col=col,
)
fig.update_layout(
title=dict(text="G4 Central Bank Macro Dashboard", font=dict(size=22, color="#1e3a5f"), x=0.5),
paper_bgcolor="#f8fafc", plot_bgcolor="#f1f5f9",
font=dict(family="Inter, system-ui, sans-serif", size=12),
legend=dict(orientation="h", yanchor="bottom", y=1.04, xanchor="center", x=0.5),
height=700, margin=dict(t=100, b=50, l=60, r=40),
)
fig.update_xaxes(showgrid=True, gridcolor="#e2e8f0", zeroline=False)
fig.update_yaxes(showgrid=True, gridcolor="#e2e8f0", zeroline=False)
return fig
if __name__ == "__main__":
print("Fetching macro data …")
data = fetch_all(start="2021-01-01")
print("Building dashboard …")
fig = build_dashboard(data)
fig.show()
fig.write_html("macro_dashboard.html", include_plotlyjs="cdn")
print("Saved macro_dashboard.html")
요약
이제 작동하는 매크로 대시보드가 있습니다.
- 정책금, 인플레이션, 실업, PMI를 USD, EUR, GBP, AUD에서 가져옵니다. FXMacroData 발표 최종점
- 데이터를 정렬, 앞으로 채워진 판다로 재구성합니다.
- Renders a four-panel interactive Plotly dashboard with colour-coded currency lines
- 공유하거나 임베드할 수 있는 HTML 파일을 내보냅니다
여기서 여러 방향으로 대시보드를 확장할 수 있습니다. 더 많은 통화를 추가하고, 덮어 놓습니다. 실업 두 개의 축에 PMI에 대 한, 또는 HTML 수출을 매일 아침 갱신 하는 일정에 데이터를 전선. 무역 균형, 신용 성장 및 COT 위치 포함 전체 지표 카탈로그 에서 사용할 수 있습니다. api-data-docs-