python-bcb 0.3.3__py3-none-any.whl → 0.3.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bcb/exceptions.py ADDED
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class BCBError(Exception):
5
+ """Base exception for all python-bcb errors."""
6
+
7
+
8
+ class BCBAPIError(BCBError):
9
+ """HTTP or API-level error from BCB."""
10
+
11
+ def __init__(self, message: str, status_code: int):
12
+ super().__init__(message)
13
+ self.status_code = status_code
14
+
15
+
16
+ class BCBAPINotFoundError(BCBAPIError):
17
+ """Raised when API returns 404 Not Found."""
18
+
19
+ pass
20
+
21
+
22
+ class BCBRateLimitError(BCBAPIError):
23
+ """Raised when API returns 429 Too Many Requests (rate limit exceeded)."""
24
+
25
+ pass
26
+
27
+
28
+ class BCBAPIServerError(BCBAPIError):
29
+ """Raised when API returns 5xx Server Error."""
30
+
31
+ pass
32
+
33
+
34
+ class CurrencyNotFoundError(BCBError):
35
+ """Raised when a requested currency symbol is not found."""
36
+
37
+
38
+ class SGSError(BCBError):
39
+ """Raised for SGS-specific API errors."""
40
+
41
+
42
+ class ODataError(BCBError):
43
+ """Raised for OData query/metadata errors."""
bcb/http.py ADDED
@@ -0,0 +1,98 @@
1
+ """Shared HTTP client and utilities for python-bcb."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, TypeVar
6
+
7
+ import httpx
8
+ from tenacity import (
9
+ retry,
10
+ stop_after_attempt,
11
+ wait_exponential,
12
+ )
13
+
14
+ # Default timeout for all HTTP requests (seconds)
15
+ DEFAULT_TIMEOUT = 30.0
16
+
17
+ # Shared synchronous HTTP client
18
+ _CLIENT = httpx.Client(
19
+ timeout=DEFAULT_TIMEOUT,
20
+ follow_redirects=True,
21
+ )
22
+
23
+ # Shared asynchronous HTTP client (for future async API)
24
+ _ASYNC_CLIENT = httpx.AsyncClient(
25
+ timeout=DEFAULT_TIMEOUT,
26
+ follow_redirects=True,
27
+ )
28
+
29
+
30
+ # Retry decorator for transient failures
31
+ # Retries on any exception (connection errors, timeouts, HTTP 5xx, etc.)
32
+ _retry_decorator = retry(
33
+ stop=stop_after_attempt(4), # 1 initial + 3 retries = 4 attempts
34
+ wait=wait_exponential(multiplier=1, min=1, max=10),
35
+ reraise=True,
36
+ )
37
+
38
+
39
+ def get_client() -> httpx.Client:
40
+ """Get the shared synchronous HTTP client.
41
+
42
+ Returns
43
+ -------
44
+ httpx.Client
45
+ Shared client with connection pooling and configured timeout.
46
+ """
47
+ return _CLIENT
48
+
49
+
50
+ def get_async_client() -> httpx.AsyncClient:
51
+ """Get the shared asynchronous HTTP client.
52
+
53
+ Returns
54
+ -------
55
+ httpx.AsyncClient
56
+ Shared async client with connection pooling and configured timeout.
57
+ """
58
+ return _ASYNC_CLIENT
59
+
60
+
61
+ def close_async_client() -> None:
62
+ """Close the shared async client.
63
+
64
+ Call this in long-running applications before shutdown to properly
65
+ close HTTP connections.
66
+ """
67
+ import asyncio
68
+
69
+ try:
70
+ loop = asyncio.get_event_loop()
71
+ if loop.is_running():
72
+ # If called from async context, schedule closing
73
+ asyncio.create_task(_ASYNC_CLIENT.aclose())
74
+ else:
75
+ # If called from sync context, run the close
76
+ loop.run_until_complete(_ASYNC_CLIENT.aclose())
77
+ except RuntimeError:
78
+ # No event loop, create one
79
+ asyncio.run(_ASYNC_CLIENT.aclose())
80
+
81
+
82
+ T = TypeVar("T")
83
+
84
+
85
+ def with_retry(func: Callable[..., T]) -> Callable[..., T]:
86
+ """Decorator to add automatic retry with exponential backoff to any function.
87
+
88
+ Parameters
89
+ ----------
90
+ func : Callable
91
+ Function to retry on failure.
92
+
93
+ Returns
94
+ -------
95
+ Callable
96
+ Wrapped function with automatic retry logic.
97
+ """
98
+ return _retry_decorator(func)
bcb/odata/__init__.py CHANGED
@@ -1,4 +1,6 @@
1
- from .api import (
1
+ from __future__ import annotations
2
+
3
+ from bcb.odata.api import (
2
4
  ODataAPI,
3
5
  Expectativas,
4
6
  PTAX,
bcb/odata/api.py CHANGED
@@ -1,4 +1,8 @@
1
- from .framework import (
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Literal, Optional, Union, overload
4
+
5
+ from bcb.odata.framework import (
2
6
  ODataEntitySet,
3
7
  ODataFunctionImport,
4
8
  ODataQuery,
@@ -13,10 +17,10 @@ OLINDA_BASE_URL = "https://olinda.bcb.gov.br/olinda/servico"
13
17
 
14
18
 
15
19
  class EndpointMeta(type):
16
- def __init__(self, *args, **kwargs):
20
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
17
21
  super().__init__(*args, **kwargs)
18
22
 
19
- def __call__(self, *args):
23
+ def __call__(self, *args: Any) -> Any:
20
24
  obj = super().__call__(*args)
21
25
  entity = args[0]
22
26
  if isinstance(entity, ODataEntitySet):
@@ -29,10 +33,10 @@ class EndpointMeta(type):
29
33
 
30
34
 
31
35
  class EndpointQuery(ODataQuery):
32
- _DATE_COLUMN_NAMES_BY_ENDPOINT = {
36
+ _DATE_COLUMN_NAMES_BY_ENDPOINT: dict[str, dict[str, str]] = {
33
37
  "IfDataCadastro": {"Data": "%Y%m"}
34
38
  }
35
- _DATE_COLUMN_NAMES = {
39
+ _DATE_COLUMN_NAMES: set[str] = {
36
40
  "Data",
37
41
  "dataHoraCotacao",
38
42
  "InicioPeriodo",
@@ -40,15 +44,70 @@ class EndpointQuery(ODataQuery):
40
44
  "DataVigencia",
41
45
  }
42
46
 
43
- def collect(self):
47
+ def __init__(
48
+ self,
49
+ entity: Any,
50
+ url: str,
51
+ date_columns: Optional[list[str]] = None,
52
+ ) -> None:
53
+ super().__init__(entity, url)
54
+ self._date_columns: list[str] = date_columns or []
55
+
56
+ @overload
57
+ def collect(self, output: Literal["dataframe"] = ...) -> pd.DataFrame: ...
58
+
59
+ @overload
60
+ def collect(self, output: Literal["text"]) -> str: ...
61
+
62
+ def collect(self, output: str = "dataframe") -> Union[pd.DataFrame, str]:
63
+ if output == "text":
64
+ return self.text()
44
65
  raw_data = super().collect()
45
66
  data = pd.DataFrame(raw_data["value"])
46
67
  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])
68
+ if self._date_columns:
69
+ # Use the explicit list provided by the API subclass.
70
+ for col in self._date_columns:
71
+ if col in data.columns:
72
+ data[col] = pd.to_datetime(data[col])
73
+ else:
74
+ # Fall back to the built-in heuristic.
75
+ endpoint_overrides = self._DATE_COLUMN_NAMES_BY_ENDPOINT.get(
76
+ self.entity.name, {}
77
+ )
78
+ for col in self._DATE_COLUMN_NAMES:
79
+ if col in endpoint_overrides:
80
+ data[col] = pd.to_datetime(
81
+ data[col], format=endpoint_overrides[col]
82
+ )
83
+ elif col in data.columns:
84
+ data[col] = pd.to_datetime(data[col])
85
+ return data
86
+
87
+ async def async_collect(
88
+ self, output: str = "dataframe"
89
+ ) -> Union[pd.DataFrame, str]:
90
+ """Async version of collect(). Awaits super().async_collect() for data fetch."""
91
+ if output == "text":
92
+ return await self.async_text()
93
+ raw_data = await super().async_collect()
94
+ data = pd.DataFrame(raw_data["value"])
95
+ if not self._raw:
96
+ if self._date_columns:
97
+ for col in self._date_columns:
98
+ if col in data.columns:
99
+ data[col] = pd.to_datetime(data[col])
100
+ else:
101
+ endpoint_overrides = self._DATE_COLUMN_NAMES_BY_ENDPOINT.get(
102
+ self.entity.name, {}
103
+ )
104
+ for col in self._DATE_COLUMN_NAMES:
105
+ if col in endpoint_overrides:
106
+ data[col] = pd.to_datetime(
107
+ data[col], format=endpoint_overrides[col]
108
+ )
109
+ elif col in data.columns:
110
+ data[col] = pd.to_datetime(data[col])
52
111
  return data
53
112
 
54
113
 
@@ -65,7 +124,10 @@ class Endpoint(metaclass=EndpointMeta):
65
124
  :py:meth:`bcb.odata.api.BaseODataAPI.get_endpoint` das classes que herdam
66
125
  :py:class:`bcb.odata.api.BaseODataAPI`.
67
126
  """
68
- def __init__(self, entity, url):
127
+
128
+ def __init__(
129
+ self, entity: Any, url: str, date_columns: Optional[list[str]] = None
130
+ ) -> None:
69
131
  """
70
132
  Construtor da classe Endpoint.
71
133
 
@@ -76,25 +138,69 @@ class Endpoint(metaclass=EndpointMeta):
76
138
  Obtidos da classe ``bcb.odata.framework.ODataService``.
77
139
  url : str
78
140
  URL da API OData.
141
+ date_columns : list[str], optional
142
+ Colunas a converter para datetime. Quando fornecido, substitui a
143
+ heurística padrão de detecção de datas.
79
144
  """
80
145
  self._entity = entity
81
146
  self._url = url
82
-
83
- def get(self, *args, **kwargs):
147
+ self._date_columns: list[str] = date_columns or []
148
+
149
+ def get(
150
+ self,
151
+ *args: Any,
152
+ filter: Optional[ODataPropertyFilter] = None,
153
+ orderby: Optional[ODataPropertyOrderBy] = None,
154
+ select: Optional[ODataProperty] = None,
155
+ limit: Optional[int] = None,
156
+ skip: Optional[int] = None,
157
+ output: str = "dataframe",
158
+ verbose: bool = False,
159
+ **kwargs: Any,
160
+ ) -> Union[pd.DataFrame, str]:
84
161
  """
85
162
  Executa a consulta na API OData e retorna o resultado.
86
163
 
87
164
  Parameters
88
165
  ----------
89
- *args : argumentos para a consulta
90
-
91
- **kwargs : argumentos para a consulta
166
+ *args : argumentos para a consulta (ODataPropertyFilter, ODataPropertyOrderBy, ODataProperty)
167
+ filter : ODataPropertyFilter, optional
168
+ Filter condition for the query
169
+ orderby : ODataPropertyOrderBy, optional
170
+ Order by condition for the query
171
+ select : ODataProperty, optional
172
+ Properties to select from the query
173
+ limit : int, optional
174
+ Limit the number of results
175
+ skip : int, optional
176
+ Skip the first N results
177
+ output : str, default "dataframe"
178
+ Output format. Use ``'text'`` to get the raw OData JSON response
179
+ string instead of a DataFrame.
180
+ verbose : bool, default False
181
+ Print the query before executing it
182
+ **kwargs : argumentos adicionais para a consulta
92
183
 
93
184
  Returns
94
185
  -------
95
- pd.DataFrame: resultado da consulta
186
+ pd.DataFrame or str: resultado da consulta. Returns a DataFrame by
187
+ default; returns a raw JSON string when ``output='text'``.
96
188
  """
97
- _query = EndpointQuery(self._entity, self._url)
189
+ _query = EndpointQuery(self._entity, self._url, self._date_columns)
190
+
191
+ # Apply explicit kwargs first
192
+ if filter is not None:
193
+ _query.filter(filter)
194
+ if orderby is not None:
195
+ _query.orderby(orderby)
196
+ if select is not None:
197
+ _query.select(select)
198
+ if limit is not None:
199
+ _query.limit(limit)
200
+ if skip is not None:
201
+ _query.skip(skip)
202
+
203
+ # Apply positional args for backwards compatibility
98
204
  for arg in args:
99
205
  if isinstance(arg, ODataPropertyFilter):
100
206
  _query.filter(arg)
@@ -102,25 +208,23 @@ class Endpoint(metaclass=EndpointMeta):
102
208
  _query.orderby(arg)
103
209
  elif isinstance(arg, ODataProperty):
104
210
  _query.select(arg)
105
- verbose = False
211
+
212
+ # Apply any remaining kwargs as query parameters
106
213
  for k, val in kwargs.items():
107
- if k == "limit":
108
- _query.limit(val)
109
- elif k == "skip":
110
- _query.skip(val)
111
- elif k == "verbose":
112
- verbose = val
113
- else:
114
- _query.parameters(**{k: val})
214
+ _query.parameters(**{k: val})
215
+
115
216
  _query.format("application/json")
116
217
 
117
218
  if verbose:
118
219
  _query.show()
119
- data = _query.collect()
220
+ if output == "text":
221
+ data = _query.collect(output="text")
222
+ else:
223
+ data = _query.collect()
120
224
  _query.reset()
121
225
  return data
122
226
 
123
- def query(self):
227
+ def query(self) -> EndpointQuery:
124
228
  """
125
229
  Retorna uma instância de EndpointQuery através da qual se construirá a consulta na API OData.
126
230
 
@@ -128,7 +232,98 @@ class Endpoint(metaclass=EndpointMeta):
128
232
  -------
129
233
  bcb.odata.api.EndpointQuery
130
234
  """
131
- return EndpointQuery(self._entity, self._url)
235
+ return EndpointQuery(self._entity, self._url, self._date_columns)
236
+
237
+ def async_query(self) -> EndpointQuery:
238
+ """
239
+ Async version of query(). Returns an EndpointQuery for manual chaining with async methods.
240
+
241
+ Returns
242
+ -------
243
+ bcb.odata.api.EndpointQuery
244
+ Same as query(); call async_collect() on the result
245
+ """
246
+ return EndpointQuery(self._entity, self._url, self._date_columns)
247
+
248
+ async def async_get(
249
+ self,
250
+ *args: Any,
251
+ filter: Optional[ODataPropertyFilter] = None,
252
+ orderby: Optional[ODataPropertyOrderBy] = None,
253
+ select: Optional[ODataProperty] = None,
254
+ limit: Optional[int] = None,
255
+ skip: Optional[int] = None,
256
+ output: str = "dataframe",
257
+ verbose: bool = False,
258
+ **kwargs: Any,
259
+ ) -> Union[pd.DataFrame, str]:
260
+ """
261
+ Async version of get(). Executes the OData query asynchronously.
262
+
263
+ Same signature as :func:`get`, but returns a coroutine.
264
+
265
+ Parameters
266
+ ----------
267
+ *args : ODataPropertyFilter, ODataPropertyOrderBy, ODataProperty
268
+ Positional filter/orderby/select arguments (for backwards compatibility)
269
+ filter : ODataPropertyFilter, optional
270
+ Filter condition for the query
271
+ orderby : ODataPropertyOrderBy, optional
272
+ Order by condition for the query
273
+ select : ODataProperty, optional
274
+ Properties to select from the query
275
+ limit : int, optional
276
+ Limit the number of results
277
+ skip : int, optional
278
+ Skip the first N results
279
+ output : str, default "dataframe"
280
+ Output format. Use ``'text'`` for raw JSON.
281
+ verbose : bool, default False
282
+ Print the query before executing it
283
+ **kwargs : argumentos adicionais para a consulta
284
+
285
+ Returns
286
+ -------
287
+ Union[pd.DataFrame, str]
288
+ Resultado da consulta
289
+ """
290
+ _query = EndpointQuery(self._entity, self._url, self._date_columns)
291
+
292
+ # Apply explicit kwargs first
293
+ if filter is not None:
294
+ _query.filter(filter)
295
+ if orderby is not None:
296
+ _query.orderby(orderby)
297
+ if select is not None:
298
+ _query.select(select)
299
+ if limit is not None:
300
+ _query.limit(limit)
301
+ if skip is not None:
302
+ _query.skip(skip)
303
+
304
+ # Apply positional args for backwards compatibility
305
+ for arg in args:
306
+ if isinstance(arg, ODataPropertyFilter):
307
+ _query.filter(arg)
308
+ elif isinstance(arg, ODataPropertyOrderBy):
309
+ _query.orderby(arg)
310
+ elif isinstance(arg, ODataProperty):
311
+ _query.select(arg)
312
+
313
+ # Apply any remaining kwargs as query parameters
314
+ for k, val in kwargs.items():
315
+ _query.parameters(**{k: val})
316
+
317
+ _query.format("application/json")
318
+
319
+ if verbose:
320
+ _query.show()
321
+ if output == "text":
322
+ data = await _query.async_collect(output="text")
323
+ else:
324
+ data = await _query.async_collect()
325
+ _query.reset()
326
+ return data
132
327
 
133
328
 
134
329
  class BaseODataAPI:
@@ -138,13 +333,16 @@ class BaseODataAPI:
138
333
  Essa classe não deve ser acessada diretamente.
139
334
  """
140
335
 
141
- def __init__(self):
336
+ BASE_URL: str
337
+ DATE_COLUMNS: list[str] = []
338
+
339
+ def __init__(self) -> None:
142
340
  """
143
341
  BaseODataAPI construtor
144
342
  """
145
343
  self.service = ODataService(self.BASE_URL)
146
344
 
147
- def describe(self, endpoint=None):
345
+ def describe(self, endpoint: Optional[str] = None) -> None:
148
346
  """
149
347
  Mostra a descrição de uma API ou de um *endpoint*
150
348
  específico.
@@ -166,7 +364,7 @@ class BaseODataAPI:
166
364
  else:
167
365
  self.service.describe()
168
366
 
169
- def get_endpoint(self, endpoint):
367
+ def get_endpoint(self, endpoint: str) -> Endpoint:
170
368
  """
171
369
  Obtem o *endpoint*
172
370
 
@@ -186,7 +384,9 @@ class BaseODataAPI:
186
384
  ValueError
187
385
  Se o *endpoint* fornecido é errado.
188
386
  """
189
- return Endpoint(self.service[endpoint], self.service.url)
387
+ return Endpoint(
388
+ self.service[endpoint], self.service.url, self.DATE_COLUMNS or None
389
+ )
190
390
 
191
391
 
192
392
  class ODataAPI(BaseODataAPI):
@@ -200,7 +400,7 @@ class ODataAPI(BaseODataAPI):
200
400
  não possuem implementação específica.
201
401
  """
202
402
 
203
- def __init__(self, url):
403
+ def __init__(self, url: str) -> None:
204
404
  """
205
405
  Parameters
206
406
  ----------
@@ -411,8 +611,8 @@ class TarifasBancariasPorInstituicaoFinanceira(BaseODataAPI):
411
611
  cobradas por instituições financeiras, por Segmento e por Instituição.
412
612
  """
413
613
 
414
- K = "Informes_ListaTarifasPorInstituicaoFinanceira"
415
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
614
+ SERVICE_KEY = "Informes_ListaTarifasPorInstituicaoFinanceira"
615
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
416
616
 
417
617
 
418
618
  class TarifasBancariasPorServico(BaseODataAPI):
@@ -424,8 +624,8 @@ class TarifasBancariasPorServico(BaseODataAPI):
424
624
  por serviço.
425
625
  """
426
626
 
427
- K = "Informes_ListaValoresDeServicoBancario"
428
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
627
+ SERVICE_KEY = "Informes_ListaValoresDeServicoBancario"
628
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
429
629
 
430
630
 
431
631
  class PostosAtendimentoEletronicoPorInstituicaoFinanceira(BaseODataAPI):
@@ -437,8 +637,8 @@ class PostosAtendimentoEletronicoPorInstituicaoFinanceira(BaseODataAPI):
437
637
  pelo Banco Central.
438
638
  """
439
639
 
440
- K = "Informes_PostosDeAtendimentoEletronico"
441
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
640
+ SERVICE_KEY = "Informes_PostosDeAtendimentoEletronico"
641
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
442
642
 
443
643
 
444
644
  class PostosAtendimentoCorrespondentesPorInstituicaoFinanceira(BaseODataAPI):
@@ -451,8 +651,8 @@ class PostosAtendimentoCorrespondentesPorInstituicaoFinanceira(BaseODataAPI):
451
651
  descrito na Resolução 3.954.
452
652
  """
453
653
 
454
- K = "Informes_Correspondentes"
455
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
654
+ SERVICE_KEY = "Informes_Correspondentes"
655
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
456
656
 
457
657
 
458
658
  class EstatisticasSTR(BaseODataAPI):
@@ -464,8 +664,8 @@ class EstatisticasSTR(BaseODataAPI):
464
664
  mantidas pelos participantes no Banco Central.
465
665
  """
466
666
 
467
- K = "STR"
468
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
667
+ SERVICE_KEY = "STR"
668
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
469
669
 
470
670
 
471
671
  class DinheiroCirculacao(BaseODataAPI):
@@ -478,8 +678,8 @@ class DinheiroCirculacao(BaseODataAPI):
478
678
  Real (símbolos : R$, BRL).
479
679
  """
480
680
 
481
- K = "mecir_dinheiro_em_circulacao"
482
- BASE_URL = f"{OLINDA_BASE_URL}/{K}/versao/v1/odata/"
681
+ SERVICE_KEY = "mecir_dinheiro_em_circulacao"
682
+ BASE_URL = f"{OLINDA_BASE_URL}/{SERVICE_KEY}/versao/v1/odata/"
483
683
 
484
684
 
485
685
  # /Informes_Ouvidorias/versao/v1/odata/