python-bcb 0.3.4__py3-none-any.whl → 0.4.0__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/currency.py CHANGED
@@ -1,16 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
1
5
  import re
2
- import warnings
6
+ import threading
3
7
  from datetime import date, timedelta
4
8
  from io import BytesIO, StringIO
5
- from typing import List, Optional, Union
9
+ from typing import Dict, List, Literal, NamedTuple, NoReturn, Union, overload
10
+ from urllib.parse import urlencode
6
11
 
7
12
  import httpx
8
13
  import numpy as np
9
14
  import pandas as pd
10
- from lxml import html
15
+ from lxml import etree, html
16
+
17
+ from bcb.http import (
18
+ RequestTimeout,
19
+ get_async_client,
20
+ get_client,
21
+ raise_for_request_error,
22
+ raise_for_status,
23
+ timeout_kwargs,
24
+ )
25
+ from bcb.exceptions import BCBAPIError, CurrencyNotFoundError
26
+ from bcb.utils import Date, DateInput
11
27
 
12
- from .exceptions import BCBAPIError, CurrencyNotFoundError
13
- from .utils import Date, DateInput
28
+ logger = logging.getLogger(__name__)
14
29
 
15
30
  """
16
31
  O módulo :py:mod:`bcb.currency` tem como objetivo fazer consultas no site do conversor de moedas do BCB.
@@ -20,17 +35,85 @@ O módulo :py:mod:`bcb.currency` tem como objetivo fazer consultas no site do co
20
35
  def _currency_url(currency_id: int, start_date: DateInput, end_date: DateInput) -> str:
21
36
  start_date = Date(start_date)
22
37
  end_date = Date(end_date)
23
- return (
24
- f"https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
25
- f"method=gerarCSVFechamentoMoedaNoPeriodo&"
26
- f"ChkMoeda={currency_id}&DATAINI={start_date.date:%d/%m/%Y}&DATAFIM={end_date.date:%d/%m/%Y}"
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
+ }
27
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
28
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)
29
92
 
30
- _CACHE: dict[str, pd.DataFrame] = dict()
93
+ def set(self, key: _CacheKey, value: pd.DataFrame) -> None:
94
+ """Set value in cache.
31
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
32
105
 
33
- def clear_cache() -> None:
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:
34
117
  """Clear the module-level session cache.
35
118
 
36
119
  :func:`get` and :func:`get_currency_list` cache the currency ID list and
@@ -38,82 +121,194 @@ def clear_cache() -> None:
38
121
  that repeated calls do not make redundant HTTP requests. Call this
39
122
  function to force a fresh fetch on the next request (useful in tests or
40
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.
41
129
  """
42
- _CACHE.clear()
130
+ (cache or _DEFAULT_CACHE).clear()
43
131
 
44
132
 
45
- def _currency_id_list() -> pd.DataFrame:
46
- if _CACHE.get("TEMP_CURRENCY_ID_LIST") is not None:
47
- return _CACHE.get("TEMP_CURRENCY_ID_LIST")
48
- else:
49
- url1 = (
50
- "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
51
- "method=exibeFormularioConsultaBoletim"
133
+ def _currency_id_list(
134
+ cache: _ThreadSafeCache | None = None,
135
+ *,
136
+ timeout: RequestTimeout = None,
137
+ ) -> pd.DataFrame:
138
+ """Fetch list of available currency IDs and names.
139
+
140
+ Parameters
141
+ ----------
142
+ cache : _ThreadSafeCache, optional
143
+ Cache instance to use. If None, uses module-level default.
144
+
145
+ Returns
146
+ -------
147
+ pd.DataFrame
148
+ DataFrame with columns: name, id
149
+
150
+ Raises
151
+ ------
152
+ BCBRateLimitError
153
+ If API rate limit is exceeded (429)
154
+ BCBAPINotFoundError
155
+ If API endpoint not found (404)
156
+ BCBAPIError
157
+ If API returns error response
158
+ """
159
+ cache = cache or _DEFAULT_CACHE
160
+ cache_key = _CacheKey(type="currency_id_list")
161
+ cached = cache.get(cache_key)
162
+ if cached is not None:
163
+ return cached
164
+
165
+ url1 = (
166
+ "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
167
+ "method=exibeFormularioConsultaBoletim"
168
+ )
169
+ logger.debug(f"Fetching currency ID list from {url1}")
170
+ try:
171
+ res = get_client().get(url1, **timeout_kwargs(timeout))
172
+ except httpx.HTTPError as ex:
173
+ raise_for_request_error(ex, context="Currency ID list")
174
+ logger.debug(
175
+ f"Currency ID list response: status={res.status_code}, length={len(res.content)}"
176
+ )
177
+ raise_for_status(
178
+ res,
179
+ context="Currency ID list",
180
+ not_found_message="BCB API endpoint not found (404)",
181
+ )
182
+
183
+ doc = html.parse(BytesIO(res.content)).getroot()
184
+ xpath = "//select[@name='ChkMoeda']/option"
185
+ x = [(elm.text, elm.get("value")) for elm in doc.xpath(xpath)]
186
+ df = pd.DataFrame(x, columns=["name", "id"])
187
+ df["id"] = df["id"].astype("int32")
188
+ cache.set(cache_key, df)
189
+ return df
190
+
191
+
192
+ def _get_valid_currency_list(
193
+ _date: date,
194
+ n: int = 0,
195
+ max_rollback: int = 30,
196
+ *,
197
+ timeout: RequestTimeout = None,
198
+ ) -> "httpx.Response":
199
+ """Fetch currency list CSV, rolling back dates if necessary.
200
+
201
+ Attempts to fetch the currency master file for the given date.
202
+ If the file doesn't exist (common for weekends/holidays), rolls back
203
+ to the previous day and retries. Connection errors trigger retries
204
+ on the same date.
205
+
206
+ Parameters
207
+ ----------
208
+ _date : date
209
+ Target date to fetch
210
+ n : int
211
+ Current connection retry attempt (internal use)
212
+ max_rollback : int
213
+ Maximum number of days to roll back before giving up
214
+
215
+ Returns
216
+ -------
217
+ httpx.Response
218
+ Response object with CSV content
219
+
220
+ Raises
221
+ ------
222
+ BCBAPIError
223
+ If unable to fetch after max rollback days exceeded
224
+ """
225
+ # Check if we've rolled back too far
226
+ days_rolled_back = (date.today() - _date).days
227
+ if days_rolled_back > max_rollback:
228
+ raise BCBAPIError(
229
+ f"No currency list available in last {max_rollback} days",
230
+ status_code=503, # Service Unavailable
52
231
  )
53
- res = httpx.get(url1, follow_redirects=True)
54
- if res.status_code != 200:
55
- msg = f"BCB API Request error, status code = {res.status_code}"
56
- raise BCBAPIError(msg, res.status_code)
57
-
58
- doc = html.parse(BytesIO(res.content)).getroot()
59
- xpath = "//select[@name='ChkMoeda']/option"
60
- x = [(elm.text, elm.get("value")) for elm in doc.xpath(xpath)]
61
- df = pd.DataFrame(x, columns=["name", "id"])
62
- df["id"] = df["id"].astype("int32")
63
- _CACHE["TEMP_CURRENCY_ID_LIST"] = df
64
- return df
65
-
66
-
67
- def _get_valid_currency_list(_date: date, n: int = 0) -> httpx.Response:
68
- url2 = f"http://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
232
+
233
+ url2 = f"https://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
234
+ logger.debug(f"Fetching currency list from {url2}")
69
235
  try:
70
- res = httpx.get(url2, follow_redirects=True)
71
- except httpx.ConnectError as ex:
236
+ res = get_client().get(url2, **timeout_kwargs(timeout))
237
+ except httpx.HTTPError as ex:
238
+ # Connection error: retry same date up to 3 times
72
239
  if n >= 3:
73
- raise ex
74
- return _get_valid_currency_list(_date, n + 1)
240
+ raise_for_request_error(ex, context="Currency list")
241
+ logger.warning(
242
+ f"Connection error fetching {url2}, retrying (attempt {n + 1}/3)"
243
+ )
244
+ return _get_valid_currency_list(_date, n + 1, max_rollback, timeout=timeout)
245
+
246
+ logger.debug(
247
+ f"Currency list response: status={res.status_code}, length={len(res.content)}"
248
+ )
75
249
  if res.status_code == 200:
76
250
  return res
77
- else:
78
- return _get_valid_currency_list(_date - timedelta(1), 0)
251
+ if res.status_code == 429 or res.status_code >= 500:
252
+ raise_for_status(res, context="Currency list")
79
253
 
254
+ # Non-200 response (file not found for date): roll back to previous day
255
+ logger.debug(f"Currency list not found for {_date}, rolling back to previous day")
256
+ return _get_valid_currency_list(
257
+ _date - timedelta(1), 0, max_rollback, timeout=timeout
258
+ )
80
259
 
81
- def get_currency_list() -> pd.DataFrame:
82
- """
83
- Listagem com todas as moedas disponíveis na API e suas configurações de paridade.
260
+
261
+ def get_currency_list(
262
+ cache: _ThreadSafeCache | None = None,
263
+ *,
264
+ timeout: RequestTimeout = 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.
84
272
 
85
273
  Returns
86
274
  -------
87
-
88
- DataFrame :
275
+ pd.DataFrame
89
276
  Tabela com a listagem de moedas disponíveis.
277
+
278
+ Raises
279
+ ------
280
+ BCBAPIError
281
+ If API returns error response
90
282
  """
91
- if _CACHE.get("TEMP_FILE_CURRENCY_LIST") is not None:
92
- return _CACHE.get("TEMP_FILE_CURRENCY_LIST")
93
- else:
94
- res = _get_valid_currency_list(date.today())
95
- df = pd.read_csv(StringIO(res.text), delimiter=";")
96
- df.columns = [
97
- "code",
98
- "name",
99
- "symbol",
100
- "country_code",
101
- "country_name",
102
- "type",
103
- "exclusion_date",
104
- ]
105
- df = df.loc[~df["country_code"].isna()]
106
- df["exclusion_date"] = pd.to_datetime(df["exclusion_date"], dayfirst=True)
107
- df["country_code"] = df["country_code"].astype("int32")
108
- df["code"] = df["code"].astype("int32")
109
- df["symbol"] = df["symbol"].str.strip()
110
- _CACHE["TEMP_FILE_CURRENCY_LIST"] = df
111
- return df
112
-
113
-
114
- def _get_currency_id(symbol: str) -> int:
115
- id_list = _currency_id_list()
116
- all_currencies = get_currency_list()
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(), timeout=timeout)
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
307
+
308
+
309
+ def _get_currency_id(symbol: str, *, timeout: RequestTimeout = None) -> int:
310
+ id_list = _currency_id_list(timeout=timeout)
311
+ all_currencies = get_currency_list(timeout=timeout)
117
312
  x = pd.merge(id_list, all_currencies, on=["name"])
118
313
  matches = x.loc[x["symbol"] == symbol, "id"]
119
314
  if matches.empty:
@@ -121,51 +316,404 @@ def _get_currency_id(symbol: str) -> int:
121
316
  return int(matches.max())
122
317
 
123
318
 
124
- def _get_symbol(
125
- symbol: str, start_date: DateInput, end_date: DateInput
126
- ) -> Optional[pd.DataFrame]:
319
+ def _raise_no_valid_currency_symbols(symbols: List[str]) -> NoReturn:
320
+ requested = ", ".join(symbols) if symbols else "<empty>"
321
+ raise CurrencyNotFoundError(f"No valid currency symbols found: {requested}")
322
+
323
+
324
+ def _is_html_response(response: httpx.Response) -> bool:
325
+ content_type = response.headers.get("Content-Type", "").lower()
326
+ if content_type.startswith("text/html"):
327
+ return True
328
+ body = response.content.lstrip().lower()
329
+ return body.startswith((b"<!doctype html", b"<html", b"<body", b"<div"))
330
+
331
+
332
+ def _clean_currency_error_message(message: str) -> str:
333
+ message = re.sub(r"^\W+", "", message)
334
+ message = re.sub(r"\W+$", "", message)
335
+ message = re.sub(r"\s+", " ", message)
336
+ return message.strip()
337
+
338
+
339
+ def _extract_currency_html_error(content: bytes) -> str | None:
127
340
  try:
128
- cid = _get_currency_id(symbol)
129
- except CurrencyNotFoundError:
130
- return None
131
- url = _currency_url(cid, start_date, end_date)
132
- res = httpx.get(url, follow_redirects=True)
133
-
134
- if res.headers["Content-Type"].startswith("text/html"):
135
- doc = html.parse(BytesIO(res.content)).getroot()
136
- xpath = "//div[@class='msgErro']"
137
- elm = doc.xpath(xpath)[0]
138
- x = elm.text
139
- x = re.sub(r"^\W+", "", x)
140
- x = re.sub(r"\W+$", "", x)
141
- msg = f"BCB API returned error: {x} - {symbol}"
142
- warnings.warn(msg)
341
+ doc = html.parse(BytesIO(content)).getroot()
342
+ except (etree.ParserError, ValueError):
143
343
  return None
344
+ xpath = "//div[@class='msgErro']"
345
+ for element in doc.xpath(xpath):
346
+ message = _clean_currency_error_message(str(element.text_content()))
347
+ if message:
348
+ return message
349
+ return None
144
350
 
145
- columns = ["Date", "aa", "bb", "cc", "bid", "ask", "dd", "ee"]
146
- df = pd.read_csv(
147
- StringIO(res.text), delimiter=";", header=None, names=columns, dtype=str
351
+
352
+ def _raise_currency_html_error(response: httpx.Response, symbol: str) -> NoReturn:
353
+ message = _extract_currency_html_error(response.content)
354
+ if message:
355
+ raise BCBAPIError(
356
+ f"BCB API returned error for {symbol}: {message}",
357
+ status_code=400,
358
+ )
359
+ raise BCBAPIError(
360
+ f"BCB API returned an HTML response for {symbol} "
361
+ "without a recognized BCB error message",
362
+ status_code=400,
148
363
  )
149
- df = df.assign(
150
- Date=lambda x: pd.to_datetime(x["Date"], format="%d%m%Y"),
151
- bid=lambda x: x["bid"].str.replace(",", ".").astype(np.float64),
152
- ask=lambda x: x["ask"].str.replace(",", ".").astype(np.float64),
364
+
365
+
366
+ def _fetch_symbol_response(
367
+ symbol: str,
368
+ start_date: DateInput,
369
+ end_date: DateInput,
370
+ *,
371
+ timeout: RequestTimeout = None,
372
+ ) -> "httpx.Response":
373
+ """Fetch exchange rate CSV response for a symbol.
374
+
375
+ Parameters
376
+ ----------
377
+ symbol : str
378
+ Currency symbol (e.g., 'USD')
379
+ start_date : DateInput
380
+ Start date for the query
381
+ end_date : DateInput
382
+ End date for the query
383
+
384
+ Returns
385
+ -------
386
+ httpx.Response
387
+ Response object with CSV content
388
+
389
+ Raises
390
+ ------
391
+ CurrencyNotFoundError
392
+ If the currency symbol is not found
393
+ BCBRateLimitError
394
+ If API rate limit is exceeded (429)
395
+ BCBAPIError
396
+ If API returns other error status codes or HTML error page
397
+ """
398
+ cid = _get_currency_id(
399
+ symbol, timeout=timeout
400
+ ) # Raises CurrencyNotFoundError if not found
401
+ url = _currency_url(cid, start_date, end_date)
402
+ logger.debug(f"Fetching currency data for {symbol} from {url.split('?')[0]}")
403
+ try:
404
+ res = get_client().get(url, **timeout_kwargs(timeout))
405
+ except httpx.HTTPError as ex:
406
+ raise_for_request_error(ex, context=f"Currency data for {symbol}")
407
+ logger.debug(
408
+ f"Currency data response: status={res.status_code}, length={len(res.content)}"
153
409
  )
410
+
411
+ # Handle HTML error responses (e.g., no data for date range).
412
+ if _is_html_response(res):
413
+ _raise_currency_html_error(res, symbol)
414
+
415
+ raise_for_status(
416
+ res,
417
+ context=f"Currency data for {symbol}",
418
+ not_found_message=f"Currency data not found for {symbol}",
419
+ )
420
+
421
+ return res
422
+
423
+
424
+ def _validate_currency_csv(csv_text: str) -> pd.DataFrame:
425
+ """Parse and validate currency CSV format.
426
+
427
+ Parameters
428
+ ----------
429
+ csv_text : str
430
+ CSV content from BCB API
431
+
432
+ Returns
433
+ -------
434
+ pd.DataFrame
435
+ Parsed DataFrame with all columns
436
+
437
+ Raises
438
+ ------
439
+ BCBAPIError
440
+ If CSV format is invalid (wrong column count)
441
+ """
442
+ if not csv_text.strip():
443
+ raise BCBAPIError("Currency CSV response is empty", status_code=400)
444
+ try:
445
+ df = pd.read_csv(StringIO(csv_text), delimiter=";", header=None, dtype=str)
446
+ except (pd.errors.EmptyDataError, pd.errors.ParserError) as e:
447
+ raise BCBAPIError(f"Failed to parse currency CSV: {e}", status_code=400) from e
448
+
449
+ # Validate column count
450
+ if len(df.columns) != 8:
451
+ raise BCBAPIError(
452
+ f"Invalid CSV format: expected 8 columns, got {len(df.columns)}",
453
+ status_code=400,
454
+ )
455
+
456
+ # Assign meaningful names
457
+ df.columns = ["Date", "_col1", "_col2", "_col3", "bid", "ask", "_col6", "_col7"]
458
+ return df
459
+
460
+
461
+ def _parse_currency_dates(df: pd.DataFrame) -> pd.DataFrame:
462
+ """Parse and validate date column in currency CSV.
463
+
464
+ Parameters
465
+ ----------
466
+ df : pd.DataFrame
467
+ DataFrame with Date column as strings
468
+
469
+ Returns
470
+ -------
471
+ pd.DataFrame
472
+ DataFrame with parsed DatetimeIndex
473
+
474
+ Raises
475
+ ------
476
+ BCBAPIError
477
+ If date parsing fails
478
+ """
479
+ try:
480
+ df["Date"] = pd.to_datetime(df["Date"], format="%d%m%Y")
481
+ except (TypeError, ValueError) as e:
482
+ raise BCBAPIError(
483
+ f"Failed to parse currency date column: {str(e)}", status_code=400
484
+ ) from e
485
+ return df
486
+
487
+
488
+ def _parse_currency_types(df: pd.DataFrame) -> pd.DataFrame:
489
+ """Parse and validate data types in currency DataFrame.
490
+
491
+ Parameters
492
+ ----------
493
+ df : pd.DataFrame
494
+ DataFrame with mixed types
495
+
496
+ Returns
497
+ -------
498
+ pd.DataFrame
499
+ DataFrame with validated types
500
+
501
+ Raises
502
+ ------
503
+ BCBAPIError
504
+ If type conversion fails
505
+ """
506
+ try:
507
+ df["bid"] = df["bid"].str.replace(",", ".").astype(np.float64)
508
+ df["ask"] = df["ask"].str.replace(",", ".").astype(np.float64)
509
+ except (TypeError, ValueError) as e:
510
+ raise BCBAPIError(
511
+ f"Failed to parse currency numeric columns: {str(e)}", status_code=400
512
+ ) from e
513
+ return df
514
+
515
+
516
+ def _get_symbol(
517
+ symbol: str,
518
+ start_date: DateInput,
519
+ end_date: DateInput,
520
+ *,
521
+ timeout: RequestTimeout = None,
522
+ ) -> pd.DataFrame:
523
+ """Fetch and parse exchange rate data for a symbol.
524
+
525
+ Parameters
526
+ ----------
527
+ symbol : str
528
+ Currency symbol
529
+ start_date : DateInput
530
+ Start date
531
+ end_date : DateInput
532
+ End date
533
+
534
+ Returns
535
+ -------
536
+ pd.DataFrame
537
+ DataFrame with exchange rate data
538
+
539
+ Raises
540
+ ------
541
+ CurrencyNotFoundError
542
+ If currency not found
543
+ BCBAPIError
544
+ If API returns error or data format is invalid
545
+ """
546
+ res = _fetch_symbol_response(symbol, start_date, end_date, timeout=timeout)
547
+ df = _validate_currency_csv(res.text)
548
+ df = _parse_currency_dates(df)
549
+ df = _parse_currency_types(df)
154
550
  df1 = df.set_index("Date")
155
551
  n = ["bid", "ask"]
156
552
  df1 = df1[n]
157
- tuples = list(zip([symbol] * len(n), n))
553
+ tuples = list(zip([symbol] * len(n), n, strict=True))
158
554
  df1.columns = pd.MultiIndex.from_tuples(tuples)
159
555
  return df1
160
556
 
161
557
 
558
+ def _get_symbol_text(
559
+ symbol: str,
560
+ start_date: DateInput,
561
+ end_date: DateInput,
562
+ *,
563
+ timeout: RequestTimeout = None,
564
+ ) -> str:
565
+ """Fetch exchange rate data as CSV text for a symbol.
566
+
567
+ Parameters
568
+ ----------
569
+ symbol : str
570
+ Currency symbol
571
+ start_date : DateInput
572
+ Start date
573
+ end_date : DateInput
574
+ End date
575
+
576
+ Returns
577
+ -------
578
+ str
579
+ CSV text with exchange rate data
580
+
581
+ Raises
582
+ ------
583
+ CurrencyNotFoundError
584
+ If currency not found
585
+ BCBAPIError
586
+ If API returns error
587
+ """
588
+ res = _fetch_symbol_response(symbol, start_date, end_date, timeout=timeout)
589
+ return res.text
590
+
591
+
592
+ # Type alias for text output with multiple symbols
593
+ CurrencyTextResult = Dict[str, str] # Maps symbol → CSV text
594
+ CurrencySide = Literal["ask", "bid", "both"]
595
+ CurrencyGroupBy = Literal["symbol", "side"]
596
+ CurrencyOutput = Literal["dataframe", "text"]
597
+
598
+
599
+ def _tidy_df(df: pd.DataFrame, side: CurrencySide) -> pd.DataFrame:
600
+ frames = []
601
+ for position, column in enumerate(df.columns):
602
+ symbol, rate_side = column
603
+ if side != "both" and rate_side != side:
604
+ continue
605
+ frames.append(
606
+ pd.DataFrame(
607
+ {
608
+ "Date": df.index,
609
+ "symbol": symbol,
610
+ "side": rate_side,
611
+ "value": df.iloc[:, position].to_numpy(),
612
+ }
613
+ )
614
+ )
615
+ if not frames:
616
+ return pd.DataFrame(columns=["Date", "symbol", "side", "value"])
617
+ return pd.concat(frames, ignore_index=True)
618
+
619
+
620
+ def _normalize_currency_symbols(symbols: Union[str, List[str]]) -> List[str]:
621
+ if isinstance(symbols, str):
622
+ symbols = [symbols]
623
+ if not symbols:
624
+ raise ValueError("At least one currency symbol must be provided")
625
+ for symbol in symbols:
626
+ if not isinstance(symbol, str) or not symbol.strip():
627
+ raise ValueError(f"Currency symbols must be non-empty strings: {symbol!r}")
628
+ return symbols
629
+
630
+
631
+ def _validate_currency_query_inputs(
632
+ symbols: Union[str, List[str]],
633
+ start: DateInput,
634
+ end: DateInput,
635
+ side: str,
636
+ groupby: str,
637
+ output: str,
638
+ ) -> List[str]:
639
+ if output not in ("dataframe", "text"):
640
+ raise ValueError("Unknown output value, use: dataframe, text")
641
+ if side not in ("bid", "ask", "both"):
642
+ raise ValueError("Unknown side value, use: bid, ask, both")
643
+ if groupby not in ("symbol", "side"):
644
+ raise ValueError("Unknown groupby value, use: symbol, side")
645
+ Date(start)
646
+ Date(end)
647
+ return _normalize_currency_symbols(symbols)
648
+
649
+
650
+ @overload
651
+ def get(
652
+ symbols: str,
653
+ start: DateInput,
654
+ end: DateInput,
655
+ side: CurrencySide = ...,
656
+ groupby: CurrencyGroupBy = ...,
657
+ output: Literal["dataframe"] = ...,
658
+ tidy: bool = ...,
659
+ *,
660
+ timeout: RequestTimeout = ...,
661
+ ) -> pd.DataFrame: ...
662
+
663
+
664
+ @overload
665
+ def get(
666
+ symbols: List[str],
667
+ start: DateInput,
668
+ end: DateInput,
669
+ side: CurrencySide = ...,
670
+ groupby: CurrencyGroupBy = ...,
671
+ output: Literal["dataframe"] = ...,
672
+ tidy: bool = ...,
673
+ *,
674
+ timeout: RequestTimeout = ...,
675
+ ) -> pd.DataFrame: ...
676
+
677
+
678
+ @overload
679
+ def get(
680
+ symbols: str,
681
+ start: DateInput,
682
+ end: DateInput,
683
+ side: CurrencySide = ...,
684
+ groupby: CurrencyGroupBy = ...,
685
+ output: Literal["text"] = ...,
686
+ tidy: bool = ...,
687
+ *,
688
+ timeout: RequestTimeout = ...,
689
+ ) -> str: ...
690
+
691
+
692
+ @overload
693
+ def get(
694
+ symbols: List[str],
695
+ start: DateInput,
696
+ end: DateInput,
697
+ side: CurrencySide = ...,
698
+ groupby: CurrencyGroupBy = ...,
699
+ output: Literal["text"] = ...,
700
+ tidy: bool = ...,
701
+ *,
702
+ timeout: RequestTimeout = ...,
703
+ ) -> CurrencyTextResult: ...
704
+
705
+
162
706
  def get(
163
707
  symbols: Union[str, List[str]],
164
708
  start: DateInput,
165
709
  end: DateInput,
166
- side: str = "ask",
167
- groupby: str = "symbol",
168
- ) -> pd.DataFrame:
710
+ side: CurrencySide = "ask",
711
+ groupby: CurrencyGroupBy = "symbol",
712
+ output: CurrencyOutput = "dataframe",
713
+ tidy: bool = False,
714
+ *,
715
+ timeout: RequestTimeout = None,
716
+ ) -> Union[pd.DataFrame, str, Dict[str, str]]:
169
717
  """
170
718
  Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
171
719
 
@@ -176,18 +724,28 @@ def get(
176
724
  Códigos das moedas padrão ISO. O código de uma única moeda que
177
725
  retorna uma série temporal univariada e uma lista de códigos
178
726
  retorna uma série temporal multivariada.
179
- start : str, int, date, datetime, Timestamp
180
- Data de início da série.
181
- Interpreta diferentes tipos e formatos de datas.
182
- end : string, int, date, datetime, Timestamp
183
- Data de início da série.
184
- Interpreta diferentes tipos e formatos de datas.
185
- side : str
727
+ start : str, date, datetime or bcb.utils.Date
728
+ Data de início da série. Strings usam o formato ``YYYY-MM-DD``;
729
+ ``'today'`` e ``'now'`` também são aceitos.
730
+ end : str, date, datetime or bcb.utils.Date
731
+ Data final da série. Strings usam o formato ``YYYY-MM-DD``;
732
+ ``'today'`` e ``'now'`` também são aceitos.
733
+ side : {"ask", "bid", "both"}, default "ask"
186
734
  Define se a série retornada vem com os ``ask`` prices,
187
735
  ``bid`` prices ou ``both`` para ambos.
188
- groupby : str
736
+ groupby : {"symbol", "side"}, default "symbol"
189
737
  Define se os índices de coluna são agrupados por ``symbol`` ou
190
738
  por ``side``.
739
+ output : {"dataframe", "text"}, default "dataframe"
740
+ Define o formato de saída. Use ``"text"`` para retornar o CSV bruto.
741
+ tidy : bool, default False
742
+ Quando ``True`` e ``output='dataframe'``, retorna um DataFrame em
743
+ formato tidy com colunas ``Date``, ``symbol``, ``side`` e ``value``.
744
+ Quando ``False``, mantém o formato largo padrão. Não altera
745
+ ``output='text'``.
746
+ timeout : float or httpx.Timeout, optional
747
+ Timeout por requisição HTTP, em segundos ou como ``httpx.Timeout``.
748
+ Quando omitido, usa o timeout padrão do cliente compartilhado.
191
749
 
192
750
  Returns
193
751
  -------
@@ -202,15 +760,317 @@ def get(
202
760
  DataFrame :
203
761
  Série temporal com cotações diárias das moedas solicitadas.
204
762
  """
205
- if isinstance(symbols, str):
206
- symbols = [symbols]
763
+ symbols = _validate_currency_query_inputs(
764
+ symbols, start, end, side, groupby, output
765
+ )
766
+
767
+ if output == "text":
768
+ results: Dict[str, str] = {}
769
+ for symbol in symbols:
770
+ try:
771
+ raw = _get_symbol_text(symbol, start, end, timeout=timeout)
772
+ results[symbol] = raw
773
+ except CurrencyNotFoundError:
774
+ pass # Skip missing currencies
775
+ if not results:
776
+ _raise_no_valid_currency_symbols(symbols)
777
+ if len(symbols) == 1:
778
+ return results[symbols[0]]
779
+ return results
780
+
207
781
  dss = []
208
782
  for symbol in symbols:
209
- df1 = _get_symbol(symbol, start, end)
210
- if df1 is not None:
783
+ try:
784
+ df1 = _get_symbol(symbol, start, end, timeout=timeout)
211
785
  dss.append(df1)
786
+ except CurrencyNotFoundError:
787
+ pass # Skip missing currencies
212
788
  if len(dss) > 0:
213
789
  df = pd.concat(dss, axis=1)
790
+ if tidy:
791
+ return _tidy_df(df, side)
792
+ if side in ("bid", "ask"):
793
+ dx = df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
794
+ return dx[side]
795
+ elif side == "both":
796
+ if groupby == "symbol":
797
+ return df
798
+ elif groupby == "side":
799
+ return df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
800
+ else:
801
+ raise ValueError("Unknown groupby value, use: symbol, side")
802
+ else:
803
+ raise ValueError("Unknown side value, use: bid, ask, both")
804
+ else:
805
+ _raise_no_valid_currency_symbols(symbols)
806
+
807
+
808
+ async def _async_currency_id_list(
809
+ cache: _ThreadSafeCache | None = None,
810
+ *,
811
+ timeout: RequestTimeout = None,
812
+ ) -> pd.DataFrame:
813
+ """Async version of _currency_id_list()."""
814
+ cache = cache or _DEFAULT_CACHE
815
+ cache_key = _CacheKey(type="currency_id_list")
816
+ cached = cache.get(cache_key)
817
+ if cached is not None:
818
+ return cached
819
+
820
+ url1 = (
821
+ "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
822
+ "method=exibeFormularioConsultaBoletim"
823
+ )
824
+ try:
825
+ res = await get_async_client().get(url1, **timeout_kwargs(timeout))
826
+ except httpx.HTTPError as ex:
827
+ raise_for_request_error(ex, context="Currency ID list")
828
+ raise_for_status(
829
+ res,
830
+ context="Currency ID list",
831
+ not_found_message="BCB API endpoint not found (404)",
832
+ )
833
+
834
+ doc = html.parse(BytesIO(res.content)).getroot()
835
+ xpath = "//select[@name='ChkMoeda']/option"
836
+ x = [(elm.text, elm.get("value")) for elm in doc.xpath(xpath)]
837
+ df = pd.DataFrame(x, columns=["name", "id"])
838
+ df["id"] = df["id"].astype("int32")
839
+ cache.set(cache_key, df)
840
+ return df
841
+
842
+
843
+ async def _async_get_valid_currency_list(
844
+ _date: date,
845
+ n: int = 0,
846
+ max_rollback: int = 30,
847
+ *,
848
+ timeout: RequestTimeout = None,
849
+ ) -> "httpx.Response":
850
+ """Async version of _get_valid_currency_list()."""
851
+ days_rolled_back = (date.today() - _date).days
852
+ if days_rolled_back > max_rollback:
853
+ raise BCBAPIError(
854
+ f"No currency list available in last {max_rollback} days",
855
+ status_code=503,
856
+ )
857
+
858
+ url2 = f"https://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
859
+ try:
860
+ res = await get_async_client().get(url2, **timeout_kwargs(timeout))
861
+ except httpx.HTTPError as ex:
862
+ if n >= 3:
863
+ raise_for_request_error(ex, context="Currency list")
864
+ return await _async_get_valid_currency_list(
865
+ _date, n + 1, max_rollback, timeout=timeout
866
+ )
867
+
868
+ if res.status_code == 200:
869
+ return res
870
+ if res.status_code == 429 or res.status_code >= 500:
871
+ raise_for_status(res, context="Currency list")
872
+ return await _async_get_valid_currency_list(
873
+ _date - timedelta(1), 0, max_rollback, timeout=timeout
874
+ )
875
+
876
+
877
+ async def _async_get_currency_list(
878
+ cache: _ThreadSafeCache | None = None,
879
+ *,
880
+ timeout: RequestTimeout = None,
881
+ ) -> pd.DataFrame:
882
+ """Async version of get_currency_list()."""
883
+ cache = cache or _DEFAULT_CACHE
884
+ cache_key = _CacheKey(type="currency_list")
885
+ cached = cache.get(cache_key)
886
+ if cached is not None:
887
+ return cached
888
+
889
+ res = await _async_get_valid_currency_list(date.today(), timeout=timeout)
890
+ df = pd.read_csv(StringIO(res.text), delimiter=";")
891
+ df.columns = [
892
+ "code",
893
+ "name",
894
+ "symbol",
895
+ "country_code",
896
+ "country_name",
897
+ "type",
898
+ "exclusion_date",
899
+ ]
900
+ df = df.loc[~df["country_code"].isna()]
901
+ df["exclusion_date"] = pd.to_datetime(df["exclusion_date"], dayfirst=True)
902
+ df["country_code"] = df["country_code"].astype("int32")
903
+ df["code"] = df["code"].astype("int32")
904
+ df["symbol"] = df["symbol"].str.strip()
905
+ cache.set(cache_key, df)
906
+ return df
907
+
908
+
909
+ async def _async_get_currency_id(symbol: str, *, timeout: RequestTimeout = None) -> int:
910
+ """Async version of _get_currency_id() with concurrent cache warming."""
911
+ id_list, all_currencies = await asyncio.gather(
912
+ _async_currency_id_list(timeout=timeout),
913
+ _async_get_currency_list(timeout=timeout),
914
+ )
915
+ x = pd.merge(id_list, all_currencies, on=["name"])
916
+ matches = x.loc[x["symbol"] == symbol, "id"]
917
+ if matches.empty:
918
+ raise CurrencyNotFoundError(f"Unknown currency symbol: {symbol}")
919
+ return int(matches.max())
920
+
921
+
922
+ async def _async_fetch_symbol_response(
923
+ symbol: str,
924
+ start_date: DateInput,
925
+ end_date: DateInput,
926
+ *,
927
+ timeout: RequestTimeout = None,
928
+ ) -> "httpx.Response":
929
+ """Async version of _fetch_symbol_response()."""
930
+ cid = await _async_get_currency_id(symbol, timeout=timeout)
931
+ url = _currency_url(cid, start_date, end_date)
932
+ try:
933
+ res = await get_async_client().get(url, **timeout_kwargs(timeout))
934
+ except httpx.HTTPError as ex:
935
+ raise_for_request_error(ex, context=f"Currency data for {symbol}")
936
+
937
+ if _is_html_response(res):
938
+ _raise_currency_html_error(res, symbol)
939
+
940
+ raise_for_status(
941
+ res,
942
+ context=f"Currency data for {symbol}",
943
+ not_found_message=f"Currency data not found for {symbol}",
944
+ )
945
+
946
+ return res
947
+
948
+
949
+ async def _async_get_symbol(
950
+ symbol: str,
951
+ start_date: DateInput,
952
+ end_date: DateInput,
953
+ *,
954
+ timeout: RequestTimeout = None,
955
+ ) -> pd.DataFrame:
956
+ """Async version of _get_symbol()."""
957
+ res = await _async_fetch_symbol_response(
958
+ symbol, start_date, end_date, timeout=timeout
959
+ )
960
+ df = _validate_currency_csv(res.text)
961
+ df = _parse_currency_dates(df)
962
+ df = _parse_currency_types(df)
963
+ df1 = df.set_index("Date")
964
+ n = ["bid", "ask"]
965
+ df1 = df1[n]
966
+ tuples = list(zip([symbol] * len(n), n, strict=True))
967
+ df1.columns = pd.MultiIndex.from_tuples(tuples)
968
+ return df1
969
+
970
+
971
+ async def _async_get_symbol_text(
972
+ symbol: str,
973
+ start_date: DateInput,
974
+ end_date: DateInput,
975
+ *,
976
+ timeout: RequestTimeout = None,
977
+ ) -> str:
978
+ """Async version of _get_symbol_text()."""
979
+ res = await _async_fetch_symbol_response(
980
+ symbol, start_date, end_date, timeout=timeout
981
+ )
982
+ return res.text
983
+
984
+
985
+ async def async_get(
986
+ symbols: Union[str, List[str]],
987
+ start: DateInput,
988
+ end: DateInput,
989
+ side: CurrencySide = "ask",
990
+ groupby: CurrencyGroupBy = "symbol",
991
+ output: CurrencyOutput = "dataframe",
992
+ tidy: bool = False,
993
+ *,
994
+ timeout: RequestTimeout = None,
995
+ ) -> Union[pd.DataFrame, str, Dict[str, str]]:
996
+ """
997
+ Retorna um DataFrame pandas com séries temporais com taxas de câmbio (async version).
998
+
999
+ Uses :func:`asyncio.gather` to fetch multiple symbols concurrently.
1000
+
1001
+ Same signature as :func:`get`, but returns a coroutine.
1002
+
1003
+ Parameters
1004
+ ----------
1005
+ symbols : str, List[str]
1006
+ Códigos das moedas padrão ISO
1007
+ start : str, date, datetime or bcb.utils.Date
1008
+ Data de início da série. Strings usam o formato ``YYYY-MM-DD``;
1009
+ ``'today'`` e ``'now'`` também são aceitos.
1010
+ end : str, date, datetime or bcb.utils.Date
1011
+ Data final da série. Strings usam o formato ``YYYY-MM-DD``;
1012
+ ``'today'`` e ``'now'`` também são aceitos.
1013
+ side : {"ask", "bid", "both"}
1014
+ ``'ask'``, ``'bid'`` ou ``'both'``
1015
+ groupby : {"symbol", "side"}
1016
+ ``'symbol'`` ou ``'side'``
1017
+ output : {"dataframe", "text"}
1018
+ ``'dataframe'`` ou ``'text'``
1019
+ tidy : bool, default False
1020
+ Quando ``True`` e ``output='dataframe'``, retorna um DataFrame em
1021
+ formato tidy com colunas ``Date``, ``symbol``, ``side`` e ``value``.
1022
+ Quando ``False``, mantém o formato largo padrão. Não altera
1023
+ ``output='text'``.
1024
+ timeout : float or httpx.Timeout, optional
1025
+ Timeout por requisição HTTP, em segundos ou como ``httpx.Timeout``.
1026
+ Quando omitido, usa o timeout padrão do cliente compartilhado.
1027
+
1028
+ Returns
1029
+ -------
1030
+ Union[pd.DataFrame, str, Dict[str, str]]
1031
+ Série temporal conforme especificado
1032
+ """
1033
+ symbols = _validate_currency_query_inputs(
1034
+ symbols, start, end, side, groupby, output
1035
+ )
1036
+
1037
+ if output == "text":
1038
+ results: Dict[str, str] = {}
1039
+ texts = await asyncio.gather(
1040
+ *[
1041
+ _async_get_symbol_text(symbol, start, end, timeout=timeout)
1042
+ for symbol in symbols
1043
+ ],
1044
+ return_exceptions=True,
1045
+ )
1046
+ for symbol, text in zip(symbols, texts, strict=True):
1047
+ if isinstance(text, CurrencyNotFoundError):
1048
+ continue
1049
+ if isinstance(text, BaseException):
1050
+ raise text
1051
+ results[symbol] = text
1052
+ if not results:
1053
+ _raise_no_valid_currency_symbols(symbols)
1054
+ if len(symbols) == 1:
1055
+ return results[symbols[0]]
1056
+ return results
1057
+
1058
+ dss = await asyncio.gather(
1059
+ *[_async_get_symbol(symbol, start, end, timeout=timeout) for symbol in symbols],
1060
+ return_exceptions=True,
1061
+ )
1062
+ valid_dss = []
1063
+ for df in dss:
1064
+ if isinstance(df, CurrencyNotFoundError):
1065
+ continue
1066
+ if isinstance(df, BaseException):
1067
+ raise df
1068
+ valid_dss.append(df)
1069
+
1070
+ if len(valid_dss) > 0:
1071
+ df = pd.concat(valid_dss, axis=1)
1072
+ if tidy:
1073
+ return _tidy_df(df, side)
214
1074
  if side in ("bid", "ask"):
215
1075
  dx = df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
216
1076
  return dx[side]
@@ -219,7 +1079,9 @@ def get(
219
1079
  return df
220
1080
  elif groupby == "side":
221
1081
  return df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
1082
+ else:
1083
+ raise ValueError("Unknown groupby value, use: symbol, side")
222
1084
  else:
223
1085
  raise ValueError("Unknown side value, use: bid, ask, both")
224
1086
  else:
225
- raise CurrencyNotFoundError(f"Currency not found: {symbols}")
1087
+ _raise_no_valid_currency_symbols(symbols)