python-bcb 0.3.6__py3-none-any.whl → 0.4.0__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/currency.py +368 -210
- bcb/http.py +101 -15
- bcb/odata/api.py +116 -31
- bcb/odata/framework.py +304 -68
- bcb/sgs/__init__.py +197 -73
- bcb/sgs/regional_economy.py +68 -44
- {python_bcb-0.3.6.dist-info → python_bcb-0.4.0.dist-info}/METADATA +45 -11
- python_bcb-0.4.0.dist-info/RECORD +14 -0
- {python_bcb-0.3.6.dist-info → python_bcb-0.4.0.dist-info}/WHEEL +1 -1
- python_bcb-0.3.6.dist-info/RECORD +0 -14
- {python_bcb-0.3.6.dist-info → python_bcb-0.4.0.dist-info}/licenses/LICENSE +0 -0
bcb/sgs/__init__.py
CHANGED
|
@@ -18,10 +18,19 @@ from typing import (
|
|
|
18
18
|
overload,
|
|
19
19
|
)
|
|
20
20
|
|
|
21
|
+
import httpx
|
|
21
22
|
import pandas as pd
|
|
22
23
|
|
|
23
|
-
from bcb.http import
|
|
24
|
-
|
|
24
|
+
from bcb.http import (
|
|
25
|
+
RequestTimeout,
|
|
26
|
+
get_async_client,
|
|
27
|
+
get_client,
|
|
28
|
+
raise_for_request_error,
|
|
29
|
+
raise_for_status,
|
|
30
|
+
timeout_kwargs,
|
|
31
|
+
with_retry,
|
|
32
|
+
)
|
|
33
|
+
from bcb.exceptions import SGSError
|
|
25
34
|
from bcb.utils import Date, DateInput
|
|
26
35
|
|
|
27
36
|
logger = logging.getLogger(__name__)
|
|
@@ -99,6 +108,16 @@ SGSCodeInput: TypeAlias = Union[
|
|
|
99
108
|
]
|
|
100
109
|
|
|
101
110
|
|
|
111
|
+
def _validate_sgs_output(output: str) -> None:
|
|
112
|
+
if output not in ("dataframe", "text"):
|
|
113
|
+
raise ValueError("Unknown output value, use: dataframe, text")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _validate_last(last: int) -> None:
|
|
117
|
+
if not isinstance(last, int) or last < 0:
|
|
118
|
+
raise ValueError(f"last must be a non-negative integer, got {last!r}")
|
|
119
|
+
|
|
120
|
+
|
|
102
121
|
def _validate_sgs_code(code: SGSCode) -> None:
|
|
103
122
|
"""Validate SGSCode value.
|
|
104
123
|
|
|
@@ -139,22 +158,32 @@ def _codes(codes: SGSCodeInput) -> Generator[SGSCode, None, None]:
|
|
|
139
158
|
_validate_sgs_code(code_obj)
|
|
140
159
|
yield code_obj
|
|
141
160
|
elif isinstance(codes, tuple):
|
|
161
|
+
if len(codes) != 2:
|
|
162
|
+
raise ValueError("Named SGS code tuples must contain (name, code)")
|
|
142
163
|
code_obj = SGSCode.from_named(codes[1], codes[0])
|
|
143
164
|
_validate_sgs_code(code_obj)
|
|
144
165
|
yield code_obj
|
|
145
166
|
elif isinstance(codes, list):
|
|
167
|
+
if not codes:
|
|
168
|
+
raise ValueError("At least one SGS code must be provided")
|
|
146
169
|
for cd in codes:
|
|
147
170
|
if isinstance(cd, tuple):
|
|
171
|
+
if len(cd) != 2:
|
|
172
|
+
raise ValueError("Named SGS code tuples must contain (name, code)")
|
|
148
173
|
code_obj = SGSCode.from_named(cd[1], cd[0])
|
|
149
174
|
else:
|
|
150
175
|
code_obj = SGSCode.from_code(cd)
|
|
151
176
|
_validate_sgs_code(code_obj)
|
|
152
177
|
yield code_obj
|
|
153
178
|
elif isinstance(codes, Mapping):
|
|
179
|
+
if not codes:
|
|
180
|
+
raise ValueError("At least one SGS code must be provided")
|
|
154
181
|
for name, code in codes.items():
|
|
155
182
|
code_obj = SGSCode.from_named(code, name)
|
|
156
183
|
_validate_sgs_code(code_obj)
|
|
157
184
|
yield code_obj
|
|
185
|
+
else:
|
|
186
|
+
raise ValueError(f"Unsupported SGS code input: {codes!r}")
|
|
158
187
|
|
|
159
188
|
|
|
160
189
|
def _get_url_and_payload(
|
|
@@ -163,6 +192,7 @@ def _get_url_and_payload(
|
|
|
163
192
|
end_date: Optional[DateInput],
|
|
164
193
|
last: int,
|
|
165
194
|
) -> Tuple[str, Dict[str, str]]:
|
|
195
|
+
_validate_last(last)
|
|
166
196
|
payload: Dict[str, str] = {"formato": "json"}
|
|
167
197
|
if last == 0:
|
|
168
198
|
if start_date is not None or end_date is not None:
|
|
@@ -178,6 +208,44 @@ def _get_url_and_payload(
|
|
|
178
208
|
return url, payload
|
|
179
209
|
|
|
180
210
|
|
|
211
|
+
def _raise_sgs_response_error(res: httpx.Response, code: int) -> None:
|
|
212
|
+
if res.status_code == 429:
|
|
213
|
+
raise_for_status(res, context=f"SGS time series code={code}")
|
|
214
|
+
|
|
215
|
+
try:
|
|
216
|
+
res_json = json.loads(res.text)
|
|
217
|
+
except json.JSONDecodeError:
|
|
218
|
+
res_json = {}
|
|
219
|
+
|
|
220
|
+
if "error" in res_json:
|
|
221
|
+
raise SGSError(f"BCB error: {res_json['error']}")
|
|
222
|
+
if "erro" in res_json:
|
|
223
|
+
raise SGSError(f"BCB error: {res_json['erro']['detail']}")
|
|
224
|
+
|
|
225
|
+
raise_for_status(
|
|
226
|
+
res,
|
|
227
|
+
context=f"SGS time series code={code}",
|
|
228
|
+
error_cls=SGSError,
|
|
229
|
+
not_found_cls=SGSError,
|
|
230
|
+
server_error_cls=SGSError,
|
|
231
|
+
error_message=f"Download error: code = {code}",
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@with_retry
|
|
236
|
+
def _get_sgs_response(
|
|
237
|
+
url: str, payload: Dict[str, str], timeout: RequestTimeout
|
|
238
|
+
) -> httpx.Response:
|
|
239
|
+
return get_client().get(url, params=payload, **timeout_kwargs(timeout))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@with_retry
|
|
243
|
+
async def _async_get_sgs_response(
|
|
244
|
+
url: str, payload: Dict[str, str], timeout: RequestTimeout
|
|
245
|
+
) -> httpx.Response:
|
|
246
|
+
return await get_async_client().get(url, params=payload, **timeout_kwargs(timeout))
|
|
247
|
+
|
|
248
|
+
|
|
181
249
|
def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataFrame:
|
|
182
250
|
cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
|
|
183
251
|
df = df.rename(columns=cns)
|
|
@@ -191,6 +259,23 @@ def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataF
|
|
|
191
259
|
return df
|
|
192
260
|
|
|
193
261
|
|
|
262
|
+
def _tidy_df(df: pd.DataFrame) -> pd.DataFrame:
|
|
263
|
+
frames = []
|
|
264
|
+
for position, series_name in enumerate(df.columns):
|
|
265
|
+
frames.append(
|
|
266
|
+
pd.DataFrame(
|
|
267
|
+
{
|
|
268
|
+
"Date": df.index,
|
|
269
|
+
"series": series_name,
|
|
270
|
+
"value": df.iloc[:, position].to_numpy(),
|
|
271
|
+
}
|
|
272
|
+
)
|
|
273
|
+
)
|
|
274
|
+
if not frames:
|
|
275
|
+
return pd.DataFrame(columns=["Date", "series", "value"])
|
|
276
|
+
return pd.concat(frames, ignore_index=True)
|
|
277
|
+
|
|
278
|
+
|
|
194
279
|
@overload
|
|
195
280
|
def get(
|
|
196
281
|
codes: SGSCodeInput,
|
|
@@ -200,6 +285,9 @@ def get(
|
|
|
200
285
|
multi: bool = ...,
|
|
201
286
|
freq: Optional[str] = ...,
|
|
202
287
|
output: Literal["dataframe"] = ...,
|
|
288
|
+
tidy: bool = ...,
|
|
289
|
+
*,
|
|
290
|
+
timeout: RequestTimeout = ...,
|
|
203
291
|
) -> Union[pd.DataFrame, List[pd.DataFrame]]: ...
|
|
204
292
|
|
|
205
293
|
|
|
@@ -212,6 +300,9 @@ def get(
|
|
|
212
300
|
multi: bool = ...,
|
|
213
301
|
freq: Optional[str] = ...,
|
|
214
302
|
output: Literal["text"] = ...,
|
|
303
|
+
tidy: bool = ...,
|
|
304
|
+
*,
|
|
305
|
+
timeout: RequestTimeout = ...,
|
|
215
306
|
) -> Union[str, Dict[int, str]]: ...
|
|
216
307
|
|
|
217
308
|
|
|
@@ -222,7 +313,10 @@ def get(
|
|
|
222
313
|
last: int = 0,
|
|
223
314
|
multi: bool = True,
|
|
224
315
|
freq: Optional[str] = None,
|
|
225
|
-
output:
|
|
316
|
+
output: Literal["dataframe", "text"] = "dataframe",
|
|
317
|
+
tidy: bool = False,
|
|
318
|
+
*,
|
|
319
|
+
timeout: RequestTimeout = None,
|
|
226
320
|
) -> Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]:
|
|
227
321
|
"""
|
|
228
322
|
Retorna um DataFrame pandas com séries temporais obtidas do SGS.
|
|
@@ -240,12 +334,12 @@ def get(
|
|
|
240
334
|
|
|
241
335
|
Com códigos numéricos é interessante utilizar os nomes com os códigos
|
|
242
336
|
para definir os nomes nas colunas das séries temporais.
|
|
243
|
-
start : str,
|
|
244
|
-
Data de início da série.
|
|
245
|
-
|
|
246
|
-
end :
|
|
247
|
-
Data final da série.
|
|
248
|
-
|
|
337
|
+
start : str, date, datetime or bcb.utils.Date
|
|
338
|
+
Data de início da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
339
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
340
|
+
end : str, date, datetime or bcb.utils.Date
|
|
341
|
+
Data final da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
342
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
249
343
|
last : int
|
|
250
344
|
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
251
345
|
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|
|
@@ -260,6 +354,13 @@ def get(
|
|
|
260
354
|
um DataFrame pandas, ou ``'text'`` para retornar o JSON bruto da API
|
|
261
355
|
do BCB. Para um único código retorna uma string; para múltiplos
|
|
262
356
|
códigos retorna um ``dict`` mapeando código inteiro → JSON string.
|
|
357
|
+
tidy : bool, default False
|
|
358
|
+
Quando ``True`` e ``output='dataframe'``, retorna um DataFrame em
|
|
359
|
+
formato tidy com colunas ``Date``, ``series`` e ``value``. Quando
|
|
360
|
+
``False``, mantém o formato largo padrão. Não altera ``output='text'``.
|
|
361
|
+
timeout : float or httpx.Timeout, optional
|
|
362
|
+
Timeout por tentativa HTTP, em segundos ou como ``httpx.Timeout``.
|
|
363
|
+
Quando omitido, usa o timeout padrão do cliente compartilhado.
|
|
263
364
|
|
|
264
365
|
Returns
|
|
265
366
|
-------
|
|
@@ -279,21 +380,29 @@ def get(
|
|
|
279
380
|
Mapeamento de código → JSON bruto (quando ``output='text'`` e
|
|
280
381
|
múltiplos códigos).
|
|
281
382
|
"""
|
|
383
|
+
_validate_sgs_output(output)
|
|
384
|
+
code_list = list(_codes(codes))
|
|
385
|
+
|
|
282
386
|
if output == "text":
|
|
283
387
|
results: Dict[int, str] = {}
|
|
284
|
-
for code in
|
|
285
|
-
results[code.value] = get_json(
|
|
388
|
+
for code in code_list:
|
|
389
|
+
results[code.value] = get_json(
|
|
390
|
+
code.value, start, end, last, timeout=timeout
|
|
391
|
+
)
|
|
286
392
|
values = list(results.values())
|
|
287
393
|
if len(values) == 1:
|
|
288
394
|
return values[0]
|
|
289
395
|
return results
|
|
290
396
|
|
|
291
397
|
dfs = []
|
|
292
|
-
for code in
|
|
293
|
-
text = get_json(code.value, start, end, last)
|
|
398
|
+
for code in code_list:
|
|
399
|
+
text = get_json(code.value, start, end, last, timeout=timeout)
|
|
294
400
|
df = pd.read_json(StringIO(text))
|
|
295
401
|
df = _format_df(df, code, freq)
|
|
296
402
|
dfs.append(df)
|
|
403
|
+
|
|
404
|
+
if tidy:
|
|
405
|
+
return _tidy_df(pd.concat(dfs, axis=1))
|
|
297
406
|
if len(dfs) == 1:
|
|
298
407
|
return dfs[0]
|
|
299
408
|
else:
|
|
@@ -304,10 +413,12 @@ def get(
|
|
|
304
413
|
|
|
305
414
|
|
|
306
415
|
def get_json(
|
|
307
|
-
code: int,
|
|
416
|
+
code: int | str,
|
|
308
417
|
start: Optional[DateInput] = None,
|
|
309
418
|
end: Optional[DateInput] = None,
|
|
310
419
|
last: int = 0,
|
|
420
|
+
*,
|
|
421
|
+
timeout: RequestTimeout = None,
|
|
311
422
|
) -> str:
|
|
312
423
|
"""
|
|
313
424
|
Retorna um JSON com séries temporais obtidas do SGS.
|
|
@@ -317,16 +428,19 @@ def get_json(
|
|
|
317
428
|
|
|
318
429
|
code : int
|
|
319
430
|
Código da série temporal
|
|
320
|
-
start : str,
|
|
321
|
-
Data de início da série.
|
|
322
|
-
|
|
323
|
-
end :
|
|
324
|
-
Data final da série.
|
|
325
|
-
|
|
431
|
+
start : str, date, datetime or bcb.utils.Date
|
|
432
|
+
Data de início da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
433
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
434
|
+
end : str, date, datetime or bcb.utils.Date
|
|
435
|
+
Data final da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
436
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
326
437
|
last : int
|
|
327
438
|
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
328
439
|
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|
|
329
440
|
e ``end`` são ignorados.
|
|
441
|
+
timeout : float or httpx.Timeout, optional
|
|
442
|
+
Timeout por tentativa HTTP, em segundos ou como ``httpx.Timeout``.
|
|
443
|
+
Quando omitido, usa o timeout padrão do cliente compartilhado.
|
|
330
444
|
|
|
331
445
|
Returns
|
|
332
446
|
-------
|
|
@@ -334,37 +448,32 @@ def get_json(
|
|
|
334
448
|
JSON :
|
|
335
449
|
série temporal univariada em formato JSON.
|
|
336
450
|
"""
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
logger.debug(
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
451
|
+
code_obj = SGSCode.from_code(code)
|
|
452
|
+
_validate_sgs_code(code_obj)
|
|
453
|
+
url, payload = _get_url_and_payload(code_obj.value, start, end, last)
|
|
454
|
+
logger.debug(
|
|
455
|
+
f"Fetching SGS time series code={code_obj.value} from {url.split('/dados')[0]}"
|
|
456
|
+
)
|
|
457
|
+
try:
|
|
458
|
+
res = _get_sgs_response(url, payload, timeout)
|
|
459
|
+
except httpx.HTTPError as ex:
|
|
460
|
+
raise_for_request_error(
|
|
461
|
+
ex, context=f"SGS time series code={code_obj.value}", error_cls=SGSError
|
|
347
462
|
)
|
|
463
|
+
logger.debug(f"SGS response: status={res.status_code}, length={len(res.text)}")
|
|
348
464
|
|
|
349
465
|
if res.status_code != 200:
|
|
350
|
-
|
|
351
|
-
res_json = json.loads(res.text)
|
|
352
|
-
except json.JSONDecodeError:
|
|
353
|
-
res_json = {}
|
|
354
|
-
|
|
355
|
-
if "error" in res_json:
|
|
356
|
-
raise SGSError(f"BCB error: {res_json['error']}")
|
|
357
|
-
elif "erro" in res_json:
|
|
358
|
-
raise SGSError(f"BCB error: {res_json['erro']['detail']}")
|
|
359
|
-
raise SGSError(f"Download error: code = {code}")
|
|
466
|
+
_raise_sgs_response_error(res, code_obj.value)
|
|
360
467
|
return str(res.text)
|
|
361
468
|
|
|
362
469
|
|
|
363
470
|
async def async_get_json(
|
|
364
|
-
code: int,
|
|
471
|
+
code: int | str,
|
|
365
472
|
start: Optional[DateInput] = None,
|
|
366
473
|
end: Optional[DateInput] = None,
|
|
367
474
|
last: int = 0,
|
|
475
|
+
*,
|
|
476
|
+
timeout: RequestTimeout = None,
|
|
368
477
|
) -> str:
|
|
369
478
|
"""
|
|
370
479
|
Retorna um JSON com séries temporais obtidas do SGS (async version).
|
|
@@ -373,12 +482,17 @@ async def async_get_json(
|
|
|
373
482
|
----------
|
|
374
483
|
code : int
|
|
375
484
|
Código da série temporal
|
|
376
|
-
start : str,
|
|
377
|
-
Data de início da série
|
|
378
|
-
|
|
379
|
-
|
|
485
|
+
start : str, date, datetime or bcb.utils.Date, optional
|
|
486
|
+
Data de início da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
487
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
488
|
+
end : str, date, datetime or bcb.utils.Date, optional
|
|
489
|
+
Data final da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
490
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
380
491
|
last : int
|
|
381
492
|
Retorna os últimos ``last`` elementos disponíveis
|
|
493
|
+
timeout : float or httpx.Timeout, optional
|
|
494
|
+
Timeout por tentativa HTTP, em segundos ou como ``httpx.Timeout``.
|
|
495
|
+
Quando omitido, usa o timeout padrão do cliente compartilhado.
|
|
382
496
|
|
|
383
497
|
Returns
|
|
384
498
|
-------
|
|
@@ -392,33 +506,25 @@ async def async_get_json(
|
|
|
392
506
|
SGSError
|
|
393
507
|
Se a API retorna um erro
|
|
394
508
|
"""
|
|
395
|
-
|
|
509
|
+
code_obj = SGSCode.from_code(code)
|
|
510
|
+
_validate_sgs_code(code_obj)
|
|
511
|
+
url, payload = _get_url_and_payload(code_obj.value, start, end, last)
|
|
396
512
|
logger.debug(
|
|
397
|
-
f"Fetching SGS time series (async) code={
|
|
513
|
+
f"Fetching SGS time series (async) code={code_obj.value} "
|
|
514
|
+
f"from {url.split('/dados')[0]}"
|
|
398
515
|
)
|
|
399
|
-
|
|
516
|
+
try:
|
|
517
|
+
res = await _async_get_sgs_response(url, payload, timeout)
|
|
518
|
+
except httpx.HTTPError as ex:
|
|
519
|
+
raise_for_request_error(
|
|
520
|
+
ex, context=f"SGS time series code={code_obj.value}", error_cls=SGSError
|
|
521
|
+
)
|
|
400
522
|
logger.debug(
|
|
401
523
|
f"SGS (async) response: status={res.status_code}, length={len(res.text)}"
|
|
402
524
|
)
|
|
403
525
|
|
|
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
526
|
if res.status_code != 200:
|
|
412
|
-
|
|
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}")
|
|
527
|
+
_raise_sgs_response_error(res, code_obj.value)
|
|
422
528
|
return str(res.text)
|
|
423
529
|
|
|
424
530
|
|
|
@@ -429,7 +535,10 @@ async def async_get(
|
|
|
429
535
|
last: int = 0,
|
|
430
536
|
multi: bool = True,
|
|
431
537
|
freq: Optional[str] = None,
|
|
432
|
-
output:
|
|
538
|
+
output: Literal["dataframe", "text"] = "dataframe",
|
|
539
|
+
tidy: bool = False,
|
|
540
|
+
*,
|
|
541
|
+
timeout: RequestTimeout = None,
|
|
433
542
|
) -> Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]:
|
|
434
543
|
"""
|
|
435
544
|
Retorna um DataFrame pandas com séries temporais obtidas do SGS (async version).
|
|
@@ -441,10 +550,12 @@ async def async_get(
|
|
|
441
550
|
----------
|
|
442
551
|
codes : {int, List[int], List[str], Dict[str:int]}
|
|
443
552
|
Código(s) da série temporal
|
|
444
|
-
start : str,
|
|
445
|
-
Data de início da série
|
|
446
|
-
|
|
447
|
-
|
|
553
|
+
start : str, date, datetime or bcb.utils.Date, optional
|
|
554
|
+
Data de início da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
555
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
556
|
+
end : str, date, datetime or bcb.utils.Date, optional
|
|
557
|
+
Data final da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
558
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
448
559
|
last : int
|
|
449
560
|
Retorna os últimos ``last`` elementos disponíveis
|
|
450
561
|
multi : bool
|
|
@@ -453,29 +564,42 @@ async def async_get(
|
|
|
453
564
|
Frequência a ser utilizada na série temporal
|
|
454
565
|
output : str
|
|
455
566
|
Formato de saída: ``'dataframe'`` ou ``'text'``
|
|
567
|
+
tidy : bool, default False
|
|
568
|
+
Quando ``True`` e ``output='dataframe'``, retorna um DataFrame em
|
|
569
|
+
formato tidy com colunas ``Date``, ``series`` e ``value``. Quando
|
|
570
|
+
``False``, mantém o formato largo padrão. Não altera ``output='text'``.
|
|
571
|
+
timeout : float or httpx.Timeout, optional
|
|
572
|
+
Timeout por tentativa HTTP, em segundos ou como ``httpx.Timeout``.
|
|
573
|
+
Quando omitido, usa o timeout padrão do cliente compartilhado.
|
|
456
574
|
|
|
457
575
|
Returns
|
|
458
576
|
-------
|
|
459
577
|
Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]
|
|
460
578
|
Série(s) temporal(is) conforme especificado
|
|
461
579
|
"""
|
|
580
|
+
_validate_sgs_output(output)
|
|
462
581
|
code_list = list(_codes(codes))
|
|
463
582
|
|
|
464
583
|
# Concurrent HTTP requests via asyncio.gather()
|
|
465
584
|
texts = await asyncio.gather(
|
|
466
|
-
*[async_get_json(c.value, start, end, last) for c in code_list]
|
|
585
|
+
*[async_get_json(c.value, start, end, last, timeout=timeout) for c in code_list]
|
|
467
586
|
)
|
|
468
587
|
|
|
469
588
|
if output == "text":
|
|
470
|
-
results: Dict[int, str] = {
|
|
589
|
+
results: Dict[int, str] = {
|
|
590
|
+
c.value: t for c, t in zip(code_list, texts, strict=True)
|
|
591
|
+
}
|
|
471
592
|
values = list(results.values())
|
|
472
593
|
if len(values) == 1:
|
|
473
594
|
return values[0]
|
|
474
595
|
return results
|
|
475
596
|
|
|
476
597
|
dfs = [
|
|
477
|
-
_format_df(pd.read_json(StringIO(t)), c, freq)
|
|
598
|
+
_format_df(pd.read_json(StringIO(t)), c, freq)
|
|
599
|
+
for c, t in zip(code_list, texts, strict=True)
|
|
478
600
|
]
|
|
601
|
+
if tidy:
|
|
602
|
+
return _tidy_df(pd.concat(dfs, axis=1))
|
|
479
603
|
if len(dfs) == 1:
|
|
480
604
|
return dfs[0]
|
|
481
605
|
else:
|
bcb/sgs/regional_economy.py
CHANGED
|
@@ -126,46 +126,69 @@ NON_PERFORMING_LOANS_BY_STATE_TOTAL = {
|
|
|
126
126
|
}
|
|
127
127
|
|
|
128
128
|
|
|
129
|
+
def _normalize_mode(mode: str) -> str:
|
|
130
|
+
if not isinstance(mode, str):
|
|
131
|
+
raise ValueError("mode must be one of: PF, PJ, total")
|
|
132
|
+
normalized = mode.upper()
|
|
133
|
+
if normalized == "ALL":
|
|
134
|
+
normalized = "TOTAL"
|
|
135
|
+
if normalized not in ("PF", "PJ", "TOTAL"):
|
|
136
|
+
raise ValueError("Unknown mode value, use: PF, PJ, total")
|
|
137
|
+
return normalized
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _normalize_locations(states_or_region: Union[str, List[str]]) -> List[str]:
|
|
141
|
+
locations = (
|
|
142
|
+
[states_or_region] if isinstance(states_or_region, str) else states_or_region
|
|
143
|
+
)
|
|
144
|
+
if not isinstance(locations, list) or not locations:
|
|
145
|
+
raise ValueError("At least one state or region must be provided")
|
|
146
|
+
|
|
147
|
+
normalized = []
|
|
148
|
+
for location in locations:
|
|
149
|
+
if not isinstance(location, str) or not location.strip():
|
|
150
|
+
raise ValueError(f"Not a valid state or region: {location!r}")
|
|
151
|
+
normalized.append(location.upper())
|
|
152
|
+
return normalized
|
|
153
|
+
|
|
154
|
+
|
|
129
155
|
def get_non_performing_loans_codes(
|
|
130
156
|
states_or_region: Union[str, List[str]], mode: str = "total"
|
|
131
157
|
) -> Dict[str, str]:
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
location in
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
for location in states_or_region:
|
|
167
|
-
codes[location] = non_performing_loans_by_location[location]
|
|
168
|
-
return codes
|
|
158
|
+
locations = _normalize_locations(states_or_region)
|
|
159
|
+
normalized_mode = _normalize_mode(mode)
|
|
160
|
+
|
|
161
|
+
states = set(NON_PERFORMING_LOANS_BY_STATE_TOTAL)
|
|
162
|
+
regions = set(NON_PERFORMING_LOANS_BY_REGION_TOTAL)
|
|
163
|
+
invalid_locations = [
|
|
164
|
+
location
|
|
165
|
+
for location in locations
|
|
166
|
+
if location not in states and location not in regions
|
|
167
|
+
]
|
|
168
|
+
if invalid_locations:
|
|
169
|
+
raise ValueError(f"Not a valid state or region: {invalid_locations}")
|
|
170
|
+
|
|
171
|
+
# Some codes are ambiguous: "SE" is both Sergipe and Sudeste.
|
|
172
|
+
# Preserve the historical state-first behavior for all-state requests.
|
|
173
|
+
if all(location in states for location in locations):
|
|
174
|
+
mappings = {
|
|
175
|
+
"PF": NON_PERFORMING_LOANS_BY_STATE_PF,
|
|
176
|
+
"PJ": NON_PERFORMING_LOANS_BY_STATE_PJ,
|
|
177
|
+
"TOTAL": NON_PERFORMING_LOANS_BY_STATE_TOTAL,
|
|
178
|
+
}
|
|
179
|
+
elif all(location in regions for location in locations):
|
|
180
|
+
mappings = {
|
|
181
|
+
"PF": NON_PERFORMING_LOANS_BY_REGION_PF,
|
|
182
|
+
"PJ": NON_PERFORMING_LOANS_BY_REGION_PJ,
|
|
183
|
+
"TOTAL": NON_PERFORMING_LOANS_BY_REGION_TOTAL,
|
|
184
|
+
}
|
|
185
|
+
else:
|
|
186
|
+
raise ValueError("Cannot mix states and regions in the same request")
|
|
187
|
+
|
|
188
|
+
non_performing_loans_by_location = mappings[normalized_mode]
|
|
189
|
+
return {
|
|
190
|
+
location: non_performing_loans_by_location[location] for location in locations
|
|
191
|
+
}
|
|
169
192
|
|
|
170
193
|
|
|
171
194
|
def get_non_performing_loans(
|
|
@@ -194,13 +217,14 @@ def get_non_performing_loans(
|
|
|
194
217
|
|
|
195
218
|
states_or_region (List[str]): Uma lista com estado ou região.
|
|
196
219
|
mode (str): O tipo de inadimplência. Pode ser "PF" (pessoas físicas),
|
|
197
|
-
"PJ" (pessoas jurídicas)
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
220
|
+
"PJ" (pessoas jurídicas), "total" ou "all"
|
|
221
|
+
(inadimplência total).
|
|
222
|
+
start : str, date, datetime or bcb.utils.Date
|
|
223
|
+
Data de início da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
224
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
225
|
+
end : str, date, datetime or bcb.utils.Date
|
|
226
|
+
Data final da série. Strings usam o formato ``YYYY-MM-DD``;
|
|
227
|
+
``'today'`` e ``'now'`` também são aceitos.
|
|
204
228
|
last : int
|
|
205
229
|
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
206
230
|
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|