Accessing real-time and historical market data is essential for traders, developers, and analysts building data-driven financial applications. One of the most powerful tools for this purpose is the Polygon.io API, which offers comprehensive coverage across multiple asset classes—including cryptocurrencies, stocks, forex, and futures. When combined with Python, one of the most popular programming languages in finance and data science, Polygon becomes an even more potent resource.
This guide walks you through setting up and using the Polygon Python API client to fetch historical price data efficiently, with built-in error handling and retry logic. Whether you're building a backtesting engine, a live trading bot, or conducting quantitative research, this tutorial provides a solid foundation.
👉 Discover how to integrate live market data into your Python projects today.
Setting Up the Polygon Python API
Before retrieving any market data, you need to install the official Polygon API client for Python. It’s recommended to work within a virtual environment to manage dependencies cleanly.
Run the following command to install the polygon-api-client package:
pip install polygon-api-clientOnce installed, ensure your environment is configured securely by storing your API key outside of your main codebase—ideally in a separate configuration file like local_settings.py.
Importing Required Libraries
Start your script by importing the necessary modules:
from polygon import RESTClient
from local_settings import polygon as settings
from datetime import date, datetime
from typing import Any, Optional
import pandas as pd
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import RetryHere, we import the REST client provided by Polygon, along with standard libraries for handling dates, typing hints, data manipulation (pandas), and robust HTTP request handling.
Enhancing Reliability with Retry Logic
API requests can fail due to rate limits or temporary server issues. To improve reliability, extend the default RESTClient class to include automatic retries using exponential backoff.
Define a custom class MyRESTClient that inherits from RESTClient and configures retry behavior for common HTTP errors:
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)This setup ensures your application automatically retries failed requests up to 10 times with increasing delays between attempts—ideal for handling rate limits (HTTP 429) and server-side errors.
Fetching Tradable Tickers by Market
To retrieve a list of available assets, use the reference_tickers_v3 endpoint. The following method allows filtering tickers by market type—crypto, stocks, or forex.
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 = df.append(pd.DataFrame(resp.results))
if market == 'crypto':
df = df[df['currency_symbol'] == 'USD']
df['name'] = df['base_currency_name']
df = df[['ticker', 'name', 'market', 'active']]
df = df.drop_duplicates(subset='ticker')
return df
return NoneFor example, calling client.get_tickers(market='crypto') returns all active USD-traded cryptocurrencies:
| ticker | name | market | active |
|---|---|---|---|
| X:BTCUSD | Bitcoin | crypto | True |
| X:ETHUSD | Ethereum | crypto | True |
| X:SOLUSD | Solana | crypto | True |
This list is useful for dynamically populating trading pairs or filtering instruments for analysis.
👉 Learn how to automate data collection from global markets using secure APIs.
Retrieving Historical Price Data (Minute Bars)
One of the most common use cases is fetching time-series price data. The get_bars method retrieves candlestick (OHLCV) data at various intervals—such as 1-minute or 1-hour bars.
def get_bars(self, market: str = None, ticker: str = None, multiplier: int = 1,
timespan: str = 'minute', from_: date = None, to: date = None) -> pd.DataFrame:
if not market in markets:
raise Exception(f'Market must be one of {markets}.')
if ticker is None:
raise Exception('Ticker must not be None.')
from_ = from_ if from_ else date(2000, 1, 1)
to = to if to else 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_minute_date = datetime.fromtimestamp(last_minute / 1000).strftime('%Y-%m-%d')
resp = self.crypto_aggregates(
ticker, multiplier, timespan,
last_minute_date, to.strftime('%Y-%m-%d'),
limit=50000
)
new_bars = pd.DataFrame(resp.results)
df = df.append(new_bars[new_bars['t'] > last_minute])
df['date'] = pd.to_datetime(df['t'], unit='ms')
df = df.rename(columns={
'o': 'open', 'h': 'high', 'l': 'low',
'c': 'close', 'v': 'volume', 'vw': 'vwap',
'n': 'transactions'
})
return df[['date', 'open', 'high', 'low', 'close', 'volume']]
return NoneExample usage:
start = date(2021, 1, 1)
client = MyRESTClient()
df = client.get_bars(market='crypto', ticker='X:BTCUSD', from_=start)
print(df.head())This will return high-resolution minute-level bars for Bitcoin/USD starting from January 2021.
Core Keywords for SEO Optimization
- Polygon API Python
- historical price data
- crypto API Python
- stock market data API
- fetch cryptocurrency prices
- Python financial data
- Polygon.io tutorial
- REST API for trading
These keywords naturally appear throughout the content and align with common search queries related to financial data retrieval using Python.
Frequently Asked Questions
Q: Is the Polygon.io API free to use?
A: Polygon offers a free tier with limited requests per day. For higher-volume access or professional use, paid plans are available with enhanced rate limits and features.
Q: Can I get intraday stock data using this API?
A: Yes. The Polygon API supports minute-level and daily aggregates for equities, making it ideal for technical analysis and algorithmic trading strategies.
Q: How do I handle pagination when fetching large datasets?
A: The API uses cursor-based pagination. In the code above, we loop through responses using next_url until all data is retrieved—ensuring completeness.
Q: What markets does Polygon support?
A: Polygon covers major asset classes including U.S. stocks, cryptocurrencies (spot and futures), forex pairs, and futures contracts.
Q: Why use a retry strategy with the API?
A: Network issues and rate limiting are common. Implementing retries with exponential backoff improves reliability and prevents script failures during transient errors.
Q: Can I use this data for live trading systems?
A: Absolutely. With proper error handling and latency optimization, Polygon’s real-time and historical feeds are widely used in production trading environments.
👉 Start building your next financial analytics tool with reliable market data integration.