python-bcb 0.3.2__tar.gz → 0.3.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-bcb
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary:
5
5
  Author: wilsonfreitas
6
6
  Author-email: wilson.freitas@gmail.com
@@ -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 pandas as pd
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(symbols, start, end, side="ask", groupby="symbol"):
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
- return None
189
+ raise Exception(f"Currency not found: {symbols}")
@@ -1,9 +1,11 @@
1
+ import json
1
2
  from io import StringIO
3
+ from typing import Dict, Generator, List, Optional, Tuple, TypeAlias, Union
2
4
 
3
- import requests
4
5
  import pandas as pd
6
+ import requests
5
7
 
6
- from bcb.utils import Date
8
+ from bcb.utils import Date, DateInput
7
9
 
8
10
  """
9
11
  Sistema Gerenciador de Séries Temporais (SGS)
@@ -16,7 +18,7 @@ interface json do serviço BCData/SGS -
16
18
 
17
19
 
18
20
  class SGSCode:
19
- def __init__(self, code, name=None):
21
+ def __init__(self, code: Union[str, int], name: Optional[str] = None) -> None:
20
22
  if name is None:
21
23
  if isinstance(code, int) or isinstance(code, str):
22
24
  self.name = str(code)
@@ -29,7 +31,16 @@ class SGSCode:
29
31
  return f"{self.code} - {self.name}" if self.name else f"{self.code}"
30
32
 
31
33
 
32
- def _codes(codes):
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]:
33
44
  if isinstance(codes, int) or isinstance(codes, str):
34
45
  yield SGSCode(codes)
35
46
  elif isinstance(codes, tuple):
@@ -43,7 +54,7 @@ def _codes(codes):
43
54
  yield SGSCode(code, name)
44
55
 
45
56
 
46
- def _get_url_and_payload(code, start_date, end_date, last):
57
+ def _get_url_and_payload(code: int, start_date: DateInput, end_date: DateInput, last: int) -> Dict[str, str]:
47
58
  payload = {"formato": "json"}
48
59
  if last == 0:
49
60
  if start_date is not None or end_date is not None:
@@ -57,7 +68,7 @@ def _get_url_and_payload(code, start_date, end_date, last):
57
68
  return {"payload": payload, "url": url}
58
69
 
59
70
 
60
- def _format_df(df, code, freq):
71
+ def _format_df(df: pd.DataFrame, code: SGSCode, freq: str) -> pd.DataFrame:
61
72
  cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
62
73
  df = df.rename(columns=cns)
63
74
  if "Date" in df:
@@ -70,7 +81,14 @@ def _format_df(df, code, freq):
70
81
  return df
71
82
 
72
83
 
73
- def get(codes, start=None, end=None, last=0, multi=True, freq=None):
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]]:
74
92
  """
75
93
  Retorna um DataFrame pandas com séries temporais obtidas do SGS.
76
94
 
@@ -116,11 +134,8 @@ def get(codes, start=None, end=None, last=0, multi=True, freq=None):
116
134
  """
117
135
  dfs = []
118
136
  for code in _codes(codes):
119
- urd = _get_url_and_payload(code.value, start, end, last)
120
- res = requests.get(urd["url"], params=urd["payload"])
121
- if res.status_code != 200:
122
- raise Exception("Download error: code = {}".format(code.value))
123
- df = pd.read_json(StringIO(res.text))
137
+ text = get_json(code.value, start, end, last)
138
+ df = pd.read_json(StringIO(text))
124
139
  df = _format_df(df, code, freq)
125
140
  dfs.append(df)
126
141
  if len(dfs) == 1:
@@ -130,3 +145,44 @@ def get(codes, start=None, end=None, last=0, multi=True, freq=None):
130
145
  return pd.concat(dfs, axis=1)
131
146
  else:
132
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
@@ -1,4 +1,9 @@
1
+ from typing import Dict, List, Optional, Union
2
+
3
+ import pandas as pd
4
+
1
5
  from bcb.sgs import get
6
+ from bcb.utils import DateInput
2
7
 
3
8
  """
4
9
  Dados da Economia Regional
@@ -119,7 +124,7 @@ NON_PERFORMING_LOANS_BY_STATE_TOTAL = {
119
124
  }
120
125
 
121
126
 
122
- def get_non_performing_loans_codes(states_or_region, mode="total"):
127
+ def get_non_performing_loans_codes(states_or_region: Union[str, List[str]], mode: str = "total") -> Dict[str, str]:
123
128
  is_state = False
124
129
  is_region = False
125
130
  states_or_region = [states_or_region] if isinstance(states_or_region, str) else states_or_region
@@ -151,7 +156,14 @@ def get_non_performing_loans_codes(states_or_region, mode="total"):
151
156
  return codes
152
157
 
153
158
 
154
- def get_non_performing_loans(states_or_region, mode="total", start=None, end=None, last=0, freq=None):
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:
155
167
  """Dados de inadimplência das operações de crédito.
156
168
 
157
169
  Esta função é um *wrapper* para o método para a função ``get`` do módulo ``sgs``,
@@ -1,21 +1,22 @@
1
- from datetime import datetime, date
2
-
1
+ from datetime import date, datetime
2
+ from typing import TypeAlias, Union
3
3
 
4
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"]
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
10
  }
11
11
  BRAZILIAN_STATES = []
12
12
  for state in BRAZILIAN_REGIONS.values():
13
13
  BRAZILIAN_STATES.extend(state)
14
14
 
15
+ DateInput: TypeAlias = Union[str, datetime, "Date", date]
16
+
15
17
 
16
18
  class Date:
17
- def __init__(self, d=None, format="%Y-%m-%d", mindate=date(1900, 1, 1)):
18
- d = d if d else mindate
19
+ def __init__(self, d: DateInput, format: str = "%Y-%m-%d") -> None:
19
20
  if isinstance(d, str):
20
21
  if d == "now" or d == "today":
21
22
  d = date.today()
@@ -29,27 +30,27 @@ class Date:
29
30
  pass
30
31
  else:
31
32
  raise ValueError()
32
- self.date = d
33
+ self.date: date = d
33
34
 
34
- def format(self, fmts="%Y-%m-%d"):
35
+ def format(self, fmts: str = "%Y-%m-%d") -> str:
35
36
  return datetime.strftime(self.date, fmts)
36
37
 
37
- def __gt__(self, other):
38
+ def __gt__(self, other) -> bool:
38
39
  return self.date > other.date
39
40
 
40
- def __ge__(self, other):
41
+ def __ge__(self, other) -> bool:
41
42
  return self.date >= other.date
42
43
 
43
- def __lt__(self, other):
44
+ def __lt__(self, other) -> bool:
44
45
  return self.date < other.date
45
46
 
46
- def __le__(self, other):
47
+ def __le__(self, other) -> bool:
47
48
  return self.date <= other.date
48
49
 
49
- def __eq__(self, other):
50
+ def __eq__(self, other) -> bool:
50
51
  return self.date == other.date
51
52
 
52
- def __repr__(self):
53
+ def __repr__(self) -> str:
53
54
  return self.format()
54
55
 
55
56
  __str__ = __repr__
@@ -1,10 +1,10 @@
1
1
  [tool.poetry]
2
2
  name = "python-bcb"
3
- version = "0.3.2"
3
+ version = "0.3.3"
4
4
  description = ""
5
5
  authors = ["wilsonfreitas <wilson.freitas@gmail.com>"]
6
6
  readme = "README.md"
7
- packages = [{include = "bcb"}]
7
+ packages = [{ include = "bcb" }]
8
8
 
9
9
  [tool.poetry.dependencies]
10
10
  python = ">= 3.10"
@@ -29,7 +29,7 @@ pygments = "^2.7"
29
29
  [tool.poetry.group.dev.dependencies]
30
30
  pycodestyle = ">= 2.9.1"
31
31
  ipykernel = ">= 6.15.2"
32
- black = {version = ">= 22.8.0", allow-prereleases = true}
32
+ black = { version = ">= 22.8.0", allow-prereleases = true }
33
33
  jupyter = "^1.1.1"
34
34
 
35
35
  [build-system]
File without changes
File without changes
File without changes
File without changes