dadosb3 0.1.0__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.
- dadosb3-0.1.0/LICENSE +9 -0
- dadosb3-0.1.0/PKG-INFO +82 -0
- dadosb3-0.1.0/README.md +59 -0
- dadosb3-0.1.0/dadosb3/__init__.py +175 -0
- dadosb3-0.1.0/dadosb3.egg-info/PKG-INFO +82 -0
- dadosb3-0.1.0/dadosb3.egg-info/SOURCES.txt +10 -0
- dadosb3-0.1.0/dadosb3.egg-info/dependency_links.txt +1 -0
- dadosb3-0.1.0/dadosb3.egg-info/requires.txt +1 -0
- dadosb3-0.1.0/dadosb3.egg-info/top_level.txt +1 -0
- dadosb3-0.1.0/pyproject.toml +32 -0
- dadosb3-0.1.0/setup.cfg +4 -0
- dadosb3-0.1.0/tests/test_client.py +85 -0
dadosb3-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lemon Tech (Dados B3)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
dadosb3-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dadosb3
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cliente Python da API Dados B3: fundamentos auditáveis de ações, FIIs e ETFs da bolsa brasileira (CVM/B3), com metodologia pública.
|
|
5
|
+
Author-email: Dados B3 <contato@dadosb3.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://dadosb3.com
|
|
8
|
+
Project-URL: Documentation, https://dadosb3.com/api
|
|
9
|
+
Project-URL: Methodology, https://dadosb3.com/metodologia
|
|
10
|
+
Project-URL: MCP connector, https://github.com/Val7h/dados-b3-mcp
|
|
11
|
+
Keywords: b3,bovespa,cvm,fundamentos,ações,fii,etf,brasil,finance,api
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: httpx>=0.24
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# dadosb3
|
|
25
|
+
|
|
26
|
+
Cliente Python da [API Dados B3](https://dadosb3.com): fundamentos **auditáveis**
|
|
27
|
+
das companhias abertas brasileiras (2010–hoje), fundos imobiliários (FIIs) e
|
|
28
|
+
ETFs, com metodologia pública. Cada número carrega a conta CVM de origem; os
|
|
29
|
+
múltiplos são ponto-no-tempo (preço do 1º pregão a partir da chegada do balanço
|
|
30
|
+
à CVM); nada é publicado sem a bateria de invariantes passar.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install dadosb3
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from dadosb3 import DadosB3
|
|
38
|
+
|
|
39
|
+
api = DadosB3() # sem chave: WEGE3, BOVA11, MXRF11, rankings de ETF, /hoje, /saude
|
|
40
|
+
api.indicadores("WEGE3")["anos"] # ROE, ROIC, margens... com a conta CVM de cada número
|
|
41
|
+
api.multiplos("WEGE3") # P/L, P/VP, EV/EBITDA ponto-no-tempo
|
|
42
|
+
api.etf("BOVA11") # cota diária, ágio/deságio, taxa efetiva, carteira
|
|
43
|
+
api.auditar_amostra(semente=4242) # sorteie a SUA amostra e confira contra a CVM
|
|
44
|
+
|
|
45
|
+
api = DadosB3(chave="sua-chave") # ou DADOS_B3_API_KEY no ambiente
|
|
46
|
+
api.screener(roic_min=0.15, dl_ebitda_max=2, ano=2024)
|
|
47
|
+
api.fiis_screener(pvp_max=0.9, dy_min=0.10)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Chave grátis (200 consultas/dia, sem cartão) ou Pro em
|
|
51
|
+
[dadosb3.com/assinar](https://dadosb3.com/assinar). Documentação da API em
|
|
52
|
+
[dadosb3.com/api](https://dadosb3.com/api); metodologia em
|
|
53
|
+
[dadosb3.com/metodologia](https://dadosb3.com/metodologia); para quem é (e para
|
|
54
|
+
quem não é) em [dadosb3.com/para-quem](https://dadosb3.com/para-quem).
|
|
55
|
+
|
|
56
|
+
## Métodos
|
|
57
|
+
|
|
58
|
+
| Método | Rota | Chave? |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `empresas()` | `/empresas` | não |
|
|
61
|
+
| `indicadores(t)`, `multiplos(t)`, `fatos(t)`, `dividendos(t)`, `scores(t)`, `reapresentacoes(t)`, `trimestres(t)` | `/empresas/{t}/...` | WEGE3 não; demais sim |
|
|
62
|
+
| `screener(ano=, **faixas)` | `/screener` | sim |
|
|
63
|
+
| `fii(t)` | `/fiis/{t}` | MXRF11 não; demais sim |
|
|
64
|
+
| `fiis_ranking()`, `fiis_screener(**faixas)` | `/fiis`, `/fiis/screener` | sim |
|
|
65
|
+
| `etfs_ranking()` | `/etfs` | não |
|
|
66
|
+
| `etf(t)` | `/etfs/{t}` | BOVA11 não; demais sim |
|
|
67
|
+
| `hoje()`, `saude()`, `dicionario()` | `/hoje`, `/saude`, `/dicionario` | não |
|
|
68
|
+
| `auditar_amostra(semente, n=25)` | `/auditoria/amostra/{semente}/{n}` | não |
|
|
69
|
+
|
|
70
|
+
Erros: `ChaveNecessaria` (401), `NaoEncontrado` (404), `ErroDadosB3` (demais),
|
|
71
|
+
todos com `.status` e `.detalhe` (o corpo da resposta da API).
|
|
72
|
+
|
|
73
|
+
## Limites, ditos antes
|
|
74
|
+
|
|
75
|
+
Preço só de fim de dia (COTAHIST); sem tratamento de viés de sobrevivência
|
|
76
|
+
(companhia que saiu da bolsa não está na base); sem composição histórica de
|
|
77
|
+
índice; a base começa em 2010. A lista completa está em
|
|
78
|
+
[dadosb3.com/o-que-nao-resolvemos](https://dadosb3.com/o-que-nao-resolvemos).
|
|
79
|
+
|
|
80
|
+
Não é recomendação de investimento. Fontes: CVM (dados abertos, ODbL) e B3
|
|
81
|
+
(COTAHIST). Projeto independente, não afiliado à B3 nem à CVM. Licença deste
|
|
82
|
+
cliente: MIT. Conector MCP: [Val7h/dados-b3-mcp](https://github.com/Val7h/dados-b3-mcp).
|
dadosb3-0.1.0/README.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# dadosb3
|
|
2
|
+
|
|
3
|
+
Cliente Python da [API Dados B3](https://dadosb3.com): fundamentos **auditáveis**
|
|
4
|
+
das companhias abertas brasileiras (2010–hoje), fundos imobiliários (FIIs) e
|
|
5
|
+
ETFs, com metodologia pública. Cada número carrega a conta CVM de origem; os
|
|
6
|
+
múltiplos são ponto-no-tempo (preço do 1º pregão a partir da chegada do balanço
|
|
7
|
+
à CVM); nada é publicado sem a bateria de invariantes passar.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install dadosb3
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from dadosb3 import DadosB3
|
|
15
|
+
|
|
16
|
+
api = DadosB3() # sem chave: WEGE3, BOVA11, MXRF11, rankings de ETF, /hoje, /saude
|
|
17
|
+
api.indicadores("WEGE3")["anos"] # ROE, ROIC, margens... com a conta CVM de cada número
|
|
18
|
+
api.multiplos("WEGE3") # P/L, P/VP, EV/EBITDA ponto-no-tempo
|
|
19
|
+
api.etf("BOVA11") # cota diária, ágio/deságio, taxa efetiva, carteira
|
|
20
|
+
api.auditar_amostra(semente=4242) # sorteie a SUA amostra e confira contra a CVM
|
|
21
|
+
|
|
22
|
+
api = DadosB3(chave="sua-chave") # ou DADOS_B3_API_KEY no ambiente
|
|
23
|
+
api.screener(roic_min=0.15, dl_ebitda_max=2, ano=2024)
|
|
24
|
+
api.fiis_screener(pvp_max=0.9, dy_min=0.10)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Chave grátis (200 consultas/dia, sem cartão) ou Pro em
|
|
28
|
+
[dadosb3.com/assinar](https://dadosb3.com/assinar). Documentação da API em
|
|
29
|
+
[dadosb3.com/api](https://dadosb3.com/api); metodologia em
|
|
30
|
+
[dadosb3.com/metodologia](https://dadosb3.com/metodologia); para quem é (e para
|
|
31
|
+
quem não é) em [dadosb3.com/para-quem](https://dadosb3.com/para-quem).
|
|
32
|
+
|
|
33
|
+
## Métodos
|
|
34
|
+
|
|
35
|
+
| Método | Rota | Chave? |
|
|
36
|
+
|---|---|---|
|
|
37
|
+
| `empresas()` | `/empresas` | não |
|
|
38
|
+
| `indicadores(t)`, `multiplos(t)`, `fatos(t)`, `dividendos(t)`, `scores(t)`, `reapresentacoes(t)`, `trimestres(t)` | `/empresas/{t}/...` | WEGE3 não; demais sim |
|
|
39
|
+
| `screener(ano=, **faixas)` | `/screener` | sim |
|
|
40
|
+
| `fii(t)` | `/fiis/{t}` | MXRF11 não; demais sim |
|
|
41
|
+
| `fiis_ranking()`, `fiis_screener(**faixas)` | `/fiis`, `/fiis/screener` | sim |
|
|
42
|
+
| `etfs_ranking()` | `/etfs` | não |
|
|
43
|
+
| `etf(t)` | `/etfs/{t}` | BOVA11 não; demais sim |
|
|
44
|
+
| `hoje()`, `saude()`, `dicionario()` | `/hoje`, `/saude`, `/dicionario` | não |
|
|
45
|
+
| `auditar_amostra(semente, n=25)` | `/auditoria/amostra/{semente}/{n}` | não |
|
|
46
|
+
|
|
47
|
+
Erros: `ChaveNecessaria` (401), `NaoEncontrado` (404), `ErroDadosB3` (demais),
|
|
48
|
+
todos com `.status` e `.detalhe` (o corpo da resposta da API).
|
|
49
|
+
|
|
50
|
+
## Limites, ditos antes
|
|
51
|
+
|
|
52
|
+
Preço só de fim de dia (COTAHIST); sem tratamento de viés de sobrevivência
|
|
53
|
+
(companhia que saiu da bolsa não está na base); sem composição histórica de
|
|
54
|
+
índice; a base começa em 2010. A lista completa está em
|
|
55
|
+
[dadosb3.com/o-que-nao-resolvemos](https://dadosb3.com/o-que-nao-resolvemos).
|
|
56
|
+
|
|
57
|
+
Não é recomendação de investimento. Fontes: CVM (dados abertos, ODbL) e B3
|
|
58
|
+
(COTAHIST). Projeto independente, não afiliado à B3 nem à CVM. Licença deste
|
|
59
|
+
cliente: MIT. Conector MCP: [Val7h/dados-b3-mcp](https://github.com/Val7h/dados-b3-mcp).
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""dadosb3 — cliente Python da API Dados B3 (https://dadosb3.com).
|
|
2
|
+
|
|
3
|
+
Fundamentos auditáveis das companhias abertas brasileiras (2010–hoje), fundos
|
|
4
|
+
imobiliários (FIIs) e ETFs, com metodologia pública: cada número carrega a
|
|
5
|
+
conta CVM de origem, os múltiplos são ponto-no-tempo (preço do 1º pregão a
|
|
6
|
+
partir da chegada do balanço à CVM) e nada é publicado sem a bateria de
|
|
7
|
+
invariantes passar.
|
|
8
|
+
|
|
9
|
+
from dadosb3 import DadosB3
|
|
10
|
+
api = DadosB3() # sem chave: WEGE3, BOVA11, MXRF11, rankings, saúde
|
|
11
|
+
api = DadosB3(chave="sua-chave") # chave grátis (200/dia) ou Pro em https://dadosb3.com/assinar
|
|
12
|
+
api.indicadores("WEGE3") # ROE, ROIC, margens... com a conta CVM de cada número
|
|
13
|
+
api.multiplos("WEGE3") # P/L, P/VP, EV/EBITDA ponto-no-tempo
|
|
14
|
+
api.etf("BOVA11") # cota diária, ágio/deságio, taxa efetiva, carteira
|
|
15
|
+
api.auditar_amostra(semente=4242) # sorteie a SUA amostra e confira contra a CVM
|
|
16
|
+
|
|
17
|
+
Não é recomendação de investimento. Fontes: CVM (dados abertos, ODbL) e B3
|
|
18
|
+
(COTAHIST fim de dia).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import os
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import httpx
|
|
27
|
+
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
__all__ = ["DadosB3", "ErroDadosB3", "ChaveNecessaria", "NaoEncontrado"]
|
|
30
|
+
|
|
31
|
+
URL_PADRAO = "https://dadosb3.com"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ErroDadosB3(Exception):
|
|
35
|
+
"""Erro devolvido pela API (status >= 400) com o corpo em `detalhe`."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, status: int, detalhe: Any):
|
|
38
|
+
self.status, self.detalhe = status, detalhe
|
|
39
|
+
super().__init__(f"HTTP {status}: {detalhe}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ChaveNecessaria(ErroDadosB3):
|
|
43
|
+
"""401: a rota exige chave (grátis ou Pro). WEGE3, BOVA11 e MXRF11 são abertos."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class NaoEncontrado(ErroDadosB3):
|
|
47
|
+
"""404: ticker ou recurso inexistente."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class DadosB3:
|
|
51
|
+
"""Cliente síncrono. Cada método devolve o JSON da API como `dict`.
|
|
52
|
+
|
|
53
|
+
Parâmetros:
|
|
54
|
+
chave — X-API-Key. Também lida de `DADOS_B3_API_KEY`.
|
|
55
|
+
url — base da API (padrão https://dadosb3.com).
|
|
56
|
+
timeout — segundos (padrão 30).
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(self, chave: str | None = None, url: str = URL_PADRAO,
|
|
60
|
+
timeout: float = 30, transport: httpx.BaseTransport | None = None):
|
|
61
|
+
self.chave = chave or os.environ.get("DADOS_B3_API_KEY", "")
|
|
62
|
+
self.url = url.rstrip("/")
|
|
63
|
+
cabecalhos = {"Accept": "application/json",
|
|
64
|
+
"User-Agent": f"dadosb3-python/{__version__}"}
|
|
65
|
+
if self.chave:
|
|
66
|
+
cabecalhos["X-API-Key"] = self.chave
|
|
67
|
+
self._http = httpx.Client(base_url=self.url, headers=cabecalhos,
|
|
68
|
+
timeout=timeout, transport=transport)
|
|
69
|
+
|
|
70
|
+
# ── infra ────────────────────────────────────────────────────────────
|
|
71
|
+
def _get(self, caminho: str, **params: Any) -> dict:
|
|
72
|
+
params = {k: v for k, v in params.items() if v not in (None, "")}
|
|
73
|
+
r = self._http.get(caminho, params=params)
|
|
74
|
+
if r.status_code >= 400:
|
|
75
|
+
try:
|
|
76
|
+
corpo = r.json()
|
|
77
|
+
except ValueError:
|
|
78
|
+
corpo = r.text
|
|
79
|
+
if r.status_code == 401:
|
|
80
|
+
raise ChaveNecessaria(401, corpo)
|
|
81
|
+
if r.status_code == 404:
|
|
82
|
+
raise NaoEncontrado(404, corpo)
|
|
83
|
+
raise ErroDadosB3(r.status_code, corpo)
|
|
84
|
+
return r.json()
|
|
85
|
+
|
|
86
|
+
def close(self) -> None:
|
|
87
|
+
self._http.close()
|
|
88
|
+
|
|
89
|
+
def __enter__(self) -> "DadosB3":
|
|
90
|
+
return self
|
|
91
|
+
|
|
92
|
+
def __exit__(self, *_: Any) -> None:
|
|
93
|
+
self.close()
|
|
94
|
+
|
|
95
|
+
# ── companhias ───────────────────────────────────────────────────────
|
|
96
|
+
def empresas(self) -> dict:
|
|
97
|
+
"""Todas as companhias cobertas (nome, CNPJ, ticker). Aberto."""
|
|
98
|
+
return self._get("/empresas")
|
|
99
|
+
|
|
100
|
+
def indicadores(self, ticker: str) -> dict:
|
|
101
|
+
"""ROE, ROIC, margens, crescimento, dívida líquida/EBITDA — série anual
|
|
102
|
+
desde 2010, cada número com a conta CVM de origem."""
|
|
103
|
+
return self._get(f"/empresas/{ticker}/indicadores")
|
|
104
|
+
|
|
105
|
+
def multiplos(self, ticker: str) -> dict:
|
|
106
|
+
"""P/L, P/VP, EV/EBITDA ponto-no-tempo (preço do 1º pregão a partir da
|
|
107
|
+
publicação real do balanço) e P/L TTM."""
|
|
108
|
+
return self._get(f"/empresas/{ticker}/multiplos")
|
|
109
|
+
|
|
110
|
+
def fatos(self, ticker: str, trimestral: bool = False) -> dict:
|
|
111
|
+
"""Contas padronizadas (receita, lucro, PL...) com a conta CVM de cada uma."""
|
|
112
|
+
return self._get(f"/empresas/{ticker}/fatos", trimestral=str(trimestral).lower())
|
|
113
|
+
|
|
114
|
+
def dividendos(self, ticker: str) -> dict:
|
|
115
|
+
"""Proventos, resumo anual e dividend yield de 12 meses."""
|
|
116
|
+
return self._get(f"/empresas/{ticker}/dividendos")
|
|
117
|
+
|
|
118
|
+
def scores(self, ticker: str) -> dict:
|
|
119
|
+
"""Piotroski F-Score (nove critérios abertos) e critério de Graham."""
|
|
120
|
+
return self._get(f"/empresas/{ticker}/scores")
|
|
121
|
+
|
|
122
|
+
def reapresentacoes(self, ticker: str) -> dict:
|
|
123
|
+
"""Balanços republicados: versão original e revisada lado a lado."""
|
|
124
|
+
return self._get(f"/empresas/{ticker}/reapresentacoes")
|
|
125
|
+
|
|
126
|
+
def trimestres(self, ticker: str) -> dict:
|
|
127
|
+
"""Série trimestral (1T/2T/3T como publicados), preço do trimestre, TTM."""
|
|
128
|
+
return self._get(f"/empresas/{ticker}/trimestres")
|
|
129
|
+
|
|
130
|
+
def screener(self, ano: int | None = None, limite: int = 100, **filtros: float) -> dict:
|
|
131
|
+
"""Filtra ações por faixas: roic_min=0.15, dl_ebitda_max=2, margem_liquida_min=0.1...
|
|
132
|
+
Sem `ano`, usa o último exercício de cada companhia. Exige chave."""
|
|
133
|
+
return self._get("/screener", ano=ano, limite=limite, **filtros)
|
|
134
|
+
|
|
135
|
+
# ── FIIs ─────────────────────────────────────────────────────────────
|
|
136
|
+
def fii(self, ticker: str) -> dict:
|
|
137
|
+
"""Um FII: P/VP ponto-no-tempo, DY 12m, vacância, rendimentos. MXRF11 é aberto."""
|
|
138
|
+
return self._get(f"/fiis/{ticker}")
|
|
139
|
+
|
|
140
|
+
def fiis_ranking(self) -> dict:
|
|
141
|
+
"""Mais descontados (P/VP), maiores DY 12m, mediana por segmento. Exige chave."""
|
|
142
|
+
return self._get("/fiis")
|
|
143
|
+
|
|
144
|
+
def fiis_screener(self, **filtros: Any) -> dict:
|
|
145
|
+
"""Filtra FIIs: pvp_min, pvp_max, dy_min, dy_max (fração), segmento, cotistas_min, limite."""
|
|
146
|
+
return self._get("/fiis/screener", **filtros)
|
|
147
|
+
|
|
148
|
+
# ── ETFs ─────────────────────────────────────────────────────────────
|
|
149
|
+
def etfs_ranking(self) -> dict:
|
|
150
|
+
"""Mais negociados, maior patrimônio, maior ágio/deságio sobre a cota do
|
|
151
|
+
dia, retorno 12m pela cota, menor taxa EFETIVA. Aberto."""
|
|
152
|
+
return self._get("/etfs")
|
|
153
|
+
|
|
154
|
+
def etf(self, ticker: str) -> dict:
|
|
155
|
+
"""Um ETF: cota diária (FNET), ágio/deságio, taxa efetiva mensal, carteira
|
|
156
|
+
(CDA) e sobreposição com pares. BOVA11 é aberto."""
|
|
157
|
+
return self._get(f"/etfs/{ticker}")
|
|
158
|
+
|
|
159
|
+
# ── mercado, metodologia, auditoria ──────────────────────────────────
|
|
160
|
+
def hoje(self) -> dict:
|
|
161
|
+
"""O que mudou nos últimos 30 dias: balanços, reenvios, proventos, eventos. Aberto."""
|
|
162
|
+
return self._get("/hoje")
|
|
163
|
+
|
|
164
|
+
def saude(self) -> dict:
|
|
165
|
+
"""Cobertura atual, versão do dado e última ingestão. Aberto."""
|
|
166
|
+
return self._get("/saude")
|
|
167
|
+
|
|
168
|
+
def dicionario(self) -> dict:
|
|
169
|
+
"""Fórmula, contas CVM e base do lucro de cada indicador. Aberto."""
|
|
170
|
+
return self._get("/dicionario")
|
|
171
|
+
|
|
172
|
+
def auditar_amostra(self, semente: int, n: int = 25) -> dict:
|
|
173
|
+
"""Sorteia `n` casos com a SUA semente para refazer cada número contra o
|
|
174
|
+
arquivo da CVM (fórmula, conta, onde procurar). Determinístico. Aberto."""
|
|
175
|
+
return self._get(f"/auditoria/amostra/{int(semente)}/{int(n)}")
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dadosb3
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cliente Python da API Dados B3: fundamentos auditáveis de ações, FIIs e ETFs da bolsa brasileira (CVM/B3), com metodologia pública.
|
|
5
|
+
Author-email: Dados B3 <contato@dadosb3.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://dadosb3.com
|
|
8
|
+
Project-URL: Documentation, https://dadosb3.com/api
|
|
9
|
+
Project-URL: Methodology, https://dadosb3.com/metodologia
|
|
10
|
+
Project-URL: MCP connector, https://github.com/Val7h/dados-b3-mcp
|
|
11
|
+
Keywords: b3,bovespa,cvm,fundamentos,ações,fii,etf,brasil,finance,api
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: httpx>=0.24
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# dadosb3
|
|
25
|
+
|
|
26
|
+
Cliente Python da [API Dados B3](https://dadosb3.com): fundamentos **auditáveis**
|
|
27
|
+
das companhias abertas brasileiras (2010–hoje), fundos imobiliários (FIIs) e
|
|
28
|
+
ETFs, com metodologia pública. Cada número carrega a conta CVM de origem; os
|
|
29
|
+
múltiplos são ponto-no-tempo (preço do 1º pregão a partir da chegada do balanço
|
|
30
|
+
à CVM); nada é publicado sem a bateria de invariantes passar.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install dadosb3
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from dadosb3 import DadosB3
|
|
38
|
+
|
|
39
|
+
api = DadosB3() # sem chave: WEGE3, BOVA11, MXRF11, rankings de ETF, /hoje, /saude
|
|
40
|
+
api.indicadores("WEGE3")["anos"] # ROE, ROIC, margens... com a conta CVM de cada número
|
|
41
|
+
api.multiplos("WEGE3") # P/L, P/VP, EV/EBITDA ponto-no-tempo
|
|
42
|
+
api.etf("BOVA11") # cota diária, ágio/deságio, taxa efetiva, carteira
|
|
43
|
+
api.auditar_amostra(semente=4242) # sorteie a SUA amostra e confira contra a CVM
|
|
44
|
+
|
|
45
|
+
api = DadosB3(chave="sua-chave") # ou DADOS_B3_API_KEY no ambiente
|
|
46
|
+
api.screener(roic_min=0.15, dl_ebitda_max=2, ano=2024)
|
|
47
|
+
api.fiis_screener(pvp_max=0.9, dy_min=0.10)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Chave grátis (200 consultas/dia, sem cartão) ou Pro em
|
|
51
|
+
[dadosb3.com/assinar](https://dadosb3.com/assinar). Documentação da API em
|
|
52
|
+
[dadosb3.com/api](https://dadosb3.com/api); metodologia em
|
|
53
|
+
[dadosb3.com/metodologia](https://dadosb3.com/metodologia); para quem é (e para
|
|
54
|
+
quem não é) em [dadosb3.com/para-quem](https://dadosb3.com/para-quem).
|
|
55
|
+
|
|
56
|
+
## Métodos
|
|
57
|
+
|
|
58
|
+
| Método | Rota | Chave? |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `empresas()` | `/empresas` | não |
|
|
61
|
+
| `indicadores(t)`, `multiplos(t)`, `fatos(t)`, `dividendos(t)`, `scores(t)`, `reapresentacoes(t)`, `trimestres(t)` | `/empresas/{t}/...` | WEGE3 não; demais sim |
|
|
62
|
+
| `screener(ano=, **faixas)` | `/screener` | sim |
|
|
63
|
+
| `fii(t)` | `/fiis/{t}` | MXRF11 não; demais sim |
|
|
64
|
+
| `fiis_ranking()`, `fiis_screener(**faixas)` | `/fiis`, `/fiis/screener` | sim |
|
|
65
|
+
| `etfs_ranking()` | `/etfs` | não |
|
|
66
|
+
| `etf(t)` | `/etfs/{t}` | BOVA11 não; demais sim |
|
|
67
|
+
| `hoje()`, `saude()`, `dicionario()` | `/hoje`, `/saude`, `/dicionario` | não |
|
|
68
|
+
| `auditar_amostra(semente, n=25)` | `/auditoria/amostra/{semente}/{n}` | não |
|
|
69
|
+
|
|
70
|
+
Erros: `ChaveNecessaria` (401), `NaoEncontrado` (404), `ErroDadosB3` (demais),
|
|
71
|
+
todos com `.status` e `.detalhe` (o corpo da resposta da API).
|
|
72
|
+
|
|
73
|
+
## Limites, ditos antes
|
|
74
|
+
|
|
75
|
+
Preço só de fim de dia (COTAHIST); sem tratamento de viés de sobrevivência
|
|
76
|
+
(companhia que saiu da bolsa não está na base); sem composição histórica de
|
|
77
|
+
índice; a base começa em 2010. A lista completa está em
|
|
78
|
+
[dadosb3.com/o-que-nao-resolvemos](https://dadosb3.com/o-que-nao-resolvemos).
|
|
79
|
+
|
|
80
|
+
Não é recomendação de investimento. Fontes: CVM (dados abertos, ODbL) e B3
|
|
81
|
+
(COTAHIST). Projeto independente, não afiliado à B3 nem à CVM. Licença deste
|
|
82
|
+
cliente: MIT. Conector MCP: [Val7h/dados-b3-mcp](https://github.com/Val7h/dados-b3-mcp).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
httpx>=0.24
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dadosb3
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dadosb3"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Cliente Python da API Dados B3: fundamentos auditáveis de ações, FIIs e ETFs da bolsa brasileira (CVM/B3), com metodologia pública."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [{ name = "Dados B3", email = "contato@dadosb3.com" }]
|
|
14
|
+
keywords = ["b3", "bovespa", "cvm", "fundamentos", "ações", "fii", "etf", "brasil", "finance", "api"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
22
|
+
]
|
|
23
|
+
dependencies = ["httpx>=0.24"]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://dadosb3.com"
|
|
27
|
+
Documentation = "https://dadosb3.com/api"
|
|
28
|
+
Methodology = "https://dadosb3.com/metodologia"
|
|
29
|
+
"MCP connector" = "https://github.com/Val7h/dados-b3-mcp"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools]
|
|
32
|
+
packages = ["dadosb3"]
|
dadosb3-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Testes do cliente sem rede: um transporte falso responde como a API."""
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from dadosb3 import ChaveNecessaria, DadosB3, ErroDadosB3, NaoEncontrado
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _api(resposta):
|
|
11
|
+
"""Cliente cujo transporte grava a requisição e devolve `resposta(req)`."""
|
|
12
|
+
vistas = []
|
|
13
|
+
|
|
14
|
+
def handler(req: httpx.Request) -> httpx.Response:
|
|
15
|
+
vistas.append(req)
|
|
16
|
+
return resposta(req)
|
|
17
|
+
|
|
18
|
+
return DadosB3(chave="k-teste", transport=httpx.MockTransport(handler)), vistas
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_cabecalhos_accept_json_e_chave():
|
|
22
|
+
api, vistas = _api(lambda r: httpx.Response(200, json={"ok": 1}))
|
|
23
|
+
assert api.indicadores("WEGE3") == {"ok": 1}
|
|
24
|
+
req = vistas[0]
|
|
25
|
+
assert req.url.path == "/empresas/WEGE3/indicadores"
|
|
26
|
+
assert req.headers["accept"] == "application/json"
|
|
27
|
+
assert req.headers["x-api-key"] == "k-teste"
|
|
28
|
+
assert req.headers["user-agent"].startswith("dadosb3-python/")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_sem_chave_nao_manda_cabecalho(monkeypatch):
|
|
32
|
+
monkeypatch.delenv("DADOS_B3_API_KEY", raising=False)
|
|
33
|
+
vistas = []
|
|
34
|
+
api = DadosB3(transport=httpx.MockTransport(lambda r: (vistas.append(r), httpx.Response(200, json={}))[1]))
|
|
35
|
+
api.saude()
|
|
36
|
+
assert "x-api-key" not in vistas[0].headers
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_chave_do_ambiente(monkeypatch):
|
|
40
|
+
monkeypatch.setenv("DADOS_B3_API_KEY", "k-env")
|
|
41
|
+
assert DadosB3(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={}))).chave == "k-env"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_rotas_e_parametros():
|
|
45
|
+
api, vistas = _api(lambda r: httpx.Response(200, json={}))
|
|
46
|
+
api.screener(roic_min=0.15, dl_ebitda_max=2, ano=2024, limite=10)
|
|
47
|
+
api.fiis_screener(pvp_max=0.9, dy_min=0.10)
|
|
48
|
+
api.fatos("ITUB4", trimestral=True)
|
|
49
|
+
api.etf("BOVA11"); api.etfs_ranking(); api.fiis_ranking(); api.fii("MXRF11")
|
|
50
|
+
api.auditar_amostra(semente=4242, n=10); api.hoje(); api.dicionario(); api.empresas()
|
|
51
|
+
caminhos = [str(v.url).replace("https://dadosb3.com", "") for v in vistas]
|
|
52
|
+
assert caminhos[0].startswith("/screener?") and "roic_min=0.15" in caminhos[0] and "ano=2024" in caminhos[0]
|
|
53
|
+
assert "dl_ebitda_max=2" in caminhos[0] and "limite=10" in caminhos[0]
|
|
54
|
+
assert caminhos[1].startswith("/fiis/screener?") and "pvp_max=0.9" in caminhos[1]
|
|
55
|
+
assert caminhos[2] == "/empresas/ITUB4/fatos?trimestral=true"
|
|
56
|
+
assert caminhos[3:] == ["/etfs/BOVA11", "/etfs", "/fiis", "/fiis/MXRF11",
|
|
57
|
+
"/auditoria/amostra/4242/10", "/hoje", "/dicionario", "/empresas"]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_parametro_vazio_nao_vai():
|
|
61
|
+
api, vistas = _api(lambda r: httpx.Response(200, json={}))
|
|
62
|
+
api.screener(ano=None, limite=100)
|
|
63
|
+
assert "ano" not in str(vistas[0].url)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.mark.parametrize("status,tipo", [(401, ChaveNecessaria), (404, NaoEncontrado), (500, ErroDadosB3)])
|
|
67
|
+
def test_erros_tipados_com_o_corpo(status, tipo):
|
|
68
|
+
corpo = {"erro": "x", "como_resolver": "crie uma chave"}
|
|
69
|
+
api, _ = _api(lambda r: httpx.Response(status, json=corpo))
|
|
70
|
+
with pytest.raises(tipo) as e:
|
|
71
|
+
api.multiplos("PETR4")
|
|
72
|
+
assert e.value.status == status and e.value.detalhe == corpo
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_erro_sem_json_traz_o_texto():
|
|
76
|
+
api, _ = _api(lambda r: httpx.Response(503, text="fora do ar"))
|
|
77
|
+
with pytest.raises(ErroDadosB3) as e:
|
|
78
|
+
api.saude()
|
|
79
|
+
assert e.value.detalhe == "fora do ar"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_gerenciador_de_contexto_fecha():
|
|
83
|
+
with DadosB3(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={}))) as api:
|
|
84
|
+
api.saude()
|
|
85
|
+
assert api._http.is_closed
|