python-bcb 0.3.0__py3-none-any.whl → 0.3.3__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 +17 -20
- bcb/{sgs.py → sgs/__init__.py} +188 -131
- bcb/sgs/regional_economy.py +208 -0
- bcb/utils.py +24 -11
- {python_bcb-0.3.0.dist-info → python_bcb-0.3.3.dist-info}/METADATA +2 -2
- python_bcb-0.3.3.dist-info/RECORD +12 -0
- python_bcb-0.3.0.dist-info/RECORD +0 -11
- {python_bcb-0.3.0.dist-info → python_bcb-0.3.3.dist-info}/LICENSE +0 -0
- {python_bcb-0.3.0.dist-info → python_bcb-0.3.3.dist-info}/WHEEL +0 -0
bcb/currency.py
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import re
|
|
2
2
|
import warnings
|
|
3
|
-
from io import BytesIO, StringIO
|
|
4
3
|
from datetime import date, timedelta
|
|
4
|
+
from io import BytesIO, StringIO
|
|
5
|
+
from typing import List, Union
|
|
5
6
|
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
6
9
|
import requests
|
|
7
10
|
from lxml import html
|
|
8
11
|
|
|
9
|
-
import
|
|
10
|
-
import numpy as np
|
|
11
|
-
|
|
12
|
-
from .utils import Date
|
|
12
|
+
from .utils import Date, DateInput
|
|
13
13
|
|
|
14
14
|
"""
|
|
15
15
|
O módulo :py:mod:`bcb.currency` tem como objetivo fazer consultas no site do conversor de moedas do BCB.
|
|
16
16
|
"""
|
|
17
17
|
|
|
18
18
|
|
|
19
|
-
def _currency_url(currency_id, start_date, end_date):
|
|
19
|
+
def _currency_url(currency_id: str, start_date: DateInput, end_date: DateInput) -> str:
|
|
20
20
|
start_date = Date(start_date)
|
|
21
21
|
end_date = Date(end_date)
|
|
22
22
|
url = (
|
|
@@ -30,14 +30,11 @@ def _currency_url(currency_id, start_date, end_date):
|
|
|
30
30
|
CACHE = dict()
|
|
31
31
|
|
|
32
32
|
|
|
33
|
-
def _currency_id_list():
|
|
33
|
+
def _currency_id_list() -> pd.DataFrame:
|
|
34
34
|
if CACHE.get("TEMP_CURRENCY_ID_LIST") is not None:
|
|
35
35
|
return CACHE.get("TEMP_CURRENCY_ID_LIST")
|
|
36
36
|
else:
|
|
37
|
-
url1 =
|
|
38
|
-
"https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?"
|
|
39
|
-
"method=exibeFormularioConsultaBoletim"
|
|
40
|
-
)
|
|
37
|
+
url1 = "https://ptax.bcb.gov.br/ptax_internet/consultaBoletim.do?" "method=exibeFormularioConsultaBoletim"
|
|
41
38
|
res = requests.get(url1)
|
|
42
39
|
if res.status_code != 200:
|
|
43
40
|
msg = f"BCB API Request error, status code = {res.status_code}"
|
|
@@ -52,7 +49,7 @@ def _currency_id_list():
|
|
|
52
49
|
return df
|
|
53
50
|
|
|
54
51
|
|
|
55
|
-
def _get_valid_currency_list(_date, n=0):
|
|
52
|
+
def _get_valid_currency_list(_date: date, n: int = 0) -> requests.models.Response:
|
|
56
53
|
url2 = f"http://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
|
|
57
54
|
try:
|
|
58
55
|
res = requests.get(url2)
|
|
@@ -66,7 +63,7 @@ def _get_valid_currency_list(_date, n=0):
|
|
|
66
63
|
return _get_valid_currency_list(_date - timedelta(1), 0)
|
|
67
64
|
|
|
68
65
|
|
|
69
|
-
def get_currency_list():
|
|
66
|
+
def get_currency_list() -> pd.DataFrame:
|
|
70
67
|
"""
|
|
71
68
|
Listagem com todas as moedas disponíveis na API e suas configurações de paridade.
|
|
72
69
|
|
|
@@ -99,14 +96,14 @@ def get_currency_list():
|
|
|
99
96
|
return df
|
|
100
97
|
|
|
101
98
|
|
|
102
|
-
def _get_currency_id(symbol):
|
|
99
|
+
def _get_currency_id(symbol: str) -> int:
|
|
103
100
|
id_list = _currency_id_list()
|
|
104
101
|
all_currencies = get_currency_list()
|
|
105
102
|
x = pd.merge(id_list, all_currencies, on=["name"])
|
|
106
103
|
return np.max(x.loc[x["symbol"] == symbol, "id"])
|
|
107
104
|
|
|
108
105
|
|
|
109
|
-
def _get_symbol(symbol, start_date, end_date):
|
|
106
|
+
def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.DataFrame:
|
|
110
107
|
cid = _get_currency_id(symbol)
|
|
111
108
|
url = _currency_url(cid, start_date, end_date)
|
|
112
109
|
res = requests.get(url)
|
|
@@ -123,9 +120,7 @@ def _get_symbol(symbol, start_date, end_date):
|
|
|
123
120
|
return None
|
|
124
121
|
|
|
125
122
|
columns = ["Date", "aa", "bb", "cc", "bid", "ask", "dd", "ee"]
|
|
126
|
-
df = pd.read_csv(
|
|
127
|
-
StringIO(res.text), delimiter=";", header=None, names=columns, dtype=str
|
|
128
|
-
)
|
|
123
|
+
df = pd.read_csv(StringIO(res.text), delimiter=";", header=None, names=columns, dtype=str)
|
|
129
124
|
df = df.assign(
|
|
130
125
|
Date=lambda x: pd.to_datetime(x["Date"], format="%d%m%Y"),
|
|
131
126
|
bid=lambda x: x["bid"].str.replace(",", ".").astype(np.float64),
|
|
@@ -139,7 +134,9 @@ def _get_symbol(symbol, start_date, end_date):
|
|
|
139
134
|
return df1
|
|
140
135
|
|
|
141
136
|
|
|
142
|
-
def get(
|
|
137
|
+
def get(
|
|
138
|
+
symbols: Union[str, List[str]], start: DateInput, end: DateInput, side: str = "ask", groupby: str = "symbol"
|
|
139
|
+
) -> pd.DataFrame:
|
|
143
140
|
"""
|
|
144
141
|
Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
|
|
145
142
|
|
|
@@ -189,4 +186,4 @@ def get(symbols, start, end, side="ask", groupby="symbol"):
|
|
|
189
186
|
else:
|
|
190
187
|
raise Exception(f"Unknown side value, use: bid, ask, both")
|
|
191
188
|
else:
|
|
192
|
-
|
|
189
|
+
raise Exception(f"Currency not found: {symbols}")
|
bcb/{sgs.py → sgs/__init__.py}
RENAMED
|
@@ -1,131 +1,188 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
1
|
+
import json
|
|
2
|
+
from io import StringIO
|
|
3
|
+
from typing import Dict, Generator, List, Optional, Tuple, TypeAlias, Union
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from bcb.utils import Date, DateInput
|
|
9
|
+
|
|
10
|
+
"""
|
|
11
|
+
Sistema Gerenciador de Séries Temporais (SGS)
|
|
12
|
+
|
|
13
|
+
O módulo ``sgs`` obtem os dados do webservice do Banco Central,
|
|
14
|
+
interface json do serviço BCData/SGS -
|
|
15
|
+
`Sistema Gerenciador de Séries Temporais (SGS)
|
|
16
|
+
<https://www3.bcb.gov.br/sgspub/localizarseries/localizarSeries.do?method=prepararTelaLocalizarSeries>`_.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
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)
|
|
29
|
+
|
|
30
|
+
def __repr__(self):
|
|
31
|
+
return f"{self.code} - {self.name}" if self.name else f"{self.code}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
SGSCodeInput: TypeAlias = Union[
|
|
35
|
+
int,
|
|
36
|
+
str,
|
|
37
|
+
Tuple[str, Union[int, str]],
|
|
38
|
+
List[Union[int, str, Tuple[str, Union[int, str]]]],
|
|
39
|
+
Dict[str, Union[int, str]],
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _codes(codes: SGSCodeInput) -> Generator[SGSCode, None, None]:
|
|
44
|
+
if isinstance(codes, int) or isinstance(codes, str):
|
|
45
|
+
yield SGSCode(codes)
|
|
46
|
+
elif isinstance(codes, tuple):
|
|
47
|
+
yield SGSCode(codes[1], codes[0])
|
|
48
|
+
elif isinstance(codes, list):
|
|
49
|
+
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):
|
|
53
|
+
for name, code in codes.items():
|
|
54
|
+
yield SGSCode(code, name)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _get_url_and_payload(code: int, start_date: DateInput, end_date: DateInput, last: int) -> Dict[str, str]:
|
|
58
|
+
payload = {"formato": "json"}
|
|
59
|
+
if last == 0:
|
|
60
|
+
if start_date is not None or end_date is not None:
|
|
61
|
+
payload["dataInicial"] = Date(start_date).date.strftime("%d/%m/%Y")
|
|
62
|
+
end_date = end_date if end_date else "today"
|
|
63
|
+
payload["dataFinal"] = Date(end_date).date.strftime("%d/%m/%Y")
|
|
64
|
+
url = "https://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados".format(code)
|
|
65
|
+
else:
|
|
66
|
+
url = ("https://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados" "/ultimos/{}").format(code, last)
|
|
67
|
+
|
|
68
|
+
return {"payload": payload, "url": url}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _format_df(df: pd.DataFrame, code: SGSCode, freq: str) -> pd.DataFrame:
|
|
72
|
+
cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
|
|
73
|
+
df = df.rename(columns=cns)
|
|
74
|
+
if "Date" in df:
|
|
75
|
+
df["Date"] = pd.to_datetime(df["Date"], format="%d/%m/%Y")
|
|
76
|
+
if "enddate" in df:
|
|
77
|
+
df["enddate"] = pd.to_datetime(df["enddate"], format="%d/%m/%Y")
|
|
78
|
+
df = df.set_index("Date")
|
|
79
|
+
if freq:
|
|
80
|
+
df.index = df.index.to_period(freq)
|
|
81
|
+
return df
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def get(
|
|
85
|
+
codes: SGSCodeInput,
|
|
86
|
+
start: Optional[DateInput] = None,
|
|
87
|
+
end: Optional[DateInput] = None,
|
|
88
|
+
last: int = 0,
|
|
89
|
+
multi: bool = True,
|
|
90
|
+
freq: Optional[str] = None,
|
|
91
|
+
) -> Union[pd.DataFrame, List[pd.DataFrame]]:
|
|
92
|
+
"""
|
|
93
|
+
Retorna um DataFrame pandas com séries temporais obtidas do SGS.
|
|
94
|
+
|
|
95
|
+
Parameters
|
|
96
|
+
----------
|
|
97
|
+
|
|
98
|
+
codes : {int, List[int], List[str], Dict[str:int]}
|
|
99
|
+
Este argumento pode ser uma das opções:
|
|
100
|
+
|
|
101
|
+
* ``int`` : código da série temporal
|
|
102
|
+
* ``list`` ou ``tuple`` : lista ou tupla com códigos
|
|
103
|
+
* ``list`` ou ``tuple`` : lista ou tupla com pares ``('nome', código)``
|
|
104
|
+
* ``dict`` : dicionário com pares ``{'nome': código}``
|
|
105
|
+
|
|
106
|
+
Com códigos numéricos é interessante utilizar os nomes com os códigos
|
|
107
|
+
para definir os nomes nas colunas das séries temporais.
|
|
108
|
+
start : str, int, date, datetime, Timestamp
|
|
109
|
+
Data de início da série.
|
|
110
|
+
Interpreta diferentes tipos e formatos de datas.
|
|
111
|
+
end : string, int, date, datetime, Timestamp
|
|
112
|
+
Data final da série.
|
|
113
|
+
Interpreta diferentes tipos e formatos de datas.
|
|
114
|
+
last : int
|
|
115
|
+
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
116
|
+
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|
|
117
|
+
e ``end`` são ignorados.
|
|
118
|
+
multi : bool
|
|
119
|
+
Define se, quando mais de 1 série for solicitada, a função retorna uma
|
|
120
|
+
série multivariada ou uma lista com séries univariadas.
|
|
121
|
+
freq : str
|
|
122
|
+
Define a frequência a ser utilizada na série temporal
|
|
123
|
+
|
|
124
|
+
Returns
|
|
125
|
+
-------
|
|
126
|
+
|
|
127
|
+
``DataFrame`` :
|
|
128
|
+
série temporal univariada ou multivariada,
|
|
129
|
+
quando solicitado mais de uma série (parâmetro ``multi=True``).
|
|
130
|
+
|
|
131
|
+
``list`` :
|
|
132
|
+
lista com séries temporais univariadas,
|
|
133
|
+
quando solicitado mais de uma série (parâmetro ``multi=False``).
|
|
134
|
+
"""
|
|
135
|
+
dfs = []
|
|
136
|
+
for code in _codes(codes):
|
|
137
|
+
text = get_json(code.value, start, end, last)
|
|
138
|
+
df = pd.read_json(StringIO(text))
|
|
139
|
+
df = _format_df(df, code, freq)
|
|
140
|
+
dfs.append(df)
|
|
141
|
+
if len(dfs) == 1:
|
|
142
|
+
return dfs[0]
|
|
143
|
+
else:
|
|
144
|
+
if multi:
|
|
145
|
+
return pd.concat(dfs, axis=1)
|
|
146
|
+
else:
|
|
147
|
+
return dfs
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def get_json(code: int, start: Optional[DateInput] = None, end: Optional[DateInput] = None, last: int = 0) -> str:
|
|
151
|
+
"""
|
|
152
|
+
Retorna um JSON com séries temporais obtidas do SGS.
|
|
153
|
+
|
|
154
|
+
Parameters
|
|
155
|
+
----------
|
|
156
|
+
|
|
157
|
+
code : int
|
|
158
|
+
Código da série temporal
|
|
159
|
+
start : str, int, date, datetime, Timestamp
|
|
160
|
+
Data de início da série.
|
|
161
|
+
Interpreta diferentes tipos e formatos de datas.
|
|
162
|
+
end : string, int, date, datetime, Timestamp
|
|
163
|
+
Data final da série.
|
|
164
|
+
Interpreta diferentes tipos e formatos de datas.
|
|
165
|
+
last : int
|
|
166
|
+
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
167
|
+
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|
|
168
|
+
e ``end`` são ignorados.
|
|
169
|
+
|
|
170
|
+
Returns
|
|
171
|
+
-------
|
|
172
|
+
|
|
173
|
+
JSON :
|
|
174
|
+
série temporal univariada em formato JSON.
|
|
175
|
+
"""
|
|
176
|
+
urd = _get_url_and_payload(code, start, end, last)
|
|
177
|
+
res = requests.get(urd["url"], params=urd["payload"])
|
|
178
|
+
if res.status_code != 200:
|
|
179
|
+
try:
|
|
180
|
+
res_json = json.loads(res.text)
|
|
181
|
+
except Exception:
|
|
182
|
+
res_json = {}
|
|
183
|
+
if "error" in res_json:
|
|
184
|
+
raise Exception("BCB error: {}".format(res_json["error"]))
|
|
185
|
+
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
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
from typing import Dict, List, Optional, Union
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from bcb.sgs import get
|
|
6
|
+
from bcb.utils import DateInput
|
|
7
|
+
|
|
8
|
+
"""
|
|
9
|
+
Dados da Economia Regional
|
|
10
|
+
|
|
11
|
+
Histórico de taxas de inadimplência das operações de crédito do Sistema Financeiro Nacional para
|
|
12
|
+
pessoas físicas e pessoas jurídicas.
|
|
13
|
+
|
|
14
|
+
Dados disponíveis por região e por estado.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
NON_PERFORMING_LOANS_BY_REGION_PF = {
|
|
18
|
+
"N": "15888",
|
|
19
|
+
"NE": "15889",
|
|
20
|
+
"CO": "15890",
|
|
21
|
+
"SE": "15891",
|
|
22
|
+
"S": "15892",
|
|
23
|
+
}
|
|
24
|
+
NON_PERFORMING_LOANS_BY_STATE_PF = {
|
|
25
|
+
"AC": "15861",
|
|
26
|
+
"AL": "15862",
|
|
27
|
+
"AP": "15863",
|
|
28
|
+
"AM": "15864",
|
|
29
|
+
"BA": "15865",
|
|
30
|
+
"CE": "15866",
|
|
31
|
+
"DF": "15867",
|
|
32
|
+
"ES": "15868",
|
|
33
|
+
"GO": "15869",
|
|
34
|
+
"MA": "15870",
|
|
35
|
+
"MT": "15871",
|
|
36
|
+
"MS": "15872",
|
|
37
|
+
"MG": "15873",
|
|
38
|
+
"PA": "15874",
|
|
39
|
+
"PB": "15875",
|
|
40
|
+
"PR": "15876",
|
|
41
|
+
"PE": "15877",
|
|
42
|
+
"PI": "15878",
|
|
43
|
+
"RJ": "15879",
|
|
44
|
+
"RN": "15880",
|
|
45
|
+
"RS": "15881",
|
|
46
|
+
"RO": "15882",
|
|
47
|
+
"RR": "15883",
|
|
48
|
+
"SC": "15884",
|
|
49
|
+
"SP": "15885",
|
|
50
|
+
"SE": "15886",
|
|
51
|
+
"TO": "15887",
|
|
52
|
+
}
|
|
53
|
+
NON_PERFORMING_LOANS_BY_REGION_PJ = {
|
|
54
|
+
"N": "15920",
|
|
55
|
+
"NE": "15921",
|
|
56
|
+
"CO": "15922",
|
|
57
|
+
"SE": "15923",
|
|
58
|
+
"S": "15924",
|
|
59
|
+
}
|
|
60
|
+
NON_PERFORMING_LOANS_BY_STATE_PJ = {
|
|
61
|
+
"AC": "15893",
|
|
62
|
+
"AL": "15894",
|
|
63
|
+
"AP": "15895",
|
|
64
|
+
"AM": "15896",
|
|
65
|
+
"BA": "15897",
|
|
66
|
+
"CE": "15898",
|
|
67
|
+
"DF": "15899",
|
|
68
|
+
"ES": "15900",
|
|
69
|
+
"GO": "15901",
|
|
70
|
+
"MA": "15902",
|
|
71
|
+
"MT": "15903",
|
|
72
|
+
"MS": "15904",
|
|
73
|
+
"MG": "15905",
|
|
74
|
+
"PA": "15906",
|
|
75
|
+
"PB": "15907",
|
|
76
|
+
"PR": "15908",
|
|
77
|
+
"PE": "15909",
|
|
78
|
+
"PI": "15910",
|
|
79
|
+
"RJ": "15911",
|
|
80
|
+
"RN": "15912",
|
|
81
|
+
"RS": "15913",
|
|
82
|
+
"RO": "15914",
|
|
83
|
+
"RR": "15915",
|
|
84
|
+
"SC": "15916",
|
|
85
|
+
"SP": "15917",
|
|
86
|
+
"SE": "15918",
|
|
87
|
+
"TO": "15919",
|
|
88
|
+
}
|
|
89
|
+
NON_PERFORMING_LOANS_BY_REGION_TOTAL = {
|
|
90
|
+
"N": "15952",
|
|
91
|
+
"NE": "15953",
|
|
92
|
+
"CO": "15954",
|
|
93
|
+
"SE": "15955",
|
|
94
|
+
"S": "15956",
|
|
95
|
+
}
|
|
96
|
+
NON_PERFORMING_LOANS_BY_STATE_TOTAL = {
|
|
97
|
+
"AC": "15925",
|
|
98
|
+
"AL": "15926",
|
|
99
|
+
"AP": "15927",
|
|
100
|
+
"AM": "15928",
|
|
101
|
+
"BA": "15929",
|
|
102
|
+
"CE": "15930",
|
|
103
|
+
"DF": "15931",
|
|
104
|
+
"ES": "15932",
|
|
105
|
+
"GO": "15933",
|
|
106
|
+
"MA": "15934",
|
|
107
|
+
"MT": "15935",
|
|
108
|
+
"MS": "15936",
|
|
109
|
+
"MG": "15937",
|
|
110
|
+
"PA": "15938",
|
|
111
|
+
"PB": "15939",
|
|
112
|
+
"PR": "15940",
|
|
113
|
+
"PE": "15941",
|
|
114
|
+
"PI": "15942",
|
|
115
|
+
"RJ": "15943",
|
|
116
|
+
"RN": "15944",
|
|
117
|
+
"RS": "15945",
|
|
118
|
+
"RO": "15946",
|
|
119
|
+
"RR": "15947",
|
|
120
|
+
"SC": "15948",
|
|
121
|
+
"SP": "15949",
|
|
122
|
+
"SE": "15950",
|
|
123
|
+
"TO": "15951",
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def get_non_performing_loans_codes(states_or_region: Union[str, List[str]], mode: str = "total") -> Dict[str, str]:
|
|
128
|
+
is_state = False
|
|
129
|
+
is_region = False
|
|
130
|
+
states_or_region = [states_or_region] if isinstance(states_or_region, str) else states_or_region
|
|
131
|
+
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):
|
|
133
|
+
is_state = True
|
|
134
|
+
elif any(location in list(NON_PERFORMING_LOANS_BY_REGION_TOTAL.keys()) for location in states_or_region):
|
|
135
|
+
is_region = True
|
|
136
|
+
|
|
137
|
+
if not is_state and not is_region:
|
|
138
|
+
raise Exception(f"Not a valid state or region: {states_or_region}")
|
|
139
|
+
|
|
140
|
+
codes = {}
|
|
141
|
+
non_performing_loans_by_location = NON_PERFORMING_LOANS_BY_STATE_TOTAL
|
|
142
|
+
if is_state:
|
|
143
|
+
if mode.upper() == "PF":
|
|
144
|
+
non_performing_loans_by_location = NON_PERFORMING_LOANS_BY_STATE_PF
|
|
145
|
+
elif mode.upper() == "PJ":
|
|
146
|
+
non_performing_loans_by_location = NON_PERFORMING_LOANS_BY_STATE_PJ
|
|
147
|
+
elif is_region:
|
|
148
|
+
non_performing_loans_by_location = NON_PERFORMING_LOANS_BY_REGION_TOTAL
|
|
149
|
+
if mode.upper() == "PF":
|
|
150
|
+
non_performing_loans_by_location = NON_PERFORMING_LOANS_BY_REGION_PF
|
|
151
|
+
elif mode.upper() == "PJ":
|
|
152
|
+
non_performing_loans_by_location = NON_PERFORMING_LOANS_BY_REGION_PJ
|
|
153
|
+
|
|
154
|
+
for location in states_or_region:
|
|
155
|
+
codes[location] = non_performing_loans_by_location[location]
|
|
156
|
+
return codes
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def get_non_performing_loans(
|
|
160
|
+
states_or_region: Union[str, List[str]],
|
|
161
|
+
mode: str = "total",
|
|
162
|
+
start: Optional[DateInput] = None,
|
|
163
|
+
end: Optional[DateInput] = None,
|
|
164
|
+
last: int = 0,
|
|
165
|
+
freq: Optional[str] = None,
|
|
166
|
+
) -> pd.DataFrame:
|
|
167
|
+
"""Dados de inadimplência das operações de crédito.
|
|
168
|
+
|
|
169
|
+
Esta função é um *wrapper* para o método para a função ``get`` do módulo ``sgs``,
|
|
170
|
+
simplificando o acesso aos dados de inadimplência das operações de crédito.
|
|
171
|
+
Nessa função o usuário escolhe o tipo de inadimplência, o(s) estado(s) ou as regiões
|
|
172
|
+
que deseja obter os dados.
|
|
173
|
+
|
|
174
|
+
>>> from bcb.sgs.regional_economy import get_non_performing_loans
|
|
175
|
+
>>> from bcb.utils import BRAZILIAN_REGIONS
|
|
176
|
+
>>> series = get_non_performing_loans(["RR"], last=10, mode="all")
|
|
177
|
+
>>> northeast_states = BRAZILIAN_REGIONS["NE"]
|
|
178
|
+
>>> series_ne = get_non_performing_loans(northeast_states, last=5, mode="pj")
|
|
179
|
+
|
|
180
|
+
Parameters
|
|
181
|
+
----------
|
|
182
|
+
|
|
183
|
+
states_or_region (List[str]): Uma lista com estado ou região.
|
|
184
|
+
mode (str): O tipo de inadimplência. Pode ser "PF" (pessoas físicas),
|
|
185
|
+
"PJ" (pessoas jurídicas) ou "total" (inadimplência total).
|
|
186
|
+
start : str, int, date, datetime, Timestamp
|
|
187
|
+
Data de início da série.
|
|
188
|
+
Interpreta diferentes tipos e formatos de datas.
|
|
189
|
+
end : string, int, date, datetime, Timestamp
|
|
190
|
+
Data final da série.
|
|
191
|
+
Interpreta diferentes tipos e formatos de datas.
|
|
192
|
+
last : int
|
|
193
|
+
Retorna os últimos ``last`` elementos disponíveis da série temporal
|
|
194
|
+
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
|
|
195
|
+
e ``end`` são ignorados.
|
|
196
|
+
freq : str
|
|
197
|
+
Define a frequência a ser utilizada na série temporal
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
Returns
|
|
201
|
+
-------
|
|
202
|
+
|
|
203
|
+
``DataFrame`` :
|
|
204
|
+
série temporal univariada ou multivariada,
|
|
205
|
+
quando solicitado mais de uma série temporal.
|
|
206
|
+
"""
|
|
207
|
+
codes = get_non_performing_loans_codes(states_or_region, mode=mode)
|
|
208
|
+
return get(codes, start=start, end=end, last=last, multi=True, freq=freq)
|
bcb/utils.py
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
|
-
from datetime import
|
|
1
|
+
from datetime import date, datetime
|
|
2
|
+
from typing import TypeAlias, Union
|
|
3
|
+
|
|
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"],
|
|
10
|
+
}
|
|
11
|
+
BRAZILIAN_STATES = []
|
|
12
|
+
for state in BRAZILIAN_REGIONS.values():
|
|
13
|
+
BRAZILIAN_STATES.extend(state)
|
|
14
|
+
|
|
15
|
+
DateInput: TypeAlias = Union[str, datetime, "Date", date]
|
|
2
16
|
|
|
3
17
|
|
|
4
18
|
class Date:
|
|
5
|
-
def __init__(self, d
|
|
6
|
-
d = d if d else mindate
|
|
19
|
+
def __init__(self, d: DateInput, format: str = "%Y-%m-%d") -> None:
|
|
7
20
|
if isinstance(d, str):
|
|
8
21
|
if d == "now" or d == "today":
|
|
9
22
|
d = date.today()
|
|
@@ -17,27 +30,27 @@ class Date:
|
|
|
17
30
|
pass
|
|
18
31
|
else:
|
|
19
32
|
raise ValueError()
|
|
20
|
-
self.date = d
|
|
33
|
+
self.date: date = d
|
|
21
34
|
|
|
22
|
-
def format(self, fmts="%Y-%m-%d"):
|
|
35
|
+
def format(self, fmts: str = "%Y-%m-%d") -> str:
|
|
23
36
|
return datetime.strftime(self.date, fmts)
|
|
24
37
|
|
|
25
|
-
def __gt__(self, other):
|
|
38
|
+
def __gt__(self, other) -> bool:
|
|
26
39
|
return self.date > other.date
|
|
27
40
|
|
|
28
|
-
def __ge__(self, other):
|
|
41
|
+
def __ge__(self, other) -> bool:
|
|
29
42
|
return self.date >= other.date
|
|
30
43
|
|
|
31
|
-
def __lt__(self, other):
|
|
44
|
+
def __lt__(self, other) -> bool:
|
|
32
45
|
return self.date < other.date
|
|
33
46
|
|
|
34
|
-
def __le__(self, other):
|
|
47
|
+
def __le__(self, other) -> bool:
|
|
35
48
|
return self.date <= other.date
|
|
36
49
|
|
|
37
|
-
def __eq__(self, other):
|
|
50
|
+
def __eq__(self, other) -> bool:
|
|
38
51
|
return self.date == other.date
|
|
39
52
|
|
|
40
|
-
def __repr__(self):
|
|
53
|
+
def __repr__(self) -> str:
|
|
41
54
|
return self.format()
|
|
42
55
|
|
|
43
56
|
__str__ = __repr__
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: python-bcb
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.3
|
|
4
4
|
Summary:
|
|
5
5
|
Author: wilsonfreitas
|
|
6
6
|
Author-email: wilson.freitas@gmail.com
|
|
@@ -48,7 +48,7 @@ pip install python-bcb
|
|
|
48
48
|
|
|
49
49
|
## SGS
|
|
50
50
|
Utiliza o webservice do SGS
|
|
51
|
-
(
|
|
51
|
+
([Sistema Gerenciador de Séries Temporais](https://www3.bcb.gov.br/sgspub/))
|
|
52
52
|
para obter os dados.
|
|
53
53
|
|
|
54
54
|
## Conversor de Moedas
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
bcb/__init__.py,sha256=TpLWnEt2a3uOsIgd-DBYrU7FgWC6nuk3rB4-QZgQsxY,371
|
|
2
|
+
bcb/currency.py,sha256=5JaPPpdT3ylLukJlljn9pRhYM5PVuYLWaiNCZbgMolU,6386
|
|
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=MkT5GqCBsNGfNWyPWVB_Knu6LTMhdlZLJiicwvpSLnw,6627
|
|
7
|
+
bcb/sgs/regional_economy.py,sha256=qOTdxnB3SuocN4OaAwh0vzWBwAOXLOKbawhr5tQAYgE,6189
|
|
8
|
+
bcb/utils.py,sha256=HFaDdPl1oPTePdT0f5nNjXNE5dqTouVN6bAkFd7Guro,1557
|
|
9
|
+
python_bcb-0.3.3.dist-info/LICENSE,sha256=PK0tDWJUgRdeZCmA39ZHQu8v2ozAOl49qEaDEcntbAA,1070
|
|
10
|
+
python_bcb-0.3.3.dist-info/METADATA,sha256=t5d3Qara2vTcO1Soz24PJJpT0Ztf4OY7nqqc2p8jkBY,2525
|
|
11
|
+
python_bcb-0.3.3.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
|
|
12
|
+
python_bcb-0.3.3.dist-info/RECORD,,
|
|
@@ -1,11 +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.py,sha256=UspoPP1OQQYTdQ9p2lYDRS_8-VP3xQUaaf0PxA3cg-8,4513
|
|
7
|
-
bcb/utils.py,sha256=3bG_9uxCXjQI-hSBXbq4zN5zIbF7ZDTafEh0-berZlI,1089
|
|
8
|
-
python_bcb-0.3.0.dist-info/LICENSE,sha256=PK0tDWJUgRdeZCmA39ZHQu8v2ozAOl49qEaDEcntbAA,1070
|
|
9
|
-
python_bcb-0.3.0.dist-info/METADATA,sha256=laHhf8Un-kSS-BGDZl6MSXSGrVxNLeoMPyi9v-tltos,2527
|
|
10
|
-
python_bcb-0.3.0.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
|
|
11
|
-
python_bcb-0.3.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|