Getting started overview

Integrating with Polygon's API involves a sequence of steps designed to provide developers with access to financial market data. This guide outlines the process from account creation and API key retrieval to making a successful initial API call. Polygon offers various APIs covering stocks, options, forex, crypto, and indices, with data available in real-time or historically, depending on the subscription tier. The platform supports multiple SDKs, streamlining integration for common programming environments.

Before making any requests, developers need to secure an API key, which authenticates their access to Polygon's data endpoints. The official documentation provides comprehensive guides for each API, detailing endpoint specifications, request parameters, and response formats. Understanding these foundational elements is crucial for effective integration and data utilization.

Quick Reference Table

Step What to Do Where
1. Sign Up Create a Polygon.io account. Polygon.io Registration Page
2. Get API Key Locate your unique API key in your dashboard. Polygon.io API Keys Dashboard
3. Choose Endpoint Select the specific market data API endpoint. Polygon.io Developer Documentation
4. Make Request Construct an API call using your key and chosen endpoint. Code editor with a preferred language (e.g., Python, Node.js)
5. Process Response Parse the JSON data returned by the API. Application logic

Create an account and get keys

To begin using Polygon's APIs, the first step is to create a user account. This can be done through the Polygon.io registration page. During the signup process, users typically provide an email address and create a password. Once registered, access to the Polygon dashboard is granted, which serves as the central hub for managing subscriptions, viewing usage statistics, and retrieving API keys.

After successful registration and login, navigate to the API Keys section of the Polygon dashboard. Here, a unique API key is generated automatically for each account. This API key is a crucial credential as it authenticates all requests made to Polygon's API endpoints. It is important to treat this key as sensitive information, similar to a password, to prevent unauthorized access to your account and data allowances. Polygon's documentation recommends storing API keys securely and avoiding hardcoding them directly into public-facing code repositories.

Polygon offers a Starter free tier, which provides access to delayed market data, suitable for initial testing and development. For real-time data and increased request limits, developers can upgrade to paid plans, starting with the Developer tier. Each tier provides different levels of access and data freshness, as detailed on the Polygon pricing page.

Your first request

With an API key secured, you can now make your first request to a Polygon API endpoint. This example will demonstrate fetching historical daily open, high, low, and close (OHLC) data for a stock using the Python SDK, a commonly supported language for financial APIs.

Prerequisites

  • Python 3.6+ installed.
  • Polygon's Python SDK installed: pip install polygon-api-client

Example: Fetching Daily OHLC Data for a Stock

This example retrieves the daily OHLC for 'AAPL' on a specific date.


from polygon import RESTClient
from datetime import date

# Replace 'YOUR_API_KEY' with your actual Polygon API key
API_KEY = "YOUR_API_KEY"

# Initialize the RESTClient
client = RESTClient(api_key=API_KEY)

def get_daily_ohlc(ticker: str, date_str: str):
    try:
        # Fetch daily OHLC aggregate for a specific ticker and date
        aggs = client.get_aggs(
            ticker=ticker,
            multiplier=1,
            timespan="day",
            from_=date_str,
            to=date_str,
            limit=1
        )

        if aggs and len(aggs) > 0:
            agg = aggs[0]
            print(f"Daily OHLC for {ticker} on {date_str}:")
            print(f"  Open: {agg.open}")
            print(f"  High: {agg.high}")
            print(f"  Low: {agg.low}")
            print(f"  Close: {agg.close}")
            print(f"  Volume: {agg.volume}")
        else:
            print(f"No OHLC data found for {ticker} on {date_str}.")

    except Exception as e:
        print(f"An error occurred: {e}")

# Call the function with Apple (AAPL) for a recent date
# Replace with a date where you expect data to be available
get_daily_ohlc("AAPL", "2023-01-09")

To execute this code:

  1. Save it as a .py file (e.g., polygon_data.py).
  2. Replace "YOUR_API_KEY" with the API key from your Polygon dashboard.
  3. Run it from your terminal: python polygon_data.py.

A successful request will print the daily OHLC values for Apple on the specified date. For more detailed examples and information on other endpoints, refer to the Polygon Stocks API documentation.

Alternative: Using curl for a direct API call

If you prefer to test direct HTTP requests without an SDK, curl can be used:


curl 'https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2023-01-09/2023-01-09?adjusted=true&sort=asc&limit=120&apiKey=YOUR_API_KEY'

Remember to replace YOUR_API_KEY with your actual key. This command fetches the same daily OHLC data for Apple. The response will be a JSON object containing the aggregate data.

Common next steps

After successfully making your first API call, several common next steps can enhance your integration with Polygon's market data:

  • Explore diverse data types: Polygon offers APIs not just for stocks, but also for options, forex, and cryptocurrencies. Investigate these to expand the scope of your financial application. Each API has specific endpoints and data models.
  • Implement real-time data streams: For applications requiring instantaneous market updates, explore Polygon's WebSocket APIs. These provide live data feeds, which are essential for algorithmic trading and real-time dashboard applications. The WebSocket documentation guides on establishing and maintaining these connections.
  • Error handling and rate limits: Integrate robust error handling into your application to manage API response codes, network issues, and data parsing errors. Pay close attention to Polygon's rate limit policies to avoid exceeding allowed request volumes, which can lead to temporary blocks or throttled access.
  • SDK utilization: Leverage the full capabilities of the provided SDKs (Python, Node.js, Go, Java, .NET, Rust, PHP) to simplify API interaction. SDKs often handle authentication, request formatting, and response parsing, reducing development time and potential errors.
  • Data storage and processing: For historical analysis or large-scale data processing, consider strategies for efficient data storage (e.g., databases, data lakes) and processing pipelines. This might involve setting up daily data ingestion jobs or implementing data warehousing solutions.
  • Security best practices: Enhance the security of your API key. Consider using environment variables or a secrets management service (e.g., AWS Secrets Manager, Google Secret Manager) instead of hardcoding keys directly into your application code. This practice is crucial for protecting sensitive credentials, as advised by general API security guidelines like those from Google Cloud security best practices.

Troubleshooting the first call

When making your initial API call to Polygon, you might encounter issues. Here are common problems and their solutions:

  • Invalid API Key (HTTP 401 Unauthorized):
    • Problem: The API returns a 401 status code, indicating that your request is not authorized.
    • Solution: Double-check that you have correctly copied your API key from your Polygon dashboard. Ensure there are no leading or trailing spaces. Verify that the key is passed as a query parameter (apiKey=YOUR_KEY) or in the header as specified by the Polygon docs.
  • Rate Limit Exceeded (HTTP 429 Too Many Requests):
    • Problem: You receive a 429 status code, meaning you've sent too many requests in a short period.
    • Solution: Review Polygon's rate limit documentation for your specific subscription tier. Implement delays between requests or use a retry mechanism with exponential backoff. For development, ensure you're not in a tight loop making excessive calls.
  • Missing or Invalid Parameters (HTTP 400 Bad Request):
    • Problem: The API responds with a 400 error, indicating that a required parameter is missing or one of the parameters has an invalid format.
    • Solution: Consult the Polygon API reference for the specific endpoint you are calling. Verify that all mandatory parameters (e.g., ticker, date range) are present and correctly formatted (e.g., dates as 'YYYY-MM-DD').
  • No Data Returned (Empty Array or HTTP 200 with no content):
    • Problem: The API call is successful (HTTP 200 OK) but returns an empty data set.
    • Solution: This often means there's no data matching your specific query. Check the ticker symbol for accuracy, verify the date range to ensure it covers periods with available data, and confirm that your subscription tier includes access to the requested data (e.g., real-time vs. delayed data).
  • Network or Connection Issues:
    • Problem: Your application cannot connect to the Polygon API endpoints.
    • Solution: Check your internet connection. Ensure there are no firewall rules or proxy settings blocking outgoing HTTP requests to api.polygon.io. If using a corporate network, consult with your IT department.
  • SDK-specific errors:
    • Problem: Errors originating from the SDK itself, such as import errors or method not found.
    • Solution: Verify that the Polygon SDK is correctly installed and up to date (e.g., pip install --upgrade polygon-api-client for Python). Consult the specific SDK documentation for usage examples and common issues.