brfinance

repository·master·Indexed 42 days ago

https://github.com/eudesrodrigo/brfinance

A Python library for accessing periodic financial data from Brazilian companies listed on B3/CVM. It provides the CVMAsyncBackend class to retrieve CVM company codes, search categories, and download detailed financial statements such as Balance Sheets, Income Statements, and Cash Flow Statements via methods like get_cvm_codes(), get_consulta_externa_cvm_results(), and get_report().

Tokens
2.3K
Snippets
7
Records
8
Agent score
4%

What's inside brfinance

  1. Use CVMAsyncBackend to fetch financial data

    master

    The primary way to interact with the library is through the CVMAsyncBackend class. You can use it to retrieve CVM company codes, search categories, search for specific reports, and download detailed financial statements.

    Workflow Example

    1. Initialize CVMAsyncBackend.
    2. Get company codes using get_cvm_codes().
    3. Get search categories using get_consulta_externa_cvm_categories().
    4. Search for reports using get_consulta_externa_cvm_results().
    5. Retrieve specific financial statements using get_report().
    from brfinance import CVMAsyncBackend
    import pandas as pd
    from datetime import datetime, date
    
    cvm_httpclient = CVMAsyncBackend()
    
    # 1. Get company codes
    cvm_codes = cvm_httpclient.get_cvm_codes()
    
    # 2. Get search categories
    categories = cvm_httpclient.get_consulta_externa_cvm_categories()
    
    # 3. Search for results
    start_date = date(2020, 1, 1)
    end_dt = date.today()
    cvm_codes_list = ['21610']
    category = ["EST_4", "EST_3", "IPE_4_-1_-1"]
    last_ref_date = False
    
    search_result = cvm_httpclient.get_consulta_externa_cvm_results(
        cod_cvm=cvm_codes_list,
        start_date=start_date,
        end_date=end_dt,
        last_ref_date=last_ref_date,
        category=category
    )
    
    # 4. Get specific reports (e.g., Balance Sheet)
    reports_list = ['Balanço Patrimonial Ativo', 'Demonstração do Resultado']
    for index, row in search_result.iterrows():
        reports = cvm_httpclient.get_report(
            row["numero_seq_documento"],
            row["codigo_tipo_instituicao"],
            reports_list=reports_list
        )
        print(reports['Balanço Patrimonial Ativo'].head())
  2. Initialize the CVMAsyncBackend client

    master

    To interact with CVM data, import and instantiate the CVMAsyncBackend class. This client serves as the primary interface for retrieving company codes, search categories, and financial reports.

    from brfinance import CVMAsyncBackend
    
    cvm_httpclient = CVMAsyncBackend()
  3. CVMAsyncBackend API Reference

    master

    The CVMAsyncBackend class provides the following methods for interacting with CVM data:

    class CVMAsyncBackend:
        def get_cvm_codes() -> dict:
            """Returns a dictionary with CVM code as key and company name as value."""
    
        def get_consulta_externa_cvm_categories() -> dict:
            """Returns a dictionary with search category codes and their descriptions (e.g., DFP, ITR)."""
    
        def get_consulta_externa_cvm_results(cod_cvm, start_date, end_date, last_ref_date, report_type) -> pd.DataFrame:
            """Returns a DataFrame containing search results based on the provided parameters."""
    
        def get_report(numero_seq_documento, codigo_tipo_instituicao, reports_list, previous_results) -> dict:
            """Returns a dictionary where keys are report names and values are DataFrames containing the financial statements."""
  4. Available financial statement names for get_report

    master

    When calling get_report, you can specify which financial statements to retrieve using the reports_list parameter. The following exact strings are supported:

    • Balanço Patrimonial Ativo (Balance sheet - Assets)
    • Balanço Patrimonial Passivo (Balance sheet - Liabilities)
    • Demonstração do Resultado (Income statement)
    • Demonstração do Resultado Abrangente (Comprehensive income statement)
    • Demonstração do Fluxo de Caixa (Cash flow statement)
    • Demonstração das Mutações do Patrimônio Líquido (Statement of changes in equity)
    • Demonstração de Valor Adicionado (Statement of added value)

    If None is passed, all available statements are returned.

  5. Search for financial results using get_consulta_externa_cvm_results

    master

    Perform a search for financial documents within a specific date range and for specific companies.

    Parameters:

    • start_date (date): The beginning of the search period.
    • end_date (date): The end of the search period.
    • cod_cvm (list): A list of CVM company codes.
    • participant_type (list): A list of participant type identifiers (e.g., [1] for 'Companhia aberta').
    • category (list): A list of category codes (e.g., ["EST_3", "EST_4"]).
    • last_ref_date (bool): If True, returns only the last report within the date range.
    from datetime import date
    
    search_result = cvm_httpclient.get_consulta_externa_cvm_results(
        start_date=date(2021, 1, 1),
        end_date=date.today(),
        cod_cvm=[21610],
        participant_type=[1],
        category=["EST_3", "EST_4", "IPE_4_-1_-1"],
        last_ref_date=False
    )
  6. Retrieve CVM company codes, categories, and participant types

    master

    Use the following methods to discover valid identifiers for your queries:

    • get_cvm_codes(): Returns a dictionary mapping CVM codes to company names.
    • get_consulta_externa_cvm_categories(): Returns a dictionary of available search categories (e.g., Fato relevante, DFP, ITR).
    • get_consulta_externa_cvm_tipo_participante(): Returns a dictionary of available participant types.
    # Get company codes
    cvm_codes = cvm_httpclient.get_cvm_codes()
    
    # Get search categories
    categories = cvm_httpclient.get_consulta_externa_cvm_categories()
    
    # Get participant types
    tipo_participante = cvm_httpclient.get_consulta_externa_cvm_tipo_participante()
  7. Retrieve specific financial reports with get_report

    master

    Once you have identified a document from a search result, use get_report to fetch the actual financial statements.

    Parameters:

    • numero_seq_documento: The document sequence number.
    • codigo_tipo_instituicao: The institution type code.
    • reports_list (list, optional): A list of specific report names to retrieve. If None, all available reports are returned.

    Supported report names in reports_list:

    • 'Balanço Patrimonial Ativo'
    • 'Balanço Patrimonial Passivo'
    • 'Demonstração do Resultado'
    • 'Demonstração do Resultado Abrangente'
    • 'Demonstração do Fluxo de Caixa'
    • 'Demonstração das Mutações do Patrimônio Líquido'
    • 'Demonstração de Valor Adicionado'
    # Example: Fetching specific reports for a document found in search_result
    reports = cvm_httpclient.get_report(
        row["numero_seq_documento"],
        row["codigo_tipo_instituicao"],
        reports_list=[
            'Balanço Patrimonial Ativo',
            'Demonstração do Resultado'
        ]
    )
    
    # The returned 'reports' is a dictionary where keys are report names
    # and values are pandas DataFrames.
    for report_name, df in reports.items():
        print(f"Report: {report_name}")
        print(df.head())