Skip to main content

Institutional-grade Python library for Japanese macroeconomic and financial data

Project description

NihonMacro ๐Ÿ‡ฏ๐Ÿ‡ต

CI Python 3.11+ License: MIT

Institutional-grade Python library for Japanese macroeconomic and financial data.

Built for global macro hedge funds, quantitative researchers, and financial content creators. Think "OpenBB for Japan."

Quick Start

pip install nihonmacro
import asyncio
from nihonmacro import BOJClient, fit_nelson_siegel

async def main():
    # Fetch BoJ interest rate data
    boj = BOJClient()
    rates = await boj.interest_rates(start="2024-01-01")
    print(rates)

    # Fit Nelson-Siegel yield curve
    maturities = [0.5, 1, 2, 5, 10, 20, 30, 40]
    yields = [0.01, 0.05, 0.15, 0.45, 0.75, 1.40, 1.85, 2.10]
    params = fit_nelson_siegel(maturities, yields)
    print(f"ฮฒโ‚€={params['beta0']:.3f}, ฮฒโ‚={params['beta1']:.3f}, ฯ„={params['tau']:.2f}")

    await boj.close()

asyncio.run(main())

Architecture

nihonmacro/
โ”œโ”€โ”€ core/
โ”‚   โ”œโ”€โ”€ config.py          # Pydantic BaseSettings (.env management)
โ”‚   โ”œโ”€โ”€ rate_limiter.py    # Token bucket + Tenacity retry (429 handling)
โ”‚   โ”œโ”€โ”€ cache.py           # SQLite + Redis dual-layer caching
โ”‚   โ””โ”€โ”€ exceptions.py      # Typed exception hierarchy
โ”œโ”€โ”€ providers/
โ”‚   โ”œโ”€โ”€ boj.py             # Bank of Japan Statistics API
โ”‚   โ”œโ”€โ”€ jquants.py         # JPX J-Quants (auth lifecycle, daily bars)
โ”‚   โ”œโ”€โ”€ edinet.py          # EDINET v2 (metadata only, no XBRL)
โ”‚   โ””โ”€โ”€ buffettcode.py     # Buffett Code normalized financials
โ”œโ”€โ”€ scrapers/
โ”‚   โ”œโ”€โ”€ mof.py             # MoF JGB constant-maturity yields (CSV)
โ”‚   โ”œโ”€โ”€ mof_auction.py     # MoF historical auction results (XLS)
โ”‚   โ”œโ”€โ”€ jsda.py            # JSDA OTC bond reference stats (CSV)
โ”‚   โ”œโ”€โ”€ jsda_repo.py       # JSDA Tokyo Repo Rate (XLS)
โ”‚   โ”œโ”€โ”€ estat.py           # e-Stat govt statistics API (JSON)
โ”‚   โ””โ”€โ”€ jpx.py             # JPX margin trading statistics (XLS)
โ”œโ”€โ”€ extensions/
โ”‚   โ”œโ”€โ”€ macro.py           # Nelson-Siegel, Tankan DI
โ”‚   โ””โ”€โ”€ equities.py        # Activist screener, sector divergence
โ”œโ”€โ”€ utils/
โ”‚   โ””โ”€โ”€ calendars.py       # Japanese holidays & TSE trading days
โ””โ”€โ”€ showcase_app/          # Reflex web application
    โ”œโ”€โ”€ showcase_app.py
    โ””โ”€โ”€ components/

Providers

Provider Data Auth
BoJ Interest rates, JGB yields, Tankan survey Public (optional API key)
J-Quants Daily OHLCV, listed info, sector indices Refresh token โ†’ ID token
EDINET Filing metadata, 5% ownership reports Public (optional key)
Buffett Code Normalized financials, screening API key required

Scrapers (Public Data)

No API key required โ€” scrapes directly from Japanese government and exchange websites.

Source Client Data
MoF MOFClient JGB constant-maturity yields (1974โ€“present, 15 tenors)
MoF Auctions MOFAuctionClient Historical JGB auction results (14 tenor sheets, coupon/price/yield)
JSDA JSDAClient OTC bond reference statistics (daily, all listed bonds)
JSDA Repo JSDARepoClient Tokyo Repo Rate โ€” ON through 1Y (daily from 2012)
e-Stat EStatClient Government statistics (CPI, GDP, labour, industrial production)
JPX JPXClient Margin trading statistics (weekly snapshots + historical)
from nihonmacro.scrapers import MOFClient, JSDARepoClient

# JGB constant-maturity yields
mof = MOFClient()
yields = await mof.jgb_yields_full_history()  # Polars DataFrame, 1974โ€“present

# Tokyo Repo Rate time series
repo = JSDARepoClient()
rates = await repo.rate_history()  # daily ON, 1W, 1M, 3M, 6M, 1Y

Key Features

Nelson-Siegel Yield Curve Fitting

$$y(t) = \beta_0 + \beta_1 \frac{1 - e^{-t/\tau}}{t/\tau} + \beta_2 \left( \frac{1 - e^{-t/\tau}}{t/\tau} - e^{-t/\tau} \right)$$

from nihonmacro.extensions.macro import fit_nelson_siegel, nelson_siegel_curve
import numpy as np

params = fit_nelson_siegel(
    maturities=[0.5, 1, 2, 5, 10, 20, 30],
    observed_yields=[0.01, 0.05, 0.15, 0.45, 0.75, 1.40, 1.85],
)

# Interpolate at any maturity
fine_grid = np.linspace(0.25, 40, 200)
fitted = nelson_siegel_curve(params, fine_grid)

Tankan Diffusion Index

$$DI = %\text{Favorable} - %\text{Unfavorable}$$

from nihonmacro.extensions.macro import tankan_diffusion_index

di = tankan_diffusion_index(favorable_pct=45.2, unfavorable_pct=12.8)
# โ†’ 32.4

Activist Target Screener

from nihonmacro.extensions.equities import screen_activist_targets

targets = await screen_activist_targets(
    tickers=["8601", "8604", "6178"],
    pb_threshold=1.0,
    filing_lookback_days=180,
)

Macro-Sector Divergence

from nihonmacro.extensions.equities import sector_rate_divergence

merged = await sector_rate_divergence(start="2023-01-01", end="2025-01-01")

Configuration

Set API credentials via environment variables or a .env file:

# .env
JQUANTS_REFRESH_TOKEN=your_jquants_token
BUFFETTCODE_API_KEY=your_buffettcode_key
EDINET_API_KEY=your_edinet_key
ESTAT_APP_ID=your_estat_app_id

Showcase Website

Run the interactive Reflex showcase:

pip install nihonmacro[showcase]
reflex run

Development

pip install -e ".[dev]"
pytest                # 429 tests
ruff check nihonmacro/ tests/

Design Principles

  • Polars-first: All DataFrames are pl.DataFrame. Use .to_pandas() only at pipeline end.
  • Fault-tolerant: Stale cache fallback on API failure. Custom exceptions, not generic tracebacks.
  • Rate-limit aware: Token-bucket + Tenacity with Retry-After header parsing.
  • Type-safe: Full type hints throughout. Pydantic validation at boundaries.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nihonmacro-0.1.1.tar.gz (33.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nihonmacro-0.1.1-py3-none-any.whl (47.8 kB view details)

Uploaded Python 3

File details

Details for the file nihonmacro-0.1.1.tar.gz.

File metadata

  • Download URL: nihonmacro-0.1.1.tar.gz
  • Upload date:
  • Size: 33.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.11

File hashes

Hashes for nihonmacro-0.1.1.tar.gz
Algorithm Hash digest
SHA256 2f6d55d1056494aff84c34331edd394b51fa4291b024f1056b030e50cce7fb5b
MD5 ac41fa6b2a6bf70e92344ec7454ff4af
BLAKE2b-256 c619ba4da1a1f723c02a62cf9162375fe70de97e7ba83642001929faa79d3691

See more details on using hashes here.

File details

Details for the file nihonmacro-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: nihonmacro-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 47.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.11

File hashes

Hashes for nihonmacro-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 fbe718a2845328ff71c1e3dc07e9bb420cdf302b750180e71ce54814081fd803
MD5 bb1d777fc168836c63f1f998a5b636f3
BLAKE2b-256 b078f7ab78853486b32bc00021f04f37d7e7321a2b9fd8b1f7f423ec9240bec5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page