python-bcb 0.3.3__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
@@ -2,13 +2,14 @@ import re
2
2
  import warnings
3
3
  from datetime import date, timedelta
4
4
  from io import BytesIO, StringIO
5
- from typing import List, Union
5
+ from typing import List, Optional, Union
6
6
 
7
+ import httpx
7
8
  import numpy as np
8
9
  import pandas as pd
9
- import requests
10
10
  from lxml import html
11
11
 
12
+ from .exceptions import BCBAPIError, CurrencyNotFoundError
12
13
  from .utils import Date, DateInput
13
14
 
14
15
  """
@@ -16,44 +17,58 @@ O módulo :py:mod:`bcb.currency` tem como objetivo fazer consultas no site do co
16
17
  """
17
18
 
18
19
 
19
- def _currency_url(currency_id: str, start_date: DateInput, end_date: DateInput) -> str:
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
+
32
+
33
+ def clear_cache() -> None:
34
+ """Clear the module-level session cache.
35
+
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()
31
43
 
32
44
 
33
45
  def _currency_id_list() -> pd.DataFrame:
34
- if CACHE.get("TEMP_CURRENCY_ID_LIST") is not None:
35
- return CACHE.get("TEMP_CURRENCY_ID_LIST")
46
+ if _CACHE.get("TEMP_CURRENCY_ID_LIST") is not None:
47
+ return _CACHE.get("TEMP_CURRENCY_ID_LIST")
36
48
  else:
37
- url1 = "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?" "method=exibeFormularioConsultaBoletim"
38
- res = requests.get(url1)
49
+ url1 = (
50
+ "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
51
+ "method=exibeFormularioConsultaBoletim"
52
+ )
53
+ res = httpx.get(url1, follow_redirects=True)
39
54
  if res.status_code != 200:
40
55
  msg = f"BCB API Request error, status code = {res.status_code}"
41
- raise Exception(msg)
56
+ raise BCBAPIError(msg, res.status_code)
42
57
 
43
58
  doc = html.parse(BytesIO(res.content)).getroot()
44
59
  xpath = "//select[@name='ChkMoeda']/option"
45
60
  x = [(elm.text, elm.get("value")) for elm in doc.xpath(xpath)]
46
61
  df = pd.DataFrame(x, columns=["name", "id"])
47
62
  df["id"] = df["id"].astype("int32")
48
- CACHE["TEMP_CURRENCY_ID_LIST"] = df
63
+ _CACHE["TEMP_CURRENCY_ID_LIST"] = df
49
64
  return df
50
65
 
51
66
 
52
- def _get_valid_currency_list(_date: date, n: int = 0) -> requests.models.Response:
67
+ def _get_valid_currency_list(_date: date, n: int = 0) -> httpx.Response:
53
68
  url2 = f"http://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
54
69
  try:
55
- res = requests.get(url2)
56
- except requests.exceptions.ConnectionError as ex:
70
+ res = httpx.get(url2, follow_redirects=True)
71
+ except httpx.ConnectError as ex:
57
72
  if n >= 3:
58
73
  raise ex
59
74
  return _get_valid_currency_list(_date, n + 1)
@@ -73,8 +88,8 @@ def get_currency_list() -> pd.DataFrame:
73
88
  DataFrame :
74
89
  Tabela com a listagem de moedas disponíveis.
75
90
  """
76
- if CACHE.get("TEMP_FILE_CURRENCY_LIST") is not None:
77
- 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")
78
93
  else:
79
94
  res = _get_valid_currency_list(date.today())
80
95
  df = pd.read_csv(StringIO(res.text), delimiter=";")
@@ -92,7 +107,7 @@ def get_currency_list() -> pd.DataFrame:
92
107
  df["country_code"] = df["country_code"].astype("int32")
93
108
  df["code"] = df["code"].astype("int32")
94
109
  df["symbol"] = df["symbol"].str.strip()
95
- CACHE["TEMP_FILE_CURRENCY_LIST"] = df
110
+ _CACHE["TEMP_FILE_CURRENCY_LIST"] = df
96
111
  return df
97
112
 
98
113
 
@@ -100,13 +115,21 @@ def _get_currency_id(symbol: str) -> int:
100
115
  id_list = _currency_id_list()
101
116
  all_currencies = get_currency_list()
102
117
  x = pd.merge(id_list, all_currencies, on=["name"])
103
- 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())
104
122
 
105
123
 
106
- def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.DataFrame:
107
- 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
108
131
  url = _currency_url(cid, start_date, end_date)
109
- res = requests.get(url)
132
+ res = httpx.get(url, follow_redirects=True)
110
133
 
111
134
  if res.headers["Content-Type"].startswith("text/html"):
112
135
  doc = html.parse(BytesIO(res.content)).getroot()
@@ -115,12 +138,14 @@ def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.D
115
138
  x = elm.text
116
139
  x = re.sub(r"^\W+", "", x)
117
140
  x = re.sub(r"\W+$", "", x)
118
- msg = "BCB API returned error: {} - {}".format(x, symbol)
141
+ msg = f"BCB API returned error: {x} - {symbol}"
119
142
  warnings.warn(msg)
120
143
  return None
121
144
 
122
145
  columns = ["Date", "aa", "bb", "cc", "bid", "ask", "dd", "ee"]
123
- df = pd.read_csv(StringIO(res.text), delimiter=";", header=None, names=columns, dtype=str)
146
+ df = pd.read_csv(
147
+ StringIO(res.text), delimiter=";", header=None, names=columns, dtype=str
148
+ )
124
149
  df = df.assign(
125
150
  Date=lambda x: pd.to_datetime(x["Date"], format="%d%m%Y"),
126
151
  bid=lambda x: x["bid"].str.replace(",", ".").astype(np.float64),
@@ -135,7 +160,11 @@ def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.D
135
160
 
136
161
 
137
162
  def get(
138
- symbols: Union[str, List[str]], start: DateInput, end: DateInput, side: str = "ask", groupby: str = "symbol"
163
+ symbols: Union[str, List[str]],
164
+ start: DateInput,
165
+ end: DateInput,
166
+ side: str = "ask",
167
+ groupby: str = "symbol",
139
168
  ) -> pd.DataFrame:
140
169
  """
141
170
  Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
@@ -163,6 +192,13 @@ def get(
163
192
  Returns
164
193
  -------
165
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
+
166
202
  DataFrame :
167
203
  Série temporal com cotações diárias das moedas solicitadas.
168
204
  """
@@ -184,6 +220,6 @@ def get(
184
220
  elif groupby == "side":
185
221
  return df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
186
222
  else:
187
- raise Exception(f"Unknown side value, use: bid, ask, both")
223
+ raise ValueError("Unknown side value, use: bid, ask, both")
188
224
  else:
189
- raise Exception(f"Currency not found: {symbols}")
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/
bcb/odata/framework.py CHANGED
@@ -1,9 +1,13 @@
1
1
  from io import BytesIO
2
2
  import logging
3
+ from typing import Any, Optional, Union
3
4
  from lxml import etree
4
5
  import json
5
6
  import httpx
6
7
  from urllib.parse import quote
8
+ from typing_extensions import Self
9
+
10
+ from bcb.exceptions import ODataError
7
11
 
8
12
 
9
13
  # Edm.Boolean
@@ -21,7 +25,7 @@ from urllib.parse import quote
21
25
  # Edm.TimeOfDay
22
26
 
23
27
 
24
- def str_types(type):
28
+ def str_types(type: str) -> str:
25
29
  if type == "Edm.Decimal":
26
30
  return "float"
27
31
  elif type in ("Edm.Int32", "Edm.Int64", "Edm.Int16"):
@@ -37,25 +41,25 @@ def str_types(type):
37
41
 
38
42
 
39
43
  class ODataEndPoint:
40
- def __init__(self, **kwargs):
41
- self.data = kwargs
44
+ def __init__(self, **kwargs: Any) -> None:
45
+ self.data: dict[str, Any] = kwargs
42
46
 
43
- def __getitem__(self, item):
47
+ def __getitem__(self, item: str) -> Any:
44
48
  return self.data[item]
45
49
 
46
- def __setitem__(self, key, value):
50
+ def __setitem__(self, key: str, value: Any) -> None:
47
51
  self.data[key] = value
48
52
 
49
- def __repr__(self):
53
+ def __repr__(self) -> str:
50
54
  url = self.data["url"]
51
55
  return f"<EndPoint {url}>"
52
56
 
53
57
 
54
58
  class ODataEntitySetMeta(type):
55
- def __init__(self, *args, **kwargs):
59
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
56
60
  super().__init__(*args, **kwargs)
57
61
 
58
- def __call__(self, *args):
62
+ def __call__(self, *args: Any) -> Any:
59
63
  obj = super().__call__(*args)
60
64
  entity = args[2]
61
65
  for name, prop in entity.properties.items():
@@ -64,12 +68,13 @@ class ODataEntitySetMeta(type):
64
68
 
65
69
 
66
70
  class ODataEntitySet(metaclass=ODataEntitySetMeta):
67
- def __init__(self, name, entity_type, entity):
71
+ def __init__(self, name: str, entity_type: str, entity: "ODataEntity") -> None:
68
72
  self.name = name
69
73
  self.entity_type = entity_type
70
74
  self.entity = entity
75
+ self.fullname: str = ""
71
76
 
72
- def describe(self):
77
+ def describe(self) -> None:
73
78
  props = ", ".join(
74
79
  [f"{prop.name}<{prop.ftype}>" for prop in self.entity.properties.values()]
75
80
  )
@@ -80,17 +85,19 @@ EntityType: {self.entity_type}
80
85
  Properties: {props}"""
81
86
  )
82
87
 
83
- def __repr__(self):
88
+ def __repr__(self) -> str:
84
89
  return f"<EntitySet {self.name}>"
85
90
 
86
91
 
87
92
  class ODataFunctionImport:
88
- def __init__(self, name, function, entity_set):
93
+ def __init__(
94
+ self, name: str, function: "ODataFunction", entity_set: ODataEntitySet
95
+ ) -> None:
89
96
  self.name = name
90
97
  self.entity_set = entity_set
91
98
  self.function = function
92
99
 
93
- def describe(self):
100
+ def describe(self) -> None:
94
101
  props = ", ".join(
95
102
  [
96
103
  f"{prop.name} <{prop.ftype}>"
@@ -108,35 +115,35 @@ EntityType: {self.entity_set.entity_type}
108
115
  Properties: {props}"""
109
116
  print(s)
110
117
 
111
- def __repr__(self):
118
+ def __repr__(self) -> str:
112
119
  return f"<FunctionImport {self.name}>"
113
120
 
114
121
 
115
122
  class ODataParameter:
116
- def __init__(self, **kwargs):
117
- self.data = kwargs
123
+ def __init__(self, **kwargs: Any) -> None:
124
+ self.data: dict[str, Any] = kwargs
118
125
 
119
126
  @property
120
- def name(self):
127
+ def name(self) -> Optional[str]:
121
128
  return self.data.get("Name")
122
129
 
123
130
  @property
124
- def type(self):
131
+ def type(self) -> Optional[str]:
125
132
  return self.data.get("Type")
126
133
 
127
134
  @property
128
- def ftype(self):
129
- return str_types(self.type)
135
+ def ftype(self) -> str:
136
+ return str_types(self.type or "")
130
137
 
131
138
  @property
132
- def required(self):
139
+ def required(self) -> bool:
133
140
  nullable = self.data.get("Nullable")
134
141
  if nullable:
135
- return nullable == "false"
142
+ return bool(nullable == "false")
136
143
  else:
137
144
  return True
138
145
 
139
- def format(self, value):
146
+ def format(self, value: Any) -> str:
140
147
  if self.type == "Edm.Decimal":
141
148
  return f"{float(value)}"
142
149
  elif self.type == "Edm.Int32":
@@ -148,24 +155,24 @@ class ODataParameter:
148
155
 
149
156
 
150
157
  class ODataPropertyOrderBy:
151
- def __init__(self, obj, order):
158
+ def __init__(self, obj: "ODataProperty", order: str) -> None:
152
159
  self.obj = obj
153
160
  self.order = order
154
161
 
155
- def __str__(self):
162
+ def __str__(self) -> str:
156
163
  return f"{self.obj.name} {self.order}"
157
164
 
158
- def __repr__(self):
165
+ def __repr__(self) -> str:
159
166
  return f"<{str(self)}>"
160
167
 
161
168
 
162
169
  class ODataPropertyFilter:
163
- def __init__(self, obj, oth, operator):
170
+ def __init__(self, obj: "ODataProperty", oth: Any, operator: str) -> None:
164
171
  self.obj = obj
165
172
  self.other = oth
166
173
  self.operator = operator
167
174
 
168
- def statement(self):
175
+ def statement(self) -> str:
169
176
  if self.obj.type == "Edm.Decimal":
170
177
  return f"{self.obj.name} {self.operator} {float(self.other)}"
171
178
  elif self.obj.type == "Edm.Int32":
@@ -177,72 +184,74 @@ class ODataPropertyFilter:
177
184
  else:
178
185
  return f"{self.obj.name} {self.operator} '{self.other}'"
179
186
 
180
- def __str__(self):
187
+ def __str__(self) -> str:
181
188
  return self.statement()
182
189
 
183
- def __repr__(self):
190
+ def __repr__(self) -> str:
184
191
  return f"<filter: {str(self)}>"
185
192
 
186
193
 
187
194
  class ODataProperty:
188
- def __init__(self, **kwargs):
189
- self.data = kwargs
195
+ def __init__(self, **kwargs: Any) -> None:
196
+ self.data: dict[str, Any] = kwargs
190
197
 
191
198
  @property
192
- def name(self):
199
+ def name(self) -> Optional[str]:
193
200
  return self.data.get("Name")
194
201
 
195
202
  @property
196
- def type(self):
203
+ def type(self) -> Optional[str]:
197
204
  return self.data.get("Type")
198
205
 
199
206
  @property
200
- def ftype(self):
201
- return str_types(self.type)
207
+ def ftype(self) -> str:
208
+ return str_types(self.type or "")
202
209
 
203
- def asc(self):
210
+ def asc(self) -> ODataPropertyOrderBy:
204
211
  return ODataPropertyOrderBy(self, "asc")
205
212
 
206
- def desc(self):
213
+ def desc(self) -> ODataPropertyOrderBy:
207
214
  return ODataPropertyOrderBy(self, "desc")
208
215
 
209
- def __gt__(self, other):
216
+ def __gt__(self, other: Any) -> ODataPropertyFilter:
210
217
  return ODataPropertyFilter(self, other, "gt")
211
218
 
212
- def __ge__(self, other):
219
+ def __ge__(self, other: Any) -> ODataPropertyFilter:
213
220
  return ODataPropertyFilter(self, other, "ge")
214
221
 
215
- def __lt__(self, other):
222
+ def __lt__(self, other: Any) -> ODataPropertyFilter:
216
223
  return ODataPropertyFilter(self, other, "lt")
217
224
 
218
- def __le__(self, other):
225
+ def __le__(self, other: Any) -> ODataPropertyFilter:
219
226
  return ODataPropertyFilter(self, other, "le")
220
227
 
221
- def __eq__(self, other):
228
+ def __eq__(self, other: Any) -> ODataPropertyFilter: # type: ignore[override]
222
229
  return ODataPropertyFilter(self, other, "eq")
223
230
 
224
- def __repr__(self):
231
+ def __repr__(self) -> str:
225
232
  return f"<Property {self.name}<{self.ftype}>>"
226
233
 
227
234
 
228
235
  class ODataFunction:
229
- def __init__(self, **kwargs):
230
- self.name = kwargs["Name"]
231
- self.parameters = kwargs["parameters"]
232
- self.return_type = kwargs["return_type"]
233
- self.fullname = f'{kwargs["namespace"]}.{self.name}'
236
+ def __init__(self, **kwargs: Any) -> None:
237
+ self.name: str = kwargs["Name"]
238
+ self.parameters: list[ODataParameter] = kwargs["parameters"]
239
+ self.return_type: str = kwargs["return_type"]
240
+ self.fullname: str = f'{kwargs["namespace"]}.{self.name}'
234
241
 
235
- def __repr__(self):
242
+ def __repr__(self) -> str:
236
243
  return f"<Function {self.name}>"
237
244
 
238
245
 
239
246
  class ODataEntity:
240
- def __init__(self, name, properties, namespace):
247
+ def __init__(
248
+ self, name: str, properties: dict[str, ODataProperty], namespace: str
249
+ ) -> None:
241
250
  self.name = name
242
251
  self.properties = properties
243
252
  self.fullname = f"{namespace}.{name}"
244
253
 
245
- def __repr__(self):
254
+ def __repr__(self) -> str:
246
255
  return f"<Entity {self.name}>"
247
256
 
248
257
 
@@ -252,46 +261,48 @@ class ODataMetadata:
252
261
  "edmx": "http://docs.oasis-open.org/odata/ns/edmx",
253
262
  }
254
263
 
255
- def __init__(self, url):
264
+ def __init__(self, url: str) -> None:
256
265
  self.url = url
257
266
  self._load_document()
258
267
  _xpath = "edmx:DataServices/edm:Schema"
259
268
  schema = self.doc.xpath(_xpath, namespaces=self.namespaces)[0]
260
- self.namespace = schema.attrib["Namespace"]
261
- self._used_elements = []
269
+ self.namespace: str = schema.attrib["Namespace"]
270
+ self._used_elements: list[str] = []
262
271
  self._parse_entities(schema)
263
272
  self._parse_entity_sets(schema)
264
273
  self._parse_functions(schema)
265
274
  self._parse_function_imports(schema)
266
275
 
267
- def _load_document(self):
276
+ def _load_document(self) -> None:
268
277
  res = httpx.get(self.url, timeout=60.0)
269
278
  self.doc = etree.parse(BytesIO(res.content))
270
279
 
271
- def _parse_entity(self, entity_element, namespace):
280
+ def _parse_entity(self, entity_element: Any, namespace: str) -> ODataEntity:
272
281
  name = entity_element.attrib["Name"]
273
282
  props = {
274
283
  prop.attrib["Name"]: ODataProperty(**prop.attrib) for prop in entity_element
275
284
  }
276
285
  return ODataEntity(name, props, namespace)
277
286
 
278
- def _parse_entities(self, schema):
287
+ def _parse_entities(self, schema: Any) -> None:
279
288
  _xpath = "edm:EntityType"
280
- self.entities = [
289
+ self.entities: list[ODataEntity] = [
281
290
  self._parse_entity(e, self.namespace)
282
291
  for e in schema.xpath(_xpath, namespaces=self.namespaces)
283
292
  ]
284
293
 
285
- self._entities_fullnames = {e.fullname: e for e in self.entities}
294
+ self._entities_fullnames: dict[str, ODataEntity] = {
295
+ e.fullname: e for e in self.entities
296
+ }
286
297
 
287
- def _parse_entity_sets(self, schema):
298
+ def _parse_entity_sets(self, schema: Any) -> None:
288
299
  _xpath = "edm:EntityContainer/edm:EntitySet"
289
300
 
290
- def _parse_entity_set(e):
301
+ def _parse_entity_set(e: Any) -> ODataEntitySet:
291
302
  entity = self._entities_fullnames[e.attrib["EntityType"]]
292
303
  return ODataEntitySet(e.attrib["Name"], e.attrib["EntityType"], entity)
293
304
 
294
- self.entity_sets = {
305
+ self.entity_sets: dict[str, ODataEntitySet] = {
295
306
  e.attrib["Name"]: _parse_entity_set(e)
296
307
  for e in schema.xpath(_xpath, namespaces=self.namespaces)
297
308
  }
@@ -299,14 +310,14 @@ class ODataMetadata:
299
310
  for n, es in self.entity_sets.items():
300
311
  es.fullname = f"{self.namespace}.{n}"
301
312
 
302
- self._entity_sets_fullnames = {
313
+ self._entity_sets_fullnames: dict[str, ODataEntitySet] = {
303
314
  es.fullname: es for es in self.entity_sets.values()
304
315
  }
305
316
 
306
- def _parse_functions(self, schema):
317
+ def _parse_functions(self, schema: Any) -> None:
307
318
  _xpath = "edm:Function"
308
319
 
309
- def _parse_function(e):
320
+ def _parse_function(e: Any) -> ODataFunction:
310
321
  parameters = []
311
322
  return_type = None
312
323
  for element in e:
@@ -314,67 +325,71 @@ class ODataMetadata:
314
325
  parameters.append(ODataParameter(**element.attrib))
315
326
  elif element.tag.endswith("ReturnType"):
316
327
  return_type = element.attrib["Type"]
317
- kwargs = dict(**e.attrib)
328
+ kwargs: dict[str, Any] = dict(**e.attrib)
318
329
  kwargs["parameters"] = parameters
319
330
  kwargs["return_type"] = return_type
320
331
  kwargs["namespace"] = self.namespace
321
332
  return ODataFunction(**kwargs)
322
333
 
323
- self.functions = {
334
+ self.functions: dict[str, ODataFunction] = {
324
335
  e.attrib["Name"]: _parse_function(e)
325
336
  for e in schema.xpath(_xpath, namespaces=self.namespaces)
326
337
  }
327
338
 
328
- self._functions_fullnames = {f.fullname: f for f in self.functions.values()}
339
+ self._functions_fullnames: dict[str, ODataFunction] = {
340
+ f.fullname: f for f in self.functions.values()
341
+ }
329
342
 
330
- def _parse_function_imports(self, schema):
343
+ def _parse_function_imports(self, schema: Any) -> None:
331
344
  _xpath = "edm:EntityContainer/edm:FunctionImport"
332
345
 
333
- def _parse_function_import(e):
346
+ def _parse_function_import(e: Any) -> ODataFunctionImport:
334
347
  function = self._functions_fullnames[e.attrib["Function"]]
335
348
  entity_set = self._entity_sets_fullnames[e.attrib["EntitySet"]]
336
349
  self._used_elements.append(e.attrib["EntitySet"])
337
350
  return ODataFunctionImport(e.attrib["Name"], function, entity_set)
338
351
 
339
- self.function_imports = {
352
+ self.function_imports: dict[str, ODataFunctionImport] = {
340
353
  e.attrib["Name"]: _parse_function_import(e)
341
354
  for e in schema.xpath(_xpath, namespaces=self.namespaces)
342
355
  }
343
356
 
344
357
 
345
358
  class ODataService:
346
- def __init__(self, url):
359
+ def __init__(self, url: str) -> None:
347
360
  self.url = url
348
361
  res = httpx.get(self.url, timeout=60.0)
349
- self.api_data = json.loads(res.text)
350
- self.endpoints = [ODataEndPoint(**x) for x in self.api_data["value"]]
351
- self._odata_context_url = self.api_data["@odata.context"]
362
+ self.api_data: dict[str, Any] = json.loads(res.text)
363
+ self.endpoints: list[ODataEndPoint] = [
364
+ ODataEndPoint(**x) for x in self.api_data["value"]
365
+ ]
366
+ self._odata_context_url: str = self.api_data["@odata.context"]
352
367
  self.metadata = ODataMetadata(self._odata_context_url)
353
368
 
354
- def __getitem__(self, item):
369
+ def __getitem__(self, item: str) -> Union[ODataEntitySet, ODataFunctionImport]:
355
370
  es = self.entity_sets.get(item)
356
371
  if es is None:
357
372
  fi = self.function_imports.get(item)
358
373
  if fi is not None:
359
374
  return fi
360
375
  else:
361
- raise ValueError("Invalid name: " + item)
376
+ raise ODataError("Invalid name: " + item)
362
377
  else:
363
378
  return es
364
379
 
365
380
  @property
366
- def entities(self):
381
+ def entities(self) -> list[ODataEntity]:
367
382
  return self.metadata.entities
368
383
 
369
384
  @property
370
- def function_imports(self):
385
+ def function_imports(self) -> dict[str, ODataFunctionImport]:
371
386
  return self.metadata.function_imports
372
387
 
373
388
  @property
374
- def entity_sets(self):
389
+ def entity_sets(self) -> dict[str, ODataEntitySet]:
375
390
  return self.metadata.entity_sets
376
391
 
377
- def describe(self):
392
+ def describe(self) -> None:
378
393
  es_names = []
379
394
  for es in self.entity_sets.keys():
380
395
  k = f"{self.metadata.namespace}.{es}"
@@ -389,80 +404,84 @@ class ODataService:
389
404
  for es in self.function_imports.keys():
390
405
  print(" ", es)
391
406
 
392
- def query(self, entity_set):
407
+ def query(
408
+ self, entity_set: Union[ODataEntitySet, ODataFunctionImport]
409
+ ) -> "ODataQuery":
393
410
  return ODataQuery(entity_set, self.url)
394
411
 
395
412
 
396
413
  class ODataQuery:
397
- def __init__(self, entity, url):
414
+ def __init__(
415
+ self, entity: Union[ODataEntitySet, ODataFunctionImport], url: str
416
+ ) -> None:
398
417
  self.entity = entity
399
418
  self.base_url = url
400
- self._params = {}
401
- self.function_parameters = {}
402
- self._filter = []
403
- self._select = []
404
- self._orderby = []
419
+ self._params: dict[str, Any] = {}
420
+ self.function_parameters: dict[str, Any] = {}
421
+ self._filter: list[ODataPropertyFilter] = []
422
+ self._select: list[ODataProperty] = []
423
+ self._orderby: list[ODataPropertyOrderBy] = []
405
424
  self._raw = False
406
425
  self.is_function = isinstance(entity, ODataFunctionImport)
407
426
  if self.is_function:
408
427
  self.function_parameters = {
409
- p.name: None for p in self.entity.function.parameters
428
+ (p.name or ""): None for p in self.entity.function.parameters # type: ignore[union-attr]
410
429
  }
411
430
 
412
- def odata_url(self):
431
+ def odata_url(self) -> str:
413
432
  self._url = (
414
433
  f"{self.base_url}{self.entity.name}"
415
434
  if self.base_url.endswith("/")
416
435
  else f"{self.base_url}/{self.entity.name}"
417
436
  )
418
437
  if self.is_function:
419
- args = [f"{p.name}=@{p.name}" for p in self.entity.function.parameters]
420
- args = ",".join(args)
421
- return f"{self._url}({args})"
438
+ args = [f"{p.name}=@{p.name}" for p in self.entity.function.parameters] # type: ignore[union-attr]
439
+ args_str = ",".join(args)
440
+ return f"{self._url}({args_str})"
422
441
  else:
423
442
  return self._url
424
443
 
425
- def parameters(self, **kwargs):
444
+ def parameters(self, **kwargs: Any) -> Self:
426
445
  for arg in kwargs:
427
446
  if arg in self.function_parameters:
428
447
  self.function_parameters[arg] = kwargs[arg]
429
448
  else:
430
- raise ValueError(f"Unknown parameter: {arg}")
449
+ raise ODataError(f"Unknown parameter: {arg}")
431
450
  return self
432
451
 
433
- def filter(self, *args):
452
+ def filter(self, *args: ODataPropertyFilter) -> Self:
434
453
  if len(args):
435
454
  self._filter.extend(args)
436
455
  return self
437
456
 
438
- def limit(self, limit):
457
+ def limit(self, limit: int) -> Self:
439
458
  self._params["$top"] = limit
440
459
  return self
441
460
 
442
- def skip(self, skip):
461
+ def skip(self, skip: int) -> Self:
443
462
  self._params["$skip"] = skip
444
463
  return self
445
464
 
446
- def format(self, fmt):
465
+ def format(self, fmt: str) -> Self:
447
466
  self._params["$format"] = fmt
448
467
  return self
449
468
 
450
- def orderby(self, *args):
469
+ def orderby(self, *args: ODataPropertyOrderBy) -> Self:
451
470
  if len(args):
452
471
  self._orderby.extend(args)
453
472
  return self
454
473
 
455
- def select(self, *args):
474
+ def select(self, *args: ODataProperty) -> Self:
456
475
  if len(args):
457
476
  self._select.extend(args)
458
477
  return self
459
478
 
460
- def raw(self):
479
+ def raw(self) -> Self:
461
480
  self._raw = True
462
481
  return self
463
482
 
464
- def _build_parameters(self):
465
- params = {"$format": self._params.get("$format", "json")}
483
+ def _build_parameters(self) -> dict[str, Any]:
484
+ params: dict[str, Any] = {"$format": self._params.get("$format", "json")}
466
485
  if len(self._filter):
467
486
  _filter = " and ".join(str(f) for f in self._filter)
468
487
  params["$filter"] = _filter
@@ -475,34 +494,34 @@ class ODataQuery:
475
494
  params.update(self._params)
476
495
  return params
477
496
 
478
- def reset(self):
497
+ def reset(self) -> None:
479
498
  self._filter = []
480
499
  self._orderby = []
481
500
  self._params = {}
482
501
 
483
- def collect(self):
502
+ def collect(self) -> Any:
484
503
  return json.loads(self.text())
485
504
 
486
- def text(self):
505
+ def text(self) -> str:
487
506
  params = self._build_parameters()
488
507
  if self.is_function and len(self.function_parameters):
489
- for p in self.entity.function.parameters:
490
- val = self.function_parameters[p.name]
508
+ for p in self.entity.function.parameters: # type: ignore[union-attr]
509
+ val = self.function_parameters[p.name or ""]
491
510
  if p.required and val is None:
492
- raise ValueError("Parameter not set: " + p.name)
493
- params["@" + p.name] = p.format(val)
511
+ raise ODataError("Parameter not set: " + (p.name or ""))
512
+ params["@" + (p.name or "")] = p.format(val)
494
513
  qs = "&".join([f"{quote(k)}={quote(str(v))}" for k, v in params.items()])
495
514
  headers = {"OData-Version": "4.0", "OData-MaxVersion": "4.0"}
496
515
  res = httpx.get(self.odata_url() + "?" + qs, headers=headers, timeout=60.0)
497
516
  return res.text
498
517
 
499
- def show(self):
518
+ def show(self) -> None:
500
519
  print(f"URL:")
501
520
  print(f" {self.odata_url()}")
502
521
  if self.is_function and len(self.function_parameters):
503
522
  print("Function Parameters:")
504
- for p in self.entity.function.parameters:
505
- v = self.function_parameters[p.name]
523
+ for p in self.entity.function.parameters: # type: ignore[union-attr]
524
+ v = self.function_parameters[p.name or ""]
506
525
  req = " (required) " if p.required else " "
507
526
  print(f" {p.name}<{p.ftype}>{req}= {v}")
508
527
  params = self._build_parameters()
@@ -513,13 +532,13 @@ class ODataQuery:
513
532
  if self.is_function:
514
533
  names = [
515
534
  f"{p.name}<{p.ftype}>"
516
- for p in self.entity.entity_set.entity.properties.values()
535
+ for p in self.entity.entity_set.entity.properties.values() # type: ignore[union-attr]
517
536
  ]
518
- names = ", ".join(names)
519
- print("Return:", names)
537
+ names_str = ", ".join(names)
538
+ print("Return:", names_str)
520
539
  else:
521
540
  names = [
522
- f"{p.name}<{p.ftype}>" for p in self.entity.entity.properties.values()
541
+ f"{p.name}<{p.ftype}>" for p in self.entity.entity.properties.values() # type: ignore[union-attr]
523
542
  ]
524
- names = ", ".join(names)
525
- print("Return:", names)
543
+ names_str = ", ".join(names)
544
+ print("Return:", names_str)
bcb/sgs/__init__.py CHANGED
@@ -1,10 +1,11 @@
1
1
  import json
2
2
  from io import StringIO
3
- from typing import Dict, Generator, List, Optional, Tuple, TypeAlias, Union
3
+ from typing import Dict, Generator, List, Mapping, Optional, Tuple, TypeAlias, Union
4
4
 
5
+ import httpx
5
6
  import pandas as pd
6
- import requests
7
7
 
8
+ from bcb.exceptions import SGSError
8
9
  from bcb.utils import Date, DateInput
9
10
 
10
11
  """
@@ -27,8 +28,8 @@ class SGSCode:
27
28
  self.name = str(name)
28
29
  self.value = int(code)
29
30
 
30
- def __repr__(self):
31
- return f"{self.code} - {self.name}" if self.name else f"{self.code}"
31
+ def __repr__(self) -> str:
32
+ return f"{self.value} - {self.name}" if self.name else f"{self.value}"
32
33
 
33
34
 
34
35
  SGSCodeInput: TypeAlias = Union[
@@ -36,7 +37,7 @@ SGSCodeInput: TypeAlias = Union[
36
37
  str,
37
38
  Tuple[str, Union[int, str]],
38
39
  List[Union[int, str, Tuple[str, Union[int, str]]]],
39
- Dict[str, Union[int, str]],
40
+ Mapping[str, Union[int, str]],
40
41
  ]
41
42
 
42
43
 
@@ -47,28 +48,37 @@ def _codes(codes: SGSCodeInput) -> Generator[SGSCode, None, None]:
47
48
  yield SGSCode(codes[1], codes[0])
48
49
  elif isinstance(codes, list):
49
50
  for cd in codes:
50
- _ist = isinstance(cd, tuple)
51
- yield SGSCode(cd[1], cd[0]) if _ist else SGSCode(cd)
52
- elif isinstance(codes, dict):
51
+ if isinstance(cd, tuple):
52
+ yield SGSCode(cd[1], cd[0])
53
+ else:
54
+ yield SGSCode(cd)
55
+ elif isinstance(codes, Mapping):
53
56
  for name, code in codes.items():
54
57
  yield SGSCode(code, name)
55
58
 
56
59
 
57
- def _get_url_and_payload(code: int, start_date: DateInput, end_date: DateInput, last: int) -> Dict[str, str]:
58
- payload = {"formato": "json"}
60
+ def _get_url_and_payload(
61
+ code: int,
62
+ start_date: Optional[DateInput],
63
+ end_date: Optional[DateInput],
64
+ last: int,
65
+ ) -> Tuple[str, Dict[str, str]]:
66
+ payload: Dict[str, str] = {"formato": "json"}
59
67
  if last == 0:
60
68
  if start_date is not None or end_date is not None:
61
- payload["dataInicial"] = Date(start_date).date.strftime("%d/%m/%Y")
69
+ payload["dataInicial"] = Date(start_date).date.strftime("%d/%m/%Y") # type: ignore[arg-type]
62
70
  end_date = end_date if end_date else "today"
63
71
  payload["dataFinal"] = Date(end_date).date.strftime("%d/%m/%Y")
64
- url = "https://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados".format(code)
72
+ url = f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.{code}/dados"
65
73
  else:
66
- url = ("https://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados" "/ultimos/{}").format(code, last)
74
+ url = (
75
+ f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.{code}/dados/ultimos/{last}"
76
+ )
67
77
 
68
- return {"payload": payload, "url": url}
78
+ return url, payload
69
79
 
70
80
 
71
- def _format_df(df: pd.DataFrame, code: SGSCode, freq: str) -> pd.DataFrame:
81
+ def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataFrame:
72
82
  cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
73
83
  df = df.rename(columns=cns)
74
84
  if "Date" in df:
@@ -147,7 +157,12 @@ def get(
147
157
  return dfs
148
158
 
149
159
 
150
- def get_json(code: int, start: Optional[DateInput] = None, end: Optional[DateInput] = None, last: int = 0) -> str:
160
+ def get_json(
161
+ code: int,
162
+ start: Optional[DateInput] = None,
163
+ end: Optional[DateInput] = None,
164
+ last: int = 0,
165
+ ) -> str:
151
166
  """
152
167
  Retorna um JSON com séries temporais obtidas do SGS.
153
168
 
@@ -173,16 +188,16 @@ def get_json(code: int, start: Optional[DateInput] = None, end: Optional[DateInp
173
188
  JSON :
174
189
  série temporal univariada em formato JSON.
175
190
  """
176
- urd = _get_url_and_payload(code, start, end, last)
177
- res = requests.get(urd["url"], params=urd["payload"])
191
+ url, payload = _get_url_and_payload(code, start, end, last)
192
+ res = httpx.get(url, params=payload, follow_redirects=True)
178
193
  if res.status_code != 200:
179
194
  try:
180
195
  res_json = json.loads(res.text)
181
196
  except Exception:
182
197
  res_json = {}
183
198
  if "error" in res_json:
184
- raise Exception("BCB error: {}".format(res_json["error"]))
199
+ raise SGSError(f"BCB error: {res_json['error']}")
185
200
  elif "erro" in res_json:
186
- raise Exception("BCB error: {}".format(res_json["erro"]["detail"]))
187
- raise Exception("Download error: code = {}".format(code))
188
- return res.text
201
+ raise SGSError(f"BCB error: {res_json['erro']['detail']}")
202
+ raise SGSError(f"Download error: code = {code}")
203
+ return str(res.text)
@@ -124,14 +124,24 @@ NON_PERFORMING_LOANS_BY_STATE_TOTAL = {
124
124
  }
125
125
 
126
126
 
127
- def get_non_performing_loans_codes(states_or_region: Union[str, List[str]], mode: str = "total") -> Dict[str, str]:
127
+ def get_non_performing_loans_codes(
128
+ states_or_region: Union[str, List[str]], mode: str = "total"
129
+ ) -> Dict[str, str]:
128
130
  is_state = False
129
131
  is_region = False
130
- states_or_region = [states_or_region] if isinstance(states_or_region, str) else states_or_region
132
+ states_or_region = (
133
+ [states_or_region] if isinstance(states_or_region, str) else states_or_region
134
+ )
131
135
  states_or_region = [location.upper() for location in states_or_region]
132
- if any(location in list(NON_PERFORMING_LOANS_BY_STATE_TOTAL.keys()) for location in states_or_region):
136
+ if any(
137
+ location in list(NON_PERFORMING_LOANS_BY_STATE_TOTAL.keys())
138
+ for location in states_or_region
139
+ ):
133
140
  is_state = True
134
- elif any(location in list(NON_PERFORMING_LOANS_BY_REGION_TOTAL.keys()) for location in states_or_region):
141
+ elif any(
142
+ location in list(NON_PERFORMING_LOANS_BY_REGION_TOTAL.keys())
143
+ for location in states_or_region
144
+ ):
135
145
  is_region = True
136
146
 
137
147
  if not is_state and not is_region:
bcb/utils.py CHANGED
@@ -29,25 +29,27 @@ class Date:
29
29
  elif isinstance(d, date):
30
30
  pass
31
31
  else:
32
- raise ValueError()
32
+ raise ValueError(f"Unsupported date type: {type(d).__name__}")
33
33
  self.date: date = d
34
34
 
35
35
  def format(self, fmts: str = "%Y-%m-%d") -> str:
36
36
  return datetime.strftime(self.date, fmts)
37
37
 
38
- def __gt__(self, other) -> bool:
38
+ def __gt__(self, other: "Date") -> bool:
39
39
  return self.date > other.date
40
40
 
41
- def __ge__(self, other) -> bool:
41
+ def __ge__(self, other: "Date") -> bool:
42
42
  return self.date >= other.date
43
43
 
44
- def __lt__(self, other) -> bool:
44
+ def __lt__(self, other: "Date") -> bool:
45
45
  return self.date < other.date
46
46
 
47
- def __le__(self, other) -> bool:
47
+ def __le__(self, other: "Date") -> bool:
48
48
  return self.date <= other.date
49
49
 
50
- def __eq__(self, other) -> bool:
50
+ def __eq__(self, other: object) -> bool:
51
+ if not isinstance(other, Date):
52
+ return NotImplemented
51
53
  return self.date == other.date
52
54
 
53
55
  def __repr__(self) -> str:
@@ -1,7 +1,8 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: python-bcb
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary:
5
+ License-File: LICENSE
5
6
  Author: wilsonfreitas
6
7
  Author-email: wilson.freitas@gmail.com
7
8
  Requires-Python: >=3.10
@@ -9,10 +10,11 @@ Classifier: Programming Language :: Python :: 3
9
10
  Classifier: Programming Language :: Python :: 3.10
10
11
  Classifier: Programming Language :: Python :: 3.11
11
12
  Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
12
15
  Requires-Dist: httpx (>=0.24.0)
13
16
  Requires-Dist: lxml (>=4.9.2)
14
17
  Requires-Dist: pandas (>=2.0.0)
15
- Requires-Dist: requests (>=2.31.0)
16
18
  Description-Content-Type: text/markdown
17
19
 
18
20
  # python-bcb
@@ -22,6 +24,8 @@ da API de dados abertos do [Banco Central do Brasil](https://www.bcb.gov.br).
22
24
 
23
25
  [![Downloads](https://img.shields.io/pypi/dm/python-bcb.svg)](https://pypi.python.org/pypi/python-bcb/)
24
26
  [![image](https://img.shields.io/pypi/v/python-bcb.svg?color=green)](https://pypi.python.org/pypi/python-bcb/)
27
+ ![Test workflow](https://github.com/wilsonfreitas/python-bcb/actions/workflows/test.yml/badge.svg)
28
+ ![Lint workflow](https://github.com/wilsonfreitas/python-bcb/actions/workflows/lint.yml/badge.svg)
25
29
  ![Sphinx workflow](https://github.com/wilsonfreitas/python-bcb/actions/workflows/sphinx.yml/badge.svg)
26
30
 
27
31
 
@@ -0,0 +1,13 @@
1
+ bcb/__init__.py,sha256=5L_MdfdTJSSOtNzwRp70bffQHQeiEzE2EwOesa7UcUI,487
2
+ bcb/currency.py,sha256=lRlbjoqsEbHuYJRJ-gmUGpJwHRy4eqTUaMWxpiURuhI,7555
3
+ bcb/exceptions.py,sha256=_LwjDQJSuQ0DEaxWqnqeW3kyfcbroBBHd5Lwl5T4Qic,557
4
+ bcb/odata/__init__.py,sha256=KLST8kgN_vk0YcNrZ-GHXHhfGTzDXXGfi71J5FCTvmc,365
5
+ bcb/odata/api.py,sha256=vGZA8z4MsWl_L90iy9o7sercQXmvtdFh3jskMk7pySs,19081
6
+ bcb/odata/framework.py,sha256=JmSid8AFmNw9O0uKAGEE3_LmuyJaaLSSDh469qaQLNo,17675
7
+ bcb/sgs/__init__.py,sha256=hbJrkUO4FUFqOEAqgEvHER95xVVEL9_N-3LAWitmV5E,6823
8
+ bcb/sgs/regional_economy.py,sha256=US5DpNyJ28V-Rh9UDKQPmWyFLjkQTNrRW56MvSS_qPA,6265
9
+ bcb/utils.py,sha256=SZiOAwwWA7fP3ztVMkdpQaBjUan0t_F2mFxOJXoTRdc,1715
10
+ python_bcb-0.3.4.dist-info/METADATA,sha256=RRUUGkwMrxgWItRpHAhCofOk6CSWWh7_vetJt_BvB2o,2812
11
+ python_bcb-0.3.4.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
12
+ python_bcb-0.3.4.dist-info/licenses/LICENSE,sha256=PK0tDWJUgRdeZCmA39ZHQu8v2ozAOl49qEaDEcntbAA,1070
13
+ python_bcb-0.3.4.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 1.8.1
2
+ Generator: poetry-core 2.2.1
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,12 +0,0 @@
1
- bcb/__init__.py,sha256=TpLWnEt2a3uOsIgd-DBYrU7FgWC6nuk3rB4-QZgQsxY,371
2
- bcb/currency.py,sha256=5JaPPpdT3ylLukJlljn9pRhYM5PVuYLWaiNCZbgMolU,6386
3
- bcb/odata/__init__.py,sha256=KLST8kgN_vk0YcNrZ-GHXHhfGTzDXXGfi71J5FCTvmc,365
4
- bcb/odata/api.py,sha256=ZSGFSlRRBy-DlFfq9Z8B-VE4GvA7105SzC_boKXsN8k,17642
5
- bcb/odata/framework.py,sha256=v_z_bsgcGM-Jbwgu0RZdQUQk7fOGUOJ9LsVHpz_3n7M,15335
6
- bcb/sgs/__init__.py,sha256=MkT5GqCBsNGfNWyPWVB_Knu6LTMhdlZLJiicwvpSLnw,6627
7
- bcb/sgs/regional_economy.py,sha256=qOTdxnB3SuocN4OaAwh0vzWBwAOXLOKbawhr5tQAYgE,6189
8
- bcb/utils.py,sha256=HFaDdPl1oPTePdT0f5nNjXNE5dqTouVN6bAkFd7Guro,1557
9
- python_bcb-0.3.3.dist-info/LICENSE,sha256=PK0tDWJUgRdeZCmA39ZHQu8v2ozAOl49qEaDEcntbAA,1070
10
- python_bcb-0.3.3.dist-info/METADATA,sha256=t5d3Qara2vTcO1Soz24PJJpT0Ztf4OY7nqqc2p8jkBY,2525
11
- python_bcb-0.3.3.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
12
- python_bcb-0.3.3.dist-info/RECORD,,