### Install Fundamentus Library Source: https://context7.com/mv/fundamentus-api/llms.txt Installs the Fundamentus Python library using pip. This is the first step to using the library's functionalities for accessing financial data. ```bash pip install fundamentus ``` -------------------------------- ### Get Raw Company Financial Multiples (Python) Source: https://github.com/mv/fundamentus-api/blob/main/README.md Fetches a DataFrame with raw financial multiples, preserving original column names from the Fundamentus website. These names are in Portuguese, may contain spaces and accents, requiring explicit filtering. ```python >>> import fundamentus >>> df = fundamentus.get_resultado_raw() >>> print(df.columns) Index(['Cotação', 'P/L', 'P/VP', 'PSR', 'Div.Yield', 'P/Ativo', 'P/Cap.Giro', 'P/EBIT', 'P/Ativ Circ.Liq', 'EV/EBIT', 'EV/EBITDA', 'Mrg Ebit', 'Mrg. Líq.', 'Liq. Corr.', 'ROIC', 'ROE', 'Liq.2meses', 'Patrim. Líq', 'Dív.Brut/ Patrim.', 'Cresc. Rec.5a'], dtype='object', name='Multiples') >>> print( df[ df['P/L'] > 0] ) papel Cotação P/L P/VP ... Dív.Brut/ Patrim. Cresc. Rec.5a ABCB4 15.81 9.66 0.83 ... 0.00 -0.5287 ABEV3 15.95 28.87 3.22 ... 0.09 0.0455 AEDU11 37.35 20.13 1.13 ... 0.30 0.2090 ... ... ... ... ... ... ... WIZS3 7.95 5.96 3.61 ... 0.00 0.1737 WSON33 45.45 34.29 1.34 ... 1.11 0.0131 YDUQ3 33.26 39.71 3.10 ... 1.45 0.0449 # filter on DataFrame df = df[ df['P/L'] > 0 ] df = df[ df['P/L'] < 100 ] df = df[ df['P/VP'] > 0 ] ``` -------------------------------- ### Get Company Financial Multiples (Python) Source: https://github.com/mv/fundamentus-api/blob/main/README.md Fetches a DataFrame containing financial multiples for companies. The column names are simplified for easier filtering. It handles filtering based on these simplified names. ```python >>> import fundamentus >>> df = fundamentus.get_resultado() >>> print(df.columns) Index(['cotacao', 'pl', 'pvp', 'psr', 'dy', 'pa', 'pcg', 'pebit', 'pacl', 'evebit', 'evebitda', 'mrgebit', 'mrgliq', 'roic', 'roe', 'liqc', 'liq2m', 'patrliq', 'divbpatr', 'c5y'], dtype='object', name='Multiples') >>> print( df[ df.pl > 0] ) papel cotacao pl pvp ... divbpatr c5y ABCB4 15.81 9.66 0.83 ... 0.00 -0.5287 ABEV3 15.95 28.87 3.22 ... 0.09 0.0455 AEDU11 37.35 20.13 1.13 ... 0.30 0.2090 ... ... ... ... ... ... ... WIZS3 7.95 5.96 3.61 ... 0.00 0.1737 WSON33 45.45 34.29 1.34 ... 1.11 0.0131 YDUQ3 33.26 39.71 3.10 ... 1.45 0.0449 # filter on DataFrame df = df[ df.pl > 0 ] df = df[ df.pl < 100 ] df = df[ df.pvp > 0 ] ``` -------------------------------- ### Get Specific Stock Data (Python) Source: https://github.com/mv/fundamentus-api/blob/main/README.md Fetches detailed financial data for a specific stock ticker or a list of tickers. The returned DataFrame includes various financial metrics for the requested companies. ```python >>> import fundamentus >>> df = fundamentus.get_papel('WEGE3') ## or... >>> df = fundamentus.get_papel(['ITSA4','WEGE3']) >>> print(df) Tipo Empresa Setor ... Receita_Liquida_3m EBIT_3m Lucro_Liquido_3m ITSA4 PN N1 ITAÚSA PN N1 Financeiros ... 1778000000 257000000 1784000000 WEGE3 ON N1 WEG SA ON N1 Máquinas e ... 4801260000 946670000 644246000 ``` -------------------------------- ### Get Market Screening Results (Raw Columns) Source: https://context7.com/mv/fundamentus-api/llms.txt Retrieves the market screening data with original Portuguese column names directly from the HTML source. This is useful when the exact original naming convention is required or for compatibility with external tools expecting these labels. Returns a Pandas DataFrame. ```python import fundamentus # Get raw data with original Portuguese column names df = fundamentus.get_resultado_raw() print(df.columns) # Filter using original Portuguese column names (requires bracket notation) filtered = df[df['P/L'] > 0] filtered = filtered[filtered['P/L'] < 100] filtered = filtered[filtered['P/VP'] > 0] print(filtered[['Cotação', 'P/L', 'P/VP', 'Div.Yield', 'ROE']].head()) ``` -------------------------------- ### Get Market Screening Results (Simplified Columns) Source: https://context7.com/mv/fundamentus-api/llms.txt Retrieves a market screening table with simplified, Python-friendly column names. This function is useful for quick analysis and filtering of stocks based on financial multiples. It returns a Pandas DataFrame indexed by stock ticker. ```python import fundamentus # Get all stocks with financial multiples df = fundamentus.get_resultado() # Available columns: # cotacao (price), pl (P/L), pvp (P/VP), psr (PSR), dy (Div.Yield), # pa (P/Ativo), pcg (P/Cap.Giro), pebit (P/EBIT), pacl (P/Ativ Circ.Liq), # evebit (EV/EBIT), evebitda (EV/EBITDA), mrgebit (Mrg Ebit), mrgliq (Mrg. Líq.), # roic (ROIC), roe (ROE), liqc (Liq. Corr.), liq2m (Liq.2meses), # patrliq (Patrim. Líq), divbpatr (Dív.Brut/Patrim.), c5y (Cresc. Rec.5a) print(df.columns) # Filter for value stocks with positive earnings value_stocks = df[df.pl > 0] value_stocks = value_stocks[value_stocks.pl < 15] value_stocks = value_stocks[value_stocks.pvp < 1.5] value_stocks = value_stocks[value_stocks.roe > 0.10] print(value_stocks[['cotacao', 'pl', 'pvp', 'dy', 'roe']].head(10)) ``` -------------------------------- ### Get Specific Stock Details Source: https://context7.com/mv/fundamentus-api/llms.txt Retrieves detailed financial information for one or more specific stock tickers. This function fetches company details, balance sheet data, income statement items, and financial indicators from the company's detail page on Fundamentus. Returns a Pandas DataFrame. ```python import fundamentus # Get details for a single stock df = fundamentus.get_papel('WEGE3') print(df.T) # Transpose for better readability # Get details for multiple stocks at once stocks = ['ITSA4', 'WEGE3', 'VALE3', 'PETR4'] df = fundamentus.get_papel(stocks) print(df[['Tipo', 'Setor', 'Cotacao', 'PL', 'PVP', 'ROE']]) ``` -------------------------------- ### Display Available Sectors Source: https://context7.com/mv/fundamentus-api/llms.txt Prints a formatted table listing all available sectors, including their labels, descriptions, and numeric IDs. ```python import fundamentus fundamentus.print_setores() ``` -------------------------------- ### print_setores Source: https://context7.com/mv/fundamentus-api/llms.txt Prints a formatted table of all available sectors with their labels, descriptions, and IDs. ```APIDOC ## GET /print_setores ### Description Prints a formatted table of all available sectors with their labels, descriptions, and IDs. ### Method GET ### Endpoint /print_setores ### Parameters None ### Request Example ```python import fundamentus fundamentus.print_setores() ``` ### Response #### Success Response (200) - **Formatted Table** - A string containing a formatted table of sectors, descriptions, and IDs printed to standard output. #### Response Example ``` label | desc | id -----------+--------------------------------------------+----- agro | Agropecuária | 1 saneamento | Água e Saneamento | 2 ... | ... | ... ``` ``` -------------------------------- ### Implement Magic Formula Strategy with Fundamentus Source: https://context7.com/mv/fundamentus-api/llms.txt This script retrieves market data, applies fundamental filters (P/L, ROIC, liquidity), removes financial sector stocks, and ranks the remaining assets based on the Magic Formula (EV/EBIT and ROIC). It outputs the top 20 ranked stocks for investment consideration. ```python import pandas as pd import fundamentus def filter_out_finance(data): """Remove financial sector stocks from analysis.""" df = data.copy() exclude = [] exclude += fundamentus.list_papel_setor(fundamentus.get_setor_id('financeiro')) exclude += fundamentus.list_papel_setor(fundamentus.get_setor_id('prev-seguros')) for ticker in exclude: try: df = df.drop(ticker) except KeyError: pass return df def magic_formula_ranking(data): """Apply Magic Formula ranking: EV/EBIT + ROIC.""" magic = data.copy() # Rank by EV/EBIT (lower is better) rank_evebit = data.sort_values('evebit', ascending=True).index df_rank1 = pd.DataFrame({'rank': range(1, len(data) + 1)}, index=rank_evebit) magic['rank_evebit'] = df_rank1['rank'] # Rank by ROIC (higher is better) rank_roic = data.sort_values('roic', ascending=False).index df_rank2 = pd.DataFrame({'rank': range(1, len(data) + 1)}, index=rank_roic) magic['rank_roic'] = df_rank2['rank'] # Combined Magic Formula rank magic['rank_magic'] = magic['rank_evebit'] + magic['rank_roic'] return magic.sort_values('rank_magic') # Get all stocks data = fundamentus.get_resultado() # Apply filters filtered = data[data.pl > 0] filtered = filtered[filtered.pl < 30] filtered = filtered[filtered.roic > 0] filtered = filtered[filtered.evebit > 0] filtered = filtered[filtered.divbpatr < 3] filtered = filtered[filtered.liq2m > 100000] # Remove financial stocks filtered = filter_out_finance(filtered) # Apply Magic Formula ranking ranked = magic_formula_ranking(filtered) # Top 20 stocks by Magic Formula top20 = ranked.head(20) print(top20[['cotacao', 'pl', 'evebit', 'roic', 'rank_evebit', 'rank_roic', 'rank_magic']]) ``` -------------------------------- ### List All Available Stocks Source: https://context7.com/mv/fundamentus-api/llms.txt Retrieves a complete list of all stock tickers currently available on the Fundamentus platform. ```python import fundamentus all_stocks = fundamentus.list_papel_all() print(f"Total stocks available: {len(all_stocks)}") ``` -------------------------------- ### list_papel_all Source: https://context7.com/mv/fundamentus-api/llms.txt Returns a list of all stock tickers available on Fundamentus. ```APIDOC ## GET /list_papel_all ### Description Returns a list of all stock tickers available on Fundamentus. ### Method GET ### Endpoint /list_papel_all ### Parameters None ### Request Example ```python import fundamentus all_stocks = fundamentus.list_papel_all() print(f"Total stocks available: {len(all_stocks)}") print(all_stocks[:10]) ``` ### Response #### Success Response (200) - **stocks** (list of strings) - A list of all available stock ticker symbols. #### Response Example ```json [ "AALR3", "ABCB4", "ABEV3", "AERI3", "AESB3", "AFLT3", "AGRO3", "AGXY3", "AHEB3", "ALLD3" ] ``` ``` -------------------------------- ### Retrieve Raw Stock Details Source: https://context7.com/mv/fundamentus-api/llms.txt Fetches raw HTML tables for a specific stock ticker. Returns a list of DataFrames containing summary, market value, indicators, and balance sheet data. ```python import fundamentus tables = fundamentus.get_detalhes_raw('VALE3') print(f"Number of tables: {len(tables)}") print(tables[0]) ``` -------------------------------- ### Output Data as CSV or Table Source: https://context7.com/mv/fundamentus-api/llms.txt Utility functions to format and print pandas DataFrames as either CSV strings or human-readable ASCII tables. ```python import fundamentus df = fundamentus.get_resultado() filtered = df[df.pl > 0][df.pl < 15] selected_cols = filtered[['cotacao', 'pl', 'pvp', 'dy', 'roe']] fundamentus.print_csv(selected_cols.head(5)) fundamentus.print_table(selected_cols.head(5)) ``` -------------------------------- ### print_csv and print_table Source: https://context7.com/mv/fundamentus-api/llms.txt Utility functions to output DataFrames in CSV format or as formatted ASCII tables. ```APIDOC ## Utility Functions: print_csv, print_table ### Description Utility functions to output DataFrames in CSV format or as formatted ASCII tables. ### Method Various (internal utility functions, typically called after retrieving data with other functions like `get_resultado`) ### Endpoint N/A (These are utility functions) ### Parameters #### `print_csv(dataframe)` - **dataframe** (pandas DataFrame) - The DataFrame to be printed in CSV format. #### `print_table(dataframe)` - **dataframe** (pandas DataFrame) - The DataFrame to be printed as a formatted table. ### Request Example ```python import fundamentus df = fundamentus.get_resultado() filtered = df[df.pl > 0][df.pl < 15] selected_cols = filtered[['cotacao', 'pl', 'pvp', 'dy', 'roe']] # Output as CSV fundamentus.print_csv(selected_cols.head(5)) # Output as formatted table fundamentus.print_table(selected_cols.head(5)) ``` ### Response #### Success Response (200) - **CSV Output** - Data printed to standard output in CSV format. - **Table Output** - Data printed to standard output as a formatted ASCII table. #### Response Example (CSV) ```csv papel,cotacao,pl,pvp,dy,roe ABCB4,15.8100,9.6600,0.8300,0.0528,0.0861 BBAS3,27.5000,4.8200,0.7800,0.0812,0.1620 ``` #### Response Example (Table) ``` papel | cotacao | pl | pvp | dy | roe ---------+-----------+--------+--------+---------+-------- ABCB4 | 15.81 | 9.66 | 0.83 | 0.0528 | 0.0861 BBAS3 | 27.5 | 4.82 | 0.78 | 0.0812 | 0.1620 ``` ``` -------------------------------- ### Map Sector Labels to IDs Source: https://context7.com/mv/fundamentus-api/llms.txt Converts a human-readable sector label string into the corresponding numeric ID required by the Fundamentus website. ```python import fundamentus finance_id = fundamentus.get_setor_id('financeiro') print(f"Finance sector ID: {finance_id}") ``` -------------------------------- ### List Stocks by Sector Source: https://context7.com/mv/fundamentus-api/llms.txt Retrieves a list of stock tickers associated with a specific sector ID. Requires the numeric sector ID as input. ```python import fundamentus mining_stocks = fundamentus.list_papel_setor(27) print(mining_stocks) ``` -------------------------------- ### get_detalhes_raw Source: https://context7.com/mv/fundamentus-api/llms.txt Retrieves raw HTML tables from the stock detail page without processing. Returns a list of DataFrames corresponding to each HTML table on the page, useful for advanced processing or debugging. ```APIDOC ## GET /detalhes_raw ### Description Retrieves raw HTML tables from the stock detail page without processing. Returns a list of DataFrames corresponding to each HTML table on the page, useful for advanced processing or debugging. ### Method GET ### Endpoint /detalhes_raw ### Parameters #### Query Parameters - **ticker** (string) - Required - The stock ticker symbol (e.g., 'VALE3'). ### Request Example ```python import fundamentus tables = fundamentus.get_detalhes_raw('VALE3') print(f"Number of tables: {len(tables)}") ``` ### Response #### Success Response (200) - **tables** (list of DataFrames) - A list where each element is a pandas DataFrame representing an HTML table from the stock detail page. #### Response Example ```json [ // DataFrame 0: Summary header // DataFrame 1: Market value and shares info // DataFrame 2: Price oscillations and fundamental indicators // DataFrame 3: Balance sheet data // DataFrame 4: Income statement ] ``` ``` -------------------------------- ### List Companies by Sector (Python) Source: https://github.com/mv/fundamentus-api/blob/main/README.md Retrieves a list of stock tickers belonging to a specific sector, identified by a sector code. This function is useful for obtaining all companies within a particular industry. ```python >>> import fundamentus >>> fin = fundamentus.list_papel_setor(35) # finance >>> seg = fundamentus.list_papel_setor(38) # seguradoras >>> print(fin) ['ABCB4', 'BBAS3', 'BBDC3', 'BBDC4', ... ] >>> print(seg) ['BBSE3', 'IRBR3', 'SULA4', 'WIZS3', ... ] ``` -------------------------------- ### list_papel_setor Source: https://context7.com/mv/fundamentus-api/llms.txt Returns a list of stock tickers belonging to a specific sector. Sectors are identified by their numeric ID from the Fundamentus website. ```APIDOC ## GET /list_papel_setor ### Description Returns a list of stock tickers belonging to a specific sector. Sectors are identified by their numeric ID from the Fundamentus website. ### Method GET ### Endpoint /list_papel_setor ### Parameters #### Query Parameters - **setor_id** (integer) - Required - The numeric ID of the sector. ### Request Example ```python import fundamentus mining_stocks = fundamentus.list_papel_setor(27) # Mining sector print(mining_stocks) ``` ### Response #### Success Response (200) - **stocks** (list of strings) - A list of stock ticker symbols belonging to the specified sector. #### Response Example ```json [ "VALE3", "CMIN3", "CSNA3" ] ``` ``` -------------------------------- ### get_setor_id Source: https://context7.com/mv/fundamentus-api/llms.txt Converts a sector label to its numeric ID used by the Fundamentus website. Labels use simplified Portuguese identifiers. ```APIDOC ## GET /get_setor_id ### Description Converts a sector label to its numeric ID used by the Fundamentus website. Labels use simplified Portuguese identifiers. ### Method GET ### Endpoint /get_setor_id ### Parameters #### Query Parameters - **label** (string) - Required - The simplified Portuguese sector label (e.g., 'financeiro', 'mineracao'). ### Request Example ```python import fundamentus finance_id = fundamentus.get_setor_id('financeiro') print(f"Finance sector ID: {finance_id}") ``` ### Response #### Success Response (200) - **sector_id** (integer) - The numeric ID of the sector. #### Response Example ```json { "sector_id": 20 } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.