How to Build a Macro Dashboard in Python with pandas & Plotly banner image

By Language

Quick Start Guides

How to Build a Macro Dashboard in Python with pandas & Plotly

पायथन के माध्यम से FXMacroData संकेतकों को लाने के लिए चरण-दर-चरण गाइड, पांडा के साथ समय श्रृंखला को फिर से आकार देना, और प्लॉटली के साथ एक इंटरैक्टिव मल्टी-पैनल डैशबोर्ड इकट्ठा करना।

इसमें भी उपलब्ध है English

एक मैक्रो डैशबोर्ड एक ही स्थान पर सबसे महत्वपूर्ण केंद्रीय बैंक और आर्थिक संकेतकों को रखता है, ताकि आप डेटा टर्मिनलों के बीच उछाल के बजाय सेकंड में बाजार की स्थिति को स्कैन कर सकें। यह गाइड आपको पायथन में एक पूरी तरह से इंटरैक्टिव, बहु-पैनल डैਸ਼बोर्ड बनाने के माध्यम से चलता है FXMacroData एपीआई से लाइव संकेतक डेटा प्राप्त करना, इसे फिर से आकार देना पांडा, और इसे के साथ प्रस्तुत करना षड्यंत्र. प्रत्येक पैनल एक एकल एपीआई कुंजी और एक मुट्ठी भर फ़ंक्शन कॉल से अद्यतन करता है.

आप क्या बनाएंगे

एक आत्मनिर्भर पायथन स्क्रिप्ट जो चार प्रमुख विदेशी मुद्रा मुद्राओं (यूएसडी, यूरो, GBP, एयूडी) के लिए नीति दरों, मुद्रास्फीति, बेरोजगारी और पीएमआई को खींचती है, प्रत्येक संकेतक के लिए एक स्वच्छ पांडा डेटाफ्रेम इकट्ठा करती है, और चार पैनल प्लॉट डैशबोर्ड को कोड की 150 पंक्तियों से कम में प्रस्तुत करती है।

पूर्व शर्तें

शुरू करने से पहले आपको निम्नलिखित की आवश्यकता होगी:

  • पायथन 3.9+
  • FXMacroData एपीआई कुंजी पर साइन अप करें /अपना नाम लिखें और डैशबोर्ड से अपनी कुंजी की प्रतिलिपि
  • पायथन पैकेज requests, pandas, plotly

निर्भरताएँ एक कमांड में स्थापित करेंः

pip install requests pandas plotly

अपनी एपीआई कुंजी को पर्यावरण चर के रूप में स्टोर करें स्क्रिप्ट में हार्ड-कोड क्रेडेंशियल्स कभी नहींः

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 (वर्षवर्ष-मम-दद), एक संख्या 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 चार्टिंग के लिए डेटा को आकार दें

Plotly के साथ सबसे अच्छा काम करता है आगे से भरा हुआ रेखा चार्ट के लिए श्रृंखला, इसलिए नवीनतम ज्ञात मान अगले रिलीज तक आगे बढ़ता है। चार्टिंग से पहले एक आगे-भरा step जोड़ें:

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() एक स्वतंत्र 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 एक ब्राउज़र विंडो खोल देगा जिसमें चार लाइव पैनलों के साथ दो पंक्तियों, दो कॉलम वाले डैशबोर्ड दिखाई देंगे प्रत्येक संकेतक के लिए एक मुद्रा द्वारा रंग-कोडित। किसी भी पंक्ति पर होवर करके उस रिलीज की सटीक तिथि और मूल्य का पता चलता है।

सेकंड में अधिक संकेतक जोड़ें

डैशबोर्ड को स्केल करने के लिए डिज़ाइन किया गया है। INDICATORS उदाहरण के लिए "core_inflation": "Core CPI (% YoY)" या "gdp_quarterly": "GDP Growth (% QoQ)" और फ़ॉरफ़ाट, फ़ॉर्मेट और चार्ट चरण इसे स्वचालित रूप से चुनते हैं। एपीआई प्रलेखन. .

चरण 7 रिलीज़-टाइमिंग एनोटेशन जोड़ें (वैकल्पिक)

सबसे उपयोगी डैशबोर्ड में सुधारों में से एक ओवरले है रिलीज़ मार्कर ऊर्ध्वाधर रेखाएं या डॉट्स जो प्रत्येक घोषणा के समय को सटीक रूप से दर्शाती हैं। 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 पैनलों को व्यक्तिगत छवियों के रूप में निर्यात करें

यदि आप एक रिपोर्ट या स्लाइड डेक में व्यक्तिगत चार्ट शामिल करना चाहते हैं, तो प्लॉटली प्रत्येक सबप्लॉट को पीएनजी के रूप में निर्यात कर सकता है। कालिडो

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")

सारांश

अब आपके पास एक कार्यशील मैक्रो डैशबोर्ड है जोः

  • मुद्रास्फीति, बेरोजगारी और अमरीकी डालर, यूरो, GBP और ऑस्ट्रेलियाई डॉलर के लिए पीएमआई की नीतिगत दरें FXMacroData की घोषणाएं
  • डेटा को संरेखित, आगे से भरे पंडा में बदलता है DataFrames
  • चार पैनल इंटरैक्टिव प्लॉट मुद्रा लाइनों के साथ डैशबोर्ड प्रस्तुत करता है
  • एक स्वतंत्र HTML फ़ाइल निर्यात करता है जिसे आप साझा या एम्बेड कर सकते हैं

यहाँ से आप डैशबोर्ड को कई दिशाओं में बढ़ा सकते हैंः अधिक मुद्राओं को जोड़ें, ओवरले बेरोजगारी या डेटा को एक अनुसूचित कार्य में कनेक्ट करें जो हर सुबह एचटीएमएल निर्यात को ताज़ा करता है। व्यापार संतुलन, क्रेडिट वृद्धि और सीओटी पोजिशनिंग सहित पूर्ण संकेतक सूची पर उपलब्ध है। एपीआई-डेटा-डॉक्स. .

AI Answer-Ready

Key Facts

Page
How To Build Macro Dashboard Python Pandas
Section
Articles
Canonical URL
https://fxmacrodata.com/articles/how-to-build-macro-dashboard-python-pandas
Source
FXMacroData editorial and official publisher references
Last Updated
2026-04-22 12:36 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.

Blogroll