ifdata-bcb 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.
Files changed (80) hide show
  1. ifdata_bcb-0.1.0/.gitattributes +59 -0
  2. ifdata_bcb-0.1.0/.github/ISSUE_TEMPLATE/bug_report.yml +49 -0
  3. ifdata_bcb-0.1.0/.github/ISSUE_TEMPLATE/feature_request.yml +24 -0
  4. ifdata_bcb-0.1.0/.github/pull_request_template.md +17 -0
  5. ifdata_bcb-0.1.0/.github/workflows/ci.yml +28 -0
  6. ifdata_bcb-0.1.0/.github/workflows/publish.yml +18 -0
  7. ifdata_bcb-0.1.0/.gitignore +11 -0
  8. ifdata_bcb-0.1.0/CHANGELOG.md +67 -0
  9. ifdata_bcb-0.1.0/CODE_OF_CONDUCT.md +39 -0
  10. ifdata_bcb-0.1.0/CONTRIBUTING.md +95 -0
  11. ifdata_bcb-0.1.0/LICENSE +21 -0
  12. ifdata_bcb-0.1.0/PKG-INFO +249 -0
  13. ifdata_bcb-0.1.0/README.md +193 -0
  14. ifdata_bcb-0.1.0/SECURITY.md +30 -0
  15. ifdata_bcb-0.1.0/docs/advanced/extending.md +662 -0
  16. ifdata_bcb-0.1.0/docs/advanced/sql-queries.md +463 -0
  17. ifdata_bcb-0.1.0/docs/getting-started.md +471 -0
  18. ifdata_bcb-0.1.0/docs/internals/README.md +54 -0
  19. ifdata_bcb-0.1.0/docs/internals/architecture.md +447 -0
  20. ifdata_bcb-0.1.0/docs/internals/core.md +735 -0
  21. ifdata_bcb-0.1.0/docs/internals/domain.md +477 -0
  22. ifdata_bcb-0.1.0/docs/internals/infra.md +592 -0
  23. ifdata_bcb-0.1.0/docs/internals/providers.md +624 -0
  24. ifdata_bcb-0.1.0/docs/internals/utils.md +381 -0
  25. ifdata_bcb-0.1.0/docs/providers/cadastro.md +386 -0
  26. ifdata_bcb-0.1.0/docs/providers/cosif.md +421 -0
  27. ifdata_bcb-0.1.0/docs/providers/ifdata.md +434 -0
  28. ifdata_bcb-0.1.0/pyproject.toml +60 -0
  29. ifdata_bcb-0.1.0/src/ifdata_bcb/__init__.py +88 -0
  30. ifdata_bcb-0.1.0/src/ifdata_bcb/core/__init__.py +9 -0
  31. ifdata_bcb-0.1.0/src/ifdata_bcb/core/api.py +23 -0
  32. ifdata_bcb-0.1.0/src/ifdata_bcb/core/base_explorer.py +468 -0
  33. ifdata_bcb-0.1.0/src/ifdata_bcb/core/constants.py +38 -0
  34. ifdata_bcb-0.1.0/src/ifdata_bcb/core/entity_lookup.py +624 -0
  35. ifdata_bcb-0.1.0/src/ifdata_bcb/domain/__init__.py +47 -0
  36. ifdata_bcb-0.1.0/src/ifdata_bcb/domain/exceptions.py +89 -0
  37. ifdata_bcb-0.1.0/src/ifdata_bcb/domain/models.py +14 -0
  38. ifdata_bcb-0.1.0/src/ifdata_bcb/domain/types.py +19 -0
  39. ifdata_bcb-0.1.0/src/ifdata_bcb/domain/validation.py +80 -0
  40. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/__init__.py +46 -0
  41. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/cache.py +45 -0
  42. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/config.py +33 -0
  43. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/log.py +77 -0
  44. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/paths.py +25 -0
  45. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/query.py +75 -0
  46. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/resilience.py +114 -0
  47. ifdata_bcb-0.1.0/src/ifdata_bcb/infra/storage.py +134 -0
  48. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/__init__.py +33 -0
  49. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/base_collector.py +315 -0
  50. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/collector_models.py +12 -0
  51. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/cosif/__init__.py +4 -0
  52. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/cosif/collector.py +195 -0
  53. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/cosif/explorer.py +388 -0
  54. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/ifdata/__init__.py +13 -0
  55. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/ifdata/cadastro_explorer.py +209 -0
  56. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/ifdata/collector.py +230 -0
  57. ifdata_bcb-0.1.0/src/ifdata_bcb/providers/ifdata/explorer.py +573 -0
  58. ifdata_bcb-0.1.0/src/ifdata_bcb/py.typed +0 -0
  59. ifdata_bcb-0.1.0/src/ifdata_bcb/ui/__init__.py +6 -0
  60. ifdata_bcb-0.1.0/src/ifdata_bcb/ui/display.py +272 -0
  61. ifdata_bcb-0.1.0/src/ifdata_bcb/utils/__init__.py +28 -0
  62. ifdata_bcb-0.1.0/src/ifdata_bcb/utils/cnpj.py +12 -0
  63. ifdata_bcb-0.1.0/src/ifdata_bcb/utils/date.py +102 -0
  64. ifdata_bcb-0.1.0/src/ifdata_bcb/utils/fuzzy.py +28 -0
  65. ifdata_bcb-0.1.0/src/ifdata_bcb/utils/period.py +35 -0
  66. ifdata_bcb-0.1.0/src/ifdata_bcb/utils/text.py +16 -0
  67. ifdata_bcb-0.1.0/tests/__init__.py +0 -0
  68. ifdata_bcb-0.1.0/tests/conftest.py +23 -0
  69. ifdata_bcb-0.1.0/tests/test_base_collector.py +94 -0
  70. ifdata_bcb-0.1.0/tests/test_base_explorer.py +250 -0
  71. ifdata_bcb-0.1.0/tests/test_cache.py +71 -0
  72. ifdata_bcb-0.1.0/tests/test_cnpj.py +59 -0
  73. ifdata_bcb-0.1.0/tests/test_constants.py +64 -0
  74. ifdata_bcb-0.1.0/tests/test_date.py +169 -0
  75. ifdata_bcb-0.1.0/tests/test_exceptions.py +91 -0
  76. ifdata_bcb-0.1.0/tests/test_logging.py +43 -0
  77. ifdata_bcb-0.1.0/tests/test_period.py +104 -0
  78. ifdata_bcb-0.1.0/tests/test_provider_contracts.py +83 -0
  79. ifdata_bcb-0.1.0/tests/test_text.py +70 -0
  80. ifdata_bcb-0.1.0/uv.lock +1202 -0
@@ -0,0 +1,59 @@
1
+ # Git attributes for consistent line endings across platforms
2
+ # See: https://git-scm.com/docs/gitattributes
3
+
4
+ # Auto detect text files and normalize line endings to LF in the repository
5
+ * text=auto
6
+
7
+ # Source code files - enforce LF in repository, CRLF on checkout for Windows
8
+ *.py text eol=lf
9
+ *.pyx text eol=lf
10
+ *.pxd text eol=lf
11
+ *.pyi text eol=lf
12
+
13
+ # Configuration files - enforce LF
14
+ *.json text eol=lf
15
+ *.toml text eol=lf
16
+ *.yaml text eol=lf
17
+ *.yml text eol=lf
18
+ *.ini text eol=lf
19
+ *.cfg text eol=lf
20
+
21
+ # Documentation - enforce LF
22
+ *.md text eol=lf
23
+ *.rst text eol=lf
24
+ *.txt text eol=lf
25
+
26
+ # Jupyter notebooks - enforce LF
27
+ *.ipynb text eol=lf
28
+
29
+ # Shell scripts - enforce LF (must use LF even on Windows)
30
+ *.sh text eol=lf
31
+ *.bash text eol=lf
32
+
33
+ # Windows scripts - enforce CRLF
34
+ *.bat text eol=crlf
35
+ *.cmd text eol=crlf
36
+ *.ps1 text eol=crlf
37
+
38
+ # Data files - treat as binary (no line ending conversion)
39
+ *.parquet binary
40
+ *.csv binary
41
+ *.xlsx binary
42
+ *.db binary
43
+ *.sqlite binary
44
+
45
+ # Image files - binary
46
+ *.png binary
47
+ *.jpg binary
48
+ *.jpeg binary
49
+ *.gif binary
50
+ *.ico binary
51
+ *.svg binary
52
+
53
+ # Archive files - binary
54
+ *.zip binary
55
+ *.tar binary
56
+ *.gz binary
57
+ *.7z binary
58
+ *.rar binary
59
+
@@ -0,0 +1,49 @@
1
+ name: Bug Report
2
+ description: Reportar um problema ou comportamento inesperado
3
+ labels: ["bug"]
4
+ body:
5
+ - type: textarea
6
+ id: description
7
+ attributes:
8
+ label: Descricao do bug
9
+ description: Descreva o que aconteceu e o que voce esperava que acontecesse.
10
+ validations:
11
+ required: true
12
+ - type: textarea
13
+ id: reproduction
14
+ attributes:
15
+ label: Como reproduzir
16
+ description: Passos ou codigo minimo para reproduzir o problema.
17
+ render: python
18
+ validations:
19
+ required: true
20
+ - type: textarea
21
+ id: error
22
+ attributes:
23
+ label: Mensagem de erro
24
+ description: Cole o traceback ou mensagem de erro, se houver.
25
+ render: shell
26
+ - type: input
27
+ id: version
28
+ attributes:
29
+ label: Versao do ifdata-bcb
30
+ placeholder: "0.1.0"
31
+ validations:
32
+ required: true
33
+ - type: dropdown
34
+ id: os
35
+ attributes:
36
+ label: Sistema operacional
37
+ options:
38
+ - Windows
39
+ - Linux
40
+ - macOS
41
+ validations:
42
+ required: true
43
+ - type: input
44
+ id: python-version
45
+ attributes:
46
+ label: Versao do Python
47
+ placeholder: "3.12"
48
+ validations:
49
+ required: true
@@ -0,0 +1,24 @@
1
+ name: Feature Request
2
+ description: Sugerir uma nova funcionalidade
3
+ labels: ["enhancement"]
4
+ body:
5
+ - type: textarea
6
+ id: problem
7
+ attributes:
8
+ label: Problema
9
+ description: Que problema essa feature resolveria?
10
+ validations:
11
+ required: true
12
+ - type: textarea
13
+ id: solution
14
+ attributes:
15
+ label: Solucao proposta
16
+ description: Como voce imagina que a API ou interface funcionaria?
17
+ render: python
18
+ validations:
19
+ required: true
20
+ - type: textarea
21
+ id: alternatives
22
+ attributes:
23
+ label: Alternativas consideradas
24
+ description: Voce tentou algum workaround ou abordagem alternativa?
@@ -0,0 +1,17 @@
1
+ ## O que muda
2
+
3
+ <!-- Descreva brevemente o que esse PR faz -->
4
+
5
+ ## Tipo de mudanca
6
+
7
+ - [ ] Bug fix
8
+ - [ ] Nova feature
9
+ - [ ] Refatoracao
10
+ - [ ] Documentacao
11
+ - [ ] Outro: <!-- descreva -->
12
+
13
+ ## Checklist
14
+
15
+ - [ ] Testes passando (`uv run pytest tests/ -v`)
16
+ - [ ] Linter passando (`uvx ruff check .`)
17
+ - [ ] Documentacao atualizada (se aplicavel)
@@ -0,0 +1,28 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [master]
6
+ pull_request:
7
+ branches: [master]
8
+
9
+ jobs:
10
+ lint:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: astral-sh/setup-uv@v7
15
+ - run: uvx ruff check .
16
+
17
+ test:
18
+ runs-on: ubuntu-latest
19
+ strategy:
20
+ matrix:
21
+ python-version: ["3.12", "3.13"]
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+ - uses: astral-sh/setup-uv@v7
25
+ with:
26
+ python-version: ${{ matrix.python-version }}
27
+ - run: uv sync
28
+ - run: uv run --frozen pytest tests/ -v
@@ -0,0 +1,18 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ id-token: write
9
+
10
+ jobs:
11
+ publish:
12
+ runs-on: ubuntu-latest
13
+ environment: pypi
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: astral-sh/setup-uv@v7
17
+ - run: uv build
18
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,11 @@
1
+ # Python
2
+ .venv
3
+ __pycache__
4
+ *egg-info
5
+
6
+ # Temp Folders
7
+ temp
8
+
9
+ # Agents
10
+ CLAUDE.md
11
+ .claude/
@@ -0,0 +1,67 @@
1
+ # Project Changelog
2
+
3
+ ## [2026-03-15 03:00]
4
+
5
+ ### Fixed
6
+ - `NormalizedDates` agora valida range de mes (1-12), rejeitando inputs como `202413` ou `202400` que antes eram aceitos silenciosamente e resultavam em queries vazias sem erro informativo
7
+ - Eliminada duplicacao de parsing: validator agora delega para `normalize_date_to_int()` (fonte unica de verdade para conversao de datas)
8
+ - String de ano puro (`"2024"`) agora levanta `InvalidDateFormatError` em vez de ser interpretada como YYYYMM=2024 (ano 20, mes 24)
9
+ - Parametro `cadastro` com colunas invalidas agora levanta `InvalidScopeError` mesmo quando o resultado da query e vazio
10
+ - Validacao movida para o inicio de `read()` (antes do query), garantindo feedback imediato independente dos dados
11
+
12
+ ## [2026-03-15 02:12]
13
+
14
+ ### Added
15
+ - Parametro `cadastro` em `cosif.read()` e `ifdata.read()` para enriquecer dados financeiros com atributos cadastrais inline (ex: `cadastro=["TCB", "SEGMENTO", "UF"]`)
16
+ - Elimina o pattern manual de ler cadastro separado e fazer merge por CNPJ
17
+ - Alinhamento temporal automatico: dados mensais COSIF recebem cadastro do trimestre mais recente via `merge_asof` backward-looking
18
+ - Dados trimestrais IFDATA fazem merge exato por DATA + CNPJ_8
19
+ - Colunas cadastrais invalidas levantam `InvalidScopeError` (consistente com hierarquia de excecoes da lib)
20
+ - `openpyxl` como dev dependency para exportacao Excel em scripts
21
+
22
+ ## [2026-03-13 19:48]
23
+
24
+ Refatoracao significativa focada em validacao com Pydantic, configuracao centralizada, e melhoria da resolucao de entidades no IFDATA.
25
+
26
+ Correcao de 6 bugs de usabilidade nas APIs publicas e flexibilizacao do Cadastro.
27
+
28
+ ### Fixed
29
+ - Filtros de `conta`, `segmento`, `relatorio` agora sao accent-insensitive (`'Lucro Liquido'` funciona igual a `'Lucro Liquido'` com acento)
30
+ - `_build_string_condition` aceita `accent_insensitive=True` usando `strip_accents()` do DuckDB
31
+ - `list_accounts()` do COSIF e IFDATA tambem usam accent-insensitive no LIKE
32
+ - DataFrames vazios agora retornam colunas de apresentacao (DATA, INSTITUICAO) em vez de nomes de storage (DATA_BASE, NomeInstituicao)
33
+ - `cosif.read()` nao retorna mais linhas duplicadas causadas pelo campo DOCUMENTO (balancete vs semestral)
34
+ - `_finalize_read` base agora chama `drop_duplicates()` apos mapeamento de colunas
35
+ - Parametro `columns` aceita nomes de apresentacao (DATA, VALOR) alem de nomes de storage (DATA_BASE, SALDO)
36
+ - Novo metodo `_translate_columns()` no BaseExplorer traduz antes de passar ao DuckDB
37
+ - `search('')` retorna DataFrame vazio sem warning do thefuzz
38
+ - `search(limit=0)` e `search(limit=-1)` agora levantam `ValueError`
39
+
40
+ ### Added
41
+ - `domain/validation.py`: Validadores Pydantic para datas, CNPJs, instituicoes e contas (`NormalizedDates`, `ValidatedCnpj8`, `InstitutionList`, `AccountList`)
42
+ - `infra/paths.py`: Utilitarios `ensure_dir` e `temp_dir` para gerenciamento seguro de diretorios temporarios
43
+ - `domain/exceptions.py`: Nova excecao `DataProcessingError` para falhas de processamento de fontes
44
+ - `infra/config.py`: Classe `Settings` baseada em `pydantic-settings` substituindo funcoes avulsas de configuracao
45
+ - `IFDATAExplorer`: Novos metodos de introspeccao (`list_accounts`, `list_institutions`, `list_reporters`, `list_reports`) e validacao de escopo
46
+ - `EntityLookup`: Resolucao canonica de entidades com suporte a CodInst e heuristica para caches legados
47
+ - Suite de testes formal em `tests/` com 11 modulos cobrindo core, domain, infra e providers
48
+ - `pyproject.toml`: Dependencias `pydantic` e `pydantic-settings`; grupo dev com `pytest`; configuracao pytest
49
+
50
+ ### Changed
51
+ - `cadastro.read()`, `cadastro.info()`, `cadastro.get_conglomerate_members()`: `start` agora e opcional (default: ultimo periodo disponivel)
52
+ - Novo metodo `_resolve_start()` no CadastroExplorer
53
+ - Novo metodo `_get_latest_period()` no BaseExplorer
54
+ - `BaseExplorer`: Validacao de inputs delegada para modelos Pydantic em vez de regex manual; novo metodo `_align_to_quarter_end`
55
+ - `BaseCollector`: Downloads isolados em `temp_dir` context manager; `_normalize_text_fields` agora opera em todas as colunas object
56
+ - `BaseCollector._download_period`: Assinatura atualizada para receber `work_dir` explicitamente
57
+ - `infra/log.py`: Logging de arquivo usa `get_settings().logs_path` com fallback silencioso para ambientes restritos
58
+ - `infra/__init__.py`: Exports atualizados (`Settings`, `get_settings`, `ensure_dir`, `temp_dir` substituem `get_cache_path`)
59
+ - `IFDATAExplorer._add_institution_names`: Usa `get_canonical_names_for_cnpjs` para nomes canonicos
60
+ - Documentacao atualizada em todos os docs para refletir nova arquitetura (README, getting-started, internals, providers)
61
+ - `notebooks/quickstart.ipynb`: Exemplos atualizados para nova API
62
+
63
+ ### Removed
64
+ - `CHANGELOG.md` anterior (substituido por esta versao atualizada)
65
+ - `EntityLookup._build_entity_union_sql`: Substituido por resolucao canonica via cadastro com CodInst
66
+ - `get_cache_path` e `get_logs_path`: Substituidos pela classe `Settings`
67
+ - Lista fixa de colunas de texto em `_normalize_text_fields`
@@ -0,0 +1,39 @@
1
+ # Codigo de Conduta - Contributor Covenant
2
+
3
+ ## Nosso Compromisso
4
+
5
+ No interesse de promover um ambiente aberto e acolhedor, nos, como contribuidores e mantenedores, nos comprometemos a tornar a participacao em nosso projeto e em nossa comunidade uma experiencia livre de assedio para todos, independentemente de idade, tamanho corporal, deficiencia, etnia, caracteristicas sexuais, identidade e expressao de genero, nivel de experiencia, educacao, status socioeconomico, nacionalidade, aparencia pessoal, raca, religiao ou identidade e orientacao sexual.
6
+
7
+ ## Nossos Padroes
8
+
9
+ Exemplos de comportamento que contribuem para criar um ambiente positivo:
10
+
11
+ - Usar linguagem acolhedora e inclusiva
12
+ - Respeitar pontos de vista e experiencias diferentes
13
+ - Aceitar criticas construtivas com graca
14
+ - Focar no que e melhor para a comunidade
15
+ - Mostrar empatia com outros membros da comunidade
16
+
17
+ Exemplos de comportamento inaceitavel:
18
+
19
+ - Uso de linguagem ou imagens sexualizadas e atencao ou avancos sexuais indesejados
20
+ - Trolling, comentarios insultuosos/depreciativos e ataques pessoais ou politicos
21
+ - Assedio publico ou privado
22
+ - Publicar informacoes privadas de terceiros sem permissao explicita
23
+ - Outra conduta que poderia ser considerada inapropriada em um ambiente profissional
24
+
25
+ ## Nossas Responsabilidades
26
+
27
+ Os mantenedores do projeto sao responsaveis por esclarecer os padroes de comportamento aceitavel e devem tomar acoes corretivas apropriadas e justas em resposta a qualquer instancia de comportamento inaceitavel.
28
+
29
+ ## Escopo
30
+
31
+ Este Codigo de Conduta se aplica em todos os espacos do projeto e tambem quando um individuo esta representando o projeto ou sua comunidade em espacos publicos.
32
+
33
+ ## Aplicacao
34
+
35
+ Instancias de comportamento abusivo, de assedio ou de outra forma inaceitavel podem ser reportadas entrando em contato com o mantenedor do projeto. Todas as reclamacoes serao revisadas e investigadas e resultarao em uma resposta considerada necessaria e apropriada as circunstancias.
36
+
37
+ ## Atribuicao
38
+
39
+ Este Codigo de Conduta e adaptado do [Contributor Covenant](https://www.contributor-covenant.org), versao 2.1.
@@ -0,0 +1,95 @@
1
+ # Contribuindo com ifdata-bcb
2
+
3
+ Obrigado pelo interesse em contribuir! Este guia explica como participar do projeto.
4
+
5
+ ## Primeiros Passos
6
+
7
+ ### Requisitos
8
+
9
+ - Python 3.12+
10
+ - [uv](https://docs.astral.sh/uv/) como gerenciador de pacotes
11
+
12
+ ### Setup local
13
+
14
+ ```bash
15
+ # Clone o repositorio
16
+ git clone https://github.com/enzoomoreira/ifdata-bcb.git
17
+ cd ifdata-bcb
18
+
19
+ # Instale dependencias
20
+ uv sync
21
+
22
+ # Rode os testes
23
+ uv run pytest tests/ -v
24
+ ```
25
+
26
+ ## Como Contribuir
27
+
28
+ ### Reportando Bugs
29
+
30
+ Abra uma [issue](https://github.com/enzoomoreira/ifdata-bcb/issues) com:
31
+
32
+ - Descricao clara do problema
33
+ - Passos para reproduzir
34
+ - Comportamento esperado vs. observado
35
+ - Versao do Python e do ifdata-bcb
36
+ - Sistema operacional
37
+
38
+ ### Sugerindo Features
39
+
40
+ Abra uma [issue](https://github.com/enzoomoreira/ifdata-bcb/issues) descrevendo:
41
+
42
+ - O problema que a feature resolve
43
+ - Como voce imagina a API/interface
44
+ - Exemplos de uso
45
+
46
+ ### Enviando Pull Requests
47
+
48
+ 1. Fork o repositorio
49
+ 2. Crie uma branch a partir de `master` (`git checkout -b feat/minha-feature`)
50
+ 3. Faca suas alteracoes
51
+ 4. Rode os testes (`uv run pytest tests/ -v`)
52
+ 5. Rode o linter (`uvx ruff check .`)
53
+ 6. Commit seguindo [Conventional Commits](https://www.conventionalcommits.org/):
54
+ - `feat:` nova funcionalidade
55
+ - `fix:` correcao de bug
56
+ - `docs:` documentacao
57
+ - `refactor:` refatoracao sem mudanca de comportamento
58
+ - `test:` adicao ou correcao de testes
59
+ 7. Abra o PR contra `master`
60
+
61
+ ## Estilo de Codigo
62
+
63
+ - **Formatacao**: ruff format
64
+ - **Linting**: ruff check
65
+ - **Type hints**: obrigatorios em todas as funcoes
66
+ - **Docstrings**: apenas em API publica ou comportamento nao-obvio
67
+ - **Encoding**: UTF-8, sem emojis
68
+
69
+ ## Estrutura do Projeto
70
+
71
+ ```
72
+ src/ifdata_bcb/
73
+ core/ # Logica central (BaseExplorer, EntityLookup, Constants)
74
+ domain/ # Modelos, excecoes, validacao
75
+ infra/ # Infraestrutura (paths, config, QueryEngine)
76
+ providers/ # Provedores de dados (cosif, ifdata)
77
+ utils/ # Utilitarios
78
+ ui/ # Componentes de interface
79
+ ```
80
+
81
+ ## Testes
82
+
83
+ ```bash
84
+ # Rodar todos os testes
85
+ uv run pytest tests/ -v
86
+
87
+ # Rodar um modulo especifico
88
+ uv run pytest tests/test_validation.py -v
89
+ ```
90
+
91
+ Os testes usam dados reais do BCB. Algumas execucoes podem ser lentas na primeira vez por conta da coleta de dados.
92
+
93
+ ## Duvidas?
94
+
95
+ Abra uma [issue](https://github.com/enzoomoreira/ifdata-bcb/issues) com sua pergunta. Ficaremos felizes em ajudar.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Enzo Moreira
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,249 @@
1
+ Metadata-Version: 2.4
2
+ Name: ifdata-bcb
3
+ Version: 0.1.0
4
+ Summary: Analise de dados financeiros do Banco Central do Brasil (BCB)
5
+ Project-URL: Homepage, https://github.com/enzoomoreira/ifdata-bcb
6
+ Project-URL: Repository, https://github.com/enzoomoreira/ifdata-bcb
7
+ Project-URL: Documentation, https://github.com/enzoomoreira/ifdata-bcb/tree/master/docs
8
+ Project-URL: Bug Tracker, https://github.com/enzoomoreira/ifdata-bcb/issues
9
+ Project-URL: Changelog, https://github.com/enzoomoreira/ifdata-bcb/blob/master/CHANGELOG.md
10
+ License: MIT License
11
+
12
+ Copyright (c) 2026 Enzo Moreira
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: Intended Audience :: Financial and Insurance Industry
35
+ Classifier: Intended Audience :: Science/Research
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Operating System :: OS Independent
38
+ Classifier: Programming Language :: Python :: 3
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Programming Language :: Python :: 3.13
41
+ Classifier: Topic :: Office/Business :: Financial
42
+ Classifier: Typing :: Typed
43
+ Requires-Python: >=3.12
44
+ Requires-Dist: duckdb>=1.4.4
45
+ Requires-Dist: loguru>=0.7.3
46
+ Requires-Dist: pandas>=2.0.0
47
+ Requires-Dist: platformdirs>=3.0.0
48
+ Requires-Dist: pyarrow>=10.0.0
49
+ Requires-Dist: pydantic-settings>=2.13.1
50
+ Requires-Dist: pydantic>=2.12.5
51
+ Requires-Dist: requests>=2.28.0
52
+ Requires-Dist: rich>=14.3.1
53
+ Requires-Dist: tenacity>=9.1.2
54
+ Requires-Dist: thefuzz[speedup]>=0.22.0
55
+ Description-Content-Type: text/markdown
56
+
57
+ # ifdata-bcb
58
+
59
+ [![PyPI version](https://img.shields.io/pypi/v/ifdata-bcb)](https://pypi.org/project/ifdata-bcb/)
60
+ [![Python](https://img.shields.io/pypi/pyversions/ifdata-bcb)](https://pypi.org/project/ifdata-bcb/)
61
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
62
+ [![CI](https://github.com/enzoomoreira/ifdata-bcb/actions/workflows/ci.yml/badge.svg)](https://github.com/enzoomoreira/ifdata-bcb/actions/workflows/ci.yml)
63
+
64
+ Coleta e analise de dados contabeis e financeiros de instituicoes financeiras brasileiras. Dados publicos do Banco Central do Brasil.
65
+
66
+ | Fonte | Modulo | Dados | Periodicidade |
67
+ |-------|--------|-------|---------------|
68
+ | COSIF | `bcb.cosif` | Plano contabil (individual e prudencial) | Mensal |
69
+ | IFDATA | `bcb.ifdata` | Informacoes financeiras | Trimestral |
70
+ | Cadastro | `bcb.cadastro` | Metadados de instituicoes (segmento, conglomerado) | Trimestral |
71
+
72
+ ## Instalacao
73
+
74
+ ```bash
75
+ uv add ifdata-bcb
76
+ ```
77
+
78
+ Requer Python 3.12+.
79
+
80
+ ## Uso Rapido
81
+
82
+ ```python
83
+ import ifdata_bcb as bcb
84
+
85
+ # 1. Coletar dados (primeira vez ou atualizar)
86
+ bcb.cadastro.collect('2024-01', '2024-12')
87
+ bcb.cosif.collect('2024-01', '2024-12')
88
+ bcb.ifdata.collect('2024-01', '2024-12')
89
+
90
+ # 2. Buscar instituicao por nome (fuzzy matching)
91
+ bcb.search('Itau')
92
+ bcb.search('Bradesco')
93
+ # CNPJ_8 INSTITUICAO SITUACAO FONTES SCORE
94
+ # 0 60872504 ITAU UNIBANCO HOLDING S.A. A ... 100
95
+ # Quando possivel, prioriza resultados com dados disponiveis em FONTES.
96
+
97
+ # 3. Ler dados usando CNPJ de 8 digitos
98
+ # COSIF/IFDATA: instituicao e start sao OBRIGATORIOS
99
+ # start sozinho = data unica; start + end = range
100
+
101
+ # COSIF (escopo=None busca em todos os escopos)
102
+ df = bcb.cosif.read(
103
+ instituicao='60872504',
104
+ start='2024-12',
105
+ conta='TOTAL GERAL DO ATIVO',
106
+ escopo='prudencial'
107
+ )
108
+
109
+ # IFDATA
110
+ df = bcb.ifdata.read(
111
+ instituicao='60872504',
112
+ start='2024-01',
113
+ end='2024-12',
114
+ conta='Lucro Liquido'
115
+ )
116
+
117
+ # Enriquecer com dados cadastrais inline
118
+ df = bcb.ifdata.read(
119
+ instituicao='60872504',
120
+ start='2024-01',
121
+ end='2024-12',
122
+ escopo='prudencial',
123
+ cadastro=['TCB', 'SEGMENTO']
124
+ )
125
+
126
+ # Cadastro
127
+ info = bcb.cadastro.info('60872504', start='2024-12')
128
+
129
+ # Cadastro tambem pode ser filtrado sem instituicao
130
+ df = bcb.cadastro.read(start='2024-12', segmento='Banco Multiplo')
131
+
132
+ # 4. Listar contas e instituicoes disponiveis
133
+ bcb.cosif.list_accounts(escopo='prudencial')
134
+ bcb.cosif.list_institutions(escopo='prudencial')
135
+
136
+ # 5. SQL direto com DuckDB (para analises avancadas)
137
+ from ifdata_bcb.infra import QueryEngine
138
+
139
+ qe = QueryEngine()
140
+ df = qe.sql("""
141
+ SELECT CNPJ_8, NOME_INSTITUICAO, SALDO
142
+ FROM '{cache}/cosif/prudencial/*.parquet'
143
+ WHERE DATA_BASE = 202412 AND NOME_CONTA = 'TOTAL GERAL DO ATIVO'
144
+ ORDER BY SALDO DESC
145
+ LIMIT 10
146
+ """)
147
+ ```
148
+
149
+ ## Documentacao
150
+
151
+ ### Guias de Uso
152
+
153
+ - **[getting-started.md](docs/getting-started.md)** - Instalacao e primeiro uso
154
+
155
+ ### Fontes de Dados
156
+
157
+ - **[cosif.md](docs/providers/cosif.md)** - Plano contabil (individual/prudencial)
158
+ - **[ifdata.md](docs/providers/ifdata.md)** - Informacoes financeiras trimestrais
159
+ - **[cadastro.md](docs/providers/cadastro.md)** - Metadados de instituicoes
160
+
161
+ ### Uso Avancado
162
+
163
+ - **[sql-queries.md](docs/advanced/sql-queries.md)** - Queries SQL com DuckDB
164
+ - **[extending.md](docs/advanced/extending.md)** - Como criar novos providers
165
+
166
+ ### Arquitetura Interna
167
+
168
+ - **[architecture.md](docs/internals/architecture.md)** - Visao geral da arquitetura
169
+ - **[core.md](docs/internals/core.md)** - BaseExplorer, EntityLookup, Constants
170
+ - **[domain.md](docs/internals/domain.md)** - Exceptions, Models, Types, Validation
171
+ - **[infra.md](docs/internals/infra.md)** - Settings, QueryEngine, DataManager
172
+ - **[providers.md](docs/internals/providers.md)** - BaseCollector, Explorers
173
+
174
+ ## Estrutura de Dados
175
+
176
+ ```
177
+ {cache}/
178
+ cosif/
179
+ individual/ # cosif_ind_YYYYMM.parquet
180
+ prudencial/ # cosif_prud_YYYYMM.parquet
181
+ ifdata/
182
+ valores/ # ifdata_val_YYYYMM.parquet
183
+ cadastro/ # ifdata_cad_YYYYMM.parquet
184
+ ```
185
+
186
+ O diretorio de cache varia por sistema:
187
+
188
+ | Sistema | Caminho |
189
+ |---------|---------|
190
+ | Windows | `%LOCALAPPDATA%\py-bacen\Cache\` |
191
+ | Linux | `~/.cache/py-bacen/` |
192
+ | macOS | `~/Library/Caches/py-bacen/` |
193
+
194
+ Customizavel via variavel de ambiente `BACEN_DATA_DIR`.
195
+
196
+ ## API Publica
197
+
198
+ ### Modulo Principal
199
+
200
+ ```python
201
+ import ifdata_bcb as bcb
202
+
203
+ # Explorers (lazy loading)
204
+ bcb.cosif # COSIFExplorer
205
+ bcb.ifdata # IFDATAExplorer
206
+ bcb.cadastro # CadastroExplorer
207
+
208
+ # Funcoes
209
+ bcb.search(termo, limit=10) # Busca instituicoes por nome
210
+
211
+ # Exceptions
212
+ bcb.BacenAnalysisError # Classe base para todos os erros
213
+ bcb.DataUnavailableError # Dados nao disponiveis
214
+ ```
215
+
216
+ ### Metodos dos Explorers
217
+
218
+ Todos os explorers possuem:
219
+
220
+ | Metodo | Descricao |
221
+ |--------|-----------|
222
+ | `collect(start, end, ...)` | Coleta dados do BCB |
223
+ | `read(instituicao, start, ...)` | Le dados com filtros |
224
+ | `list_periods()` | Periodos disponiveis |
225
+ | `has_data()` | Verifica se tem dados |
226
+
227
+ Metodos especificos:
228
+
229
+ | Explorer | Metodos Adicionais |
230
+ |----------|-------------------|
231
+ | `cosif` | `list_accounts()`, `list_institutions()` |
232
+ | `ifdata` | `list_accounts()`, `list_institutions()`, `list_reporters()`, `list_reports()` |
233
+ | `cadastro` | `info()`, `list_segmentos()`, `list_ufs()`, `get_conglomerate_members()` |
234
+
235
+ ## Limitacoes Conhecidas
236
+
237
+ - **Dependencia de APIs do BCB**: a coleta depende da disponibilidade dos endpoints publicos do Banco Central. Se a API estiver fora do ar ou mudar seu schema, a coleta pode falhar.
238
+ - **Dados historicos**: nem todos os periodos estao disponiveis para todas as fontes. Use `list_periods()` para verificar disponibilidade.
239
+ - **Primeira coleta lenta**: a coleta inicial de dados pode demorar dependendo do range de datas solicitado, pois faz requisicoes HTTP sequenciais ao BCB.
240
+ - **Cache sem invalidacao automatica**: dados coletados ficam em cache local indefinidamente. Para atualizar, colete novamente o periodo desejado.
241
+ - **Sem suporte offline**: a coleta requer conexao com a internet. A leitura funciona offline se os dados ja estiverem em cache.
242
+
243
+ ## Contribuindo
244
+
245
+ Contribuicoes sao bem-vindas! Consulte o [guia de contribuicao](CONTRIBUTING.md) para detalhes sobre como participar.
246
+
247
+ ## Licenca
248
+
249
+ Distribuido sob a licenca MIT. Veja [LICENSE](LICENSE) para mais informacoes.