python-bcb 0.3.4__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/__init__.py +4 -2
- bcb/currency.py +787 -83
- bcb/exceptions.py +22 -1
- bcb/http.py +98 -0
- bcb/odata/__init__.py +3 -1
- bcb/odata/api.py +184 -18
- bcb/odata/framework.py +66 -14
- bcb/sgs/__init__.py +302 -20
- bcb/sgs/regional_economy.py +2 -0
- bcb/utils.py +2 -0
- python_bcb-0.3.6.dist-info/METADATA +191 -0
- python_bcb-0.3.6.dist-info/RECORD +14 -0
- {python_bcb-0.3.4.dist-info → python_bcb-0.3.6.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.3.6.dist-info}/licenses/LICENSE +0 -0
bcb/sgs/__init__.py
CHANGED
|
@@ -1,13 +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
|
|
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
|
-
import httpx
|
|
6
21
|
import pandas as pd
|
|
7
22
|
|
|
8
|
-
from bcb.
|
|
23
|
+
from bcb.http import _CLIENT, _ASYNC_CLIENT
|
|
24
|
+
from bcb.exceptions import BCBRateLimitError, SGSError
|
|
9
25
|
from bcb.utils import Date, DateInput
|
|
10
26
|
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
11
29
|
"""
|
|
12
30
|
Sistema Gerenciador de Séries Temporais (SGS)
|
|
13
31
|
|
|
@@ -18,18 +36,58 @@ interface json do serviço BCData/SGS -
|
|
|
18
36
|
"""
|
|
19
37
|
|
|
20
38
|
|
|
39
|
+
@dataclass(frozen=True)
|
|
21
40
|
class SGSCode:
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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)
|
|
30
88
|
|
|
31
89
|
def __repr__(self) -> str:
|
|
32
|
-
return f"{self.value} - {self.name}"
|
|
90
|
+
return f"{self.value} - {self.name}"
|
|
33
91
|
|
|
34
92
|
|
|
35
93
|
SGSCodeInput: TypeAlias = Union[
|
|
@@ -41,20 +99,62 @@ SGSCodeInput: TypeAlias = Union[
|
|
|
41
99
|
]
|
|
42
100
|
|
|
43
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
|
+
|
|
44
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
|
+
"""
|
|
45
137
|
if isinstance(codes, int) or isinstance(codes, str):
|
|
46
|
-
|
|
138
|
+
code_obj = SGSCode.from_code(codes)
|
|
139
|
+
_validate_sgs_code(code_obj)
|
|
140
|
+
yield code_obj
|
|
47
141
|
elif isinstance(codes, tuple):
|
|
48
|
-
|
|
142
|
+
code_obj = SGSCode.from_named(codes[1], codes[0])
|
|
143
|
+
_validate_sgs_code(code_obj)
|
|
144
|
+
yield code_obj
|
|
49
145
|
elif isinstance(codes, list):
|
|
50
146
|
for cd in codes:
|
|
51
147
|
if isinstance(cd, tuple):
|
|
52
|
-
|
|
148
|
+
code_obj = SGSCode.from_named(cd[1], cd[0])
|
|
53
149
|
else:
|
|
54
|
-
|
|
150
|
+
code_obj = SGSCode.from_code(cd)
|
|
151
|
+
_validate_sgs_code(code_obj)
|
|
152
|
+
yield code_obj
|
|
55
153
|
elif isinstance(codes, Mapping):
|
|
56
154
|
for name, code in codes.items():
|
|
57
|
-
|
|
155
|
+
code_obj = SGSCode.from_named(code, name)
|
|
156
|
+
_validate_sgs_code(code_obj)
|
|
157
|
+
yield code_obj
|
|
58
158
|
|
|
59
159
|
|
|
60
160
|
def _get_url_and_payload(
|
|
@@ -91,6 +191,30 @@ def _format_df(df: pd.DataFrame, code: SGSCode, freq: Optional[str]) -> pd.DataF
|
|
|
91
191
|
return df
|
|
92
192
|
|
|
93
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
|
+
|
|
94
218
|
def get(
|
|
95
219
|
codes: SGSCodeInput,
|
|
96
220
|
start: Optional[DateInput] = None,
|
|
@@ -98,7 +222,8 @@ def get(
|
|
|
98
222
|
last: int = 0,
|
|
99
223
|
multi: bool = True,
|
|
100
224
|
freq: Optional[str] = None,
|
|
101
|
-
|
|
225
|
+
output: str = "dataframe",
|
|
226
|
+
) -> Union[pd.DataFrame, List[pd.DataFrame], str, Dict[int, str]]:
|
|
102
227
|
"""
|
|
103
228
|
Retorna um DataFrame pandas com séries temporais obtidas do SGS.
|
|
104
229
|
|
|
@@ -130,6 +255,11 @@ def get(
|
|
|
130
255
|
série multivariada ou uma lista com séries univariadas.
|
|
131
256
|
freq : str
|
|
132
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.
|
|
133
263
|
|
|
134
264
|
Returns
|
|
135
265
|
-------
|
|
@@ -141,7 +271,23 @@ def get(
|
|
|
141
271
|
``list`` :
|
|
142
272
|
lista com séries temporais univariadas,
|
|
143
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).
|
|
144
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
|
+
|
|
145
291
|
dfs = []
|
|
146
292
|
for code in _codes(codes):
|
|
147
293
|
text = get_json(code.value, start, end, last)
|
|
@@ -189,15 +335,151 @@ def get_json(
|
|
|
189
335
|
série temporal univariada em formato JSON.
|
|
190
336
|
"""
|
|
191
337
|
url, payload = _get_url_and_payload(code, start, end, last)
|
|
192
|
-
|
|
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
|
+
|
|
193
349
|
if res.status_code != 200:
|
|
194
350
|
try:
|
|
195
351
|
res_json = json.loads(res.text)
|
|
196
|
-
except
|
|
352
|
+
except json.JSONDecodeError:
|
|
197
353
|
res_json = {}
|
|
354
|
+
|
|
198
355
|
if "error" in res_json:
|
|
199
356
|
raise SGSError(f"BCB error: {res_json['error']}")
|
|
200
357
|
elif "erro" in res_json:
|
|
201
358
|
raise SGSError(f"BCB error: {res_json['erro']['detail']}")
|
|
202
359
|
raise SGSError(f"Download error: code = {code}")
|
|
203
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
|
bcb/sgs/regional_economy.py
CHANGED
bcb/utils.py
CHANGED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-bcb
|
|
3
|
+
Version: 0.3.6
|
|
4
|
+
Author-email: wilsonfreitas <wilson.freitas@gmail.com>
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Requires-Dist: httpx>=0.24.0
|
|
8
|
+
Requires-Dist: lxml>=4.9.2
|
|
9
|
+
Requires-Dist: pandas>=2.0.0
|
|
10
|
+
Requires-Dist: tenacity>=8.0.0
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# python-bcb
|
|
14
|
+
|
|
15
|
+
**python-bcb** é uma interface em Python estruturada para obter informações
|
|
16
|
+
da API de dados abertos do [Banco Central do Brasil](https://www.bcb.gov.br).
|
|
17
|
+
|
|
18
|
+
[](https://pypi.python.org/pypi/python-bcb/)
|
|
19
|
+
[](https://pypi.python.org/pypi/python-bcb/)
|
|
20
|
+

|
|
21
|
+

|
|
22
|
+

|
|
23
|
+
|
|
24
|
+
O projeto de [Dados Abertos do Banco Central do Brasil](https://dadosabertos.bcb.gov.br/)
|
|
25
|
+
disponibiliza diversas APIs provendo acesso direto a dados de:
|
|
26
|
+
|
|
27
|
+
* Moedas
|
|
28
|
+
* Taxas de Juros
|
|
29
|
+
* Índices de preços
|
|
30
|
+
* Informações de Instituições Financeiras
|
|
31
|
+
* Expectativas do Mercado (Expectativas do Boletim FOCUS)
|
|
32
|
+
* E muito mais...
|
|
33
|
+
|
|
34
|
+
## Instalação
|
|
35
|
+
|
|
36
|
+
**python-bcb** está disponível no [Python Package Index](https://pypi.org/project/python-bcb/) e pode ser instalado via `pip`.
|
|
37
|
+
|
|
38
|
+
```shell
|
|
39
|
+
pip install python-bcb
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## APIs
|
|
43
|
+
|
|
44
|
+
### SGS - Sistema Gerenciador de Séries Temporais
|
|
45
|
+
|
|
46
|
+
Utiliza o webservice do SGS ([Sistema Gerenciador de Séries Temporais](https://www3.bcb.gov.br/sgspub/)) para obter dados históricos de indicadores econômicos. Oferece a maior base de dados históricos com diversas séries temporais.
|
|
47
|
+
|
|
48
|
+
### Conversor de Moedas
|
|
49
|
+
|
|
50
|
+
Implementado no módulo `currency`, realiza webscraping no site do [Conversor de Moedas](https://www.bcb.gov.br/conversao) do Banco Central. Fornece séries temporais de frequência diária de taxas de câmbio (cotações de compra e venda).
|
|
51
|
+
|
|
52
|
+
### OData - APIs Estruturadas
|
|
53
|
+
|
|
54
|
+
O Banco Central disponibiliza diversas informações em APIs que seguem o padrão [OData](https://odata.org). Inclui:
|
|
55
|
+
- **PTAX**: Boletins diários de taxas de câmbio com dados institucionalmentedetalhados
|
|
56
|
+
- **Expectativas**: Expectativas de mercado coletadas do Boletim FOCUS
|
|
57
|
+
- **TaxaJuros**: Diversas taxas de juros (Selic, CDI, Cheque especial, etc.)
|
|
58
|
+
- **MercadoImobiliario**: Dados de financiamento imobiliário
|
|
59
|
+
- **IFDATA**: Informações de instituições financeiras
|
|
60
|
+
- **SPI**: Sistema de Pagamentos Instantâneos
|
|
61
|
+
|
|
62
|
+
## Qual Módulo Devo Usar?
|
|
63
|
+
|
|
64
|
+
Use esta tabela para escolher o módulo certo para seu caso de uso:
|
|
65
|
+
|
|
66
|
+
| Caso de Uso | Módulo | Características Principais |
|
|
67
|
+
|----------|--------|--------------|
|
|
68
|
+
| Séries temporais diárias (inflação, taxas de juros) | `bcb.sgs` | Maior base histórica, controle granular de frequência, múltiplas séries pré-definidas |
|
|
69
|
+
| Taxas de câmbio diárias (PTAX) | `bcb.currency` | Spreads de compra/venda, implementação rápida, frequência diária |
|
|
70
|
+
| Expectativas de mercado (Boletim FOCUS) | `bcb.odata` (Expectativas) | Indicadores de expectativas, previsões de consenso |
|
|
71
|
+
| Taxas de juros (diversos tipos) | `bcb.odata` (TaxaJuros) | Curvas detalhadas, taxas de financiamento imobiliário |
|
|
72
|
+
| Dados de financiamento imobiliário | `bcb.odata` (MercadoImobiliario) | Originações, taxas médias, volumes |
|
|
73
|
+
| Informações de instituições financeiras | `bcb.odata` (IFDATA) | Dados de balanço, informações regulatórias |
|
|
74
|
+
| Análise de dados avançada com filtros | `bcb.odata` (qualquer serviço) | API encadeável, filtragem tipo SQL, ordenação, seleção |
|
|
75
|
+
| Busca concorrente de dados | Qualquer módulo com `async_get()` | Requisições não-bloqueantes, melhor performance para operações em massa |
|
|
76
|
+
|
|
77
|
+
## Início Rápido
|
|
78
|
+
|
|
79
|
+
### Séries Temporais com SGS
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from bcb import sgs
|
|
83
|
+
|
|
84
|
+
# Buscar taxa Selic (código 1)
|
|
85
|
+
df = sgs.get(1, start="2023-01-01", end="2024-12-31")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Taxas de Câmbio com Currency
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from bcb import currency
|
|
92
|
+
|
|
93
|
+
# Buscar preços de compra/venda do USD
|
|
94
|
+
usd = currency.get("USD", start="2023-01-01", end="2024-12-31")
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Expectativas de Mercado com OData
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from bcb import Expectativas
|
|
101
|
+
|
|
102
|
+
api = Expectativas()
|
|
103
|
+
endpoint = api.get_endpoint("ExpectativasMercadoAnuais")
|
|
104
|
+
|
|
105
|
+
# Obter previsões do IPCA
|
|
106
|
+
df = endpoint.query().filter(endpoint.Indicador == "IPCA").limit(100).collect()
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Perguntas Frequentes
|
|
110
|
+
|
|
111
|
+
### P: Qual é a diferença entre dados de moedas do SGS e PTAX?
|
|
112
|
+
**R:** SGS contém principalmente indicadores econômicos. Para taxas de câmbio, use `bcb.currency` (dados PTAX) para cotações diárias ou o serviço `bcb.odata` PTAX para dados institucionais detalhados. O módulo currency é mais simples para casos comuns.
|
|
113
|
+
|
|
114
|
+
### P: Quão longe no tempo os dados históricos vão?
|
|
115
|
+
**R:** Varia por série:
|
|
116
|
+
- SGS: Maioria das séries remontam aos anos 1980/1990 (verifique documentação específica do código)
|
|
117
|
+
- Currency: Cotações diárias disponíveis desde aproximadamente 1980
|
|
118
|
+
- Serviços OData: Varia; consulte documentação BCB para endpoints específicos
|
|
119
|
+
|
|
120
|
+
### P: Posso buscar dados de forma assíncrona?
|
|
121
|
+
**R:** Sim! Todos os módulos têm métodos `async_get()` ou similares. Use-os para requisições concorrentes:
|
|
122
|
+
```python
|
|
123
|
+
import asyncio
|
|
124
|
+
from bcb import sgs
|
|
125
|
+
|
|
126
|
+
async def main():
|
|
127
|
+
results = await asyncio.gather(
|
|
128
|
+
sgs.async_get(1), # SELIC
|
|
129
|
+
sgs.async_get(433), # IPCA
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
asyncio.run(main())
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### P: Como trato erros e dados faltantes?
|
|
136
|
+
**R:** A biblioteca lança exceções específicas:
|
|
137
|
+
- `CurrencyNotFoundError`: Símbolo de moeda não encontrado
|
|
138
|
+
- `SGSError`: Erro do serviço SGS
|
|
139
|
+
- `BCBRateLimitError`: Limite de requisições excedido (HTTP 429)
|
|
140
|
+
- `BCBAPIError`: Outros erros de API
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from bcb import sgs
|
|
144
|
+
from bcb.exceptions import SGSError, BCBRateLimitError
|
|
145
|
+
|
|
146
|
+
try:
|
|
147
|
+
df = sgs.get(99999) # Código inválido
|
|
148
|
+
except SGSError as e:
|
|
149
|
+
print(f"Erro de dados: {e}")
|
|
150
|
+
except BCBRateLimitError:
|
|
151
|
+
print("Limite de requisições excedido - tente novamente mais tarde")
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### P: Como habilito logging para depurar requisições?
|
|
155
|
+
**R:** A biblioteca usa o módulo logging padrão do Python:
|
|
156
|
+
```python
|
|
157
|
+
import logging
|
|
158
|
+
|
|
159
|
+
logging.basicConfig(level=logging.DEBUG)
|
|
160
|
+
logger = logging.getLogger("bcb")
|
|
161
|
+
logger.setLevel(logging.DEBUG)
|
|
162
|
+
|
|
163
|
+
# Agora todas as requisições/respostas HTTP serão registradas
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### P: Existe cache para evitar requisições redundantes?
|
|
167
|
+
**R:** Sim:
|
|
168
|
+
- `bcb.currency`: Cache em memória automático de listas de moedas
|
|
169
|
+
- `bcb.odata`: Metadados OData em cache por URL de serviço
|
|
170
|
+
- Chame `currency.clear_cache()` para resetar se dados mudarem
|
|
171
|
+
|
|
172
|
+
### P: Posso usar isso em uma aplicação de longa duração?
|
|
173
|
+
**R:** Sim, mas tenha cuidado com:
|
|
174
|
+
- Limites de requisições: APIs BCB podem ter limites; implemente backoff se necessário
|
|
175
|
+
- Cache: Cache de moedas persiste em memória; limpe se atualizações de dados importarem
|
|
176
|
+
- Pool de conexões: Usa httpx com connection pooling por padrão
|
|
177
|
+
- API Assíncrona: Use métodos async para comportamento verdadeiramente não-bloqueante
|
|
178
|
+
|
|
179
|
+
### P: Como contribuo ou reporto problemas?
|
|
180
|
+
**R:** Visite o [repositório GitHub](https://github.com/wilsonfreitas/python-bcb) para:
|
|
181
|
+
- Reportar bugs
|
|
182
|
+
- Solicitar features
|
|
183
|
+
- Enviar pull requests
|
|
184
|
+
- Ver documentação
|
|
185
|
+
|
|
186
|
+
### P: Onde encontro documentação mais detalhada?
|
|
187
|
+
**R:**
|
|
188
|
+
- [Documentação de API](https://bcb-python.readthedocs.io/)
|
|
189
|
+
- [Diretório de Exemplos](./examples/)
|
|
190
|
+
- Docstrings inline: `help(bcb.sgs.get)`, `help(bcb.currency.get)`, etc.
|
|
191
|
+
- [Portal de Dados Abertos BCB](https://dadosabertos.bcb.gov.br/)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
bcb/__init__.py,sha256=WqaBnwklYV39rVHsIjExiC6uwGWyX6HB_fIHEaB40lc,529
|
|
2
|
+
bcb/currency.py,sha256=OYxvDQa_TPOLiCABfdHqu0sbvT_FHTmAdaFLx_s404o,27033
|
|
3
|
+
bcb/exceptions.py,sha256=gnREvUECVbsb-f57uLSkl8hD7ITmSvXuT2y5ycpVHlk,912
|
|
4
|
+
bcb/http.py,sha256=VbNXYLJqzwzM_Mjt0DR54gAiIOHpP0lTyKEwZlLqefU,2346
|
|
5
|
+
bcb/utils.py,sha256=HHrEpEM9b2nEVmPEBU0nV__47HeAUCKkfbx9pYQhYQ4,1751
|
|
6
|
+
bcb/odata/__init__.py,sha256=O9dLRmMa6jq18ICAEK-cRfZNRJPtRFSWVqqeD_8VB98,410
|
|
7
|
+
bcb/odata/api.py,sha256=TSoa7TRE18bA7RB1mYyGVwwXXfSX2Ht6FmPeXS67CtE,25142
|
|
8
|
+
bcb/odata/framework.py,sha256=p2FnWoxMLoc7vzUyWZNlfrrwcqQgfZqFr_yp2T1aeTA,19787
|
|
9
|
+
bcb/sgs/__init__.py,sha256=MqEJOgushIk--IPiS0toOwd4jZHU5qUiyk0MW0XUpio,14676
|
|
10
|
+
bcb/sgs/regional_economy.py,sha256=5miptnHJuLznsrFok8DAkvGEaYMg8dJcWlK_6FESaEs,6303
|
|
11
|
+
python_bcb-0.3.6.dist-info/METADATA,sha256=8WUAL-BQxjia1nE1KpWhM03POSUwvMYrC4B7xN9ceNE,7686
|
|
12
|
+
python_bcb-0.3.6.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
13
|
+
python_bcb-0.3.6.dist-info/licenses/LICENSE,sha256=PK0tDWJUgRdeZCmA39ZHQu8v2ozAOl49qEaDEcntbAA,1070
|
|
14
|
+
python_bcb-0.3.6.dist-info/RECORD,,
|