BC Data
auctions(start=None, end=None, auction_type=None)
Recupera dados de leilões para um determinado período e tipo de leilão da API do BC.
Consultas de Período:
- Para consultar dados de um intervalo, forneça as datas de start e end.
Exemplo: auctions(start='2024-10-20', end='2024-10-27')
- Se apenas start for fornecido, a API do BC retornará dados de leilão a partir
da data de start até a data mais recente disponível.
Exemplo: auctions(start='2024-10-20')
- Se apenas end for fornecido, a API do BC retornará dados de leilão desde a
data mais antiga disponível até a data de end.
Exemplo: auctions(end='2024-10-27')
Série Histórica Completa:
- Para recuperar a série histórica completa de leilões (desde 12/11/2012 até o
último dia útil), chame a função sem fornecer os parâmetros start e end.
Exemplo: auctions()
Busca dados de leilões da API do BC para as datas de início e fim especificadas,
filtrando os resultados diretamente na API pelo tipo de leilão, se especificado.
O comportamento da função em relação aos parâmetros start e end segue o padrão
da API do Banco Central:
- Se start for fornecido e end não, a função retorna dados de start até o fim.
- Se end for fornecido e start não, a API retorna dados do início até end.
- Se ambos start e end forem omitidos, a API retorna a série histórica completa.
Os dados podem ser filtrados pelo tipo de leilão especificado ("Sell" ou "Buy"). Leilões de "Sell" são aqueles em que o Tesouro Nacional vende títulos ao mercado. Leilões de "Buy" são aqueles em que o Tesouro Nacional compra títulos do mercado.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
(DateScalar, opcional)
|
A data de início para a consulta dos leilões.
Se |
None
|
end
|
(DateScalar, opcional)
|
A data de fim para a consulta de dados de leilão.
Se |
None
|
auction_type
|
(Literal['sell', 'buy'], opcional)
|
O tipo de leilão para filtrar
diretamente na API. Padrão é |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Um DataFrame contendo dados de leilões para o período e tipo especificados. Em caso de erro ao buscar os dados, um DataFrame vazio é retornado e uma mensagem de erro é registrada no log. |
Examples:
>>> from pyield import bc
>>> bc.auctions(start="19-08-2025", end="19-08-2025")
shape: (5, 30)
┌────────────┬────────────┬─────────────┬───────────┬───┬──────────────────┬─────────────┬──────────┬─────────────┐
│ Date ┆ Settlement ┆ AuctionType ┆ Ordinance ┆ … ┆ AcceptedQuantity ┆ ValueFR ┆ ValueSR ┆ Value │
│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ date ┆ str ┆ i64 ┆ ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞════════════╪════════════╪═════════════╪═══════════╪═══╪══════════════════╪═════════════╪══════════╪═════════════╡
│ 2025-08-19 ┆ 2025-08-20 ┆ Venda ┆ 192 ┆ … ┆ 150000 ┆ 2572400000 ┆ 0 ┆ 2572400000 │
│ 2025-08-19 ┆ 2025-08-20 ┆ Venda ┆ 192 ┆ … ┆ 751003 ┆ 12804476147 ┆ 17123853 ┆ 12821600000 │
│ 2025-08-19 ┆ 2025-08-20 ┆ Venda ┆ 193 ┆ … ┆ 300759 ┆ 1289936461 ┆ 3263539 ┆ 1293200000 │
│ 2025-08-19 ┆ 2025-08-20 ┆ Venda ┆ 194 ┆ … ┆ 500542 ┆ 2071654327 ┆ 2245673 ┆ 2073900000 │
│ 2025-08-19 ┆ 2025-08-20 ┆ Venda ┆ 194 ┆ … ┆ 500000 ┆ 2010700000 ┆ 0 ┆ 2010700000 │
└────────────┴────────────┴─────────────┴───────────┴───┴──────────────────┴─────────────┴──────────┴─────────────┘
Notes
FR = First Round (Primeira Rodada) SR = Second Round (Segunda Rodada)
DataFrame Columns
- Date: Data do leilão.
- Settlement: Data de liquidação do leilão.
- AuctionType: Tipo de leilão (ex: "Sell" ou "Buy").
- Ordinance: Edital normativo associado ao leilão.
- Buyer: Categoria do comprador (ex: "TodoMercado", "SomenteDealerApto").
- BondType: Categoria do título (ex: "LTN", "LFT", "NTN-B", "NTN-F").
- SelicCode: Código do título no sistema Selic.
- Maturity: Data de vencimento do título.
- BDToMat: Dias úteis entre a liquidação da 1R e a data de vencimento do título.
- Duration: Duration (Duração) calculada com base na data de liquidação da 1R e na data de vencimento do título.
- AvgMaturity: Maturidade média do título (em anos).
- AvgPrice: Preço médio no leilão.
- CutPrice: Preço de corte.
- AvgRate: Taxa de juros média.
- CutRate: Taxa de corte.
- DV01FR: DV01 da Primeira Rodada (FR) em R$.
- DV01SR: DV01 da Segunda Rodada (SR) em R$.
- DV01: Valor do DV01 total do leilão em R$.
- DV01FRUSD: DV01 da Primeira Rodada (FR) em dólares (USD).
- DV01SRUSD: DV01 da Segunda Rodada (SR) em dólares (USD).
- DV01USD: DV01 total do leilão em dólares (USD).
- OfferedQuantityFR: Quantidade ofertada na primeira rodada (FR).
- OfferedQuantitySR: Quantidade ofertada na segunda rodada (SR).
- OfferedQuantity: Quantidade total ofertada no leilão (FR + SR).
- AcceptedQuantityFR: Quantidade aceita na primeira rodada (FR).
- AcceptedQuantitySR: Quantidade aceita na segunda rodada (SR).
- AcceptedQuantity: Quantidade total aceita no leilão (FR + SR).
- ValueFR: Valor da primeira rodada (FR) do leilão em R$.
- ValueSR: Valor da segunda rodada (SR) em R$.
- Value: Valor total do leilão em R$ (FR + SR).
Source code in pyield/bc/auction.py
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | |
di_over(date, annualized=True)
Fetches the DI Over rate value for a specific date.
This is a convenience function that returns only the value (not the DataFrame) for the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date
|
DateScalar
|
The reference date to fetch the DI Over rate for. |
required |
annualized
|
bool
|
If True, returns the annualized rate (252 trading days per year), otherwise returns the daily rate. |
True
|
Returns:
| Type | Description |
|---|---|
float
|
The DI Over rate as a float or float("nan") if not available. |
Examples:
Source code in pyield/bc/rates.py
di_over_series(start, end=None, annualized=True)
Fetches the DI (Interbank Deposit) rate from the Brazilian Central Bank.
The DI rate represents the average interest rate of interbank loans.
API URL Example
https://api.bcb.gov.br/dados/serie/bcdata.sgs.11/dados?formato=json&dataInicial=12/04/2024&dataFinal=12/04/2024 https://api.bcb.gov.br/dados/serie/bcdata.sgs.11/dados?formato=csv&dataInicial=12/04/2024&dataFinal=12/04/2024
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
DateScalar
|
The start date for the data to fetch. If None, returns data from the earliest available date. |
required |
end
|
DateScalar | None
|
The end date for the data to fetch. If None, returns data up to the latest available date. |
None
|
annualized
|
bool
|
If True, returns the annualized rate (252 trading days per year), otherwise returns the daily rate. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing Date and Value columns with the DI rate, |
DataFrame
|
or empty DataFrame if data is not available. |
Examples:
>>> from pyield import bc
>>> # Returns all data since 29-01-2025
>>> bc.di_over_series("29-01-2025").head(5) # Showing only first 5 rows
shape: (5, 2)
┌────────────┬────────┐
│ Date ┆ Value │
│ --- ┆ --- │
│ date ┆ f64 │
╞════════════╪════════╡
│ 2025-01-29 ┆ 0.1215 │
│ 2025-01-30 ┆ 0.1315 │
│ 2025-01-31 ┆ 0.1315 │
│ 2025-02-03 ┆ 0.1315 │
│ 2025-02-04 ┆ 0.1315 │
└────────────┴────────┘
Source code in pyield/bc/rates.py
ptax(date)
Busca a cotação PTAX média de fechamento para uma data específica.
Esta função é um wrapper para a função ptax_series, otimizada para
buscar o valor de um único dia.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date
|
DateScalar
|
A data para a qual a cotação PTAX é desejada. Pode ser uma string no formato "dd-mm-aaaa" ou um objeto date/datetime. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
O valor da PTAX (taxa média) para a data especificada. Retorna None se não houver cotação para a data (ex: feriado, fim de semana ou data futura). |
Examples:
Source code in pyield/bc/ptax_api.py
ptax_series(start=None, end=None)
Cotações de Dólar PTAX (taxa de câmbio) - Fonte: Banco Central do Brasil (BCB) - Frequência: Diária - Unidade: R$
Documentação da API do BCB:
https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/documentacao
Exemplo de chamada à API:
https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoDolarPeriodo(dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)?@dataInicial='08-01-2025'&@dataFinalCotacao='08-05-2025'&$format=text/csv
Consultas de Período:
-
Para consultar dados de um intervalo, forneça as datas de
starteend. Exemplo:`ptax_series(start='20-10-2024', end='27-10-2024')` -
Se apenas
startfor fornecido, a API do BC retornará dados a partir da data destartaté a data mais recente disponível. Exemplo:`ptax_series(start='20-10-2024')` -
Se apenas
endfor fornecido, a API do BC retornará dados desde a data mais antiga disponível até a data deend. Exemplo:ptax_series(end='27-10-2024')
Série Histórica Completa:
- Para recuperar a série histórica completa de leilões (desde 28.11.1984
até o último dia útil), chame a função sem fornecer os parâmetros
starteend. Exemplo:`ptax_series()`
Busca dados de cotações de dólar PTAX (taxa de câmbio) para o período:
- Se
startfor fornecido eendnão, a função retorna dados destartaté o fim. - Se
endfor fornecido estartnão, a API retorna dados do início atéend. - Se ambos
starteendforem omitidos, a API retorna a série histórica completa.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
(DateScalar, opcional)
|
A data de início para a consulta dos leilões.
Se |
None
|
end
|
(DateScalar, opcional)
|
A data de fim para a consulta de dados de leilão.
Se |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Um DataFrame contendo os dados de cotações de dólar PTAX. |
DataFrame
|
Se não houver dados disponíveis para o período especificado, um DataFrame vazio |
DataFrame
|
será retornado. |
Examples:
>>> from pyield import bc
>>> bc.ptax_series(start="20-04-2025", end="25-04-2025")
shape: (4, 5)
┌────────────┬─────────────────────────┬─────────┬──────────┬─────────┐
│ Date ┆ DateTime ┆ BuyRate ┆ SellRate ┆ MidRate │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ datetime[ms] ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪═════════════════════════╪═════════╪══════════╪═════════╡
│ 2025-04-22 ┆ 2025-04-22 13:09:35.629 ┆ 5.749 ┆ 5.7496 ┆ 5.7493 │
│ 2025-04-23 ┆ 2025-04-23 13:06:30.443 ┆ 5.6874 ┆ 5.688 ┆ 5.6877 │
│ 2025-04-24 ┆ 2025-04-24 13:04:29.639 ┆ 5.6732 ┆ 5.6738 ┆ 5.6735 │
│ 2025-04-25 ┆ 2025-04-25 13:09:26.592 ┆ 5.684 ┆ 5.6846 ┆ 5.6843 │
└────────────┴─────────────────────────┴─────────┴──────────┴─────────┘
Notes
Disponível desde 28.11.1984, refere-se às taxas administradas até março de 1990 e às taxas livres a partir de então (Resolução 1690, de 18.3.1990). As taxas administradas são aquelas fixadas pelo Banco Central; a partir de março de 1992, essa taxa recebeu a denominação de taxa PTAX (fechamento). Até 30 de junho de 2011, as taxas livres correspondiam à média das taxas efetivas de operações no mercado interbancário, ponderada pelo volume de transações do dia. A partir de 1 de julho de 2011 (Circular 3506, de 23.9.2010), a Ptax passou a corresponder à média aritmética das taxas obtidas em quatro consultas diárias aos dealers de câmbio e refletem a taxa negociada no momento de abertura da janela de consulta; o boletim de fechamento PTAX corresponde à média aritmética das taxas dos boletins do dia.
- Primeira data disponível: 28.11.1984
- Última data disponível: data atual
O DataFrame possui as seguintes colunas:
- Date: Data da cotação.
- DateTime: Data e hora da cotação.
- BuyRate: Taxa de compra.
- SellRate: Taxa de venda.
- MidRate: Taxa média entre a compra/venda arredondada para 5 casas decimais.
Source code in pyield/bc/ptax_api.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
repos(start=None, end=None)
Consulta e retorna leilões de operações compromissadas (repos) do BCB.
Semântica dos parâmetros de período (API OData): - start somente: dados de start até o fim da série. - end somente: dados do início da série até end. - ambos omitidos: série histórica completa.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
DateScalar | None
|
Data inicial (inclusive) ou None. |
None
|
end
|
DateScalar | None
|
Data final (inclusive) ou None. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame com colunas normalizadas em português e tipos |
DataFrame
|
enriquecidos (frações decimais, inteiros, datas). Em caso de erro |
DataFrame
|
retorna DataFrame vazio e registra log da exceção. |
DataFrame columns
- data_leilao: data de ocorrência do leilão.
- data_liquidacao: data de liquidação (início da operação).
- data_retorno: data de recompra / término da operação.
- hora_inicio: horário de início do leilão.
- prazo_dias_corridos: dias corridos até a data de retorno.
- prazo_dias_uteis: dias úteis entre liquidação e retorno (bday.count).
- numero_comunicado: número do comunicado/aviso do BC (pode ser nulo).
- tipo_oferta: classif. do tipo de oferta (ex: Tomador, Compromissada 1047).
- publico_permitido: escopo de participantes (SomenteDealer, TodoMercado).
- volume_aceito: volume aceito no leilão em reais (convertido de milhares).
- taxa_corte: taxa de corte (ex. 0.1490 = 14,90%). Nula se volume_aceito = 0.
- percentual_aceito: percentual do volume ofertado efetivamente aceito (0-100). 100 = nenhuma rejeição. 0 indica nada aceito (volume_aceito = 0).
Notes
- Dados ordenados por: data_leilao, hora_inicio, tipo_oferta.
Examples:
>>> from pyield import bc
>>> bc.repos(start="21-08-2025", end="21-08-2025")
shape: (2, 12)
┌─────────────┬─────────────────┬──────────────┬─────────────┬───┬───────────────────┬───────────────┬────────────┬───────────────────┐
│ data_leilao ┆ data_liquidacao ┆ data_retorno ┆ hora_inicio ┆ … ┆ publico_permitido ┆ volume_aceito ┆ taxa_corte ┆ percentual_aceito │
│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ date ┆ date ┆ time ┆ ┆ str ┆ i64 ┆ f64 ┆ f64 │
╞═════════════╪═════════════════╪══════════════╪═════════════╪═══╪═══════════════════╪═══════════════╪════════════╪═══════════════════╡
│ 2025-08-21 ┆ 2025-08-21 ┆ 2025-08-22 ┆ 09:00:00 ┆ … ┆ SomenteDealer ┆ 647707406000 ┆ 0.149 ┆ 100.0 │
│ 2025-08-21 ┆ 2025-08-22 ┆ 2025-11-21 ┆ 12:00:00 ┆ … ┆ TodoMercado ┆ 5000000000 ┆ 0.9978 ┆ 35.87 │
└─────────────┴─────────────────┴──────────────┴─────────────┴───┴───────────────────┴───────────────┴────────────┴───────────────────┘
Source code in pyield/bc/repo.py
selic_over(date)
Fetches the SELIC Over rate value for a specific date.
This is a convenience function that returns only the value (not the DataFrame) for the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date
|
DateScalar
|
The reference date to fetch the SELIC Over rate for. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The SELIC Over rate as a float or None if not available. |
Examples:
Source code in pyield/bc/rates.py
selic_over_series(start, end=None)
Fetches the SELIC Over rate from the Brazilian Central Bank.
The SELIC Over rate is the daily average interest rate effectively practiced between banks in the interbank market, using public securities as collateral.
API URL Example
https://api.bcb.gov.br/dados/serie/bcdata.sgs.1178/dados?formato=json&dataInicial=12/04/2024&dataFinal=12/04/2024
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
DateScalar
|
The start date for the data to fetch. If None, returns data from the earliest available date. |
required |
end
|
DateScalar | None
|
The end date for the data to fetch. If None, returns data up to the latest available date. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing Date and Value columns with the SELIC Over rate, |
DataFrame
|
or empty DataFrame if data is not available. |
Examples:
>>> from pyield import bc
>>> # No data on 26-01-2025 (sunday). Selic changed due to Copom meeting.
>>> bc.selic_over_series("26-01-2025").head(5) # Showing first 5 rows
shape: (5, 2)
┌────────────┬────────┐
│ Date ┆ Value │
│ --- ┆ --- │
│ date ┆ f64 │
╞════════════╪════════╡
│ 2025-01-27 ┆ 0.1215 │
│ 2025-01-28 ┆ 0.1215 │
│ 2025-01-29 ┆ 0.1215 │
│ 2025-01-30 ┆ 0.1315 │
│ 2025-01-31 ┆ 0.1315 │
└────────────┴────────┘
>>> # Fetching data for a specific date range
>>> bc.selic_over_series("14-09-2025", "17-09-2025")
shape: (3, 2)
┌────────────┬───────┐
│ Date ┆ Value │
│ --- ┆ --- │
│ date ┆ f64 │
╞════════════╪═══════╡
│ 2025-09-15 ┆ 0.149 │
│ 2025-09-16 ┆ 0.149 │
│ 2025-09-17 ┆ 0.149 │
└────────────┴───────┘
Source code in pyield/bc/rates.py
selic_target(date)
Fetches the SELIC Target rate value for a specific date.
This is a convenience function that returns only the value (not the DataFrame) for the specified date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date
|
DateScalar
|
The reference date to fetch the SELIC Target rate for. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The SELIC Target rate as a float or None if not available. |
Examples:
Source code in pyield/bc/rates.py
selic_target_series(start, end=None)
Fetches the SELIC Target rate from the Brazilian Central Bank.
The SELIC Target rate is the official interest rate set by the Central Bank of Brazil's Monetary Policy Committee (COPOM).
API URL Example
https://api.bcb.gov.br/dados/serie/bcdata.sgs.432/dados?formato=json&dataInicial=12/04/2024&dataFinal=12/04/2024
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
DateScalar
|
The start date for the data to fetch. |
required |
end
|
DateScalar | None
|
The end date for the data to fetch. If None, returns data up to the latest available date. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing Date and Value columns with the SELIC Target rate, |
DataFrame
|
or empty DataFrame if data is not available |
Examples:
>>> from pyield import bc
>>> bc.selic_target_series("31-05-2024", "31-05-2024")
shape: (1, 2)
┌────────────┬───────┐
│ Date ┆ Value │
│ --- ┆ --- │
│ date ┆ f64 │
╞════════════╪═══════╡
│ 2024-05-31 ┆ 0.105 │
└────────────┴───────┘
Source code in pyield/bc/rates.py
tpf_intraday_trades()
Fetches real-time secondary trading data for domestic Federal Public Debt (TPF - títulos públicos federais) from the Central Bank of Brazil (BCB).
This function checks if the SELIC market is currently open based on Brazil/Sao_Paulo timezone business days and trading hours (defined by REALTIME_START_TIME and REALTIME_END_TIME). If the market is closed, or if no data is available from the source, or if an error occurs during fetching or processing, an empty DataFrame is returned. Otherwise, it retrieves, cleans, and processes the intraday trade data provided by BCB for Brazilian government bonds.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: A DataFrame containing the latest intraday trades for FPD securities. Returns an empty DataFrame if the market is closed, no data is found, or an error occurs. The DataFrame includes the following columns: |
DataFrame Columns
CollectedAt: Timestamp indicating when the data was collected (in Brazil/Sao_Paulo timezone).SettlementDate: The reference date for the spot market trading activity reported in this dataset (the current business day). Forward trades listed have future settlement dates not specified here.BondType: Abbreviation/ticker for the bond type (e.g., LFT, LTN, NTN-B).SelicCode: The unique SELIC code identifying the specific bond issue.MaturityDate: The maturity date of the bond.MinPrice: Minimum traded price.AvgPrice: Average traded price.MaxPrice: Maximum traded price.LastPrice: Last traded price.MinRate: Minimum traded yield/rate (as a decimal, e.g., 0.11 for 11%).AvgRate: Average traded yield/rate (as a decimal).MaxRate: Maximum traded yield/rate (as a decimal).LastRate: Last traded yield/rate (as a decimal).Trades: Total number of trades settled.Quantity: Total number of bonds traded (quantity).Value: Total financial value traded (in BRL).BrokeredTrades: Number of brokered trades settled.BrokeredQuantity: Quantity of bonds traded via brokers.FwdMinPrice: Forward minimum traded price.FwdAvgPrice: Forward average traded price.FwdMaxPrice: Forward maximum traded price.FwdLastPrice: Forward last traded price.FwdMinRate: Forward minimum traded yield/rate (decimal).FwdAvgRate: Forward average traded yield/rate (decimal).FwdMaxRate: Forward maximum traded yield/rate (decimal).FwdLastRate: Forward last traded yield/rate (decimal).FwdTrades: Forward total number of trades contracted.FwdQuantity: Forward total number of bonds traded (quantity).FwdValue: Forward total financial value traded (in BRL).FwdBrokeredTrades: Forward number of brokered trades contracted.FwdBrokeredQuantity: Forward quantity of bonds traded via brokers.
Notes
- The DataFrame returned by this function may be empty if the market is closed, no data is found, or an error occurs.
- Arrow data types are used for better performance and compatibility with other libraries.
Source code in pyield/bc/trades_intraday.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
tpf_monthly_trades(target_date, extragroup=False)
Fetches monthly secondary trading data for the domestic 'Federal Public Debt' (TPF - títulos públicos federais) registered in the Brazilian Central Bank (BCB) Selic system.
Downloads the monthly bond trading data from the Brazilian Central Bank (BCB) website for the month corresponding to the provided date. The data is downloaded as a ZIP file, extracted, and loaded into a Pandas DataFrame. The data contains all trades executed during the month, separated by each 'SettlementDate'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_date
|
DateScalar
|
The date for which the monthly trading data will be fetched. This date can be a string, datetime, or pandas Timestamp object. It will be converted to a date object. Only the year and month of this date will be used to download the corresponding monthly file. |
required |
extragroup
|
bool
|
If True, fetches only the trades that are considered 'extragroup' (between different economic groups)". If False, fetches all trades. Default is False. Extragroup trades are those where the transferring counterparty's conglomerate is different from the receiving counterparty's conglomerate, or when at least one of the counterparties does not belong to a conglomerate. In the case of funds, the conglomerate considered is that of the administrator. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: A DataFrame containing the bond trading data for the specified month. |
DataFrame columns
- SettlementDate: Date when the trade settled
- BondType: Security type abbreviation
- SelicCode: Unique code in the SELIC system
- ISIN: International Securities Identification Number
- IssueDate: Date when the security was issued
- MaturityDate: Security's maturity date
- Trades: Number of trades executed
- Quantity: Quantity traded
- Value: Value traded
- AvgPrice: Average price
- AvgRate: Average rate And additional trading metrics like min/max prices and rates.
Examples:
>>> from pyield import bc
>>> # Fetches all trades for Jan/2025
>>> bc.tpf_monthly_trades("07-01-2025", extragroup=True)
shape: (1_019, 19)
┌────────────────┬──────────┬───────────┬──────────────┬───┬─────────┬─────────┬─────────────────┬───────────────────┐
│ SettlementDate ┆ BondType ┆ SelicCode ┆ ISIN ┆ … ┆ AvgRate ┆ MaxRate ┆ BrokerageTrades ┆ BrokerageQuantity │
│ --- ┆ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ i64 ┆ str ┆ ┆ f64 ┆ f64 ┆ i64 ┆ i64 │
╞════════════════╪══════════╪═══════════╪══════════════╪═══╪═════════╪═════════╪═════════════════╪═══════════════════╡
│ 2025-01-02 ┆ LFT ┆ 210100 ┆ BRSTNCLF1RC4 ┆ … ┆ 0.0132 ┆ 0.0906 ┆ 2 ┆ 9581 │
│ 2025-01-02 ┆ LFT ┆ 210100 ┆ BRSTNCLF1RD2 ┆ … ┆ 0.0561 ┆ 0.101 ┆ 11 ┆ 42823 │
│ 2025-01-02 ┆ LFT ┆ 210100 ┆ BRSTNCLF1RE0 ┆ … ┆ 0.0191 ┆ 0.0405 ┆ 19 ┆ 33330 │
│ 2025-01-02 ┆ LFT ┆ 210100 ┆ BRSTNCLF1RF7 ┆ … ┆ 0.0304 ┆ 0.05 ┆ 10 ┆ 14583 │
│ 2025-01-02 ┆ LFT ┆ 210100 ┆ BRSTNCLF1RG5 ┆ … ┆ 0.0697 ┆ 0.0935 ┆ 12 ┆ 51776 │
│ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … ┆ … │
│ 2025-01-31 ┆ NTN-F ┆ 950199 ┆ BRSTNCNTF1P8 ┆ … ┆ null ┆ null ┆ 0 ┆ 0 │
│ 2025-01-31 ┆ NTN-F ┆ 950199 ┆ BRSTNCNTF1Q6 ┆ … ┆ null ┆ null ┆ 0 ┆ 0 │
│ 2025-01-31 ┆ NTN-F ┆ 950199 ┆ BRSTNCNTF204 ┆ … ┆ null ┆ null ┆ 12 ┆ 570000 │
│ 2025-01-31 ┆ NTN-F ┆ 950199 ┆ BRSTNCNTF212 ┆ … ┆ null ┆ null ┆ 0 ┆ 0 │
│ 2025-01-31 ┆ NTN-F ┆ 950199 ┆ BRSTNCNTF238 ┆ … ┆ null ┆ null ┆ 4 ┆ 115000 │
└────────────────┴──────────┴───────────┴──────────────┴───┴─────────┴─────────┴─────────────────┴───────────────────┘
Source code in pyield/bc/trades_monthly.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | |
vna_lft(date)
Retrieves the VNA (Valor Nominal Atualizado) from the BCB for a given date.
This function fetches daily data from the BCB website, extracts the VNA value from a specific table within the downloaded content, and returns this value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date
|
DateScalar
|
The date for which to retrieve the VNA value.
This argument accepts various date formats, including string and
datetime objects, which are then standardized using the
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The VNA (Valor Nominal Atualizado) value for the specified date, or None if the date is invalid or data is not available. |
Examples:
Raises:
| Type | Description |
|---|---|
ValueError
|
If the extracted VNA values from the BCB website are inconsistent (i.e., not all extracted values are identical), suggesting potential data discrepancies on the source website. The error message includes a link to the BCB website for manual verification. |
HTTPError
|
If the HTTP request to the BCB website fails. This could be due to network issues, website unavailability, or the requested data not being found for the given date. |