python-bcb 0.3.4__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/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 TYPE_CHECKING, Dict, List, Literal, NamedTuple, Union, overload
10
+ from urllib.parse import urlencode
6
11
 
7
- import httpx
8
12
  import numpy as np
9
13
  import pandas as pd
10
14
  from lxml import html
11
15
 
12
- from .exceptions import BCBAPIError, CurrencyNotFoundError
13
- from .utils import Date, DateInput
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__)
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 {}
28
76
 
77
+ def get(self, key: _CacheKey) -> pd.DataFrame | None:
78
+ """Get value from cache.
29
79
 
30
- _CACHE: dict[str, pd.DataFrame] = dict()
80
+ Parameters
81
+ ----------
82
+ key : _CacheKey
83
+ Cache key
31
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)
32
92
 
33
- def clear_cache() -> None:
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:
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,77 +121,189 @@ 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
+ ) -> 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 = (
164
+ "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
165
+ "method=exibeFormularioConsultaBoletim"
166
+ )
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,
52
181
  )
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)
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)
57
190
 
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
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
198
+
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.
65
204
 
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.
66
209
 
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"
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
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
+ )
236
+
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}")
69
239
  try:
70
- res = httpx.get(url2, follow_redirects=True)
71
- except httpx.ConnectError as ex:
240
+ res = _CLIENT.get(url2)
241
+ except Exception as ex:
242
+ # Connection error: retry same date up to 3 times
72
243
  if n >= 3:
73
244
  raise ex
74
- return _get_valid_currency_list(_date, n + 1)
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
+ )
75
253
  if res.status_code == 200:
76
254
  return res
77
255
  else:
78
- return _get_valid_currency_list(_date - timedelta(1), 0)
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)
79
261
 
80
262
 
81
- def get_currency_list() -> pd.DataFrame:
82
- """
83
- Listagem com todas as moedas disponíveis na API e suas configurações de paridade.
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.
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
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
112
307
 
113
308
 
114
309
  def _get_currency_id(symbol: str) -> int:
@@ -121,16 +316,43 @@ def _get_currency_id(symbol: str) -> int:
121
316
  return int(matches.max())
122
317
 
123
318
 
124
- def _get_symbol(
319
+ def _fetch_symbol_response(
125
320
  symbol: str, start_date: DateInput, end_date: DateInput
126
- ) -> Optional[pd.DataFrame]:
127
- try:
128
- cid = _get_currency_id(symbol)
129
- except CurrencyNotFoundError:
130
- return None
321
+ ) -> "httpx.Response":
322
+ """Fetch exchange rate CSV response for a symbol.
323
+
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
131
348
  url = _currency_url(cid, start_date, end_date)
132
- res = httpx.get(url, follow_redirects=True)
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
+ )
133
354
 
355
+ # Handle HTML error response (e.g., no data for date range)
134
356
  if res.headers["Content-Type"].startswith("text/html"):
135
357
  doc = html.parse(BytesIO(res.content)).getroot()
136
358
  xpath = "//div[@class='msgErro']"
@@ -139,18 +361,150 @@ def _get_symbol(
139
361
  x = re.sub(r"^\W+", "", x)
140
362
  x = re.sub(r"\W+$", "", x)
141
363
  msg = f"BCB API returned error: {x} - {symbol}"
142
- warnings.warn(msg)
143
- return None
364
+ raise BCBAPIError(msg, status_code=400)
144
365
 
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
148
- )
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),
153
- )
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)
154
508
  df1 = df.set_index("Date")
155
509
  n = ["bid", "ask"]
156
510
  df1 = df1[n]
@@ -159,13 +513,90 @@ def _get_symbol(
159
513
  return df1
160
514
 
161
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
549
+ def get(
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
+
162
592
  def get(
163
593
  symbols: Union[str, List[str]],
164
594
  start: DateInput,
165
595
  end: DateInput,
166
596
  side: str = "ask",
167
597
  groupby: str = "symbol",
168
- ) -> pd.DataFrame:
598
+ output: str = "dataframe",
599
+ ) -> Union[pd.DataFrame, str, Dict[str, str]]:
169
600
  """
170
601
  Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
171
602
 
@@ -204,11 +635,282 @@ def get(
204
635
  """
205
636
  if isinstance(symbols, str):
206
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
+
207
653
  dss = []
208
654
  for symbol in symbols:
209
- df1 = _get_symbol(symbol, start, end)
210
- if df1 is not None:
655
+ try:
656
+ df1 = _get_symbol(symbol, start, end)
211
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
+
212
914
  if len(dss) > 0:
213
915
  df = pd.concat(dss, axis=1)
214
916
  if side in ("bid", "ask"):
@@ -219,6 +921,8 @@ def get(
219
921
  return df
220
922
  elif groupby == "side":
221
923
  return df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
924
+ else:
925
+ raise ValueError("Unknown groupby value, use: symbol, side")
222
926
  else:
223
927
  raise ValueError("Unknown side value, use: bid, ask, both")
224
928
  else: