Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The official Python client library for the Polygon REST and WebSocket API.

License

NotificationsYou must be signed in to change notification settings

polygon-io/client-python

Repository files navigation

PyPI versionDocs

Polygon Python Client - WebSocket & RESTful APIs

Welcome to the official Python client library for thePolygon REST and WebSocket API. To get started, please see theGetting Started section in our documentation, view theexamples directory for code snippets, or theblog post with video tutorials to learn more.

Prerequisites

Before installing the Polygon Python client, ensure your environment has Python 3.8 or higher.

Install

Please use pip to install or update to the latest stable version.

pip install -U polygon-api-client

Getting started

To get started, please see theGetting Started section in our docs, view theexamples directory for code snippets, or view theblog post with videos to learn more.

The free tier of our API comes with usage limitations, potentially leading to rate limit errors if these are exceeded. For uninterrupted access and to support larger data requirements, we recommend reviewing oursubscription plans, which are tailored for a wide range of needs from development to high-demand applications. Refer to our pricing page for detailed information on limits and features to ensure a seamless experience, especially for real-time data processing.

REST API Client

Import the RESTClient.

frompolygonimportRESTClient

Create a new client with yourAPI key

client=RESTClient(api_key="<API_KEY>")

Using the Client

Request data using client methods.

ticker="AAPL"# List Aggregates (Bars)aggs= []forainclient.list_aggs(ticker=ticker,multiplier=1,timespan="minute",from_="2023-01-01",to="2023-06-13",limit=50000):aggs.append(a)print(aggs)# Get Last Tradetrade=client.get_last_trade(ticker=ticker)print(trade)# List Tradestrades=client.list_trades(ticker=ticker,timestamp="2022-01-04")fortradeintrades:print(trade)# Get Last Quotequote=client.get_last_quote(ticker=ticker)print(quote)# List Quotesquotes=client.list_quotes(ticker=ticker,timestamp="2022-01-04")forquoteinquotes:print(quote)

Pagination Behavior

By default, the client paginates results for endpoints likelist_trades andlist_quotes behind the scenes for you. Understanding how pagination interacts with thelimit parameter is key.

Default (Pagination Enabled)

Pagination is enabled by default (pagination=True):

  • limit controls the page size, not the total number of results.
  • The client automatically fetches all pages, yielding results until none remain.

Here's an example:

client=RESTClient(api_key="<API_KEY>")trades= [tfortinclient.list_trades(ticker="TSLA",limit=100)]

This fetches all TSLA trades, 100 per page.

Disabling Pagination

To return a fixed number of results and stop, disable pagination:

client=RESTClient(api_key="<API_KEY>",pagination=False)trades= [tfortinclient.list_trades(ticker="TSLA",limit=100)]

This returns at most 100 total trades, no additional pages.

Performance Tip

If you're fetching large datasets, always use the maximum supported limit for the API endpoint. This reduces the number of API calls and improves overall performance.

Additional Filter Parameters

Many of the APIs in this client library support the use of additional filter parameters to refine your queries. Please refer to the specific API documentation for details on which filter parameters are supported for each endpoint. These filters can be applied using the following operators:

  • .gt: greater than
  • .gte: greater than or equal to
  • .lt: less than
  • .lte: less than or equal to

Here's a sample code snippet that demonstrates how to use these filter parameters when requesting an Options Chain using thelist_snapshot_options_chain method. In this example, the filter parameters ensure that the returned options chain data will only include options with an expiration date that is greater than or equal to "2024-03-16" and a strike price that falls between 29 and 30 (inclusive).

options_chain= []foroinclient.list_snapshot_options_chain("HCP",params={"expiration_date.gte":"2024-03-16","strike_price.gte":29,"strike_price.lte":30,    },):options_chain.append(o)print(options_chain)print(len(options_chain))

Also, please refer to the API documentation to get a full understanding of how the API works and the supported arguments. All required arguments are annotated with red asterisks " * " and argument examples are set.

Debugging with RESTClient

Sometimes you may find it useful to see the actual request and response details while working with the API. TheRESTClient allows for this through itstrace=True option.

How to Enable Debug Mode

You can activate the debug mode as follows:

client=RESTClient(trace=True)

What Does Debug Mode Do?

When debug mode is enabled, the client will print out useful debugging information for each API request. This includes: the request URL, the headers sent in the request, and the headers received in the response.

Example Output

For instance, if you made a request forTSLA data for the date2023-08-01, you would see debug output similar to the following:

Request URL: https://api.polygon.io/v2/aggs/ticker/TSLA/range/1/minute/2023-08-01/2023-08-01?limit=50000Request Headers: {'Authorization': 'Bearer REDACTED', 'Accept-Encoding': 'gzip', 'User-Agent': 'Polygon.io PythonClient/1.12.4'}Response Headers: {'Server': 'nginx/1.19.2', 'Date': 'Tue, 05 Sep 2023 23:07:02 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'X-Request-Id': '727c82feed3790b44084c3f4cae1d7d4', 'Strict-Transport-Security': 'max-age=15724800; includeSubDomains'}

This can be an invaluable tool for debugging issues or understanding how the client interacts with the API.

WebSocket Client

Import classes

frompolygonimportWebSocketClientfrompolygon.websocket.modelsimportWebSocketMessagefromtypingimportList

Using the client

Create a new client with yourAPI key and subscription options.

# Note: Multiple subscriptions can be added to the array# For example, if you want to subscribe to AAPL and META,# you can do so by adding "T.META" to the subscriptions array. ["T.AAPL", "T.META"]# If you want to subscribe to all tickers, place an asterisk in place of the symbol. ["T.*"]ws=WebSocketClient(api_key=<API_KEY>,subscriptions=["T.AAPL"])

Create a handler function and run the WebSocket.

defhandle_msg(msg:List[WebSocketMessage]):forminmsg:print(m)ws.run(handle_msg=handle_msg)

Check out more detailed exampleshere.

Contributing

If you found a bug or have an idea for a new feature, please first discuss it with us bysubmitting a new issue.We will respond to issues within at most 3 weeks.We're also open to volunteers if you want to submit a PR for any open issues butplease discuss it with us beforehand. PRs that aren't linked to an existing issue ordiscussed with us ahead of time will generally be declined. If you have more generalfeedback or want to discuss using this client with other users, feel free to reach outon ourSlack channel.

Development

If you plan to contribute by developing new features then you will need to install certain dependencies.

Poetry

Poetry is a packaging and dependency manager for Python.Installation instructions can be foundon their website.Once installed runpoetry install to install the required dependencies. This step should be run after incorporating new upstream changes.

Makefile

Our Makefile has the common operations needed when developing on this repo. Running tests and linting can both berun through our Makefile. Just runmake help to see the list of available commands.

If you're usingpyenv to manage active Python versions then you might need to launch a Poetry shell before runningMake commands in order to actually use your chosen Python version. This is because Poetry uses the system Python versionby default.

poetry shell# start shellpoetry install# install depsmaketest# run your make commands

Release planning

This client will attempt to follow the release cadence of our API.When endpoints are deprecated and newer versions are added, the client willmaintain two methods in a backwards compatible way(e.g.list_trades andlist_trades_v4(...)).When deprecated endpoints are removed from the API, we'll rename the versionedmethod (e.g.list_trades_v4(...) ->list_trades(...)), remove the old method,and release a new major version of the client.

The goal is to give users ample time to upgrade to newer versions of our APIbefore we bump the major version of the client, and in general, we'll try tobundle breaking changes like this to avoid frequent major version bumps.

Exceptions to this are:

  • Methods underclient.vx. These are expiremental.
  • Methods that start with_*. We use these internally.
  • Type annotations. We may modify these based on our JSON responses.
  • We may add model fields.

[8]ページ先頭

©2009-2025 Movatter.jp