### WebSocketClient Connection and Monitoring Example Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/WebSocketClient.md Demonstrates how to initialize and start the WebSocketClient, monitor its running status, and handle potential connection losses after maximum reconnection attempts. ```python from eodhd import WebSocketClient import time client = WebSocketClient( api_key="demo", endpoint="us", symbols=["AAPL.US"], max_reconnect_attempts=3 ) client.start() while client.running: time.sleep(5) print(f"Still running: {len(client.get_data())} messages") # If client.running is False, reconnection failed if not client.running: print("Connection lost. Max reconnect attempts reached.") ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/CLAUDE.md Installs the library in editable mode with development dependencies. Use this command to set up the project for local development. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Instantiate and Use WebSocketClient Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/configuration.md Example of creating a WebSocketClient to stream US stocks with 1-minute candles and store data. It starts the client, waits for 60 seconds, stops the client, and then retrieves and prints the count of collected messages. ```python from eodhd import WebSocketClient import time # US stocks with 1-minute candles client = WebSocketClient( api_key="demo", endpoint="us", symbols=["AAPL.US", "MSFT.US"], display_candle_1m=True, store_data=True ) client.start() time.sleep(60) client.stop() # Analyze stored data data = client.get_data() print(f"Collected {len(data)} messages") ``` -------------------------------- ### Example HTTP GET Request Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/ARCHITECTURE.md A concrete example of an HTTP GET request for historical end-of-day data, specifying date ranges and period. ```text GET https://eodhd.com/api/eod/AAPL.US?api_token=abc123&fmt=json&period=d&from=2024-01-01&to=2024-12-31 ``` -------------------------------- ### Facade Pattern Example Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/ARCHITECTURE.md The APIClient acts as a facade, providing a single entry point for accessing various API endpoints. This example shows how to instantiate the client and retrieve historical data and financial news. ```python # Facade pattern: single entry point client = APIClient("api_key") data = client.get_historical_data(...) # Delegates to EodHistoricalStockMarketDataAPI news = client.financial_news(...) # Delegates to FinancialNewsAPI ``` -------------------------------- ### start() Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/WebSocketClient.md Starts the WebSocket connection in background threads for data collection and keep-alive pings. This method is essential for initiating the real-time data stream. ```APIDOC ## start() ### Description Starts the WebSocket connection in background threads. Spawns two threads: one for data collection with automatic reconnection, and one for keep-alive pings. ### Method Signature ```python def start(self) -> None ``` ### Example ```python client = WebSocketClient(api_key="demo", endpoint="us", symbols=["AAPL.US"]) client.start() try: while client.running: time.sleep(1) except KeyboardInterrupt: client.stop() ``` ``` -------------------------------- ### Get Stock Market Screener with Filters and Limit Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/ScannerClient.md Demonstrates the usage of get_stock_market_screener, an alias for run_scanner. This example filters stocks by P/E ratio and limits the results to 50. ```python results = scanner.get_stock_market_screener( filters={"pe": [10, 20]}, limit=50 ) ``` -------------------------------- ### Install EODHD Python Library Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Install the EODHD Python library using pip. This is the first step to using the library. ```bash pip install eodhd ``` -------------------------------- ### Install EODHD Python Library Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/README.md Install the EODHD Python library using pip. The -U flag ensures you get the latest version. ```bash python3 -m pip install eodhd -U ``` -------------------------------- ### get_mp_us_options_contracts (Pagination Example) Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/MarketplaceAPIs.md Fetches US options contracts with support for pagination. This example demonstrates how to retrieve all contracts by iterating through pages. ```APIDOC ## GET /api/mp/us/options/contracts ### Description Retrieve US options contracts with pagination support. ### Method GET ### Endpoint /api/mp/us/options/contracts ### Parameters #### Query Parameters - **underlying_symbol** (string) - Required - The underlying symbol for the options contracts. - **page_limit** (integer) - Optional - The number of contracts to retrieve per page. Defaults to 500. - **page_offset** (integer) - Optional - The offset for pagination. Defaults to 0. ``` -------------------------------- ### Initialize APIClient with Demo Key Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/configuration.md Initializes the APIClient using the 'demo' API key for testing purposes. No setup or imports are required beyond this line. ```python from eodhd import APIClient # Minimum configuration (demo) client = APIClient("demo") ``` -------------------------------- ### get_mp_us_options_contracts (Filtering Example) Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/MarketplaceAPIs.md Fetches US options contracts with filtering capabilities. This example shows how to filter for ATM calls for the next month. ```APIDOC ## GET /api/mp/us/options/contracts ### Description Retrieve US options contracts with filtering capabilities. ### Method GET ### Endpoint /api/mp/us/options/contracts ### Parameters #### Query Parameters - **underlying_symbol** (string) - Required - The underlying symbol for the options contracts. - **exp_date_eq** (string) - Optional - Filter by expiration date (YYYY-MM-DD). - **type** (string) - Optional - Filter by option type ('call' or 'put'). - **strike_from** (float) - Optional - Filter by minimum strike price. - **strike_to** (float) - Optional - Filter by maximum strike price. ``` -------------------------------- ### Initialize API Client and Fetch Bulk Fundamentals Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Demonstrates initializing the API client and fetching a bulk list of fundamental data for a specified exchange. Use this to get a large dataset of company fundamentals. ```python from eodhd import APIClient client = APIClient("api_key") bulk = client.get_bulk_fundamentals("US", limit=1000) ``` -------------------------------- ### Complete Fibonacci Workflow Example Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/EODHDGraphs.md Demonstrates fetching historical data and generating both Fibonacci extension and retracement charts for uptrend analysis, and a basic downtrend retracement chart. ```python from eodhd import APIClient, EODHDGraphs import pandas as pd # Fetch 1 year of daily data with APIClient("demo") as client: df = client.get_historical_data("MSFT.US", "d", results=252) # Create uptrend analysis chart EODHDGraphs.fibonacci_extension( df=df, trend_direction="uptrend", price_field="adjusted_close", save_file="msft_uptrend.png" ) # Create retracement analysis chart EODHDGraphs.fibonacci_retracement( df=df, trend_direction="uptrend", price_field="adjusted_close", save_file="msft_retracement.png" ) # Downtrend analysis EODHDGraphs.fibonacci_retracement( df=df, trend_direction="downtrend", price_field="close", quiet=True ) print("Charts saved successfully") ``` -------------------------------- ### Start WebSocket Connection Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/WebSocketClient.md Starts the WebSocket connection in background threads for data collection and keep-alive pings. Ensure the client is initialized with API key, endpoint, and symbols. ```python client = WebSocketClient(api_key="demo", endpoint="us", symbols=["AAPL.US"]) client.start() try: while client.running: time.sleep(1) except KeyboardInterrupt: client.stop() ``` -------------------------------- ### Efficient API Calls with Connection Pooling Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/ARCHITECTURE.md Demonstrates the performance benefits of reusing a `requests.Session` object for multiple API calls. The 'Good' example shows efficient connection reuse, while the 'Bad' example illustrates the overhead of creating a new session for each request. ```python # Good: Reuse session with APIClient("key") as client: for symbol in symbols: data = client.get_historical_data(symbol, "d") # ~200ms per request (connection reuse) # Bad: Create new session per request for symbol in symbols: client = APIClient("key") data = client.get_historical_data(symbol, "d") client.close() # ~500ms per request (new connection each time) ``` -------------------------------- ### Initialize API Client and Get Upcoming Dividends Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Initializes the API client with your API key and retrieves upcoming dividend data for specified symbols. Ensure you have your 'api_key' ready. ```python from eodhd import APIClient client = APIClient("api_key") upcoming = client.get_upcoming_dividends(symbols="AAPL.US,MSFT.US") ``` -------------------------------- ### Get All Supported Exchanges Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve a DataFrame containing metadata for all supported exchanges. Requires an initialized APIClient. ```python client = APIClient("demo") exchanges = client.get_exchanges() print(exchanges.head()) ``` -------------------------------- ### Get User Information Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieves current user's subscription and API usage details. Returns a dictionary containing account information. ```python def get_user_info(self) -> dict: # ... implementation details ... pass ``` ```python user = client.get_user_info() print(user.get("subscription")) ``` -------------------------------- ### Initialize API Client and Get Historical Splits Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Initializes the API client and fetches historical stock split data for a given symbol. Replace 'api_key' with your actual key. ```python from eodhd import APIClient client = APIClient("api_key") splits = client.get_historical_splits("AAPL.US") ``` -------------------------------- ### Get Exchange Details Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Retrieve detailed information about a specific stock exchange using its code. Requires an initialized APIClient. ```python from eodhd import APIClient client = APIClient("api_key") details = client.get_exchange_details(exchange_code="US") ``` ```python us_details = client.get_exchange_details("US") ``` -------------------------------- ### Get InvestVerte Data Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/MarketplaceAPIs.md Retrieves InvestVerte alternative data using the APIClient. Requires an initialized APIClient with a valid API key. ```python from eodhd import APIClient client = APIClient("api_key") data = client.get_mp_investverte() ``` ```python investverte = client.get_mp_investverte() ``` -------------------------------- ### Get UnicornBay Extras Data Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/MarketplaceAPIs.md Retrieves additional UnicornBay datasets using the APIClient. Requires an initialized APIClient with a valid API key. ```python from eodhd import APIClient client = APIClient("api_key") data = client.get_mp_unicornbay_extras() ``` ```python extras = client.get_mp_unicornbay_extras() ``` -------------------------------- ### Invalid API Client Configurations Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/configuration.md Examples of invalid API key formats that will raise a ValueError. This includes keys that are too short or contain invalid characters. ```python # Invalid API key format APIClient("short") # Too short APIClient("invalid@key!invalid") # Invalid characters ``` -------------------------------- ### Initialize and Use API Client Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/00-START-HERE.md Demonstrates how to initialize the APIClient with an API key and fetch historical data, real-time quotes, and fundamental data. Includes examples for both direct initialization and using a context manager. ```python from eodhd import APIClient # Initialize client = APIClient("demo") # or your API key # Fetch data data = client.get_historical_data("AAPL.US", "d") # Returns DataFrame quotes = client.get_real_time_data("AAPL.US") fundamentals = client.get_fundamental_data("AAPL.US") # Clean up client.close() # or use context manager: with APIClient("demo") as client: data = client.get_historical_data("AAPL.US", "d") ``` -------------------------------- ### Complete Fibonacci Extension Chart Workflow Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/EODHDGraphs.md Demonstrates fetching historical data and generating both uptrend and downtrend Fibonacci extension charts. Ensure you have the 'eodhd' and 'pandas' libraries installed. ```python from eodhd import APIClient, EODHDGraphs import pandas as pd # Fetch 1 year of daily data with APIClient("demo") as client: df = client.get_historical_data("MSFT.US", "d", results=252) # Create uptrend analysis chart EODHDGraphs.fibonacci_extension( df=df, trend_direction="uptrend", price_field="adjusted_close", save_file="msft_uptrend.png" ) # Create downtrend analysis chart EODHDGraphs.fibonacci_extension( df=df, trend_direction="downtrend", price_field="close", save_file="msft_downtrend.png" ) print("Charts saved: msft_uptrend.png, msft_downtrend.png") ``` -------------------------------- ### Get Historical Data (Date Range) Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve historical data within a specific date range for a given symbol and interval. Supports 'YYYY-MM-DD' or 'YYYY-MM-DDTHH:MM:SS' formats for start and end dates. ```python intraday = client.get_historical_data( "BTC-USD.CC", "1m", iso8601_start="2023-01-01", iso8601_end="2023-01-02" ) ``` -------------------------------- ### Initialize APIClient with Environment Variable Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/configuration.md Load the API key from an environment variable for secure configuration in production. Defaults to 'demo' if the environment variable is not set. ```python import os from eodhd import APIClient # Load API key from environment for production api_key = os.getenv("EODHD_API_KEY", "demo") client = APIClient(api_key) ``` -------------------------------- ### Get US Options Contracts as Dictionary Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Fetches US options contract data for a specified date range, returning a dictionary. Suitable for retrieving specific contract details. ```python options = client.get_mp_us_options_contracts( underlying_symbol="AAPL", exp_date_from="2024-06-01", exp_date_to="2024-06-30" ) # Returns dict with contract data ``` -------------------------------- ### Using ScannerClient as a Context Manager Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/ScannerClient.md Demonstrates how to initialize and use ScannerClient within a 'with' statement for automatic resource management. This ensures the client is properly closed after use. ```python with ScannerClient("demo") as scanner: results = scanner.run_scanner(filters={"pe": [0, 15]}) ``` -------------------------------- ### Implementing Application-Level Response Caching Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/ARCHITECTURE.md Provides a simple example of how to implement application-level caching for API responses. This function checks a local cache before making an API call, reducing redundant requests for the same data. ```python cache = {} def fetch_cached(symbol): if symbol not in cache: cache[symbol] = client.get_historical_data(symbol, "d") return cache[symbol] ``` -------------------------------- ### HTTP GET Request Structure Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/ARCHITECTURE.md Defines the standard structure for HTTP GET requests to the EODHD API, including common parameters. ```text GET https://eodhd.com/api/{endpoint}/{uri}?api_token={key}&fmt=json{querystring} ``` -------------------------------- ### Run Scanner for Small-Cap Growth Stocks Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/ScannerClient.md This example shows how to filter for small-cap stocks with high EPS growth. It sets a market cap limit and an EPS growth range, then limits the results to 50. ```python # Small-cap growth stocks results = scanner.run_scanner( filters={ "market_cap": [0, 2_000_000_000], "eps_growth": [20, 100] }, limit=50 ) ``` -------------------------------- ### Run Scanner with Pagination Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/ScannerClient.md Illustrates how to fetch data in pages using the limit and offset parameters. This is useful for retrieving large datasets without overwhelming the client or server. ```python # Pagination page1 = scanner.run_scanner(limit=100, offset=0) page2 = scanner.run_scanner(limit=100, offset=100) ``` -------------------------------- ### Configure WebSocket Client Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Set up a WebSocketClient for real-time streaming data. Specify the API key, endpoint, symbols, and candle display options. ```python # WebSocket with real-time streaming ws = WebSocketClient( api_key="api_key", endpoint="us", symbols=["AAPL.US"], display_candle_1m=True, max_reconnect_attempts=5 ) ``` -------------------------------- ### Initialize API Client and Fetch US Options Contracts Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/MarketplaceAPIs.md Initializes the API client with your API key and fetches US options contracts for a specified underlying symbol within a date range. Ensure you have your 'api_key' set. ```python from eodhd import APIClient client = APIClient("api_key") contracts = client.get_mp_us_options_contracts( underlying_symbol="AAPL", exp_date_from="2024-06-01", exp_date_to="2024-06-30" ) ``` -------------------------------- ### Exchange Information Methods Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/METHODS_INDEX.md Get details about exchanges, symbols, and trading hours. ```APIDOC ## Exchange Information ### Description Methods for retrieving exchange-related information. ### Methods - `get_exchanges()` - `get_exchange_symbols()` - `get_exchange_details()` - `get_details_trading_hours_stock_market_holidays()` ``` -------------------------------- ### Indices & Components Methods Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/METHODS_INDEX.md Get information about index components and lists of indices. ```APIDOC ## Indices & Components ### Description Methods for retrieving index and component data. ### Methods - `get_mp_index_components()` - `get_mp_indices_list()` - `get_cboe_index_feed()` ``` -------------------------------- ### Valid API Client and WebSocket Client Configurations Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/configuration.md Demonstrates valid configurations for both APIClient and WebSocketClient, including using a demo key, a valid API key, and custom timeouts for the APIClient. The WebSocketClient example shows configuration for a crypto endpoint with specific symbols. ```python from eodhd import APIClient, WebSocketClient # Valid configurations try: # APIClient client1 = APIClient("demo") client2 = APIClient("valid_api_key_1234567890") client3 = APIClient("demo", timeout=(10.0, 60.0)) # WebSocketClient ws = WebSocketClient( api_key="demo", endpoint="crypto", symbols=["BTC-USD", "ETH-USD"], store_data=True ) except ValueError as e: print(f"Configuration error: {e}") ``` -------------------------------- ### news_word_weights() Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Get weighted keywords from financial news for a specific symbol over a defined period. ```APIDOC ## news_word_weights() ### Description Retrieve weighted keywords from financial news for a symbol over a date range. ### Method `client.news_word_weights()` ### Parameters #### Query Parameters - **s** (str, required) - Symbol, e.g. "AAPL.US". - **date_from** (str, optional) - Start date as "YYYY-MM-DD". - **date_to** (str, optional) - End date as "YYYY-MM-DD". - **limit** (int, optional) - Maximum keywords to return. ### Returns `pd.DataFrame` with keyword weights. ### Example ```python weights = client.news_word_weights("AAPL.US", date_from="2023-01-01", limit=50) ``` ``` -------------------------------- ### Get Real-Time Stock Price Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Fetch the current (delayed) stock price for a given symbol. ```python # Current stock price (delayed) quote = client.get_real_time_data("AAPL.US") ``` -------------------------------- ### Use APIClient with Context Manager Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/configuration.md Demonstrates using the APIClient within a context manager to ensure automatic cleanup. This is the recommended approach for managing client resources. ```python from eodhd import APIClient # Use context manager for automatic cleanup with APIClient("demo") as client: data = client.get_exchanges() ``` -------------------------------- ### Initialize API Client and Fetch Historical Dividends Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Demonstrates initializing the API client and fetching historical dividend payments for a given stock symbol. This is useful for analyzing a company's dividend history. ```python from eodhd import APIClient client = APIClient("api_key") dividends = client.get_historical_dividends("AAPL.US") ``` -------------------------------- ### Downtrend Retracement Calculation Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/EODHDGraphs.md Calculates Fibonacci retracement levels for a downtrend, starting from the low price. ```python diff = high - low fib_0pct = low fib_236 = low + (diff * 0.236) fib_382 = low + (diff * 0.382) fib_50pct = low + (diff * 0.500) fib_618 = low + (diff * 0.618) fib_764 = low + (diff * 0.764) fib_100pct = high ``` -------------------------------- ### Uptrend Retracement Calculation Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/EODHDGraphs.md Calculates Fibonacci retracement levels for an uptrend, starting from the high price. ```python diff = high - low fib_0pct = high fib_236 = high - (diff * 0.236) fib_382 = high - (diff * 0.382) fib_50pct = high - (diff * 0.500) fib_618 = high - (diff * 0.618) fib_764 = high - (diff * 0.764) fib_100pct = low ``` -------------------------------- ### Initialize APIClient Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Initialize the APIClient for accessing financial data. Supports demo mode without an API key or production mode with a valid key. Can be used as a context manager for automatic resource cleanup. ```python from eodhd import APIClient # Demo mode (no API key required) client = APIClient("demo") # Production (requires API key from https://eodhd.com) client = APIClient("your_api_key_here") # Use as context manager for automatic cleanup with APIClient("demo") as client: data = client.get_exchanges() ``` -------------------------------- ### Initialize ScannerClient Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/ScannerClient.md Instantiate the ScannerClient with your API key. It's recommended to use a real API key for actual requests. The client can also be used as a context manager for automatic session cleanup. ```python from eodhd import ScannerClient scanner = ScannerClient("demo") # or with a real API key: scanner = ScannerClient("your_api_key_here") # Use context manager for automatic cleanup with ScannerClient("demo") as scanner: results = scanner.run_scanner(filters={"pe": [0, 15]}) ``` -------------------------------- ### Complete Stock Screening Workflow with ScannerClient Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/ScannerClient.md Shows a full workflow for screening stocks using ScannerClient, including setting multiple filters, sorting results, and basic data manipulation with pandas. It also includes an example of paginating through results. ```python from eodhd import ScannerClient import pandas as pd # Initialize scanner = ScannerClient("your_api_key") # Fetch value stocks with positive momentum results = scanner.run_scanner( filters={ "pe": [0, 15], "pb": [0, 1.5], "dividend_yield": [1, 100], "market_cap": [500_000_000, 100_000_000_000] }, sort={"pe": "asc"}, limit=200 ) # Filter and rank results = results[results["eps_growth"] > 0].sort_values("pe") print(f"Found {len(results)} matching stocks") print(results[["code", "name", "pe", "dividend_yield", "market_cap"]].head(20)) # Pagination example: fetch all results 100 at a time all_results = [] for offset in range(0, 1000, 100): page = scanner.run_scanner( filters={"pe": [0, 20]}, limit=100, offset=offset ) if len(page) == 0: break all_results.append(page) combined = pd.concat(all_results, ignore_index=True) print(f"Total results: {len(combined)}") scanner.close() ``` -------------------------------- ### Get Last Minute of Previous Day Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve the last minute of the previous day formatted as 'YYYY-MM-DD 23:59:00'. ```python last_minute = DateUtils.previous_day_last_minute() # e.g., "2023-06-20 23:59:00" ``` -------------------------------- ### Initialize WebSocketClient for US Stocks Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/WebSocketClient.md Instantiate the WebSocketClient to receive real-time US stock prices. Set display_stream to True to print raw messages and store_data to True to store received data in memory. ```python from eodhd import WebSocketClient # Real-time US stock prices client = WebSocketClient( api_key="demo", endpoint="us", symbols=["AAPL.US", "MSFT.US"], display_stream=True, store_data=True ) ``` -------------------------------- ### Get Last Second of Previous Day Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve the last second of the previous day formatted as 'YYYY-MM-DD 23:59:59'. ```python last_second = DateUtils.previous_day_last_second() # e.g., "2023-06-20 23:59:59" ``` -------------------------------- ### Get Historical Dividends Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve historical dividend data for a specific stock symbol. Requires the symbol as a string. ```python divs = client.get_historical_dividends("AAPL.US") ``` -------------------------------- ### Run Scanner with Filters, Sorting, and Limit Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/ScannerClient.md Example of using the run_scanner method to screen stocks based on P/E ratio, dividend yield, and EPS growth. Results are sorted by P/E ratio in ascending order and limited to 100. ```python # Low P/E, profitable stocks with dividend results = scanner.run_scanner( filters={ "pe": [0, 15], "dividend_yield": [2, 100], "eps_growth": [0, 100] }, sort={"pe": "asc"}, limit=100 ) print(results) ``` -------------------------------- ### Get Upcoming Earnings Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Retrieve upcoming earnings announcements for specified symbols. Supports date range filtering. ```python earnings = client.get_upcoming_earnings(symbols="AAPL.US,MSFT.US") ``` -------------------------------- ### APIClient Initialization Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Initializes the APIClient for accessing financial data. Supports demo mode or production with an API key. Can be used as a context manager. ```APIDOC ## APIClient Initialization ### Description Initializes the APIClient for accessing financial data. Supports demo mode or production with an API key. Can be used as a context manager. ### Method `APIClient(api_key: str, **kwargs)` ### Parameters - **api_key** (str) - Required - Your EODHD API key or 'demo' for demo mode. ### Request Example ```python from eodhd import APIClient # Demo mode client = APIClient("demo") # Production client = APIClient("your_api_key_here") # Context manager with APIClient("demo") as client: data = client.get_exchanges() ``` ``` -------------------------------- ### Get Upcoming Splits Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Retrieve upcoming stock splits for specified symbols. Requires an API key for initialization. ```python from eodhd import APIClient client = APIClient("api_key") upcoming = client.get_upcoming_splits(symbols="AAPL.US") ``` ```python upcoming = client.get_upcoming_splits() ``` -------------------------------- ### Get Historical Splits Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve historical stock split data for a specific stock symbol. Requires the symbol as a string. ```python splits = client.get_historical_splits("AAPL.US") ``` -------------------------------- ### Standard Python Imports and Function Signature Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/INDEX.md Illustrates standard imports and type-hinted function signature for data fetching. Type hints are optional but recommended. ```python # Standard imports from eodhd import APIClient # Type hints are documented but not required def fetch_data(symbol: str) -> pd.DataFrame: pass ``` -------------------------------- ### Initialize API Client with Environment Variable Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/configuration.md Load your EODHD API key from the environment variable 'EODHD_API_KEY' for secure access in production environments. Ensure the environment variable is set before running the code. ```python import os from eodhd import APIClient # Load from environment (production) API_KEY = os.getenv("EODHD_API_KEY") if not API_KEY: raise ValueError("EODHD_API_KEY environment variable not set") client = APIClient(API_KEY) # Never hardcode API keys in source files # Never commit API keys to version control # Rotate keys periodically ``` -------------------------------- ### Get Extended Live Quotes Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Retrieve extended live quote data for one or more symbols using the v2 endpoint. ```python # Extended quotes (v2) quotes = client.get_live_extended_quotes("AAPL.US,MSFT.US") ``` -------------------------------- ### Get Daily Sentiment Data Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve daily sentiment data for one or more stock symbols. Symbols should be provided as a comma-separated string. ```python sentiment = client.get_sentiment("AAPL.US,MSFT.US") ``` -------------------------------- ### Get Technical Indicator Data Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve technical indicator data for a stock symbol. Various indicator functions and periods can be specified. ```python def get_technical_indicator( self, symbol: str, function: str, period: int = 50, **kwargs ) -> pd.DataFrame: """Retrieve technical indicator data.""" pass ``` ```python # 20-period SMA sma = client.get_technical_indicator("AAPL.US", "sma", period=20) ``` ```python # RSI with 14 period rsi = client.get_technical_indicator("AAPL.US", "rsi", period=14) ``` -------------------------------- ### Configure API Client Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Instantiate the APIClient with your API key. A custom timeout can be specified for large requests. ```python # Standard configuration client = APIClient("api_key") ``` ```python # Custom timeout (important for large requests) client = APIClient("api_key", timeout=(10.0, 120.0)) ``` -------------------------------- ### Get Indices List Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/MarketplaceAPIs.md Retrieve a list of all available S&P Global indices. Initialize the APIClient with your API key before calling this method. ```python from eodhd import APIClient client = APIClient("api_key") indices = client.get_mp_indices_list() print(f"Available indices: {indices}") ``` -------------------------------- ### Initialize WebSocketClient for Cryptocurrency Data Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/WebSocketClient.md Instantiate the WebSocketClient to receive real-time cryptocurrency data. Set display_candle_1m to True to aggregate and display 1-minute candles. ```python # Real-time cryptocurrency crypto_client = WebSocketClient( api_key="demo", endpoint="crypto", symbols=["BTC-USD", "ETH-USD"], display_candle_1m=True ) ``` -------------------------------- ### Initialize API Client Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Instantiate the APIClient with your API key to interact with EODHD services. This is a prerequisite for all API calls. ```python from eodhd import APIClient client = APIClient("api_key") ``` -------------------------------- ### APIClient Constructor & Session Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/METHODS_INDEX.md Initializes the APIClient and manages its session. Supports context manager protocol for automatic session handling. ```APIDOC ## APIClient Constructor & Session ### Description Initializes the APIClient with an API key and optional timeout. Provides methods for closing the session and supports context manager usage. ### Methods - `__init__(api_key: str, timeout: tuple = (5.0, 30.0)) -> None`: Constructor for APIClient. - `close() -> None`: Closes the client session. - `__enter__()`: Enters the runtime context related to this object. - `__exit__()`: Exits the runtime context related to this object. ``` -------------------------------- ### Get Live Extended Quotes (v2) Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve extended quotes for US stocks. Supports pagination with batch size and page number. ```python def get_live_extended_quotes( self, symbols: str, batch_size: int = None, page: int = None, ) -> pd.DataFrame: pass ``` ```python quotes = client.get_live_extended_quotes("AAPL.US,MSFT.US") ``` -------------------------------- ### Get Exchange Symbols (Delisted Only) Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve a DataFrame containing only delisted symbols for a given exchange. Requires the exchange's URI code. ```python # US exchange, delisted only delisted = client.get_exchange_symbols("US", delisted=True) ``` -------------------------------- ### Run Stock Scanner with Filters Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Use ScannerClient to find stocks based on specific financial filters like P/E ratio, dividend yield, and market cap. Results can be limited. ```python from eodhd import ScannerClient scanner = ScannerClient("your_api_key") # Find low P/E dividend payers results = scanner.run_scanner( filters={ "pe": [0, 15], "dividend_yield": [2, 100], "market_cap": [500_000_000, 100_000_000_000] }, limit=100 ) ``` -------------------------------- ### Get Exchange Symbols (Active Only) Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Retrieve a DataFrame of active symbols trading on a specified exchange. Use the exchange's URI code. ```python # US exchange, active symbols only symbols = client.get_exchange_symbols("US") print(symbols.head()) ``` -------------------------------- ### Cryptocurrency Streaming with 5-Minute Candles Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/WebSocketClient.md Connects to the cryptocurrency endpoint to stream data for specified pairs. This example disables raw stream display but enables 5-minute candle aggregation. It runs for a fixed duration before stopping. Use this for observing cryptocurrency market trends over specific intervals. ```python from eodhd import WebSocketClient import time crypto = WebSocketClient( api_key="your_api_key", endpoint="crypto", symbols=["BTC-USD", "ETH-USD"], display_stream=False, display_candle_5m=True ) crypto.start() time.sleep(300) # Run for 5 minutes crypto.stop() ``` -------------------------------- ### Get Earning Trends Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Retrieve earnings trend data and analyst estimates for specified symbols. This function requires a comma-separated string of symbols. ```python trends = client.get_earning_trends(symbols="AAPL.US,MSFT.US") ``` -------------------------------- ### Typical Data Request Flow Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/ARCHITECTURE.md Illustrates the sequence of operations for a typical data request, from client initiation to data retrieval and return. ```text 1. APIClient.get_historical_data("AAPL.US", "d") ↓ 2. Construct request parameters & validation ↓ 3. Delegate to EodHistoricalStockMarketDataAPI.get_eod_historical_stock_market_data() ↓ 4. Call BaseAPI._rest_get_method() ↓ 5. Build full URL: "https://eodhd.com/api/eod/AAPL.US?api_token=...&fmt=json..." ↓ 6. Execute: self._session.get(url, timeout=self._timeout) ↓ 7. Handle response: - Status 200: Parse JSON, return as pd.DataFrame - Status 400-5xx: Raise EODHDHTTPError - Connection error: Raise EODHDConnectionError - Timeout: Raise EODHDTimeoutError ↓ 8. Return pd.DataFrame to caller ``` -------------------------------- ### Get Upcoming Dividends by Date Range Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/CoreAPIs.md Retrieves upcoming dividend announcements within a specified date range. The dates should be in 'YYYY-MM-DD' format. ```python upcoming_q1 = client.get_upcoming_dividends( from_date="2024-01-01", to_date="2024-03-31" ) ``` -------------------------------- ### Paginate Bulk Fundamentals Data Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Demonstrates fetching a large dataset of bulk fundamentals using pagination. This method is efficient for retrieving over 1000 records by making sequential requests with specified offsets and limits. ```python all_data = [] for offset in range(0, 10000, 1000): page = client.get_bulk_fundamentals("US", offset=offset, limit=1000) if not page: break all_data.append(page) ``` -------------------------------- ### Get Company Logo as Bytes Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/README.md Downloads a company's logo as raw bytes and saves it to a file. Use this for retrieving image assets. ```python png = client.get_logo("AAPL.US") with open("logo.png", "wb") as f: f.write(png) ``` -------------------------------- ### ScannerClient Constructor & Session Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/METHODS_INDEX.md Initializes the ScannerClient and manages its session. Supports context manager protocol for automatic session handling. ```APIDOC ## ScannerClient Constructor & Session ### Description Initializes the ScannerClient with an API key and optional timeout. Provides methods for closing the session and supports context manager usage. ### Methods - `__init__(api_key: str, timeout: tuple = (5.0, 30.0)) -> None`: Constructor for ScannerClient. - `close() -> None`: Closes the client session. - `__enter__()`: Enters the runtime context related to this object. - `__exit__()`: Exits the runtime context related to this object. ``` -------------------------------- ### APIClient Constructor Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Initializes the APIClient with an API key and optional timeout settings. The API key must be a valid EODHD token, and the timeout can be specified as a tuple of connect and read timeouts. ```APIDOC ## APIClient Constructor ### Description Initializes the APIClient with an API key and optional timeout settings. The API key must be a valid EODHD token, and the timeout can be specified as a tuple of connect and read timeouts. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **api_key** (str) - Required - EODHD API token. Must be 16–32 alphanumeric characters or the literal string "demo". Raises `ValueError` if invalid. - **timeout** (tuple) - Optional - Request timeout as (connect_timeout, read_timeout) in seconds. Defaults to (5.0, 30.0). ### Raises: - `ValueError` — if api_key format is invalid ### Example: ```python from eodhd import APIClient client = APIClient("demo") # or with a real API key: client = APIClient("your_api_key_here") # Use context manager for automatic cleanup with APIClient("demo") as client: data = client.get_exchanges() ``` ``` -------------------------------- ### Handle EODHDTimeoutError and Retry Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/errors.md Catch and handle API request timeouts. This example demonstrates how to retry the request with an increased timeout if an EODHDTimeoutError occurs. ```python from eodhd import APIClient from eodhd.errors import EODHDTimeoutError import time client = APIClient("demo", timeout=(5.0, 10.0)) # Short timeout try: # This may timeout on slow connections data = client.get_bulk_fundamentals("US", limit=10000) except EODHDTimeoutError as e: print(f"Request timed out: {e}") print("Retrying with longer timeout...") # Recreate with longer timeout client.close() client = APIClient("demo", timeout=(10.0, 60.0)) data = client.get_bulk_fundamentals("US", limit=1000) finally: client.close() ``` -------------------------------- ### Get Company Logo as SVG Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Fetches a company's logo in SVG format using its stock symbol. The logo is returned as raw bytes. ```python def get_logo_svg(self, symbol: str) -> bytes: # ... implementation details ... pass ``` ```python svg = client.get_logo_svg("AAPL.US") with open("logo.svg", "wb") as f: f.write(svg) ``` -------------------------------- ### Get Company Logo as PNG Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/api-reference/APIClient.md Fetches a company's logo in PNG format using its stock symbol. The logo is returned as raw bytes. ```python def get_logo(self, symbol: str) -> bytes: # ... implementation details ... pass ``` ```python png = client.get_logo("AAPL.US") with open("logo.png", "wb") as f: f.write(png) ``` -------------------------------- ### ScannerClient.run_scanner() Source: https://github.com/eodhistoricaldata/eodhd-apis-python-financial-library/blob/main/_autodocs/INDEX.md Runs a stock screener query. ```APIDOC ## POST /scanner ### Description Runs a stock screener query. ### Method POST ### Endpoint /scanner ### Parameters #### Request Body - **api_token** (string) - Required - Your API token. - **query** (object) - Required - Screener query parameters. ### Request Example ```json { "api_token": "YOUR_API_TOKEN", "query": { "exchange": "US", "market_cap_greater_than": 1000000000, "volume_greater_than": 100000 } } ``` ### Response #### Success Response (200) - Returns a list of symbols matching the screener criteria. ```