python-bcb 0.3.6__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
@@ -6,25 +6,25 @@ import re
6
6
  import threading
7
7
  from datetime import date, timedelta
8
8
  from io import BytesIO, StringIO
9
- from typing import TYPE_CHECKING, Dict, List, Literal, NamedTuple, Union, overload
9
+ from typing import Dict, List, Literal, NamedTuple, NoReturn, Union, overload
10
10
  from urllib.parse import urlencode
11
11
 
12
+ import httpx
12
13
  import numpy as np
13
14
  import pandas as pd
14
- from lxml import html
15
-
16
- from bcb.http import _CLIENT, _ASYNC_CLIENT
17
- from bcb.exceptions import (
18
- BCBAPIError,
19
- BCBAPINotFoundError,
20
- BCBRateLimitError,
21
- CurrencyNotFoundError,
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,
22
24
  )
25
+ from bcb.exceptions import BCBAPIError, CurrencyNotFoundError
23
26
  from bcb.utils import Date, DateInput
24
27
 
25
- if TYPE_CHECKING:
26
- import httpx
27
-
28
28
  logger = logging.getLogger(__name__)
29
29
 
30
30
  """
@@ -132,6 +132,8 @@ def clear_cache(cache: _ThreadSafeCache | None = None) -> None:
132
132
 
133
133
  def _currency_id_list(
134
134
  cache: _ThreadSafeCache | None = None,
135
+ *,
136
+ timeout: RequestTimeout = None,
135
137
  ) -> pd.DataFrame:
136
138
  """Fetch list of available currency IDs and names.
137
139
 
@@ -165,28 +167,18 @@ def _currency_id_list(
165
167
  "method=exibeFormularioConsultaBoletim"
166
168
  )
167
169
  logger.debug(f"Fetching currency ID list from {url1}")
168
- res = _CLIENT.get(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")
169
174
  logger.debug(
170
175
  f"Currency ID list response: status={res.status_code}, length={len(res.content)}"
171
176
  )
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)
177
+ raise_for_status(
178
+ res,
179
+ context="Currency ID list",
180
+ not_found_message="BCB API endpoint not found (404)",
181
+ )
190
182
 
191
183
  doc = html.parse(BytesIO(res.content)).getroot()
192
184
  xpath = "//select[@name='ChkMoeda']/option"
@@ -198,7 +190,11 @@ def _currency_id_list(
198
190
 
199
191
 
200
192
  def _get_valid_currency_list(
201
- _date: date, n: int = 0, max_rollback: int = 30
193
+ _date: date,
194
+ n: int = 0,
195
+ max_rollback: int = 30,
196
+ *,
197
+ timeout: RequestTimeout = None,
202
198
  ) -> "httpx.Response":
203
199
  """Fetch currency list CSV, rolling back dates if necessary.
204
200
 
@@ -237,31 +233,35 @@ def _get_valid_currency_list(
237
233
  url2 = f"https://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
238
234
  logger.debug(f"Fetching currency list from {url2}")
239
235
  try:
240
- res = _CLIENT.get(url2)
241
- except Exception as ex:
236
+ res = get_client().get(url2, **timeout_kwargs(timeout))
237
+ except httpx.HTTPError as ex:
242
238
  # Connection error: retry same date up to 3 times
243
239
  if n >= 3:
244
- raise ex
240
+ raise_for_request_error(ex, context="Currency list")
245
241
  logger.warning(
246
242
  f"Connection error fetching {url2}, retrying (attempt {n + 1}/3)"
247
243
  )
248
- return _get_valid_currency_list(_date, n + 1, max_rollback)
244
+ return _get_valid_currency_list(_date, n + 1, max_rollback, timeout=timeout)
249
245
 
250
246
  logger.debug(
251
247
  f"Currency list response: status={res.status_code}, length={len(res.content)}"
252
248
  )
253
249
  if res.status_code == 200:
254
250
  return res
255
- else:
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)
251
+ if res.status_code == 429 or res.status_code >= 500:
252
+ raise_for_status(res, context="Currency list")
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
+ )
261
259
 
262
260
 
263
261
  def get_currency_list(
264
262
  cache: _ThreadSafeCache | None = None,
263
+ *,
264
+ timeout: RequestTimeout = None,
265
265
  ) -> pd.DataFrame:
266
266
  """Listagem com todas as moedas disponíveis na API e suas configurações de paridade.
267
267
 
@@ -286,7 +286,7 @@ def get_currency_list(
286
286
  if cached is not None:
287
287
  return cached
288
288
 
289
- res = _get_valid_currency_list(date.today())
289
+ res = _get_valid_currency_list(date.today(), timeout=timeout)
290
290
  df = pd.read_csv(StringIO(res.text), delimiter=";")
291
291
  df.columns = [
292
292
  "code",
@@ -306,9 +306,9 @@ def get_currency_list(
306
306
  return df
307
307
 
308
308
 
309
- def _get_currency_id(symbol: str) -> int:
310
- id_list = _currency_id_list()
311
- all_currencies = get_currency_list()
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)
312
312
  x = pd.merge(id_list, all_currencies, on=["name"])
313
313
  matches = x.loc[x["symbol"] == symbol, "id"]
314
314
  if matches.empty:
@@ -316,8 +316,59 @@ def _get_currency_id(symbol: str) -> int:
316
316
  return int(matches.max())
317
317
 
318
318
 
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:
340
+ try:
341
+ doc = html.parse(BytesIO(content)).getroot()
342
+ except (etree.ParserError, ValueError):
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
350
+
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,
363
+ )
364
+
365
+
319
366
  def _fetch_symbol_response(
320
- symbol: str, start_date: DateInput, end_date: DateInput
367
+ symbol: str,
368
+ start_date: DateInput,
369
+ end_date: DateInput,
370
+ *,
371
+ timeout: RequestTimeout = None,
321
372
  ) -> "httpx.Response":
322
373
  """Fetch exchange rate CSV response for a symbol.
323
374
 
@@ -344,46 +395,28 @@ def _fetch_symbol_response(
344
395
  BCBAPIError
345
396
  If API returns other error status codes or HTML error page
346
397
  """
347
- cid = _get_currency_id(symbol) # Raises CurrencyNotFoundError if not found
398
+ cid = _get_currency_id(
399
+ symbol, timeout=timeout
400
+ ) # Raises CurrencyNotFoundError if not found
348
401
  url = _currency_url(cid, start_date, end_date)
349
402
  logger.debug(f"Fetching currency data for {symbol} from {url.split('?')[0]}")
350
- res = _CLIENT.get(url)
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}")
351
407
  logger.debug(
352
408
  f"Currency data response: status={res.status_code}, length={len(res.content)}"
353
409
  )
354
410
 
355
- # Handle HTML error response (e.g., no data for date range)
356
- if res.headers["Content-Type"].startswith("text/html"):
357
- doc = html.parse(BytesIO(res.content)).getroot()
358
- xpath = "//div[@class='msgErro']"
359
- elm = doc.xpath(xpath)[0]
360
- x = elm.text
361
- x = re.sub(r"^\W+", "", x)
362
- x = re.sub(r"\W+$", "", x)
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
- )
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
+ )
387
420
 
388
421
  return res
389
422
 
@@ -406,7 +439,12 @@ def _validate_currency_csv(csv_text: str) -> pd.DataFrame:
406
439
  BCBAPIError
407
440
  If CSV format is invalid (wrong column count)
408
441
  """
409
- df = pd.read_csv(StringIO(csv_text), delimiter=";", header=None, dtype=str)
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
410
448
 
411
449
  # Validate column count
412
450
  if len(df.columns) != 8:
@@ -440,10 +478,10 @@ def _parse_currency_dates(df: pd.DataFrame) -> pd.DataFrame:
440
478
  """
441
479
  try:
442
480
  df["Date"] = pd.to_datetime(df["Date"], format="%d%m%Y")
443
- except ValueError as e:
481
+ except (TypeError, ValueError) as e:
444
482
  raise BCBAPIError(
445
483
  f"Failed to parse currency date column: {str(e)}", status_code=400
446
- )
484
+ ) from e
447
485
  return df
448
486
 
449
487
 
@@ -468,15 +506,19 @@ def _parse_currency_types(df: pd.DataFrame) -> pd.DataFrame:
468
506
  try:
469
507
  df["bid"] = df["bid"].str.replace(",", ".").astype(np.float64)
470
508
  df["ask"] = df["ask"].str.replace(",", ".").astype(np.float64)
471
- except (ValueError, TypeError) as e:
509
+ except (TypeError, ValueError) as e:
472
510
  raise BCBAPIError(
473
511
  f"Failed to parse currency numeric columns: {str(e)}", status_code=400
474
- )
512
+ ) from e
475
513
  return df
476
514
 
477
515
 
478
516
  def _get_symbol(
479
- symbol: str, start_date: DateInput, end_date: DateInput
517
+ symbol: str,
518
+ start_date: DateInput,
519
+ end_date: DateInput,
520
+ *,
521
+ timeout: RequestTimeout = None,
480
522
  ) -> pd.DataFrame:
481
523
  """Fetch and parse exchange rate data for a symbol.
482
524
 
@@ -501,19 +543,25 @@ def _get_symbol(
501
543
  BCBAPIError
502
544
  If API returns error or data format is invalid
503
545
  """
504
- res = _fetch_symbol_response(symbol, start_date, end_date)
546
+ res = _fetch_symbol_response(symbol, start_date, end_date, timeout=timeout)
505
547
  df = _validate_currency_csv(res.text)
506
548
  df = _parse_currency_dates(df)
507
549
  df = _parse_currency_types(df)
508
550
  df1 = df.set_index("Date")
509
551
  n = ["bid", "ask"]
510
552
  df1 = df1[n]
511
- tuples = list(zip([symbol] * len(n), n))
553
+ tuples = list(zip([symbol] * len(n), n, strict=True))
512
554
  df1.columns = pd.MultiIndex.from_tuples(tuples)
513
555
  return df1
514
556
 
515
557
 
516
- def _get_symbol_text(symbol: str, start_date: DateInput, end_date: DateInput) -> str:
558
+ def _get_symbol_text(
559
+ symbol: str,
560
+ start_date: DateInput,
561
+ end_date: DateInput,
562
+ *,
563
+ timeout: RequestTimeout = None,
564
+ ) -> str:
517
565
  """Fetch exchange rate data as CSV text for a symbol.
518
566
 
519
567
  Parameters
@@ -537,12 +585,66 @@ def _get_symbol_text(symbol: str, start_date: DateInput, end_date: DateInput) ->
537
585
  BCBAPIError
538
586
  If API returns error
539
587
  """
540
- res = _fetch_symbol_response(symbol, start_date, end_date)
588
+ res = _fetch_symbol_response(symbol, start_date, end_date, timeout=timeout)
541
589
  return res.text
542
590
 
543
591
 
544
592
  # Type alias for text output with multiple symbols
545
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)
546
648
 
547
649
 
548
650
  @overload
@@ -550,9 +652,12 @@ def get(
550
652
  symbols: str,
551
653
  start: DateInput,
552
654
  end: DateInput,
553
- side: str = ...,
554
- groupby: str = ...,
655
+ side: CurrencySide = ...,
656
+ groupby: CurrencyGroupBy = ...,
555
657
  output: Literal["dataframe"] = ...,
658
+ tidy: bool = ...,
659
+ *,
660
+ timeout: RequestTimeout = ...,
556
661
  ) -> pd.DataFrame: ...
557
662
 
558
663
 
@@ -561,9 +666,12 @@ def get(
561
666
  symbols: List[str],
562
667
  start: DateInput,
563
668
  end: DateInput,
564
- side: str = ...,
565
- groupby: str = ...,
669
+ side: CurrencySide = ...,
670
+ groupby: CurrencyGroupBy = ...,
566
671
  output: Literal["dataframe"] = ...,
672
+ tidy: bool = ...,
673
+ *,
674
+ timeout: RequestTimeout = ...,
567
675
  ) -> pd.DataFrame: ...
568
676
 
569
677
 
@@ -572,9 +680,12 @@ def get(
572
680
  symbols: str,
573
681
  start: DateInput,
574
682
  end: DateInput,
575
- side: str = ...,
576
- groupby: str = ...,
683
+ side: CurrencySide = ...,
684
+ groupby: CurrencyGroupBy = ...,
577
685
  output: Literal["text"] = ...,
686
+ tidy: bool = ...,
687
+ *,
688
+ timeout: RequestTimeout = ...,
578
689
  ) -> str: ...
579
690
 
580
691
 
@@ -583,9 +694,12 @@ def get(
583
694
  symbols: List[str],
584
695
  start: DateInput,
585
696
  end: DateInput,
586
- side: str = ...,
587
- groupby: str = ...,
697
+ side: CurrencySide = ...,
698
+ groupby: CurrencyGroupBy = ...,
588
699
  output: Literal["text"] = ...,
700
+ tidy: bool = ...,
701
+ *,
702
+ timeout: RequestTimeout = ...,
589
703
  ) -> CurrencyTextResult: ...
590
704
 
591
705
 
@@ -593,9 +707,12 @@ def get(
593
707
  symbols: Union[str, List[str]],
594
708
  start: DateInput,
595
709
  end: DateInput,
596
- side: str = "ask",
597
- groupby: str = "symbol",
598
- output: str = "dataframe",
710
+ side: CurrencySide = "ask",
711
+ groupby: CurrencyGroupBy = "symbol",
712
+ output: CurrencyOutput = "dataframe",
713
+ tidy: bool = False,
714
+ *,
715
+ timeout: RequestTimeout = None,
599
716
  ) -> Union[pd.DataFrame, str, Dict[str, str]]:
600
717
  """
601
718
  Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
@@ -607,18 +724,28 @@ def get(
607
724
  Códigos das moedas padrão ISO. O código de uma única moeda que
608
725
  retorna uma série temporal univariada e uma lista de códigos
609
726
  retorna uma série temporal multivariada.
610
- start : str, int, date, datetime, Timestamp
611
- Data de início da série.
612
- Interpreta diferentes tipos e formatos de datas.
613
- end : string, int, date, datetime, Timestamp
614
- Data de início da série.
615
- Interpreta diferentes tipos e formatos de datas.
616
- 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"
617
734
  Define se a série retornada vem com os ``ask`` prices,
618
735
  ``bid`` prices ou ``both`` para ambos.
619
- groupby : str
736
+ groupby : {"symbol", "side"}, default "symbol"
620
737
  Define se os índices de coluna são agrupados por ``symbol`` ou
621
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.
622
749
 
623
750
  Returns
624
751
  -------
@@ -633,19 +760,20 @@ def get(
633
760
  DataFrame :
634
761
  Série temporal com cotações diárias das moedas solicitadas.
635
762
  """
636
- if isinstance(symbols, str):
637
- symbols = [symbols]
763
+ symbols = _validate_currency_query_inputs(
764
+ symbols, start, end, side, groupby, output
765
+ )
638
766
 
639
767
  if output == "text":
640
768
  results: Dict[str, str] = {}
641
769
  for symbol in symbols:
642
770
  try:
643
- raw = _get_symbol_text(symbol, start, end)
771
+ raw = _get_symbol_text(symbol, start, end, timeout=timeout)
644
772
  results[symbol] = raw
645
773
  except CurrencyNotFoundError:
646
774
  pass # Skip missing currencies
647
775
  if not results:
648
- raise CurrencyNotFoundError(f"Currency not found: {symbols}")
776
+ _raise_no_valid_currency_symbols(symbols)
649
777
  if len(symbols) == 1:
650
778
  return results[symbols[0]]
651
779
  return results
@@ -653,12 +781,14 @@ def get(
653
781
  dss = []
654
782
  for symbol in symbols:
655
783
  try:
656
- df1 = _get_symbol(symbol, start, end)
784
+ df1 = _get_symbol(symbol, start, end, timeout=timeout)
657
785
  dss.append(df1)
658
786
  except CurrencyNotFoundError:
659
787
  pass # Skip missing currencies
660
788
  if len(dss) > 0:
661
789
  df = pd.concat(dss, axis=1)
790
+ if tidy:
791
+ return _tidy_df(df, side)
662
792
  if side in ("bid", "ask"):
663
793
  dx = df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
664
794
  return dx[side]
@@ -672,11 +802,13 @@ def get(
672
802
  else:
673
803
  raise ValueError("Unknown side value, use: bid, ask, both")
674
804
  else:
675
- raise CurrencyNotFoundError(f"Currency not found: {symbols}")
805
+ _raise_no_valid_currency_symbols(symbols)
676
806
 
677
807
 
678
808
  async def _async_currency_id_list(
679
809
  cache: _ThreadSafeCache | None = None,
810
+ *,
811
+ timeout: RequestTimeout = None,
680
812
  ) -> pd.DataFrame:
681
813
  """Async version of _currency_id_list()."""
682
814
  cache = cache or _DEFAULT_CACHE
@@ -689,25 +821,15 @@ async def _async_currency_id_list(
689
821
  "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
690
822
  "method=exibeFormularioConsultaBoletim"
691
823
  )
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)
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
+ )
711
833
 
712
834
  doc = html.parse(BytesIO(res.content)).getroot()
713
835
  xpath = "//select[@name='ChkMoeda']/option"
@@ -719,7 +841,11 @@ async def _async_currency_id_list(
719
841
 
720
842
 
721
843
  async def _async_get_valid_currency_list(
722
- _date: date, n: int = 0, max_rollback: int = 30
844
+ _date: date,
845
+ n: int = 0,
846
+ max_rollback: int = 30,
847
+ *,
848
+ timeout: RequestTimeout = None,
723
849
  ) -> "httpx.Response":
724
850
  """Async version of _get_valid_currency_list()."""
725
851
  days_rolled_back = (date.today() - _date).days
@@ -731,22 +857,27 @@ async def _async_get_valid_currency_list(
731
857
 
732
858
  url2 = f"https://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
733
859
  try:
734
- res = await _ASYNC_CLIENT.get(url2)
735
- except Exception as ex:
860
+ res = await get_async_client().get(url2, **timeout_kwargs(timeout))
861
+ except httpx.HTTPError as ex:
736
862
  if n >= 3:
737
- raise ex
738
- return await _async_get_valid_currency_list(_date, n + 1, max_rollback)
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
+ )
739
867
 
740
868
  if res.status_code == 200:
741
869
  return res
742
- else:
743
- return await _async_get_valid_currency_list(
744
- _date - timedelta(1), 0, max_rollback
745
- )
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
+ )
746
875
 
747
876
 
748
877
  async def _async_get_currency_list(
749
878
  cache: _ThreadSafeCache | None = None,
879
+ *,
880
+ timeout: RequestTimeout = None,
750
881
  ) -> pd.DataFrame:
751
882
  """Async version of get_currency_list()."""
752
883
  cache = cache or _DEFAULT_CACHE
@@ -755,7 +886,7 @@ async def _async_get_currency_list(
755
886
  if cached is not None:
756
887
  return cached
757
888
 
758
- res = await _async_get_valid_currency_list(date.today())
889
+ res = await _async_get_valid_currency_list(date.today(), timeout=timeout)
759
890
  df = pd.read_csv(StringIO(res.text), delimiter=";")
760
891
  df.columns = [
761
892
  "code",
@@ -775,11 +906,11 @@ async def _async_get_currency_list(
775
906
  return df
776
907
 
777
908
 
778
- async def _async_get_currency_id(symbol: str) -> int:
909
+ async def _async_get_currency_id(symbol: str, *, timeout: RequestTimeout = None) -> int:
779
910
  """Async version of _get_currency_id() with concurrent cache warming."""
780
911
  id_list, all_currencies = await asyncio.gather(
781
- _async_currency_id_list(),
782
- _async_get_currency_list(),
912
+ _async_currency_id_list(timeout=timeout),
913
+ _async_get_currency_list(timeout=timeout),
783
914
  )
784
915
  x = pd.merge(id_list, all_currencies, on=["name"])
785
916
  matches = x.loc[x["symbol"] == symbol, "id"]
@@ -789,68 +920,65 @@ async def _async_get_currency_id(symbol: str) -> int:
789
920
 
790
921
 
791
922
  async def _async_fetch_symbol_response(
792
- symbol: str, start_date: DateInput, end_date: DateInput
923
+ symbol: str,
924
+ start_date: DateInput,
925
+ end_date: DateInput,
926
+ *,
927
+ timeout: RequestTimeout = None,
793
928
  ) -> "httpx.Response":
794
929
  """Async version of _fetch_symbol_response()."""
795
- cid = await _async_get_currency_id(symbol)
930
+ cid = await _async_get_currency_id(symbol, timeout=timeout)
796
931
  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
- )
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
+ )
829
945
 
830
946
  return res
831
947
 
832
948
 
833
949
  async def _async_get_symbol(
834
- symbol: str, start_date: DateInput, end_date: DateInput
950
+ symbol: str,
951
+ start_date: DateInput,
952
+ end_date: DateInput,
953
+ *,
954
+ timeout: RequestTimeout = None,
835
955
  ) -> pd.DataFrame:
836
956
  """Async version of _get_symbol()."""
837
- res = await _async_fetch_symbol_response(symbol, start_date, end_date)
957
+ res = await _async_fetch_symbol_response(
958
+ symbol, start_date, end_date, timeout=timeout
959
+ )
838
960
  df = _validate_currency_csv(res.text)
839
961
  df = _parse_currency_dates(df)
840
962
  df = _parse_currency_types(df)
841
963
  df1 = df.set_index("Date")
842
964
  n = ["bid", "ask"]
843
965
  df1 = df1[n]
844
- tuples = list(zip([symbol] * len(n), n))
966
+ tuples = list(zip([symbol] * len(n), n, strict=True))
845
967
  df1.columns = pd.MultiIndex.from_tuples(tuples)
846
968
  return df1
847
969
 
848
970
 
849
971
  async def _async_get_symbol_text(
850
- symbol: str, start_date: DateInput, end_date: DateInput
972
+ symbol: str,
973
+ start_date: DateInput,
974
+ end_date: DateInput,
975
+ *,
976
+ timeout: RequestTimeout = None,
851
977
  ) -> str:
852
978
  """Async version of _get_symbol_text()."""
853
- res = await _async_fetch_symbol_response(symbol, start_date, end_date)
979
+ res = await _async_fetch_symbol_response(
980
+ symbol, start_date, end_date, timeout=timeout
981
+ )
854
982
  return res.text
855
983
 
856
984
 
@@ -858,9 +986,12 @@ async def async_get(
858
986
  symbols: Union[str, List[str]],
859
987
  start: DateInput,
860
988
  end: DateInput,
861
- side: str = "ask",
862
- groupby: str = "symbol",
863
- output: str = "dataframe",
989
+ side: CurrencySide = "ask",
990
+ groupby: CurrencyGroupBy = "symbol",
991
+ output: CurrencyOutput = "dataframe",
992
+ tidy: bool = False,
993
+ *,
994
+ timeout: RequestTimeout = None,
864
995
  ) -> Union[pd.DataFrame, str, Dict[str, str]]:
865
996
  """
866
997
  Retorna um DataFrame pandas com séries temporais com taxas de câmbio (async version).
@@ -873,46 +1004,73 @@ async def async_get(
873
1004
  ----------
874
1005
  symbols : str, List[str]
875
1006
  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
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"}
881
1014
  ``'ask'``, ``'bid'`` ou ``'both'``
882
- groupby : str
1015
+ groupby : {"symbol", "side"}
883
1016
  ``'symbol'`` ou ``'side'``
884
- output : str
1017
+ output : {"dataframe", "text"}
885
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.
886
1027
 
887
1028
  Returns
888
1029
  -------
889
1030
  Union[pd.DataFrame, str, Dict[str, str]]
890
1031
  Série temporal conforme especificado
891
1032
  """
892
- if isinstance(symbols, str):
893
- symbols = [symbols]
1033
+ symbols = _validate_currency_query_inputs(
1034
+ symbols, start, end, side, groupby, output
1035
+ )
894
1036
 
895
1037
  if output == "text":
896
1038
  results: Dict[str, str] = {}
897
1039
  texts = await asyncio.gather(
898
- *[_async_get_symbol_text(symbol, start, end) for symbol in symbols]
1040
+ *[
1041
+ _async_get_symbol_text(symbol, start, end, timeout=timeout)
1042
+ for symbol in symbols
1043
+ ],
1044
+ return_exceptions=True,
899
1045
  )
900
- for symbol, text in zip(symbols, texts):
901
- if text is not None:
902
- results[symbol] = text
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
903
1052
  if not results:
904
- raise CurrencyNotFoundError(f"Currency not found: {symbols}")
1053
+ _raise_no_valid_currency_symbols(symbols)
905
1054
  if len(symbols) == 1:
906
1055
  return results[symbols[0]]
907
1056
  return results
908
1057
 
909
1058
  dss = await asyncio.gather(
910
- *[_async_get_symbol(symbol, start, end) for symbol in symbols]
1059
+ *[_async_get_symbol(symbol, start, end, timeout=timeout) for symbol in symbols],
1060
+ return_exceptions=True,
911
1061
  )
912
- dss = [df for df in dss if df is not None]
913
-
914
- if len(dss) > 0:
915
- df = pd.concat(dss, axis=1)
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)
916
1074
  if side in ("bid", "ask"):
917
1075
  dx = df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
918
1076
  return dx[side]
@@ -926,4 +1084,4 @@ async def async_get(
926
1084
  else:
927
1085
  raise ValueError("Unknown side value, use: bid, ask, both")
928
1086
  else:
929
- raise CurrencyNotFoundError(f"Currency not found: {symbols}")
1087
+ _raise_no_valid_currency_symbols(symbols)