Library Interface Documentation
Here is the Entire Library Interface reference.
Base Client
- class polygon.base_client.BaseClient(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
This is the base client class for all other REST clients which inherit from this class and implement their own endpoints on top of it.
Any method starting with
async_
in its name is meant to be for async programming. All methods have their sync and async counterparts. Any async method must be awaited while non-async (or sync) methods should be called directly.Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.It is also a very good idea to visit the official documentation. I highly recommend using the UI there to play with the endpoints a bit. Observe the data you receive as the actual data received through python lib is exactly the same as shown on their page when you click
Run Query
.- __init__(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
Initiates a Client to be used to access all the endpoints.
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
use_async – Set to True to get an async client. Defaults to False which returns a non-async client.
connect_timeout – The connection timeout in seconds. Defaults to 10. basically the number of seconds to wait for a connection to be established. Raises a
ConnectTimeout
if unable to connect within specified time limit.read_timeout – The read timeout in seconds. Defaults to 10. basically the number of seconds to wait for date to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.
- close()
Closes the
requests.Session
and frees up resources. It is recommended to call this method in your exit handlers Note that this is meant for sync programming only. Useasync_close()
for async.
- async async_close()
Closes the
httpx.AsyncClient
and frees up resources. It is recommended to call this method in your exit handlers. This method should be awaited as this is a coroutine. Note that this is meant for async programming only. Useclose()
for sync.
- _get_response(path: str, params: Optional[dict] = None, raw_response: bool = True) Union[requests.models.Response, dict]
Get response on a path. Meant to be used internally but can be used if you know what you’re doing. To be used by sync client only. For async access, see
_get_async_response()
- Parameters
path – RESTful path for the endpoint. Available on the docs for the endpoint right above its name.
params – Query Parameters to be supplied with the request. These are mapped 1:1 with the endpoint.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to check the status code or inspect the headers. Defaults to True which returns theResponse
object.
- Returns
A Response object by default. Make
raw_response=False
to get JSON decoded Dictionary
- async _get_async_response(path: str, params: Optional[dict] = None, raw_response: bool = True) Union[httpx.Response, dict]
Get response on a path - meant to be used internally but can be used if you know what you’re doing - to be used by async client only. For sync access, see
_get_response()
- Parameters
path – RESTful path for the endpoint. Available on the docs for the endpoint right above its name.
params – Query Parameters to be supplied with the request. These are mapped 1:1 with the endpoint.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to check the status code or inspect the headers. Defaults to True which returns theResponse
object.
- Returns
A Response object by default. Make
raw_response=False
to get JSON decoded Dictionary
- get_next_page_by_url(url: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the next page of a response. The URl is returned within
next_url
attribute on endpoints which support pagination (eg the tickers endpoint). If the response doesn’t contain this attribute, either all pages were received or the endpoint doesn’t have pagination. Meant for internal use primarily.Note that this method is meant for sync programming. See
async_get_next_page_by_url()
for async.- Parameters
url – The next URL. As contained in
next_url
of the response.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of raw_response. Defaults to Dict.
- async async_get_next_page_by_url(url: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the next page of a response. The URl is returned within
next_url
attribute on endpoints which support pagination (eg the tickers endpoint). If the response doesn’t contain this attribute, either all pages were received or the endpoint doesn’t have pagination. Meant for internal use primarily.Note that this method is meant for async programming. See
get_next_page_by_url()
for sync.- Parameters
url – The next URL. As contained in
next_url
of the response.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of raw_response. Defaults to Dict.
- get_next_page(old_response: Union[requests.models.Response, dict], raw_response: bool = False) Union[requests.models.Response, dict, bool]
Get the next page using the most recent old response. This function simply parses the next_url attribute from the existing response and uses it to get the next page. Returns False if there is no next page remaining (which implies that you have reached the end of all pages or the endpoint doesn’t support pagination).
- Parameters
old_response – The most recent existing response. Can be either
Response
Object or Dictionariesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_next_page(old_response: Union[httpx.Response, dict], raw_response: bool = False) Union[httpx.Response, dict, bool]
Get the next page using the most recent old response. This function simply parses the next_url attribute from the existing response and uses it to get the next page. Returns False if there is no next page remaining (which implies that you have reached the end of all pages or the endpoint doesn’t support pagination) - Async method
- Parameters
old_response – The most recent existing response. Can be either
Response
Object or Dictionariesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_previous_page(old_response: Union[requests.models.Response, dict], raw_response: bool = False) Union[requests.models.Response, dict, bool]
Get the previous page using the most recent old response. This function simply parses the previous_url attribute from the existing response and uses it to get the previous page. Returns False if there is no previous page remaining (which implies that you have reached the start of all pages or the endpoint doesn’t support pagination).
- Parameters
old_response – The most recent existing response. Can be either
Response
Object or Dictionariesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_previous_page(old_response: Union[httpx.Response, dict], raw_response: bool = False) Union[httpx.Response, dict, bool]
Get the previous page using the most recent old response. This function simply parses the previous_url attribute from the existing response and uses it to get the previous page. Returns False if there is no previous page remaining (which implies that you have reached the start of all pages or the endpoint doesn’t support pagination) - Async method
- Parameters
old_response – The most recent existing response. Can be either
Response
Object or Dictionariesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
Stocks Client
- class polygon.stocks.stocks.StocksClient(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
This class implements all the Stocks REST endpoints. Note that you should always import names from top level. eg:
from polygon import StocksClient
orimport polygon
(which allows you to access all names easily)Creating the client is as simple as:
client = StocksClient('MY_API_KEY')
Once you have the client, you can call its methods to get data from the APIs. All methods have sane default values and almost everything can be customized.Any method starting with
async_
in its name is meant to be for async programming. All methods have their sync and async counterparts. Any async method must be awaited while non-async (or sync) methods should be called directly.Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.It is also a very good idea to visit the official documentation. I highly recommend using the UI there to play with the endpoints a bit. Observe the data you receive as the actual data received through python lib is exactly the same as shown on their page when you click
Run Query
.- __init__(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
Initiates a Client to be used to access all the endpoints.
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
use_async – Set to True to get an async client. Defaults to False which returns a non-async client.
connect_timeout – The connection timeout in seconds. Defaults to 10. basically the number of seconds to wait for a connection to be established. Raises a
ConnectTimeout
if unable to connect within specified time limit.read_timeout – The read timeout in seconds. Defaults to 10. basically the number of seconds to wait for date to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.
- get_trades(symbol: str, date, timestamp: Optional[int] = None, timestamp_limit: Optional[int] = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False) Union[requests.models.Response, dict]
Get trades for a given ticker symbol on a specified date. The response from polygon seems to have a
map
attribute which gives a mapping of attribute names to readable values. Official Docs- Parameters
symbol – The ticker symbol we want trades for.
date – The date/day of the trades to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
timestamp – The timestamp offset, used for pagination. Timestamp is the offset at which to start the results. Using the
timestamp
of the last result as the offset will give you the next page of results. Default: None. I’m trying to think of a good way to implement pagination support for this type of pagination.timestamp_limit – The maximum timestamp allowed in the results. Default: None
reverse – Reverse the order of the results. Default True: oldest first. Make it False for Newest first
limit – Limit the size of the response, max 50000 and default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_quotes(symbol: str, date, timestamp: Optional[int] = None, timestamp_limit: Optional[int] = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False) Union[requests.models.Response, dict]
Get Quotes for a given ticker symbol on a specified date. The response from polygon seems to have a
map
attribute which gives a mapping of attribute names to readable values. Official Docs- Parameters
symbol – The ticker symbol we want quotes for.
date – The date/day of the quotes to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
timestamp – The timestamp offset, used for pagination. Timestamp is the offset at which to start the results. Using the
timestamp
of the last result as the offset will give you the next page of results. Default: None. Thinking of a good way to implement this pagination here.timestamp_limit – The maximum timestamp allowed in the results. Default: None
reverse – Reverse the order of the results. Default True: oldest first. Make it False for Newest first
limit – Limit the size of the response, max 50000 and default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_last_trade(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the most recent trade for a given stock. Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_last_quote(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the most recent NBBO (Quote) tick for a given stock. Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_daily_open_close(symbol: str, date, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the OCHLV and after-hours prices of a stock symbol on a certain date. Official Docs
- Parameters
symbol – The ticker symbol we want daily-OCHLV for.
date – The date/day of the daily-OCHLV to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_aggregate_bars(symbol: str, from_date, to_date, adjusted: bool = True, sort='asc', limit: int = 5000, multiplier: int = 1, timespan='day', raw_response: bool = False) Union[requests.models.Response, dict]
Get aggregate bars for a stock over a given date range in custom time window sizes. For example, if
timespan = ‘minute’
andmultiplier = ‘5’
then 5-minute bars will be returned. Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
from_date – The start of the aggregate time window. Could be
datetime
ordate
or stringYYYY-MM-DD
to_date – The end of the aggregate time window. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
sort – Sort the results by timestamp. See
polygon.enums.SortOrder
for choices.asc
default.limit – Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000.
multiplier – The size of the timespan multiplier. Must be a positive whole number.
timespan – The size of the time window. See
polygon.enums.Timespan
for choices. defaults today
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the daily OCHLV for the entire stocks/equities markets. Official docs
- Parameters
date – The date to get the data for. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the previous day’s OCHLV for the specified stock ticker. Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_snapshot(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for a single traded stock ticker. Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_current_price(symbol: str) float
get current market price for the ticker symbol specified.
Uses
get_last_trade()
under the hood Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
- Returns
The current price. A
KeyError
indicates the request wasn’t successful.
- get_snapshot_all(symbols: list, raw_response: bool = False) Union[requests.models.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for all traded stock symbols. Official Docs
- Parameters
symbols – A comma separated list of tickers to get snapshots for.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_gainers_and_losers(direction='gainers', raw_response: bool = False) Union[requests.models.Response, dict]
Get the current top 20 gainers or losers of the day in stocks/equities markets. Official Docs
- Parameters
direction – The direction of results. Defaults to gainers. See
polygon.enums.SnapshotDirection
for choicesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_trades(symbol: str, date, timestamp: Optional[int] = None, timestamp_limit: Optional[int] = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False) Union[httpx.Response, dict]
Get trades for a given ticker symbol on a specified date. The response from polygon seems to have a
map
attribute which gives a mapping of attribute names to readable values - Async method Official Docs- Parameters
symbol – The ticker symbol we want trades for.
date – The date/day of the trades to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
timestamp – The timestamp offset, used for pagination. Timestamp is the offset at which to start the results. Using the
timestamp
of the last result as the offset will give you the next page of results. Default: None. I’m trying to think of a good way to implement pagination support for this type of pagination.timestamp_limit – The maximum timestamp allowed in the results. Default: None
reverse – Reverse the order of the results. Default True: oldest first. Make it False for Newest first
limit – Limit the size of the response, max 50000 and default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_quotes(symbol: str, date, timestamp: Optional[int] = None, timestamp_limit: Optional[int] = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False) Union[httpx.Response, dict]
Get Quotes for a given ticker symbol on a specified date. The response from polygon seems to have a
map
attribute which gives a mapping of attribute names to readable values - Async method Official Docs- Parameters
symbol – The ticker symbol we want quotes for.
date – The date/day of the quotes to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
timestamp – The timestamp offset, used for pagination. Timestamp is the offset at which to start the results. Using the
timestamp
of the last result as the offset will give you the next page of results. Default: None. Thinking of a good way to implement this pagination here.timestamp_limit – The maximum timestamp allowed in the results. Default: None
reverse – Reverse the order of the results. Default True: oldest first. Make it False for Newest first
limit – Limit the size of the response, max 50000 and default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_last_trade(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the most recent trade for a given stock - Async method Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_last_quote(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the most recent NBBO (Quote) tick for a given stock - Async method Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_daily_open_close(symbol: str, date, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the OCHLV and after-hours prices of a stock symbol on a certain date - Async method Official Docs
- Parameters
symbol – The ticker symbol we want daily-OCHLV for.
date – The date/day of the daily-OCHLV to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_aggregate_bars(symbol: str, from_date, to_date, adjusted: bool = True, sort='asc', limit: int = 5000, multiplier: int = 1, timespan='day', raw_response: bool = False) Union[httpx.Response, dict]
Get aggregate bars for a stock over a given date range in custom time window sizes. For example, if
timespan = ‘minute’
andmultiplier = ‘5’
then 5-minute bars will be returned - Async method Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
from_date – The start of the aggregate time window. Could be
datetime
ordate
or stringYYYY-MM-DD
to_date – The end of the aggregate time window. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
sort – Sort the results by timestamp. See
polygon.enums.SortOrder
for choices.asc
default.limit – Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000.
multiplier – The size of the timespan multiplier. Must be a positive whole number.
timespan – The size of the time window. See
polygon.enums.Timespan
for choices. defaults today
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the daily OCHLV for the entire stocks/equities markets - Async method Official docs
- Parameters
date – The date to get the data for. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the previous day’s OCHLV for the specified stock ticker - Async method Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_snapshot(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for a single traded stock ticker - Async method Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_current_price(symbol: str) float
get current market price for the ticker symbol specified - Async method
Uses
async_get_last_trade()
under the hood Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
- Returns
The current price. A
KeyError
indicates the request wasn’t successful.
- async async_get_snapshot_all(symbols: list, raw_response: bool = False) Union[httpx.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for all traded stock symbols - Async method Official Docs
- Parameters
symbols – A comma separated list of tickers to get snapshots for.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_gainers_and_losers(direction='gainers', raw_response: bool = False) Union[httpx.Response, dict]
Get the current top 20 gainers or losers of the day in stocks/equities markets - Asnyc method Official Docs
- Parameters
direction – The direction of results. Defaults to gainers. See
polygon.enums.SnapshotDirection
for choicesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
Options Client
- polygon.options.options.build_option_symbol(underlying_symbol: str, expiry, call_or_put, strike_price, prefix_o: bool = False)
Build the option symbol from the details provided.
- Parameters
underlying_symbol – The underlying stock ticker symbol.
expiry – The expiry date for the option. You can pass this argument as
datetime.datetime
ordatetime.date
object. Or a string in format:YYMMDD
. Using datetime objects is recommended.call_or_put – The option type. You can specify:
c
orcall
orp
orput
. Capital letters are also supported.strike_price – The strike price for the option. ALWAYS pass this as one number.
145
,240.5
,15.003
,56
,129.02
are all valid values. It shouldn’t have more than three numbers after decimal point.prefix_o – Whether or not to prefix the symbol with ‘O:’. It is needed by polygon endpoints. However all the library functions will automatically add this prefix if you pass in symbols without this prefix.
- Returns
The option symbol in the format specified by polygon
- polygon.options.options.parse_option_symbol(option_symbol: str, output_format='object', expiry_format='date')
Function to parse an option symbol.
- Parameters
option_symbol – the symbol you want to parse. Both
TSLA211015P125000
andO:TSLA211015P125000
are validoutput_format – Output format of the result. defaults to object. Set it to
dict
orlist
as needed.expiry_format – The format for the expiry date in the results. Defaults to
date
object. change this param tostring
to get the value as a string:YYYY-MM-DD
- Returns
The parsed values either as an object, list or a dict as indicated by
output_format
.
- polygon.options.options.build_option_symbol_for_tda(underlying_symbol: str, expiry, call_or_put, strike_price)
Only use this function if you need to create option symbol for TD ameritrade API. This function is just a bonus.
- Parameters
underlying_symbol – The underlying stock ticker symbol.
expiry – The expiry date for the option. You can pass this argument as
datetime.datetime
ordatetime.date
object. Or a string in format:MMDDYY
. Using datetime objects is recommended.call_or_put – The option type. You can specify:
c
orcall
orp
orput
. Capital letters are also supported.strike_price – The strike price for the option. ALWAYS pass this as one number.
145
,240.5
,15.003
,56
,129.02
are all valid values. It shouldn’t have more than three numbers after decimal point.
- Returns
The option symbol built in the format supported by TD Ameritrade.
- polygon.options.options.parse_option_symbol_from_tda(option_symbol: str, output_format='object', expiry_format='date')
Function to parse an option symbol in format supported by TD Ameritrade.
- Parameters
option_symbol – the symbol you want to parse. Both
TSLA211015P125000
andO:TSLA211015P125000
are validoutput_format – Output format of the result. defaults to object. Set it to
dict
orlist
as needed.expiry_format – The format for the expiry date in the results. Defaults to
date
object. change this param tostring
to get the value as a string:YYYY-MM-DD
- Returns
The parsed values either as an object, list or a dict as indicated by
output_format
.
- class polygon.options.options.OptionSymbol(option_symbol: str, output_format, expiry_format, symbol_format='polygon')
The custom object for parsed details from option symbols.
- __init__(option_symbol: str, output_format, expiry_format, symbol_format='polygon')
Parses the details from symbol and creates attributes for the object.
- Parameters
option_symbol – the symbol you want to parse. Both
TSLA211015P125000
andO:TSLA211015P125000
are validexpiry_format – The format for the expiry date in the results. Defaults to
date
object. change this param tostring
to get the value as a string:YYYY-MM-DD
symbol_format – Which formatting spec to use. Defaults to polygon. also supports
tda
which is the format supported by TD Ameritrade
- class polygon.options.options.OptionsClient(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
This class implements all the Options REST endpoints. Note that you should always import names from top level. eg:
from polygon import OptionsClient
orimport polygon
(which allows you to access all names easily)Creating the client is as simple as:
client = OptionsClient('MY_API_KEY')
Once you have the client, you can call its methods to get data from the APIs. All methods have sane default values and almost everything can be customized.Any method starting with
async_
in its name is meant to be for async programming. All methods have their sync and async counterparts. Any async method must be awaited while non-async (or sync) methods should be called directly.Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.It is also a very good idea to visit the official documentation. I highly recommend using the UI there to play with the endpoints a bit. Observe the data you receive as the actual data received through python lib is exactly the same as shown on their page when you click
Run Query
.- __init__(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
Initiates a Client to be used to access all the endpoints.
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
use_async – Set to True to get an async client. Defaults to False which returns a non-async client.
connect_timeout – The connection timeout in seconds. Defaults to 10. basically the number of seconds to wait for a connection to be established. Raises a
ConnectTimeout
if unable to connect within specified time limit.read_timeout – The read timeout in seconds. Defaults to 10. basically the number of seconds to wait for date to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.
- get_trades(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, sort='timestamp', limit: int = 100, order='asc', raw_response: bool = False)
Get trades for an options ticker symbol in a given time range. Note that you need to have an option symbol in correct format for this endpoint. You can use
polygon.reference_apis.reference_api.ReferenceClient.get_option_contracts()
to query option contracts using many filter parameters such as underlying symbol etc. Official Docs- Parameters
option_symbol – The options ticker symbol to get trades for. for eg
O:TSLA210903C00700000
. you can pass the symbol with or without the prefixO:
timestamp – Query by trade timestamp. You can supply a
date
,datetime
object or ananosecond UNIX timestamp
or a string in format:YYYY-MM-DD
.timestamp_lt – query results where timestamp is less than the supplied value
timestamp_lte – query results where timestamp is less than or equal to the supplied value
timestamp_gt – query results where timestamp is greater than the supplied value
timestamp_gte – query results where timestamp is greater than or equal to the supplied value
sort – Sort field used for ordering. Defaults to timestamp. See
polygon.enums.OptionTradesSort
for available choices.limit – Limit the number of results returned. Defaults to 100. max is 50000.
order – order of the results. Defaults to
asc
. Seepolygon.enums.SortOrder
for info and available choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of
raw_response
. Defaults to Dict.
- get_last_trade(ticker: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the most recent trade for a given options contract. Official Docs
- Parameters
ticker – The ticker symbol of the options contract. Eg:
O:TSLA210903C00700000
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of
raw_response
. Defaults to Dict.
- get_previous_close(ticker: str, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the previous day’s open, high, low, and close (OHLC) for the specified option contract. Official Docs
- Parameters
ticker – The ticker symbol of the options contract. Eg:
O:TSLA210903C00700000
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of
raw_response
. Defaults to Dict.
- async async_get_trades(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, sort='timestamp', limit: int = 100, order='asc', raw_response: bool = False)
Get trades for an options ticker symbol in a given time range. Note that you need to have an option symbol in correct format for this endpoint. You can use
polygon.reference_apis.reference_api.ReferenceClient.async_get_option_contracts()
to query option contracts using many filter parameters such as underlying symbol etc. Official Docs- Parameters
option_symbol – The options ticker symbol to get trades for. for eg
O:TSLA210903C00700000
. you can pass the symbol with or without the prefixO:
timestamp – Query by trade timestamp. You can supply a
date
,datetime
object or ananosecond UNIX timestamp
or a string in format:YYYY-MM-DD
.timestamp_lt – query results where timestamp is less than the supplied value
timestamp_lte – query results where timestamp is less than or equal to the supplied value
timestamp_gt – query results where timestamp is greater than the supplied value
timestamp_gte – query results where timestamp is greater than or equal to the supplied value
sort – Sort field used for ordering. Defaults to timestamp. See
polygon.enums.OptionTradesSort
for available choices.limit – Limit the number of results returned. Defaults to 100. max is 50000.
order – order of the results. Defaults to
asc
. Seepolygon.enums.SortOrder
for info and available choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of
raw_response
. Defaults to Dict.
- async async_get_last_trade(ticker: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the most recent trade for a given options contract - Async Official Docs
- Parameters
ticker – The ticker symbol of the options contract. Eg:
O:TSLA210903C00700000
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of
raw_response
. Defaults to Dict.
- async async_get_previous_close(ticker: str, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the previous day’s open, high, low, and close (OHLC) for the specified option contract - Async Official Docs
- Parameters
ticker – The ticker symbol of the options contract. Eg:
O:TSLA210903C00700000
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
Either a Dictionary or a Response object depending on value of
raw_response
. Defaults to Dict.
- polygon.options.options.ensure_prefix(symbol: str)
Ensure that the option symbol has the prefix
O:
as needed by polygon endpoints. If it does, make no changes. If it doesn’t, add the prefix and return the new value.- Parameters
symbol – the option symbol to check
References Client
- class polygon.reference_apis.reference_api.ReferenceClient(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
This class implements all the References REST endpoints. Note that you should always import names from top level. eg:
from polygon import ReferenceClient
orimport polygon
(which allows you to access all names easily)Creating the client is as simple as:
client = ReferenceClient('MY_API_KEY')
Once you have the client, you can call its methods to get data from the APIs. All methods have sane default values and almost everything can be customized.Any method starting with
async_
in its name is meant to be for async programming. All methods have their sync and async counterparts. Any async method must be awaited while non-async (or sync) methods should be called directly.Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.It is also a very good idea to visit the official documentation. I highly recommend using the UI there to play with the endpoints a bit. Observe the data you receive as the actual data received through python lib is exactly the same as shown on their page when you click
Run Query
.- __init__(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
Initiates a Client to be used to access all the endpoints.
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
use_async – Set to True to get an async client. Defaults to False which returns a non-async client.
connect_timeout – The connection timeout in seconds. Defaults to 10. basically the number of seconds to wait for a connection to be established. Raises a
ConnectTimeout
if unable to connect within specified time limit.read_timeout – The read timeout in seconds. Defaults to 10. basically the number of seconds to wait for date to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.
- get_tickers(symbol: str = '', ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, symbol_type='', market='', exchange: str = '', cusip: Optional[str] = None, cik: str = '', date=None, search: Optional[str] = None, active: bool = True, sort='ticker', order='asc', limit: int = 100, raw_response: bool = False) Union[requests.models.Response, dict]
Query all ticker symbols which are supported by Polygon.io. This API currently includes Stocks/Equities, Crypto, and Forex. Official Docs
- Parameters
symbol – Specify a ticker symbol. Defaults to empty string which queries all tickers.
ticker_lt – Return results where this field is less than the value given
ticker_lte – Return results where this field is less than or equal to the value given
ticker_gt – Return results where this field is greater than the value given
ticker_gte – Return results where this field is greater than or equal to the value given
symbol_type – Specify the type of the tickers. See
polygon.enums.TickerType
for common choices. Find all supported types via the Ticker Types API Defaults to empty string which queries all types.market – Filter by market type. By default all markets are included. See
polygon.enums.TickerMarketType
for available choices.exchange – Specify the primary exchange of the asset in the ISO code format. Find more information about the ISO codes at the ISO org website. Defaults to empty string which queries all exchanges.
cusip – Specify the
CUSIP
code of the asset you want to search for. Find more information about CUSIP codes on their website Defaults to empty string which queries all CUSIPscik – Specify the
CIK
of the asset you want to search for. Find more information about CIK codes at their website Defaults to empty string which queries all CIKs.date – Specify a point in time to retrieve tickers available on that date. Defaults to the most recent available date. Could be
datetime
,date
or a stringYYYY-MM-DD
search – Search for terms within the ticker and/or company name. for eg
MS
will match matching symbolsactive – Specify if the tickers returned should be actively traded on the queried date. Default is True
sort – The field to sort the results on. Default is ticker. If the search query parameter is present, sort is ignored and results are ordered by relevance. See
polygon.enums.TickerSortType
for available choices.order – The order to sort the results on. Default is asc. See
polygon.enums.SortOrder
for available choices.limit – Limit the size of the response, default is 100 and max is 1000.
Pagination
is supported by the pagination function belowraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- static get_ticker_types(*args, **kwargs) None
DEPRECATED! Replaced by
get_ticker_types_v3()
. This method will be removed in a future version from the library.Get a mapping of ticker types to their descriptive names. Official Docs
- get_ticker_types_v3(asset_class=None, locale=None, raw_response: bool = False) Union[requests.models.Response, dict]
Get a mapping of ticker types to their descriptive names. Official Docs
- Parameters
asset_class – Filter by asset class. see
polygon.enums.AssetClass
for choiceslocale – Filter by locale. See
polygon.enums.Locale
for choicesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_ticker_details(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get details for a ticker symbol’s company/entity. This provides a general overview of the entity with information such as name, sector, exchange, logo and similar companies.
This endpoint will be replaced by
get_ticker_details_vx()
in future. Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_ticker_details_vx(symbol: str, date=None, raw_response: bool = False) Union[requests.models.Response, dict]
This API is Experimental and will replace
get_ticker_details()
in future.Get a single ticker supported by Polygon.io. This response will have detailed information about the ticker and the company behind it. Official Docs
- Parameters
symbol – The ticker symbol of the asset.
date – Specify a point in time to get information about the ticker available on that date. When retrieving information from SEC filings, we compare this date with the period of report date on the SEC filing. Defaults to the most recent available date.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_option_contracts(underlying_ticker: Optional[str] = None, ticker: Optional[str] = None, contract_type=None, expiration_date=None, expiration_date_lt=None, expiration_date_lte=None, expiration_date_gt=None, expiration_date_gte=None, order='asc', sort=None, limit=100, raw_response: bool = False) Union[requests.models.Response, dict]
List currently active options contracts Official Docs
- Parameters
underlying_ticker – Query for contracts relating to an underlying stock ticker.
ticker – Query for a contract by option ticker.
contract_type – Query by the type of contract. see
polygon.enums.OptionsContractType
for choicesexpiration_date – Query by contract expiration date. either
datetime
,date
or stringYYYY-MM-DD
expiration_date_lt – expiration date less than given value
expiration_date_lte – expiration date less than equal to given value
expiration_date_gt – expiration_date greater than given value
expiration_date_gte – expiration_date greater than equal to given value
order – Order of results. See
polygon.enums.SortOrder
for choices.sort – Sort field for ordering. See
polygon.enums.OptionsContractsSortType
for choices.limit – Number of results to return
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_ticker_news(symbol: Optional[str] = None, limit: int = 100, order='desc', sort='published_utc', ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, published_utc=None, published_utc_lt=None, published_utc_lte=None, published_utc_gt=None, published_utc_gte=None, raw_response: bool = False) Union[requests.models.Response, dict]
Get the most recent news articles relating to a stock ticker symbol, including a summary of the article and a link to the original source. Official Docs
- Parameters
symbol – To get news mentioning the name given. Defaults to empty string which doesn’t filter tickers
limit – Limit the size of the response, default is 100 and max is 1000. Use pagination helper function for larger responses.
order – Order the results. See
polygon.enums.SortOrder
for choices.sort – The field key to sort. See
polygon.enums.TickerNewsSort
for choices.ticker_lt – Return results where this field is less than the value.
ticker_lte – Return results where this field is less than or equal to the value.
ticker_gt – Return results where this field is greater than the value
ticker_gte – Return results where this field is greater than or equal to the value.
published_utc – A date string
YYYY-MM-DD
ordatetime
for published date time filters.published_utc_lt – Return results where this field is less than the value given
published_utc_lte – Return results where this field is less than or equal to the value given
published_utc_gt – Return results where this field is greater than the value given
published_utc_gte – Return results where this field is greater than or equal to the value given
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_stock_dividends(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get a list of historical dividends for a stock, including the relevant dates and the amount of the dividend. Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_stock_financials(symbol: str, limit: int = 100, report_type=None, sort=None, raw_response: bool = False) Union[requests.models.Response, dict]
Get historical financial data for a stock ticker. This API will be replaced by
get_stock_financials_vx()
in future. Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
limit – Limit the number of results. Defaults to 100
report_type – Specify a type of report to return. see
polygon.enums.StockReportType
for choices. Defaults toNone
sort – The key for sorting the results. see
polygon.enums.StockFinancialsSortType
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_stock_financials_vx(ticker: Optional[str] = None, cik: Optional[str] = None, company_name: Optional[str] = None, company_name_search: Optional[str] = None, sic: Optional[str] = None, filing_date=None, filing_date_lt=None, filing_date_lte=None, filing_date_gt=None, filing_date_gte=None, period_of_report_date=None, period_of_report_date_lt=None, period_of_report_date_lte=None, period_of_report_date_gt=None, period_of_report_date_gte=None, time_frame=None, include_sources: bool = False, order='asc', limit: int = 50, sort='filing_date', raw_response: bool = False)
Get historical financial data for a stock ticker. The financials data is extracted from XBRL from company SEC filings using this methodology Official Docs
This API is experimental and will replace
get_stock_financials()
in future.- Parameters
ticker – Filter query by company ticker.
cik – filter the Query by
central index key (CIK)
Numbercompany_name – filter the query by company name
company_name_search – partial match text search for company names
sic – Query by
standard industrial classification (SIC)
filing_date – Query by the date when the filing with financials data was filed.
datetime/date
or stringYYYY-MM-DD
filing_date_lt – filter for filing date less than given value
filing_date_lte – filter for filing date less than equal to given value
filing_date_gt – filter for filing date greater than given value
filing_date_gte – filter for filing date greater than equal to given value
period_of_report_date – query by The period of report for the filing with financials data.
datetime/date
or string in format:YYY-MM-DD
.period_of_report_date_lt – filter for period of report date less than given value
period_of_report_date_lte – filter for period of report date less than equal to given value
period_of_report_date_gt – filter for period of report date greater than given value
period_of_report_date_gte – filter for period of report date greater than equal to given value
time_frame – Query by timeframe. Annual financials originate from 10-K filings, and quarterly financials originate from 10-Q filings. Note: Most companies do not file quarterly reports for Q4 and instead include those financials in their annual report, so some companies my not return quarterly financials for Q4. See
polygon.enums.StockFinancialsTimeframe
for choices.include_sources – Whether or not to include the xpath and formula attributes for each financial data point. See the xpath and formula response attributes for more info.
False
by defaultorder – Order results based on the sort field. ‘asc’ by default. See
polygon.enums.SortOrder
for choices.limit – number of max results to obtain. defaults to 50.
sort – Sort field key used for ordering. ‘filing_date’ default. see
polygon.enums.StockFinancialsSortKey
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_stock_splits(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get a list of historical stock splits for a ticker symbol, including the execution and payment dates of the stock split, and the split ratio. Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_market_holidays(raw_response: bool = False) Union[requests.models.Response, dict]
Get upcoming market holidays and their open/close times. Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_market_status(raw_response: bool = False) Union[requests.models.Response, dict]
Get the current trading status of the exchanges and overall financial markets. Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_condition_mappings(tick_type='trades', raw_response: bool = False) Union[requests.models.Response, dict]
Get a unified numerical mapping for conditions on trades and quotes. Each feed/exchange uses its own set of codes to identify conditions, so the same condition may have a different code depending on the originator of the data. Polygon.io defines its own mapping to allow for uniformly identifying a condition across feeds/exchanges. Official Docs
- Parameters
tick_type – The type of ticks to return mappings for. Defaults to ‘trades’. See
polygon.enums.ConditionMappingTickType
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_conditions(asset_class=None, data_type=None, id=None, sip=None, order=None, limit: int = 50, sort='name', raw_response: bool = False)
List all conditions that Polygon.io uses. Official Docs
- Parameters
asset_class – Filter for conditions within a given asset class. See
polygon.enums.AssetClass
for choices. Defaults to all assets.data_type – Filter by data type. See
polygon.enums.ConditionsDataType
for choices. defaults to all.id – Filter for conditions with a given ID
sip – Filter by SIP. If the condition contains a mapping for that SIP, the condition will be returned.
order – Order results. See
polygon.enums.SortOrder
for choices.limit – limit the number of results. defaults to 50.
sort – Sort field used for ordering. Defaults to ‘name’. See
polygon.enums.ConditionsSortKey
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_exchanges(asset_class=None, locale=None, raw_response: bool = False)
List all exchanges that Polygon.io knows about. Official Docs
- Parameters
asset_class – filter by asset class. See
polygon.enums.AssetClass
for choices.locale – Filter by locale name. See
polygon.enums.Locale
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- static get_stock_exchanges(*args, **kwargs)
DEPRECATED! Replaced by
get_exchanges()
. This method will be removed in a future version from the library
- static get_crypto_exchanges(*args, **kwargs)
DEPRECATED! Replaced by
get_exchanges()
. This method will be removed in a future version from the library
- get_locales(raw_response: bool = False) Union[requests.models.Response, dict]
Get a list of locales currently supported by Polygon.io. Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_markets(raw_response: bool = False) Union[requests.models.Response, dict]
Get a list of markets that are currently supported by Polygon.io. Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_tickers(symbol: str = '', ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, symbol_type='', market='', exchange: str = '', cusip: Optional[str] = None, cik: str = '', date: Optional[Union[str, datetime.date, datetime.datetime]] = None, search: Optional[str] = None, active: bool = True, sort='ticker', order: str = 'asc', limit: int = 100, raw_response: bool = False) Union[httpx.Response, dict]
Query all ticker symbols which are supported by Polygon.io. This API currently includes Stocks/Equities, Crypto, and Forex - Assync method Official Docs
- Parameters
symbol – Specify a ticker symbol. Defaults to empty string which queries all tickers.
ticker_lt – Return results where this field is less than the value given
ticker_lte – Return results where this field is less than or equal to the value given
ticker_gt – Return results where this field is greater than the value given
ticker_gte – Return results where this field is greater than or equal to the value given
symbol_type – Specify the type of the tickers. See
polygon.enums.TickerType
for common choices. Find all supported types via the Ticker Types API Defaults to empty string which queries all types.market – Filter by market type. By default all markets are included. See
polygon.enums.TickerMarketType
for available choices.exchange – Specify the primary exchange of the asset in the ISO code format. Find more information about the ISO codes at the ISO org website. Defaults to empty string which queries all exchanges.
cusip – Specify the
CUSIP
code of the asset you want to search for. Find more information about CUSIP codes on their website Defaults to empty string which queries all CUSIPscik – Specify the
CIK
of the asset you want to search for. Find more information about CIK codes at their website Defaults to empty string which queries all CIKs.date – Specify a point in time to retrieve tickers available on that date. Defaults to the most recent available date. Could be
datetime
,date
or a stringYYYY-MM-DD
search – Search for terms within the ticker and/or company name. for eg
MS
will match matching symbolsactive – Specify if the tickers returned should be actively traded on the queried date. Default is True
sort – The field to sort the results on. Default is ticker. If the search query parameter is present, sort is ignored and results are ordered by relevance. See
polygon.enums.TickerSortType
for available choices.order – The order to sort the results on. Default is asc. See
polygon.enums.SortOrder
for available choices.limit – Limit the size of the response, default is 100 and max is 1000.
Pagination
is supported by the pagination function belowraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async static async_get_ticker_types(*args, **kwargs) None
DEPRECATED! Replaced by
async_get_ticker_types_v3()
. This method will be removed in a future version from the library.Get a mapping of ticker types to their descriptive names. Official Docs
- async async_get_ticker_types_v3(asset_class=None, locale=None, raw_response: bool = False) Union[httpx.Response, dict]
Get a mapping of ticker types to their descriptive names - Async method Official Docs
- Parameters
asset_class – Filter by asset class. see
polygon.enums.AssetClass
for choiceslocale – Filter by locale. See
polygon.enums.Locale
for choicesraw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_ticker_details(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get details for a ticker symbol’s company/entity. This provides a general overview of the entity with information such as name, sector, exchange, logo and similar companies - Async method
This endpoint will be replaced by
async_get_ticker_details_vx()
in future. Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_ticker_details_vx(symbol: str, date=None, raw_response: bool = False) Union[httpx.Response, dict]
This API is Experimental and will replace
async_get_ticker_details()
in future - Async methodGet a single ticker supported by Polygon.io. This response will have detailed information about the ticker and the company behind it. Official Docs
- Parameters
symbol – The ticker symbol of the asset.
date – Specify a point in time to get information about the ticker available on that date. When retrieving information from SEC filings, we compare this date with the period of report date on the SEC filing. Defaults to the most recent available date.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_option_contracts(underlying_ticker: Optional[str] = None, ticker: Optional[str] = None, contract_type=None, expiration_date=None, expiration_date_lt=None, expiration_date_lte=None, expiration_date_gt=None, expiration_date_gte=None, order='asc', sort=None, limit: int = 50, raw_response: bool = False) Union[httpx.Response, dict]
List currently active options contracts - Async method Official Docs
- Parameters
underlying_ticker – Query for contracts relating to an underlying stock ticker.
ticker – Query for a contract by option ticker.
contract_type – Query by the type of contract. see
polygon.enums.OptionsContractType
for choicesexpiration_date – Query by contract expiration date. either
datetime
,date
or stringYYYY-MM-DD
expiration_date_lt – expiration date less than given value
expiration_date_lte – expiration date less than equal to given value
expiration_date_gt – expiration_date greater than given value
expiration_date_gte – expiration_date greater than equal to given value
order – Order of results. See
polygon.enums.SortOrder
for choices.sort – Sort field for ordering. See
polygon.enums.OptionsContractsSortType
for choices.limit – Number of results to return
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_ticker_news(symbol: Optional[str] = None, limit: int = 100, order='desc', sort='published_utc', ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, published_utc=None, published_utc_lt=None, published_utc_lte=None, published_utc_gt=None, published_utc_gte=None, raw_response: bool = False) Union[httpx.Response, dict]
Get the most recent news articles relating to a stock ticker symbol, including a summary of the article and a link to the original source - Async method Official Docs
- Parameters
symbol – To get news mentioning the name given. Defaults to empty string which doesn’t filter tickers
limit – Limit the size of the response, default is 100 and max is 1000. Use pagination helper function for larger responses.
order – Order the results. See
polygon.enums.SortOrder
for choices.sort – The field key to sort. See
polygon.enums.TickerNewsSort
for choices.ticker_lt – Return results where this field is less than the value.
ticker_lte – Return results where this field is less than or equal to the value.
ticker_gt – Return results where this field is greater than the value
ticker_gte – Return results where this field is greater than or equal to the value.
published_utc – A date string
YYYY-MM-DD
ordatetime
for published date time filters.published_utc_lt – Return results where this field is less than the value given
published_utc_lte – Return results where this field is less than or equal to the value given
published_utc_gt – Return results where this field is greater than the value given
published_utc_gte – Return results where this field is greater than or equal to the value given
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_stock_dividends(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get a list of historical dividends for a stock, including the relevant dates and the amount of the dividend - Async method Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_stock_financials(symbol: str, limit: int = 100, report_type=None, sort=None, raw_response: bool = False) Union[httpx.Response, dict]
Get historical financial data for a stock ticker. This API will be replaced by
async_get_stock_financials_vx()
in future - Async method Official Docs- Parameters
symbol – The ticker symbol of the stock/equity.
limit – Limit the number of results. Defaults to 100
report_type – Specify a type of report to return. see
polygon.enums.StockReportType
for choices. Defaults toNone
sort – The key for sorting the results. see
polygon.enums.StockFinancialsSortType
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_stock_financials_vx(ticker: Optional[str] = None, cik: Optional[str] = None, company_name: Optional[str] = None, company_name_search: Optional[str] = None, sic: Optional[str] = None, filing_date=None, filing_date_lt=None, filing_date_lte=None, filing_date_gt=None, filing_date_gte=None, period_of_report_date=None, period_of_report_date_lt=None, period_of_report_date_lte=None, period_of_report_date_gt=None, period_of_report_date_gte=None, time_frame=None, include_sources: bool = False, order='asc', limit: int = 50, sort='filing_date', raw_response: bool = False)
Get historical financial data for a stock ticker. The financials data is extracted from XBRL from company SEC filings using this methodology - Async method Official Docs
This API is experimental and will replace
async_get_stock_financials()
in future.- Parameters
ticker – Filter query by company ticker.
cik – filter the Query by
central index key (CIK)
Numbercompany_name – filter the query by company name
company_name_search – partial match text search for company names
sic – Query by
standard industrial classification (SIC)
filing_date – Query by the date when the filing with financials data was filed.
datetime/date
or stringYYYY-MM-DD
filing_date_lt – filter for filing date less than given value
filing_date_lte – filter for filing date less than equal to given value
filing_date_gt – filter for filing date greater than given value
filing_date_gte – filter for filing date greater than equal to given value
period_of_report_date – query by The period of report for the filing with financials data.
datetime/date
or string in format:YYY-MM-DD
.period_of_report_date_lt – filter for period of report date less than given value
period_of_report_date_lte – filter for period of report date less than equal to given value
period_of_report_date_gt – filter for period of report date greater than given value
period_of_report_date_gte – filter for period of report date greater than equal to given value
time_frame – Query by timeframe. Annual financials originate from 10-K filings, and quarterly financials originate from 10-Q filings. Note: Most companies do not file quarterly reports for Q4 and instead include those financials in their annual report, so some companies my not return quarterly financials for Q4. See
polygon.enums.StockFinancialsTimeframe
for choices.include_sources – Whether or not to include the xpath and formula attributes for each financial data point. See the xpath and formula response attributes for more info.
False
by defaultorder – Order results based on the sort field. ‘asc’ by default. See
polygon.enums.SortOrder
for choices.limit – number of max results to obtain. defaults to 50.
sort – Sort field key used for ordering. ‘filing_date’ default. see
polygon.enums.StockFinancialsSortKey
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_stock_splits(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get a list of historical stock splits for a ticker symbol, including the execution and payment dates of the stock split, and the split ratio - Async method Official Docs
- Parameters
symbol – The ticker symbol of the stock/equity.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_market_holidays(raw_response: bool = False) Union[httpx.Response, dict]
Get upcoming market holidays and their open/close times - Async method Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_market_status(raw_response: bool = False) Union[httpx.Response, dict]
Get the current trading status of the exchanges and overall financial markets - Async method Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_condition_mappings(tick_type='trades', raw_response: bool = False) Union[httpx.Response, dict]
Get a unified numerical mapping for conditions on trades and quotes. Each feed/exchange uses its own set of codes to identify conditions, so the same condition may have a different code depending on the originator of the data. Polygon.io defines its own mapping to allow for uniformly identifying a condition across feeds/exchanges - Async method Official Docs
- Parameters
tick_type – The type of ticks to return mappings for. Defaults to ‘trades’. See
polygon.enums.ConditionMappingTickType
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_conditions(asset_class=None, data_type=None, id=None, sip=None, order=None, limit: int = 50, sort='name', raw_response: bool = False)
List all conditions that Polygon.io uses - Async method Official Docs
- Parameters
asset_class – Filter for conditions within a given asset class. See
polygon.enums.AssetClass
for choices. Defaults to all assets.data_type – Filter by data type. See
polygon.enums.ConditionsDataType
for choices. defaults to all.id – Filter for conditions with a given ID
sip – Filter by SIP. If the condition contains a mapping for that SIP, the condition will be returned.
order – Order results. See
polygon.enums.SortOrder
for choices.limit – limit the number of results. defaults to 50.
sort – Sort field used for ordering. Defaults to ‘name’. See
polygon.enums.ConditionsSortKey
for choices.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_exchanges(asset_class=None, locale=None, raw_response: bool = False)
List all exchanges that Polygon.io knows about - Async method Official Docs
- Parameters
asset_class – filter by asset class. See
polygon.enums.AssetClass
for choices.locale – Filter by locale name. See
polygon.enums.Locale
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async static async_get_stock_exchanges(**kwargs)
DEPRECATED! Replaced by
async_get_exchanges()
. This method will be removed in a future version from the library
- async static async_get_crypto_exchanges(**kwargs)
DEPRECATED! Replaced by
async_get_exchanges()
. This method will be removed in a future version from the library
- async async_get_locales(raw_response: bool = False) Union[httpx.Response, dict]
Get a list of locales currently supported by Polygon.io - Async method Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_markets(raw_response: bool = False) Union[httpx.Response, dict]
Get a list of markets that are currently supported by Polygon.io - Async method Official Docs
- Parameters
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
Forex Client
- class polygon.forex.forex_api.ForexClient(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
This class implements all the Forex REST endpoints. Note that you should always import names from top level. eg:
from polygon import ForexClient
orimport polygon
(which allows you to access all names easily)Creating the client is as simple as:
client = ForexClient('MY_API_KEY')
Once you have the client, you can call its methods to get data from the APIs. All methods have sane default values and almost everything can be customized.Any method starting with
async_
in its name is meant to be for async programming. All methods have their sync and async counterparts. Any async method must be awaited while non-async (or sync) methods should be called directly.Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.It is also a very good idea to visit the official documentation. I highly recommend using the UI there to play with the endpoints a bit. Observe the data you receive as the actual data received through python lib is exactly the same as shown on their page when you click
Run Query
.- __init__(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
Initiates a Client to be used to access all the endpoints.
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
use_async – Set to True to get an async client. Defaults to False which returns a non-async client.
connect_timeout – The connection timeout in seconds. Defaults to 10. basically the number of seconds to wait for a connection to be established. Raises a
ConnectTimeout
if unable to connect within specified time limit.read_timeout – The read timeout in seconds. Defaults to 10. basically the number of seconds to wait for date to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.
- get_historic_forex_ticks(from_symbol: str, to_symbol: str, date, offset: Optional[Union[str, int]] = None, limit: int = 500, raw_response: bool = False) Union[requests.models.Response, dict]
Get historic trade ticks for a forex currency pair. Official Docs
- Parameters
from_symbol – The “from” symbol of the forex currency pair.
to_symbol – The “to” symbol of the forex currency pair.
date – The date/day of the historic ticks to retrieve. Could be
datetime
,date
or stringYYYY-MM-DD
offset – The timestamp offset, used for pagination. This is the offset at which to start the results. Using the timestamp of the last result as the offset will give you the next page of results. I’m thinking about a good way to implement this type of pagination in the lib which doesn’t have a
next_url
in the response attributes.limit – Limit the size of the response, max 10000. Default 500
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_last_quote(from_symbol: str, to_symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the last trade tick for a forex currency pair. Official Docs
- Parameters
from_symbol – The “from” symbol of the forex currency pair.
to_symbol – The “to” symbol of the forex currency pair.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='day', adjusted: bool = True, sort='asc', limit: int = 5000, raw_response: bool = False) Union[requests.models.Response, dict]
Get aggregate bars for a forex pair over a given date range in custom time window sizes. For example, if
timespan = ‘minute’
andmultiplier = ‘5’
then5-minute
bars will be returned. Official Docs- Parameters
symbol – The ticker symbol of the forex pair. eg:
C:EURUSD
. You can supply with or without prefixC:
from_date – The start of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
to_date – The end of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
multiplier – The size of the timespan multiplier
timespan – The size of the time window. Defaults to day candles. see
polygon.enums.Timespan
for choicesadjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
sort – Sort the results by timestamp. see
polygon.enums.SortOrder
for available choices. Defaults toasc
which is oldest at the top.limit – Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the daily open, high, low, and close (OHLC) for the entire forex markets. Official Docs
- Parameters
date – The date for the aggregate window. Could be
datetime
,date
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the previous day’s open, high, low, and close (OHLC) for the specified forex pair. Official Docs
- Parameters
symbol – The ticker symbol of the forex pair.
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_snapshot_all(symbols: list, raw_response: bool = False) Union[requests.models.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for all traded forex symbols Official Docs
- Parameters
symbols – A list of tickers to get snapshots for.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_snapshot(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for a single traded forex symbol. Official Docs
- Parameters
symbol – Symbol of the forex pair. eg:
C:EURUSD
. You can supply with or without prefixC:
.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_gainers_and_losers(direction='gainers', raw_response: bool = False) Union[requests.models.Response, dict]
Get the current top 20 gainers or losers of the day in forex markets. Official docs
- Parameters
direction – The direction of the snapshot results to return. See
polygon.enums.SnapshotDirection
for available choices. Defaults to Gainers.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- real_time_currency_conversion(from_symbol: str, to_symbol: str, amount: float, precision: int = 2, raw_response: bool = False) Union[requests.models.Response, dict]
Get currency conversions using the latest market conversion rates. Note than you can convert in both directions. For example USD to CAD or CAD to USD. Official Docs
- Parameters
from_symbol – The “from” symbol of the pair.
to_symbol – The “to” symbol of the pair.
amount – The amount to convert,
precision – The decimal precision of the conversion. Defaults to 2 which is 2 decimal places accuracy.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_historic_forex_ticks(from_symbol: str, to_symbol: str, date, offset: Optional[Union[str, int]] = None, limit: int = 500, raw_response: bool = False) Union[httpx.Response, dict]
Get historic trade ticks for a forex currency pair - Async method. Official Docs
- Parameters
from_symbol – The “from” symbol of the forex currency pair.
to_symbol – The “to” symbol of the forex currency pair.
date – The date/day of the historic ticks to retrieve. Could be
datetime
,date
or stringYYYY-MM-DD
offset – The timestamp offset, used for pagination. This is the offset at which to start the results. Using the timestamp of the last result as the offset will give you the next page of results. I’m thinking about a good way to implement this type of pagination in the lib which doesn’t have a
next_url
in the response attributes.limit – Limit the size of the response, max 10000. Default 500
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_last_quote(from_symbol: str, to_symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the last trade tick for a forex currency pair - Async method Official Docs
- Parameters
from_symbol – The “from” symbol of the forex currency pair.
to_symbol – The “to” symbol of the forex currency pair.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='day', adjusted: bool = True, sort='asc', limit: int = 5000, raw_response: bool = False) Union[httpx.Response, dict]
Get aggregate bars for a forex pair over a given date range in custom time window sizes. For example, if
timespan = ‘minute’
andmultiplier = ‘5’
then5-minute
bars will be returned. Official Docs- Parameters
symbol – The ticker symbol of the forex pair. eg:
C:EURUSD
. You can supply with or without prefixC:
from_date – The start of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
to_date – The end of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
multiplier – The size of the timespan multiplier
timespan – The size of the time window. Defaults to day candles. see
polygon.enums.Timespan
for choicesadjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
sort – Sort the results by timestamp. see
polygon.enums.SortOrder
for available choices. Defaults toasc
which is oldest at the top.limit – Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the daily open, high, low, and close (OHLC) for the entire forex markets - Async method Official Docs
- Parameters
date – The date for the aggregate window. Could be
datetime
,date
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the previous day’s open, high, low, and close (OHLC) for the specified forex pair - Async method Official Docs
- Parameters
symbol – The ticker symbol of the forex pair.
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_snapshot_all(symbols: list, raw_response: bool = False) Union[httpx.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for all traded forex symbols - Async method Official Docs
- Parameters
symbols – A list of tickers to get snapshots for.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_snapshot(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for a single traded forex symbol - Async method Official Docs
- Parameters
symbol – Symbol of the forex pair. eg:
C:EURUSD
. You can supply with or without prefixC:
.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_gainers_and_losers(direction='gainers', raw_response: bool = False) Union[httpx.Response, dict]
Get the current top 20 gainers or losers of the day in forex markets. Official docs
- Parameters
direction – The direction of the snapshot results to return. See
polygon.enums.SnapshotDirection
for available choices. Defaults to Gainers.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_real_time_currency_conversion(from_symbol: str, to_symbol: str, amount: float, precision: int = 2, raw_response: bool = False) Union[httpx.Response, dict]
Get currency conversions using the latest market conversion rates. Note than you can convert in both directions. For example USD to CAD or CAD to USD - Async method Official Docs
- Parameters
from_symbol – The “from” symbol of the pair.
to_symbol – The “to” symbol of the pair.
amount – The amount to convert,
precision – The decimal precision of the conversion. Defaults to 2 which is 2 decimal places accuracy.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
Crypto Client
- class polygon.crypto.crypto_api.CryptoClient(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
This class implements all the crypto REST endpoints. Note that you should always import names from top level. eg:
from polygon import CryptoClient
orimport polygon
(which allows you to access all names easily)Creating the client is as simple as:
client = CryptoClient('MY_API_KEY')
Once you have the client, you can call its methods to get data from the APIs. All methods have sane default values and almost everything can be customized.Any method starting with
async_
in its name is meant to be for async programming. All methods have their sync and async counterparts. Any async method must be awaited while non-async (or sync) methods should be called directly.Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.It is also a very good idea to visit the official documentation. I highly recommend using the UI there to play with the endpoints a bit. Observe the data you receive as the actual data received through python lib is exactly the same as shown on their page when you click
Run Query
.- __init__(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10)
Initiates a Client to be used to access all the endpoints.
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
use_async – Set to True to get an async client. Defaults to False which returns a non-async client.
connect_timeout – The connection timeout in seconds. Defaults to 10. basically the number of seconds to wait for a connection to be established. Raises a
ConnectTimeout
if unable to connect within specified time limit.read_timeout – The read timeout in seconds. Defaults to 10. basically the number of seconds to wait for date to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.
- get_historic_trades(from_symbol: str, to_symbol: str, date, offset: Optional[Union[str, int]] = None, limit: int = 500, raw_response: bool = False) Union[requests.models.Response, dict]
Get historic trade ticks for a cryptocurrency pair. Official Docs
- Parameters
from_symbol – The “from” symbol of the crypto pair.
to_symbol – The “to” symbol of the crypto pair.
date – The date/day of the historic ticks to retrieve. Could be
datetime
,date
or stringYYYY-MM-DD
offset – The timestamp offset, used for pagination. This is the offset at which to start the results. Using the timestamp of the last result as the offset will give you the next page of results. I’m trying to think of a good way to implement pagination in the library for these endpoints which do not return a
next_url
attribute.limit – Limit the size of the response, max 10000. Default 500
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_last_trade(from_symbol: str, to_symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the last trade tick for a cryptocurrency pair. Official Docs
- Parameters
from_symbol – The “from” symbol of the pair.
to_symbol – The “to” symbol of the pair.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_daily_open_close(from_symbol: str, to_symbol: str, date, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the open, close prices of a cryptocurrency symbol on a certain day. Official Docs:
- Parameters
from_symbol – The “from” symbol of the pair.
to_symbol – The “to” symbol of the pair.
date – The date of the requested open/close. Could be
datetime
,date
or stringYYYY-MM-DD
.adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='day', adjusted: bool = True, sort='asc', limit: int = 5000, raw_response: bool = False) Union[requests.models.Response, dict]
Get aggregate bars for a cryptocurrency pair over a given date range in custom time window sizes. For example, if
timespan=‘minute’
andmultiplier=‘5’
then 5-minute bars will be returned. Official Docs- Parameters
symbol – The ticker symbol of the currency pair. eg:
X:BTCUSD
. You can specify with or without prefixX:
from_date – The start of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
to_date – The end of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
multiplier – The size of the timespan multiplier
timespan – The size of the time window. Defaults to day candles. see
polygon.enums.Timespan
for choicesadjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
sort – Order of sorting the results. See
polygon.enums.SortOrder
for available choices. Defaults toasc
(oldest at the top)limit – Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the daily open, high, low, and close (OHLC) for the entire cryptocurrency market. Official Docs
- Parameters
date – The date for the aggregate window. Could be
datetime
,date
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False) Union[requests.models.Response, dict]
Get the previous day’s open, high, low, and close (OHLC) for the specified cryptocurrency pair. Official Docs
- Parameters
symbol – The ticker symbol of the currency pair. eg:
X:BTCUSD
. You can specify with or without the prefixX:
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_snapshot_all(symbols: list, raw_response: bool = False) Union[requests.models.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for all traded cryptocurrency symbols Official Docs
- Parameters
symbols – A list of tickers to get snapshots for.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_snapshot(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for a single traded cryptocurrency symbol. Official Docs
- Parameters
symbol – Symbol of the currency pair. eg:
X:BTCUSD
. you can specify with or without prefixX:
raw_response – Whether or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_gainers_and_losers(direction='gainers', raw_response: bool = False) Union[requests.models.Response, dict]
Get the current top 20 gainers or losers of the day in cryptocurrency markets. Official docs
- Parameters
direction – The direction of the snapshot results to return. See
polygon.enums.SnapshotDirection
for available choices. Defaults to Gainers.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- get_level2_book(symbol: str, raw_response: bool = False) Union[requests.models.Response, dict]
Get the current level 2 book of a single ticker. This is the combined book from all of the exchanges. Official Docs
- Parameters
symbol – The cryptocurrency ticker. eg:
X:BTCUSD
. You can specify with or without the prefix`X:
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_historic_trades(from_symbol: str, to_symbol: str, date, offset: Optional[Union[str, int]] = None, limit: int = 500, raw_response: bool = False) Union[httpx.Response, dict]
Get historic trade ticks for a cryptocurrency pair - Async method. Official Docs
- Parameters
from_symbol – The “from” symbol of the crypto pair.
to_symbol – The “to” symbol of the crypto pair.
date – The date/day of the historic ticks to retrieve. Could be
datetime
,date
or stringYYYY-MM-DD
offset – The timestamp offset, used for pagination. This is the offset at which to start the results. Using the timestamp of the last result as the offset will give you the next page of results. I’m trying to think of a good way to implement pagination in the library for these endpoints which do not return a
next_url
attribute.limit – Limit the size of the response, max 10000. Default 500
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_last_trade(from_symbol: str, to_symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the last trade tick for a cryptocurrency pair - Async method Official Docs
- Parameters
from_symbol – The “from” symbol of the pair.
to_symbol – The “to” symbol of the pair.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_daily_open_close(from_symbol: str, to_symbol: str, date, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the open, close prices of a cryptocurrency symbol on a certain day - Async method Official Docs:
- Parameters
from_symbol – The “from” symbol of the pair.
to_symbol – The “to” symbol of the pair.
date – The date of the requested open/close. Could be
datetime
,date
or stringYYYY-MM-DD
.adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='day', adjusted: bool = True, sort='asc', limit: int = 5000, raw_response: bool = False) Union[httpx.Response, dict]
et aggregate bars for a cryptocurrency pair over a given date range in custom time window sizes. For example, if
timespan=‘minute’
andmultiplier=‘5’
then 5-minute bars will be returned - Async method Official Docs- Parameters
symbol – The ticker symbol of the currency pair. eg:
X:BTCUSD
. You can specify with or without prefixX:
from_date – The start of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
to_date – The end of the aggregate time window. Could be
datetime
,date
or stringYYYY-MM-DD
multiplier – The size of the timespan multiplier
timespan – The size of the time window. Defaults to day candles. see
polygon.enums.Timespan
for choicesadjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
sort – Order of sorting the results. See
polygon.enums.SortOrder
for available choices. Defaults toasc
(oldest at the top)limit – Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the daily open, high, low, and close (OHLC) for the entire cryptocurrency market - Async method Official Docs
- Parameters
date – The date for the aggregate window. Could be
datetime
,date
or stringYYYY-MM-DD
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False) Union[httpx.Response, dict]
Get the previous day’s open, high, low, and close (OHLC) for the specified cryptocurrency pair - Async method Official Docs
- Parameters
symbol – The ticker symbol of the currency pair. eg:
X:BTCUSD
. You can specify with or without the prefixX:
adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to False to get results that are NOT adjusted for splits.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_snapshot_all(symbols: list, raw_response: bool = False) Union[httpx.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for all traded cryptocurrency symbols - Async method Official Docs
- Parameters
symbols – A list of tickers to get snapshots for.
raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_snapshot(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the current minute, day, and previous day’s aggregate, as well as the last trade and quote for a single traded cryptocurrency symbol - Async method Official Docs
- Parameters
symbol – Symbol of the currency pair. eg:
X:BTCUSD
. you can specify with or without prefixX:
raw_response – Whether or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_gainers_and_losers(direction='gainers', raw_response: bool = False) Union[httpx.Response, dict]
Get the current top 20 gainers or losers of the day in cryptocurrency markets - Async method Official docs
- Parameters
direction – The direction of the snapshot results to return. See
polygon.enums.SnapshotDirection
for available choices. Defaults to Gainers.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
- async async_get_level2_book(symbol: str, raw_response: bool = False) Union[httpx.Response, dict]
Get the current level 2 book of a single ticker. combined book from all of the exchanges - Async method Official Docs
- Parameters
symbol – The cryptocurrency ticker. eg:
X:BTCUSD
. You can specify with or without the prefix`X:
.raw_response – Whether or not to return the
Response
Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.
- Returns
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object
Callback Streamer Client (Sync)
- class polygon.streaming.streaming.StreamClient(api_key: str, cluster, host='socket.polygon.io', on_message=None, on_close=None, on_error=None, enable_connection_logs: bool = False)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
Note that this is callback based stream client which is suitable for threaded/multi-processed applications. If you need to stream using an
asyncio
based stream client, see Async Streamer Client.This class implements all the websocket endpoints. Note that you should always import names from top level. eg:
from polygon import StreamClient
orimport polygon
(which allows you to access all names easily)Creating the client is as simple as:
client = StreamClient('MY_API_KEY', 'other_options')
Once you have the client, you can call its methods to subscribe/unsubscribe to streams, change handlers and process messages. All methods have sane default values and almost everything can be customized.
Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.Take a look at the Official documentation to get an idea of the stream, data formatting for messages and related useful stuff.
- __init__(api_key: str, cluster, host='socket.polygon.io', on_message=None, on_close=None, on_error=None, enable_connection_logs: bool = False)
Initializes the callback function based stream client Official Docs
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
cluster – Which market/cluster to connect to. See
polygon.enums.StreamCluster
for choices. NEVER connect to the same cluster again if there is an existing stream connected to it. The existing connection would be dropped and new one will be established. You can have up to 4 concurrent streams connected to 4 different clusters.host – Host url to connect to. Default is real time. See
polygon.enums.StreamHost
for choices.on_message – The function to be called when data is received. This is primary function you’ll write to process the data from the stream. The function should accept one and only one
arg
(message). Default handler is_default_on_msg()
.on_close – The function to be called when stream is closed. Function should accept two args ( close_status_code, close_message). Default handler is
_default_on_close()
on_error – Function to be called when an error is encountered. Function should accept one arg ( exception object). Default handler is
_default_on_error()
enable_connection_logs – Whether or not to print debug info related to the stream connection. Helpful for debugging.
- _start_stream(ping_interval: int = 21, ping_timeout: int = 20, ping_payload: str = '', skip_utf8_validation: bool = True)
Starts the Stream Event Loop. The loop is infinite and will continue to run until the stream is terminated, either manually or due to an exception. This method is for internal use only. you should always use
start_stream_thread()
to start the stream.- Parameters
ping_interval – client would send a
ping
every specified number of seconds to server to keep connection alive. Set to 0 to disable pinging. Defaults to 21 secondsping_timeout – Timeout in seconds if a
pong
(response to ping from server) is not received. The Stream is terminated as it is considered to be dead if no pong is received within the specified timeout. default: 20 secondsping_payload – The option message to be sent with the ping. Better to leave it empty string.
skip_utf8_validation – Whether to skip utf validation of messages. Defaults to True. Setting it to False may result in performance downgrade
- Returns
None
- start_stream_thread(ping_interval: int = 21, ping_timeout: int = 20, ping_payload: str = '', skip_utf8_validation: bool = True)
Starts the Stream. This will not block the main thread and it spawns the streamer in its own thread.
- Parameters
ping_interval – client would send a
ping
every specified number of seconds to server to keep connection alive. Set to 0 to disable pinging. Defaults to 21 secondsping_timeout – Timeout in seconds if a
pong
(response to ping from server) is not received. The Stream is terminated as it is considered to be dead if no pong is received within the specified timeout. default: 20 secondsping_payload – The option message to be sent with the ping. Better to leave it empty string.
skip_utf8_validation – Whether to skip utf validation of messages. Defaults to True. Setting it to False may result in performance downgrade
- Returns
None
- close_stream(*args, **kwargs)
Close the websocket connection. Wait for thread to finish if running.
- _authenticate()
Authenticates the client with the server using API key. Internal function, not meant to be called directly by users.
- Returns
None
- _modify_sub(symbols=None, action='subscribe', _prefix='T.')
Internal Function to send subscribe or unsubscribe requests to websocket. You should prefer using the corresponding methods to subscribe or unsubscribe to streams.
- Parameters
symbols – The list of symbols to apply the actions to.
action – Defaults to subscribe which subscribes to requested stream. Change to unsubscribe to remove an existing subscription.
_prefix – prefix of the stream service. See
polygon.enums.StreamServicePrefix
for choices.
- Returns
None
- subscribe_stock_trades(symbols: Optional[list] = None)
Stream real-time trades for given stock ticker symbol(s).
- Parameters
symbols – A list of tickers. Default is
*
which subscribes to ALL tickers in the market- Returns
None
- unsubscribe_stock_trades(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_quotes(symbols: Optional[list] = None)
Stream real-time Quotes for given stock ticker symbol(s).
- Parameters
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
- Returns
None
- unsubscribe_stock_quotes(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_minute_aggregates(symbols: Optional[list] = None)
Stream real-time minute aggregates for given stock ticker symbol(s).
- Parameters
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
- Returns
None
- unsubscribe_stock_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_second_aggregates(symbols: Optional[list] = None)
Stream real-time second aggregates for given stock ticker symbol(s).
- Parameters
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
- Returns
None
- unsubscribe_stock_second_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_limit_up_limit_down(symbols: Optional[list] = None)
Stream real-time LULD events for given stock ticker symbol(s).
- Parameters
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
- Returns
None
- unsubscribe_stock_limit_up_limit_down(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_imbalances(symbols: Optional[list] = None)
Stream real-time Imbalance Events for given stock ticker symbol(s).
- Parameters
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
- Returns
None
- unsubscribe_stock_imbalances(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_option_trades(symbols: Optional[list] = None)
Stream real-time Options Trades for given Options contract.
- Parameters
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns
None
- unsubscribe_option_trades(symbols: Optional[list] = None)
Unsubscribe real-time Options Trades for given Options contract.
- Parameters
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns
None
- subscribe_option_minute_aggregates(symbols: Optional[list] = None)
Stream real-time Options Minute Aggregates for given Options contract(s).
- Parameters
symbols – A list of symbols. Default is * which subscribes to ALL tickers in the market. you can pass with or without the prefix
O:
- Returns
None
- unsubscribe_option_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe real-time Options Minute aggregates for given Options contract.
- Parameters
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns
None
- subscribe_option_second_aggregates(symbols: Optional[list] = None)
Stream real-time Options Second Aggregates for given Options contract(s).
- Parameters
symbols – A list of symbols. Default is * which subscribes to ALL tickers in the market. you can pass with or without the prefix
O:
- Returns
None
- unsubscribe_option_second_aggregates(symbols: Optional[list] = None)
Unsubscribe real-time Options Second Aggregates for given Options contract.
- Parameters
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns
None
- subscribe_forex_quotes(symbols: Optional[list] = None)
Stream real-time forex quotes for given forex pair(s).
- Parameters
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
- Returns
None
- unsubscribe_forex_quotes(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- Parameters
symbols – A list of forex tickers. Default is * which unsubscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
- subscribe_forex_minute_aggregates(symbols: Optional[list] = None)
Stream real-time forex Minute Aggregates for given forex pair(s).
- Parameters
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
- Returns
None
- unsubscribe_forex_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- Parameters
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
- subscribe_crypto_trades(symbols: Optional[list] = None)
Stream real-time Trades for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- unsubscribe_crypto_trades(symbols: Optional[list] = None)
Unsubscribe real-time trades for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- subscribe_crypto_quotes(symbols: Optional[list] = None)
Stream real-time Quotes for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- unsubscribe_crypto_quotes(symbols: Optional[list] = None)
Unsubscribe real-time quotes for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- subscribe_crypto_minute_aggregates(symbols: Optional[list] = None)
Stream real-time Minute Aggregates for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- unsubscribe_crypto_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe real-time minute aggregates for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- subscribe_crypto_level2_book(symbols: Optional[list] = None)
Stream real-time level 2 book data for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- unsubscribe_crypto_level2_book(symbols: Optional[list] = None)
Unsubscribe real-time level 2 book data for given cryptocurrency pair(s).
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- static _default_on_msg(_ws: websocket._app.WebSocketApp, msg)
Default handler for message processing
- Parameters
msg – The message as received from the server
- Returns
None
- static _default_on_close(_ws: websocket._app.WebSocketApp, close_code, msg)
THe default function to be called when stream is closed.
- Parameters
close_code – The close code as received from server
msg – The close message as received from server
- Returns
- static _default_on_error(_ws: websocket._app.WebSocketApp, error, *args)
Default function to be called when an error is encountered.
- Parameters
error – The exception object as supplied by the handler
- Returns
None
- _default_on_open(_ws: websocket._app.WebSocketApp, *args)
Default function to be called when stream client is initialized. Takes care of the authentication.
- Parameters
args – Any args supplied by the handler
- Returns
None
- static _change_enum(val, allowed_type=<class 'str'>)
Async Streamer Client
- class polygon.streaming.async_streaming.AsyncStreamClient(api_key: str, cluster, host='socket.polygon.io', ping_interval: int = 20, ping_timeout: bool = 19, max_message_size: int = 1048576, max_memory_queue: int = 32, read_limit: int = 65536, write_limit: int = 65536)
These docs are not meant for general users. These are library API references. The actual docs will be available on the index page when they are prepared.
Note that this is asyncio based stream client which is suitable for async applications. If you need to stream using an
callback
based stream client, see Callback Streamer Client (Sync).This class implements all the websocket endpoints. Note that you should always import names from top level. eg:
from polygon import AsyncStreamClient
orimport polygon
(which allows you to access all names easily)Creating the client is as simple as:
client = AsyncStreamClient('MY_API_KEY', 'other_options')
Once you have the client, you can call its methods to subscribe/unsubscribe to streams, change handlers and process messages. All methods have sane default values and almost everything can be customized.
Type Hinting tells you what data type a parameter is supposed to be. You should always use
enums
for most parameters to avoid supplying error prone values.Take a look at the Official documentation to get an idea of the stream, data formatting for messages and related useful stuff.
- __init__(api_key: str, cluster, host='socket.polygon.io', ping_interval: int = 20, ping_timeout: bool = 19, max_message_size: int = 1048576, max_memory_queue: int = 32, read_limit: int = 65536, write_limit: int = 65536)
Initializes the stream client for async streaming Official Docs
- Parameters
api_key – Your API Key. Visit your dashboard to get yours.
cluster – Which market/cluster to connect to. See
polygon.enums.StreamCluster
for choices. NEVER connect to the same cluster again if there is an existing stream connected to it. The existing connection would be dropped and new one will be established. You can have up to 4 concurrent streams connected to 4 different clusters.host – Host url to connect to. Default is real time. See
polygon.enums.StreamHost
for choicesping_interval – Send a
ping
to server every specified number of seconds to keep the connection alive. Defaults to 20 seconds. Setting to 0 disables pinging.ping_timeout – The number of seconds to wait after sending a ping for the response (
pong
). If no response is received from the server in those many seconds, stream is considered dead and exits with code1011
. Defaults to 19 seconds.max_message_size – The max_size parameter enforces the maximum size for incoming messages in bytes. The default value is
1 MiB
(not MB). None disables the limit. If a message larger than the maximum size is received,recv()
will raiseConnectionClosedError
and the connection will be closed with code1009
max_memory_queue – sets the maximum length of the queue that holds incoming messages. The default value is
32
. None disables the limit. Messages are added to an in-memory queue when they’re received; thenrecv()
pops from that queueread_limit – sets the high-water limit of the buffer for incoming bytes. The low-water limit is half the high-water limit. The default value is
64 KiB
, half of asyncio’s default. Don’t change if you are unsure of what it implies.write_limit – The write_limit argument sets the high-water limit of the buffer for outgoing bytes. The low-water limit is a quarter of the high-water limit. The default value is
64 KiB
, equal to asyncio’s default. Don’t change if you’re unsure what it implies.
- async login(key: Optional[str] = None)
Creates Websocket Socket client using the configuration and Logs to the stream with credentials. Primarily meant for internal uses. You shouldn’t need to call this method manually as the streamer does it automatically behind the scenes
- Returns
None
- async _send(data: str)
Internal function to send data to websocket server endpoint
- Parameters
data – The formatted data string to be sent.
- Returns
None
- async _recv()
Internal function to receive messages from websocket server endpoint.
- Returns
The JSON decoded message data dictionary.
- async handle_messages(reconnect: bool = False, max_reconnection_attempts=5, reconnection_delay=5)
The primary method to start the stream. Connects & Logs in by itself. Allows Reconnecting by simply altering a parameter (subscriptions are persisted across reconnected streams)
- Parameters
reconnect – If this is
False
(default), it simply awaits the next message and calls the appropriate handler. Uses the_default_process_message()
if no handler was specified. You should use the statement inside a while loop in that case. Setting it to True creates an inner loop which traps disconnection errors except login failed due to invalid Key, and reconnects to the stream with the same subscriptions it had earlier before getting disconnected.max_reconnection_attempts – Determines how many times should the program attempt to reconnect in case of failed attempts. The Counter is reset as soon as a successful connection is re-established. Setting it to False disables the limit which is NOT recommended unless you know you got a situation. This value is ignored if
reconnect
is False (The default). Defaults to 5.reconnection_delay – Number of seconds to wait before attempting to reconnect after a failed reconnection attempt or a disconnection. This value is ignored if
reconnect
is False (the default). Defaults to 5.
- Returns
None
- async reconnect() tuple
Reconnects the stream. Existing subscriptions (ones before disconnections) are persisted and automatically re-subscribed when reconnection succeeds. All the handlers are also automatically restored. Returns a tuple based on success status. While this instance method is supposed to be used internally, it is possible to utilize this in your your custom attempts of reconnection implementation. Feel free to share your implementations with the community if you find success :)
- Returns
(True, message)
if reconnection succeeds else(False, message)
- async _default_process_message(update)
The default Handler for Message Streams which were NOT initialized with a handler function
- Parameters
update – The update message as received after decoding the message.
- Returns
None
- _default_handlers_and_apis()
Assign default handler value to all stream setups. ONLY meant for internal use
- async _modify_sub(symbols: Optional[Union[str, list]], action: str = 'subscribe', _prefix: str = 'T.')
Internal Function to send subscribe or unsubscribe requests to websocket. You should prefer using the corresponding methods to subscribe or unsubscribe to streams.
- Parameters
symbols – The list of symbols to apply the actions to.
action – Defaults to subscribe which subscribes to requested stream. Change to unsubscribe to remove an existing subscription.
_prefix – prefix of the stream service. See
polygon.enums.StreamServicePrefix
for choices.
- Returns
None
- async subscribe_stock_trades(symbols: Optional[list] = None, handler_function=None)
Get Real time trades for provided symbol(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL tickers.
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_stock_trades(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied ticker symbols.
- Parameters
symbols – A list of tickers to unsubscribe from. Defaults to ALL tickers.
- Returns
None
- async subscribe_stock_quotes(symbols: Optional[list] = None, handler_function=None)
Get Real time quotes for provided symbol(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL tickers.
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_stock_quotes(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied ticker symbols.
- Parameters
symbols – A list of tickers to unsubscribe from. Defaults to ALL tickers.
- Returns
None
- async subscribe_stock_minute_aggregates(symbols: Optional[list] = None, handler_function=None)
Get Real time Minute Aggregates for provided symbol(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL ticker.
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_stock_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied ticker symbols.
- Parameters
symbols – A list of tickers to unsubscribe from. Defaults to ALL tickers.
- Returns
None
- async subscribe_stock_second_aggregates(symbols: Optional[list] = None, handler_function=None)
Get Real time Seconds Aggregates for provided symbol(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL ticker.
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_stock_second_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied ticker symbols.
- Parameters
symbols – A list of tickers to unsubscribe from. Defaults to ALL tickers.
- Returns
None
- async subscribe_stock_limit_up_limit_down(symbols: Optional[list] = None, handler_function=None)
Get Real time LULD Events for provided symbol(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL ticker.
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_stock_limit_up_limit_down(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied ticker symbols.
- Parameters
symbols – A list of tickers to unsubscribe from. Defaults to ALL tickers.
- Returns
None
- async subscribe_stock_imbalances(symbols: Optional[list] = None, handler_function=None)
Get Real time Imbalance Events for provided symbol(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL ticker.
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_stock_imbalances(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied ticker symbols.
- Parameters
symbols – A list of tickers to unsubscribe from. Defaults to ALL tickers.
- Returns
None
- async subscribe_option_trades(symbols: Optional[list] = None, handler_function=None)
Get Real time options trades for provided ticker(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL ticker. You can specify with or without the prefix
O:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_option_trades(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied option symbols.
- Parameters
symbols – A list of symbols to unsubscribe from. Defaults to ALL tickers. You can specify with or without the prefix
O:
- Returns
None
- async subscribe_option_minute_aggregates(symbols: Optional[list] = None, handler_function=None)
Get Real time options minute aggregates for given ticker(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL ticker. You can specify with or without the prefix
O:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_option_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied option symbols.
- Parameters
symbols – A list of symbols to unsubscribe from. Defaults to ALL tickers. You can specify with or without the prefix
O:
- Returns
None
- async subscribe_option_second_aggregates(symbols: Optional[list] = None, handler_function=None)
Get Real time options second aggregates for given ticker(s)
- Parameters
symbols – A list of tickers to subscribe to. Defaults to ALL ticker. You can specify with or without the prefix
O:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_option_second_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied option symbols.
- Parameters
symbols – A list of symbols to unsubscribe from. Defaults to ALL tickers. You can specify with or without the prefix
O:
- Returns
None
- async subscribe_forex_quotes(symbols: Optional[list] = None, handler_function=None)
Get Real time Forex Quotes for provided symbol(s)
- Parameters
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_forex_quotes(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied forex symbols.
- Parameters
symbols – A list of forex tickers. Default is * which unsubscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
- Returns
None
- async subscribe_forex_minute_aggregates(symbols: Optional[list] = None, handler_function=None)
Get Real time Forex Minute Aggregates for provided symbol(s)
- Parameters
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_forex_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied forex symbols.
- Parameters
symbols – A list of forex tickers. Default is * which unsubscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
. you can pass with or without the prefixC:
- Returns
None
- async subscribe_crypto_trades(symbols: Optional[list] = None, handler_function=None)
Get Real time Crypto Trades for provided symbol(s)
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_crypto_trades(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied crypto symbols.
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- async subscribe_crypto_quotes(symbols: Optional[list] = None, handler_function=None)
Get Real time Crypto Quotes for provided symbol(s)
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_crypto_quotes(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied crypto symbols.
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- async subscribe_crypto_minute_aggregates(symbols: Optional[list] = None, handler_function=None)
Get Real time Crypto Minute Aggregates for provided symbol(s)
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_crypto_minute_aggregates(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied crypto symbols.
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- async subscribe_crypto_level2_book(symbols: Optional[list] = None, handler_function=None)
Get Real time Crypto Level 2 Book Data for provided symbol(s)
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
handler_function – The function which you’d want to call to process messages received from this subscription. Defaults to None which uses the default process message function.
- Returns
None
- async unsubscribe_crypto_level2_book(symbols: Optional[list] = None)
Unsubscribe from the stream for the supplied crypto symbols.
- Parameters
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns
None
- async change_handler(service_prefix, handler_function)
Change your handler function for a service. Can be used to update handlers dynamically while stream is running.
- Parameters
service_prefix – The Prefix of the service you want to change handler for. see
polygon.enums.StreamServicePrefix
for choices.handler_function – The new handler function to assign for this service
- Returns
None
Enums Interface
- class polygon.enums.TickerMarketType(value)
Market Types for method:
ReferenceClient.get_tickers()
- STOCKS = 'stocks'
- OPTIONS = 'options'
- FOREX = 'fx'
- CRYPTO = 'crypto'
- class polygon.enums.TickerType(value)
Ticker types for method:
ReferenceClient.get_tickers()
- CS = 'CS'
- COMMON_STOCKS = 'CS'
- ADRC = 'ADRC'
- ADRP = 'ADRP'
- ADRR = 'ADRR'
- UNIT = 'UNIT'
- RIGHT = 'RIGHT'
- PFD = 'PFD'
- FUND = 'FUND'
- SP = 'SP'
- WARRANT = 'WARRANT'
- INDEX = 'INDEX'
- ETF = 'ETF'
- ETN = 'ETN'
- class polygon.enums.TickerSortType(value)
Sort key for method:
ReferenceClient.get_tickers()
- TICKER = 'ticker'
- NAME = 'name'
- MARKET = 'market'
- LOCALE = 'locale'
- PRIMARY_EXCHANGE = 'primary_exchange'
- TYPE = 'type'
- ACTIVE = 'active'
- CURRENCY_SYMBOL = 'currency_symbol'
- CURRENCY_NAME = 'currency_name'
- BASE_CURRENCY_SYMBOL = 'base_currency_symbol'
- BASE_CURRENCY_NAME = 'base_currency_name'
- CIK = 'cik'
- COMPOSITE_FIGI = 'composite_figi'
- SHARE_CLASS_FIGI = 'share_class_figi'
- LAST_UPDATED_UTC = 'last_updated_utc'
- DELISTED_UTC = 'delisted_utc'
- class polygon.enums.SortOrder(value)
Order of sort. Ascending usually means oldest at the top. Descending usually means newest at the top. It is recommended to ensure the behavior in the corresponding function’s docs. This enum can be used by any method accepting Sort order values.
- ASCENDING = 'asc'
- ASC = 'asc'
- DESCENDING = 'desc'
- DESC = 'desc'
- class polygon.enums.TickerTypeAssetClass(value)
Asset Class for method:
ReferenceClient.get_ticker_types_v3()
- STOCKS = 'stocks'
- OPTIONS = 'options'
- FOREX = 'fx'
- CRYPTO = 'crypto'
- class polygon.enums.TickerNewsSort(value)
Sort key for method:
ReferenceClient.get_ticker_news()
- PUBLISHED_UTC = 'published_utc'
- ALL = None
- class polygon.enums.StockReportType(value)
Type of report for method:
ReferenceClient.get_stock_financials()
- YEAR = 'Y'
- Y = 'Y'
- YA = 'YA'
- YEAR_ANNUALIZED = 'YA'
- Q = 'Q'
- QUARTER = 'Q'
- QA = 'QA'
- QUARTER_ANNUALIZED = 'QA'
- T = 'T'
- TRAILING_TWELVE_MONTHS = 'T'
- TA = 'TA'
- TRAILING_TWELVE_MONTHS_ANNUALIZED = 'TA'
- class polygon.enums.StockFinancialsSortType(value)
Direction to use for sorting report for method:
ReferenceClient.get_stock_financials()
- REPORT_PERIOD = 'reportPeriod'
- REVERSE_REPORT_PERIOD = '-reportPeriod'
- CALENDAR_DATE = 'calendarDate'
- REVERSE_CALENDAR_DATE = '-calendarDate'
- class polygon.enums.StockFinancialsTimeframe(value)
Query by timeframe. Annual financials originate from 10-K filings, and quarterly financials originate from 10-Q filings. Note: Most companies do not file quarterly reports for Q4 and instead include those financials in their annual report, so some companies my not return quarterly financials for Q4 for method:
ReferenceClient.get_stock_financials_vx()
- ANNUAL = 'annual'
- QUARTERLY = 'quarterly'
- class polygon.enums.StockFinancialsSortKey(value)
Sort field for method:
ReferenceClient.get_stock_financials_vx()
- FILLING_DATE = 'filling_date'
- PERIOD_OF_REPORT_DATE = 'period_of_report_date'
- class polygon.enums.ConditionMappingTickType(value)
Tick Type for method:
ReferenceClient.get_condition_mappings()
- TRADES = 'trades'
- QUOTES = 'quotes'
- class polygon.enums.ConditionsDataType(value)
Type of data for method:
ReferenceClient.get_conditions()
- TRADE = 'trade'
- BBO = 'bbo'
- NBBO = 'nbbo'
- class polygon.enums.ConditionsSIP(value)
SIP for method:
ReferenceClient.get_conditions()
- CTA = 'CTA'
- UTP = 'UTP'
- OPRA = 'OPRA'
- class polygon.enums.ConditionsSortKey(value)
Sort key for method:
ReferenceClient.get_conditions()
- ASSET_CLASS = 'asset_class'
- ID = 'id'
- TYPE = 'type'
- NAME = 'name'
- DATA_TYPES = 'data_types'
- LEGACY = 'legacy'
- class polygon.enums.AssetClass(value)
Asset Class for methods:
ReferenceClient.get_exchanges_v3()
andReferenceClient.get_conditions()
and wherever needed.- STOCKS = 'stocks'
- OPTIONS = 'options'
- FOREX = 'fx'
- CRYPTO = 'crypto'
- class polygon.enums.SnapshotDirection
Direction to be supplied to the SnapShot - Gainers and Losers APIs on Stocks, Forex and Crypto endpoints
- GAINERS = 'gainers'
- GAIN = 'gainers'
- LOSERS = 'losers'
- LOSE = 'losers'
- class polygon.enums.StreamCluster(value)
The cluster to connect to. To be used for both callback and async stream client. NEVER connect to the same cluster again if there is an existing stream connected to it. The existing connection would be dropped and new one will be established. You can have up to 4 concurrent streams connected to 4 different clusters.
- STOCKS = 'stocks'
- OPTIONS = 'options'
- FOREX = 'forex'
- CRYPTO = 'crypto'
- class polygon.enums.OptionsContractType(value)
Contract Type for method:
ReferenceClient.get_options_contracts()
- CALL = ('call',)
- PUT = 'put'
- OTHER = 'other'
- class polygon.enums.OptionsContractsSortType(value)
Sort field used for ordering for method:
ReferenceClient.get_options_contracts()
- TICKER = 'ticker'
- UNDERLYING_TICKER = 'underlying_ticker'
- EXPIRATION_DATE = 'expiration_date'
- STRIKE_PRICE = 'strike_price'
- class polygon.enums.OptionTradesSort(value)
Sort field used for ordering option trades. Used for method:
OptionsClient.get_trades
- TIMESTAMP = 'timestamp'
- class polygon.enums.StreamHost(value)
Host to be used for stream connections. WHY on earth would you use delayed if you’re paying for polygon??
- REAL_TIME = 'socket.polygon.io'
- DELAYED = 'delayed.polygon.io'
- class polygon.enums.StreamServicePrefix(value)
Service Prefix for Stream endpoints. To be used for method:
AsyncStreamClient.async change_handler()
- STOCK_TRADES = 'T'
- STOCK_QUOTES = 'Q'
- STOCK_MINUTE_AGGREGATES = 'AM'
- STOCK_SECOND_AGGREGATES = 'A'
- STOCK_LULD = 'LULD'
- STOCK_IMBALANCES = 'NOI'
- FOREX_QUOTES = 'C'
- FOREX_MINUTE_AGGREGATES = 'CA'
- CRYPTO_TRADES = 'XT'
- CRYPTO_QUOTES = 'XQ'
- CRYPTO_LEVEL2 = 'XL2'
- CRYPTO_MINUTE_AGGREGATES = 'XA'
- STATUS = 'status'
- OPTION_TRADES = 'T'
- OPTION_MINUTE_AGGREGATES = 'AM'
- OPTION_SECOND_AGGREGATES = 'A'