# Brazil Treasury Bonds API (Tesouro Direto) (`br_data_hub/br-tesouro-direto`) Actor

Daily rates and unit prices of Brazilian Treasury bonds (Tesouro Direto: Selic, Prefixado, IPCA+, Renda+, Educa+) from the Brazilian Treasury's open data, clean and typed, with days to maturity, on-sale flag and 1-day and 30-day rate changes.

- **URL**: https://apify.com/br_data_hub/br-tesouro-direto.md
- **Developed by:** [br_data_hub](https://apify.com/br_data_hub) (community)
- **Categories:** Business, AI, Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.70 / 1,000 bond rates

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

## Brazil Treasury Bonds API (Tesouro Direto)

Daily **rates and unit prices of Brazilian Treasury bonds** sold to individuals through **Tesouro Direto**: Tesouro Selic, Prefixado, Prefixado com Juros Semestrais, IPCA+, IPCA+ com Juros Semestrais, Renda+ and Educa+ (plus the retired IGP-M+). Data comes from the official open data of the Brazilian National Treasury (Tesouro Transparente).

The official CSV uses comma decimals, `dd/mm/yyyy` dates, blanks and zeros for bonds that are not for sale, and is not sorted. This Actor returns **clean, typed JSON**, one row per bond and date, with extra fields ready for dashboards, spreadsheets and AI agents:

- days to maturity
- whether the bond is still on sale today
- change of the buy and sell rate against the previous day and against 30 days before
- a **latest day** mode: one row per bond with today's rates, in a few seconds

> This Actor is independent. It is **not affiliated with, endorsed by or operated by** the Brazilian National Treasury (Tesouro Nacional), the Tesouro Direto program or B3. It only reads the Treasury's public open data.

### Input

| Field | Description |
|---|---|
| `latestOnly` | Default `true`: only the most recent date in the official file, one row per bond. Turn off to get a history. |
| `bondTypes` | Bond families: `selic`, `prefixado`, `prefixado-juros-semestrais`, `ipca`, `ipca-juros-semestrais`, `igpm-juros-semestrais`, `renda`, `educa`. Empty for all. |
| `maturities` | Maturity years (`2035`) or exact dates (`2035-05-15`). Empty for all. |
| `dateFrom`, `dateTo` | Base date range (`YYYY-MM-DD`) when `latestOnly` is off. Defaults: the last 30 days up to today. The file goes back to 2002. |
| `maxItems` | Stop after this many rows. |

Examples:

```json
{ "latestOnly": true, "bondTypes": ["ipca", "renda"] }
```

```json
{ "latestOnly": false, "bondTypes": ["prefixado"], "maturities": ["2029"], "dateFrom": "2025-01-01", "dateTo": "2026-10-29" }
```

### Output

```json
{
  "bondId": "ipca-juros-semestrais-2035-05-15",
  "bondType": "Tesouro IPCA+ com Juros Semestrais",
  "bondTypeCode": "ipca-juros-semestrais",
  "sourceName": "Tesouro IPCA+ com Juros Semestrais",
  "maturityDate": "2035-05-15",
  "date": "2026-10-29",
  "buyRate": 7.46,
  "sellRate": 7.58,
  "buyPrice": 4199.8,
  "sellPrice": 4159.7,
  "basePrice": 4159.02,
  "daysToMaturity": 3120,
  "onSale": true,
  "previousDate": "2026-10-28",
  "buyRateChange1d": 0.06,
  "sellRateChange1d": 0.06,
  "date30dAgo": "2026-09-29",
  "buyRateChange30d": -0.06,
  "sellRateChange30d": -0.06,
  "sellPriceChange30dPct": 0.4625,
  "latestDateInSource": "2026-10-29",
  "liveData": true
}
```

- `buyRate` / `sellRate`: annual rate in % (for Tesouro Selic, the spread over Selic). `buyRate` is the rate an investor gets when buying; `sellRate` when selling back to the Treasury.
- `buyPrice` / `sellPrice` / `basePrice`: unit prices (PU) in BRL, morning quote. `buyPrice` and `buyRate` are `null` when the bond was not for sale that day.
- `buyRateChange1d`, `sellRateChange1d`: change in percentage points against the previous date in the series. `*Change30d`: against the last quote on or before 30 calendar days earlier (`null` when the series has a gap).
- `onSale`: the bond is quoted for purchase on the latest date of the file.
- `daysToMaturity`: calendar days from `date` to `maturityDate`.
- `liveData`: `true` when the file was downloaded from the portal in this run, `false` when the portal was unreachable and the copy bundled with the Actor was used (see `latestDateInSource`).

The run's `OUTPUT` record has the number of rows, the latest date in the file, the source URL and the license reported by the portal.

### How much does it cost?

Pay per event, nothing else (no usage-based fees): one `rate` event, **US$ 0.001**, per bond × date row returned (US$ 1 per 1,000 rows). The default run (latest day, all bonds, about 30 to 45 rows) costs about US$ 0.03 to 0.05. Failed runs, invalid inputs and runs with no rows are free. Use `maxItems`, or a maximum charge per run, to cap a run: the Actor stops when it is reached.

Every run downloads and scans the whole official file (about 300,000 rows), estimated at 20 to 30 s with 256 MB, so the compute is shared by all rows of a run.

Comparable Actors on the Store charge US$ 0.00005 to US$ 0.011 per result for Central Bank series (Selic, PTAX, IPCA; most at US$ 0.0005 to US$ 0.001) and US$ 0.02 per event for Treasury auction monitoring. We found no Actor for Tesouro Direto bond rates and prices.

**$0.001 per bond rate** (`rate` event, pay per event). Charged once per bond × date row returned. Failed runs and invalid inputs are free.

| You get | Free tier | Bronze tier (10% off) | Gold tier (30% off) |
|---|---|---|---|
| 100 bond rates | $0.10 | $0.09 | $0.07 |
| 1,000 bond rates | $1.00 | $0.90 | $0.70 |
| 10,000 bond rates | $10.00 | $9.00 | $7.00 |

Discounts follow your Apify subscription tier: Bronze 10%, Silver 20%, Gold and above 30%. No subscription to this Actor and no charge for platform usage: you pay only for results.
The Apify Free plan includes $5 of monthly credit, enough for about **5,000 bond rates** at the list price.
You can cap the cost of any run with **Maximum cost per run**; the Actor stops when it is reached.

### Data source

- Dataset **"Taxas dos Títulos Ofertados pelo Tesouro Direto"** on [Tesouro Transparente](https://www.tesourotransparente.gov.br/ckan/dataset/taxas-dos-titulos-ofertados-pelo-tesouro-direto), the open data portal of the Brazilian National Treasury (Secretaria do Tesouro Nacional). File `PrecoTaxaTesouroDireto.csv`, resolved through the portal's CKAN API on every run.
- Published as open data under Brazil's Open Data Policy (Decree 8,777/2016) and Access to Information Law (Law 12,527/2011). Please credit **"Fonte: Tesouro Nacional / Tesouro Transparente"** when you republish the data.
- Morning quotes only, as published; the file is usually updated once per business day. Rates and prices are as published by the Treasury; this Actor only cleans and enriches them. It is not investment advice.
- No personal data: the dataset contains only bond rates and prices.
- If the portal is unreachable (it may block requests from outside Brazil), the Actor falls back to a copy of the file bundled in its image, when one is present, and marks every row with `liveData: false`. Without a copy, the run fails with a clear message and nothing is charged. To refresh the copy before a build: `curl -L <CSV URL> | gzip -9 > data/PrecoTaxaTesouroDireto.csv.gz`.

### More questions

#### How fresh is the data?

As fresh as the Treasury's file. Every run downloads the official CSV again, and the file is usually updated once per business day with the morning quotes. `latestDateInSource` in every row (and in the `OUTPUT` record) tells you the most recent date the file had at run time.

#### Does it have intraday or afternoon prices?

No. The official file has only the morning quote of each business day (rates and unit prices), and that is what the Actor returns.

#### How far back does the history go?

To 2002, which is where the official file starts. Turn off `latestOnly` and set `dateFrom` and `dateTo`. There is no maximum range: a full history of all bonds is a few hundred thousand rows, so use `bondTypes`, `maturities` or `maxItems` to keep a run small.

#### How do I get one specific bond, such as Tesouro IPCA+ 2035?

Combine the bond family with the maturity: `{"bondTypes": ["ipca"], "maturities": ["2035"]}`. A maturity can be a year (`2035`, all maturities in that year) or an exact date (`2035-05-15`). Each row also has a stable `bondId`, like `ipca-2035-05-15`, for joins.

#### Why is `buyPrice` empty for some bonds?

The Treasury publishes no buy rate or price for bonds that are not for sale that day; the file has zero or a blank there. The Actor turns both into `null` and keeps the sell (buy-back) rate and price. `onSale` tells you whether the bond is offered for purchase on the latest date in the file.

#### What does `buyRate` mean for Tesouro Selic?

For Tesouro Selic the rate is the spread over the Selic rate, as published by the Treasury, not the full annual yield. For Prefixado it is the fixed annual rate, and for IPCA+, Renda+ and Educa+ it is the real rate on top of inflation.

#### Older files call the bonds LTN, LFT and NTN-B. Is that handled?

Yes. The Actor maps the official names and the legacy acronyms (LFT, LTN, NTN-F, NTN-B, NTN-B Principal, NTN-C) to the same `bondTypeCode`, so a history crosses the change of names without gaps. `sourceName` keeps the name exactly as it appears in the file.

#### What if the portal does not answer?

The Actor tries the download up to 4 times. If it still fails, it uses the copy of the file bundled with the Actor when there is one, and marks every row with `liveData: false`. Without a copy, the run fails with a clear message and nothing is charged.

### Use it via API

Run it from any language and get the results as JSON. Replace `<YOUR_API_TOKEN>` with your [Apify API token](https://console.apify.com/settings/integrations).

```bash
curl -X POST "https://api.apify.com/v2/acts/br_data_hub~br-tesouro-direto/run-sync-get-dataset-items?token=<YOUR_API_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"latestOnly": true}'
```

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_API_TOKEN>")
run = client.actor("br_data_hub/br-tesouro-direto").call(run_input={'latestOnly': True})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)
```

You can also schedule runs, send results to webhooks, or connect the Actor to Make, Zapier, n8n, Google Sheets and other [integrations](https://docs.apify.com/platform/integrations).

### Use it with AI agents (MCP)

This Actor is ready for AI agents: typed input and output schemas, pay-per-event pricing, limited permissions and short runs.

- **Apify MCP server:** add `https://mcp.apify.com/?tools=br_data_hub/br-tesouro-direto` to Claude, ChatGPT, Cursor, VS Code or any MCP client, and the agent can call this Actor as a tool.
- **Agent frameworks:** call it from LangChain, LlamaIndex, CrewAI or the OpenAI Agents SDK through the Apify integrations, or with the API call above.
- Results come as structured JSON with stable field names, documented in the **Output** tab.

### FAQ

#### Where does the data come from?

- Dataset **"Taxas dos Títulos Ofertados pelo Tesouro Direto"** on [Tesouro Transparente](https://www.tesourotransparente.gov.br/ckan/dataset/taxas-dos-titulos-ofertados-pelo-tesouro-direto), the open data portal of the Brazilian National Treasury (Secretaria do Tesouro Nacional). File `PrecoTaxaTesouroDireto.csv`, resolved through the portal's CKAN API on every run. - Published as open data under Brazil's Open Data Policy (Decree 8,777/2016) and Access to Information Law (Law 12,527/2011). Please credit **"Fonte: Tesouro Nacional / Tesouro Transparente"** when you republish the data. - Morning quotes only, as published; the file is usually updated once per business day. Rates and prices are as published by the Treasury; this Actor only cleans and enriches them. It is not investment advice. - No personal data: the dataset contains only bond rates and prices. - If the portal is unreachable (it may block requests from outside Brazil), the Actor falls back to a copy of the file bundled in its image, when one is present, and marks every row with `liveData: false`. Without a copy, the run fails with a clear message and nothing is charged. To refresh the copy before a build: `curl -L <CSV URL> | gzip -9 > data/PrecoTaxaTesouroDireto.csv.gz`.

#### How much does it cost?

$0.001 per bond rate. Discounts follow your Apify subscription tier: Bronze 10%, Silver 20%, Gold and above 30%. See **How much does it cost?** above for examples.

#### Do I pay for errors or empty results?

No. Charged once per bond × date row returned. Failed runs and invalid inputs are free.

#### Can I run it on a schedule or connect it to other tools?

Yes. Use Apify schedules to run it daily or weekly, webhooks to get notified, and integrations such as Make, Zapier, n8n and Google Sheets. Everything also works through the API.

#### Can AI agents use it?

Yes. It works as a tool in the Apify MCP server and in agent frameworks, and AI agents can pay per event. See **Use it with AI agents (MCP)**.

#### Is it legal to use this data?

The Actor reads only public, official sources and keeps personal data masked as the source publishes it. You are responsible for how you use the data, including LGPD compliance.

#### I found a bug or need a feature. What should I do?

Open an issue in the **Issues** tab. We answer within 14 days, usually much sooner.

### More Actors from BR Data Hub

| Actor | What it does |
|---|---|
| [Brazil Exchange Rates API (Cotação PTAX)](https://apify.com/br_data_hub/br-exchange-rates) | Get official PTAX exchange rates from Banco Central do Brasil: buy and sell rates in BRL, parities and bulleti |
| [Brazil Inflation Calculator (IPCA, IGP-M, Selic)](https://apify.com/br_data_hub/br-monetary-correction) | Correct BRL amounts in bulk by IPCA, INPC, IGP-M, IGP-DI, IPC-Fipe, Selic, CDI, TR or savings (poupança) using |
| [Brazil Company Financials (CVM DFP/ITR, B3)](https://apify.com/br_data_hub/br-cvm-company-financials) | Standardized financial statements of Brazilian listed companies from CVM open data (DFP annual, ITR quarterly) |
| [Brazil Investment Fund Returns (Fundos CVM)](https://apify.com/br_data_hub/br-cvm-fund-performance) | Ready-made performance metrics for Brazilian investment funds from CVM open data: period, YTD and 12-month ret |
| [Brazil Fuel Prices by City (ANP Combustíveis)](https://apify.com/br_data_hub/br-anp-fuel-prices) | Weekly fuel prices in Brazil from the ANP open data survey (not affiliated with the ANP): average, minimum, ma |

See all our Actors at [apify.com/br_data_hub](https://apify.com/br_data_hub).

### Usar em português

Taxas e preços unitários (PU) dos **títulos do Tesouro Direto** (Tesouro Selic, Prefixado, Prefixado com Juros Semestrais, IPCA+, IPCA+ com Juros Semestrais, Renda+ e Educa+, além do antigo IGP-M+), a partir dos dados abertos do Tesouro Transparente.

**Para que serve:** acompanhar as taxas do dia num painel ou planilha; montar a série histórica de um título desde 2002; alimentar um simulador ou um agente de IA com a taxa e o preço oficiais; saber quais títulos ainda estão à venda.

**O que ele resolve:** o CSV oficial tem vírgula decimal, datas dd/mm/aaaa, zeros e vazios para título fora de venda e linhas fora de ordem. O Actor entrega JSON limpo, uma linha por título e data, já com dias até o vencimento, se o título está à venda e a variação da taxa contra o dia anterior e contra 30 dias antes.

**Como usar em 3 passos:**

1. Deixe `latestOnly` ligado (padrão) para receber só o último dia do arquivo, uma linha por título. Desligue para ter histórico.
2. Filtre, se quiser, por família em `bondTypes` (`selic`, `prefixado`, `prefixado-juros-semestrais`, `ipca`, `ipca-juros-semestrais`, `igpm-juros-semestrais`, `renda`, `educa`) e por vencimento em `maturities` (ano `2035` ou data `2035-05-15`).
3. No modo histórico, informe `dateFrom` e `dateTo` (AAAA-MM-DD; sem datas, os últimos 30 dias). Use `maxItems` para limitar o número de linhas. Rode e baixe em JSON, CSV ou Excel.

**Exemplo de entrada:**

```json
{"latestOnly": false, "bondTypes": ["ipca"], "maturities": ["2035"], "dateFrom": "2026-01-01", "dateTo": "2026-10-31"}
```

**Campos principais:** `bondType` e `maturityDate` (título e vencimento), `date` (data base), `buyRate` e `sellRate` (taxa de compra e de venda, % ao ano; no Tesouro Selic, o ágio ou deságio sobre a Selic), `buyPrice`, `sellPrice` e `basePrice` (PU em reais, cotação da manhã), `daysToMaturity`, `onSale`, `buyRateChange1d` e `buyRateChange30d` (variação em pontos percentuais), `sellPriceChange30dPct` e `liveData`.

**Bom saber:**

- O arquivo oficial só tem a cotação da manhã, normalmente atualizada uma vez por dia útil. `latestDateInSource` mostra a data mais recente disponível.
- Título fora de venda vem com `buyRate` e `buyPrice` nulos.
- Nomes antigos (LTN, LFT, NTN-B, NTN-F, NTN-C) são reconhecidos e entram na mesma família.

**O que é grátis:** execuções que falham, entradas inválidas e execuções sem linhas. Você paga só por linha entregue (evento `rate`). Não é recomendação de investimento. Fonte: Tesouro Nacional / Tesouro Transparente. Ferramenta independente, sem vínculo com o Tesouro Nacional, o programa Tesouro Direto ou a B3.

**Quanto custa:** $0.001 por resultado (`rate`); 1.000 resultados saem por $1.00. Desconto pelo nível da assinatura Apify: Bronze 10%, Silver 20%, Gold ou acima 30%. Erros e consultas sem resultado não são cobrados. Use também pela API ou por agentes de IA no servidor MCP da Apify (`https://mcp.apify.com/?tools=br_data_hub/br-tesouro-direto`).

# Actor input Schema

## `latestOnly` (type: `boolean`):

Keep on to return only the most recent date in the official file (one row per bond). Turn off to use the date range below.

## `bondTypes` (type: `array`):

Pick the bond families to return, e.g. Tesouro IPCA+. Leave empty for all, including retired ones such as IGP-M+.

## `maturities` (type: `array`):

Enter maturities, one per line, as a year (2035) or an exact date (2035-05-15). Leave empty for all.

## `dateFrom` (type: `string`):

Type the first base date as YYYY-MM-DD. Leave empty for 30 days before 'To date'.

## `dateTo` (type: `string`):

Type the last base date as YYYY-MM-DD. Leave empty for today.

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

Set the maximum number of bond × date rows to return (each row is one charged 'rate' event), e.g. 500. Leave empty for no limit.

## Actor input object example

```json
{
  "latestOnly": true,
  "bondTypes": [],
  "maturities": [],
  "dateFrom": "",
  "dateTo": ""
}
```

# Actor output Schema

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

Dataset with all results

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

OUTPUT record: rows returned, latest date in the source, source URL and license

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("br_data_hub/br-tesouro-direto").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("br_data_hub/br-tesouro-direto").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 '{}' |
apify call br_data_hub/br-tesouro-direto --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,br_data_hub/br-tesouro-direto"
        }
    }
}
```

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/AVDCZE1aZjILh7Ef5/builds/gKMztjwK73ke2rjt3/openapi.json
