Skip to main content

Python client for the U.S. Treasury Fiscal Data API

Project description

Treasury Fiscal Data API Client

PyPI version Python License: MIT Tests Coverage

A professional Python client for the U.S. Treasury Fiscal Data API. No API key required.

Features

  • Zero config — no API key, no registration
  • Type-safe — Pydantic v2 models for every dataset
  • Fluent filtersFilterBuilder for clean, composable queries
  • Auto-pagination — lazy iter_pages() generator and get_all() collector
  • Resilient — automatic retries with exponential backoff on server errors
  • pandas-ready — one-line response.to_dataframe() export
  • Context manager — proper session lifecycle management

Installation

pip install fiscaldata-treasury-api

With pandas support:

pip install "fiscaldata-treasury-api[pandas]"

Quick Start

from core import TreasuryClient

client = TreasuryClient()

# Latest U.S. public debt figures
debt = client.get_public_debt(limit=5)
for record in debt:
    print(f"{record.record_date}  ${record.tot_pub_debt_out_amt:,.0f}")

# Recent T-Bill auction results
auctions = client.get_auctions(security_type="Bill", limit=10)
for a in auctions:
    print(f"{a.auction_date}  {a.security_term}  rate={a.high_investment_rate}%")

# USD/EUR exchange rates
rates = client.get_exchange_rates(country_currency="Euro Zone-Euro", limit=4)
for r in rates:
    print(f"{r.record_date}  {r.exchange_rate}")

Filtering

Use FilterBuilder to compose queries with a fluent API:

from core import TreasuryClient
from core.filters import FilterBuilder

client = TreasuryClient()

f = (
    FilterBuilder()
    .eq("security_type", "Note")
    .gte("auction_date", "2024-01-01")
    .lte("auction_date", "2024-12-31")
)

auctions = client.get_all("auctions", filters=f, sort="-auction_date")
Method Operator
.eq(field, value) field == value
.neq(field, value) field != value
.gt(field, value) field > value
.gte(field, value) field >= value
.lt(field, value) field < value
.lte(field, value) field <= value
.in_(field, [v1, v2]) field in (v1, v2)

Pagination

# Lazy page-by-page iteration (memory-efficient for large datasets)
for page in client.iter_pages("auctions", page_size=1000, sort="-auction_date"):
    for record in page.data:
        process(record)

# Collect all records into a flat list
all_records = client.get_all(
    "debt_to_penny",
    filters=FilterBuilder().gte("record_date", "2023-01-01"),
    page_size=1000,
)

Export to pandas

response = client.get("debt_to_penny", page_size=200, sort="-record_date")
df = response.to_dataframe()

Raw endpoint access

# Named key (recommended)
response = client.get("debt_to_penny", page_size=10)

# Raw path (access any endpoint, including undocumented ones)
response = client.get("/v2/accounting/od/debt_to_penny", page_size=10)

Available Endpoints

Key Description API Version
debt_to_penny Daily U.S. public debt outstanding v2
avg_interest_rates Average interest rates on Treasury securities v2
interest_expense Monthly interest expense on the national debt v2
auctions Treasury security auction results v1
exchange_rates Treasury Reporting Rates of Exchange v1
savings_bonds U.S. Savings Bonds issuances and redemptions v1
mts_receipts_outlays Monthly Treasury Statement — receipts & outlays v1
mts_outlays_by_agency Monthly Treasury Statement — outlays by agency v1
mts_budget_comparison Monthly Treasury Statement — budget comparison v1
dts_operating_cash Daily Treasury Statement — operating cash v1
top_by_state Treasury Offset Program by state v1
top_federal Treasury Offset Program — federal agencies v1
# Discover all endpoints at runtime
for name, info in TreasuryClient.list_endpoints().items():
    print(f"{name:<25}  {info.description}")

API Reference

TreasuryClient

TreasuryClient(
    timeout: int = 30,
    max_retries: int = 3,
    backoff_factor: float = 0.5,
)

Generic methods

Method Returns
get(endpoint, *, fields, filters, sort, page_number, page_size) APIResponse
iter_pages(endpoint, *, fields, filters, sort, page_size) Generator[APIResponse]
get_all(endpoint, *, fields, filters, sort, page_size, limit) List[Dict]
list_endpoints() Dict[str, EndpointInfo]

Typed convenience methods

Method Model
get_public_debt(*, start_date, end_date, limit) DebtRecord
get_avg_interest_rates(*, security_type, start_date, limit) InterestRateRecord
get_auctions(*, security_type, start_date, end_date, limit) AuctionRecord
get_exchange_rates(*, country_currency, start_date, limit) ExchangeRateRecord
get_interest_expense(*, start_date, limit) InterestExpenseRecord
get_savings_bonds(*, series, limit) SavingsBondsRecord
get_dts_operating_cash(*, start_date, account_type, limit) DtsOperatingCashRecord
get_top_collections_by_state(*, state, limit) TopByStateRecord

APIResponse

Attribute / Method Description
.data List[Dict] — raw records
.meta.total_count Total records matching the query
.meta.total_pages Total pages at the current page size
.meta.labels Human-readable field labels
.links.has_next True if more pages exist
.to_dataframe() Convert to pandas DataFrame
.to_models(ModelClass) Deserialize into Pydantic models

Examples

See the examples/ directory:

File Description
basic_usage.py Quick tour of the main convenience methods
debt_analysis.py Year-over-year debt growth analysis
auction_analysis.py Bid-to-cover ratio statistics by security term
exchange_rates.py Compare rates across major currencies
pandas_export.py Export to pandas DataFrame
python examples/basic_usage.py
python examples/debt_analysis.py 2023
python examples/auction_analysis.py 2024

Development

git clone https://github.com/user/fiscaldata-treasury-api.git
cd fiscaldata-treasury-api
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest

Run with coverage:

pytest --cov=core --cov-report=term-missing

Lint and format:

ruff check core tests
ruff format core tests
mypy core

Publishing to PyPI

pip install build twine
python -m build
twine upload dist/*

License

MIT © Charles-Emmanuel Teuf

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

fiscaldata_treasury_api-0.1.2.tar.gz (16.9 kB view details)

Uploaded Source

Built Distribution

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

fiscaldata_treasury_api-0.1.2-py3-none-any.whl (13.8 kB view details)

Uploaded Python 3

File details

Details for the file fiscaldata_treasury_api-0.1.2.tar.gz.

File metadata

  • Download URL: fiscaldata_treasury_api-0.1.2.tar.gz
  • Upload date:
  • Size: 16.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for fiscaldata_treasury_api-0.1.2.tar.gz
Algorithm Hash digest
SHA256 b42569c8238c7ec9c38c05bea1716dca21c52f59749833bbc807649239d1f5ed
MD5 bf1513c3a5c17802d4c2780ede969e0d
BLAKE2b-256 51678f3c8600e2f9022db38bddeec4cf770391ca12f467f5f2d5fca8027c2d27

See more details on using hashes here.

Provenance

The following attestation bundles were made for fiscaldata_treasury_api-0.1.2.tar.gz:

Publisher: publish.yml on ce-teuf/fiscaldata-treasury-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fiscaldata_treasury_api-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for fiscaldata_treasury_api-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0aef0d5036e86ea027db232be4df58aa9981d27d398f1fee214106430bab2e42
MD5 292de92f66219a49fe5c270f8b259da7
BLAKE2b-256 2601ea9dec547fa3d5032ff29a80fb201fa51e655abe62172de75f37a6de4ff7

See more details on using hashes here.

Provenance

The following attestation bundles were made for fiscaldata_treasury_api-0.1.2-py3-none-any.whl:

Publisher: publish.yml on ce-teuf/fiscaldata-treasury-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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