Skill: simonpierreboucher02/eodhd-api (version 1.0.0)

--- name: eodhd-api description: Provides tools and workflows to interact with the EODHD (EOD Historical Data) API for financial data. Use this skill to fetch market data, fundamental data, technical indicators, financial news, and more. --- # EODHD API Skill This skill provides a comprehensive toolkit for interacting with the EOD Historical Data (EODHD) API, a powerful source for a wide range of financial data. ## Core Principles 1. **API Token First**: Before using any function, ensure the user has provided an EODHD API token. The `config.json` file must be updated with a valid token. If the token is missing or invalid, ask the user to provide one. 2. **Use the Client**: All API interactions MUST go through the provided Python client: `scripts/eodhd_client.py`. This client handles authentication, request formation, and basic error handling. 3. **Be Specific**: When fetching data, use the most specific function available in the client. For example, use `get_dividends()` for dividend data instead of a generic fundamental data call. 4. **Handle Errors**: The client returns an `{"error": "..."}` dictionary on failure. Always check for this and report errors clearly to the user. ## Setup: API Token Configuration Before the first use, you must configure the API token. The user needs to provide their personal EODHD API key. 1. **Ask the user** for their EODHD API token. 2. **Write the token** to the configuration file using the `file` tool: ```python default_api.file( action="write", path="/home/ubuntu/skills/eodhd-api/config.json", text=f"{{\"api_token\": \"{user_provided_token}\"}}" ) ``` ## Workflow: Fetching Financial Data Follow this general workflow to retrieve and use financial data from the EODHD API. ### Step 1: Understand the User's Request Identify the specific type of data the user needs. Is it historical prices, company fundamentals, news, or something else? Map their request to one of the available functions in the `eodhd_client.py` script. ### Step 2: Instantiate the Client and Call the Method Create a Python script to import and use the `EODHDClient`. **Example: Fetching Historical EOD Prices** ```python # File: /home/ubuntu/fetch_eod.py from skills.eodhd-api.scripts.eodhd_client import EODHDClient import json client = EODHDClient() data = client.get_eod_historical_data( 'AAPL.US', from_date='2023-01-01', to_date='2023-01-10' ) if 'error' in data: print(f"An error occurred: {data['error']}") else: print(json.dumps(data, indent=2)) ``` ### Step 3: Execute the Script Run the script using the `shell` tool. ```bash python3.11 /home/ubuntu/fetch_eod.py ``` ### Step 4: Process and Present the Data Analyze the JSON output from the script. Present the information to the user in a clear and readable format, often using Markdown tables or summaries. ## Available Client Functions The `eodhd_client.py` script provides a high-level interface for the most common EODHD API endpoints. Refer to the script's docstrings for detailed usage of each function. | Function | Description | |---|---| | `get_eod_historical_data` | Fetches end-of-day historical data. | | `get_intraday_historical_data` | Fetches intraday (1m, 5m, 1h) historical data. | | `get_real_time_data` | Fetches real-time (delayed) price data. | | `get_fundamental_data` | Fetches comprehensive fundamental data for a company. | | `get_technical_indicator` | Calculates and fetches various technical indicators. | | `get_financial_news` | Retrieves financial news for a ticker or topic. | | `get_sentiment_data` | Fetches aggregated sentiment scores. | | `get_options_data` | Retrieves options chain data. | | `get_screener_data` | Filters stocks based on specified criteria. | | `get_macro_indicator_data` | Fetches macroeconomic data for a country. | | `get_calendar_events` | Gets upcoming earnings, IPOs, and splits. | | `get_exchange_list` | Lists all supported exchanges. | | `get_exchange_symbols` | Lists all symbols for a given exchange. | | `search_instrument` | Searches for tickers and instruments. | | `get_dividends` | Fetches historical dividend data. | | `get_splits` | Fetches historical stock split data. | | `get_bulk_eod` | Fetches bulk EOD data for an entire exchange. | For detailed parameters and options for each function, consult the official [EODHD API Documentation](https://eodhd.com/financial-apis).

path: config.json
content: api_token: YOUR_API_TOKEN

path: scripts/eodhd_client.py
content: '''
EODHD API Client

This script provides a Python class to interact with the EOD Historical Data API.

Usage:
1. Make sure you have a `config.json` file in the root of the skill directory 
   with your API token: `{"api_token": "YOUR_API_TOKEN"}`.
2. Import the client: `from eodhd_client import EODHDClient`
3. Instantiate the client: `client = EODHDClient()`
4. Call the desired methods.
'''

import json
import os
import requests

class EODHDClient:
    def __init__(self, api_token=None):
        if api_token:
            self.api_token = api_token
        else:
            config_path = os.path.join(os.path.dirname(__file__), '..', 'config.json')
            if not os.path.exists(config_path):
                raise FileNotFoundError("config.json not found. Please create it with your API token.")
            with open(config_path, 'r') as f:
                config = json.load(f)
            self.api_token = config.get("api_token")

        if not self.api_token or self.api_token == "YOUR_API_TOKEN":
            raise ValueError("API token is not set or is invalid. Please check your config.json.")

        self.base_url = "https://eodhd.com/api"

    def _get_request(self, endpoint, params=None):
        '''Helper function to make a GET request to the API.'''
        if params is None:
            params = {}
        params['api_token'] = self.api_token
        params['fmt'] = 'json'
        
        url = f"{self.base_url}/{endpoint}"
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": str(e), "url": url, "params": params}

    def get_eod_historical_data(self, symbol, **kwargs):
        '''Get End-of-Day historical data.'''
        return self._get_request(f"eod/{symbol}", params=kwargs)

    def get_intraday_historical_data(self, symbol, **kwargs):
        '''Get intraday historical data.'''
        return self._get_request(f"intraday/{symbol}", params=kwargs)

    def get_real_time_data(self, symbol, **kwargs):
        '''Get real-time (delayed) data.'''
        return self._get_request(f"real-time/{symbol}", params=kwargs)

    def get_fundamental_data(self, symbol, **kwargs):
        '''Get fundamental data for stocks, ETFs, and funds.'''
        return self._get_request(f"fundamentals/{symbol}", params=kwargs)

    def get_technical_indicator(self, symbol, **kwargs):
        '''Get technical indicator data.'''
        if 'function' not in kwargs:
            return {"error": "The 'function' parameter is required for technical indicators."}
        return self._get_request(f"technical/{symbol}", params=kwargs)

    def get_financial_news(self, **kwargs):
        '''Get financial news.'''
        if 's' not in kwargs and 't' not in kwargs:
            return {"error": "Either a symbol 's' or a tag 't' is required for news."}
        return self._get_request("news", params=kwargs)

    def get_sentiment_data(self, **kwargs):
        '''Get sentiment data.'''
        return self._get_request("sentiments", params=kwargs)

    def get_options_data(self, symbol, **kwargs):
        '''Get options data.'''
        return self._get_request(f"options/{symbol}", params=kwargs)

    def get_screener_data(self, **kwargs):
        '''Get stock screener data.'''
        return self._get_request("screener", params=kwargs)

    def get_macro_indicator_data(self, country, **kwargs):
        '''Get macroeconomic indicator data.'''
        return self._get_request(f"macro-indicator/{country}", params=kwargs)

    def get_calendar_events(self, event_type, **kwargs):
        '''Get calendar events (earnings, IPOs).'''
        return self._get_request(f"calendar/{event_type}", params=kwargs)

    def get_exchange_list(self, **kwargs):
        '''Get the list of supported exchanges.'''
        return self._get_request("exchanges-list", params=kwargs)

    def get_exchange_symbols(self, exchange_code, **kwargs):
        '''Get the list of symbols for an exchange.'''
        return self._get_request(f"exchange-symbol-list/{exchange_code}", params=kwargs)

    def search_instrument(self, query, **kwargs):
        '''Search for an instrument.'''
        return self._get_request(f"search/{query}", params=kwargs)

    def get_dividends(self, symbol, **kwargs):
        '''Get dividend data.'''
        return self._get_request(f"div/{symbol}", params=kwargs)

    def get_splits(self, symbol, **kwargs):
        '''Get stock split data.'''
        return self._get_request(f"splits/{symbol}", params=kwargs)

    def get_bulk_eod(self, exchange_code, **kwargs):
        '''Get bulk EOD data for an exchange.'''
        return self._get_request(f"eod-bulk-last-day/{exchange_code}", params=kwargs)

# Example usage:
if __name__ == '__main__':
    try:
        client = EODHDClient()
        
        # Example 1: Get EOD data for AAPL.US
        print("Fetching EOD data for AAPL.US...")
        eod_data = client.get_eod_historical_data('AAPL.US', from_date='2023-01-01', to_date='2023-01-10')
        if 'error' in eod_data:
            print(f"Error: {eod_data['error']}")
        else:
            print(json.dumps(eod_data[:2], indent=2)) # Print first 2 results

        # Example 2: Get fundamental data for AAPL.US
        print("\nFetching fundamental data for AAPL.US...")
        fundamental_data = client.get_fundamental_data('AAPL.US', filter='General::Name,General::Sector')
        if 'error' in fundamental_data:
            print(f"Error: {fundamental_data['error']}")
        else:
            print(json.dumps(fundamental_data, indent=2))

        # Example 3: Get news for the technology tag
        print("\nFetching news for tag 'technology'...")
        news_data = client.get_financial_news(t='technology', limit=1)
        if 'error' in news_data:
            print(f"Error: {news_data['error']}")
        else:
            print(json.dumps(news_data, indent=2))

    except (FileNotFoundError, ValueError) as e:
        print(f"Configuration Error: {e}")


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector:  ()