python-bcb 0.3.4__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/__init__.py +4 -2
- bcb/currency.py +976 -114
- bcb/exceptions.py +22 -1
- bcb/http.py +184 -0
- bcb/odata/__init__.py +3 -1
- bcb/odata/api.py +284 -33
- bcb/odata/framework.py +359 -71
- bcb/sgs/__init__.py +448 -42
- bcb/sgs/regional_economy.py +70 -44
- bcb/utils.py +2 -0
- python_bcb-0.4.0.dist-info/METADATA +225 -0
- python_bcb-0.4.0.dist-info/RECORD +14 -0
- {python_bcb-0.3.4.dist-info → python_bcb-0.4.0.dist-info}/WHEEL +1 -1
- python_bcb-0.3.4.dist-info/METADATA +0 -81
- python_bcb-0.3.4.dist-info/RECORD +0 -13
- {python_bcb-0.3.4.dist-info → python_bcb-0.4.0.dist-info}/licenses/LICENSE +0 -0
bcb/sgs/__init__.py
CHANGED
|
@@ -1,13 +1,40 @@
|
|
|
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
|
|
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 httpx
|
|
6
22
|
import pandas as pd
|
|
7
23
|
|
|
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
|
+
)
|
|
8
33
|
from bcb.exceptions import SGSError
|
|
9
34
|
from bcb.utils import Date, DateInput
|
|
10
35
|
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
11
38
|
"""
|
|
12
39
|
Sistema Gerenciador de Séries Temporais (SGS)
|
|
13
40
|
|
|
@@ -18,18 +45,58 @@ interface json do serviço BCData/SGS -
|
|
|
18
45
|
"""
|
|
19
46
|
|
|
20
47
|
|
|
48
|
+
@dataclass(frozen=True)
|
|
21
49
|
class SGSCode:
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
50
|
+
"""SGS time series code with optional human-readable name.
|
|
51
|
+
|
|
52
|
+
Attributes
|
|
53
|
+
----------
|
|
54
|
+
value : int
|
|
55
|
+
Numeric SGS code
|
|
56
|
+
name : str
|
|
57
|
+
Human-readable name or string representation of code
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
value: int
|
|
61
|
+
name: str
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_code(cls, code: int | str) -> "SGSCode":
|
|
65
|
+
"""Create SGSCode from numeric or string code.
|
|
66
|
+
|
|
67
|
+
Parameters
|
|
68
|
+
----------
|
|
69
|
+
code : int | str
|
|
70
|
+
SGS code
|
|
71
|
+
|
|
72
|
+
Returns
|
|
73
|
+
-------
|
|
74
|
+
SGSCode
|
|
75
|
+
New instance with name = str(code)
|
|
76
|
+
"""
|
|
77
|
+
code_int = int(code)
|
|
78
|
+
return cls(value=code_int, name=str(code_int))
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def from_named(cls, code: int | str, name: str) -> "SGSCode":
|
|
82
|
+
"""Create SGSCode with explicit name.
|
|
83
|
+
|
|
84
|
+
Parameters
|
|
85
|
+
----------
|
|
86
|
+
code : int | str
|
|
87
|
+
SGS code
|
|
88
|
+
name : str
|
|
89
|
+
Human-readable name
|
|
90
|
+
|
|
91
|
+
Returns
|
|
92
|
+
-------
|
|
93
|
+
SGSCode
|
|
94
|
+
New instance with value and name
|
|
95
|
+
"""
|
|
96
|
+
return cls(value=int(code), name=name)
|
|
30
97
|
|
|
31
98
|
def __repr__(self) -> str:
|
|
32
|
-
return f"{self.value} - {self.name}"
|
|
99
|
+
return f"{self.value} - {self.name}"
|
|
33
100
|
|
|
34
101
|
|
|
35
102
|
SGSCodeInput: TypeAlias = Union[
|
|
@@ -41,20 +108,82 @@ SGSCodeInput: TypeAlias = Union[
|
|
|
41
108
|
]
|
|
42
109
|
|
|
43
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
|
+
|
|
121
|
+
def _validate_sgs_code(code: SGSCode) -> None:
|
|
122
|
+
"""Validate SGSCode value.
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
code : SGSCode
|
|
127
|
+
Code to validate
|
|
128
|
+
|
|
129
|
+
Raises
|
|
130
|
+
------
|
|
131
|
+
ValueError
|
|
132
|
+
If code value is not positive integer
|
|
133
|
+
"""
|
|
134
|
+
if code.value <= 0:
|
|
135
|
+
raise ValueError(f"SGS code must be positive integer, got {code.value}")
|
|
136
|
+
|
|
137
|
+
|
|
44
138
|
def _codes(codes: SGSCodeInput) -> Generator[SGSCode, None, None]:
|
|
139
|
+
"""Normalize various SGSCodeInput formats to SGSCode instances.
|
|
140
|
+
|
|
141
|
+
Parameters
|
|
142
|
+
----------
|
|
143
|
+
codes : SGSCodeInput
|
|
144
|
+
Input in various formats: int, str, tuple, list, or mapping
|
|
145
|
+
|
|
146
|
+
Yields
|
|
147
|
+
------
|
|
148
|
+
SGSCode
|
|
149
|
+
Validated SGSCode instances
|
|
150
|
+
|
|
151
|
+
Raises
|
|
152
|
+
------
|
|
153
|
+
ValueError
|
|
154
|
+
If any code is a non-positive integer
|
|
155
|
+
"""
|
|
45
156
|
if isinstance(codes, int) or isinstance(codes, str):
|
|
46
|
-
|
|
157
|
+
code_obj = SGSCode.from_code(codes)
|
|
158
|
+
_validate_sgs_code(code_obj)
|
|
159
|
+
yield code_obj
|
|
47
160
|
elif isinstance(codes, tuple):
|
|
48
|
-
|
|
161
|
+
if len(codes) != 2:
|
|
162
|
+
raise ValueError("Named SGS code tuples must contain (name, code)")
|
|
163
|
+
code_obj = SGSCode.from_named(codes[1], codes[0])
|
|
164
|
+
_validate_sgs_code(code_obj)
|
|
165
|
+
yield code_obj
|
|
49
166
|
elif isinstance(codes, list):
|
|
167
|
+
if not codes:
|
|
168
|
+
raise ValueError("At least one SGS code must be provided")
|
|
50
169
|
for cd in codes:
|
|
51
170
|
if isinstance(cd, tuple):
|
|
52
|
-
|
|
171
|
+
if len(cd) != 2:
|
|
172
|
+
raise ValueError("Named SGS code tuples must contain (name, code)")
|
|
173
|
+
code_obj = SGSCode.from_named(cd[1], cd[0])
|
|
53
174
|
else:
|
|
54
|
-
|
|
175
|
+
code_obj = SGSCode.from_code(cd)
|
|
176
|
+
_validate_sgs_code(code_obj)
|
|
177
|
+
yield code_obj
|
|
55
178
|
elif isinstance(codes, Mapping):
|
|
179
|
+
if not codes:
|
|
180
|
+
raise ValueError("At least one SGS code must be provided")
|
|
56
181
|
for name, code in codes.items():
|
|
57
|
-
|
|
182
|
+
code_obj = SGSCode.from_named(code, name)
|
|
183
|
+
_validate_sgs_code(code_obj)
|
|
184
|
+
yield code_obj
|
|
185
|
+
else:
|
|
186
|
+
raise ValueError(f"Unsupported SGS code input: {codes!r}")
|
|
58
187
|
|
|
59
188
|
|
|
60
189
|
def _get_url_and_payload(
|
|
@@ -63,6 +192,7 @@ def _get_url_and_payload(
|
|
|
63
192
|
end_date: Optional[DateInput],
|
|
64
193
|
last: int,
|
|
65
194
|
) -> Tuple[str, Dict[str, str]]:
|
|
195
|
+
_validate_last(last)
|
|
66
196
|
payload: Dict[str, str] = {"formato": "json"}
|
|
67
197
|
if last == 0:
|
|
68
198
|
if start_date is not None or end_date is not None:
|
|
@@ -78,6 +208,44 @@ def _get_url_and_payload(
|
|
|
78
208
|
return url, payload
|
|
79
209
|
|
|
80
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
|
+
|
|
81
249
|
def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataFrame:
|
|
82
250
|
cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
|
|
83
251
|
df = df.rename(columns=cns)
|
|
@@ -91,6 +259,53 @@ def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataF
|
|
|
91
259
|
return df
|
|
92
260
|
|
|
93
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
|
+
|
|
279
|
+
@overload
|
|
280
|
+
def get(
|
|
281
|
+
codes: SGSCodeInput,
|
|
282
|
+
start: Optional[DateInput] = ...,
|
|
283
|
+
end: Optional[DateInput] = ...,
|
|
284
|
+
last: int = ...,
|
|
285
|
+
multi: bool = ...,
|
|
286
|
+
freq: Optional[str] = ...,
|
|
287
|
+
output: Literal["dataframe"] = ...,
|
|
288
|
+
tidy: bool = ...,
|
|
289
|
+
*,
|
|
290
|
+
timeout: RequestTimeout = ...,
|
|
291
|
+
) -> Union[pd.DataFrame, List[pd.DataFrame]]: ...
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
@overload
|
|
295
|
+
def get(
|
|
296
|
+
codes: SGSCodeInput,
|
|
297
|
+
start: Optional[DateInput] = ...,
|
|
298
|
+
end: Optional[DateInput] = ...,
|
|
299
|
+
last: int = ...,
|
|
300
|
+
multi: bool = ...,
|
|
301
|
+
freq: Optional[str] = ...,
|
|
302
|
+
output: Literal["text"] = ...,
|
|
303
|
+
tidy: bool = ...,
|
|
304
|
+
*,
|
|
305
|
+
timeout: RequestTimeout = ...,
|
|
306
|
+
) -> Union[str, Dict[int, str]]: ...
|
|
307
|
+
|
|
308
|
+
|
|
94
309
|
def get(
|
|
95
310
|
codes: SGSCodeInput,
|
|
96
311
|
start: Optional[DateInput] = None,
|
|
@@ -98,7 +313,11 @@ def get(
|
|
|
98
313
|
last: int = 0,
|
|
99
314
|
multi: bool = True,
|
|
100
315
|
freq: Optional[str] = None,
|
|
101
|
-
|
|
316
|
+
output: Literal["dataframe", "text"] = "dataframe",
|
|
317
|
+
tidy: bool = False,
|
|
318
|
+
*,
|
|
319
|
+
timeout: RequestTimeout = None,
|
|
320
|
+
) -> Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]:
|
|
102
321
|
"""
|
|
103
322
|
Retorna um DataFrame pandas com séries temporais obtidas do SGS.
|
|
104
323
|
|
|
@@ -115,12 +334,12 @@ def get(
|
|
|
115
334
|
|
|
116
335
|
Com códigos numéricos é interessante utilizar os nomes com os códigos
|
|
117
336
|
para definir os nomes nas colunas das séries temporais.
|
|
118
|
-
start : str,
|
|
119
|
-
Data de início da série.
|
|
120
|
-
|
|
121
|
-
end :
|
|
122
|
-
Data final da série.
|
|
123
|
-
|
|
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.
|
|
124
343
|
last : int
|
|
125
344
|
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
126
345
|
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|
|
@@ -130,6 +349,18 @@ def get(
|
|
|
130
349
|
série multivariada ou uma lista com séries univariadas.
|
|
131
350
|
freq : str
|
|
132
351
|
Define a frequência a ser utilizada na série temporal
|
|
352
|
+
output : str
|
|
353
|
+
Define o formato de saída. Use ``'dataframe'`` (padrão) para retornar
|
|
354
|
+
um DataFrame pandas, ou ``'text'`` para retornar o JSON bruto da API
|
|
355
|
+
do BCB. Para um único código retorna uma string; para múltiplos
|
|
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.
|
|
133
364
|
|
|
134
365
|
Returns
|
|
135
366
|
-------
|
|
@@ -141,13 +372,37 @@ def get(
|
|
|
141
372
|
``list`` :
|
|
142
373
|
lista com séries temporais univariadas,
|
|
143
374
|
quando solicitado mais de uma série (parâmetro ``multi=False``).
|
|
375
|
+
|
|
376
|
+
``str`` :
|
|
377
|
+
JSON bruto da API (quando ``output='text'`` e um único código).
|
|
378
|
+
|
|
379
|
+
``dict`` :
|
|
380
|
+
Mapeamento de código → JSON bruto (quando ``output='text'`` e
|
|
381
|
+
múltiplos códigos).
|
|
144
382
|
"""
|
|
383
|
+
_validate_sgs_output(output)
|
|
384
|
+
code_list = list(_codes(codes))
|
|
385
|
+
|
|
386
|
+
if output == "text":
|
|
387
|
+
results: Dict[int, str] = {}
|
|
388
|
+
for code in code_list:
|
|
389
|
+
results[code.value] = get_json(
|
|
390
|
+
code.value, start, end, last, timeout=timeout
|
|
391
|
+
)
|
|
392
|
+
values = list(results.values())
|
|
393
|
+
if len(values) == 1:
|
|
394
|
+
return values[0]
|
|
395
|
+
return results
|
|
396
|
+
|
|
145
397
|
dfs = []
|
|
146
|
-
for code in
|
|
147
|
-
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)
|
|
148
400
|
df = pd.read_json(StringIO(text))
|
|
149
401
|
df = _format_df(df, code, freq)
|
|
150
402
|
dfs.append(df)
|
|
403
|
+
|
|
404
|
+
if tidy:
|
|
405
|
+
return _tidy_df(pd.concat(dfs, axis=1))
|
|
151
406
|
if len(dfs) == 1:
|
|
152
407
|
return dfs[0]
|
|
153
408
|
else:
|
|
@@ -158,10 +413,12 @@ def get(
|
|
|
158
413
|
|
|
159
414
|
|
|
160
415
|
def get_json(
|
|
161
|
-
code: int,
|
|
416
|
+
code: int | str,
|
|
162
417
|
start: Optional[DateInput] = None,
|
|
163
418
|
end: Optional[DateInput] = None,
|
|
164
419
|
last: int = 0,
|
|
420
|
+
*,
|
|
421
|
+
timeout: RequestTimeout = None,
|
|
165
422
|
) -> str:
|
|
166
423
|
"""
|
|
167
424
|
Retorna um JSON com séries temporais obtidas do SGS.
|
|
@@ -171,16 +428,19 @@ def get_json(
|
|
|
171
428
|
|
|
172
429
|
code : int
|
|
173
430
|
Código da série temporal
|
|
174
|
-
start : str,
|
|
175
|
-
Data de início da série.
|
|
176
|
-
|
|
177
|
-
end :
|
|
178
|
-
Data final da série.
|
|
179
|
-
|
|
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.
|
|
180
437
|
last : int
|
|
181
438
|
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
182
439
|
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|
|
183
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.
|
|
184
444
|
|
|
185
445
|
Returns
|
|
186
446
|
-------
|
|
@@ -188,16 +448,162 @@ def get_json(
|
|
|
188
448
|
JSON :
|
|
189
449
|
série temporal univariada em formato JSON.
|
|
190
450
|
"""
|
|
191
|
-
|
|
192
|
-
|
|
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
|
|
462
|
+
)
|
|
463
|
+
logger.debug(f"SGS response: status={res.status_code}, length={len(res.text)}")
|
|
464
|
+
|
|
465
|
+
if res.status_code != 200:
|
|
466
|
+
_raise_sgs_response_error(res, code_obj.value)
|
|
467
|
+
return str(res.text)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
async def async_get_json(
|
|
471
|
+
code: int | str,
|
|
472
|
+
start: Optional[DateInput] = None,
|
|
473
|
+
end: Optional[DateInput] = None,
|
|
474
|
+
last: int = 0,
|
|
475
|
+
*,
|
|
476
|
+
timeout: RequestTimeout = None,
|
|
477
|
+
) -> str:
|
|
478
|
+
"""
|
|
479
|
+
Retorna um JSON com séries temporais obtidas do SGS (async version).
|
|
480
|
+
|
|
481
|
+
Parameters
|
|
482
|
+
----------
|
|
483
|
+
code : int
|
|
484
|
+
Código da série temporal
|
|
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.
|
|
491
|
+
last : int
|
|
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.
|
|
496
|
+
|
|
497
|
+
Returns
|
|
498
|
+
-------
|
|
499
|
+
str
|
|
500
|
+
JSON bruto da API do BCB
|
|
501
|
+
|
|
502
|
+
Raises
|
|
503
|
+
------
|
|
504
|
+
BCBRateLimitError
|
|
505
|
+
Se API rate limit é excedido (429)
|
|
506
|
+
SGSError
|
|
507
|
+
Se a API retorna um erro
|
|
508
|
+
"""
|
|
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)
|
|
512
|
+
logger.debug(
|
|
513
|
+
f"Fetching SGS time series (async) code={code_obj.value} "
|
|
514
|
+
f"from {url.split('/dados')[0]}"
|
|
515
|
+
)
|
|
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
|
+
)
|
|
522
|
+
logger.debug(
|
|
523
|
+
f"SGS (async) response: status={res.status_code}, length={len(res.text)}"
|
|
524
|
+
)
|
|
525
|
+
|
|
193
526
|
if res.status_code != 200:
|
|
194
|
-
|
|
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}")
|
|
527
|
+
_raise_sgs_response_error(res, code_obj.value)
|
|
203
528
|
return str(res.text)
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
async def async_get(
|
|
532
|
+
codes: SGSCodeInput,
|
|
533
|
+
start: Optional[DateInput] = None,
|
|
534
|
+
end: Optional[DateInput] = None,
|
|
535
|
+
last: int = 0,
|
|
536
|
+
multi: bool = True,
|
|
537
|
+
freq: Optional[str] = None,
|
|
538
|
+
output: Literal["dataframe", "text"] = "dataframe",
|
|
539
|
+
tidy: bool = False,
|
|
540
|
+
*,
|
|
541
|
+
timeout: RequestTimeout = None,
|
|
542
|
+
) -> Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]:
|
|
543
|
+
"""
|
|
544
|
+
Retorna um DataFrame pandas com séries temporais obtidas do SGS (async version).
|
|
545
|
+
|
|
546
|
+
Same signature as :func:`get`, but uses async HTTP requests and
|
|
547
|
+
:func:`asyncio.gather` to fetch multiple codes concurrently.
|
|
548
|
+
|
|
549
|
+
Parameters
|
|
550
|
+
----------
|
|
551
|
+
codes : {int, List[int], List[str], Dict[str:int]}
|
|
552
|
+
Código(s) da série temporal
|
|
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.
|
|
559
|
+
last : int
|
|
560
|
+
Retorna os últimos ``last`` elementos disponíveis
|
|
561
|
+
multi : bool
|
|
562
|
+
Define se retorna série multivariada ou lista de séries univariadas
|
|
563
|
+
freq : str, optional
|
|
564
|
+
Frequência a ser utilizada na série temporal
|
|
565
|
+
output : str
|
|
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.
|
|
574
|
+
|
|
575
|
+
Returns
|
|
576
|
+
-------
|
|
577
|
+
Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]
|
|
578
|
+
Série(s) temporal(is) conforme especificado
|
|
579
|
+
"""
|
|
580
|
+
_validate_sgs_output(output)
|
|
581
|
+
code_list = list(_codes(codes))
|
|
582
|
+
|
|
583
|
+
# Concurrent HTTP requests via asyncio.gather()
|
|
584
|
+
texts = await asyncio.gather(
|
|
585
|
+
*[async_get_json(c.value, start, end, last, timeout=timeout) for c in code_list]
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
if output == "text":
|
|
589
|
+
results: Dict[int, str] = {
|
|
590
|
+
c.value: t for c, t in zip(code_list, texts, strict=True)
|
|
591
|
+
}
|
|
592
|
+
values = list(results.values())
|
|
593
|
+
if len(values) == 1:
|
|
594
|
+
return values[0]
|
|
595
|
+
return results
|
|
596
|
+
|
|
597
|
+
dfs = [
|
|
598
|
+
_format_df(pd.read_json(StringIO(t)), c, freq)
|
|
599
|
+
for c, t in zip(code_list, texts, strict=True)
|
|
600
|
+
]
|
|
601
|
+
if tidy:
|
|
602
|
+
return _tidy_df(pd.concat(dfs, axis=1))
|
|
603
|
+
if len(dfs) == 1:
|
|
604
|
+
return dfs[0]
|
|
605
|
+
else:
|
|
606
|
+
if multi:
|
|
607
|
+
return pd.concat(dfs, axis=1)
|
|
608
|
+
else:
|
|
609
|
+
return dfs
|