pt-BR | en-US
Interface Julia para os serviços de dados abertos do Banco Central do Brasil (BCB), incluindo séries temporais econômicas (SGS), expectativas de mercado (relatório Focus) e câmbio (PTAX/OLINDA).
- Séries temporais (SGS):
sgs_series— qualquer uma das milhares de séries do SGS, com fracionamento automático de intervalos longos (a API SGS limita consultas a 10 anos) e suporte a múltiplas séries. - Expectativas de mercado (Focus):
focus_expectations— as 8 categorias da API OLINDA (anuais, mensais, trimestrais, inflação 12 meses, Selic e suas variantes Top 5) numa única função, selecionadas porperiod::Symbol. - Câmbio (PTAX / OLINDA):
fx_currency,fx_currencies,fx_all_currencies,fx_cross_rates— cotações diárias e intraday, listagem de moedas e matriz completa de cross-rates.
import Pkg
Pkg.add("BacenBR")
using BacenBRsgs_series(code; start_date=nothing, end_date=nothing, last=0, window_years=5)Intervalos maiores que window_years anos são fracionados automaticamente em múltiplas requisições e concatenados — a API SGS rejeita consultas com dataFinal - dataInicial maior que 10 anos.
| Forma | Coluna resultante |
|---|---|
433 |
"433" |
"ipca" => 433 |
"ipca" |
Dict("ipca" => 433) |
"ipca" |
["ipca" => 433, "igpm" => 189] |
"ipca", "igpm" |
| Parâmetro | Tipo | Descrição |
|---|---|---|
start_date |
Date ou String "YYYY-MM-DD" |
Data inicial |
end_date |
Date ou String "YYYY-MM-DD" |
Data final |
last |
Int |
Últimos N registros (ignora start_date/end_date/window_years) |
window_years |
Int |
Tamanho máximo (em anos) de cada janela de consulta ao SGS. Default: 5. |
- Um único
code→DataFramecom colunasdatee o valor. - Múltiplos códigos →
Vector{DataFrame}, um por série. Séries do SGS podem ter periodicidades diferentes (ex: IPCA mensal, Selic diária); juntar tudo num únicoDataFramepordategera uma explosão demissing, então cada série vem separada.
using BacenBR
using Dates
# Série completa sem nome customizado
sgs_series(433)
# Com nome na coluna
sgs_series("ipca" => 433)
# Últimos 12 meses
sgs_series("ipca" => 433; last=12)
# Intervalo de datas
sgs_series("ipca" => 433; start_date="2020-01-01", end_date="2022-12-31")
# Intervalo longo — fracionado automaticamente em janelas de 5 anos
sgs_series("selic" => 432; start_date="1995-01-01")
# Múltiplas séries — Vector{DataFrame}, uma por série
dfs = sgs_series(["ipca" => 433, "igpm" => 189, "selic" => 432]; start_date="2023-01-01")
ipca, igpm, selic = dfsExemplo de saída para sgs_series("ipca" => 433; last=5):
5×2 DataFrame
Row │ date ipca
│ Date Float64?
─────┼──────────────────────
1 │ 2026-01-01 0.33
2 │ 2026-02-01 0.70
3 │ 2026-03-01 0.88
4 │ 2026-04-01 0.67
5 │ 2026-05-01 0.58
| Código | Descrição |
|---|---|
| 433 | IPCA — variação mensal (%) |
| 7478 | IPCA-15 — variação mensal (%) |
| 13522 | INPC — variação mensal (%) |
| 189 | IGP-M — variação mensal (%) |
| 190 | IGP-DI — variação mensal (%) |
| 432 | Taxa Selic — % ao dia |
| 1178 | Taxa Selic Over — % ao ano |
| 1 | Taxa de câmbio — USD/BRL |
| 21619 | Taxa de câmbio — EUR/BRL |
Para encontrar outros códigos, acesse o SGS.
focus_expectations(period::Symbol; top5=false, indic=nothing, start_date=nothing,
end_date=nothing, top=nothing, skip=nothing)Todas as 8 categorias da API OLINDA de Expectativas ficam atrás de uma única função: o endpoint é selecionado por period e pela flag top5.
period |
Endpoint OLINDA | aceita top5=true? |
|---|---|---|
:annual |
ExpectativasMercadoAnuais | sim |
:quarterly |
ExpectativasMercadoTrimestrais | não |
:monthly |
ExpectativaMercadoMensais | sim |
:inflation_12m |
ExpectativasMercadoInflacao12Meses | não |
:selic |
ExpectativasMercadoSelic | sim |
| Parâmetro | Tipo | Descrição |
|---|---|---|
top5 |
Bool |
Se true, retorna as estatísticas Top 5 (só válido para :annual, :monthly e :selic) |
indic |
String ou Vector{String} |
Indicador(es). Case-sensitive, com acentos. |
start_date |
Date ou String "YYYY-MM-DD" |
Data inicial da coleta |
end_date |
Date ou String "YYYY-MM-DD" |
Data final da coleta |
top |
Int |
Máximo de linhas retornadas |
skip |
Int |
Pular os primeiros N registros |
using BacenBR
# IPCA anual — a partir de 2023
focus_expectations(:annual; indic="IPCA", start_date="2023-01-01")
# Múltiplos indicadores anuais
focus_expectations(:annual; indic=["IPCA", "Câmbio", "PIB Total"], top=30)
# Expectativas mensais de IPCA
# → reference_date é convertida automaticamente para Date (primeiro dia do mês)
focus_expectations(:monthly; indic="IPCA", start_date="2024-01-01")
# PIB trimestral
focus_expectations(:quarterly; indic="PIB Total", top=20)
# Inflação acumulada 12 meses à frente
focus_expectations(:inflation_12m; indic=["IPCA", "IGP-M"], start_date="2024-01-01")
# Top 5 IPCA mensal
focus_expectations(:monthly; indic="IPCA", top5=true, top=12)
# Expectativas para a Selic por reunião do COPOM
focus_expectations(:selic; start_date="2025-01-01")
# Top 5 Selic
focus_expectations(:selic; top5=true, start_date="2025-01-01", top=20)| Categoria | Indicadores |
|---|---|
| Inflação | IPCA, IPCA-15, INPC, IGP-M, IGP-DI, IPA-M, IPA-DI, IPC-Fipe |
| Câmbio | Câmbio |
| Atividade | PIB Total, PIB Indústria, PIB Serviços, PIB Agropecuária, Produção industrial |
| Mercado de trabalho | Taxa de desocupação |
| Juros | Selic |
| Setor externo | Balança Comercial, Conta corrente, Investimento direto no país |
| Fiscal | Resultado primário, Resultado nominal, Dívida bruta do governo geral |
Atenção: os nomes dos indicadores são case-sensitive e devem incluir acentos exatamente como listados. Consulte a documentação da API OLINDA para a lista completa.
| Coluna | Descrição |
|---|---|
date |
Data de divulgação da expectativa |
indic |
Nome do indicador |
reference_date |
Período de referência (ano, mês ou trimestre) |
mean |
Média das expectativas |
median |
Mediana |
sd |
Desvio padrão |
min / max |
Mínimo / Máximo |
respondents |
Número de instituições respondentes |
coefvar |
Coeficiente de variação |
smoothed |
Expectativa suavizada — "S" (sim) ou "N" (não) |
meeting |
Reunião do COPOM — formato "RN/YYYY" |
typeCalc |
Tipo de cálculo — endpoints Top 5 |
fx_currency(symbol, start_date, end_date=start_date; intraday=false, parity=false)
fx_currencies(; source=:ptax)
fx_all_currencies(date)
fx_cross_rates(date; ref=:ask)O pacote oferece duas camadas de acesso unificadas atrás de fx_currency:
| Camada | API | Retorno |
|---|---|---|
intraday=false (padrão) |
PTAX legada (CSV) | date, bid, ask — uma linha por dia |
intraday=true |
OLINDA (JSON) | datetime, bid, ask — todos os boletins do dia; aceita parity=true |
Nota sobre USD: o BCB removeu o USD da interface PTAX legada.
fx_currency("USD", ...)redireciona automaticamente para OLINDA, retornando a cotação de fechamento diária no mesmo formato.
using BacenBR
using Dates
# Série diária — PTAX (fechamento)
fx_currency("USD", "2024-01-01", "2024-01-31")
fx_currency("EUR", "2024-01-01", "2024-01-31")
fx_currency("JPY", Date(2024,1,1), Date(2024,1,31))
# Série intraday — OLINDA (todos os boletins do dia)
fx_currency("USD", "2024-01-02", "2024-01-05"; intraday=true)
fx_currency("EUR", "2024-01-02", "2024-01-05"; intraday=true)
# Com paridade (cotação em USD, não em BRL) — requer intraday=true
# Tipo A (ex: JPY): paridade = JPY / USD
# Tipo B (ex: EUR, AUD): paridade = USD / EUR
fx_currency("EUR", "2024-01-02", "2024-01-05"; intraday=true, parity=true)
fx_currency("JPY", "2024-01-02", "2024-01-05"; intraday=true, parity=true)
# Listar moedas disponíveis
fx_currencies() # CSV mestre BCB — ~200 moedas com código numérico
fx_currencies(; source=:olinda) # OLINDA — moedas com tipo A/B
# Todas as moedas em BRL numa data específica
fx_all_currencies(Date(2024, 1, 2))
# Matriz de cross-rates (todas as combinações entre moedas)
m = fx_cross_rates(Date(2024, 1, 2)) # ask (padrão)
m = fx_cross_rates(Date(2024, 1, 2); ref=:bid)
# Acessar um par específico: quanto USD vale 1 EUR?
m[m.symbol .== "EUR", :USD]fx_currency:
| Coluna | Descrição |
|---|---|
date (diário) / datetime (intraday) |
Data ou data+hora da cotação |
bid |
Taxa de compra em BRL (ou paridade USD se parity=true) |
ask |
Taxa de venda em BRL (ou paridade USD se parity=true) |
fx_currencies(; source=:ptax):
| Coluna | Descrição |
|---|---|
symbol |
Código ISO da moeda (ex: "USD", "EUR") |
name |
Nome da moeda |
code |
Código numérico BCB |
country_name |
País de origem |
currency_type |
"A" (moeda/USD) ou "B" (USD/moeda) |
fx_cross_rates:
DataFrame com coluna :symbol + uma coluna por moeda. Cada célula [linha, coluna] = 1 unidade da moeda da linha em unidades da moeda da coluna. Inclui BRL.
| Pacote | Uso |
|---|---|
HTTP.jl |
Requisições HTTP |
JSON3.jl |
Parsing de respostas JSON |
DataFrames.jl |
Estrutura de dados tabular |
Dates |
Manipulação de datas (stdlib) |
- SGS: api.bcb.gov.br — Sistema Gerenciador de Séries Temporais do BCB
- PTAX: ptax.bcb.gov.br — Sistema de cotações de câmbio do BCB
- OLINDA: olinda.bcb.gov.br — Plataforma de dados abertos do BCB
Todas as APIs são públicas e não requerem autenticação.
Agradecimentos a Wilson Freitas, cujo trabalho em rbcb mapeou boa parte dos endpoints do BCB usados aqui.
MIT
pt-BR | en-US
Julia interface for the Brazilian Central Bank (BCB) open data services, covering economic time series (SGS), market expectations (Focus Report), and exchange rates (PTAX/OLINDA).
- Time series (SGS):
sgs_series— any of the thousands of series from BCB's SGS, with automatic windowing for long date ranges (the SGS API caps queries at 10 years) and support for multiple series. - Market expectations (Focus):
focus_expectations— all 8 categories from the OLINDA API (annual, monthly, quarterly, 12-month inflation, Selic, and their Top 5 variants) in a single function, selected viaperiod::Symbol. - Exchange rates (PTAX / OLINDA):
fx_currency,fx_currencies,fx_all_currencies,fx_cross_rates— daily and intraday quotes, currency listings, and a full cross-rate matrix.
import Pkg
Pkg.add("BacenBR")
using BacenBRsgs_series(code; start_date=nothing, end_date=nothing, last=0, window_years=5)Ranges longer than window_years years are automatically split into multiple requests and concatenated — the SGS API rejects queries where dataFinal - dataInicial exceeds 10 years.
| Form | Resulting column |
|---|---|
433 |
"433" |
"ipca" => 433 |
"ipca" |
Dict("ipca" => 433) |
"ipca" |
["ipca" => 433, "igpm" => 189] |
"ipca", "igpm" |
| Parameter | Type | Description |
|---|---|---|
start_date |
Date or String "YYYY-MM-DD" |
Start date |
end_date |
Date or String "YYYY-MM-DD" |
End date |
last |
Int |
Last N records (overrides start_date/end_date/window_years) |
window_years |
Int |
Maximum size (in years) of each SGS query window. Default: 5. |
- Single
code→DataFramewith columnsdateand the value. - Multiple codes →
Vector{DataFrame}, one per series. SGS series can have different frequencies (e.g. monthly IPCA, daily Selic); merging everything into a singleDataFramebydateproduces an explosion ofmissingvalues, so each series comes back separately.
using BacenBR
using Dates
# Full series without a custom name
sgs_series(433)
# With a custom column name
sgs_series("ipca" => 433)
# Last 12 records
sgs_series("ipca" => 433; last=12)
# Date range
sgs_series("ipca" => 433; start_date="2020-01-01", end_date="2022-12-31")
# Long range — automatically split into 5-year windows
sgs_series("selic" => 432; start_date="1995-01-01")
# Multiple series — Vector{DataFrame}, one per series
dfs = sgs_series(["ipca" => 433, "igpm" => 189, "selic" => 432]; start_date="2023-01-01")
ipca, igpm, selic = dfsSample output for sgs_series("ipca" => 433; last=5):
5×2 DataFrame
Row │ date ipca
│ Date Float64?
─────┼──────────────────────
1 │ 2026-01-01 0.33
2 │ 2026-02-01 0.70
3 │ 2026-03-01 0.88
4 │ 2026-04-01 0.67
5 │ 2026-05-01 0.58
| Code | Description |
|---|---|
| 433 | IPCA — monthly change (%) |
| 7478 | IPCA-15 — monthly change (%) |
| 13522 | INPC — monthly change (%) |
| 189 | IGP-M — monthly change (%) |
| 190 | IGP-DI — monthly change (%) |
| 432 | Selic rate — % per day |
| 1178 | Selic Over rate — % per year |
| 1 | Exchange rate — USD/BRL |
| 21619 | Exchange rate — EUR/BRL |
Find more series codes at the SGS portal.
focus_expectations(period::Symbol; top5=false, indic=nothing, start_date=nothing,
end_date=nothing, top=nothing, skip=nothing)All 8 categories of the OLINDA Expectations API sit behind a single function: the endpoint is selected via period and the top5 flag.
period |
OLINDA endpoint | accepts top5=true? |
|---|---|---|
:annual |
ExpectativasMercadoAnuais | yes |
:quarterly |
ExpectativasMercadoTrimestrais | no |
:monthly |
ExpectativaMercadoMensais | yes |
:inflation_12m |
ExpectativasMercadoInflacao12Meses | no |
:selic |
ExpectativasMercadoSelic | yes |
| Parameter | Type | Description |
|---|---|---|
top5 |
Bool |
If true, returns Top 5 statistics (only valid for :annual, :monthly, and :selic) |
indic |
String or Vector{String} |
Indicator(s). Case-sensitive, accents required. |
start_date |
Date or String "YYYY-MM-DD" |
Start date |
end_date |
Date or String "YYYY-MM-DD" |
End date |
top |
Int |
Maximum number of rows |
skip |
Int |
Skip first N records |
using BacenBR
# Annual IPCA expectations since 2023
focus_expectations(:annual; indic="IPCA", start_date="2023-01-01")
# Multiple annual indicators
focus_expectations(:annual; indic=["IPCA", "Câmbio", "PIB Total"], top=30)
# Monthly IPCA expectations
# → reference_date is automatically converted to Date (first day of the month)
focus_expectations(:monthly; indic="IPCA", start_date="2024-01-01")
# Quarterly GDP
focus_expectations(:quarterly; indic="PIB Total", top=20)
# 12-month ahead inflation
focus_expectations(:inflation_12m; indic=["IPCA", "IGP-M"], start_date="2024-01-01")
# Top 5 monthly IPCA
focus_expectations(:monthly; indic="IPCA", top5=true, top=12)
# Selic expectations by COPOM meeting
focus_expectations(:selic; start_date="2025-01-01")
# Top 5 Selic
focus_expectations(:selic; top5=true, start_date="2025-01-01", top=20)| Category | Indicators |
|---|---|
| Inflation | IPCA, IPCA-15, INPC, IGP-M, IGP-DI, IPA-M, IPA-DI, IPC-Fipe |
| Exchange rate | Câmbio |
| Activity | PIB Total, PIB Indústria, PIB Serviços, PIB Agropecuária, Produção industrial |
| Labor market | Taxa de desocupação |
| Interest rate | Selic |
| External sector | Balança Comercial, Conta corrente, Investimento direto no país |
| Fiscal | Resultado primário, Resultado nominal, Dívida bruta do governo geral |
Note: indicator names are case-sensitive and must include accents exactly as listed. See the OLINDA API documentation for the full list.
| Column | Description |
|---|---|
date |
Date the expectation was published |
indic |
Indicator name |
reference_date |
Reference period (year, month, or quarter) |
mean |
Mean of expectations |
median |
Median |
sd |
Standard deviation |
min / max |
Minimum / Maximum |
respondents |
Number of reporting institutions |
coefvar |
Coefficient of variation |
smoothed |
Smoothed expectation — "S" (yes) or "N" (no) |
meeting |
COPOM meeting — format "RN/YYYY" |
typeCalc |
Calculation type — Top 5 endpoints |
fx_currency(symbol, start_date, end_date=start_date; intraday=false, parity=false)
fx_currencies(; source=:ptax)
fx_all_currencies(date)
fx_cross_rates(date; ref=:ask)The package unifies both access layers behind fx_currency:
| Layer | API | Returns |
|---|---|---|
intraday=false (default) |
Legacy PTAX (CSV) | date, bid, ask — one row per day |
intraday=true |
OLINDA (JSON) | datetime, bid, ask — every bulletin of the day; accepts parity=true |
Note on USD: the BCB removed USD from the legacy PTAX interface.
fx_currency("USD", ...)automatically redirects to OLINDA, returning the daily closing rate in the same format.
using BacenBR
using Dates
# Daily series — PTAX (closing rate)
fx_currency("USD", "2024-01-01", "2024-01-31")
fx_currency("EUR", "2024-01-01", "2024-01-31")
fx_currency("JPY", Date(2024,1,1), Date(2024,1,31))
# Intraday series — OLINDA (all bulletins per day)
fx_currency("USD", "2024-01-02", "2024-01-05"; intraday=true)
fx_currency("EUR", "2024-01-02", "2024-01-05"; intraday=true)
# With parity (rate in USD, not BRL) — requires intraday=true
# Type A (e.g. JPY): parity = JPY / USD
# Type B (e.g. EUR, AUD): parity = USD / EUR
fx_currency("EUR", "2024-01-02", "2024-01-05"; intraday=true, parity=true)
fx_currency("JPY", "2024-01-02", "2024-01-05"; intraday=true, parity=true)
# List available currencies
fx_currencies() # BCB master CSV — ~200 currencies with numeric code
fx_currencies(; source=:olinda) # OLINDA — currencies with type A/B
# All currencies in BRL for a specific date
fx_all_currencies(Date(2024, 1, 2))
# Cross-rate matrix (all currency pairs)
m = fx_cross_rates(Date(2024, 1, 2)) # ask (default)
m = fx_cross_rates(Date(2024, 1, 2); ref=:bid)
# Access a specific pair: how many USD does 1 EUR buy?
m[m.symbol .== "EUR", :USD]fx_currency:
| Column | Description |
|---|---|
date (daily) / datetime (intraday) |
Date or date+time of the quote |
bid |
Buy rate in BRL (or USD parity if parity=true) |
ask |
Sell rate in BRL (or USD parity if parity=true) |
fx_currencies(; source=:ptax):
| Column | Description |
|---|---|
symbol |
ISO currency code (e.g. "USD", "EUR") |
name |
Currency name |
code |
BCB numeric code |
country_name |
Country of origin |
currency_type |
"A" (currency/USD) or "B" (USD/currency) |
fx_cross_rates:
DataFrame with a :symbol column + one column per currency. Each cell [row, col] = 1 unit of the row currency expressed in column currency units. Includes BRL.
| Package | Purpose |
|---|---|
HTTP.jl |
HTTP requests |
JSON3.jl |
JSON response parsing |
DataFrames.jl |
Tabular data structure |
Dates |
Date handling (stdlib) |
- SGS: api.bcb.gov.br — BCB Time Series Management System
- PTAX: ptax.bcb.gov.br — BCB foreign exchange system
- OLINDA: olinda.bcb.gov.br — BCB Open Data Platform
All APIs are public and require no authentication.
Thanks to Wilson Freitas, whose work on rbcb mapped much of the BCB endpoints used here.
MIT