Building a Trading Bot with the Intraday Historical Data API from EODHD

Building a Trading Bot with the Intraday Historical Data API from EODHD

Introduction

For anyone embarking on a journey to create a trading system or perform in-depth market analysis, data quality is paramount. However, obtaining daily — or more granular — market data can be rife with challenges. Let’s look at three common problems:

  1. Incomplete Historical Data Many free data sources limit how far back you can go, leaving gaps that can disrupt backtesting or skew your models.
  2. Inconsistent or Unreliable Updates Some providers don’t update data in a timely manner, or they introduce random delays. This inconsistency becomes a significant hurdle when attempting to trade intraday strategies.
  3. Lack of Granularity Daily or hourly data might not be enough for certain strategies requiring minute-by-minute (or even tick-level) updates.

One solution that tackles these issues is the Intraday Historical Data API from EODHD. In addition to delivering comprehensive and historical intraday data, this API provides:

  • Wide Market Coverage: Stocks (NYSE, NASDAQ), FOREX, cryptocurrencies, and more.
  • Multiple Time Intervals: 1-minute, 5-minute, and 1-hour data (depending on availability).
  • Extensive Historical Depth: Up to 17+ years for U.S. markets, 12+ years for FOREX/crypto.

Examples of Use Cases

  1. Algorithmic Trading: Develop, backtest, and refine strategies that rely on fast intraday signals, from simple moving averages to advanced machine learning models.
  2. Portfolio Analysis: Monitor multiple assets intraday to rebalance or hedge positions in real time.
  3. Research and Statistical Modeling: Gather data for correlation studies, volatility analyses, or event-driven research that requires precise time-stamping.

Opportunity is missed by most people because it is dressed in overalls and looks like work.” – Thomas Edison

Reliable and granular market data can seem like a luxury, yet it forms the bedrock of any successful trading strategy. Before diving into advanced algorithms or technical indicators, you must establish a clear process for extracting and structuring the data you’ll rely on for both analysis and decision-making. In the next section, we’ll see how to fetch intraday data from EODHD and transform it into a format that is easy to analyze and ready for backtesting.

Prerequisites for Running the Code

Before we dive in, make sure you have the following in place:

  1. Python 3.7+ installed on your system.
  2. Libraries:

  • requests for making HTTP requests (pip install requests).
  • pandas for handling data frames (pip install pandas).
  • pandas_ta if you plan to use technical analysis indicators (pip install pandas_ta).

3. EODHD API Key: You’ll need a valid API key from EODHD. Sign up on their website, and make sure you store your key in a safe place. You can use the alternative free API key available here

4. Internet Connection: This is required to fetch data from the API in real time.

API Parameters and Response Structure

The Intraday Historical Data API endpoint typically follows this format:

https://eodhistoricaldata.com/api/intraday/{SYMBOL}?
    api_token=YOUR_API_KEY
    &interval={INTERVAL}
    &from={START_TIMESTAMP}
    &to={END_TIMESTAMP}
    &fmt=json        

  • {SYMBOL}: The ticker symbol followed by the market suffix. For instance, AAPL.US (Apple on NASDAQ), BTC-USD.CC (Bitcoin vs. USD in Crypto), EURUSD.FX (EUR/USD in Forex), etc.
  • api_token: Your unique API Key from EODHD.
  • interval: The intraday resolution you want. Common options include 1m, 5m, and 1h.
  • from / to: Unix timestamps or supported date formats specifying your desired time range.
  • fmt=json: Indicates you want the response in JSON format.

[
  {
    "t": 1664582400,     // Unix timestamp
    "o": 140.51,         // Open price
    "h": 141.00,         // High price
    "l": 139.75,         // Low price
    "c": 140.30,         // Close price
    "v": 125400          // Volume
  },
  ...
]        

Where:

  • t: Unix timestamp (in UTC).
  • o (open), h (high), l (low), c (close): Standard OHLC data for the interval.
  • v: Traded volume during that interval (if available for that market).

Phase 1: Extracting Intraday Data from EODHD

Below, you’ll find a step-by-step guide to fetch and store intraday data in a Pandas DataFrame. We’ll specify dates in the friendly MM-DD-YYYY format, then convert them into Unix timestamps, which the API requires.

import requests
import json
import datetime
import pandas as pd

# 1. Configuration
API_KEY = 'YOUR_EODHD_API_KEY'   # Replace with your actual API Key
symbol = 'AAPL.US'               # AAPL on NASDAQ
interval = '1m'                  # 1-minute intervals
from_date_str = '10-01-2022'     # MM-DD-YYYY
to_date_str   = '10-02-2022'     # MM-DD-YYYY

# 2. Convert to Python datetime
from_date_obj = datetime.datetime.strptime(from_date_str, '%m-%d-%Y')
to_date_obj   = datetime.datetime.strptime(to_date_str, '%m-%d-%Y')

# 3. Convert to Unix timestamps
from_timestamp = int(from_date_obj.timestamp())
to_timestamp   = int(to_date_obj.timestamp())

# 4. Build the API request URL
url = (
    f'https://eodhistoricaldata.com/api/intraday/{symbol}'
    f'?api_token={API_KEY}'
    f'&interval={interval}'
    f'&from={from_timestamp}'
    f'&to={to_timestamp}'
    f'&fmt=json'
)

# 5. Fetch data
response = requests.get(url)
if response.status_code == 200:
    data_json = json.loads(response.text)
    # 6. Convert to a Pandas DataFrame
    df = pd.DataFrame(data_json)
    
    # Rename columns for clarity
    df.rename(columns={
        't': 'timestamp',
        'o': 'open',
        'h': 'high',
        'l': 'low',
        'c': 'close',
        'v': 'volume'
    }, inplace=True)
    
    # Convert timestamps to UTC datetime and set index
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s', utc=True)
    df.set_index('timestamp', inplace=True)

    # Print a sample
    print(df.head())
else:
    print(f'Error retrieving data: {response.status_code} - {response.text}')        

Explanation

  1. Date Parsing: Convert MM-DD-YYYY strings into Python datetime objects.
  2. Unix Timestamps: The API often requires timestamps rather than date strings.
  3. API Request: We construct the URL for intraday data, including our API key, the interval, and the start/end times.
  4. Result: A DataFrame containing open, high, low, close, and volume, indexed by the parsed UTC timestamp.

Output code

Risk comes from not knowing what you’re doing.” – Warren Buffett

Once you have reliable market data at your fingertips, the next logical step is to automate how you act on it. A trading bot allows you to execute strategies systematically, free from human bias and around the clock. Whether you’re focusing on short-term signals or multi-day patterns, bots help you streamline the process of analyzing data, entering positions, and managing risk. In the next section, we’ll explore how to create a simple RSI-based trading bot using the data you’ve extracted.

Phase 2: Simple RSI-Based Trading Bot

With high-quality intraday data in hand, you can begin experimenting with trading strategies. A good starting point is the RSI (Relative Strength Index), a momentum oscillator that fluctuates between 0 and 100. Traditionally:

  • RSI below 30: Potentially oversold (a buy signal for some traders).
  • RSI above 70: Potentially overbought (a sell signal for some traders).

Below is an example script that downloads the same data, calculates the RSI using pandas_ta, and outputs hypothetical buy/sell signals based on RSI thresholds.

import requests
import json
import datetime
import pandas as pd
import pandas_ta as ta

API_KEY = 'YOUR_EODHD_API_KEY'
symbol = 'AAPL.US'
interval = '1m'
from_date_str = '10-01-2022'
to_date_str   = '10-02-2022'

# Convert from string dates to timestamps
from_date_obj = datetime.datetime.strptime(from_date_str, '%m-%d-%Y')
to_date_obj   = datetime.datetime.strptime(to_date_str, '%m-%d-%Y')
from_timestamp = int(from_date_obj.timestamp())
to_timestamp   = int(to_date_obj.timestamp())

# Construct the URL
url = (
    f'https://eodhistoricaldata.com/api/intraday/{symbol}'
    f'?api_token={API_KEY}'
    f'&interval={interval}'
    f'&from={from_timestamp}'
    f'&to={to_timestamp}'
    f'&fmt=json'
)

response = requests.get(url)
if response.status_code == 200:
    data_json = json.loads(response.text)
    df = pd.DataFrame(data_json)
    df.rename(columns={
        't': 'timestamp',
        'o': 'open',
        'h': 'high',
        'l': 'low',
        'c': 'close',
        'v': 'volume'
    }, inplace=True)
    
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s', utc=True)
    df.set_index('timestamp', inplace=True)

    # Calculate RSI with a 14-bar period
    df['RSI'] = ta.rsi(df['close'], length=14)

    # Simple signals based on RSI thresholds
    df['Signal'] = 0
    df.loc[df['RSI'] <= 30, 'Signal'] = 1   # Buy
    df.loc[df['RSI'] >= 70, 'Signal'] = -1  # Sell

    print(df[['open','high','low','close','volume','RSI','Signal']].head(10))

    # Example of simulating trades
    position = 0  # 1 if holding a buy position, -1 if short, 0 if neutral
    for idx, row in df.iterrows():
        if row['Signal'] == 1 and position == 0:
            print(f"{idx} => BUY at {row['close']:.2f} (RSI={row['RSI']:.2f})")
            position = 1
        elif row['Signal'] == -1 and position == 1:
            print(f"{idx} => SELL at {row['close']:.2f} (RSI={row['RSI']:.2f})")
            position = 0

else:
    print(f'Error retrieving data: {response.status_code} - {response.text}')        

Brief Explanation:

  1. Importing Libraries:

  • requests for API requests,
  • json for handling data,
  • datetime for date manipulation,
  • pandas for data processing,
  • pandas_ta for technical analysis.

2. Configuration Parameters:

  • API_KEY: API access key.
  • symbol: Apple stock (AAPL.US).
  • interval: Data with a 1-minute interval.
  • from_date_str and to_date_str: Date range to fetch.

3. Date Conversion:

  • Converts string dates into UNIX timestamps.

4. Constructing the URL and sending an HTTP request to the API:

  • The request is sent to eodhistoricaldata.com with the defined parameters.

5. Data Processing:

  • If the request is successful (status_code == 200), the response is converted into a Pandas DataFrame.
  • Columns (o, h, l, c, v) are renamed to more meaningful names (open, high, low, close, volume).
  • Timestamps are adjusted.

6. Calculating RSI:

  • Uses pandas_ta.rsi with a 14-period setting.

7. Generating Trading Signals:

  • Buy (Signal = 1): When RSI ≤ 30 (oversold).
  • Sell (Signal = -1): When RSI ≥ 70 (overbought).

8. Simulating Trades:

  • A position variable tracks if a trade is open.
  • When a buy signal is generated, it prints a buy action with price and RSI.
  • When a sell signal is generated, it prints a sell action with price and RSI.

9. Error Handling:

  • If the API request fails, it displays an error message with the status code.

Coding results

Key Points for an RSI Trading Strategy

  • RSI: A measure of the speed and magnitude of price movements.
  • Thresholds: Common ones are 30 (oversold) and 70 (overbought). You can adjust these based on your risk tolerance and market conditions.
  • Risk Management: Real-world bots need a combination of stop-loss, take-profit, and often additional indicators or models to confirm signals.
  • Backtesting: Always test on historical data to gauge past performance. Markets can change, so continuous monitoring and updates may be necessary.

Conclusion

By leveraging the Intraday Historical Data API from EODHD, you can overcome common pitfalls in market data collection — such as incomplete coverage, irregular updates, and insufficient resolution. Automating your trading strategy through a bot then lets you capitalize on these quality data feeds around the clock.

“It always seems impossible until it’s done.” – Nelson Mandela

When you combine a reliable data pipeline with a well-structured strategy, the possibilities for innovation in algorithmic trading expand significantly. Continue refining your approach with additional technical indicators, risk management techniques, and robust backtesting to build a more resilient and profitable system.

要查看或添加评论,请登录

Kevin Meneses的更多文章

社区洞察