Mudanças entre as edições de "BCBFinancialService"

De Wiki do Leitão
Ir para: navegação, pesquisa
(Criou página com '= BCBFinancialService = A classe <code>BCBFinancialService</code> é responsável por realizar a consulta de índices financeiros diretamente na API pública do Banco Central do Brasil (BCB). == Objetivo == Facilitar o acesso a séries históricas financeiras como: - Taxa SELIC (diária e mensal) - Cotação do Dólar (compra e venda) - Índice IPCA - Rentabilidade da Poupança (regra pós-2012) Sem a necessidade de configuração adicional de bibliotecas externas. T...')
 
 
Linha 19: Linha 19:
=== Métodos Públicos Disponíveis ===
=== Métodos Públicos Disponíveis ===


* <code>getSelicDailySeries(String startDate, String endDate)</code>   
* <code>getSelicDailySeries(LocalDate startDate, LocalDate endDate)</code>   
Retorna a série da Taxa SELIC diária no período informado.
Retorna a série da Taxa SELIC diária no período informado.


* <code>getSelicMonthlySeries(String startDate, String endDate)</code>   
* <code>getSelicMonthlySeries(LocalDate startDate, LocalDate endDate)</code>   
Retorna a série da Taxa SELIC mensal (taxa acumulada no mês).
Retorna a série da Taxa SELIC mensal (taxa acumulada no mês).


* <code>getDollarBuySeries(String startDate, String endDate)</code>   
* <code>getDollarBuySeries(LocalDate startDate, LocalDate endDate)</code>   
Retorna a série da cotação de compra do Dólar.
Retorna a série da cotação de compra do Dólar.


* <code>getDollarSellSeries(String startDate, String endDate)</code>   
* <code>getDollarSellSeries(LocalDate startDate, LocalDate endDate)</code>   
Retorna a série da cotação de venda do Dólar.
Retorna a série da cotação de venda do Dólar.


* <code>getIPCASeries(String startDate, String endDate)</code>   
* <code>getIPCASeries(LocalDate startDate, LocalDate endDate)</code>   
Retorna a série histórica do índice IPCA.
Retorna a série histórica do índice IPCA.


* <code>getPoupanca2012Series(String startDate, String endDate)</code>   
* <code>getPoupanca2012Series(LocalDate startDate, LocalDate endDate)</code>   
Retorna a série histórica da rentabilidade da poupança segundo regra pós-2012.
Retorna a série histórica da rentabilidade da poupança segundo regra pós-2012.


Todos os métodos recebem:
Todos os métodos recebem:
- <code>startDate</code>: Data inicial no formato <code>dd/MM/yyyy</code>
- <code>startDate</code>: Data inicial como <code>LocalDate</code>.
- <code>endDate</code>: Data final no formato <code>dd/MM/yyyy</code>
- <code>endDate</code>: Data final como <code>LocalDate</code>.


E retornam uma <code>List&lt;FinancialIndexEntry&gt;</code> contendo data e valor.
E retornam uma <code>List&lt;FinancialIndexEntry&gt;</code> contendo data e valor.
Linha 48: Linha 48:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
import java.time.LocalDate;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.List;
import br.eng.rodrigogml.rfw.finance.fetcher.BCBFinancialService;
import br.eng.rodrigogml.rfw.finance.fetcher.BCBFinancialService;
Linha 61: Linha 60:
             LocalDate inicio = hoje.minusMonths(1);
             LocalDate inicio = hoje.minusMonths(1);


            String dataInicio = inicio.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
             List<FinancialIndexEntry> selicDiaria = BCBFinancialService.getSelicDailySeries(inicio, hoje);
            String dataFim = hoje.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
 
             List<FinancialIndexEntry> selicDiaria = BCBFinancialService.getSelicDailySeries(dataInicio, dataFim);


             for (FinancialIndexEntry entry : selicDiaria) {
             for (FinancialIndexEntry entry : selicDiaria) {
Linha 78: Linha 74:
=== Consultar a cotação de compra do Dólar ===
=== Consultar a cotação de compra do Dólar ===
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
import java.time.LocalDate;
import java.util.List;
import br.eng.rodrigogml.rfw.finance.fetcher.BCBFinancialService;
import br.eng.rodrigogml.rfw.finance.fetcher.BCBFinancialService;
import br.eng.rodrigogml.rfw.finance.fetcher.FinancialIndexEntry;
import br.eng.rodrigogml.rfw.finance.fetcher.FinancialIndexEntry;
import java.util.List;
import br.eng.rodrigogml.rfw.kernel.exceptions.RFWException;


public class ExemploDolarCompra {
public class ExemploDolarCompra {
Linha 86: Linha 84:
     public static void main(String[] args) {
     public static void main(String[] args) {
         try {
         try {
             List<FinancialIndexEntry> dolarCompra = BCBFinancialService.getDollarBuySeries("01/04/2025", "29/04/2025");
            LocalDate inicio = LocalDate.of(2025, 4, 1);
            LocalDate fim = LocalDate.of(2025, 4, 29);
 
             List<FinancialIndexEntry> dolarCompra = BCBFinancialService.getDollarBuySeries(inicio, fim);


             for (FinancialIndexEntry entry : dolarCompra) {
             for (FinancialIndexEntry entry : dolarCompra) {
                 System.out.println(entry.getDate() + ": " + entry.getValue());
                 System.out.println(entry.getDate() + ": " + entry.getValue());
             }
             }
         } catch (Exception e) {
         } catch (RFWException e) {
             e.printStackTrace();
             e.printStackTrace();
         }
         }

Edição atual tal como às 13h14min de 29 de abril de 2025

BCBFinancialService

A classe BCBFinancialService é responsável por realizar a consulta de índices financeiros diretamente na API pública do Banco Central do Brasil (BCB).

Objetivo

Facilitar o acesso a séries históricas financeiras como: - Taxa SELIC (diária e mensal) - Cotação do Dólar (compra e venda) - Índice IPCA - Rentabilidade da Poupança (regra pós-2012)

Sem a necessidade de configuração adicional de bibliotecas externas. Toda comunicação é feita via HTTP(S) e interpretada via JSON nativo.

Principais Funcionalidades

A classe é utilitária (não deve ser instanciada) e expõe métodos estáticos para consulta de diferentes séries financeiras.

Métodos Públicos Disponíveis

  • getSelicDailySeries(LocalDate startDate, LocalDate endDate)

Retorna a série da Taxa SELIC diária no período informado.

  • getSelicMonthlySeries(LocalDate startDate, LocalDate endDate)

Retorna a série da Taxa SELIC mensal (taxa acumulada no mês).

  • getDollarBuySeries(LocalDate startDate, LocalDate endDate)

Retorna a série da cotação de compra do Dólar.

  • getDollarSellSeries(LocalDate startDate, LocalDate endDate)

Retorna a série da cotação de venda do Dólar.

  • getIPCASeries(LocalDate startDate, LocalDate endDate)

Retorna a série histórica do índice IPCA.

  • getPoupanca2012Series(LocalDate startDate, LocalDate endDate)

Retorna a série histórica da rentabilidade da poupança segundo regra pós-2012.

Todos os métodos recebem: - startDate: Data inicial como LocalDate. - endDate: Data final como LocalDate.

E retornam uma List<FinancialIndexEntry> contendo data e valor.

Exemplos de Uso

Consultar a taxa SELIC diária dos últimos 30 dias

import java.time.LocalDate;
import java.util.List;
import br.eng.rodrigogml.rfw.finance.fetcher.BCBFinancialService;
import br.eng.rodrigogml.rfw.finance.fetcher.FinancialIndexEntry;
import br.eng.rodrigogml.rfw.kernel.exceptions.RFWException;

public class ExemploSelic {

    public static void main(String[] args) {
        try {
            LocalDate hoje = LocalDate.now();
            LocalDate inicio = hoje.minusMonths(1);

            List<FinancialIndexEntry> selicDiaria = BCBFinancialService.getSelicDailySeries(inicio, hoje);

            for (FinancialIndexEntry entry : selicDiaria) {
                System.out.println(entry.getDate() + ": " + entry.getValue());
            }
        } catch (RFWException e) {
            e.printStackTrace();
        }
    }
}

Consultar a cotação de compra do Dólar

import java.time.LocalDate;
import java.util.List;
import br.eng.rodrigogml.rfw.finance.fetcher.BCBFinancialService;
import br.eng.rodrigogml.rfw.finance.fetcher.FinancialIndexEntry;
import br.eng.rodrigogml.rfw.kernel.exceptions.RFWException;

public class ExemploDolarCompra {

    public static void main(String[] args) {
        try {
            LocalDate inicio = LocalDate.of(2025, 4, 1);
            LocalDate fim = LocalDate.of(2025, 4, 29);

            List<FinancialIndexEntry> dolarCompra = BCBFinancialService.getDollarBuySeries(inicio, fim);

            for (FinancialIndexEntry entry : dolarCompra) {
                System.out.println(entry.getDate() + ": " + entry.getValue());
            }
        } catch (RFWException e) {
            e.printStackTrace();
        }
    }
}

Observações Importantes

- É importante validar limites de requisições impostos pela API pública do BCB.