Introducing

Polygon.io + Python: Unlocking Real-Time and Historical Stock Market Data

Feb 17, 2023

In this blog post, we will show you how to access market data using Polygon's Stock API and the Python programming language. Polygon is a financial data platform that provides both real-time and historical market data for Stocks, Options, Forex, and Crypto. With access to this information, developers, investors, and financial institutions can gain valuable insights and make informed decisions.

Getting Started

To access real-time and historical stock market data with Polygon you will need to first create an account and obtain an API key to authenticate your requests. Next, to learn more about the wide range of market data, reference data, and real-time streaming data that is available, please read Stock API documentation. Finally, to access the Stock API using Python, you will need to have a few libraries, such as the “polygon-api-client” client library for accessing market data, "requests" for REST API requests, and "websockets" for real-time data streaming.

To get started, you will need Python 3.8+, and to install the polygon python client library:

python3 --version
pip install polygon-api-client

From here, fetching data is easy. For example, here is how to get aggregate bars for a stock over a given date range:

from polygon import RESTClient

client = RESTClient(“POLYGON_API_KEY”)

aggs = []
for a in client.list_aggs(
    "AAPL",
    1,
    "minute",
    "2022-01-01",
    "2023-02-03",
    limit=50000,
):
    aggs.append(a)

print(aggs)

To see this in action, below is a step-by-step guided video tour for getting started with Polygon's APIs. Whether you are new to Polygon.io, or have used it before, this video will be a helpful resource for you as you started.

With these steps in place, you are now ready to start accessing all that Polygon's APIs offer with the Python programming language. For more information, please see the polygon-io/client-python and documentation.

Market Data Endpoints

In this section, we will look at why Market Data Endpoints are a key feature of Polygon's APIs and how they provide access to real-time and historical data for the stock market. There are several types of market data endpoints available that provide real-time and historical, including:

  • Aggregated bar data for stocks
  • Quotes for stocks
  • Trades data for stocks
  • Snapshots that span the entire stock market
  • Technical indicators for selected ticker symbols

To access real-time and historical market data using Polygon's APIs and Python, you can make REST API requests to the appropriate endpoints. For example, you can use the following code to retrieve real-time trade and quote data for

AAPL
:

from polygon import RESTClient

# docs
# https://polygon.io/docs/stocks/get_v2_last_trade__stocksticker
# https://polygon-api-client.readthedocs.io/en/latest/Trades.html#get-last-trade

# client = RESTClient("XXXXXX") # hardcoded api_key is used
client = RESTClient()  # POLYGON_API_KEY environment variable is used

# get last trade
trade = client.get_last_trade(
    "AAPL",
)
print(trade)

# get last quote
quote = client.get_last_quote(
    "AAPL",
)
print(quote)

To see this in action, below is a step-by-step guided video tour for getting started with Market Data for stocks with Polygon. This video will be a helpful resource for you as you start exploring real-time and historical trades and quotes, market wide snapshots, and technical indicators.

For more information, please see the polygon-io/client-python repository and the documentation.

Reference Data Endpoints

In this section, we'll be diving into how to use Polygon's Reference Data Endpoints with Python. There is a range of endpoints, which can be used to retrieve data such as ticker symbols, exchanges, and historical events like stock splits and dividends, amongst other things.

To use these endpoints with Python, you can follow the code snippets provided in the client-python library's examples/rest directory. The Tickers endpoint can be used to get a list of all active ticker symbols in the stock market, which can be used as a seed for other queries. For example, you can fetch all dividends or stock splits for these stocks. These reference data endpoints can be powerful when chained together, and can help you to answer questions, enrich existing data, or act as a type of index for ticker symbols that exist.

from polygon import RESTClient

# docs
# https://polygon.io/docs/stocks/get_v3_reference_tickers
# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#list-tickers

# client = RESTClient("XXXXXX") # hardcoded api_key is used
client = RESTClient()  # POLYGON_API_KEY environment variable is used

tickers = []
for t in client.list_tickers(market="stocks", type="CS", active="true", limit=1000):
    tickers.append(t)
print(tickers)

To see this in action, below is a step-by-step guided video tour for getting started with stock market reference data with Polygon.io. This video will be a helpful resource for you as you get exploring ticker symbols, exchanges, ticker news, dividends, splits, and more.

For more information, please see the polygon-io/client-python repository and the documentation.

Streaming Real-Time Data

The Polygon Stock WebSocket API provides both real-time and 15-minute delayed data streaming access to stock market data from all US stock exchanges (see pricing). Things happen very quickly in the world of finance and having the latest information is essential for monitoring portfolio performance, reacting quickly to news, doing research or conducting technical analysis, making day trading decisions, and for executing algorithmic trading strategies.

Here are the types of data which can be streamed via a WebSocket in real-time for both individual stock ticker and across the entire market (all tickers):

  • Aggregates (Per Minute): Stream real-time minute aggregates.
  • Aggregates (Per Second): Stream real-time second aggregates.
  • Trades: Stream real-time trades.
  • Quotes: Stream real-time quotes.

The code sample below, subscribes to all trades across the entire market passing

T.*
as the subscription parameter and prints them to the console:

from polygon import WebSocketClient
from polygon.websocket.models import WebSocketMessage
from typing import List

# subscribes to all trades
c = WebSocketClient(subscriptions=["T.*"])

def handle_msg(msgs: List[WebSocketMessage]):
    for m in msgs:
        print(m)

c.run(handle_msg)

To see this in action, below is a step-by-step guided video tour for getting started with streaming real-time stock market data with Polygon.io. This video will be a helpful resource for you as you get started streaming aggregates, trades, and quotes.

With these steps in place, you are now ready to start streaming the real-time data that Polygon's APIs offer. For more information, please see the polygon-io/client-python and documentation.

Next Steps

You should now have a well-rounded understanding of how to use Polygon's APIs and Python to access market data, reference data, and real-time streaming data. By using Polygon's APIs, you have very powerful tools at your fingertips to analyze market trends, develop real-time financial dashboards, and gain valuable insights.

The best way to get started is to sign up, explore the Stock API documentation, experiment with different endpoints using the Python examples, and then build your own applications to increase your knowledge and gain practical hands-on experience.

From the blog

See what's happening at polygon.io

integration quantconnect Feature Image
featured

Integration: QuantConnect

We are excited to announce our integration with QuantConnect! This offering empowers users with state-of-the-art research, backtesting, parameter optimization, and live trading capabilities, all fueled by the robust market data APIs and WebSocket Streams of Polygon.io.