BCB Exchange Rate Service
The BCBExchangeRateService class offers a service to query the dollar exchange rate against the real directly from the official API of the Central Bank of Brazil (BCB).
On this page
#Overview
The BCBExchangeRateService class offers a service to query the dollar exchange rate against the real directly from the official API of the Central Bank of Brazil (BCB). This service is useful for developing financial applications, currency exchange systems, economic analysis and situations where up-to-date exchange rates need to be obtained automatically and programmatically.
The main feature of the class is to allow looking up the dollar exchange rate for specific dates, as well as making it easier to retrieve the best available rate within a range of past days, starting from the current date. This provides flexibility to capture values even when there is no rate on recent days, for example weekends or holidays.
In practice, a developer can instantiate the class and call the get_latest_rate method, defining how many previous days to consider when searching for the rate. The method returns the best rate and the corresponding date, making quick integrations with official data easier.
#Execution Flow
- Initialization: The user creates an instance of
BCBExchangeRateService, and can set a timeout for HTTP requests (default 10 seconds). - Call to the
get_latest_ratemethod: This method receives an optionalmax_days_backparameter that defines how many previous days to search for the rate. - Iterative search: For each day, starting from the current one and going back up to
max_days_back, the method makes a GET request to the BCB API using the URL format built for that date. - Response processing: If the API returns valid data, the method extracts the selling rate and the date of that rate.
- Comparison and selection: For each rate obtained, it checks whether it is the best (most recent) found so far and stores that information.
- Delay between requests: There is a small delay of 0.2 seconds between attempts so as not to overload the API.
- Returning the result: After going through the days, it returns a dictionary with the value of the best rate found and its date. If an error occurs, it returns
Nonevalues. - Logs: The process prints details of attempts, successes, failures and the final result to the console.
#Class Methods Table
| Method | Description |
|---|---|
__init__ | Initializes the instance by setting the request timeout. |
_build_url | Builds the API URL for a specific date. |
_fetch_rate_for_date | Performs the HTTP request to obtain the rate for a date. |
get_latest_rate | Searches for the best available rate within the defined range. |
#Environment Variables
No environment variables are used for this class to work.
#Key Architecture Points and Insights
- Encapsulation: The class explicitly separates URL building (
_build_url) and data retrieval (_fetch_rate_for_date) as private methods, keeping the public API clean. - Robustness: The code handles exceptions at several points to prevent request failures from compromising the overall operation.
- Respect for the API: Using delays between requests avoids overloading the BCB service.
- External dependency: Uses the
requestslibrary for HTTP communication, ensuring ease and robustness in the calls. - Good time practice: Uses UTC dates and formats the date to the standard expected by the API.
- Structured return value: Ensures consumability by returning a dictionary with
rateanddate, making integrations easier.
#Class and Methods Description
#BCBExchangeRateService Class
#Description
This class is responsible for querying US dollar exchange rates against the Brazilian real directly from the official API of the Central Bank of Brazil. It allows both querying values for specific dates and searching for the best rate within a period, supporting financial applications that need up-to-date and reliable data.
#Constructor Arguments
| Argument | Type | Description | Default Value |
|---|---|---|---|
timeout | int | Maximum time in seconds for HTTP requests | 10 |
#1. __init__
Description
Initializes an instance of the service by setting the maximum time for responses to the HTTP requests made to the BCB API.
Arguments
timeout(int): time limit in seconds for requests.
Returns
- Returns no value.
Raises
- None.
Examples
service = BCBExchangeRateService(timeout=5) # Timeout menor para conexões lentas#2. _build_url
Description
Private method that builds the query URL of the Central Bank API for a specific date, formatting the date in the required standard.
Arguments
date(datetime): date that will be queried in the API.
Returns
str: URL formatted to perform the query.
Raises
- None.
Examples
from datetime import datetime
service = BCBExchangeRateService()
url = service._build_url(datetime(2024, 6, 10))
print(url)
# Exemplo de saída:
# https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoDolarDia(dataCotacao=@dataCotacao)?@dataCotacao='06-10-2024'&$top=1&$format=json#3. _fetch_rate_for_date
Description
Private method that tries to fetch the dollar rate for a specific date using the Central Bank API. It returns the selling rate and the date of the rate on success.
Arguments
date(datetime): date for which the rate will be queried.
Returns
(float, datetime): a tuple containing the rate value (float) and the date of the rate (datetime).(None, None): if the rate cannot be obtained due to an error or lack of data.
Raises
- None explicitly, but possible exceptions are caught internally.
Examples
service = BCBExchangeRateService()
rate, date = service._fetch_rate_for_date(datetime(2024, 6, 10))
print(rate, date)
# Saída esperada (se houver cotação nessa data):
# 5.0892 2024-06-10 00:00:00#4. get_latest_rate
Description
Searches for the best dollar rate against the real available in the last max_days_back days from the moment of the call, returning the value and the date of the most recent rate found.
Arguments
max_days_back(int): number of previous days to search for the rate (default: 5).
Returns
dict: with the keys:rate(float or None): best rate found.date(datetime or None): date of that rate.
Raises
- None explicitly, errors are handled internally.
Examples
service = BCBExchangeRateService()
result = service.get_latest_rate(3)
print(f"Cotação: {result['rate']} em {result['date']}")
# Saída possível:
# Cotação: 5.0892 em 2024-06-10 00:00:00
# python -m src.tokens_calculate.bcbThus, the BCBExchangeRateService class is a practical and reliable solution for obtaining official commercial dollar rates, useful for any system that needs easy, programmatic access to this data.
Source: src/tokens_calculate/exchange_rate/bcb.py