Live release feed
Sub-second macro releases for FX backtests
Point-in-time history
Official CPI, jobs, GDP, and central-bank events with point-in-time history.
USD 25/month 14-day free trial
Start Free Trial
パンダとプロットリーで Python でマクロダッシュボードを構築する方法 image
Share headline card X LinkedIn Email
Download

By Language

Quick Start Guides

パンダとプロットリーで Python でマクロダッシュボードを構築する方法

Python で FXMacroData インディケーターを取得する手順ガイド,パンダでタイムシリーズを再構成し,Plotly でインタラクティブなマルチパネルダッシュボードを組み立てます.

他言語版 English
Share article X LinkedIn Email

A macro dashboard puts the most important central-bank and economic indicators in one place, so you can scan market conditions in seconds instead of bouncing between data terminals. This guide walks you through building a fully interactive, multi-panel dashboard in Python — fetching live indicator data from the FXMacroData API, reshaping it with パンダ翻訳して 意図的に機能の呼び出しから更新されます.

あなた が 築く もの

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.

条件

始める前に次のものが必要です.

  • Python 3.9+
  • FXMacroData API キーを 登録する / サブスクリプト そしてダッシュボードからあなたの鍵をコピー
  • Python パッケージありがとうございました requestsほら pandasほら plotly

一つのコマンドで依存関係をインストールする:

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, and — where available — a second-level UTC announcement_datetime. The consistent shape across all indicators is what lets one function serve every panel in the dashboard.

ステップ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 ダッシュボードのすべての指標を取得

With the fetch helper in place, pulling four indicators for four currencies is a concise loop. Add a small retry wrapper to handle transient network hiccups:

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としてエクスポートしたり Jupyter ノートブックに埋め込むことができます. 図形は,

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}}{通貨.上方() }",
                ),
                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() 共有したり埋め込むことができます. ウェブのページをクリックすると,

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

Plotly will open a browser window showing a two-row, two-column dashboard with four live panels — one for each indicator — colour-coded by currency. Hovering over any line reveals the exact date and value for that release.

秒でより多くの指標を追加

ダイッシュボードはスケーリングに設計されています. INDICATORS と 言う "core_inflation": "Core CPI (% YoY)" ほら "gdp_quarterly": "GDP Growth (% QoQ)" 検索,形状,チャート手順は自動的にそれをピックアップします. 完全な指標カタログは, API 文書ほら

ステップ7 リリースタイムアノテーションを追加 (オプション)

ダイッシュボードの改良の"つは オーバーレイです 放出マーカー — vertical lines or dots that show exactly when each announcement was made. FXMacroData carries second-level 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として輸出できます. 図形は,Plotlyのプロットで作成されます. カレードありがとうございました

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}}{通貨.上方() }",
                ),
                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を,ドル,ユーロ,英,オーストラリアドルから FXMacroData の発表 エンドポイント
  • データを並べた,前向きに埋められたパンダに再構成します DataFrames
  • Renders a four-panel interactive Plotly dashboard with colour-coded currency lines
  • 共有したり埋め込むことができる自立 HTML ファイルを輸出します

複数の方向に拡張できます. 通貨を追加し,オーバーレイ 失業 貿易平衡,信用成長,COTポジショニングを含む全指標カタログは,WEB で入手できます. api-data-docs についてほら

Blogroll

AI Answer-Ready

Key Facts

Page
How To Build Macro Dashboard Python Pandas
Section
Articles
Canonical URL
https://fxmacrodata.com/ja/articles/how-to-build-macro-dashboard-python-pandas
Source
FXMacroData editorial and official publisher references
Last Updated
2026-06-15 11:06 UTC

Provenance And Trust

Cite the canonical URL and source field above. Where available, this page maps to official publisher releases and timestamped updates.

Quick Q&A

What is this page about? This page explains How To Build Macro Dashboard Python Pandas with directly usable context for trading, research, and API workflows.

What source should be cited? Use the canonical URL and the listed source field; cite official publisher references when available.

How fresh is this content? The last updated value above reflects the page metadata or latest available data timestamp.

Can this be used in AI assistants? Yes. This section is intentionally structured for retrieval and citation in chat assistants.

Prompt Packs

Use these in ChatGPT, Claude, Gemini, Mistral, Perplexity, or Grok for consistent source-aware outputs.