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/sgs/__init__.py CHANGED
@@ -1,12 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
1
4
  import json
5
+ import logging
6
+ from dataclasses import dataclass
2
7
  from io import StringIO
3
- from typing import Dict, Generator, List, Optional, Tuple, TypeAlias, Union
8
+ from typing import (
9
+ Dict,
10
+ Generator,
11
+ List,
12
+ Literal,
13
+ Mapping,
14
+ Optional,
15
+ Tuple,
16
+ TypeAlias,
17
+ Union,
18
+ overload,
19
+ )
4
20
 
5
21
  import pandas as pd
6
- import requests
7
22
 
23
+ from bcb.http import _CLIENT, _ASYNC_CLIENT
24
+ from bcb.exceptions import BCBRateLimitError, SGSError
8
25
  from bcb.utils import Date, DateInput
9
26
 
27
+ logger = logging.getLogger(__name__)
28
+
10
29
  """
11
30
  Sistema Gerenciador de Séries Temporais (SGS)
12
31
 
@@ -17,18 +36,58 @@ interface json do serviço BCData/SGS -
17
36
  """
18
37
 
19
38
 
39
+ @dataclass(frozen=True)
20
40
  class SGSCode:
21
- def __init__(self, code: Union[str, int], name: Optional[str] = None) -> None:
22
- if name is None:
23
- if isinstance(code, int) or isinstance(code, str):
24
- self.name = str(code)
25
- self.value = int(code)
26
- else:
27
- self.name = str(name)
28
- self.value = int(code)
41
+ """SGS time series code with optional human-readable name.
42
+
43
+ Attributes
44
+ ----------
45
+ value : int
46
+ Numeric SGS code
47
+ name : str
48
+ Human-readable name or string representation of code
49
+ """
50
+
51
+ value: int
52
+ name: str
53
+
54
+ @classmethod
55
+ def from_code(cls, code: int | str) -> "SGSCode":
56
+ """Create SGSCode from numeric or string code.
57
+
58
+ Parameters
59
+ ----------
60
+ code : int | str
61
+ SGS code
62
+
63
+ Returns
64
+ -------
65
+ SGSCode
66
+ New instance with name = str(code)
67
+ """
68
+ code_int = int(code)
69
+ return cls(value=code_int, name=str(code_int))
70
+
71
+ @classmethod
72
+ def from_named(cls, code: int | str, name: str) -> "SGSCode":
73
+ """Create SGSCode with explicit name.
74
+
75
+ Parameters
76
+ ----------
77
+ code : int | str
78
+ SGS code
79
+ name : str
80
+ Human-readable name
81
+
82
+ Returns
83
+ -------
84
+ SGSCode
85
+ New instance with value and name
86
+ """
87
+ return cls(value=int(code), name=name)
29
88
 
30
- def __repr__(self):
31
- return f"{self.code} - {self.name}" if self.name else f"{self.code}"
89
+ def __repr__(self) -> str:
90
+ return f"{self.value} - {self.name}"
32
91
 
33
92
 
34
93
  SGSCodeInput: TypeAlias = Union[
@@ -36,39 +95,90 @@ SGSCodeInput: TypeAlias = Union[
36
95
  str,
37
96
  Tuple[str, Union[int, str]],
38
97
  List[Union[int, str, Tuple[str, Union[int, str]]]],
39
- Dict[str, Union[int, str]],
98
+ Mapping[str, Union[int, str]],
40
99
  ]
41
100
 
42
101
 
102
+ def _validate_sgs_code(code: SGSCode) -> None:
103
+ """Validate SGSCode value.
104
+
105
+ Parameters
106
+ ----------
107
+ code : SGSCode
108
+ Code to validate
109
+
110
+ Raises
111
+ ------
112
+ ValueError
113
+ If code value is not positive integer
114
+ """
115
+ if code.value <= 0:
116
+ raise ValueError(f"SGS code must be positive integer, got {code.value}")
117
+
118
+
43
119
  def _codes(codes: SGSCodeInput) -> Generator[SGSCode, None, None]:
120
+ """Normalize various SGSCodeInput formats to SGSCode instances.
121
+
122
+ Parameters
123
+ ----------
124
+ codes : SGSCodeInput
125
+ Input in various formats: int, str, tuple, list, or mapping
126
+
127
+ Yields
128
+ ------
129
+ SGSCode
130
+ Validated SGSCode instances
131
+
132
+ Raises
133
+ ------
134
+ ValueError
135
+ If any code is a non-positive integer
136
+ """
44
137
  if isinstance(codes, int) or isinstance(codes, str):
45
- yield SGSCode(codes)
138
+ code_obj = SGSCode.from_code(codes)
139
+ _validate_sgs_code(code_obj)
140
+ yield code_obj
46
141
  elif isinstance(codes, tuple):
47
- yield SGSCode(codes[1], codes[0])
142
+ code_obj = SGSCode.from_named(codes[1], codes[0])
143
+ _validate_sgs_code(code_obj)
144
+ yield code_obj
48
145
  elif isinstance(codes, list):
49
146
  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):
147
+ if isinstance(cd, tuple):
148
+ code_obj = SGSCode.from_named(cd[1], cd[0])
149
+ else:
150
+ code_obj = SGSCode.from_code(cd)
151
+ _validate_sgs_code(code_obj)
152
+ yield code_obj
153
+ elif isinstance(codes, Mapping):
53
154
  for name, code in codes.items():
54
- yield SGSCode(code, name)
155
+ code_obj = SGSCode.from_named(code, name)
156
+ _validate_sgs_code(code_obj)
157
+ yield code_obj
55
158
 
56
159
 
57
- def _get_url_and_payload(code: int, start_date: DateInput, end_date: DateInput, last: int) -> Dict[str, str]:
58
- payload = {"formato": "json"}
160
+ def _get_url_and_payload(
161
+ code: int,
162
+ start_date: Optional[DateInput],
163
+ end_date: Optional[DateInput],
164
+ last: int,
165
+ ) -> Tuple[str, Dict[str, str]]:
166
+ payload: Dict[str, str] = {"formato": "json"}
59
167
  if last == 0:
60
168
  if start_date is not None or end_date is not None:
61
- payload["dataInicial"] = Date(start_date).date.strftime("%d/%m/%Y")
169
+ payload["dataInicial"] = Date(start_date).date.strftime("%d/%m/%Y") # type: ignore[arg-type]
62
170
  end_date = end_date if end_date else "today"
63
171
  payload["dataFinal"] = Date(end_date).date.strftime("%d/%m/%Y")
64
- url = "https://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados".format(code)
172
+ url = f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.{code}/dados"
65
173
  else:
66
- url = ("https://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados" "/ultimos/{}").format(code, last)
174
+ url = (
175
+ f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.{code}/dados/ultimos/{last}"
176
+ )
67
177
 
68
- return {"payload": payload, "url": url}
178
+ return url, payload
69
179
 
70
180
 
71
- def _format_df(df: pd.DataFrame, code: SGSCode, freq: str) -> pd.DataFrame:
181
+ def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataFrame:
72
182
  cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
73
183
  df = df.rename(columns=cns)
74
184
  if "Date" in df:
@@ -81,6 +191,30 @@ def _format_df(df: pd.DataFrame, code: SGSCode, freq: str) -> pd.DataFrame:
81
191
  return df
82
192
 
83
193
 
194
+ @overload
195
+ def get(
196
+ codes: SGSCodeInput,
197
+ start: Optional[DateInput] = ...,
198
+ end: Optional[DateInput] = ...,
199
+ last: int = ...,
200
+ multi: bool = ...,
201
+ freq: Optional[str] = ...,
202
+ output: Literal["dataframe"] = ...,
203
+ ) -> Union[pd.DataFrame, List[pd.DataFrame]]: ...
204
+
205
+
206
+ @overload
207
+ def get(
208
+ codes: SGSCodeInput,
209
+ start: Optional[DateInput] = ...,
210
+ end: Optional[DateInput] = ...,
211
+ last: int = ...,
212
+ multi: bool = ...,
213
+ freq: Optional[str] = ...,
214
+ output: Literal["text"] = ...,
215
+ ) -> Union[str, Dict[int, str]]: ...
216
+
217
+
84
218
  def get(
85
219
  codes: SGSCodeInput,
86
220
  start: Optional[DateInput] = None,
@@ -88,7 +222,8 @@ def get(
88
222
  last: int = 0,
89
223
  multi: bool = True,
90
224
  freq: Optional[str] = None,
91
- ) -> Union[pd.DataFrame, List[pd.DataFrame]]:
225
+ output: str = "dataframe",
226
+ ) -> Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]:
92
227
  """
93
228
  Retorna um DataFrame pandas com séries temporais obtidas do SGS.
94
229
 
@@ -120,6 +255,11 @@ def get(
120
255
  série multivariada ou uma lista com séries univariadas.
121
256
  freq : str
122
257
  Define a frequência a ser utilizada na série temporal
258
+ output : str
259
+ Define o formato de saída. Use ``'dataframe'`` (padrão) para retornar
260
+ um DataFrame pandas, ou ``'text'`` para retornar o JSON bruto da API
261
+ do BCB. Para um único código retorna uma string; para múltiplos
262
+ códigos retorna um ``dict`` mapeando código inteiro → JSON string.
123
263
 
124
264
  Returns
125
265
  -------
@@ -131,7 +271,23 @@ def get(
131
271
  ``list`` :
132
272
  lista com séries temporais univariadas,
133
273
  quando solicitado mais de uma série (parâmetro ``multi=False``).
274
+
275
+ ``str`` :
276
+ JSON bruto da API (quando ``output='text'`` e um único código).
277
+
278
+ ``dict`` :
279
+ Mapeamento de código → JSON bruto (quando ``output='text'`` e
280
+ múltiplos códigos).
134
281
  """
282
+ if output == "text":
283
+ results: Dict[int, str] = {}
284
+ for code in _codes(codes):
285
+ results[code.value] = get_json(code.value, start, end, last)
286
+ values = list(results.values())
287
+ if len(values) == 1:
288
+ return values[0]
289
+ return results
290
+
135
291
  dfs = []
136
292
  for code in _codes(codes):
137
293
  text = get_json(code.value, start, end, last)
@@ -147,7 +303,12 @@ def get(
147
303
  return dfs
148
304
 
149
305
 
150
- def get_json(code: int, start: Optional[DateInput] = None, end: Optional[DateInput] = None, last: int = 0) -> str:
306
+ def get_json(
307
+ code: int,
308
+ start: Optional[DateInput] = None,
309
+ end: Optional[DateInput] = None,
310
+ last: int = 0,
311
+ ) -> str:
151
312
  """
152
313
  Retorna um JSON com séries temporais obtidas do SGS.
153
314
 
@@ -173,16 +334,152 @@ def get_json(code: int, start: Optional[DateInput] = None, end: Optional[DateInp
173
334
  JSON :
174
335
  série temporal univariada em formato JSON.
175
336
  """
176
- urd = _get_url_and_payload(code, start, end, last)
177
- res = requests.get(urd["url"], params=urd["payload"])
337
+ url, payload = _get_url_and_payload(code, start, end, last)
338
+ logger.debug(f"Fetching SGS time series code={code} from {url.split('/dados')[0]}")
339
+ res = _CLIENT.get(url, params=payload)
340
+ logger.debug(f"SGS response: status={res.status_code}, length={len(res.text)}")
341
+
342
+ # Check for rate limiting first
343
+ if res.status_code == 429:
344
+ raise BCBRateLimitError(
345
+ "BCB API rate limit exceeded. Please try again later.",
346
+ status_code=429,
347
+ )
348
+
178
349
  if res.status_code != 200:
179
350
  try:
180
351
  res_json = json.loads(res.text)
181
- except Exception:
352
+ except json.JSONDecodeError:
182
353
  res_json = {}
354
+
183
355
  if "error" in res_json:
184
- raise Exception("BCB error: {}".format(res_json["error"]))
356
+ raise SGSError(f"BCB error: {res_json['error']}")
185
357
  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
358
+ raise SGSError(f"BCB error: {res_json['erro']['detail']}")
359
+ raise SGSError(f"Download error: code = {code}")
360
+ return str(res.text)
361
+
362
+
363
+ async def async_get_json(
364
+ code: int,
365
+ start: Optional[DateInput] = None,
366
+ end: Optional[DateInput] = None,
367
+ last: int = 0,
368
+ ) -> str:
369
+ """
370
+ Retorna um JSON com séries temporais obtidas do SGS (async version).
371
+
372
+ Parameters
373
+ ----------
374
+ code : int
375
+ Código da série temporal
376
+ start : str, int, date, datetime, Timestamp, optional
377
+ Data de início da série
378
+ end : string, int, date, datetime, Timestamp, optional
379
+ Data final da série
380
+ last : int
381
+ Retorna os últimos ``last`` elementos disponíveis
382
+
383
+ Returns
384
+ -------
385
+ str
386
+ JSON bruto da API do BCB
387
+
388
+ Raises
389
+ ------
390
+ BCBRateLimitError
391
+ Se API rate limit é excedido (429)
392
+ SGSError
393
+ Se a API retorna um erro
394
+ """
395
+ url, payload = _get_url_and_payload(code, start, end, last)
396
+ logger.debug(
397
+ f"Fetching SGS time series (async) code={code} from {url.split('/dados')[0]}"
398
+ )
399
+ res = await _ASYNC_CLIENT.get(url, params=payload)
400
+ logger.debug(
401
+ f"SGS (async) response: status={res.status_code}, length={len(res.text)}"
402
+ )
403
+
404
+ # Check for rate limiting first
405
+ if res.status_code == 429:
406
+ raise BCBRateLimitError(
407
+ "BCB API rate limit exceeded. Please try again later.",
408
+ status_code=429,
409
+ )
410
+
411
+ if res.status_code != 200:
412
+ try:
413
+ res_json = json.loads(res.text)
414
+ except json.JSONDecodeError:
415
+ res_json = {}
416
+
417
+ if "error" in res_json:
418
+ raise SGSError(f"BCB error: {res_json['error']}")
419
+ elif "erro" in res_json:
420
+ raise SGSError(f"BCB error: {res_json['erro']['detail']}")
421
+ raise SGSError(f"Download error: code = {code}")
422
+ return str(res.text)
423
+
424
+
425
+ async def async_get(
426
+ codes: SGSCodeInput,
427
+ start: Optional[DateInput] = None,
428
+ end: Optional[DateInput] = None,
429
+ last: int = 0,
430
+ multi: bool = True,
431
+ freq: Optional[str] = None,
432
+ output: str = "dataframe",
433
+ ) -> Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]:
434
+ """
435
+ Retorna um DataFrame pandas com séries temporais obtidas do SGS (async version).
436
+
437
+ Same signature as :func:`get`, but uses async HTTP requests and
438
+ :func:`asyncio.gather` to fetch multiple codes concurrently.
439
+
440
+ Parameters
441
+ ----------
442
+ codes : {int, List[int], List[str], Dict[str:int]}
443
+ Código(s) da série temporal
444
+ start : str, int, date, datetime, Timestamp, optional
445
+ Data de início da série
446
+ end : string, int, date, datetime, Timestamp, optional
447
+ Data final da série
448
+ last : int
449
+ Retorna os últimos ``last`` elementos disponíveis
450
+ multi : bool
451
+ Define se retorna série multivariada ou lista de séries univariadas
452
+ freq : str, optional
453
+ Frequência a ser utilizada na série temporal
454
+ output : str
455
+ Formato de saída: ``'dataframe'`` ou ``'text'``
456
+
457
+ Returns
458
+ -------
459
+ Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]
460
+ Série(s) temporal(is) conforme especificado
461
+ """
462
+ code_list = list(_codes(codes))
463
+
464
+ # Concurrent HTTP requests via asyncio.gather()
465
+ texts = await asyncio.gather(
466
+ *[async_get_json(c.value, start, end, last) for c in code_list]
467
+ )
468
+
469
+ if output == "text":
470
+ results: Dict[int, str] = {c.value: t for c, t in zip(code_list, texts)}
471
+ values = list(results.values())
472
+ if len(values) == 1:
473
+ return values[0]
474
+ return results
475
+
476
+ dfs = [
477
+ _format_df(pd.read_json(StringIO(t)), c, freq) for c, t in zip(code_list, texts)
478
+ ]
479
+ if len(dfs) == 1:
480
+ return dfs[0]
481
+ else:
482
+ if multi:
483
+ return pd.concat(dfs, axis=1)
484
+ else:
485
+ return dfs
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  from typing import Dict, List, Optional, Union
2
4
 
3
5
  import pandas as pd
@@ -124,14 +126,24 @@ NON_PERFORMING_LOANS_BY_STATE_TOTAL = {
124
126
  }
125
127
 
126
128
 
127
- def get_non_performing_loans_codes(states_or_region: Union[str, List[str]], mode: str = "total") -> Dict[str, str]:
129
+ def get_non_performing_loans_codes(
130
+ states_or_region: Union[str, List[str]], mode: str = "total"
131
+ ) -> Dict[str, str]:
128
132
  is_state = False
129
133
  is_region = False
130
- states_or_region = [states_or_region] if isinstance(states_or_region, str) else states_or_region
134
+ states_or_region = (
135
+ [states_or_region] if isinstance(states_or_region, str) else states_or_region
136
+ )
131
137
  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):
138
+ if any(
139
+ location in list(NON_PERFORMING_LOANS_BY_STATE_TOTAL.keys())
140
+ for location in states_or_region
141
+ ):
133
142
  is_state = True
134
- elif any(location in list(NON_PERFORMING_LOANS_BY_REGION_TOTAL.keys()) for location in states_or_region):
143
+ elif any(
144
+ location in list(NON_PERFORMING_LOANS_BY_REGION_TOTAL.keys())
145
+ for location in states_or_region
146
+ ):
135
147
  is_region = True
136
148
 
137
149
  if not is_state and not is_region:
bcb/utils.py CHANGED
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  from datetime import date, datetime
2
4
  from typing import TypeAlias, Union
3
5
 
@@ -29,25 +31,27 @@ class Date:
29
31
  elif isinstance(d, date):
30
32
  pass
31
33
  else:
32
- raise ValueError()
34
+ raise ValueError(f"Unsupported date type: {type(d).__name__}")
33
35
  self.date: date = d
34
36
 
35
37
  def format(self, fmts: str = "%Y-%m-%d") -> str:
36
38
  return datetime.strftime(self.date, fmts)
37
39
 
38
- def __gt__(self, other) -> bool:
40
+ def __gt__(self, other: "Date") -> bool:
39
41
  return self.date > other.date
40
42
 
41
- def __ge__(self, other) -> bool:
43
+ def __ge__(self, other: "Date") -> bool:
42
44
  return self.date >= other.date
43
45
 
44
- def __lt__(self, other) -> bool:
46
+ def __lt__(self, other: "Date") -> bool:
45
47
  return self.date < other.date
46
48
 
47
- def __le__(self, other) -> bool:
49
+ def __le__(self, other: "Date") -> bool:
48
50
  return self.date <= other.date
49
51
 
50
- def __eq__(self, other) -> bool:
52
+ def __eq__(self, other: object) -> bool:
53
+ if not isinstance(other, Date):
54
+ return NotImplemented
51
55
  return self.date == other.date
52
56
 
53
57
  def __repr__(self) -> str: