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/sgs/__init__.py CHANGED
@@ -1,9 +1,12 @@
1
+ import json
1
2
  from io import StringIO
3
+ from typing import Dict, Generator, List, Mapping, Optional, Tuple, TypeAlias, Union
2
4
 
3
- import requests
5
+ import httpx
4
6
  import pandas as pd
5
7
 
6
- from bcb.utils import Date
8
+ from bcb.exceptions import SGSError
9
+ from bcb.utils import Date, DateInput
7
10
 
8
11
  """
9
12
  Sistema Gerenciador de Séries Temporais (SGS)
@@ -16,7 +19,7 @@ interface json do serviço BCData/SGS -
16
19
 
17
20
 
18
21
  class SGSCode:
19
- def __init__(self, code, name=None):
22
+ def __init__(self, code: Union[str, int], name: Optional[str] = None) -> None:
20
23
  if name is None:
21
24
  if isinstance(code, int) or isinstance(code, str):
22
25
  self.name = str(code)
@@ -25,39 +28,57 @@ class SGSCode:
25
28
  self.name = str(name)
26
29
  self.value = int(code)
27
30
 
28
- def __repr__(self):
29
- 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}"
30
33
 
31
34
 
32
- def _codes(codes):
35
+ SGSCodeInput: TypeAlias = Union[
36
+ int,
37
+ str,
38
+ Tuple[str, Union[int, str]],
39
+ List[Union[int, str, Tuple[str, Union[int, str]]]],
40
+ Mapping[str, Union[int, str]],
41
+ ]
42
+
43
+
44
+ def _codes(codes: SGSCodeInput) -> Generator[SGSCode, None, None]:
33
45
  if isinstance(codes, int) or isinstance(codes, str):
34
46
  yield SGSCode(codes)
35
47
  elif isinstance(codes, tuple):
36
48
  yield SGSCode(codes[1], codes[0])
37
49
  elif isinstance(codes, list):
38
50
  for cd in codes:
39
- _ist = isinstance(cd, tuple)
40
- yield SGSCode(cd[1], cd[0]) if _ist else SGSCode(cd)
41
- 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):
42
56
  for name, code in codes.items():
43
57
  yield SGSCode(code, name)
44
58
 
45
59
 
46
- def _get_url_and_payload(code, start_date, end_date, last):
47
- 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"}
48
67
  if last == 0:
49
68
  if start_date is not None or end_date is not None:
50
- 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]
51
70
  end_date = end_date if end_date else "today"
52
71
  payload["dataFinal"] = Date(end_date).date.strftime("%d/%m/%Y")
53
- 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"
54
73
  else:
55
- 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
+ )
56
77
 
57
- return {"payload": payload, "url": url}
78
+ return url, payload
58
79
 
59
80
 
60
- def _format_df(df, code, freq):
81
+ def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataFrame:
61
82
  cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
62
83
  df = df.rename(columns=cns)
63
84
  if "Date" in df:
@@ -70,7 +91,14 @@ def _format_df(df, code, freq):
70
91
  return df
71
92
 
72
93
 
73
- def get(codes, start=None, end=None, last=0, multi=True, freq=None):
94
+ def get(
95
+ codes: SGSCodeInput,
96
+ start: Optional[DateInput] = None,
97
+ end: Optional[DateInput] = None,
98
+ last: int = 0,
99
+ multi: bool = True,
100
+ freq: Optional[str] = None,
101
+ ) -> Union[pd.DataFrame, List[pd.DataFrame]]:
74
102
  """
75
103
  Retorna um DataFrame pandas com séries temporais obtidas do SGS.
76
104
 
@@ -116,11 +144,8 @@ def get(codes, start=None, end=None, last=0, multi=True, freq=None):
116
144
  """
117
145
  dfs = []
118
146
  for code in _codes(codes):
119
- urd = _get_url_and_payload(code.value, start, end, last)
120
- res = requests.get(urd["url"], params=urd["payload"])
121
- if res.status_code != 200:
122
- raise Exception("Download error: code = {}".format(code.value))
123
- df = pd.read_json(StringIO(res.text))
147
+ text = get_json(code.value, start, end, last)
148
+ df = pd.read_json(StringIO(text))
124
149
  df = _format_df(df, code, freq)
125
150
  dfs.append(df)
126
151
  if len(dfs) == 1:
@@ -130,3 +155,49 @@ def get(codes, start=None, end=None, last=0, multi=True, freq=None):
130
155
  return pd.concat(dfs, axis=1)
131
156
  else:
132
157
  return dfs
158
+
159
+
160
+ def get_json(
161
+ code: int,
162
+ start: Optional[DateInput] = None,
163
+ end: Optional[DateInput] = None,
164
+ last: int = 0,
165
+ ) -> str:
166
+ """
167
+ Retorna um JSON com séries temporais obtidas do SGS.
168
+
169
+ Parameters
170
+ ----------
171
+
172
+ code : int
173
+ Código da série temporal
174
+ start : str, int, date, datetime, Timestamp
175
+ Data de início da série.
176
+ Interpreta diferentes tipos e formatos de datas.
177
+ end : string, int, date, datetime, Timestamp
178
+ Data final da série.
179
+ Interpreta diferentes tipos e formatos de datas.
180
+ last : int
181
+ Retorna os últimos ``last`` elementos disponíveis da série temporal
182
+ solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
183
+ e ``end`` são ignorados.
184
+
185
+ Returns
186
+ -------
187
+
188
+ JSON :
189
+ série temporal univariada em formato JSON.
190
+ """
191
+ url, payload = _get_url_and_payload(code, start, end, last)
192
+ res = httpx.get(url, params=payload, follow_redirects=True)
193
+ if res.status_code != 200:
194
+ try:
195
+ res_json = json.loads(res.text)
196
+ except Exception:
197
+ res_json = {}
198
+ if "error" in res_json:
199
+ raise SGSError(f"BCB error: {res_json['error']}")
200
+ elif "erro" in res_json:
201
+ raise SGSError(f"BCB error: {res_json['erro']['detail']}")
202
+ raise SGSError(f"Download error: code = {code}")
203
+ return str(res.text)
@@ -1,4 +1,9 @@
1
+ from typing import Dict, List, Optional, Union
2
+
3
+ import pandas as pd
4
+
1
5
  from bcb.sgs import get
6
+ from bcb.utils import DateInput
2
7
 
3
8
  """
4
9
  Dados da Economia Regional
@@ -119,14 +124,24 @@ NON_PERFORMING_LOANS_BY_STATE_TOTAL = {
119
124
  }
120
125
 
121
126
 
122
- def get_non_performing_loans_codes(states_or_region, mode="total"):
127
+ def get_non_performing_loans_codes(
128
+ states_or_region: Union[str, List[str]], mode: str = "total"
129
+ ) -> Dict[str, str]:
123
130
  is_state = False
124
131
  is_region = False
125
- 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
+ )
126
135
  states_or_region = [location.upper() for location in states_or_region]
127
- 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
+ ):
128
140
  is_state = True
129
- 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
+ ):
130
145
  is_region = True
131
146
 
132
147
  if not is_state and not is_region:
@@ -151,7 +166,14 @@ def get_non_performing_loans_codes(states_or_region, mode="total"):
151
166
  return codes
152
167
 
153
168
 
154
- def get_non_performing_loans(states_or_region, mode="total", start=None, end=None, last=0, freq=None):
169
+ def get_non_performing_loans(
170
+ states_or_region: Union[str, List[str]],
171
+ mode: str = "total",
172
+ start: Optional[DateInput] = None,
173
+ end: Optional[DateInput] = None,
174
+ last: int = 0,
175
+ freq: Optional[str] = None,
176
+ ) -> pd.DataFrame:
155
177
  """Dados de inadimplência das operações de crédito.
156
178
 
157
179
  Esta função é um *wrapper* para o método para a função ``get`` do módulo ``sgs``,
bcb/utils.py CHANGED
@@ -1,21 +1,22 @@
1
- from datetime import datetime, date
2
-
1
+ from datetime import date, datetime
2
+ from typing import TypeAlias, Union
3
3
 
4
4
  BRAZILIAN_REGIONS = {
5
- "N": ["AC", "AP", "AM", "PA", "RO", "RR", "TO"],
6
- "NE": ["AL", "BA", "CE", "MA", "PB", "PE", "PI", "RN", "SE"],
7
- "CO": ["DF", "GO", "MT", "MS"],
8
- "SE": ["ES", "MG", "RJ", "SP"],
9
- "S": ["PR", "RS", "SC"]
5
+ "N": ["AC", "AP", "AM", "PA", "RO", "RR", "TO"],
6
+ "NE": ["AL", "BA", "CE", "MA", "PB", "PE", "PI", "RN", "SE"],
7
+ "CO": ["DF", "GO", "MT", "MS"],
8
+ "SE": ["ES", "MG", "RJ", "SP"],
9
+ "S": ["PR", "RS", "SC"],
10
10
  }
11
11
  BRAZILIAN_STATES = []
12
12
  for state in BRAZILIAN_REGIONS.values():
13
13
  BRAZILIAN_STATES.extend(state)
14
14
 
15
+ DateInput: TypeAlias = Union[str, datetime, "Date", date]
16
+
15
17
 
16
18
  class Date:
17
- def __init__(self, d=None, format="%Y-%m-%d", mindate=date(1900, 1, 1)):
18
- d = d if d else mindate
19
+ def __init__(self, d: DateInput, format: str = "%Y-%m-%d") -> None:
19
20
  if isinstance(d, str):
20
21
  if d == "now" or d == "today":
21
22
  d = date.today()
@@ -28,28 +29,30 @@ class Date:
28
29
  elif isinstance(d, date):
29
30
  pass
30
31
  else:
31
- raise ValueError()
32
- self.date = d
32
+ raise ValueError(f"Unsupported date type: {type(d).__name__}")
33
+ self.date: date = d
33
34
 
34
- def format(self, fmts="%Y-%m-%d"):
35
+ def format(self, fmts: str = "%Y-%m-%d") -> str:
35
36
  return datetime.strftime(self.date, fmts)
36
37
 
37
- def __gt__(self, other):
38
+ def __gt__(self, other: "Date") -> bool:
38
39
  return self.date > other.date
39
40
 
40
- def __ge__(self, other):
41
+ def __ge__(self, other: "Date") -> bool:
41
42
  return self.date >= other.date
42
43
 
43
- def __lt__(self, other):
44
+ def __lt__(self, other: "Date") -> bool:
44
45
  return self.date < other.date
45
46
 
46
- def __le__(self, other):
47
+ def __le__(self, other: "Date") -> bool:
47
48
  return self.date <= other.date
48
49
 
49
- def __eq__(self, other):
50
+ def __eq__(self, other: object) -> bool:
51
+ if not isinstance(other, Date):
52
+ return NotImplemented
50
53
  return self.date == other.date
51
54
 
52
- def __repr__(self):
55
+ def __repr__(self) -> str:
53
56
  return self.format()
54
57
 
55
58
  __str__ = __repr__
@@ -1,7 +1,8 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: python-bcb
3
- Version: 0.3.2
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=yGU4BLdmy69hBK2o2DyPciHIr21fhWDzQfd6WFkewQI,6114
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=OPpYSmYYMnmLkldNf4FCq0RADRO8IgfPfkRrwRMBRCM,4738
7
- bcb/sgs/regional_economy.py,sha256=Y8FvaufqeGVXsuQp1wfGcbNEfrGq_dDZ_YILz_Fz85o,5885
8
- bcb/utils.py,sha256=dNJx7YR-Chi6NYAa-J74wTSV33ckrIICD7f4HbmRD_I,1427
9
- python_bcb-0.3.2.dist-info/LICENSE,sha256=PK0tDWJUgRdeZCmA39ZHQu8v2ozAOl49qEaDEcntbAA,1070
10
- python_bcb-0.3.2.dist-info/METADATA,sha256=Rpe6YO7DOD2XtARSbQ0tlwB-cU3_SJ0rn-utmaQJcoQ,2525
11
- python_bcb-0.3.2.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
12
- python_bcb-0.3.2.dist-info/RECORD,,