Skip to content

Commit dfb2e81

Browse files
committed
Enhance type annotations for functions in currency module for improved clarity and type safety
Issue #26
1 parent 3dcaed5 commit dfb2e81

1 file changed

Lines changed: 17 additions & 20 deletions

File tree

bcb/currency.py

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
import re
22
import warnings
3-
from io import BytesIO, StringIO
43
from datetime import date, timedelta
4+
from io import BytesIO, StringIO
5+
from typing import List, Union
56

7+
import numpy as np
8+
import pandas as pd
69
import requests
710
from lxml import html
811

9-
import pandas as pd
10-
import numpy as np
11-
12-
from .utils import Date
12+
from .utils import Date, DateInput
1313

1414
"""
1515
O módulo :py:mod:`bcb.currency` tem como objetivo fazer consultas no site do conversor de moedas do BCB.
1616
"""
1717

1818

19-
def _currency_url(currency_id, start_date, end_date):
19+
def _currency_url(currency_id: str, start_date: DateInput, end_date: DateInput) -> str:
2020
start_date = Date(start_date)
2121
end_date = Date(end_date)
2222
url = (
@@ -30,14 +30,11 @@ def _currency_url(currency_id, start_date, end_date):
3030
CACHE = dict()
3131

3232

33-
def _currency_id_list():
33+
def _currency_id_list() -> pd.DataFrame:
3434
if CACHE.get("TEMP_CURRENCY_ID_LIST") is not None:
3535
return CACHE.get("TEMP_CURRENCY_ID_LIST")
3636
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"
4138
res = requests.get(url1)
4239
if res.status_code != 200:
4340
msg = f"BCB API Request error, status code = {res.status_code}"
@@ -52,7 +49,7 @@ def _currency_id_list():
5249
return df
5350

5451

55-
def _get_valid_currency_list(_date, n=0):
52+
def _get_valid_currency_list(_date: date, n: int = 0) -> requests.models.Response:
5653
url2 = f"http://www4.bcb.gov.br/Download/fechamento/M{_date:%Y%m%d}.csv"
5754
try:
5855
res = requests.get(url2)
@@ -66,7 +63,7 @@ def _get_valid_currency_list(_date, n=0):
6663
return _get_valid_currency_list(_date - timedelta(1), 0)
6764

6865

69-
def get_currency_list():
66+
def get_currency_list() -> pd.DataFrame:
7067
"""
7168
Listagem com todas as moedas disponíveis na API e suas configurações de paridade.
7269
@@ -99,14 +96,14 @@ def get_currency_list():
9996
return df
10097

10198

102-
def _get_currency_id(symbol):
99+
def _get_currency_id(symbol: str) -> int:
103100
id_list = _currency_id_list()
104101
all_currencies = get_currency_list()
105102
x = pd.merge(id_list, all_currencies, on=["name"])
106103
return np.max(x.loc[x["symbol"] == symbol, "id"])
107104

108105

109-
def _get_symbol(symbol, start_date, end_date):
106+
def _get_symbol(symbol: str, start_date: DateInput, end_date: DateInput) -> pd.DataFrame:
110107
cid = _get_currency_id(symbol)
111108
url = _currency_url(cid, start_date, end_date)
112109
res = requests.get(url)
@@ -123,9 +120,7 @@ def _get_symbol(symbol, start_date, end_date):
123120
return None
124121

125122
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)
129124
df = df.assign(
130125
Date=lambda x: pd.to_datetime(x["Date"], format="%d%m%Y"),
131126
bid=lambda x: x["bid"].str.replace(",", ".").astype(np.float64),
@@ -139,7 +134,9 @@ def _get_symbol(symbol, start_date, end_date):
139134
return df1
140135

141136

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:
143140
"""
144141
Retorna um DataFrame pandas com séries temporais com taxas de câmbio.
145142
@@ -189,4 +186,4 @@ def get(symbols, start, end, side="ask", groupby="symbol"):
189186
else:
190187
raise Exception(f"Unknown side value, use: bid, ask, both")
191188
else:
192-
return None
189+
raise Exception(f"Currency not found: {symbols}")

0 commit comments

Comments
 (0)