python-bcb 0.3.3__py3-none-any.whl → 0.3.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bcb/__init__.py +10 -1
- bcb/currency.py +819 -79
- bcb/exceptions.py +43 -0
- bcb/http.py +98 -0
- bcb/odata/__init__.py +3 -1
- bcb/odata/api.py +248 -48
- bcb/odata/framework.py +203 -132
- bcb/sgs/__init__.py +332 -35
- bcb/sgs/regional_economy.py +16 -4
- bcb/utils.py +10 -6
- python_bcb-0.3.6.dist-info/METADATA +191 -0
- python_bcb-0.3.6.dist-info/RECORD +14 -0
- {python_bcb-0.3.3.dist-info → python_bcb-0.3.6.dist-info}/WHEEL +1 -1
- python_bcb-0.3.3.dist-info/METADATA +0 -77
- python_bcb-0.3.3.dist-info/RECORD +0 -12
- {python_bcb-0.3.3.dist-info → python_bcb-0.3.6.dist-info/licenses}/LICENSE +0 -0
bcb/currency.py
CHANGED
|
@@ -1,113 +1,358 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
1
5
|
import re
|
|
2
|
-
import
|
|
6
|
+
import threading
|
|
3
7
|
from datetime import date, timedelta
|
|
4
8
|
from io import BytesIO, StringIO
|
|
5
|
-
from typing import List, Union
|
|
9
|
+
from typing import TYPE_CHECKING, Dict, List, Literal, NamedTuple, Union, overload
|
|
10
|
+
from urllib.parse import urlencode
|
|
6
11
|
|
|
7
12
|
import numpy as np
|
|
8
13
|
import pandas as pd
|
|
9
|
-
import requests
|
|
10
14
|
from lxml import html
|
|
11
15
|
|
|
12
|
-
from .
|
|
16
|
+
from bcb.http import _CLIENT, _ASYNC_CLIENT
|
|
17
|
+
from bcb.exceptions import (
|
|
18
|
+
BCBAPIError,
|
|
19
|
+
BCBAPINotFoundError,
|
|
20
|
+
BCBRateLimitError,
|
|
21
|
+
CurrencyNotFoundError,
|
|
22
|
+
)
|
|
23
|
+
from bcb.utils import Date, DateInput
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
import httpx
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
13
29
|
|
|
14
30
|
"""
|
|
15
31
|
O módulo :py:mod:`bcb.currency` tem como objetivo fazer consultas no site do conversor de moedas do BCB.
|
|
16
32
|
"""
|
|
17
33
|
|
|
18
34
|
|
|
19
|
-
def _currency_url(currency_id:
|
|
35
|
+
def _currency_url(currency_id: int, start_date: DateInput, end_date: DateInput) -> str:
|
|
20
36
|
start_date = Date(start_date)
|
|
21
37
|
end_date = Date(end_date)
|
|
22
|
-
|
|
38
|
+
params = urlencode(
|
|
39
|
+
{
|
|
40
|
+
"method": "gerarCSVFechamentoMoedaNoPeriodo",
|
|
41
|
+
"ChkMoeda": currency_id,
|
|
42
|
+
"DATAINI": start_date.date.strftime("%d/%m/%Y"),
|
|
43
|
+
"DATAFIM": end_date.date.strftime("%d/%m/%Y"),
|
|
44
|
+
}
|
|
45
|
+
)
|
|
46
|
+
return f"https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?{params}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _CacheKey(NamedTuple):
|
|
50
|
+
"""Structured cache key for currency module.
|
|
51
|
+
|
|
52
|
+
Attributes
|
|
53
|
+
----------
|
|
54
|
+
type : str
|
|
55
|
+
Cache type: "currency_id_list" or "currency_list"
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
type: str
|
|
59
|
+
|
|
60
|
+
def __repr__(self) -> str:
|
|
61
|
+
return f"CacheKey(type={self.type!r})"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _ThreadSafeCache:
|
|
65
|
+
"""Thread-safe cache wrapper for currency data.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
initial_data : dict, optional
|
|
70
|
+
Initial cache data (default: empty)
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, initial_data: dict[_CacheKey, pd.DataFrame] | None = None):
|
|
74
|
+
self._lock = threading.RLock()
|
|
75
|
+
self._data: dict[_CacheKey, pd.DataFrame] = initial_data or {}
|
|
76
|
+
|
|
77
|
+
def get(self, key: _CacheKey) -> pd.DataFrame | None:
|
|
78
|
+
"""Get value from cache.
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
key : _CacheKey
|
|
83
|
+
Cache key
|
|
84
|
+
|
|
85
|
+
Returns
|
|
86
|
+
-------
|
|
87
|
+
pd.DataFrame | None
|
|
88
|
+
Cached DataFrame or None if not found
|
|
89
|
+
"""
|
|
90
|
+
with self._lock:
|
|
91
|
+
return self._data.get(key)
|
|
92
|
+
|
|
93
|
+
def set(self, key: _CacheKey, value: pd.DataFrame) -> None:
|
|
94
|
+
"""Set value in cache.
|
|
95
|
+
|
|
96
|
+
Parameters
|
|
97
|
+
----------
|
|
98
|
+
key : _CacheKey
|
|
99
|
+
Cache key
|
|
100
|
+
value : pd.DataFrame
|
|
101
|
+
DataFrame to cache
|
|
102
|
+
"""
|
|
103
|
+
with self._lock:
|
|
104
|
+
self._data[key] = value
|
|
105
|
+
|
|
106
|
+
def clear(self) -> None:
|
|
107
|
+
"""Clear all cache entries."""
|
|
108
|
+
with self._lock:
|
|
109
|
+
self._data.clear()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# Default module-level cache instance
|
|
113
|
+
_DEFAULT_CACHE = _ThreadSafeCache()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def clear_cache(cache: _ThreadSafeCache | None = None) -> None:
|
|
117
|
+
"""Clear the module-level session cache.
|
|
118
|
+
|
|
119
|
+
:func:`get` and :func:`get_currency_list` cache the currency ID list and
|
|
120
|
+
the full currency master table for the duration of the Python session so
|
|
121
|
+
that repeated calls do not make redundant HTTP requests. Call this
|
|
122
|
+
function to force a fresh fetch on the next request (useful in tests or
|
|
123
|
+
long-running scripts where the master data may have changed).
|
|
124
|
+
|
|
125
|
+
Parameters
|
|
126
|
+
----------
|
|
127
|
+
cache : _ThreadSafeCache, optional
|
|
128
|
+
Cache instance to clear. If None, uses module-level default.
|
|
129
|
+
"""
|
|
130
|
+
(cache or _DEFAULT_CACHE).clear()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _currency_id_list(
|
|
134
|
+
cache: _ThreadSafeCache | None = None,
|
|
135
|
+
) -> pd.DataFrame:
|
|
136
|
+
"""Fetch list of available currency IDs and names.
|
|
137
|
+
|
|
138
|
+
Parameters
|
|
139
|
+
----------
|
|
140
|
+
cache : _ThreadSafeCache, optional
|
|
141
|
+
Cache instance to use. If None, uses module-level default.
|
|
142
|
+
|
|
143
|
+
Returns
|
|
144
|
+
-------
|
|
145
|
+
pd.DataFrame
|
|
146
|
+
DataFrame with columns: name, id
|
|
147
|
+
|
|
148
|
+
Raises
|
|
149
|
+
------
|
|
150
|
+
BCBRateLimitError
|
|
151
|
+
If API rate limit is exceeded (429)
|
|
152
|
+
BCBAPINotFoundError
|
|
153
|
+
If API endpoint not found (404)
|
|
154
|
+
BCBAPIError
|
|
155
|
+
If API returns error response
|
|
156
|
+
"""
|
|
157
|
+
cache = cache or _DEFAULT_CACHE
|
|
158
|
+
cache_key = _CacheKey(type="currency_id_list")
|
|
159
|
+
cached = cache.get(cache_key)
|
|
160
|
+
if cached is not None:
|
|
161
|
+
return cached
|
|
162
|
+
|
|
163
|
+
url1 = (
|
|
23
164
|
"https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
|
|
24
|
-
"method=
|
|
25
|
-
"ChkMoeda={}&DATAINI={:%d/%m/%Y}&DATAFIM={:%d/%m/%Y}"
|
|
165
|
+
"method=exibeFormularioConsultaBoletim"
|
|
26
166
|
)
|
|
27
|
-
|
|
167
|
+
logger.debug(f"Fetching currency ID list from {url1}")
|
|
168
|
+
res = _CLIENT.get(url1)
|
|
169
|
+
logger.debug(
|
|
170
|
+
f"Currency ID list response: status={res.status_code}, length={len(res.content)}"
|
|
171
|
+
)
|
|
172
|
+
if res.status_code == 429:
|
|
173
|
+
raise BCBRateLimitError(
|
|
174
|
+
"BCB API rate limit exceeded. Please try again later.",
|
|
175
|
+
status_code=429,
|
|
176
|
+
)
|
|
177
|
+
if res.status_code == 404:
|
|
178
|
+
raise BCBAPINotFoundError(
|
|
179
|
+
"BCB API endpoint not found (404)",
|
|
180
|
+
status_code=404,
|
|
181
|
+
)
|
|
182
|
+
if res.status_code >= 500:
|
|
183
|
+
raise BCBAPIError(
|
|
184
|
+
f"BCB API server error (status {res.status_code})",
|
|
185
|
+
status_code=res.status_code,
|
|
186
|
+
)
|
|
187
|
+
if res.status_code != 200:
|
|
188
|
+
msg = f"BCB API Request error, status code = {res.status_code}"
|
|
189
|
+
raise BCBAPIError(msg, res.status_code)
|
|
28
190
|
|
|
191
|
+
doc = html.parse(BytesIO(res.content)).getroot()
|
|
192
|
+
xpath = "//select[@name='ChkMoeda']/option"
|
|
193
|
+
x = [(elm.text, elm.get("value")) for elm in doc.xpath(xpath)]
|
|
194
|
+
df = pd.DataFrame(x, columns=["name", "id"])
|
|
195
|
+
df["id"] = df["id"].astype("int32")
|
|
196
|
+
cache.set(cache_key, df)
|
|
197
|
+
return df
|
|
29
198
|
|
|
30
|
-
CACHE = dict()
|
|
31
199
|
|
|
200
|
+
def _get_valid_currency_list(
|
|
201
|
+
_date: date, n: int = 0, max_rollback: int = 30
|
|
202
|
+
) -> "httpx.Response":
|
|
203
|
+
"""Fetch currency list CSV, rolling back dates if necessary.
|
|
32
204
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
url1 = "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?" "method=exibeFormularioConsultaBoletim"
|
|
38
|
-
res = requests.get(url1)
|
|
39
|
-
if res.status_code != 200:
|
|
40
|
-
msg = f"BCB API Request error, status code = {res.status_code}"
|
|
41
|
-
raise Exception(msg)
|
|
205
|
+
Attempts to fetch the currency master file for the given date.
|
|
206
|
+
If the file doesn't exist (common for weekends/holidays), rolls back
|
|
207
|
+
to the previous day and retries. Connection errors trigger retries
|
|
208
|
+
on the same date.
|
|
42
209
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
210
|
+
Parameters
|
|
211
|
+
----------
|
|
212
|
+
_date : date
|
|
213
|
+
Target date to fetch
|
|
214
|
+
n : int
|
|
215
|
+
Current connection retry attempt (internal use)
|
|
216
|
+
max_rollback : int
|
|
217
|
+
Maximum number of days to roll back before giving up
|
|
218
|
+
|
|
219
|
+
Returns
|
|
220
|
+
-------
|
|
221
|
+
httpx.Response
|
|
222
|
+
Response object with CSV content
|
|
50
223
|
|
|
224
|
+
Raises
|
|
225
|
+
------
|
|
226
|
+
BCBAPIError
|
|
227
|
+
If unable to fetch after max rollback days exceeded
|
|
228
|
+
"""
|
|
229
|
+
# Check if we've rolled back too far
|
|
230
|
+
days_rolled_back = (date.today() - _date).days
|
|
231
|
+
if days_rolled_back > max_rollback:
|
|
232
|
+
raise BCBAPIError(
|
|
233
|
+
f"No currency list available in last {max_rollback} days",
|
|
234
|
+
status_code=503, # Service Unavailable
|
|
235
|
+
)
|
|
51
236
|
|
|
52
|
-
|
|
53
|
-
|
|
237
|
+
url2 = f"https://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
|
|
238
|
+
logger.debug(f"Fetching currency list from {url2}")
|
|
54
239
|
try:
|
|
55
|
-
res =
|
|
56
|
-
except
|
|
240
|
+
res = _CLIENT.get(url2)
|
|
241
|
+
except Exception as ex:
|
|
242
|
+
# Connection error: retry same date up to 3 times
|
|
57
243
|
if n >= 3:
|
|
58
244
|
raise ex
|
|
59
|
-
|
|
245
|
+
logger.warning(
|
|
246
|
+
f"Connection error fetching {url2}, retrying (attempt {n + 1}/3)"
|
|
247
|
+
)
|
|
248
|
+
return _get_valid_currency_list(_date, n + 1, max_rollback)
|
|
249
|
+
|
|
250
|
+
logger.debug(
|
|
251
|
+
f"Currency list response: status={res.status_code}, length={len(res.content)}"
|
|
252
|
+
)
|
|
60
253
|
if res.status_code == 200:
|
|
61
254
|
return res
|
|
62
255
|
else:
|
|
63
|
-
|
|
256
|
+
# Non-200 response (file not found for date): roll back to previous day
|
|
257
|
+
logger.debug(
|
|
258
|
+
f"Currency list not found for {_date}, rolling back to previous day"
|
|
259
|
+
)
|
|
260
|
+
return _get_valid_currency_list(_date - timedelta(1), 0, max_rollback)
|
|
64
261
|
|
|
65
262
|
|
|
66
|
-
def get_currency_list(
|
|
67
|
-
|
|
68
|
-
|
|
263
|
+
def get_currency_list(
|
|
264
|
+
cache: _ThreadSafeCache | None = None,
|
|
265
|
+
) -> pd.DataFrame:
|
|
266
|
+
"""Listagem com todas as moedas disponíveis na API e suas configurações de paridade.
|
|
267
|
+
|
|
268
|
+
Parameters
|
|
269
|
+
----------
|
|
270
|
+
cache : _ThreadSafeCache, optional
|
|
271
|
+
Cache instance to use. If None, uses module-level default.
|
|
69
272
|
|
|
70
273
|
Returns
|
|
71
274
|
-------
|
|
72
|
-
|
|
73
|
-
DataFrame :
|
|
275
|
+
pd.DataFrame
|
|
74
276
|
Tabela com a listagem de moedas disponíveis.
|
|
277
|
+
|
|
278
|
+
Raises
|
|
279
|
+
------
|
|
280
|
+
BCBAPIError
|
|
281
|
+
If API returns error response
|
|
75
282
|
"""
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
283
|
+
cache = cache or _DEFAULT_CACHE
|
|
284
|
+
cache_key = _CacheKey(type="currency_list")
|
|
285
|
+
cached = cache.get(cache_key)
|
|
286
|
+
if cached is not None:
|
|
287
|
+
return cached
|
|
288
|
+
|
|
289
|
+
res = _get_valid_currency_list(date.today())
|
|
290
|
+
df = pd.read_csv(StringIO(res.text), delimiter=";")
|
|
291
|
+
df.columns = [
|
|
292
|
+
"code",
|
|
293
|
+
"name",
|
|
294
|
+
"symbol",
|
|
295
|
+
"country_code",
|
|
296
|
+
"country_name",
|
|
297
|
+
"type",
|
|
298
|
+
"exclusion_date",
|
|
299
|
+
]
|
|
300
|
+
df = df.loc[~df["country_code"].isna()]
|
|
301
|
+
df["exclusion_date"] = pd.to_datetime(df["exclusion_date"], dayfirst=True)
|
|
302
|
+
df["country_code"] = df["country_code"].astype("int32")
|
|
303
|
+
df["code"] = df["code"].astype("int32")
|
|
304
|
+
df["symbol"] = df["symbol"].str.strip()
|
|
305
|
+
cache.set(cache_key, df)
|
|
306
|
+
return df
|
|
97
307
|
|
|
98
308
|
|
|
99
309
|
def _get_currency_id(symbol: str) -> int:
|
|
100
310
|
id_list = _currency_id_list()
|
|
101
311
|
all_currencies = get_currency_list()
|
|
102
312
|
x = pd.merge(id_list, all_currencies, on=["name"])
|
|
103
|
-
|
|
313
|
+
matches = x.loc[x["symbol"] == symbol, "id"]
|
|
314
|
+
if matches.empty:
|
|
315
|
+
raise CurrencyNotFoundError(f"Unknown currency symbol: {symbol}")
|
|
316
|
+
return int(matches.max())
|
|
317
|
+
|
|
104
318
|
|
|
319
|
+
def _fetch_symbol_response(
|
|
320
|
+
symbol: str, start_date: DateInput, end_date: DateInput
|
|
321
|
+
) -> "httpx.Response":
|
|
322
|
+
"""Fetch exchange rate CSV response for a symbol.
|
|
105
323
|
|
|
106
|
-
|
|
107
|
-
|
|
324
|
+
Parameters
|
|
325
|
+
----------
|
|
326
|
+
symbol : str
|
|
327
|
+
Currency symbol (e.g., 'USD')
|
|
328
|
+
start_date : DateInput
|
|
329
|
+
Start date for the query
|
|
330
|
+
end_date : DateInput
|
|
331
|
+
End date for the query
|
|
332
|
+
|
|
333
|
+
Returns
|
|
334
|
+
-------
|
|
335
|
+
httpx.Response
|
|
336
|
+
Response object with CSV content
|
|
337
|
+
|
|
338
|
+
Raises
|
|
339
|
+
------
|
|
340
|
+
CurrencyNotFoundError
|
|
341
|
+
If the currency symbol is not found
|
|
342
|
+
BCBRateLimitError
|
|
343
|
+
If API rate limit is exceeded (429)
|
|
344
|
+
BCBAPIError
|
|
345
|
+
If API returns other error status codes or HTML error page
|
|
346
|
+
"""
|
|
347
|
+
cid = _get_currency_id(symbol) # Raises CurrencyNotFoundError if not found
|
|
108
348
|
url = _currency_url(cid, start_date, end_date)
|
|
109
|
-
|
|
349
|
+
logger.debug(f"Fetching currency data for {symbol} from {url.split('?')[0]}")
|
|
350
|
+
res = _CLIENT.get(url)
|
|
351
|
+
logger.debug(
|
|
352
|
+
f"Currency data response: status={res.status_code}, length={len(res.content)}"
|
|
353
|
+
)
|
|
110
354
|
|
|
355
|
+
# Handle HTML error response (e.g., no data for date range)
|
|
111
356
|
if res.headers["Content-Type"].startswith("text/html"):
|
|
112
357
|
doc = html.parse(BytesIO(res.content)).getroot()
|
|
113
358
|
xpath = "//div[@class='msgErro']"
|
|
@@ -115,17 +360,151 @@ def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.D
|
|
|
115
360
|
x = elm.text
|
|
116
361
|
x = re.sub(r"^\W+", "", x)
|
|
117
362
|
x = re.sub(r"\W+$", "", x)
|
|
118
|
-
msg = "BCB API returned error: {} - {}"
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
363
|
+
msg = f"BCB API returned error: {x} - {symbol}"
|
|
364
|
+
raise BCBAPIError(msg, status_code=400)
|
|
365
|
+
|
|
366
|
+
# Handle HTTP error responses
|
|
367
|
+
if res.status_code == 429:
|
|
368
|
+
raise BCBRateLimitError(
|
|
369
|
+
"BCB API rate limit exceeded. Please try again later.",
|
|
370
|
+
status_code=429,
|
|
371
|
+
)
|
|
372
|
+
if res.status_code == 404:
|
|
373
|
+
raise BCBAPINotFoundError(
|
|
374
|
+
f"Currency data not found for {symbol}",
|
|
375
|
+
status_code=404,
|
|
376
|
+
)
|
|
377
|
+
if res.status_code >= 500:
|
|
378
|
+
raise BCBAPIError(
|
|
379
|
+
f"BCB API server error (status {res.status_code})",
|
|
380
|
+
status_code=res.status_code,
|
|
381
|
+
)
|
|
382
|
+
if res.status_code != 200:
|
|
383
|
+
raise BCBAPIError(
|
|
384
|
+
f"BCB API request failed with status {res.status_code}",
|
|
385
|
+
status_code=res.status_code,
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
return res
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _validate_currency_csv(csv_text: str) -> pd.DataFrame:
|
|
392
|
+
"""Parse and validate currency CSV format.
|
|
393
|
+
|
|
394
|
+
Parameters
|
|
395
|
+
----------
|
|
396
|
+
csv_text : str
|
|
397
|
+
CSV content from BCB API
|
|
398
|
+
|
|
399
|
+
Returns
|
|
400
|
+
-------
|
|
401
|
+
pd.DataFrame
|
|
402
|
+
Parsed DataFrame with all columns
|
|
403
|
+
|
|
404
|
+
Raises
|
|
405
|
+
------
|
|
406
|
+
BCBAPIError
|
|
407
|
+
If CSV format is invalid (wrong column count)
|
|
408
|
+
"""
|
|
409
|
+
df = pd.read_csv(StringIO(csv_text), delimiter=";", header=None, dtype=str)
|
|
410
|
+
|
|
411
|
+
# Validate column count
|
|
412
|
+
if len(df.columns) != 8:
|
|
413
|
+
raise BCBAPIError(
|
|
414
|
+
f"Invalid CSV format: expected 8 columns, got {len(df.columns)}",
|
|
415
|
+
status_code=400,
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
# Assign meaningful names
|
|
419
|
+
df.columns = ["Date", "_col1", "_col2", "_col3", "bid", "ask", "_col6", "_col7"]
|
|
420
|
+
return df
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _parse_currency_dates(df: pd.DataFrame) -> pd.DataFrame:
|
|
424
|
+
"""Parse and validate date column in currency CSV.
|
|
425
|
+
|
|
426
|
+
Parameters
|
|
427
|
+
----------
|
|
428
|
+
df : pd.DataFrame
|
|
429
|
+
DataFrame with Date column as strings
|
|
430
|
+
|
|
431
|
+
Returns
|
|
432
|
+
-------
|
|
433
|
+
pd.DataFrame
|
|
434
|
+
DataFrame with parsed DatetimeIndex
|
|
435
|
+
|
|
436
|
+
Raises
|
|
437
|
+
------
|
|
438
|
+
BCBAPIError
|
|
439
|
+
If date parsing fails
|
|
440
|
+
"""
|
|
441
|
+
try:
|
|
442
|
+
df["Date"] = pd.to_datetime(df["Date"], format="%d%m%Y")
|
|
443
|
+
except ValueError as e:
|
|
444
|
+
raise BCBAPIError(
|
|
445
|
+
f"Failed to parse currency date column: {str(e)}", status_code=400
|
|
446
|
+
)
|
|
447
|
+
return df
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _parse_currency_types(df: pd.DataFrame) -> pd.DataFrame:
|
|
451
|
+
"""Parse and validate data types in currency DataFrame.
|
|
452
|
+
|
|
453
|
+
Parameters
|
|
454
|
+
----------
|
|
455
|
+
df : pd.DataFrame
|
|
456
|
+
DataFrame with mixed types
|
|
457
|
+
|
|
458
|
+
Returns
|
|
459
|
+
-------
|
|
460
|
+
pd.DataFrame
|
|
461
|
+
DataFrame with validated types
|
|
462
|
+
|
|
463
|
+
Raises
|
|
464
|
+
------
|
|
465
|
+
BCBAPIError
|
|
466
|
+
If type conversion fails
|
|
467
|
+
"""
|
|
468
|
+
try:
|
|
469
|
+
df["bid"] = df["bid"].str.replace(",", ".").astype(np.float64)
|
|
470
|
+
df["ask"] = df["ask"].str.replace(",", ".").astype(np.float64)
|
|
471
|
+
except (ValueError, TypeError) as e:
|
|
472
|
+
raise BCBAPIError(
|
|
473
|
+
f"Failed to parse currency numeric columns: {str(e)}", status_code=400
|
|
474
|
+
)
|
|
475
|
+
return df
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _get_symbol(
|
|
479
|
+
symbol: str, start_date: DateInput, end_date: DateInput
|
|
480
|
+
) -> pd.DataFrame:
|
|
481
|
+
"""Fetch and parse exchange rate data for a symbol.
|
|
482
|
+
|
|
483
|
+
Parameters
|
|
484
|
+
----------
|
|
485
|
+
symbol : str
|
|
486
|
+
Currency symbol
|
|
487
|
+
start_date : DateInput
|
|
488
|
+
Start date
|
|
489
|
+
end_date : DateInput
|
|
490
|
+
End date
|
|
491
|
+
|
|
492
|
+
Returns
|
|
493
|
+
-------
|
|
494
|
+
pd.DataFrame
|
|
495
|
+
DataFrame with exchange rate data
|
|
496
|
+
|
|
497
|
+
Raises
|
|
498
|
+
------
|
|
499
|
+
CurrencyNotFoundError
|
|
500
|
+
If currency not found
|
|
501
|
+
BCBAPIError
|
|
502
|
+
If API returns error or data format is invalid
|
|
503
|
+
"""
|
|
504
|
+
res = _fetch_symbol_response(symbol, start_date, end_date)
|
|
505
|
+
df = _validate_currency_csv(res.text)
|
|
506
|
+
df = _parse_currency_dates(df)
|
|
507
|
+
df = _parse_currency_types(df)
|
|
129
508
|
df1 = df.set_index("Date")
|
|
130
509
|
n = ["bid", "ask"]
|
|
131
510
|
df1 = df1[n]
|
|
@@ -134,9 +513,90 @@ def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.D
|
|
|
134
513
|
return df1
|
|
135
514
|
|
|
136
515
|
|
|
516
|
+
def _get_symbol_text(symbol: str, start_date: DateInput, end_date: DateInput) -> str:
|
|
517
|
+
"""Fetch exchange rate data as CSV text for a symbol.
|
|
518
|
+
|
|
519
|
+
Parameters
|
|
520
|
+
----------
|
|
521
|
+
symbol : str
|
|
522
|
+
Currency symbol
|
|
523
|
+
start_date : DateInput
|
|
524
|
+
Start date
|
|
525
|
+
end_date : DateInput
|
|
526
|
+
End date
|
|
527
|
+
|
|
528
|
+
Returns
|
|
529
|
+
-------
|
|
530
|
+
str
|
|
531
|
+
CSV text with exchange rate data
|
|
532
|
+
|
|
533
|
+
Raises
|
|
534
|
+
------
|
|
535
|
+
CurrencyNotFoundError
|
|
536
|
+
If currency not found
|
|
537
|
+
BCBAPIError
|
|
538
|
+
If API returns error
|
|
539
|
+
"""
|
|
540
|
+
res = _fetch_symbol_response(symbol, start_date, end_date)
|
|
541
|
+
return res.text
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
# Type alias for text output with multiple symbols
|
|
545
|
+
CurrencyTextResult = Dict[str, str] # Maps symbol → CSV text
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
@overload
|
|
137
549
|
def get(
|
|
138
|
-
symbols:
|
|
139
|
-
|
|
550
|
+
symbols: str,
|
|
551
|
+
start: DateInput,
|
|
552
|
+
end: DateInput,
|
|
553
|
+
side: str = ...,
|
|
554
|
+
groupby: str = ...,
|
|
555
|
+
output: Literal["dataframe"] = ...,
|
|
556
|
+
) -> pd.DataFrame: ...
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
@overload
|
|
560
|
+
def get(
|
|
561
|
+
symbols: List[str],
|
|
562
|
+
start: DateInput,
|
|
563
|
+
end: DateInput,
|
|
564
|
+
side: str = ...,
|
|
565
|
+
groupby: str = ...,
|
|
566
|
+
output: Literal["dataframe"] = ...,
|
|
567
|
+
) -> pd.DataFrame: ...
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
@overload
|
|
571
|
+
def get(
|
|
572
|
+
symbols: str,
|
|
573
|
+
start: DateInput,
|
|
574
|
+
end: DateInput,
|
|
575
|
+
side: str = ...,
|
|
576
|
+
groupby: str = ...,
|
|
577
|
+
output: Literal["text"] = ...,
|
|
578
|
+
) -> str: ...
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
@overload
|
|
582
|
+
def get(
|
|
583
|
+
symbols: List[str],
|
|
584
|
+
start: DateInput,
|
|
585
|
+
end: DateInput,
|
|
586
|
+
side: str = ...,
|
|
587
|
+
groupby: str = ...,
|
|
588
|
+
output: Literal["text"] = ...,
|
|
589
|
+
) -> CurrencyTextResult: ...
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def get(
|
|
593
|
+
symbols: Union[str, List[str]],
|
|
594
|
+
start: DateInput,
|
|
595
|
+
end: DateInput,
|
|
596
|
+
side: str = "ask",
|
|
597
|
+
groupby: str = "symbol",
|
|
598
|
+
output: str = "dataframe",
|
|
599
|
+
) -> Union[pd.DataFrame, str, Dict[str, str]]:
|
|
140
600
|
"""
|
|
141
601
|
Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
|
|
142
602
|
|
|
@@ -163,16 +623,294 @@ def get(
|
|
|
163
623
|
Returns
|
|
164
624
|
-------
|
|
165
625
|
|
|
626
|
+
Notes
|
|
627
|
+
-----
|
|
628
|
+
The currency ID list and the master currency table are cached in memory
|
|
629
|
+
for the lifetime of the Python session so that multiple calls to
|
|
630
|
+
:func:`get` do not repeat the same HTTP requests. Use
|
|
631
|
+
:func:`clear_cache` to invalidate the cache when fresh data is needed.
|
|
632
|
+
|
|
166
633
|
DataFrame :
|
|
167
634
|
Série temporal com cotações diárias das moedas solicitadas.
|
|
168
635
|
"""
|
|
169
636
|
if isinstance(symbols, str):
|
|
170
637
|
symbols = [symbols]
|
|
638
|
+
|
|
639
|
+
if output == "text":
|
|
640
|
+
results: Dict[str, str] = {}
|
|
641
|
+
for symbol in symbols:
|
|
642
|
+
try:
|
|
643
|
+
raw = _get_symbol_text(symbol, start, end)
|
|
644
|
+
results[symbol] = raw
|
|
645
|
+
except CurrencyNotFoundError:
|
|
646
|
+
pass # Skip missing currencies
|
|
647
|
+
if not results:
|
|
648
|
+
raise CurrencyNotFoundError(f"Currency not found: {symbols}")
|
|
649
|
+
if len(symbols) == 1:
|
|
650
|
+
return results[symbols[0]]
|
|
651
|
+
return results
|
|
652
|
+
|
|
171
653
|
dss = []
|
|
172
654
|
for symbol in symbols:
|
|
173
|
-
|
|
174
|
-
|
|
655
|
+
try:
|
|
656
|
+
df1 = _get_symbol(symbol, start, end)
|
|
175
657
|
dss.append(df1)
|
|
658
|
+
except CurrencyNotFoundError:
|
|
659
|
+
pass # Skip missing currencies
|
|
660
|
+
if len(dss) > 0:
|
|
661
|
+
df = pd.concat(dss, axis=1)
|
|
662
|
+
if side in ("bid", "ask"):
|
|
663
|
+
dx = df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
|
|
664
|
+
return dx[side]
|
|
665
|
+
elif side == "both":
|
|
666
|
+
if groupby == "symbol":
|
|
667
|
+
return df
|
|
668
|
+
elif groupby == "side":
|
|
669
|
+
return df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
|
|
670
|
+
else:
|
|
671
|
+
raise ValueError("Unknown groupby value, use: symbol, side")
|
|
672
|
+
else:
|
|
673
|
+
raise ValueError("Unknown side value, use: bid, ask, both")
|
|
674
|
+
else:
|
|
675
|
+
raise CurrencyNotFoundError(f"Currency not found: {symbols}")
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
async def _async_currency_id_list(
|
|
679
|
+
cache: _ThreadSafeCache | None = None,
|
|
680
|
+
) -> pd.DataFrame:
|
|
681
|
+
"""Async version of _currency_id_list()."""
|
|
682
|
+
cache = cache or _DEFAULT_CACHE
|
|
683
|
+
cache_key = _CacheKey(type="currency_id_list")
|
|
684
|
+
cached = cache.get(cache_key)
|
|
685
|
+
if cached is not None:
|
|
686
|
+
return cached
|
|
687
|
+
|
|
688
|
+
url1 = (
|
|
689
|
+
"https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
|
|
690
|
+
"method=exibeFormularioConsultaBoletim"
|
|
691
|
+
)
|
|
692
|
+
res = await _ASYNC_CLIENT.get(url1)
|
|
693
|
+
if res.status_code == 429:
|
|
694
|
+
raise BCBRateLimitError(
|
|
695
|
+
"BCB API rate limit exceeded. Please try again later.",
|
|
696
|
+
status_code=429,
|
|
697
|
+
)
|
|
698
|
+
if res.status_code == 404:
|
|
699
|
+
raise BCBAPINotFoundError(
|
|
700
|
+
"BCB API endpoint not found (404)",
|
|
701
|
+
status_code=404,
|
|
702
|
+
)
|
|
703
|
+
if res.status_code >= 500:
|
|
704
|
+
raise BCBAPIError(
|
|
705
|
+
f"BCB API server error (status {res.status_code})",
|
|
706
|
+
status_code=res.status_code,
|
|
707
|
+
)
|
|
708
|
+
if res.status_code != 200:
|
|
709
|
+
msg = f"BCB API Request error, status code = {res.status_code}"
|
|
710
|
+
raise BCBAPIError(msg, res.status_code)
|
|
711
|
+
|
|
712
|
+
doc = html.parse(BytesIO(res.content)).getroot()
|
|
713
|
+
xpath = "//select[@name='ChkMoeda']/option"
|
|
714
|
+
x = [(elm.text, elm.get("value")) for elm in doc.xpath(xpath)]
|
|
715
|
+
df = pd.DataFrame(x, columns=["name", "id"])
|
|
716
|
+
df["id"] = df["id"].astype("int32")
|
|
717
|
+
cache.set(cache_key, df)
|
|
718
|
+
return df
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
async def _async_get_valid_currency_list(
|
|
722
|
+
_date: date, n: int = 0, max_rollback: int = 30
|
|
723
|
+
) -> "httpx.Response":
|
|
724
|
+
"""Async version of _get_valid_currency_list()."""
|
|
725
|
+
days_rolled_back = (date.today() - _date).days
|
|
726
|
+
if days_rolled_back > max_rollback:
|
|
727
|
+
raise BCBAPIError(
|
|
728
|
+
f"No currency list available in last {max_rollback} days",
|
|
729
|
+
status_code=503,
|
|
730
|
+
)
|
|
731
|
+
|
|
732
|
+
url2 = f"https://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
|
|
733
|
+
try:
|
|
734
|
+
res = await _ASYNC_CLIENT.get(url2)
|
|
735
|
+
except Exception as ex:
|
|
736
|
+
if n >= 3:
|
|
737
|
+
raise ex
|
|
738
|
+
return await _async_get_valid_currency_list(_date, n + 1, max_rollback)
|
|
739
|
+
|
|
740
|
+
if res.status_code == 200:
|
|
741
|
+
return res
|
|
742
|
+
else:
|
|
743
|
+
return await _async_get_valid_currency_list(
|
|
744
|
+
_date - timedelta(1), 0, max_rollback
|
|
745
|
+
)
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
async def _async_get_currency_list(
|
|
749
|
+
cache: _ThreadSafeCache | None = None,
|
|
750
|
+
) -> pd.DataFrame:
|
|
751
|
+
"""Async version of get_currency_list()."""
|
|
752
|
+
cache = cache or _DEFAULT_CACHE
|
|
753
|
+
cache_key = _CacheKey(type="currency_list")
|
|
754
|
+
cached = cache.get(cache_key)
|
|
755
|
+
if cached is not None:
|
|
756
|
+
return cached
|
|
757
|
+
|
|
758
|
+
res = await _async_get_valid_currency_list(date.today())
|
|
759
|
+
df = pd.read_csv(StringIO(res.text), delimiter=";")
|
|
760
|
+
df.columns = [
|
|
761
|
+
"code",
|
|
762
|
+
"name",
|
|
763
|
+
"symbol",
|
|
764
|
+
"country_code",
|
|
765
|
+
"country_name",
|
|
766
|
+
"type",
|
|
767
|
+
"exclusion_date",
|
|
768
|
+
]
|
|
769
|
+
df = df.loc[~df["country_code"].isna()]
|
|
770
|
+
df["exclusion_date"] = pd.to_datetime(df["exclusion_date"], dayfirst=True)
|
|
771
|
+
df["country_code"] = df["country_code"].astype("int32")
|
|
772
|
+
df["code"] = df["code"].astype("int32")
|
|
773
|
+
df["symbol"] = df["symbol"].str.strip()
|
|
774
|
+
cache.set(cache_key, df)
|
|
775
|
+
return df
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
async def _async_get_currency_id(symbol: str) -> int:
|
|
779
|
+
"""Async version of _get_currency_id() with concurrent cache warming."""
|
|
780
|
+
id_list, all_currencies = await asyncio.gather(
|
|
781
|
+
_async_currency_id_list(),
|
|
782
|
+
_async_get_currency_list(),
|
|
783
|
+
)
|
|
784
|
+
x = pd.merge(id_list, all_currencies, on=["name"])
|
|
785
|
+
matches = x.loc[x["symbol"] == symbol, "id"]
|
|
786
|
+
if matches.empty:
|
|
787
|
+
raise CurrencyNotFoundError(f"Unknown currency symbol: {symbol}")
|
|
788
|
+
return int(matches.max())
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
async def _async_fetch_symbol_response(
|
|
792
|
+
symbol: str, start_date: DateInput, end_date: DateInput
|
|
793
|
+
) -> "httpx.Response":
|
|
794
|
+
"""Async version of _fetch_symbol_response()."""
|
|
795
|
+
cid = await _async_get_currency_id(symbol)
|
|
796
|
+
url = _currency_url(cid, start_date, end_date)
|
|
797
|
+
res = await _ASYNC_CLIENT.get(url)
|
|
798
|
+
|
|
799
|
+
if res.headers["Content-Type"].startswith("text/html"):
|
|
800
|
+
doc = html.parse(BytesIO(res.content)).getroot()
|
|
801
|
+
xpath = "//div[@class='msgErro']"
|
|
802
|
+
elm = doc.xpath(xpath)[0]
|
|
803
|
+
x = elm.text
|
|
804
|
+
x = re.sub(r"^\W+", "", x)
|
|
805
|
+
x = re.sub(r"\W+$", "", x)
|
|
806
|
+
msg = f"BCB API returned error: {x} - {symbol}"
|
|
807
|
+
raise BCBAPIError(msg, status_code=400)
|
|
808
|
+
|
|
809
|
+
if res.status_code == 429:
|
|
810
|
+
raise BCBRateLimitError(
|
|
811
|
+
"BCB API rate limit exceeded. Please try again later.",
|
|
812
|
+
status_code=429,
|
|
813
|
+
)
|
|
814
|
+
if res.status_code == 404:
|
|
815
|
+
raise BCBAPINotFoundError(
|
|
816
|
+
f"Currency data not found for {symbol}",
|
|
817
|
+
status_code=404,
|
|
818
|
+
)
|
|
819
|
+
if res.status_code >= 500:
|
|
820
|
+
raise BCBAPIError(
|
|
821
|
+
f"BCB API server error (status {res.status_code})",
|
|
822
|
+
status_code=res.status_code,
|
|
823
|
+
)
|
|
824
|
+
if res.status_code != 200:
|
|
825
|
+
raise BCBAPIError(
|
|
826
|
+
f"BCB API request failed with status {res.status_code}",
|
|
827
|
+
status_code=res.status_code,
|
|
828
|
+
)
|
|
829
|
+
|
|
830
|
+
return res
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
async def _async_get_symbol(
|
|
834
|
+
symbol: str, start_date: DateInput, end_date: DateInput
|
|
835
|
+
) -> pd.DataFrame:
|
|
836
|
+
"""Async version of _get_symbol()."""
|
|
837
|
+
res = await _async_fetch_symbol_response(symbol, start_date, end_date)
|
|
838
|
+
df = _validate_currency_csv(res.text)
|
|
839
|
+
df = _parse_currency_dates(df)
|
|
840
|
+
df = _parse_currency_types(df)
|
|
841
|
+
df1 = df.set_index("Date")
|
|
842
|
+
n = ["bid", "ask"]
|
|
843
|
+
df1 = df1[n]
|
|
844
|
+
tuples = list(zip([symbol] * len(n), n))
|
|
845
|
+
df1.columns = pd.MultiIndex.from_tuples(tuples)
|
|
846
|
+
return df1
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
async def _async_get_symbol_text(
|
|
850
|
+
symbol: str, start_date: DateInput, end_date: DateInput
|
|
851
|
+
) -> str:
|
|
852
|
+
"""Async version of _get_symbol_text()."""
|
|
853
|
+
res = await _async_fetch_symbol_response(symbol, start_date, end_date)
|
|
854
|
+
return res.text
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
async def async_get(
|
|
858
|
+
symbols: Union[str, List[str]],
|
|
859
|
+
start: DateInput,
|
|
860
|
+
end: DateInput,
|
|
861
|
+
side: str = "ask",
|
|
862
|
+
groupby: str = "symbol",
|
|
863
|
+
output: str = "dataframe",
|
|
864
|
+
) -> Union[pd.DataFrame, str, Dict[str, str]]:
|
|
865
|
+
"""
|
|
866
|
+
Retorna um DataFrame pandas com séries temporais com taxas de câmbio (async version).
|
|
867
|
+
|
|
868
|
+
Uses :func:`asyncio.gather` to fetch multiple symbols concurrently.
|
|
869
|
+
|
|
870
|
+
Same signature as :func:`get`, but returns a coroutine.
|
|
871
|
+
|
|
872
|
+
Parameters
|
|
873
|
+
----------
|
|
874
|
+
symbols : str, List[str]
|
|
875
|
+
Códigos das moedas padrão ISO
|
|
876
|
+
start : str, int, date, datetime, Timestamp
|
|
877
|
+
Data de início da série
|
|
878
|
+
end : string, int, date, datetime, Timestamp
|
|
879
|
+
Data final da série
|
|
880
|
+
side : str
|
|
881
|
+
``'ask'``, ``'bid'`` ou ``'both'``
|
|
882
|
+
groupby : str
|
|
883
|
+
``'symbol'`` ou ``'side'``
|
|
884
|
+
output : str
|
|
885
|
+
``'dataframe'`` ou ``'text'``
|
|
886
|
+
|
|
887
|
+
Returns
|
|
888
|
+
-------
|
|
889
|
+
Union[pd.DataFrame, str, Dict[str, str]]
|
|
890
|
+
Série temporal conforme especificado
|
|
891
|
+
"""
|
|
892
|
+
if isinstance(symbols, str):
|
|
893
|
+
symbols = [symbols]
|
|
894
|
+
|
|
895
|
+
if output == "text":
|
|
896
|
+
results: Dict[str, str] = {}
|
|
897
|
+
texts = await asyncio.gather(
|
|
898
|
+
*[_async_get_symbol_text(symbol, start, end) for symbol in symbols]
|
|
899
|
+
)
|
|
900
|
+
for symbol, text in zip(symbols, texts):
|
|
901
|
+
if text is not None:
|
|
902
|
+
results[symbol] = text
|
|
903
|
+
if not results:
|
|
904
|
+
raise CurrencyNotFoundError(f"Currency not found: {symbols}")
|
|
905
|
+
if len(symbols) == 1:
|
|
906
|
+
return results[symbols[0]]
|
|
907
|
+
return results
|
|
908
|
+
|
|
909
|
+
dss = await asyncio.gather(
|
|
910
|
+
*[_async_get_symbol(symbol, start, end) for symbol in symbols]
|
|
911
|
+
)
|
|
912
|
+
dss = [df for df in dss if df is not None]
|
|
913
|
+
|
|
176
914
|
if len(dss) > 0:
|
|
177
915
|
df = pd.concat(dss, axis=1)
|
|
178
916
|
if side in ("bid", "ask"):
|
|
@@ -183,7 +921,9 @@ def get(
|
|
|
183
921
|
return df
|
|
184
922
|
elif groupby == "side":
|
|
185
923
|
return df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
|
|
924
|
+
else:
|
|
925
|
+
raise ValueError("Unknown groupby value, use: symbol, side")
|
|
186
926
|
else:
|
|
187
|
-
raise
|
|
927
|
+
raise ValueError("Unknown side value, use: bid, ask, both")
|
|
188
928
|
else:
|
|
189
|
-
raise
|
|
929
|
+
raise CurrencyNotFoundError(f"Currency not found: {symbols}")
|