0Pricing
AI Agents · Lesson

Market Data API Integration

Alpha Vantage, Yahoo Finance, and Polygon.io for real-time and historical data.

Market Data API Integration is a free AI Agents lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Market Data in Financial Agents

Financial analysis agents need access to real-time and historical market data. Common data types include OHLCV (Open/High/Low/Close/Volume), earnings dates, fundamental ratios, and options chains.

Several APIs provide this data: yfinance (free, Yahoo Finance), Polygon.io (paid, reliable), and Alpha Vantage (free tier available).

yfinance: Historical Price Data

yfinance wraps the Yahoo Finance API and is the quickest way to get started. Ticker.history() returns a pandas DataFrame of OHLCV data.

import yfinance as yf

ticker = yf.Ticker('AAPL')

# 1 year of daily data
history = ticker.history(period='1y')
print(history.tail(3))
#                  Open        High         Low       Close    Volume
# Date
# 2026-05-27  189.1500  190.3200  188.9200  190.0500  55234000
# 2026-05-28  190.4200  191.5600  189.7800  191.1200  62345000
print(f'Rows: {len(history)}')

yfinance: Custom Date Ranges

Use start and end parameters for custom date ranges, or interval for intraday data (1m, 5m, 1h). Note that intraday data is limited to the last 60 days depending on the interval.

import yfinance as yf

ticker = yf.Ticker('MSFT')

# Custom date range
history = ticker.history(start='2024-01-01', end='2024-12-31')
print(f'Trading days in 2024: {len(history)}')

# Batch multiple tickers
tickers = yf.download(['AAPL', 'MSFT', 'GOOGL'],
                       start='2025-01-01', end='2025-12-31')
print(tickers['Close'].head())

Polygon.io REST API

Polygon.io provides professional-grade market data with higher rate limits and more reliable uptime than free sources. Use it for production financial agents.

import requests

POLYGON_KEY = 'YOUR_POLYGON_API_KEY'

def get_polygon_daily(ticker: str, from_date: str, to_date: str) -> list[dict]:
    url = f'https://api.polygon.io/v2/aggs/ticker/{ticker}/range/1/day/{from_date}/{to_date}'
    resp = requests.get(url, params={'apiKey': POLYGON_KEY, 'limit': 365})
    resp.raise_for_status()
    data = resp.json()
    return data.get('results', [])

bars = get_polygon_daily('AAPL', '2025-01-01', '2025-12-31')
print(f'Bars returned: {len(bars)}')
if bars:
    print('Latest close:', bars[-1]['c'])

Alpha Vantage TIME_SERIES_DAILY

Alpha Vantage provides a free tier (25 calls/day) and a paid tier. The TIME_SERIES_DAILY endpoint returns OHLCV data with optional adjusted prices.

import requests

ALPHA_KEY = 'YOUR_ALPHA_VANTAGE_KEY'

def get_alpha_vantage_daily(symbol: str, outputsize: str = 'compact') -> dict:
    # outputsize: 'compact' (100 days) or 'full' (20+ years)
    resp = requests.get('https://www.alphavantage.co/query', params={
        'function':   'TIME_SERIES_DAILY_ADJUSTED',
        'symbol':     symbol,
        'outputsize': outputsize,
        'apikey':     ALPHA_KEY
    })
    resp.raise_for_status()
    data = resp.json()
    series = data.get('Time Series (Daily)', {})
    return series   # dict: {date_str: {open, high, low, close, volume, ...}}

Rate Limits and Retry Logic

All market data APIs enforce rate limits. Exceed them and you get 429 (Too Many Requests). Always implement exponential backoff and respect the limits.

import time, requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

def make_rate_limited_session(calls_per_minute: int = 5) -> requests.Session:
    session = requests.Session()
    retry = Retry(
        total=3,
        backoff_factor=2,         # 1s, 2s, 4s waits
        status_forcelist=[429, 500, 502, 503, 504]
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('https://', adapter)
    session._calls_per_min = calls_per_minute
    session._min_interval  = 60.0 / calls_per_minute
    session._last_call     = 0.0
    return session

def rate_limited_get(session, url, **kwargs):
    elapsed = time.time() - session._last_call
    if elapsed < session._min_interval:
        time.sleep(session._min_interval - elapsed)
    session._last_call = time.time()
    return session.get(url, **kwargs)

Caching Market Data

Historical data is immutable — yesterday's close price never changes. Cache it to avoid redundant API calls. Use a simple disk cache keyed by (ticker, date_range).

import hashlib, json, os

CACHE_DIR = '/tmp/market_cache'
os.makedirs(CACHE_DIR, exist_ok=True)

def cache_key(ticker: str, start: str, end: str) -> str:
    return hashlib.md5(f'{ticker}_{start}_{end}'.encode()).hexdigest()

def get_cached(ticker: str, start: str, end: str):
    key = cache_key(ticker, start, end)
    path = os.path.join(CACHE_DIR, f'{key}.json')
    if os.path.exists(path):
        with open(path) as f:
            return json.load(f)
    return None

def set_cached(ticker: str, start: str, end: str, data):
    key = cache_key(ticker, start, end)
    path = os.path.join(CACHE_DIR, f'{key}.json')
    with open(path, 'w') as f:
        json.dump(data, f)

if __name__ == '__main__':
    set_cached('AAPL', '2024-01-01', '2024-01-31', {'close': [150, 151, 149]})
    cached = get_cached('AAPL', '2024-01-01', '2024-01-31')
    print('Cached data for AAPL:', cached)
    print('Cache miss for MSFT:', get_cached('MSFT', '2024-01-01', '2024-01-31'))

Handling Trading Hours and Market Gaps

Markets are closed on weekends and holidays. Date ranges that span non-trading days will have gaps in the data. Always detect and handle these gaps rather than assuming continuous daily data.

import pandas as pd
from pandas.tseries.offsets import BDay

def detect_gaps(history: pd.DataFrame) -> list[str]:
    if history.empty:
        return []
    date_range = pd.date_range(
        start=history.index.min(),
        end=history.index.max(),
        freq=BDay()  # Business days only
    )
    missing = date_range.difference(history.index)
    return [str(d.date()) for d in missing]

import yfinance as yf
history = yf.Ticker('AAPL').history(start='2024-12-23', end='2025-01-07')
gaps = detect_gaps(history)
print('Missing business days (holidays):', gaps)

Building a Market Data Tool for Agents

Register a market data fetcher as an agent tool. The LLM can call it to retrieve data, then use another tool (analysis) to process the result.

import yfinance as yf, json

def get_market_data_tool(ticker: str, period: str = '1y') -> str:
    cached = get_cached(ticker, period, 'yfinance')
    if cached:
        return json.dumps(cached)
    try:
        hist = yf.Ticker(ticker).history(period=period)
        if hist.empty:
            return json.dumps({'error': f'No data for {ticker}'})
        result = {
            'ticker':     ticker,
            'period':     period,
            'start':      str(hist.index.min().date()),
            'end':        str(hist.index.max().date()),
            'latest_close': float(hist['Close'].iloc[-1]),
            'pct_change_ytd': float((hist['Close'].iloc[-1] / hist['Close'].iloc[0] - 1) * 100),
            'rows':       len(hist)
        }
        set_cached(ticker, period, 'yfinance', result)
        return json.dumps(result)
    except Exception as e:
        return json.dumps({'error': str(e)})

Fundamental Data from yfinance

Beyond price data, yfinance provides fundamental data: P/E ratio, earnings per share, market cap, and more. Fundamental data enriches an agent's analysis beyond pure price action.

import yfinance as yf

ticker = yf.Ticker('AAPL')
info  = ticker.info

print('Market Cap:      ', info.get('marketCap'))
print('P/E Ratio:       ', info.get('trailingPE'))
print('EPS:             ', info.get('trailingEps'))
print('52-Week High:    ', info.get('fiftyTwoWeekHigh'))
print('52-Week Low:     ', info.get('fiftyTwoWeekLow'))
print('Dividend Yield:  ', info.get('dividendYield'))
print('Analyst Target:  ', info.get('targetMeanPrice'))

Error Handling: Delisted and Invalid Tickers

Not all ticker symbols are valid or currently trading. A delisted company returns empty history. Always validate the response before proceeding with analysis.

import yfinance as yf

def safe_fetch(ticker_symbol: str, period: str = '1y') -> dict:
    try:
        ticker = yf.Ticker(ticker_symbol)
        history = ticker.history(period=period)

        if history.empty:
            return {
                'error': f'No data for {ticker_symbol}. May be delisted or invalid.',
                'ticker': ticker_symbol
            }
        return {
            'ticker':       ticker_symbol,
            'latest_close': float(history['Close'].iloc[-1]),
            'data_start':   str(history.index.min().date()),
            'bars':         len(history)
        }
    except Exception as e:
        return {'error': str(e), 'ticker': ticker_symbol}

print(safe_fetch('AAPL'))    # valid
print(safe_fetch('INVALID')) # returns error dict

What does the 'compact' outputsize return in the Alpha Vantage TIME_SERIES_DAILY endpoint?

Understanding API output size parameters is important for managing bandwidth, latency, and API quotas in financial agents.

Market Data API Integration Recap

Use yfinance for quick prototyping (free), Polygon.io for production (reliable, paid), and Alpha Vantage for a free-tier option. Always implement rate limiting, disk caching for historical data, and gap detection for non-trading days.

Expose fetching as an agent tool so the LLM can request data when needed.

Frequently asked questions

Is the “Market Data API Integration” lesson free?

Yes — the full text of “Market Data API Integration” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “Market Data API Integration”?

Alpha Vantage, Yahoo Finance, and Polygon.io for real-time and historical data. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Market Data API Integration” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Market Data API Integration
  2. Portfolio Analysis Agent Tools
  3. Risk and Compliance Guardrails
  4. Backtesting Agent Decisions
← Back to AI Agents