# Us Treasury Fiscal Data Scraper (`b2b_lead_generation/us-treasury-fiscal-data-scraper`) Actor

Extract official US Treasury debt totals and exchange rates effortlessly. Filter records by date, handle errors smoothly, and instantly export complete fiscal archives to JSON, CSV, or Excel datasets for reliable financial research and tracking.

- **URL**: https://apify.com/b2b_lead_generation/us-treasury-fiscal-data-scraper.md
- **Developed by:** [B2B Lead Generation](https://apify.com/b2b_lead_generation) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.99 / 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 Fiscal Data Scraper

<p align="center">
  <img src="https://imgur.com/SMfHr4x.png" alt="Uk Parliament Members" style="max-width:100%; border-radius:14px; width:680px;" />
</p>

An efficient tool designed to pull historical financial tracking records, national debt breakdowns, and foreign exchange rates, saving them directly into a clean dataset ready for export to JSON, CSV, or Excel.

***

### What Data Does It Extract?

This tool focuses on core macroeconomic metrics, structured neatly for analysis:

- **Debt Tracking**: Comprehensive daily national debt figures, including breakdowns of debt held by the public and intragovernmental holdings.
- **Exchange Rates**: Official currency conversion rates organized by country, currency, and effective date.

***

### Key Use Cases

- **Debt Archiving**: Maintain a consistent, long-term archive of daily national debt figures.
- **FX Reference**: Quickly export exchange rate tables by country and currency for specific date ranges.
- **Scheduled Runs**: Set automated runs to keep your financial datasets updated over time.
- **Research & Analysis**: Download clean CSV or Excel files instantly without dealing with manual pagination or data formatting headaches.
- **Pipeline Monitoring**: Capture unexpected response codes or invalid filters as separate error rows so you can track run health easily.

***

### Input Configuration

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | string | `dataset` | Selects the mode for pulling rows into your dataset. |
| `endpoint` | string | `debt_to_penny` | Choose between debt tracking records and exchange rates. |
| `filter` | string | `empty` | Custom record date filters (e.g., `record_date:gte:2025-01-01`). |
| `sort` | string | `-record_date` | Sorting expression. A leading minus sign sorts in descending order. |
| `maxItems` | integer | `100` | Row cap for a single run (hard maximum of 1000). |
| `timeoutSecs` | integer | `300` | Stops the run after this many seconds. |
| `requestTimeoutSecs` | integer | `30` | Timeout limit per individual request before retrying. |

***

### Output Structure

Successful runs populate your dataset with structured fields containing the requested records, timestamps, and source tracking URLs. If a specific request encounters an issue, an error row is logged so the rest of your run continues smoothly without interruption.

```json
{
    "record_date": "2026-10-08",
    "debt_held_public_amt": "32454086117711.32",
    "intragov_hold_amt": "7851230093118.40",
    "tot_pub_debt_out_amt": "40305316210829.72",
    "src_line_nbr": "1",
    "record_fiscal_year": "2027",
    "record_fiscal_quarter": "1",
    "record_calendar_year": "2026",
    "record_calendar_quarter": "4",
    "record_calendar_month": "10",
    "record_calendar_day": "08",
    "scrapedAt": "2026-10-12T00:00:00+00:00",
    "sourceUrl": "https://example.com/source-record"
}

```

***

### Reliability & Limits

- **Smart Pagination**: The tool requests data in manageable page sizes, automatically walking through pages until your row cap or the end of the series is reached.
- **Automatic Retries**: Temporary connection drops or rate-limiting responses are automatically retried with smart backoff intervals.
- **Duplicate Prevention**: Duplicate entries (matching dates, lines, or currencies) are automatically filtered out in memory to keep your final dataset clean.

***

### Frequently Asked Questions

- **How many rows can a single run save?**
  The row cap defaults to 100 and can be adjusted up to 1000 items per run.
- **Can I schedule automated exports?**
  Yes, you can set recurring schedules on your platform and download the resulting dataset as JSON, CSV, or Excel whenever needed.
- **What happens if my filter is incorrect?**
  The tool records a clear error row with the status snippet and continues running rather than crashing the entire job.

***

### Is Web Scraping Legal?

Collecting publicly available data is a common practice for research, reporting, and data analysis, but how you handle and use the data matters:

- **Personal Data**: Ensure compliance with local privacy regulations (such as GDPR or CCPA) if any personal information is ever captured in your datasets.
- **Copyright**: Respect intellectual property rights and do not republish copyrighted content without explicit permission.
- **Terms of Use**: Always adhere to reasonable usage limits and respect the terms provided by data publishers.
- **Disclaimer**: This tool is an independent utility. Users are solely responsible for ensuring their data collection and usage comply with all applicable regulations and terms of service.

# Actor input Schema

## `mode` (type: `string`):

Pull rows from one verified Fiscal Data API dataset.

## `endpoint` (type: `string`):

Verified path only: v2/accounting/od/debt_to_penny or v1/accounting/od/rates_of_exchange. A full Fiscal Data URL for one of those paths is accepted.

## `filter` (type: `string`):

Optional Fiscal Data filter, for example record_date:gte:2025-01-01. Leave empty to take the newest rows.

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

Sort expression passed to the API. Prefix a field with a minus sign for descending order. Default is newest record_date first.

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

Maximum dataset rows to save in one run. Values above 1000 are clamped to 1000.

## `timeoutSecs` (type: `integer`):

Stop the run after this many seconds and keep rows already saved.

## `requestTimeoutSecs` (type: `integer`):

How long to wait for a single Fiscal Data HTTP response before retrying.

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

Optional proxy settings. Default is no proxy. Turn on Apify Proxy or add your own proxy URLs only if you need them.

## Actor input object example

```json
{
  "mode": "dataset",
  "endpoint": "v2/accounting/od/debt_to_penny",
  "sort": "-record_date",
  "maxItems": 100,
  "timeoutSecs": 300,
  "requestTimeoutSecs": 30,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `datasetUrl` (type: `string`):

Default dataset with fiscal rows from this run.

## `datasetItemsUrl` (type: `string`):

JSON items in the default dataset.

# 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 = {
    "endpoint": "v2/accounting/od/debt_to_penny",
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("b2b_lead_generation/us-treasury-fiscal-data-scraper").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 = {
    "endpoint": "v2/accounting/od/debt_to_penny",
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("b2b_lead_generation/us-treasury-fiscal-data-scraper").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 '{
  "endpoint": "v2/accounting/od/debt_to_penny",
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call b2b_lead_generation/us-treasury-fiscal-data-scraper --silent --output-dataset

```

## MCP server setup

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

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/7ByVkTIcVIdcPkETi/builds/AnTrj8bdnrresInMH/openapi.json
