Skip to content

Commit ce497ab

Browse files
committed
Updated documentation
1 parent 566f87a commit ce497ab

9 files changed

Lines changed: 94 additions & 68 deletions

File tree

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11

22
# Changelog
33

4+
## [0.1.9] -
5+
- Created class bcb.ODataAPI to directly wrap OData APIs
6+
- Updated documentation
7+
48
## [0.1.8] - 2022-09-10
59
- Updated documentation
610
- Migrated to poetry

bcb/sgs.py

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
from io import StringIO
32

43
import requests
@@ -42,52 +41,48 @@ def _codes(codes):
4241

4342

4443
def _get_url_and_payload(code, start_date, end_date, last):
45-
payload = {'formato': 'json'}
44+
payload = {"formato": "json"}
4645
if last == 0:
4746
if start_date is not None or end_date is not None:
48-
payload['dataInicial'] = Date(start_date).date.strftime('%d/%m/%Y')
49-
end_date = end_date if end_date else 'today'
50-
payload['dataFinal'] = Date(end_date).date.strftime('%d/%m/%Y')
51-
url = 'http://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados'\
52-
.format(code)
47+
payload["dataInicial"] = Date(start_date).date.strftime("%d/%m/%Y")
48+
end_date = end_date if end_date else "today"
49+
payload["dataFinal"] = Date(end_date).date.strftime("%d/%m/%Y")
50+
url = "http://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados".format(code)
5351
else:
54-
url = ('http://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados'
55-
'/ultimos/{}').format(code, last)
52+
url = (
53+
"http://api.bcb.gov.br/dados/serie/bcdata.sgs.{}/dados" "/ultimos/{}"
54+
).format(code, last)
5655

57-
return {
58-
'payload': payload,
59-
'url': url
60-
}
56+
return {"payload": payload, "url": url}
6157

6258

6359
def _format_df(df, code, freq):
64-
cns = {'data': 'Date', 'valor': code.name, 'datafim': 'enddate'}
60+
cns = {"data": "Date", "valor": code.name, "datafim": "enddate"}
6561
df = df.rename(columns=cns)
66-
if 'Date' in df:
67-
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
68-
if 'enddate' in df:
69-
df['enddate'] = pd.to_datetime(df['enddate'], format='%d/%m/%Y')
70-
df = df.set_index('Date')
62+
if "Date" in df:
63+
df["Date"] = pd.to_datetime(df["Date"], format="%d/%m/%Y")
64+
if "enddate" in df:
65+
df["enddate"] = pd.to_datetime(df["enddate"], format="%d/%m/%Y")
66+
df = df.set_index("Date")
7167
if freq:
7268
df.index = df.index.to_period(freq)
7369
return df
7470

7571

7672
def get(codes, start=None, end=None, last=0, multi=True, freq=None):
77-
'''
73+
"""
7874
Retorna um DataFrame pandas com séries temporais obtidas do SGS.
7975
8076
Parameters
8177
----------
8278
83-
symbols : {int, List[int], List[str], Dict[str:int]}
79+
codes : {int, List[int], List[str], Dict[str:int]}
8480
Este argumento pode ser uma das opções:
8581
86-
``int`` : código da série temporal
87-
88-
``list`` ou ``tuple`` : lista ou tupla com pares ``('nome', código)``
89-
90-
``dict`` : dicionário com pares ``{'nome': código}``
82+
* ``int`` : código da série temporal
83+
* ``list`` ou ``tuple`` : lista ou tupla com códigos
84+
* ``list`` ou ``tuple`` : lista ou tupla com pares ``('nome', código)``
85+
* ``dict`` : dicionário com pares ``{'nome': código}``
9186
9287
Com códigos numéricos é interessante utilizar os nomes com os códigos
9388
para definir os nomes nas colunas das séries temporais.
@@ -112,18 +107,18 @@ def get(codes, start=None, end=None, last=0, multi=True, freq=None):
112107
113108
``DataFrame`` :
114109
série temporal univariada ou multivariada,
115-
quando solicitado mais de uma série.
110+
quando solicitado mais de uma série (parâmetro ``multi=True``).
116111
117112
``list`` :
118113
lista com séries temporais univariadas,
119-
quando solicitado mais de uma série.
120-
'''
114+
quando solicitado mais de uma série (parâmetro ``multi=False``).
115+
"""
121116
dfs = []
122117
for code in _codes(codes):
123118
urd = _get_url_and_payload(code.value, start, end, last)
124-
res = requests.get(urd['url'], params=urd['payload'])
119+
res = requests.get(urd["url"], params=urd["payload"])
125120
if res.status_code != 200:
126-
raise Exception('Download error: code = {}'.format(code.value))
121+
raise Exception("Download error: code = {}".format(code.value))
127122
df = pd.read_json(StringIO(res.text))
128123
df = _format_df(df, code, freq)
129124
dfs.append(df)
-609 Bytes
Loading

docs/api.rst

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@
22
API
33
===
44

5-
Módulo :ref:`bcb.sgs`
6-
---------------------
5+
Módulo :py:mod:`bcb.sgs`
6+
------------------------
77

88
.. currentmodule:: bcb.sgs
99

1010
.. autosummary::
1111

1212
get
1313

14-
Módulo :ref:`bcb.currency`
15-
--------------------------
14+
Módulo :py:mod:`bcb.currency`
15+
-----------------------------
1616

1717
.. currentmodule:: bcb.currency
1818

@@ -22,24 +22,19 @@ Módulo :ref:`bcb.currency`
2222
get_currency_list
2323

2424

25-
APIs OData
26-
----------
25+
:ref:`APIs OData`
26+
-----------------
2727

2828
.. currentmodule:: bcb
2929

3030
.. autosummary::
3131

3232
Endpoint
3333
BaseODataAPI
34+
ODataAPI
3435
Expectativas
3536
PTAX
3637
IFDATA
3738
TaxaJuros
3839
SPI
3940
MercadoImobiliario
40-
TarifasBancariasPorInstituicaoFinanceira
41-
TarifasBancariasPorServico
42-
PostosAtendimentoEletronicoPorInstituicaoFinanceira
43-
PostosAtendimentoCorrespondentesPorInstituicaoFinanceira
44-
EstatisticasSTR
45-
DinheiroCirculacao

docs/conf.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,20 @@
6060
# The theme to use for HTML and HTML Help pages. See the documentation for
6161
# a list of builtin themes.
6262
#
63-
html_theme = "pydata_sphinx_theme"
63+
html_theme = "furo"
6464
html_theme_options = {
65-
"external_links": [],
66-
"github_url": "https://github.com/wilsonfreitas/python-bcb",
65+
"source_repository": "https://github.com/wilsonfreitas/python-bcb/",
66+
"source_branch": "main",
67+
"source_directory": "docs/",
6768
}
69+
# html_theme = "alabaster"
70+
# html_theme_options = {
71+
# "description": "Interface em Python para o portal de dados abertos do BCB",
72+
# "github_user": "wilsonfreitas",
73+
# "github_repo": "python-bcb",
74+
# "fixed_sidebar": True,
75+
# }
76+
6877

6978
# Add any paths that contain custom static files (such as style sheets) here,
7079
# relative to this directory. They are copied after the builtin static files,

docs/currency.rst

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
Moedas
2-
######
2+
======
33

44
O pacote tem 2 APIs que dão acesso a informações de moedas.
55

@@ -11,22 +11,24 @@ O pacote tem 2 APIs que dão acesso a informações de moedas.
1111
Conversor de Moedas
1212
-------------------
1313

14-
O módulo ``currency`` obtem dados de moedas do conversor de moedas do Banco Central através de webscraping.
14+
.. automodule:: bcb.currency
1515

16-
.. currentmodule:: bcb.currency
16+
O módulo :py:mod:`bcb.currency` obtem dados de moedas do conversor de moedas do Banco Central através de webscraping.
1717

18+
.. currentmodule:: bcb.currency
1819

1920
.. autofunction:: get
2021

2122

2223
.. ipython:: python
2324
2425
from bcb import currency
25-
df = currency.get(['USD', 'EUR'], start='2000-01-01', end='2021-01-01', side='ask')
26+
df = currency.get(['USD', 'EUR'],
27+
start='2000-01-01',
28+
end='2021-01-01',
29+
side='ask')
2630
df.head()
2731
28-
.. ipython:: python
29-
3032
@savefig currency1.png
3133
df.plot(figsize=(12, 6));
3234
@@ -46,7 +48,7 @@ API OData
4648

4749
__ documentacao_
4850

49-
Diferente da interface _`currency`, os dados são obtidos a partir da `API de Moedas`__.
51+
Diferente do módulo :py:mod:`bcb.currency`, aqui os dados são obtidos a partir da `API de Moedas`__.
5052

5153
.. currentmodule:: bcb
5254

@@ -65,10 +67,28 @@ Diferente da interface _`currency`, os dados são obtidos a partir da `API de Mo
6567
6668
ptax.describe('Moedas')
6769
70+
ep = ptax.get_endpoint('Moedas')
71+
ep.query().limit(10).collect()
72+
6873
.. ipython:: python
6974
70-
ptax.describe('CotacaoMoedaPeriodoFechamento')
75+
ptax.describe('CotacaoMoedaDia')
76+
77+
ep = ptax.get_endpoint('CotacaoMoedaDia')
78+
(ep.query()
79+
.parameters(moeda='AUD', dataCotacao='1/31/2022')
80+
.collect())
81+
82+
É importante notar que as datas estão no formato dia/mês/ano e os números não
83+
são preenchidos com 0 para ter 2 dígitos.
7184

7285
.. ipython:: python
7386
7487
ptax.describe('CotacaoMoedaPeriodo')
88+
89+
ep = ptax.get_endpoint('CotacaoMoedaPeriodo')
90+
(ep.query()
91+
.parameters(moeda='AUD',
92+
dataInicial='1/1/2022',
93+
dataFinalCotacao='1/5/2022')
94+
.collect())

docs/index.rst

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,6 @@
66
python-bcb
77
==========
88

9-
.. toctree::
10-
:maxdepth: 1
11-
:caption: Conteúdo:
12-
13-
sgs
14-
currency
15-
expectativas
16-
taxajuros
17-
odata
18-
api
19-
209
**python-bcb** é uma interface em Python estruturada para obter informações
2110
da API de dados abertos do `Banco Central do Brasil <https://www.bcb.gov.br>`_.
2211

@@ -87,6 +76,16 @@ Uso
8776
sgs.get(('IPCA', 433), last=12)
8877
8978
79+
.. toctree::
80+
:maxdepth: 1
81+
82+
sgs
83+
currency
84+
expectativas
85+
taxajuros
86+
odata
87+
api
88+
9089
Índices e tabelas
9190
==================
9291

docs/sgs.rst

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
SGS
2-
###
2+
===
33

44
O módulo ``sgs`` obtem os dados do webservice do Banco Central,
55
interface json do serviço BCData/SGS -
66
`Sistema Gerenciador de Séries Temporais (SGS) <https://www3.bcb.gov.br/sgspub/localizarseries/localizarSeries.do?method=prepararTelaLocalizarSeries>`_.
77

88
.. automodule:: bcb.sgs
99

10-
Função :ref:`bcb.sgs.get`
11-
-------------------------
10+
Função bcb.sgs.get
11+
--------------------
1212

1313
.. currentmodule:: bcb.sgs
1414

1515
.. autofunction:: get
1616

17+
Exemplo
18+
-------
19+
1720
.. ipython:: python
1821
1922
from bcb import sgs

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Sphinx = "^5.1.1"
2121
pydata-sphinx-theme = "^0.10.1"
2222
matplotlib = "^3.5.3"
2323
ipython = "^8.5.0"
24+
furo = "^2022.6.21"
2425

2526

2627
[tool.poetry.group.dev.dependencies]

0 commit comments

Comments
 (0)