Polygon API Python: A Complete Guide

·

Learn how to leverage the Polygon.io Python API to fetch historical price data for cryptocurrencies, stocks, futures, and forex markets. This guide provides step-by-step instructions for setting up and using the API efficiently.


Installation and Setup

1. Install Polygon API Client

Activate your Python virtual environment and install the Polygon API client using pip:

pip install polygon-api-client

2. Import Required Modules

Import the necessary modules, including the Polygon RESTClient and your API key settings:

from polygon import RESTClient
from local_settings import polygon as settings

Extending RESTClient Functionality

3. Inherit and Customize RESTClient

Enhance the default RESTClient by adding a retry strategy for robust API calls:

from datetime import date, datetime
from typing import Any, Optional
import pandas as pd
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

markets = ['crypto', 'stocks', 'fx']

class MyRESTClient(RESTClient):
    def __init__(self, auth_key: str=settings['api_key'], timeout:int=5):
        super().__init__(auth_key)
        retry_strategy = Retry(
            total=10,
            backoff_factor=10,
            status_forcelist=[429, 500, 502, 503, 504]
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self._session.mount('https://', adapter)

Core Methods

4. Fetch Tickers

Retrieve active tickers for a specific market (e.g., crypto):

def get_tickers(self, market:str=None) -> pd.DataFrame:
    if not market in markets:
        raise Exception(f'Market must be one of {markets}.')
    resp = self.reference_tickers_v3(market=market)
    if hasattr(resp, 'results'):
        df = pd.DataFrame(resp.results)
        while hasattr(resp, 'next_url'):
            resp = self.reference_tickers_v3(next_url=resp.next_url)
            df = pd.concat([df, pd.DataFrame(resp.results)])
        if market == 'crypto':
            df = df[df['currency_symbol'] == 'USD']
            df['name'] = df['base_currency_name']
        return df[['ticker', 'name', 'market', 'active']].drop_duplicates('ticker')
    return None

👉 Explore real-time ticker data


5. Fetch Historical Price Data

Get minute-level bars for a given ticker:

def get_bars(self, market:str, ticker:str, multiplier:int=1,
             timespan:str='minute', from_:date=None, to:date=None) -> pd.DataFrame:
    from_ = from_ or date(2000, 1, 1)
    to = to or date.today()
    if market == 'crypto':
        resp = self.crypto_aggregates(
            ticker, multiplier, timespan,
            from_.strftime('%Y-%m-%d'), to.strftime('%Y-%m-%d'),
            limit=50000
        )
        df = pd.DataFrame(resp.results)
        last_minute = 0
        while resp.results[-1]['t'] > last_minute:
            last_minute = resp.results[-1]['t']
            last_date = datetime.fromtimestamp(last_minute/1000).strftime('%Y-%m-%d')
            resp = self.crypto_aggregates(
                ticker, multiplier, timespan,
                last_date, to.strftime('%Y-%m-%d'),
                limit=50000
            )
            new_df = pd.DataFrame(resp.results)
            df = pd.concat([df, new_df[new_df['t'] > last_minute]])
        df['date'] = pd.to_datetime(df['t'], unit='ms')
        return df.rename(columns={
            'o': 'open', 'h': 'high', 'l': 'low',
            'c': 'close', 'v': 'volume'
        })[['date', 'open', 'high', 'low', 'close', 'volume']]
    return None

Example Usage

client = MyRESTClient(settings['api_key'])
crypto_tickers = client.get_tickers(market='crypto')
btc_data = client.get_bars(
    market='crypto',
    ticker='X:BTCUSD',
    from_=datetime(2021, 1, 1).date()
)

FAQ

Q: How do I handle API rate limits?

A: The custom Retry strategy automatically handles 429 and 5xx errors with exponential backoff.

Q: Can I use this for real-time data?

A: This guide focuses on historical data. For real-time streams, explore Polygon’s WebSocket API.

Q: What markets are supported?

A: Crypto, stocks, and forex (FX). Futures support is also available.

👉 Learn advanced API techniques


Keywords