# US Public Debt & Treasury Interest Rate History (`grit-77/us-treasury-debt`) Actor

US Treasury Fiscal Data scraper for Debt to the Penny and Average Interest Rates. Filter dates and export accounting series as JSON with exact debt amounts, units and source links.

- **URL**: https://apify.com/grit-77/us-treasury-debt.md
- **Developed by:** [Grit](https://apify.com/grit-77) (community)
- **Categories:** Business, News
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$0.50 / 1,000 datapoints

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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 Public Debt & Treasury Interest Rate History

Retrieve dated US public-debt totals and average Treasury security interest rates from the official Fiscal Data API, with exact debt amounts, units and source links.

Choose **Debt to the Penny** or **Average Interest Rates**, filter by date, sort the records and page through history. This actor is for Treasury accounting series. `usaspending-awards` concerns award recipients; `world-bank-indicators` concerns World Bank indicators. This actor returns neither of those, and does not collect exchange rates, recipient records or individual records.

### Official sources

- [Debt to the Penny](https://fiscaldata.treasury.gov/datasets/debt-to-the-penny/): `/v2/accounting/od/debt_to_penny`.
- [Average Interest Rates on U.S. Treasury Securities](https://fiscaldata.treasury.gov/datasets/average-interest-rates-treasury-securities/): `/v2/accounting/od/avg_interest_rates`.

The API host is `https://api.fiscaldata.treasury.gov/services/api/fiscal_service`. These are the two supported endpoints; there is no custom URL or endpoint input. No source API key is required.

### What it returns

Each successful row represents one dated debt observation or one dated security-category rate. Dataset rows are available through the Actor's **Results** link and can be exported with Apify's dataset tools.

| Field | Type | Meaning |
|---|---|---|
| `status` | string | `ok` or `error` |
| `dataset` | string | `debt_to_penny` or `avg_interest_rates` |
| `recordDate` | string | Treasury's observation date, `YYYY-MM-DD` |
| `totalPublicDebt` | string | Total public debt outstanding, exact USD decimal; debt rows |
| `debtHeldByPublic` | string | Debt held by the public, exact USD decimal; debt rows |
| `intragovernmentalHoldings` | string | Intragovernmental holdings, exact USD decimal; debt rows |
| `averageInterestRate` | number | Reported percentage, such as `7.577`; rate rows |
| `securityType` | string | Treasury security type, such as `Non-marketable`; rate rows |
| `securityDescription` | string | Treasury security category, such as `Domestic Series`; rate rows |
| `units` | string | `USD` for debt or `percent` for rates |
| `sourceEndpoint` | string | Full official endpoint URL |
| `sourceUrl` | string | Official request URL including filters, sort and pagination |
| `retrievedAt` | string | UTC retrieval timestamp |
| `errorCode` | string | Error rows: `invalid_record`, `request_failed` or `invalid_response` |
| `error` | string | Error detail, without an untrusted response body |
| `pageNumber` | integer | Error rows: API page containing the failure |

Debt amounts stay as decimal strings to preserve cents for these large totals. Rate numbers are percentages: `7.577` means **7.577%**, not a fractional value of `0.07577`. Fields for the other series are absent. Error rows can omit `recordDate` and value fields.

### Input examples

The exact prefilled input is:

```json
{"dataset":"debt_to_penny","sort":"-record_date","maxItems":5}
```

It requests `page[size]=5` and starts at page one. An empty input object uses these defaults.

Historical category rates:

```json
{
  "dataset": "avg_interest_rates",
  "startDate": "2026-01-01",
  "endDate": "2026-08-31",
  "securityType": "Marketable",
  "securityDescription": "Treasury Bills",
  "sort": "record_date",
  "pageSize": 5,
  "pageNumber": 1,
  "maxItems": 20
}
```

| Input | Default | Behavior |
|---|---|---|
| `dataset` | `debt_to_penny` | Selects one supported Treasury series |
| `startDate`, `endDate` | No bounds | Inclusive `record_date` filters; optional `YYYY-MM-DD` dates |
| `sort` | `-record_date` | API fields separated by commas; `-` means descending |
| `maxItems` | `5` | Maximum dataset rows in this run, including errors; integer 1–100,000 |
| `pageSize` | `5` | API rows per page; integer 1–1,000, capped to `maxItems` once |
| `pageNumber` | `1` | One-based starting page after filters and sort; integer 1–1,000,000 |
| `securityType` | No filter | Exact `security_type_desc`, rates only |
| `securityDescription` | No filter | Exact `security_desc`, rates only |

Sort fields: `record_date` for either series; debt also permits `tot_pub_debt_out_amt`, `debt_held_public_amt` and `intragov_hold_amt`; rates also permit `security_desc`, `security_type_desc` and `avg_interest_rate_amt`. Date and security fields are appended as stable tie-breaks when absent. Page size stays fixed across pages, including the final page. To continue a paginated export, keep the same filters, sort and effective page size. Category filters are exact source labels and apply only to the rates dataset.

### Real output examples

This debt row was produced by the local prefill run on 2026-10-06. The complete five-row output is in `sample_output.json`.

```json
{
  "dataset": "debt_to_penny",
  "sourceEndpoint": "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny",
  "sourceUrl": "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny?sort=-record_date&page%5Bsize%5D=5&page%5Bnumber%5D=1",
  "retrievedAt": "2026-10-06T08:30:33.306907+00:00",
  "units": "USD",
  "status": "ok",
  "recordDate": "2026-10-02",
  "totalPublicDebt": "40242446619209.33",
  "debtHeldByPublic": "32428913787327.44",
  "intragovernmentalHoldings": "7813532831881.89"
}
```

The separate local rates run produced this observation (selected fields; full row in `evidence/behavior-results.json`):

```json
{
  "dataset": "avg_interest_rates",
  "status": "ok",
  "recordDate": "2026-08-31",
  "securityType": "Non-marketable",
  "securityDescription": "Domestic Series",
  "averageInterestRate": 7.577,
  "units": "percent"
}
```

### Pricing

Proposed event: **`datapoint` at 0.0005 USD per successful saved observation** (0.50 USD for 1,000 custom events). Error rows and empty results do not trigger this event. The SDK spending limit stops further results when the custom event budget is exhausted. Platform costs depend on the published pricing configuration.

The observed comparable Store leader, [fortuitous_pirate/treasury-fiscal-scraper](https://apify.com/fortuitous_pirate/treasury-fiscal-scraper), lists 0.00365 USD per result plus a 0.05 USD startup event in the 2026-10-06 API snapshot. It is tied for most total users and leads those ties by total runs. See `PRICING.md` for the ranking, other prices, exact event proposal and receipts. Pricing is a proposal until the owner activates monetization.

### Limits and errors

Requests run serially, with one connection. Each request has a 30-second timeout and up to three attempts for network failures, HTTP 429 and server errors, using bounded backoff. Other HTTP failures return a source-linked error row. A malformed observation becomes an uncharged error row while subsequent records continue; a failed page returns an error row and stops that series. An empty date range produces no rows. Invalid inputs fail with a clear message before requesting data.

Output reflects records available from Treasury at run time. Publication delays and source revisions can change the latest available date or historical values. Average interest rates are Treasury accounting category averages, not daily market yield curves. No currency conversion, award-recipient enrichment or individual-level records are provided.

### Use with AI agents / MCP

An AI agent can invoke the published Actor through Apify's MCP server or Actor API, pass the JSON input above, then read the dataset through the Results link. Give the agent the two allowed dataset values, a date range and a small `maxItems` cap. Preserve `recordDate`, `units`, `sourceEndpoint` and `sourceUrl` in any answer so the observation can be checked. This repository supplies an Actor; it does not run a separate MCP server.

### FAQ

**Why are debt amounts strings?** The values are large; keeping the decimal text avoids losing cents through floating-point conversion. Use a decimal-aware tool when calculating with them.

**Why can several rows have the same date?** The rates series has one observation per Treasury security category on a record date. Stable category sorting makes pagination predictable.

**Why is the latest rate older than today's date?** The actor returns Treasury's published `record_date`, not a fabricated current observation. Check the source link and retrieval timestamp.

**Can I fetch exchange rates or spending recipients?** The supported sources are limited to Debt to the Penny and Average Interest Rates. There is no recipient, individual, exchange-rate or custom endpoint option.

**Are local runs charged?** The local SDK ignores charging without an active pay-per-event model. Configure the `datapoint` event before publishing. Actual paid billing and cloud execution have not been tested here.

### Local development and verification

Dependencies are listed in `requirements.txt`. The designated project environment already contains them; no packages were installed into it.

From the actor directory in PowerShell, place the desired input in `storage/key_value_stores/default/INPUT.json`, then run:

```powershell
$env:APIFY_LOCAL_STORAGE_DIR = "$PWD/storage"
& C:/GritWork/earn/.venv/Scripts/python.exe -m src
& C:/GritWork/earn/.venv/Scripts/python.exe -m pytest -q -p no:cacheprovider
apify validate-schema
```

Tests include real-response fixtures and `@pytest.mark.live` smoke tests for both endpoints. Recorded result: **37 passed in 2.87s** on 2026-10-06 (`evidence/tests-final.log`). The prefill saved **5 rows**; a fresh repeat took **2.3561 seconds** locally (`evidence/behavior-results.json`). These are local observations, not performance guarantees.

Input and dataset schemas passed `apify validate-schema` in this actor directory. Apify CLI 1.10.0 does not discover the required `outputSchema` key; the same output file also passed the CLI through the compatibility descriptor in `evidence/schema-validation`. No Docker build, cloud run or publication was performed.

# Actor input Schema

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

Debt to the Penny returns daily accounting totals. Average Interest Rates returns dated averages by Treasury security category.

## `sort` (type: `string`):

Comma-separated API fields; prefix - for descending. Common: record_date. Debt: tot_pub_debt_out_amt, debt_held_public_amt, intragov_hold_amt. Rates: security_desc, security_type_desc, avg_interest_rate_amt. Stable tie-break fields are appended.

## `maxItems` (type: `integer`):

Cap for this run, including error rows. Only successful datapoints are charged.

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

Optional YYYY-MM-DD lower bound for record_date. Leave blank for no lower bound.

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

Optional YYYY-MM-DD upper bound for record_date. Leave blank for no upper bound.

## `pageSize` (type: `integer`):

Rows per API page (1-1000). Capped to maxItems once at run start; the size stays fixed across pages. Prefill requests page\[size]=5.

## `pageNumber` (type: `integer`):

One-based API page to begin at. Applies after date/category filters and sorting, using the effective page size.

## `securityType` (type: `string`):

Optional exact security_type_desc label, such as Marketable. Only supported for avg_interest_rates. Blank includes all categories.

## `securityDescription` (type: `string`):

Optional exact security_desc label, such as Treasury Bills or Treasury Notes. Only supported for avg_interest_rates.

## Actor input object example

```json
{
  "dataset": "debt_to_penny",
  "sort": "-record_date",
  "maxItems": 5,
  "pageSize": 5,
  "pageNumber": 1
}
```

# Actor output Schema

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

Dataset containing source-linked Treasury accounting datapoints and uncharged error rows.

# 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 = {
    "dataset": "debt_to_penny",
    "sort": "-record_date",
    "maxItems": 5
};

// Run the Actor and wait for it to finish
const run = await client.actor("grit-77/us-treasury-debt").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 = {
    "dataset": "debt_to_penny",
    "sort": "-record_date",
    "maxItems": 5,
}

# Run the Actor and wait for it to finish
run = client.actor("grit-77/us-treasury-debt").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 '{
  "dataset": "debt_to_penny",
  "sort": "-record_date",
  "maxItems": 5
}' |
apify call grit-77/us-treasury-debt --silent --output-dataset

```

## MCP server setup

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

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/gzQqq9x9kViFGlFfB/builds/ZgRHqL2JlxyDZA5mH/openapi.json
