Metadata-Version: 2.4
Name: nihonmacro
Version: 0.1.1
Summary: Institutional-grade Python library for Japanese macroeconomic and financial data
Project-URL: Homepage, https://showcase-app-navy-apple.reflex.run/
Project-URL: Repository, https://github.com/YenAle-FT-Gmail/NihonMacro
Project-URL: Documentation, https://showcase-app-navy-apple.reflex.run/docs
Project-URL: Issues, https://github.com/YenAle-FT-Gmail/NihonMacro/issues
Author: NihonMacro Contributors
License-Expression: MIT
License-File: LICENSE
Keywords: boj,edinet,finance,japan,jgb,jquants,macro
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Office/Business :: Financial
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: numpy>=1.26
Requires-Dist: polars>=1.0
Requires-Dist: pydantic-settings>=2.1
Requires-Dist: pydantic>=2.5
Requires-Dist: python-dotenv>=1.0
Requires-Dist: scipy>=1.12
Requires-Dist: tenacity>=8.2
Requires-Dist: xlrd>=2.0
Provides-Extra: all
Requires-Dist: mkdocs-material>=9.5; extra == 'all'
Requires-Dist: mkdocstrings[python]>=1.0; extra == 'all'
Requires-Dist: plotly>=5.18; extra == 'all'
Requires-Dist: pytest-asyncio>=0.23; extra == 'all'
Requires-Dist: pytest>=8.0; extra == 'all'
Requires-Dist: redis>=5.0; extra == 'all'
Requires-Dist: reflex>=0.6; extra == 'all'
Requires-Dist: respx>=0.20; extra == 'all'
Requires-Dist: ruff>=0.3; extra == 'all'
Requires-Dist: xlwt>=1.3; extra == 'all'
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: respx>=0.20; extra == 'dev'
Requires-Dist: ruff>=0.3; extra == 'dev'
Requires-Dist: xlwt>=1.3; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=1.0; extra == 'docs'
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == 'redis'
Provides-Extra: showcase
Requires-Dist: plotly>=5.18; extra == 'showcase'
Requires-Dist: reflex>=0.6; extra == 'showcase'
Description-Content-Type: text/markdown

# NihonMacro 🇯🇵

[![CI](https://github.com/YenAle-FT-Gmail/NihonMacro/actions/workflows/ci.yml/badge.svg)](https://github.com/YenAle-FT-Gmail/NihonMacro/actions/workflows/ci.yml)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/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

```bash
pip install nihonmacro
```

```python
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) |

```python
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)$$

```python
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}$$

```python
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

```python
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

```python
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:

```bash
# .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:

```bash
pip install nihonmacro[showcase]
reflex run
```

## Development

```bash
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
