### Basic Investpy Usage Example Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/README.md Demonstrates fetching recent and historical stock data, searching for products, retrieving technical indicators, and accessing the economic calendar. Ensure investpy is installed. ```python import investpy # Get recent stock data data = investpy.get_stock_recent_data(stock='AAPL', country='United States') print(data.head()) # Get historical data hist = investpy.get_stock_historical_data( stock='AAPL', country='United States', from_date='01/01/2020', to_date='01/01/2024' ) # Search for a product result = investpy.search_quotes(text='apple', products=['stocks'], n_results=1) print(f"Symbol: {result.symbol}") # Get technical indicators indicators = investpy.technical_indicators( name='AAPL', country='United States', product_type='stock' ) print(indicators) # Get economic calendar calendar = investpy.economic_calendar() print(calendar) ``` -------------------------------- ### Example: Fetch and Display Recent EUR/USD Data Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/currency_crosses.md Demonstrates how to retrieve recent historical data for the EUR/USD currency cross using investpy and display the first few rows. Ensure the 'investpy' library is installed. ```pycon >>> data = investpy.get_currency_cross_recent_data(currency_cross='EUR/USD') >>> data.head() Open High Low Close Currency Date 2019-08-27 1.1101 1.1116 1.1084 1.1091 USD 2019-08-28 1.1090 1.1099 1.1072 1.1078 USD 2019-08-29 1.1078 1.1093 1.1042 1.1057 USD 2019-08-30 1.1058 1.1062 1.0963 1.0991 USD 2019-09-02 1.0990 1.1000 1.0958 1.0968 USD ``` -------------------------------- ### Usage Examples Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/00-CONTENTS.txt A collection of 50+ working code examples demonstrating various library functionalities. ```APIDOC ## Usage Examples This section contains 50+ working code examples covering: - Basic data retrieval patterns - Searching for products - Asset class-specific examples (stocks, cryptos, indices, etc.) - Technical analysis workflows - Economic calendar usage - Data analysis patterns - Bulk operations - Comprehensive error handling examples - Real-world scenarios ``` -------------------------------- ### Get Crypto Information Example Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/crypto.md Retrieves fundamental financial information for a specified cryptocurrency. The output can be a pandas DataFrame or a dictionary. ```default crypto_information = { 'Chg (7D)': '-4.63%', 'Circulating Supply': ' BTC18.10M', 'Crypto Currency': 'Bitcoin', 'Currency': 'USD', 'Market Cap': '$129.01B', 'Max Supply': 'BTC21.00M', 'Todays Range': '7,057.8 - 7,153.1', 'Vol (24H)': '$17.57B' } ``` -------------------------------- ### Install investpy from source Source: https://github.com/alvarobartt/investpy/blob/master/README.md Install the latest investpy version directly from the master branch of the GitHub repository. This ensures you have the most up-to-date features. ```bash pip install git+https://github.com/alvarobartt/investpy.git@master ``` -------------------------------- ### Search and Retrieve Financial Data with investpy Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/02-search.md Use this workflow to search for a financial product, retrieve its recent and historical data, get technical indicators, and access product information and currency. Ensure investpy is installed and imported. ```python import investpy # 1. Search for a product search_result = investpy.search_quotes( text='tesla', products=['stocks'], countries=['united states'], n_results=1 ) # 2. Retrieve recent data recent_data = search_result.retrieve_recent_data() print(recent_data.tail(5)) # 3. Retrieve historical data historical_data = search_result.retrieve_historical_data( from_date='01/01/2020', to_date='01/01/2022' ) # 4. Get technical indicators indicators = search_result.retrieve_technical_indicators(interval='daily') print(indicators) # 5. Get product information info = search_result.retrieve_information() print(f"Market Cap: {info['marketCap']}") # 6. Get default currency currency = search_result.retrieve_currency() print(f"Trading Currency: {currency}") ``` -------------------------------- ### Install investpy via pip Source: https://github.com/alvarobartt/investpy/blob/master/README.md Install the stable version of the investpy package using pip. Requires Python 3.6 or higher. ```bash pip install investpy ``` -------------------------------- ### Get Pivot Points for a Currency Pair Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Retrieves pivot points for a currency pair. This example demonstrates fetching data for a currency cross without specifying a country. ```python import investpy # Get pivot points for a currency pair pivots = investpy.pivot_points( name='EUR/USD', country=None, product_type='currency_cross' ) print(f"Pivot: {pivots['Pivot'].values[0]}") print(f"Support 1: {pivots['S1'].values[0]}") print(f"Resistance 1: {pivots['R1'].values[0]}") ``` -------------------------------- ### Get Certificates Overview Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves an overview DataFrame for certificates. Optionally filter by country. ```python def get_certificates_overview(country=None): ``` ``` -------------------------------- ### Get Stock Historical Data - Python Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_info/usage.md Retrieves historical stock data for a specified period. Ensure you have the investpy library installed. ```python import investpy df = investpy.get_stock_historical_data(stock='AAPL', country='United States', from_date='01/01/2010', to_date='01/01/2020') print(df.head()) ``` ```default Open High Low Close Volume Currency Date 2010-01-04 30.49 30.64 30.34 30.57 123432176 USD 2010-01-05 30.66 30.80 30.46 30.63 150476160 USD 2010-01-06 30.63 30.75 30.11 30.14 138039728 USD 2010-01-07 30.25 30.29 29.86 30.08 119282440 USD 2010-01-08 30.04 30.29 29.87 30.28 111969192 USD ``` -------------------------------- ### Get Crypto Currencies Overview Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/crypto.md Retrieves an overview of main crypto currencies with real-time data. Use to get a general view of the market. The `n_results` parameter can limit the number of returned cryptocurrencies. ```python import investpy cryptos_overview = investpy.crypto.get_cryptos_overview() print(cryptos_overview.head()) ``` -------------------------------- ### Get Funds Overview Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves an overview DataFrame for funds. Optionally filter by country. ```python def get_funds_overview(country=None): ``` -------------------------------- ### Get ETFs Overview Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves an overview DataFrame of ETFs. Optionally filter by country. ```python def get_etfs_overview(country=None): ``` -------------------------------- ### Get All Funds as DataFrame Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/funds.md Retrieves all available funds from Investing.com and returns them as a pandas DataFrame. This includes all fields from the funds.csv file. ```python import investpy funds_df = investpy.funds.get_funds() print(funds_df.head()) ``` -------------------------------- ### Get List of Cryptocurrencies Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/03-crypto.md Retrieves a list of all supported cryptocurrencies. Use this to see available options. ```python import investpy # 1. Get list of cryptocurrencies cryptos = investpy.get_cryptos_list() print(f"Available cryptos: {len(cryptos)}") ``` -------------------------------- ### Get List of Certificate Names Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of all available certificate names. Optionally filter by country. ```python def get_certificates_list(country=None): ``` ``` -------------------------------- ### Get Stock Financial Summary Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/01-stocks.md Fetches a summary of financial information for a stock. Requires stock symbol and country. ```python import investpy summary = investpy.get_stock_financial_summary(stock='IBM', country='United States') ``` -------------------------------- ### Search for Multiple Products Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Search for multiple financial products across different countries. This example looks for 'bank' stocks in Spain and France, returning up to 10 results. ```python import investpy # Search for multiple products results = investpy.search_quotes( text='bank', products=['stocks'], countries=['spain', 'france'], n_results=10 ) for result in results: print(f"{result.symbol}: {result.name} ({result.country})") ``` -------------------------------- ### Calculate Returns with Pandas Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/INDEX.md Demonstrates how to calculate daily returns from historical stock data using pandas. Assumes data is already retrieved. ```python import investpy import pandas as pd data = investpy.get_stock_historical_data(stock='AAPL', country='United States', from_date='01/01/2023', to_date='31/12/2023', interval='Daily') returns = pd.DataFrame(data['Close'].pct_change()) print(returns.head()) ``` -------------------------------- ### Basic Product Search Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Perform a basic search for a financial product using text, product type, country, and the number of results. This example searches for 'apple' stocks in the United States. ```python import investpy # Search for a product result = investpy.search_quotes( text='apple', products=['stocks'], countries=['united states'], n_results=1 ) print(f"Name: {result.name}") print(f"Symbol: {result.symbol}") print(f"Exchange: {result.exchange}") ``` -------------------------------- ### Get Historical ETF Data Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves historical OHLCV data for a specific ETF within a date range. Requires ETF symbol, country, start date, and end date. Supports JSON output and custom sort order. ```python def get_etf_historical_data( etf, country, from_date, to_date, as_json=False, order="ascending" ): ``` -------------------------------- ### Retrieve Product Information with SearchObj Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/02-search.md Use 'retrieve_information' to get detailed product information and financial metrics. The results are stored in the 'information' attribute as a dictionary. ```python import investpy result = investpy.search_quotes(text='apple', products=['stocks'], n_results=1) info = result.retrieve_information() print(f"Market Cap: {info.get('marketCap')}") print(f"P/E Ratio: {info.get('ratio')}") ``` -------------------------------- ### Get Fund Recent Data (DataFrame Format) Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/funds.md Retrieves recent historical data for a specified fund in a pandas DataFrame. The data includes Open, High, Low, Close prices and Currency. This example shows the first few rows of the returned DataFrame. ```python >>> data = investpy.get_fund_recent_data(fund='bbva multiactivo conservador pp', country='spain') >>> data.head() Open High Low Close Currency Date 2019-08-13 1.110 1.110 1.110 1.110 EUR 2019-08-16 1.109 1.109 1.109 1.109 EUR 2019-08-19 1.114 1.114 1.114 1.114 EUR 2019-08-20 1.112 1.112 1.112 1.112 EUR 2019-08-21 1.115 1.115 1.115 1.115 EUR ``` -------------------------------- ### Download Data for Multiple Stocks Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Demonstrates how to fetch recent data for a list of stocks from a specific country and combine them into a single DataFrame. Includes error handling for individual stock downloads. ```python import investpy import pandas as pd from datetime import datetime # Get list of stocks from a country stocks = investpy.get_stocks_list(country='Spain') # Download data for all stocks all_data = {} for stock in stocks[:10]: # Limit to first 10 try: data = investpy.get_stock_recent_data( stock=stock, country='Spain' ) all_data[stock] = data print(f"Downloaded: {stock}") except Exception as e: print(f"Failed to download {stock}: {e}") # Combine all data combined = pd.concat(all_data, names=['Symbol', 'Date']) print(combined.head()) ``` -------------------------------- ### Compare Multiple Stocks Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Fetch recent closing prices for multiple stocks and create a normalized comparison DataFrame. Requires pandas. ```python import investpy # Get data for multiple stocks stocks = ['AAPL', 'MSFT', 'GOOGL'] data_dict = {} for stock in stocks: data = investpy.get_stock_recent_data( stock=stock, country='United States' ) data_dict[stock] = data['Close'] # Create comparison DataFrame comparison = pd.concat(data_dict, axis=1) comparison_normalized = comparison / comparison.iloc[0] * 100 # Normalize to 100 print(comparison_normalized) ``` -------------------------------- ### Get All Stocks by Country Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/stocks.md Retrieves a DataFrame of all available stocks for a specified country from the stocks.csv file. This function is useful for getting a list of stocks to analyze further. ```default country | name | full name | isin | currency | symbol --------|------|-----------|------|----------|-------- xxxxxxx | xxxx | xxxxxxxxx | xxxx | xxxxxxxx | xxxxxx ``` -------------------------------- ### investpy.certificates.get_certificates_overview Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/api.md Retrieves an overview of available certificates. ```APIDOC ## investpy.certificates.get_certificates_overview ### Description Get certificates overview. ### Method `get_certificates_overview()` ### Parameters This function does not explicitly list parameters in the provided documentation. ``` -------------------------------- ### Get List of All Fund Names Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/funds.md Retrieves a list of all available fund names from Investing.com. This function is useful for getting a quick overview of fund names. ```python import investpy funds_list = investpy.funds.get_funds_list() print(funds_list) ``` -------------------------------- ### Get Fund Data in Python Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Retrieve a list of available funds for a specific country and fetch recent data for a particular fund. ```python import investpy # Get funds from a country funds = investpy.get_funds_list(country='France') print(f"Available funds: {len(funds)}") # Get recent data data = investpy.get_fund_recent_data( fund='Carmignac Patrimoine', country='France' ) ``` -------------------------------- ### Get All Cryptocurrencies Data Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/03-crypto.md Retrieves a DataFrame containing data for all supported cryptocurrencies. Useful for getting a comprehensive list of available cryptos and their basic information. ```python import investpy cryptos = investpy.get_cryptos() print(cryptos.head()) ``` -------------------------------- ### Compare Multiple Assets Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/INDEX.md Compares the performance of multiple assets by retrieving their historical data and plotting their closing prices. Ensure all assets are valid. ```python import investpy import pandas as pd import matplotlib.pyplot as plt stocks = ['AAPL', 'MSFT', 'GOOG'] all_data = pd.DataFrame() for stock in stocks: data = investpy.get_stock_historical_data(stock=stock, country='United States', from_date='01/01/2023', to_date='31/12/2023', interval='Daily') all_data[stock] = data['Close'] plt.figure(figsize=(12, 6)) plt.plot(all_data) plt.legend(all_data.columns) plt.show() ``` -------------------------------- ### Get Crypto Historical Data Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/crypto.md Retrieves historical data for a specified cryptocurrency. Use this to get daily, weekly, or monthly price and volume information. The data can be returned as a pandas DataFrame or a JSON object. ```python >>> data = investpy.get_crypto_historical_data(crypto='bitcoin', from_date='01/01/2018', to_date='01/01/2019') >>> data.head() Open High Low Close Volume Currency Date 2018-01-01 13850.5 13921.5 12877.7 13444.9 78425 USD 2018-01-02 13444.9 15306.1 12934.2 14754.1 137732 USD 2018-01-03 14754.1 15435.0 14579.7 15156.6 106543 USD 2018-01-04 15156.5 15408.7 14244.7 15180.1 110969 USD 2018-01-05 15180.1 17126.9 14832.4 16954.8 141960 USD ``` -------------------------------- ### Get Recent Stock Data Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/01-stocks.md Retrieves recent historical data for a stock. Specify 'as_json=True' to get a JSON string, otherwise a pandas DataFrame is returned. The 'interval' parameter can be 'Daily', 'Weekly', or 'Monthly'. ```python def get_stock_recent_data( stock, country, as_json=False, order="ascending", interval="Daily" ): """ stock: str Stock symbol to retrieve data for. country: str Country where the stock is listed. as_json: bool, optional Return as JSON if True, pandas.DataFrame if False. order: str, optional "ascending" or "descending" for sort order. interval: str, optional "Daily", "Weekly", or "Monthly". Returns: pandas.DataFrame or str (JSON) """ ``` ```python import investpy # Get recent data as DataFrame data = investpy.get_stock_recent_data( stock='BBVA', country='Spain' ) print(data.head()) # Get as JSON with weekly data json_data = investpy.get_stock_recent_data( stock='AAPL', country='United States', as_json=True, interval='Weekly' ) ``` -------------------------------- ### Find All Events for a Date Range and Forecast Misses Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/06-economic-calendar.md Retrieve all economic events within a specified date range. This example also shows how to group events by country and identify events where the actual value differed from the forecast. ```python import investpy calendar = investpy.economic_calendar( from_date='01/01/2023', to_date='31/01/2023' ) # Group by country by_country = calendar.groupby('zone').size() print(by_country) # Find events with forecast misses misses = calendar[ (calendar['actual'].notna()) & (calendar['forecast'].notna()) & (calendar['actual'] != calendar['forecast']) ] print(f"Events with forecast misses: {len(misses)}") ``` -------------------------------- ### Get Index Countries Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of countries for which index data is available. ```python def get_index_countries(): ``` -------------------------------- ### Get Fund Countries Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of countries for which fund data is available. ```python def get_fund_countries(): ``` -------------------------------- ### Analyze Technical Indicators for Decision-Making Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/05-technical-analysis.md This workflow demonstrates how to fetch various technical indicators (RSI, moving averages, pivot points) and recent stock data to inform investment decisions. It includes checking RSI for oversold/overbought conditions and printing support/resistance levels. ```python import investpy # Example: Analyze technical indicators for decision-making # 1. Get technical indicators indicators = investpy.technical_indicators( name='MSFT', country='United States', product_type='stock', interval='daily' ) # 2. Check RSI for oversold/overbought rsi = indicators[indicators['technical_indicator'] == 'RSI(14)'] rsi_value = rsi['value'].values[0] if rsi_value < 30: print("Oversold (RSI < 30)") elif rsi_value > 70: print("Overbought (RSI > 70)") # 3. Get moving averages ma = investpy.moving_averages( name='MSFT', country='United States', product_type='stock', interval='daily' ) # 4. Get pivot points pivots = investpy.pivot_points( name='MSFT', country='United States', product_type='stock' ) print(f"Support 1: {pivots['S1'].values[0]}") print(f"Resistance 1: {pivots['R1'].values[0]}") # 5. Get recent data recent = investpy.get_stock_recent_data( stock='MSFT', country='United States' ) current_price = recent['Close'].iloc[-1] print(f"Current Price: {current_price}") ``` -------------------------------- ### Get ETF Countries Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of countries for which ETF data is available. ```python def get_etf_countries(): """ Returns: list """ ``` -------------------------------- ### investpy.certificates.get_certificates_overview Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/certificates.md Retrieves a real-time overview of main certificates from a specified country, including names, symbols, current values, and change percentages. It defaults to the top 100 results but can be configured with `n_results`. ```APIDOC ## investpy.certificates.get_certificates_overview(country, as_json=False, n_results=100) ### Description This function retrieves an overview containing all the real-time data available for the main certificates from a country, such as the names, symbols, current value, etc. as indexed in Investing.com. The main usage of this function is to get an overview on the main certificates from a country for a general view. ### Parameters #### Path Parameters - **country** (str) - The name of the country to retrieve the certificates overview from. - **as_json** (bool, optional) - Optional argument to determine the format of the output data (`pandas.DataFrame` or `json`). Defaults to False. - **n_results** (int, optional) - Number of results to be displayed on the overview table (0-1000). Defaults to 100. ### Returns - **pandas.DataFrame** - A DataFrame containing the certificates overview with columns: `country`, `name`, `symbol`, `last`, `change_percentage`, `turnover`. ### Raises - **ValueError** - Raised if any of the introduced arguments is not valid or errored. - **FileNotFoundError** - Raised when certificates.csv file is missing. - **IOError** - Raised if data could not be retrieved due to file error. - **RuntimeError** - Raised either if the introduced country does not match any of the listed ones or if no overview results could be retrieved from Investing.com. - **ConnectionError** - Raised if GET requests does not return 200 status code. ``` -------------------------------- ### Get Certificate Information Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves detailed information for a specific certificate, filtered by country. ```python def get_certificate_information(certificate, country): ``` ``` -------------------------------- ### Stock/Fund/ETF Listing DataFrame Structure Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/08-types-and-constants.md Illustrates the structure of the DataFrame returned by get_stocks(), get_funds(), and get_etfs(). It shows the columns and their typical data. ```python country name full_name isin currency symbol 0 spain BBVA Banco Bilbao Vizcaya Argentaria ES0113900J37 EUR BBVA 1 spain BANCO Banco Santander ES0113900J37 EUR SAN 2 spain Telefonica Telefonica, S.A. ES0113900J37 EUR TEF ``` -------------------------------- ### retrieve_information() Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/02-search.md Retrieves detailed product information and financial metrics. The information is returned as a dictionary and also stored in the `information` attribute of the object. ```APIDOC ## retrieve_information() ### Description Retrieve product information and financial metrics. ### Method GET (Implicit) ### Parameters None ### Response #### Success Response (200) - **information** (dict) - Dictionary containing product information such as price metrics, volume metrics, financial metrics, dividend info, and date-based info. ### Request Example ```python import investpy result = investpy.search_quotes(text='apple', products=['stocks'], n_results=1) info = result.retrieve_information() print(f"Market Cap: {info.get('marketCap')}") print(f"P/E Ratio: {info.get('ratio')}") ``` ``` -------------------------------- ### Get Countries with Certificate Data Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of countries for which certificate data is available. ```python def get_certificate_countries(): ``` ``` -------------------------------- ### Get Bonds Overview Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves an overview DataFrame for bonds. Optionally filter by country. ```python def get_bonds_overview(country=None): ``` ``` -------------------------------- ### retrieve_information() Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/search.md Retrieves general information for a financial product from Investing.com using search results. ```APIDOC ## retrieve_information() ### Description Class method used to retrieve the information from the class instance of any financial product. This method retrieves the information from Investing.com of the financial product of the current class instance, so it fills the SearchObj.info attribute with the retrieved `dict`. This method uses the previously retrieved data from the investpy.search_quotes(text, products, countries, n_results) function search results to build the request that it is going to be sent to Investing.com so to retrieve and parse the information, since the product tag is required. ### Returns This method retrieves the information from the current class instance of a financial product from Investing.com. This method both stores retrieved information in self.information attribute of the class instance and it also returns it as a normal function will do. * **Return type:** `dict` - info ### Raises * **ConnectionError** – raised if connection to Investing.com could not be established. * **RuntimeError** – raised if there was any problem while retrieving the data from Investing.com. ``` -------------------------------- ### Get Bond Information Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves detailed information for a specific bond, filtered by country. ```python def get_bond_information(bond, country): ``` ``` -------------------------------- ### Get ETF Data in Python Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Fetch lists of ETFs, recent data for a specific ETF, and historical data for a given date range. ```python import investpy # Get all ETFs from a country all_etfs = investpy.get_etfs(country='Germany') print(f"Total ETFs: {len(all_etfs)}") # Get recent data for an ETF data = investpy.get_etf_recent_data( etf='iShares Core DAX', country='Germany' ) # Get historical data hist_data = investpy.get_etf_historical_data( etf='iShares Core DAX', country='Germany', from_date='01/01/2023', to_date='01/01/2024' ) ``` -------------------------------- ### Get Countries with Bond Data Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of countries for which bond data is available. ```python def get_bond_countries(): ``` ``` -------------------------------- ### Get Indices Overview Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves an overview DataFrame for indices. Optionally filter by country. ```python def get_indices_overview(country=None): ``` -------------------------------- ### Search Financial Products with investpy Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_info/usage.md Use this function to search for financial products like stocks, specifying text, product types, countries, and the number of results. The output is a list of SearchObj instances or a single instance if n_results is 1. ```python import investpy search_result = investpy.search_quotes(text='apple', products=['stocks'], countries=['united states'], n_results=1) print(search_result) ``` ```default {"id_": 6408, "name": "Apple Inc", "symbol": "AAPL", "country": "united states", "tag": "/equities/apple-computer-inc", "pair_type": "stocks", "exchange": "NASDAQ"} ``` -------------------------------- ### Get Indices List Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of index symbols. Optionally filter by country. ```python def get_indices_list(country=None): ``` -------------------------------- ### Get Funds List Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of fund symbols. Optionally filter by country. ```python def get_funds_list(country=None): ``` -------------------------------- ### Get Stock Data with Different Intervals Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/09-usage-examples.md Retrieve stock data at different intervals: Daily, Weekly, or Monthly. The 'Daily' interval is the default if not specified. ```python import investpy # Daily data (default) daily = investpy.get_stock_recent_data( stock='MSFT', country='United States', interval='Daily' ) # Weekly data weekly = investpy.get_stock_recent_data( stock='MSFT', country='United States', interval='Weekly' ) # Monthly data monthly = investpy.get_stock_recent_data( stock='MSFT', country='United States', interval='Monthly' ) print(f"Daily: {len(daily)} records") print(f"Weekly: {len(weekly)} records") print(f"Monthly: {len(monthly)} records") ``` -------------------------------- ### Get Funds Data Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a DataFrame with fund data. Optionally filter by country. ```python def get_funds(country=None): ``` -------------------------------- ### investpy.commodities.get_commodities_overview Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/api.md Retrieves an overview of available commodities. ```APIDOC ## investpy.commodities.get_commodities_overview ### Description Get commodities overview. ### Method `get_commodities_overview()` ### Parameters This function does not explicitly list parameters in the provided documentation. ``` -------------------------------- ### Get ETF List Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a list of ETF symbols. Optionally filter by country. ```python def get_etfs_list(country=None): ``` -------------------------------- ### get_etfs_overview() Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves an overview of ETFs for a specified country. If no country is provided, it returns the overview for all available countries. ```APIDOC ## get_etfs_overview() ### Description Retrieves an overview of ETFs for a specified country. If no country is provided, it returns the overview for all available countries. ### Method ```python def get_etfs_overview(country=None): ``` ### Parameters #### Path Parameters - **country** (str) - Optional - Country name to filter ETF overview by. Returns all if None. ``` -------------------------------- ### Get Funds by Country and Columns as Dictionary Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/funds.md Retrieves specific fund data for a given country and returns it as a dictionary. You can specify which columns to retrieve. ```python import investpy funds_dict_spain = investpy.funds.get_funds_dict(country='Spain', columns=[ 'name', 'symbol', 'currency' ]) print(funds_dict_spain.head()) ``` -------------------------------- ### Get Fund Information Structure Source: https://github.com/alvarobartt/investpy/blob/master/docs/source/_api/funds.md This is the structure of the dictionary returned when requesting fund information with as_json=True. ```default fund_information = { 'Fund Name': fund_name, 'Rating': rating, '1-Year Change': year_change, 'Previous Close': prev_close, 'Risk Rating': risk_rating, 'TTM Yield': ttm_yield, 'ROE': roe, 'Issuer': issuer, 'Turnover': turnover, 'ROA': row, 'Inception Date': inception_date, 'Total Assets': total_assets, 'Expenses': expenses, 'Min Investment': min_investment, 'Market Cap': market_cap, 'Category': category } ``` -------------------------------- ### Basic investpy Error Handling Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/07-errors-and-exceptions.md Demonstrates handling common exceptions like ValueError, RuntimeError, ConnectionError, and IndexError when fetching stock data. ```python import investpy # Handling ValueError for invalid parameters try: data = investpy.get_stock_recent_data( stock='INVALID', country='Invalid Country' ) except ValueError as e: print(f"Validation error: {e}") # Handling RuntimeError for product not found try: data = investpy.get_stock_recent_data( stock='NONEXISTENT', country='Spain' ) except RuntimeError as e: print(f"Product not found: {e}") # Handling ConnectionError for network issues try: data = investpy.get_stock_recent_data( stock='AAPL', country='United States' ) except ConnectionError as e: print(f"Connection failed: {e}") # Handling IndexError for unavailable data try: data = investpy.get_stock_recent_data( stock='AAPL', country='United States' ) except IndexError as e: print(f"Data unavailable: {e}") ``` -------------------------------- ### Get Indices Data Source: https://github.com/alvarobartt/investpy/blob/master/_autodocs/04-other-products.md Retrieves a DataFrame with stock index data. Optionally filter by country. ```python def get_indices(country=None): ```