python-bcb 0.3.2__py3-none-any.whl → 0.3.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bcb/__init__.py CHANGED
@@ -1,3 +1,10 @@
1
+ from .exceptions import (
2
+ BCBError,
3
+ BCBAPIError,
4
+ CurrencyNotFoundError,
5
+ SGSError,
6
+ ODataError,
7
+ )
1
8
  from .odata.api import (
2
9
  ODataAPI,
3
10
  Expectativas,
bcb/currency.py CHANGED
@@ -1,62 +1,74 @@
1
1
  import re
2
2
  import warnings
3
- from io import BytesIO, StringIO
4
3
  from datetime import date, timedelta
4
+ from io import BytesIO, StringIO
5
+ from typing import List, Optional, Union
5
6
 
6
- import requests
7
- from lxml import html
8
-
9
- import pandas as pd
7
+ import httpx
10
8
  import numpy as np
9
+ import pandas as pd
10
+ from lxml import html
11
11
 
12
- from .utils import Date
12
+ from .exceptions import BCBAPIError, CurrencyNotFoundError
13
+ from .utils import Date, DateInput
13
14
 
14
15
  """
15
16
  O módulo :py:mod:`bcb.currency` tem como objetivo fazer consultas no site do conversor de moedas do BCB.
16
17
  """
17
18
 
18
19
 
19
- def _currency_url(currency_id, start_date, end_date):
20
+ def _currency_url(currency_id: int, start_date: DateInput, end_date: DateInput) -> str:
20
21
  start_date = Date(start_date)
21
22
  end_date = Date(end_date)
22
- url = (
23
- "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
24
- "method=gerarCSVFechamentoMoedaNoPeriodo&"
25
- "ChkMoeda={}&DATAINI={:%d/%m/%Y}&DATAFIM={:%d/%m/%Y}"
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}"
26
27
  )
27
- return url.format(currency_id, start_date.date, end_date.date)
28
28
 
29
29
 
30
- CACHE = dict()
30
+ _CACHE: dict[str, pd.DataFrame] = dict()
31
+
31
32
 
33
+ def clear_cache() -> None:
34
+ """Clear the module-level session cache.
32
35
 
33
- def _currency_id_list():
34
- if CACHE.get("TEMP_CURRENCY_ID_LIST") is not None:
35
- return CACHE.get("TEMP_CURRENCY_ID_LIST")
36
+ :func:`get` and :func:`get_currency_list` cache the currency ID list and
37
+ the full currency master table for the duration of the Python session so
38
+ that repeated calls do not make redundant HTTP requests. Call this
39
+ function to force a fresh fetch on the next request (useful in tests or
40
+ long-running scripts where the master data may have changed).
41
+ """
42
+ _CACHE.clear()
43
+
44
+
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")
36
48
  else:
37
49
  url1 = (
38
50
  "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
39
51
  "method=exibeFormularioConsultaBoletim"
40
52
  )
41
- res = requests.get(url1)
53
+ res = httpx.get(url1, follow_redirects=True)
42
54
  if res.status_code != 200:
43
55
  msg = f"BCB API Request error, status code = {res.status_code}"
44
- raise Exception(msg)
56
+ raise BCBAPIError(msg, res.status_code)
45
57
 
46
58
  doc = html.parse(BytesIO(res.content)).getroot()
47
59
  xpath = "//select[@name='ChkMoeda']/option"
48
60
  x = [(elm.text, elm.get("value")) for elm in doc.xpath(xpath)]
49
61
  df = pd.DataFrame(x, columns=["name", "id"])
50
62
  df["id"] = df["id"].astype("int32")
51
- CACHE["TEMP_CURRENCY_ID_LIST"] = df
63
+ _CACHE["TEMP_CURRENCY_ID_LIST"] = df
52
64
  return df
53
65
 
54
66
 
55
- def _get_valid_currency_list(_date, n=0):
67
+ def _get_valid_currency_list(_date: date, n: int = 0) -> httpx.Response:
56
68
  url2 = f"http://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
57
69
  try:
58
- res = requests.get(url2)
59
- except requests.exceptions.ConnectionError as ex:
70
+ res = httpx.get(url2, follow_redirects=True)
71
+ except httpx.ConnectError as ex:
60
72
  if n >= 3:
61
73
  raise ex
62
74
  return _get_valid_currency_list(_date, n + 1)
@@ -66,7 +78,7 @@ def _get_valid_currency_list(_date, n=0):
66
78
  return _get_valid_currency_list(_date - timedelta(1), 0)
67
79
 
68
80
 
69
- def get_currency_list():
81
+ def get_currency_list() -> pd.DataFrame:
70
82
  """
71
83
  Listagem com todas as moedas disponíveis na API e suas configurações de paridade.
72
84
 
@@ -76,8 +88,8 @@ def get_currency_list():
76
88
  DataFrame :
77
89
  Tabela com a listagem de moedas disponíveis.
78
90
  """
79
- if CACHE.get("TEMP_FILE_CURRENCY_LIST") is not None:
80
- return CACHE.get("TEMP_FILE_CURRENCY_LIST")
91
+ if _CACHE.get("TEMP_FILE_CURRENCY_LIST") is not None:
92
+ return _CACHE.get("TEMP_FILE_CURRENCY_LIST")
81
93
  else:
82
94
  res = _get_valid_currency_list(date.today())
83
95
  df = pd.read_csv(StringIO(res.text), delimiter=";")
@@ -95,21 +107,29 @@ def get_currency_list():
95
107
  df["country_code"] = df["country_code"].astype("int32")
96
108
  df["code"] = df["code"].astype("int32")
97
109
  df["symbol"] = df["symbol"].str.strip()
98
- CACHE["TEMP_FILE_CURRENCY_LIST"] = df
110
+ _CACHE["TEMP_FILE_CURRENCY_LIST"] = df
99
111
  return df
100
112
 
101
113
 
102
- def _get_currency_id(symbol):
114
+ def _get_currency_id(symbol: str) -> int:
103
115
  id_list = _currency_id_list()
104
116
  all_currencies = get_currency_list()
105
117
  x = pd.merge(id_list, all_currencies, on=["name"])
106
- return np.max(x.loc[x["symbol"] == symbol, "id"])
118
+ matches = x.loc[x["symbol"] == symbol, "id"]
119
+ if matches.empty:
120
+ raise CurrencyNotFoundError(f"Unknown currency symbol: {symbol}")
121
+ return int(matches.max())
107
122
 
108
123
 
109
- def _get_symbol(symbol, start_date, end_date):
110
- cid = _get_currency_id(symbol)
124
+ def _get_symbol(
125
+ 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
111
131
  url = _currency_url(cid, start_date, end_date)
112
- res = requests.get(url)
132
+ res = httpx.get(url, follow_redirects=True)
113
133
 
114
134
  if res.headers["Content-Type"].startswith("text/html"):
115
135
  doc = html.parse(BytesIO(res.content)).getroot()
@@ -118,7 +138,7 @@ def _get_symbol(symbol, start_date, end_date):
118
138
  x = elm.text
119
139
  x = re.sub(r"^\W+", "", x)
120
140
  x = re.sub(r"\W+$", "", x)
121
- msg = "BCB API returned error: {} - {}".format(x, symbol)
141
+ msg = f"BCB API returned error: {x} - {symbol}"
122
142
  warnings.warn(msg)
123
143
  return None
124
144
 
@@ -139,7 +159,13 @@ def _get_symbol(symbol, start_date, end_date):
139
159
  return df1
140
160
 
141
161
 
142
- def get(symbols, start, end, side="ask", groupby="symbol"):
162
+ def get(
163
+ symbols: Union[str, List[str]],
164
+ start: DateInput,
165
+ end: DateInput,
166
+ side: str = "ask",
167
+ groupby: str = "symbol",
168
+ ) -> pd.DataFrame:
143
169
  """
144
170
  Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
145
171
 
@@ -166,6 +192,13 @@ def get(symbols, start, end, side="ask", groupby="symbol"):
166
192
  Returns
167
193
  -------
168
194
 
195
+ Notes
196
+ -----
197
+ The currency ID list and the master currency table are cached in memory
198
+ for the lifetime of the Python session so that multiple calls to
199
+ :func:`get` do not repeat the same HTTP requests. Use
200
+ :func:`clear_cache` to invalidate the cache when fresh data is needed.
201
+
169
202
  DataFrame :
170
203
  Série temporal com cotações diárias das moedas solicitadas.
171
204
  """
@@ -187,6 +220,6 @@ def get(symbols, start, end, side="ask", groupby="symbol"):
187
220
  elif groupby == "side":
188
221
  return df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
189
222
  else:
190
- raise Exception(f"Unknown side value, use: bid, ask, both")
223
+ raise ValueError("Unknown side value, use: bid, ask, both")
191
224
  else:
192
- return None
225
+ raise CurrencyNotFoundError(f"Currency not found: {symbols}")
bcb/exceptions.py ADDED
@@ -0,0 +1,22 @@
1
+ class BCBError(Exception):
2
+ """Base exception for all python-bcb errors."""
3
+
4
+
5
+ class BCBAPIError(BCBError):
6
+ """HTTP or API-level error from BCB."""
7
+
8
+ def __init__(self, message: str, status_code: int | None = None):
9
+ super().__init__(message)
10
+ self.status_code = status_code
11
+
12
+
13
+ class CurrencyNotFoundError(BCBError):
14
+ """Raised when a requested currency symbol is not found."""
15
+
16
+
17
+ class SGSError(BCBError):
18
+ """Raised for SGS-specific API errors."""
19
+
20
+
21
+ class ODataError(BCBError):
22
+ """Raised for OData query/metadata errors."""
bcb/odata/api.py CHANGED
@@ -1,3 +1,4 @@
1
+ from typing import Any, Optional
1
2
  from .framework import (
2
3
  ODataEntitySet,
3
4
  ODataFunctionImport,
@@ -13,10 +14,10 @@ OLINDA_BASE_URL = "https://olinda.bcb.gov.br/olinda/servico"
13
14
 
14
15
 
15
16
  class EndpointMeta(type):
16
- def __init__(self, *args, **kwargs):
17
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
17
18
  super().__init__(*args, **kwargs)
18
19
 
19
- def __call__(self, *args):
20
+ def __call__(self, *args: Any) -> Any:
20
21
  obj = super().__call__(*args)
21
22
  entity = args[0]
22
23
  if isinstance(entity, ODataEntitySet):
@@ -29,10 +30,10 @@ class EndpointMeta(type):
29
30
 
30
31
 
31
32
  class EndpointQuery(ODataQuery):
32
- _DATE_COLUMN_NAMES_BY_ENDPOINT = {
33
+ _DATE_COLUMN_NAMES_BY_ENDPOINT: dict[str, dict[str, str]] = {
33
34
  "IfDataCadastro": {"Data": "%Y%m"}
34
35
  }
35
- _DATE_COLUMN_NAMES = {
36
+ _DATE_COLUMN_NAMES: set[str] = {
36
37
  "Data",
37
38
  "dataHoraCotacao",
38
39
  "InicioPeriodo",
@@ -40,15 +41,36 @@ class EndpointQuery(ODataQuery):
40
41
  "DataVigencia",
41
42
  }
42
43
 
43
- def collect(self):
44
+ def __init__(
45
+ self,
46
+ entity: Any,
47
+ url: str,
48
+ date_columns: Optional[list[str]] = None,
49
+ ) -> None:
50
+ super().__init__(entity, url)
51
+ self._date_columns: list[str] = date_columns or []
52
+
53
+ def collect(self) -> pd.DataFrame:
44
54
  raw_data = super().collect()
45
55
  data = pd.DataFrame(raw_data["value"])
46
56
  if not self._raw:
47
- for col in self._DATE_COLUMN_NAMES:
48
- if self.entity.name in self._DATE_COLUMN_NAMES_BY_ENDPOINT and col in self._DATE_COLUMN_NAMES_BY_ENDPOINT[self.entity.name]:
49
- data[col] = pd.to_datetime(data[col], format=self._DATE_COLUMN_NAMES_BY_ENDPOINT[self.entity.name][col])
50
- elif col in data.columns:
51
- data[col] = pd.to_datetime(data[col])
57
+ if self._date_columns:
58
+ # Use the explicit list provided by the API subclass.
59
+ for col in self._date_columns:
60
+ if col in data.columns:
61
+ data[col] = pd.to_datetime(data[col])
62
+ else:
63
+ # Fall back to the built-in heuristic.
64
+ endpoint_overrides = self._DATE_COLUMN_NAMES_BY_ENDPOINT.get(
65
+ self.entity.name, {}
66
+ )
67
+ for col in self._DATE_COLUMN_NAMES:
68
+ if col in endpoint_overrides:
69
+ data[col] = pd.to_datetime(
70
+ data[col], format=endpoint_overrides[col]
71
+ )
72
+ elif col in data.columns:
73
+ data[col] = pd.to_datetime(data[col])
52
74
  return data
53
75
 
54
76
 
@@ -65,7 +87,10 @@ class Endpoint(metaclass=EndpointMeta):
65
87
  :py:meth:`bcb.odata.api.BaseODataAPI.get_endpoint` das classes que herdam
66
88
  :py:class:`bcb.odata.api.BaseODataAPI`.
67
89
  """
68
- def __init__(self, entity, url):
90
+
91
+ def __init__(
92
+ self, entity: Any, url: str, date_columns: Optional[list[str]] = None
93
+ ) -> None:
69
94
  """
70
95
  Construtor da classe Endpoint.
71
96
 
@@ -76,11 +101,15 @@ class Endpoint(metaclass=EndpointMeta):
76
101
  Obtidos da classe ``bcb.odata.framework.ODataService``.
77
102
  url : str
78
103
  URL da API OData.
104
+ date_columns : list[str], optional
105
+ Colunas a converter para datetime. Quando fornecido, substitui a
106
+ heurística padrão de detecção de datas.
79
107
  """
80
108
  self._entity = entity
81
109
  self._url = url
110
+ self._date_columns: list[str] = date_columns or []
82
111
 
83
- def get(self, *args, **kwargs):
112
+ def get(self, *args: Any, **kwargs: Any) -> pd.DataFrame:
84
113
  """
85
114
  Executa a consulta na API OData e retorna o resultado.
86
115
 
@@ -94,7 +123,7 @@ class Endpoint(metaclass=EndpointMeta):
94
123
  -------
95
124
  pd.DataFrame: resultado da consulta
96
125
  """
97
- _query = EndpointQuery(self._entity, self._url)
126
+ _query = EndpointQuery(self._entity, self._url, self._date_columns)
98
127
  for arg in args:
99
128
  if isinstance(arg, ODataPropertyFilter):
100
129
  _query.filter(arg)
@@ -120,7 +149,7 @@ class Endpoint(metaclass=EndpointMeta):
120
149
  _query.reset()
121
150
  return data
122
151
 
123
- def query(self):
152
+ def query(self) -> EndpointQuery:
124
153
  """
125
154
  Retorna uma instância de EndpointQuery através da qual se construirá a consulta na API OData.
126
155
 
@@ -128,7 +157,7 @@ class Endpoint(metaclass=EndpointMeta):
128
157
  -------
129
158
  bcb.odata.api.EndpointQuery
130
159
  """
131
- return EndpointQuery(self._entity, self._url)
160
+ return EndpointQuery(self._entity, self._url, self._date_columns)
132
161
 
133
162
 
134
163
  class BaseODataAPI:
@@ -138,13 +167,16 @@ class BaseODataAPI:
138
167
  Essa classe não deve ser acessada diretamente.
139
168
  """
140
169
 
141
- def __init__(self):
170
+ BASE_URL: str
171
+ DATE_COLUMNS: list[str] = []
172
+
173
+ def __init__(self) -> None:
142
174
  """
143
175
  BaseODataAPI construtor
144
176
  """
145
177
  self.service = ODataService(self.BASE_URL)
146
178
 
147
- def describe(self, endpoint=None):
179
+ def describe(self, endpoint: Optional[str] = None) -> None:
148
180
  """
149
181
  Mostra a descrição de uma API ou de um *endpoint*
150
182
  específico.
@@ -166,7 +198,7 @@ class BaseODataAPI:
166
198
  else:
167
199
  self.service.describe()
168
200
 
169
- def get_endpoint(self, endpoint):
201
+ def get_endpoint(self, endpoint: str) -> Endpoint:
170
202
  """
171
203
  Obtem o *endpoint*
172
204
 
@@ -186,7 +218,9 @@ class BaseODataAPI:
186
218
  ValueError
187
219
  Se o *endpoint* fornecido é errado.
188
220
  """
189
- return Endpoint(self.service[endpoint], self.service.url)
221
+ return Endpoint(
222
+ self.service[endpoint], self.service.url, self.DATE_COLUMNS or None
223
+ )
190
224
 
191
225
 
192
226
  class ODataAPI(BaseODataAPI):
@@ -200,7 +234,7 @@ class ODataAPI(BaseODataAPI):
200
234
  não possuem implementação específica.
201
235
  """
202
236
 
203
- def __init__(self, url):
237
+ def __init__(self, url: str) -> None:
204
238
  """
205
239
  Parameters
206
240
  ----------
@@ -411,8 +445,8 @@ class TarifasBancariasPorInstituicaoFinanceira(BaseODataAPI):
411
445
  cobradas por instituições financeiras, por Segmento e por Instituição.
412
446
  """
413
447
 
414
- K = "Informes_ListaTarifasPorInstituicaoFinanceira"
415
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
448
+ SERVICE_KEY = "Informes_ListaTarifasPorInstituicaoFinanceira"
449
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
416
450
 
417
451
 
418
452
  class TarifasBancariasPorServico(BaseODataAPI):
@@ -424,8 +458,8 @@ class TarifasBancariasPorServico(BaseODataAPI):
424
458
  por serviço.
425
459
  """
426
460
 
427
- K = "Informes_ListaValoresDeServicoBancario"
428
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
461
+ SERVICE_KEY = "Informes_ListaValoresDeServicoBancario"
462
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
429
463
 
430
464
 
431
465
  class PostosAtendimentoEletronicoPorInstituicaoFinanceira(BaseODataAPI):
@@ -437,8 +471,8 @@ class PostosAtendimentoEletronicoPorInstituicaoFinanceira(BaseODataAPI):
437
471
  pelo Banco Central.
438
472
  """
439
473
 
440
- K = "Informes_PostosDeAtendimentoEletronico"
441
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
474
+ SERVICE_KEY = "Informes_PostosDeAtendimentoEletronico"
475
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
442
476
 
443
477
 
444
478
  class PostosAtendimentoCorrespondentesPorInstituicaoFinanceira(BaseODataAPI):
@@ -451,8 +485,8 @@ class PostosAtendimentoCorrespondentesPorInstituicaoFinanceira(BaseODataAPI):
451
485
  descrito na Resolução 3.954.
452
486
  """
453
487
 
454
- K = "Informes_Correspondentes"
455
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
488
+ SERVICE_KEY = "Informes_Correspondentes"
489
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
456
490
 
457
491
 
458
492
  class EstatisticasSTR(BaseODataAPI):
@@ -464,8 +498,8 @@ class EstatisticasSTR(BaseODataAPI):
464
498
  mantidas pelos participantes no Banco Central.
465
499
  """
466
500
 
467
- K = "STR"
468
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
501
+ SERVICE_KEY = "STR"
502
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
469
503
 
470
504
 
471
505
  class DinheiroCirculacao(BaseODataAPI):
@@ -478,8 +512,8 @@ class DinheiroCirculacao(BaseODataAPI):
478
512
  Real (símbolos : R$, BRL).
479
513
  """
480
514
 
481
- K = "mecir_dinheiro_em_circulacao"
482
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
515
+ SERVICE_KEY = "mecir_dinheiro_em_circulacao"
516
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
483
517
 
484
518
 
485
519
  # /Informes_Ouvidorias/versao/v1/odata/