# US Treasury Data — Yields, Debt & Rates for AI Agents (`haketa/treasury-data`) Actor

Get official US Treasury data for AI agents: daily yield curve (with 2s10s spread), national debt, average interest rates, interest expense and official exchange rates. Real-time fiscal & rates grounding for finance, macro and trading agents — keyless.

- **URL**: https://apify.com/haketa/treasury-data.md
- **Developed by:** [Haketa](https://apify.com/haketa) (community)
- **Categories:** AI, Agents, Business
- **Features:** Limited permissions
- **Stats:** 3 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.40 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## US Treasury Data Scraper — Yield Curve, National Debt, Interest & Exchange Rates

[![Apify Actor](https://img.shields.io/badge/Apify-Actor-orange?style=flat-square\&logo=apify)](https://apify.com/haketa/treasury-data)
[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg?style=flat-square)](https://apify.com/haketa/treasury-data)
[![Data Export](https://img.shields.io/badge/Export-JSON%20%7C%20CSV%20%7C%20Excel-blue?style=flat-square)](https://apify.com/haketa/treasury-data)
[![Finance Intelligence](https://img.shields.io/badge/Finance-Macro%20Grounding-brightgreen?style=flat-square)](https://apify.com/haketa/treasury-data)
[![Scale](https://img.shields.io/badge/Pagination-1%2C000%2B%20Historical%20Records-purple?style=flat-square)](https://apify.com/haketa/treasury-data)

**Scrape official US Treasury data** in a single call: the **daily Treasury yield curve** (every tenor, 1 Mo → 30 Yr, with the **2s10s spread** pre-computed), the **US national debt to the penny**, **average interest rates**, **interest expense on the debt**, and the **official Treasury exchange rates** (150+ currencies) — returned as clean, structured records, each with a ready-to-use human-readable summary. This **US Treasury scraper** pulls authoritative data straight from the [U.S. Department of the Treasury](https://fiscaldata.treasury.gov/) — **no login, no API key, no coding**.

Export to **JSON, CSV, Excel, or API**.

> Built for AI finance & macro agents, fixed-income and trading tools, quant researchers, fintech dashboards, economists, and journalists who need exact, citable sovereign-rate and debt figures on demand.

***

### ⚡ At a glance

| Feature | Details |
| --- | --- |
| **Primary Sources** | U.S. Department of the Treasury (FiscalData API & Daily Treasury Yield Curve Portal) |
| **Datasets Covered** | Daily Yield Curve (14 tenors), National Debt to the Penny, Average Interest Rates, Interest Expense, Official FX Rates |
| **Recession Signal** | Pre-computed 10Y minus 2Y (2s10s) yield spread with automatic inversion classification |
| **Historical Scope** | Instant daily snapshot or multi-year historical queries spanning thousands of trading days |
| **Throughput & Speed** | Keyless pure-HTTP execution returning 1,000+ records in 3–5 seconds |
| **Data Licensing** | 100% public-domain U.S. government official data; no third-party API keys required |
| **Output Formats** | Clean datasets in JSON, CSV, Excel, XML, HTML, and JSON Lines |
| **Integrations** | Apify REST API, webhooks, Python SDK, Node.js SDK, LangChain, Make, Zapier |

***

### 🔎 Why scrape US Treasury data?

The U.S. Department of the Treasury publishes the benchmark metrics that anchor the entire global financial system: the **par yield curve** that dictates pricing for residential mortgages, municipal bonds, and corporate borrowing; the **national debt** figure that drives federal fiscal policy; and the **official reporting rates of exchange** mandated for U.S. governmental accounting. These numbers are non-negotiable, authoritative references that update every business day. A financial model or AI assistant quoting last quarter's 10-year yield or an outdated national debt figure produces severe miscalculations.

However, gathering this data programmatically presents hurdles. Official statistics are fragmented across separate legacy portals — the FiscalData REST API and the daily CSV rate chart center. Dates use disparate formats (`MM/DD/YYYY` vs. `YYYY-MM-DD`), monetary totals are formatted as unparsed strings, and quarterly exchange rate feeds span 150+ international currencies.

This **US Treasury data scraper** unifies and normalizes the entire ecosystem into a clean, uniform record schema. It retrieves live daily snapshots or backtest-ready multi-year historical series, computes key macroeconomic spreads (such as the 2s10s curve inversion), formats agent-friendly summary sentences, and delivers structured datasets ready for direct analysis.

**Common reasons teams scrape US Treasury data:**

- **Ground AI financial agents** — supply LLM agents and trading bots with authoritative fiscal data to prevent hallucinated rates.
- **Track the 2s10s yield curve inversion** — monitor the classic yield curve recession signal updated each trading day.
- **Analyze federal sovereign debt** — track public debt outstanding and federal interest expense growth over multi-year horizons.
- **Backtesting & quantitative modeling** — pull continuous historical yields across all 14 tenors for bond valuation and duration hedging models.
- **Corporate compliance & statutory accounting** — access official Treasury reporting foreign exchange rates for IRS, customs, and defense contract reporting.
- **Fintech dashboards & macro alerts** — power executive dashboards with real-time interest rates, debt totals, and currency benchmarks.

***

### ✨ What this US Treasury scraper does

- ✅ **Five official datasets in one schema** — combines **Daily Yield Curve**, **National Debt (Debt to the Penny)**, **Average Interest Rates**, **Interest Expense**, and **Official Exchange Rates**.
- ✅ **Latest snapshot or deep history** — toggle `latest: true` for an instantaneous snapshot of today's figures, or supply a `startDate`/`endDate` range to extract complete multi-year historical series.
- ✅ **Complete 14-tenor yield curve** — extracts 1 Mo, 1.5 Month, 2 Mo, 3 Mo, 4 Mo, 6 Mo, 1 Yr, 2 Yr, 3 Yr, 5 Yr, 7 Yr, 10 Yr, 20 Yr, and 30 Yr par yields.
- ✅ **Pre-computed 2s10s spread & inversion flag** — calculates `10Y - 2Y` spread and explicitly labels yield curve inversions in the summary text.
- ✅ **National debt to the penny** — tracks total public debt outstanding down to the exact cent, broken down by public debt vs. intragovernmental holdings.
- ✅ **AI-agent ready text fields** — each record includes a formatted `headline` and full-sentence `summary` for direct RAG ingestion.
- ✅ **150+ currency exchange rates** — filter by major economic regions (`Euro Zone`, `United Kingdom`, `Japan`, `China`) or extract all 150+ world currencies.
- ✅ **Unlocked 1,000+ pagination** — historical queries support 1,000+ to 10,000 records without restrictive sampling caps.
- ✅ **Keyless & zero-token cost** — hits public U.S. government endpoints directly with built-in retries and zero proxy requirements.

***

### 🎯 Use cases & workflows

#### 1. Macroeconomic Grounding for LLMs & AI Agents

Expose this Actor via tool calling or MCP to an AI investment copilot. When a user asks "what is the current US 10-year yield and is the curve inverted?", the agent fetches exact, real-time government figures.

#### 2. Quantitative Fixed-Income Backtesting

Pull historical daily yield curves from 2020 through present to model mortgage-backed security (MBS) prepayments, interest rate swaps, or corporate credit spreads against risk-free sovereign baselines.

#### 3. Federal Fiscal & Debt Tracking Dashboards

Automate a daily Apify schedule that pulls the national debt and monthly interest expense. Feed the output directly into Google Sheets or PowerBI to visualize debt service trajectory.

#### 4. Statutory Foreign Exchange Conversion

Incorporate official quarterly Treasury foreign exchange rates into enterprise ERPs to ensure compliance with federal government contract accounting and defense acquisition regulations.

***

### 📊 Comprehensive Datasets Reference

| Dataset Identifier | Frequency | Key Metrics Extracted | Typical Use Case |
| --- | --- | --- | --- |
| `yield_curve` | Daily (business days) | 14 tenors (1M to 30Y), 10Y-2Y spread, inversion flag | Benchmark risk-free discount curves, recession forecasting |
| `national_debt` | Daily (business days) | Total public debt outstanding, debt held by public, intragovernmental holdings | Sovereign debt tracking, fiscal deficit analysis |
| `interest_rates` | Monthly | Security descriptions (Treasury Bills, Notes, Bonds, TIPS), average interest rates | Federal borrowing cost analysis across maturities |
| `interest_expense` | Monthly | Month expense amount, fiscal year-to-date (FYTD) expense amount | Federal budget deficit and debt servicing burden |
| `exchange_rates` | Quarterly | 150+ official bilateral foreign currency exchange rates per USD | Government accounting, customs valuation, federal contracts |

***

### 📈 Yield Curve Tenors & Maturity Structure Reference

The U.S. Treasury par yield curve represents the theoretical yield on risk-free, coupon-bearing Treasury securities selling at par. The Actor captures all 14 official maturities across three duration categories:

| Tenor Category | Tenor Code | Typical Market Use Case | Sensitivity |
| --- | --- | --- | --- |
| **Short-End (Bills)** | `1 Mo` (4-week) | Fed funds expectations, money market cash management | Ultra-high Fed policy sensitivity |
| **Short-End (Bills)** | `1.5 Month` | Intermediate commercial paper benchmark | Fed policy sensitivity |
| **Short-End (Bills)** | `2 Mo` (8-week) | Short-term liquidity pricing | Fed policy sensitivity |
| **Short-End (Bills)** | `3 Mo` (13-week) | Primary proxy for short-term risk-free rate, SOFR baseline | Fed policy sensitivity |
| **Short-End (Bills)** | `4 Mo` (17-week) | Commercial treasury liquidity management | Fed policy sensitivity |
| **Short-End (Bills)** | `6 Mo` (26-week) | Semi-annual cash flow discounting | Near-term monetary policy expectations |
| **Intermediate (Notes)**| `1 Yr` (52-week) | Corporate revolving credit facilities, ARM mortgage benchmarks | 1-year forward policy path |
| **Intermediate (Notes)**| `2 Yr` | Critical policy rate benchmark; used in 2s10s spread calculation | Fed rate trajectory expectations |
| **Intermediate (Notes)**| `3 Yr` | Medium-term auto loan and personal credit pricing | Medium-term growth expectations |
| **Intermediate (Notes)**| `5 Yr` | Mid-duration corporate bond benchmark, 5-year breakeven inflation | 5-year macroeconomic outlook |
| **Intermediate (Notes)**| `7 Yr` | Intermediate mortgage-backed security duration anchor | Growth and inflation equilibrium |
| **Long-End (Notes/Bonds)**| `10 Yr` | Global risk-free benchmark; 30-year fixed mortgage anchor; 2s10s spread | Long-term growth, term premium, inflation expectations |
| **Long-End (Bonds)** | `20 Yr` | Pension fund liability matching, long-duration balance sheet hedging | Long-term sovereign supply dynamics |
| **Long-End (Bonds)** | `30 Yr` | Ultimate long-term sovereign bond anchor; infrastructure finance | Long-term structural inflation & fiscal sustainability |

***

### 🏛️ Understanding the National Debt Components

The Actor splits the U.S. National Debt into its official statutory classifications:

1. **Total Public Debt Outstanding (`totalDebtOutstanding`)**: The comprehensive legal sovereign debt subject to the statutory debt limit.
2. **Debt Held by the Public (`debtHeldByPublic`)**: All federal debt held by individuals, institutional investors, the Federal Reserve, foreign central banks, and international corporations in the open Treasury secondary market.
3. **Intragovernmental Holdings (`intragovernmentalHoldings`)**: Government Account Series securities held by federal trust funds, revolving funds, and special funds (such as the Social Security Old-Age and Survivors Insurance Trust Fund, Military Retirement Fund, and Medicare trust funds).

***

### 🔄 End-to-End Automation & Webhook Integration

Automate macro intelligence feeds directly into data lakes, trading bots, and executive spreadsheets:

#### Automated Yield Curve Ingestion with Make or n8n

1. **Daily Trigger**: Schedule an Apify run every business day at 5:30 PM EST following the Treasury's daily publication.
2. **Webhook Catch**: Receive the finished run event in Make or n8n.
3. **Parse Spreads**: Extract `headline` and the pre-computed `2s10s` spread.
4. **Recession Alert**: If the 2s10s spread is negative (`< 0.00%`), automatically fire an urgent notification to your Slack or Microsoft Teams trading channel.
5. **Database Archive**: Upsert the daily record into PostgreSQL, BigQuery, or Snowflake for long-term quantitative time-series modeling.

#### Sample CSV Export Structure

When exporting historical records to CSV, the output formats cleanly into standardized columns:

```csv
dataset,recordDate,headline,summary,unit,valuesJson,source,scrapedAt
"yield_curve","2026-11-09","10Y 4.94% · 2Y 4.56% · 3M 4.16% · 2s10s 0.38%","US Treasury par yield curve (2026-11-09): 3M 4.16%, 10Y 4.94%...","percent","{""10 Yr"":""4.94"",""2 Yr"":""4.56""}","US Department of the Treasury","2026-11-10T16:00:00.000Z"
"national_debt","2026-11-06","Total public debt outstanding: $40.59T","US national debt on 2026-11-06: $40.59T total...","USD","{""totalDebtOutstanding"":""40593637262883.48""}","US Department of the Treasury","2026-11-10T16:00:00.000Z"
```

***

### 📥 Input parameters

Configure your run via the Apify Console or pass a JSON payload directly through the API. Every field is optional.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `datasets` | array (multi-select) | `["yield_curve", "national_debt", "interest_rates"]` | Official Treasury datasets to fetch: `yield_curve`, `national_debt`, `interest_rates`, `interest_expense`, `exchange_rates`. |
| `latest` | boolean | `true` | When true, returns the most recent reporting snapshot (finishes in seconds). Set to false for historical ranges. |
| `startDate` | string (date) | `"2024-01-01"` | Historical range start date (`YYYY-MM-DD`). Used when `latest` is false. |
| `endDate` | string (date) | `""` | Historical range end date (`YYYY-MM-DD`). Leave empty for up to today. |
| `maxRecords` | integer | `60` | Maximum records per dataset in historical mode. Set to `0` for unlimited (up to 10,000 records). Supports 1,000+ records. |
| `currency` | string (select) | `""` | Exchange rates filter: select a specific country/currency (e.g. `Euro Zone`, `United Kingdom`, `Japan`) or all countries. |
| `currencyText` | string | `""` | Advanced free-text currency or country search for countries not present in the dropdown. |
| `proxyConfiguration` | object | `{ "useApifyProxy": false }` | Optional Apify Proxy settings (public Treasury endpoints require no proxy by default). |

#### Example input — Current market snapshot (default)

```json
{
  "datasets": ["yield_curve", "national_debt", "interest_rates"],
  "latest": true
}
```

#### Example input — 1,000+ records historical yield curve

```json
{
  "datasets": ["yield_curve"],
  "latest": false,
  "startDate": "2022-01-01",
  "endDate": "2026-11-10",
  "maxRecords": 1500
}
```

#### Example input — Quarterly official FX rates for the Euro

```json
{
  "datasets": ["exchange_rates"],
  "latest": true,
  "currency": "Euro Zone"
}
```

***

### 📤 Output structure

Every record is normalized to a clean, standardized structure regardless of the underlying dataset:

#### Yield curve record example

```json
{
  "dataset": "yield_curve",
  "recordDate": "2026-11-09",
  "headline": "10Y 4.94% · 2Y 4.56% · 3M 4.16% · 2s10s 0.38%",
  "summary": "US Treasury par yield curve (2026-11-09): 3M 4.16%, 1Y 4.36%, 2Y 4.56%, 5Y 4.71%, 10Y 4.94%, 30Y 5.31%. 10Y–2Y spread 0.38% (normal).",
  "valuesJson": "{\"1 Mo\":\"4.06\",\"1.5 Month\":\"4.09\",\"2 Mo\":\"4.16\",\"3 Mo\":\"4.16\",\"4 Mo\":\"4.18\",\"6 Mo\":\"4.25\",\"1 Yr\":\"4.36\",\"2 Yr\":\"4.56\",\"3 Yr\":\"4.65\",\"5 Yr\":\"4.71\",\"7 Yr\":\"4.80\",\"10 Yr\":\"4.94\",\"20 Yr\":\"5.34\",\"30 Yr\":\"5.31\"}",
  "unit": "percent",
  "source": "US Department of the Treasury",
  "scrapedAt": "2026-11-10T16:00:00.000Z"
}
```

#### National debt record example

```json
{
  "dataset": "national_debt",
  "recordDate": "2026-11-06",
  "headline": "Total public debt outstanding: $40.59T",
  "summary": "US national debt on 2026-11-06: $40.59T total — $32.71T held by the public, $7.88T intragovernmental.",
  "valuesJson": "{\"totalDebtOutstanding\":\"40593637262883.48\",\"debtHeldByPublic\":\"32712190190967.42\",\"intragovernmentalHoldings\":\"7881447071916.06\"}",
  "unit": "USD",
  "source": "US Department of the Treasury",
  "scrapedAt": "2026-11-10T16:00:00.000Z"
}
```

***

### 📊 Extracted fields & data coverage

| Field | Coverage | Type | Description |
| --- | --- | --- | --- |
| 🏷️ `dataset` | 🟢 High (100%) | String | Dataset source identifier (`yield_curve`, `national_debt`, etc.) |
| 📅 `recordDate` | 🟢 High (100%) | String | Effective date normalized to `YYYY-MM-DD` |
| 📰 `headline` | 🟢 High (100%) | String | Formatted executive highlight metric (e.g., benchmark yields or debt total) |
| 📝 `summary` | 🟢 High (100%) | String | Human and AI-agent readable sentence detailing the record |
| 📦 `valuesJson` | 🟢 High (100%) | String | Complete numeric payload serialized as JSON string |
| 📏 `unit` | 🟢 High (100%) | String | Measurement denomination (`percent`, `USD`, `per USD`) |
| 🏛️ `source` | 🟢 High (100%) | String | Authoritative issuing institution (`US Department of the Treasury`) |
| ⏰ `scrapedAt` | 🟢 High (100%) | String | ISO 8601 UTC timestamp of extraction execution |

***

### 🔁 Scale & 1,000+ historical pagination

The Treasury's FiscalData API and yield curve portals support rapid bulk ingestion. This Actor unlocks deep historical queries without artificial constraints:

- **1,000+ to 10,000 records per dataset**: By setting `maxRecords: 1000` or `maxRecords: 0`, users can extract complete multi-year histories of daily rates.
- **Removed 100-record clamp**: Explicit user requests above 100 are strictly honored directly at the API query level.
- **Streaming dataset push**: Records are pushed to the Apify dataset in batches of 100, maintaining constant memory overhead during massive historical extractions.
- **Sub-5 second performance**: High-speed HTTP ingestion returns thousands of records in mere seconds.

***

### 💻 Developer integration & code samples

#### Python SDK

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_APIFY_TOKEN")

run_input = {
    "datasets": ["yield_curve", "national_debt"],
    "latest": True
}

run = client.actor("haketa/treasury-data").call(run_input=run_input)

for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(f"[{item['dataset']}] {item['recordDate']}: {item['headline']}")
```

#### Node.js SDK

```javascript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_APIFY_TOKEN' });

const run = await client.actor('haketa/treasury-data').call({
    datasets: ['yield_curve'],
    latest: false,
    startDate: '2024-01-01',
    maxRecords: 250,
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.table(items.map(i => ({ date: i.recordDate, headline: i.headline, unit: i.unit })));
```

#### cURL API

```bash
curl -X POST "https://api.apify.com/v2/acts/haketa~treasury-data/runs?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "datasets": ["yield_curve", "national_debt"],
    "latest": true
  }'
```

***

### 💡 Practical tips for financial analysis

1. **Monitor the 2s10s spread**: A negative spread indicates an inverted yield curve, which has historically preceded every modern U.S. economic recession.
2. **Combine with SEC EDGAR**: Pair sovereign yield curves with corporate 10-K and 10-Q filings from [SEC EDGAR Scraper](https://apify.com/haketa/sec-edgar-scraper) to evaluate corporate debt refinancing risk against prevailing Treasury rates.
3. **Use `valuesJson` for calculations**: Parse `valuesJson` directly in Python or JavaScript to extract individual tenors (e.g. `item['valuesJson']['10 Yr']`) for quantitative charts.
4. **Schedule automated daily runs**: Set up an Apify schedule for 5:00 PM EST on weekdays to capture new daily Treasury yield curves as soon as the market closes.

***

### ❓ Frequently Asked Questions

**Are these live market quotes from secondary trading desks?**\
No. These are official end-of-day Treasury par yields and accounting figures published by the U.S. Department of the Treasury. They represent the authoritative benchmark for regulatory, compliance, and academic purposes.

**Are private API keys required?**\
No. The U.S. Treasury publishes this data as public-domain government records. The Actor accesses endpoints keylessly without private subscriptions.

**Can I export historical data across multiple years?**\
Yes. Turn off `latest: true`, provide a `startDate` such as `2020-01-01`, and set `maxRecords: 1500` or `0` for unlimited history.

**What formats can I download?**\
Datasets can be downloaded in JSON, CSV, Excel, XML, HTML, or JSON Lines via the Apify Console or API.

**How does the currency filter work?**\
The exchange rates dataset tracks over 150 currencies. Selecting a country from the dropdown isolates that currency; choosing "All countries" outputs the complete global table.

**Can an LLM or AI agent call this via tool use or LangChain?**\
Yes. Because the Actor accepts a clean JSON input and returns structured dataset records with pre-formatted headline and summary fields, it integrates seamlessly as an autonomous tool for LangChain, LlamaIndex, AutoGen, or MCP-compatible AI frameworks.

**What is the difference between Par Yields and Constant Maturity Treasury (CMT) rates?**\
The Daily Treasury Par Yield Curve rates are based on the closing market bid prices on actively traded Treasury securities in the over-the-counter market, derived using a quasi-cubic Hermite spline algorithm. These represent the official par rates for coupon-bearing bonds.

**Is there any rate limiting on requests?**\
The underlying U.S. government endpoints are public-domain and designed for high-availability access. The Actor includes automated backoff retries to guarantee dependable data extraction even during periods of heavy market volatility.

***

### 🔗 Related financial & regulatory scrapers

- [SEC EDGAR Scraper](https://apify.com/haketa/sec-edgar-scraper) — extract company filings, 10-K, 10-Q, and executive transactions.
- [GLEIF LEI Lookup](https://apify.com/haketa/gleif-lei) — verify corporate legal entity identifiers and global ownership structures.
- [AML & Sanctions Screening](https://apify.com/haketa/sanctions-screening) — screen counterparties against OFAC, EU, UN, and UK watchlists.
- [Bulk Tech Detector](https://apify.com/haketa/bulk-tech-detector) — detect website software stacks and technographics in bulk.

***

### 📋 Changelog

#### v1.2 (2026-11)

- **Unlocked 1,000+ deep pagination**: removed restrictive `Math.min` clamp on explicit `maxRecords > 100`, allowing comprehensive multi-year historical extractions.
- **Supported `maxRecords: 0`**: setting `maxRecords` to `0` now returns complete available series up to the Treasury API limit of 10,000 rows.
- **Streaming dataset push**: implemented chunked dataset writing in batches of 100 records for optimal memory efficiency.
- **Expanded documentation**: added visual badges, `⚡ At a glance` quick reference, and detailed Python/Node.js SDK snippets.

#### v1.1 (2026-07)

- Unified FiscalData API endpoints with Daily Treasury Yield Curve CSV ingestion.
- Added pre-computed 2s10s spread and curve inversion indicator.

#### v1.0 (2026-06)

- Initial release with keyless public-domain Treasury extraction.

# Changelog

This Actor's version history is a separate document: https://apify.com/haketa/treasury-data/changelog.md

# Actor input Schema

## `datasets` (type: `array`):

Pick the official Treasury datasets you want. Choose one or many — results are combined into a single, clean output.

## `latest` (type: `boolean`):

Keep this on for the most recent snapshot (fast). Turn it off to pull a historical date range.

## `startDate` (type: `string`):

Only used when "Latest values only" is off. Beginning of the date range, e.g. 2024-01-01.

## `endDate` (type: `string`):

Only used when "Latest values only" is off. End of the date range, e.g. 2024-12-31. Leave empty for up to today.

## `maxRecords` (type: `integer`):

Limit how many records each dataset returns when fetching history. Set to 0 or leave empty for unlimited (up to API cap of 10,000 records). Supports 1,000+ records.

## `currency` (type: `string`):

For the Official Exchange Rates dataset only. Pick a country to see just its rate against the US Dollar, or leave on "All countries".

## `currencyText` (type: `string`):

Optional. Not in the list above? Type any country or currency name (e.g. "Kenya", "Ariary"). Used only if the dropdown is set to "All countries".

## `proxyConfiguration` (type: `object`):

Apify Proxy settings. The Treasury sources are public, so a proxy is OFF by default.

## Actor input object example

```json
{
  "datasets": [
    "yield_curve",
    "national_debt",
    "interest_rates"
  ],
  "latest": true,
  "startDate": "2024-01-01",
  "maxRecords": 60,
  "currency": "",
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `dataset` (type: `string`):

Which dataset

## `recordDate` (type: `string`):

Record date

## `headline` (type: `string`):

Key figure(s)

## `summary` (type: `string`):

Human-readable summary

## `valuesJson` (type: `string`):

All metrics for this record as JSON

## `unit` (type: `string`):

Unit of the values

## `source` (type: `string`):

Source dataset name

## `scrapedAt` (type: `string`):

Timestamp

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "datasets": [
        "yield_curve",
        "national_debt",
        "interest_rates"
    ],
    "startDate": "2024-01-01",
    "maxRecords": 60
};

// Run the Actor and wait for it to finish
const run = await client.actor("haketa/treasury-data").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "datasets": [
        "yield_curve",
        "national_debt",
        "interest_rates",
    ],
    "startDate": "2024-01-01",
    "maxRecords": 60,
}

# Run the Actor and wait for it to finish
run = client.actor("haketa/treasury-data").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "datasets": [
    "yield_curve",
    "national_debt",
    "interest_rates"
  ],
  "startDate": "2024-01-01",
  "maxRecords": 60
}' |
apify call haketa/treasury-data --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,haketa/treasury-data"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Ggaga6UY3O4pNy6qZ/builds/g6dWnxpllHMPdBGpz/openapi.json
