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
R でマクロデータを分析する方法 image
Share headline card X LinkedIn Email
Download

By Language

Quick Start Guides

R でマクロデータを分析する方法

RでFXMacroData指標の時間列を httr2,jsonlite,ggplot2 を使って API コールから公開準備のチャートに 50 行未満のコードで取得,整理,視覚化するための実践的なガイド.

他言語版 English
Share article X LinkedIn Email

R is one of the most powerful languages for statistical analysis and financial modelling — and it has a mature ecosystem for working with time-series data. This guide walks through everything you need to fetch, clean, and analyse FXMacroData indicator series in R, using the modern httr2 ほら ジュンライト 整理されたタブルを構築し 公開可能チャートを作ります 50行未満のコードで

あなた が 築く もの

FXMacroData REST API に基づいて認証し,複数の通貨の政策レートとインフレ時間列を取得し,単一のチブルに結合し,ggplot2 でプロットし,クォートまたはR Markdown レポートに埋め込む準備ができています.

条件

  • R ≥ 4.2 と RStudio (または任意のR環境)
  • 荷物は以下のとおりです httr2ほら jsonliteほら dplyrほら tidyrほら lubridateほら ggplot2
  • 登録する / サブスクリプト 買える

必要なパッケージを一度インストールしてください.

install.packages(c("httr2", "jsonlite", "dplyr", "tidyr", "lubridate", "ggplot2"))

Step 1 — Understand the API Shape

FXMacroDataのすべてのエンドポイントは同じURLパターンをフォローします.

GET https://fxmacrodata.com/api/v1/announcements/{currency}/{indicator}?api_key=YOUR_API_KEY

応答は JSON オブジェクトで data 配列は,各要素が date ほら val フィールド (選択的には announcement_datetime 公開時の精度について) 参照します.例えば,アメリカ連邦準備制度理事会の政策金利を

curl "https://fxmacrodata.com/api/v1/announcements/usd/policy_rate?api_key=YOUR_API_KEY&start=2022-01-01"
{
  "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" }
  ]
}

このクリーンな構造は Rデータフレームに完璧にマップされ 変容は最小限です

Step 2 — Set Up Your API Key

文字でコードする代わりに環境変数に保存します. ~/.Renviron ファイル:

FXMD_API_KEY=your_actual_api_key_here

スクリプトのトップにある鍵を 読み返してください

readRenviron("~/.Renviron")
API_KEY <- Sys.getenv("FXMD_API_KEY")
if (nchar(API_KEY) == 0) stop("FXMD_API_KEY is not set in .Renviron")

セキュリティ・ティップ

バージョンコントロールに API キーをコミットしないでください. .Renviron ほら ほろ .gitignore 複製可能な展開では,秘密管理者または CI 環境変数を使用します.

ステップ3 一般的な検索ヘルパーを書いてください

付き合ってる httr2 命令の作成は,JSONの処理を,Jsonの処理の処理と,JSONの処理が,JSSONの操作を,

library(httr2)
library(jsonlite)
library(dplyr)
library(lubridate)

BASE_URL <- "https://fxmacrodata.com/api/v1"

#' Fetch an indicator time series from FXMacroData
#'
#' @param currency  Three-letter currency code, e.g. "usd", "eur", "gbp"
#' @param indicator Indicator slug, e.g. "policy_rate", "inflation", "gdp"
#' @param start     Optional start date as "YYYY-MM-DD" string
#' @param end       Optional end date as "YYYY-MM-DD" string
#' @return A tibble with columns: date (Date), val (numeric), currency (chr), indicator (chr)
fetch_indicator <- function(currency, indicator, start = NULL, end = NULL) {
  req <- request(BASE_URL) |>
    req_url_path_append("announcements", currency, indicator) |>
    req_url_query(api_key = API_KEY) |>
    req_error(is_error = \(resp) resp_status(resp) >= 400)

  if (!is.null(start)) req <- req |> req_url_query(start = start)
  if (!is.null(end))   req <- req |> req_url_query(end   = end)

  resp <- req |> req_perform()
  rows <- resp |> resp_body_json(simplifyVector = TRUE)

  as_tibble(rows$data) |>
    mutate(
      date      = as_date(date),
      val       = as.numeric(val),
      currency  = toupper(currency),
      indicator = indicator
    )
}

鍵となる選択は req_error() HTTP 4xx/5xx応答が,無音で悪いデータを返すのではなく,R条件を投げるようにします. resp_body_json(simplifyVector = TRUE) リストではなくデータフレームに直接嵌入した配列を強制します. as_date() 潤滑液から 適切な Date すぐ列を

ステップ4 複数の通貨と指標を取得する

Now use the helper to pull policy rates for four G4 currencies over a three-year window — exactly the kind of multi-currency comparison that drives divergence trading decisions:

currencies <- c("usd", "eur", "gbp", "jpy")
START      <- "2022-01-01"

# Pull policy rates for all four currencies and stack into one tibble
policy_rates <- purrr::map_dfr(
  currencies,
  \(ccy) fetch_indicator(ccy, "policy_rate", start = START)
)

# Quick check
dplyr::glimpse(policy_rates)
#> Rows: ~80
#> Columns: date <date>, val <dbl>, currency <chr>, indicator <chr>

利率の差を計算できます.これは,キャリトレードポジショニングの重要な要因です.

inflation <- purrr::map_dfr(
  currencies,
  \(ccy) fetch_indicator(ccy, "inflation", start = START)
)

# Combine into one tidy frame
macro_data <- bind_rows(policy_rates, inflation)

入手できる指標

詳細はこちらから fxmacrodata.com/api-data-docs ファイルファイルは外国為替分析の主要シリーズには 政策率ほら インフレほら GDPほら 失業ほら 血圧通貨とインディケーターのスラグを変更するだけです.

ステップ 5 データをクリーンにして再構成する

分析のほとんどはデータが必要です format — one column per indicator per currency — rather than the stacked tidy format returned by the API. The tidyr pivot_wider() call handles this in one step, and fill() 定期的な月間格子に中央銀行の稀な発表の観察を転送します.

library(tidyr)

# Build a regular monthly date spine
date_spine <- tibble(date = seq.Date(as_date(START), Sys.Date(), by = "month"))

# Pivot to wide: one row per date, columns = currency_indicator
wide_data <- macro_data |>
  # Use year-month as join key so quarterly data aligns to month boundaries
  mutate(date = floor_date(date, "month")) |>
  pivot_wider(
    names_from  = c(currency, indicator),
    values_from = val,
    values_fn   = \(x) last(x)   # take latest reading within each month
  )

# Left-join onto the date spine and forward-fill sparse series
full_data <- date_spine |>
  left_join(wide_data, by = "date") |>
  fill(everything(), .direction = "down")

head(full_data)

ステップ6 リアルレート・スプレッドを計算する

利率の差は政策利率マイナスインフレです. 利差は消費価格の成長に対して中央銀行が制限的領域にあることを意味します. EUR/USDの実質利率差は,EUR/USD方向性の最も強い中期予測要因の一つです.

spread_data <- full_data |>
  mutate(
    real_rate_usd = USD_policy_rate - USD_inflation,
    real_rate_eur = EUR_policy_rate - EUR_inflation,
    real_rate_gbp = GBP_policy_rate - GBP_inflation,
    real_rate_jpy = JPY_policy_rate - JPY_inflation,
    # EUR minus USD spread: positive = EUR relatively less restrictive
    eur_usd_spread = real_rate_eur - real_rate_usd
  )

ステップ7 ggplot2で視覚化する

整理されたタブルが準備されているので, ggplot2の多行グラフは数行になります. colour 美しい

library(ggplot2)

policy_rates |>
  ggplot(aes(x = date, y = val, colour = currency)) +
  geom_step(linewidth = 0.9) +
  scale_colour_manual(
    values = c(USD = "#2563eb", EUR = "#16a34a", GBP = "#7c3aed", JPY = "#dc2626")
  ) +
  scale_y_continuous(labels = scales::label_percent(scale = 1)) +
  labs(
    title   = "G4 Central Bank Policy Rates",
    x       = NULL,
    y       = "Policy rate (%)",
    colour  = "Currency",
    caption = "Source: FXMacroData"
  ) +
  theme_minimal(base_size = 13) +
  theme(legend.position = "bottom")

使用する geom_step() 代わりに geom_line() 政策金利シリーズでは 中央銀行の決定は別々の階層変化であり,ステップチャートはそれを正しく表しています.

ステップ8 報告書の輸出

このチャートをQuartoまたはR Markdown文書に埋め込む場合は,再現可能性のためにデータフレームをCSVに保存し,インラインレンダリングのために高解像度のPNGにプロットします.

readr::write_csv(spread_data, "macro_spread_data.csv")

ggsave(
  filename = "policy_rates.png",
  width    = 10,
  height   = 5.6,
  dpi      = 150
)

インタラクティブなシャイニーダッシュボードでは 同じタブを直接 plotly::ggplotly() 摩擦がゼロのインタラクティビティのため

ステップ9 計画されたスクリプトで自動化

自動再実行なしで分析を継続するには, スタンドアロンRスクリプトにフェッチロジックを包み込み, cronR (Linux/macOS) または Windows タスクスケジューラー:

# file: refresh_macro.R — run daily at 08:00 UTC
readRenviron("~/.Renviron")
source("fetch_helpers.R")

macro_data <- purrr::map_dfr(
  tidyr::crossing(
    currency  = c("usd", "eur", "gbp", "jpy"),
    indicator = c("policy_rate", "inflation", "unemployment")
  ),
  \(row) fetch_indicator(row$currency, row$indicator, start = "2020-01-01")
)

readr::write_csv(macro_data, paste0("data/macro_", Sys.Date(), ".csv"))
message("Refresh complete: ", nrow(macro_data), " observations written.")

組み合わせる リリースカレンダーエンドポイント 静かな日に不要な API コールを省くため,高影響データが期待される日にのみリフレッシュを起動します.

完全な実用例

上記のすべてのスニペットが 単一の~60行のスクリプトに結合します. FXMD_API_KEY ほら ほろ .RenvironRでモデル化できる マクロデータセットが用意されています

概要

学習する方法

  • 環境変数を使用してFXMacroDataで安全に認証する
  • 復元可能なものを作る fetch_indicator() 助手として httr2 ほら ジュンライト
  • 複数の通貨の指標を引いて並べます purrr::map_dfr()
  • 計算して, 計算する について ほら 静かさ
  • 公開準備の段階図を作成します ggplot2 について
  • 日々の更新をスケジュールされたRスクリプトで自動化します

次のステップとして,探検 GDPほら PMIほら 貿易バランス G10の通貨全体でより完全なマクロスコアカードを構築するエンドポイント.同じフェッチヘルパーと ggplot2ワークフローが変更されないまま適用されます.

Blogroll

AI Answer-Ready

Key Facts

Page
How To Macro Data R Analysis
Section
Articles
Canonical URL
https://fxmacrodata.com/ja/articles/how-to-macro-data-r-analysis
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 Macro Data R Analysis 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.