Library Interface Documentation
Here is the Entire Library Interface reference.
Base Clients
Base Client
- class polygon.base_client.Base
- split_date_range(start, end, timespan: str, high_volatility: bool = False, reverse: bool = True) list
Internal helper function to split a BIGGER date range into smaller chunks to be able to easily fetch aggregate bars data. The chunks duration is supposed to be different for time spans. For 1 minute bars, multiplier would be 1, timespan would be ‘minute’
- Parameters:
start – start of the time frame. accepts date, datetime objects or a string
YYYY-MM-DD
end – end of the time frame. accepts date, datetime objects or a string
YYYY-MM-DD
timespan – The frequency type. like day or minute. see
polygon.enums.Timespan
for choiceshigh_volatility – Specifies whether the symbol/security in question is highly volatile. If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
reverse – If True (the default), will reverse the order of chunks (chronologically)
- Returns:
a list of tuples. each tuple is in format
(start, end)
and represents one chunk of time frame
- static normalize_datetime(dt, output_type: str = 'ts', _dir: str = 'start', _format: str = '%Y-%m-%d', unit: str = 'ms', tz=None)
a core method to perform some specific datetime operations before/after interaction with the API
- Parameters:
dt – The datetime input
output_type – what to return. defaults to timestamp (utc if unaware obj)
_dir – whether the input is meant for start of a range or end of it
_format – The format string to use IFF expected to return as string
unit – the timestamp units to work with. defaults to ms (milliseconds)
tz – the timezone to assume/use. defaults to None (which means UTC)
- Returns:
The output timestamp or formatted string
- static _change_enum(val: str | ~enum.Enum | float | int, allowed_type=<class 'str'>)
- static to_json_safe(response: Response | dict) dict
- get_dates_between(from_date=None, to_date=None, include_to_date: bool = True) list
Get a list of dates between the two specified dates (from_date and to_date)
- Parameters:
from_date – The start date
to_date – The end date
include_to_date – Whether to include the end date in the list
- Returns:
A list of dates between the two specified dates
Base Sync Client
- class polygon.base_client.BaseClient(api_key: str, 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.
- __init__(api_key: str, 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.
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
- _get_response(path: str, params: dict | None = None, raw_response: bool = True) Response | dict
Get response on a path. Meant to be used internally but can be used if you know what you’re doing
- 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 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_page_by_url(url: str, raw_response: bool = False) Response | dict
Get the next page of a response. The URl is returned within
next_url
attribute on endpoints which support pagination (e.g. 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.- Parameters:
url – The next URL. As contained in
next_url
of the response.raw_response – Whether 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: Response | dict, raw_response: bool = False) 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 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: Response | dict, raw_response: bool = False) 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 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_all_pages(old_response, max_pages: int | None = None, direction: str = 'next', verbose: bool = False, raw_responses: bool = False)
A helper function for endpoints which implement pagination using
next_url
andprevious_url
attributes. Can be used externally too to get all responses in a list.- Parameters:
old_response – The last response you had. In most cases, this would be simply the very first response.
max_pages – If you want to limit the number of pages to retrieve. Defaults to None which fetches ALL available pages
direction – The direction to paginate in. Defaults to next which grabs all next_pages. see
polygon.enums.PaginationDirection
for choicesverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_responses – If set to True, the elements in container list, you will get underlying Response object instead of the json formatted dict/list. Only use if you need to check status codes or headers. Defaults to False, which makes it return decoded data in list.
- Returns:
A list of responses. By default, responses are actual json decoded dict/list. Depending on value of
raw_response
- _paginate(_res, merge_all_pages: bool = True, max_pages: int | None = None, verbose: bool = False, raw_page_responses: bool = False)
Internal function to call the core pagination methods to build the response object to be parsed by individual methods.
- Parameters:
merge_all_pages – whether to merge all the pages into one response. defaults to True
max_pages – number of pages to fetch. defaults to all available pages.
verbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – whether to keep raw response objects or decode them. Only considered if merge_all_pages is set to False. Defaults to False.
- Returns:
- get_full_range_aggregates(fn, symbol: str, time_chunks: list, run_parallel: bool = True, max_concurrent_workers: int = 10, warnings: bool = True, info: bool = True, adjusted: bool = True, sort='asc', limit: int = 5000, multiplier: int = 1, timespan='day') list
Internal helper function to fetch aggregate bars for BIGGER time ranges. Should only be used internally. Users should prefer the relevant aggregate function with additional parameters.
- Parameters:
fn – The method to call in each chunked timeframe
symbol – The ticker symbol to get data for
time_chunks – The list of time chunks as returned by method
split_datetime_range
run_parallel – If true (the default), it will use an internal
ThreadPool
to get the responses in parallel. Note That since python has the GIL restrictions, it would mean that if you have a ThreadPool of your own, only one ThreadPool will be running at a time and the other pool will wait. set to False to get all responses in sequence (will take time)warnings – Defaults to True which prints warnings. Set to False to disable warnings.
info – Defaults to True which prints mild level warnings / informational messages e.g. when there is no data in response but the response is otherwise OK. Set to False to disable
max_concurrent_workers – This is only used if run_parallel is set to true. Controls how many worker threads are spawned in the internal thread pool. Defaults to
your cpu core count * 5
adjusted – Whether 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
- Returns:
A single merged list of ALL candles/bars
- _get_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10-day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- _get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10-day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- _get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate RSI. The default
close
will result in using close prices to calculate RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- _get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Base Async Client
- class polygon.base_client.BaseAsyncClient(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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 async client class for all other REST clients which inherit from this class and implement their own endpoints on top of it.
- __init__(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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.
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 data to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.pool_timeout – The pool timeout in seconds. Defaults to 10. Basically the number of seconds to wait while trying to get a connection from connection pool. Do NOT change if you’re unsure of what it implies
max_connections – Max number of connections in the pool. Defaults to NO LIMITS. Do NOT change if you’re unsure of application
max_keepalive – max number of allowable keep alive connections in the pool. Defaults to no limit. Do NOT change if you’re unsure of the applications.
write_timeout – The write timeout in seconds. Defaults to 10. basically the number of seconds to wait for data to be written/posted. Raises a
WriteTimeout
if unable to connect within the specified time limit.
- async static aw_task(aw, semaphore)
- 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.
- async _get_response(path: str, params: dict | None = None, raw_response: bool = True) Response | dict
Get response on a path - meant to be used internally but can be used if you know what you’re doing
- 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 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_page_by_url(url: str, raw_response: bool = False) Response | dict
Get the next page of a response. The URl is returned within
next_url
attribute on endpoints which support pagination (e.g. 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.- Parameters:
url – The next URL. As contained in
next_url
of the response.raw_response – Whether 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 get_next_page(old_response: Response | dict, raw_response: bool = False) 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 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 get_previous_page(old_response: Response | dict, raw_response: bool = False) 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 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 get_all_pages(old_response, max_pages: int | None = None, direction: str = 'next', verbose: bool = False, raw_responses: bool = False)
A helper function for endpoints which implement pagination using
next_url
andprevious_url
attributes. Can be used externally too to get all responses in a list.- Parameters:
old_response – The last response you had. In most cases, this would be simply the very first response.
max_pages – If you want to limit the number of pages to retrieve. Defaults to None which fetches ALL available pages
direction – The direction to paginate in. Defaults to next which grabs all next_pages. see
polygon.enums.PaginationDirection
for choicesverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_responses – If set to True, the elements in container list, you will get underlying Response object instead of the json formatted dict/list. Only use if you need to check status codes or headers. Defaults to False, which makes it return decoded data in list.
- Returns:
A list of responses. By default, responses are actual json decoded dict/list. Depending on value of
raw_response
- async _paginate(_res, merge_all_pages: bool = True, max_pages: int | None = None, verbose: bool = False, raw_page_responses: bool = False)
Internal function to call the core pagination methods to build the response object to be parsed by individual methods.
- Parameters:
merge_all_pages – whether to merge all the pages into one response. defaults to True
max_pages – number of pages to fetch. defaults to all available pages.
verbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – whether to keep raw response objects or decode them. Only considered if merge_all_pages is set to False. Defaults to False.
- Returns:
- async get_full_range_aggregates(fn, symbol: str, time_chunks: list, run_parallel: bool = True, max_concurrent_workers: int = 10, warnings: bool = True, info: bool = True, adjusted: bool = True, sort='asc', limit: int = 5000, multiplier: int = 1, timespan='day') list
Internal helper function to fetch aggregate bars for BIGGER time ranges. Should only be used internally. Users should prefer the relevant aggregate function with additional parameters.
- Parameters:
fn – The method to call in each chunked timeframe
symbol – The ticker symbol to get data for
time_chunks – The list of time chunks as returned by method
split_datetime_range
run_parallel – If true (the default), it will use an internal
ThreadPool
to get the responses in parallel. Note That since python has the GIL restrictions, it would mean that if you have a ThreadPool of your own, only one ThreadPool will be running at a time and the other pool will wait. set to False to get all responses in sequence (will take time)warnings – Defaults to True which prints warnings. Set to False to disable warnings.
info – Defaults to True which prints mild warnings and informational messages. E.g. if the response came back with no data, but otherwise it was a valid response
max_concurrent_workers – This is only used if run_parallel is set to true. Controls how many worker coroutines are spawned internally. Defaults to
your cpu core count * 5
. Anasyncio.Semaphore()
is used behind the scenes.adjusted – whether 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
- Returns:
A single merged list of ALL candles/bars
- async _get_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async _get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async _get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate RSI. The default
close
will result in using close prices to calculate RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async _get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence. COMMON method for all clients
- Parameters:
symbol – The corrected symbol according to asset type
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Stocks Clients
Stocks Sync Client
- class polygon.stocks.stocks.SyncStocksClient(api_key: str, 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. e.g.:
from polygon import StocksClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, 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.
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: int | None = None, timestamp_limit: int | None = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False)
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 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_trades_v3(symbol: str, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get trades for a ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want trades for.
timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.StocksTradesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_quotes(symbol: str, date, timestamp: int | None = None, timestamp_limit: int | None = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False)
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 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_v3(symbol: str, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get NBBO Quotes for a ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want quotes for.
timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.StocksQuotesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_last_trade(symbol: str, raw_response: bool = False)
Get the most recent trade for a given stock. Official Docs
- Parameters:
symbol – The ticker symbol of the stock/equity.
raw_response – whether 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)
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 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)
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 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 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', full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, warnings: bool = True, info: bool = True, high_volatility: bool = False, raw_response: bool = False)
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 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
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolwarnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
info – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, warnings: bool = True, info: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for a stock. For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the stock. e.g.:
AMD
.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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolwarnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
info – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False)
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 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 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)
Get the previous day’s OCHLV for the specified stock ticker. Official Docs
- Parameters:
symbol – The ticker symbol of the stock/equity.
adjusted – whether 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 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)
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 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 | None = None, raw_response: bool = False)
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. Defaults to ALL tickers
raw_response – whether 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)
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 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_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for a Stock symbol
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for a Stock symbol
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for a Stock symbol
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for a stock
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Stocks Async Client
- class polygon.stocks.stocks.AsyncStocksClient(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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. e.g.:
from polygon import StocksClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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.
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 data to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.pool_timeout – The pool timeout in seconds. Defaults to 10. Basically the number of seconds to wait while trying to get a connection from connection pool. Do NOT change if you’re unsure of what it implies
max_connections – Max number of connections in the pool. Defaults to NO LIMITS. Do NOT change if you’re unsure of application
max_keepalive – max number of allowable keep alive connections in the pool. Defaults to no limit. Do NOT change if you’re unsure of the applications.
write_timeout – The write timeout in seconds. Defaults to 10. basically the number of seconds to wait for data to be written/posted. Raises a
WriteTimeout
if unable to connect within the specified time limit.
- async get_trades(symbol: str, date, timestamp: int | None = None, timestamp_limit: int | None = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False)
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 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 get_trades_v3(symbol: str, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get trades for a ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want trades for.
timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.StocksTradesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_quotes(symbol: str, date, timestamp: int | None = None, timestamp_limit: int | None = None, reverse: bool = True, limit: int = 5000, raw_response: bool = False)
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 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 get_quotes_v3(symbol: str, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get NBBO Quotes for a ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want quotes for.
timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.StocksQuotesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_last_trade(symbol: str, raw_response: bool = False)
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 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 get_last_quote(symbol: str, raw_response: bool = False)
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 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 get_daily_open_close(symbol: str, date, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_aggregate_bars(symbol: str, from_date, to_date, adjusted: bool = True, sort='asc', limit: int = 5000, multiplier: int = 1, timespan='day', full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, warnings: bool = True, info: bool = True, high_volatility: bool = False, raw_response: bool = False)
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 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
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolwarnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
info – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- async get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, warnings: bool = True, info: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for a stock. For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the currency pair. e.g.:
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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolwarnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
info – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- async get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_snapshot(symbol: str, raw_response: bool = False)
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 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 get_current_price(symbol: str) float
get current market price for the ticker symbol specified - Async method
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.
- async get_snapshot_all(symbols: list | None = None, raw_response: bool = False)
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. Defaults to ALL tickers
raw_response – whether 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 get_gainers_and_losers(direction='gainers', raw_response: bool = False)
Get the current top 20 gainers or losers of the day in stocks/equities markets - Async method Official Docs
- Parameters:
direction – The direction of results. Defaults to gainers. See
polygon.enums.SnapshotDirection
for choicesraw_response – whether 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 get_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for a Stock symbol
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for a Stock symbol
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for a Stock symbol
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for a stock
- Parameters:
symbol – The stock symbol
timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Options Clients
Option Symbol Helper Functions & Objects
- polygon.options.options.build_option_symbol(underlying_symbol: str, expiry, call_or_put, strike_price, _format='polygon', prefix_o: bool = False) str
Generic function to build option symbols for ALL supported formats:
polygon.enums.OptionSymbolFormat
. Default format ispolygon
.- 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. Try to keep up to 3 digits after the decimal point_format – The format to use when building symbol. Defaults to
polygon
. Supported formats arepolygon, tda, tos, ibkr, tradier, trade_station
. If you prefer to use convenient enums, seepolygon.enums.OptionSymbolFormat
prefix_o – Whether 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. This parameter is ignored if format is notpolygon
- Returns:
The option symbols string in the format specified
- polygon.options.options.parse_option_symbol(option_symbol: str, _format='polygon', output_format='object')
Generic function to build option symbols for ALL supported formats:
polygon.enums.OptionSymbolFormat
. Default format ispolygon
.- Parameters:
option_symbol – the option symbol you want to parse
_format – What format the symbol is in. If you don’t know the format you can use the
detect_option_symbol_format
function to detect the format (best effort detection). Supported formats arepolygon, tda, tos, ibkr, tradier, trade_station
. If you prefer to use convenient enums, seepolygon.enums.OptionSymbolFormat
. Default:polygon
output_format – Output format of the result. defaults to object. Set it to
dict
orlist
as needed.
- Returns:
The parsed info from symbol either as an object, list or a dict as indicated by
output_format
.
- polygon.options.options.build_polygon_option_symbol(underlying_symbol: str, expiry, call_or_put, strike_price, prefix_o: bool = False) str
Build the option symbol from the details provided, in standard polygon format
- 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 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_polygon_option_symbol(option_symbol: str, output_format='object')
Function to parse an option symbol in standard polygon format
- 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.
- Returns:
The parsed values either as an object, list or a dict as indicated by
output_format
.
- polygon.options.options.convert_option_symbol_formats(option_symbol: str, from_format: str, to_format: str) str
Convert an option symbol from one format to another within supported formats:
polygon.enums.OptionSymbolFormat
- Parameters:
option_symbol – The option symbol you want to convert
from_format – The format in which the option symbol is currently in. If you don’t know the format you can use the
detect_option_symbol_format
function to detect the format (best effort detection). Supported formats arepolygon, tda, tos, ibkr, tradier, trade_station
. If you prefer to use convenient enums, seepolygon.enums.OptionSymbolFormat
to_format – The format to which you want to convert the option symbol. Supported formats are
polygon, tda, tos, ibkr, tradier, trade_station
. If you prefer to use convenient enums, seepolygon.enums.OptionSymbolFormat
- Returns:
The converted option symbol as a string
- polygon.options.options.detect_option_symbol_format(option_symbol: str) str | bool | list
Detect what format a symbol is formed in. Supported formats are
polygon.enums.OptionSymbolFormat
. This function does basic detection according to some simple rules. Test well before using in production.- Parameters:
option_symbol – The option symbol to check the format of
- Returns:
Format’s shorthand string or list of strings if able to recognize the format.
False
otherwise. Possible shorthand strings arepolygon, tda, tos, ibkr, tradier, trade_station
- 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
- class polygon.options.options.OptionSymbol(option_symbol: str, symbol_format='polygon')
The custom object for parsed details from option symbols.
- __init__(option_symbol: str, 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 validsymbol_format – Which formatting spec to use. Defaults to polygon. also supports
tda
which is the format supported by TD Ameritrade
- __repr__()
Return repr(self).
Options Sync Client
- class polygon.options.options.SyncOptionsClient(api_key: str, 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. e.g.:
from polygon import OptionsClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, 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.
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 = 5000, order='asc', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, 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
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 e.g.
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 – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
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 5000. max is 50000.
order – order of the results. Defaults to
asc
. Seepolygon.enums.SortOrder
for info and available choices.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_quotes(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, sort='timestamp', limit: int = 5000, order='asc', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get quotes 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
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 quotes for. for e.g.
O:TSLA210903C00700000
. you can pass the symbol with or without the prefixO:
timestamp – Query by quote timestamp. You can supply a
date
,datetime
object or ananosecond UNIX timestamp
or a string in format:YYYY-MM-DD
.timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
sort – Sort field used for ordering. Defaults to timestamp. See
polygon.enums.OptionQuotesSort
for available choices.limit – Limit the number of results returned. Defaults to 5000. max is 50000.
order – order of the results. Defaults to
asc
. Seepolygon.enums.SortOrder
for info and available choices.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_last_trade(ticker: str, raw_response: bool = False)
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 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_daily_open_close(symbol: str, date, adjusted: bool = True, raw_response: bool = False)
Get the OCHLV and after-hours prices of a contract on a certain date. Official Docs
- Parameters:
symbol – The option symbol we want daily-OCHLV for. e.g.
O:FB210903C00700000
. You can pass it with or without the prefixO:
date – The date/day of the daily-OCHLV to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – whether 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 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', full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False, raw_response: bool = False)
Get aggregate bars for an option contract 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 contract. e.g.
O:FB210903C00700000
. You can pass in with or without the prefixO:
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 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. see this article for more info.
multiplier – The size of the timespan multiplier. Must be a positive whole number. defaults to 1.
timespan – The size of the time window. See
polygon.enums.Timespan
for choices. defaults today
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for an option contract. For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the currency pair. e.g.:
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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- get_snapshot(underlying_symbol: str, option_symbol: str, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the snapshot of an option contract for a stock equity. Official Docs
- Parameters:
underlying_symbol – The underlying ticker symbol of the option contract. e.g.
AMD
option_symbol – the option symbol. You can use use the Working with Option Symbols section to make it easy to work with option symbols in polygon or tda formats.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_previous_close(ticker: str, adjusted: bool = True, raw_response: bool = False)
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 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 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_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Options Async Client
- class polygon.options.options.AsyncOptionsClient(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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 for async uses. Note that you should always import names from top level. e.g.:
from polygon import OptionsClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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.
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 data to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.pool_timeout – The pool timeout in seconds. Defaults to 10. Basically the number of seconds to wait while trying to get a connection from connection pool. Do NOT change if you’re unsure of what it implies
max_connections – Max number of connections in the pool. Defaults to NO LIMITS. Do NOT change if you’re unsure of application
max_keepalive – max number of allowable keep alive connections in the pool. Defaults to no limit. Do NOT change if you’re unsure of the applications.
write_timeout – The write timeout in seconds. Defaults to 10. basically the number of seconds to wait for data to be written/posted. Raises a
WriteTimeout
if unable to connect within the specified time limit.
- async get_trades(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, sort='timestamp', limit: int = 5000, order='asc', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, 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
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 e.g.
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 – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
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.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_quotes(option_symbol: str, timestamp=None, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, sort='timestamp', limit: int = 5000, order='asc', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get quotes 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
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 quotes for. for e.g.
O:TSLA210903C00700000
. you can pass the symbol with or without the prefixO:
timestamp – Query by quote timestamp. You can supply a
date
,datetime
object or ananosecond UNIX timestamp
or a string in format:YYYY-MM-DD
.timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
sort – Sort field used for ordering. Defaults to timestamp. See
polygon.enums.OptionQuotesSort
for available choices.limit – Limit the number of results returned. Defaults to 5000. max is 50000.
order – order of the results. Defaults to
asc
. Seepolygon.enums.SortOrder
for info and available choices.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_last_trade(ticker: str, raw_response: bool = False)
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 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 get_daily_open_close(symbol: str, date, adjusted: bool = True, raw_response: bool = False)
Get the OCHLV and after-hours prices of a contract on a certain date. Official Docs
- Parameters:
symbol – The option symbol we want daily-OCHLV for. e.g.
O:FB210903C00700000
. You can pass it with or without the prefixO:
date – The date/day of the daily-OCHLV to retrieve. Could be
datetime
ordate
or stringYYYY-MM-DD
adjusted – whether 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 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 get_aggregate_bars(symbol: str, from_date, to_date, adjusted: bool = True, sort='asc', limit: int = 5000, multiplier: int = 1, timespan='day', full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False, raw_response: bool = False)
Get aggregate bars for an option contract 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 contract. e.g.
O:FB210903C00700000
. You can pass in with or without the prefixO:
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 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. see this article for more info.
multiplier – The size of the timespan multiplier. Must be a positive whole number. defaults to 1.
timespan – The size of the time window. See
polygon.enums.Timespan
for choices. defaults today
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- async get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for an option contract For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the currency pair. e.g.:
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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- async get_snapshot(underlying_symbol: str, option_symbol: str, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the snapshot of an option contract for a stock equity. Official Docs
- Parameters:
underlying_symbol – The underlying ticker symbol of the option contract. e.g.
AMD
option_symbol – the option symbol. You can use use the Working with Option Symbols section to make it easy to work with option symbols in polygon or tda formats.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_previous_close(ticker: str, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for an option contract
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
O:
. If you want to build option symbols from details such as expiry and strike price, use the option symbol functionstimestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
References Clients
Reference Sync Client
- class polygon.reference_apis.reference_api.SyncReferenceClient(api_key: str, 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. e.g.:
from polygon import ReferenceClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, 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.
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: str | None = None, cik: str = '', date=None, search: str | None = None, active: bool = True, sort='ticker', order='asc', limit: int = 1000, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
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 e.g.
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 1000 which is also the max.
Pagination
is supported by the pagination function belowall_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_ticker_types(asset_class=None, locale=None, raw_response: bool = False)
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 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, date=None, raw_response: bool = False)
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 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_bulk_ticker_details(symbol: str, from_date=None, to_date=None, custom_dates: list | None = None, run_parallel: bool = True, warnings: bool = True, sort='asc', max_concurrent_workers: int = 10) OrderedDict
Get ticker details for a symbol for specified date range and/or dates. Each response will have detailed information about the ticker and the company behind it (on THAT particular date) Official Docs
- Parameters:
symbol – The ticker symbol to get data for
from_date – The start date of the date range. Must be specified if custom_dates is not supplied
to_date – The end date of the date range. Must be specified if custom_dates is not supplied
custom_dates – A list of dates, for which to get data for. You can specify this WITH a range. Each date can be a
date
,datetime
object or a stringYYYY-MM-DD
run_parallel – If true (the default), it will use an internal
ThreadPool
to get the responses in parallel. Note That since python has the GIL restrictions, it would mean that if you have a ThreadPool of your own, only one ThreadPool will be running at a time and the other pool will wait. set to False to get all responses in sequence (will take time)warnings – Defaults to True which prints warnings. Set to False to disable warnings.
sort – The order of sorting the final results. Defaults to ascending order of dates. See
polygon.enums.SortOrder
for choicesmax_concurrent_workers – This is only used if run_parallel is set to true. Controls how many worker threads are spawned in the internal thread pool. Defaults to
your cpu core count * 5
- Returns:
An OrderedDict where keys are dates, and values are corresponding ticker details.
- get_option_contract(ticker: str, as_of_date=None, raw_response: bool = False)
get Info about an option contract Official Docs
- Parameters:
ticker – An option ticker in standard format. The lib provides easy functions to build and work with option symbols
as_of_date – Specify a point in time for the contract. You can pass a
datetime
ordate
object or a string in formatYYYY-MM-DD
. Defaults to today’s dateraw_response – whether 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: str | None = None, ticker: str | None = 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='expiration_date', limit=1000, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False, as_of_date=None)
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. defaults to expiration_datelimit – Limit the size of the response, default is 1000.
Pagination
is supported by the pagination function belowall_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.as_of_date – Specify a point in time for contracts as of this date with format YYYY-MM-DD. Defaults to today’s date.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_ticker_news(symbol: str | None = None, limit: int = 1000, 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, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
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 1000 which is also the max.
Pagination
is supported by the pagination function beloworder – 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
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_stock_dividends(ticker: str | None = None, ex_dividend_date=None, record_date=None, declaration_date=None, pay_date=None, frequency: int | None = None, limit: int = 1000, cash_amount=None, dividend_type=None, sort: str = 'pay_date', order: str = 'asc', ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, ex_dividend_date_lt=None, ex_dividend_date_lte=None, ex_dividend_date_gt=None, ex_dividend_date_gte=None, record_date_lt=None, record_date_lte=None, record_date_gt=None, record_date_gte=None, declaration_date_lt=None, declaration_date_lte=None, declaration_date_gt=None, declaration_date_gte=None, pay_date_lt=None, pay_date_lte=None, pay_date_gt=None, pay_date_gte=None, cash_amount_lt=None, cash_amount_lte=None, cash_amount_gt=None, cash_amount_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get a list of historical cash dividends, including the ticker symbol, declaration date, ex-dividend date, record date, pay date, frequency, and amount. Official Docs
- Parameters:
ticker – Return the dividends that contain this ticker.
ex_dividend_date – Query by ex-dividend date. could be a date, datetime object or a string
YYYY-MM-DD
record_date – Query by record date. could be a date, datetime object or a string
YYYY-MM-DD
declaration_date – Query by declaration date. could be a date, datetime object or a string
YYYY-MM-DD
pay_date – Query by pay date. could be a date, datetime object or a string
YYYY-MM-DD
frequency – Query by the number of times per year the dividend is paid out. No default value applied. see
polygon.enums.PayoutFrequency
for choiceslimit – Limit the size of the response, default is 1000 which is also the max.
Pagination
is supported by the pagination function belowcash_amount – Query by the cash amount of the dividend.
dividend_type – Query by the type of dividend. See
polygon.enums.DividendType
for choicessort – sort key used for ordering. See
polygon.enums.DividendSort
for choices.order – orders of results. defaults to asc. see
polygon.enums.SortOrder
for choicesticker_lt – filter where ticker is less than given value (alphabetically)
ticker_lte – filter where ticker is less than or equal to given value (alphabetically)
ticker_gt – filter where ticker is greater than given value (alphabetically)
ticker_gte – filter where ticker is greater than or equal to given value (alphabetically)
ex_dividend_date_lt – filter where ex-div date is less than given date
ex_dividend_date_lte – filter where ex-div date is less than or equal to given date
ex_dividend_date_gt – filter where ex-div date is greater than given date
ex_dividend_date_gte – filter where ex-div date is greater than or equal to given date
record_date_lt – filter where record date is less than given date
record_date_lte – filter where record date is less than or equal to given date
record_date_gt – filter where record date is greater than given date
record_date_gte – filter where record date is greater than or equal to given date
declaration_date_lt – filter where declaration date is less than given date
declaration_date_lte – filter where declaration date is less than or equal to given date
declaration_date_gt – filter where declaration date is greater than given date
declaration_date_gte – filter where declaration date is greater than or equal to given date
pay_date_lt – filter where pay date is less than given date
pay_date_lte – filter where pay date is less than or equal to given date
pay_date_gt – filter where pay date is greater than given date
pay_date_gte – filter where pay date is greater than or equal to given date
cash_amount_lt – filter where cash amt is less than given value
cash_amount_lte – filter where cash amt is less than or equal to given value
cash_amount_gt – filter where cash amt is greater than given value
cash_amount_gte – filter where cash amt is greater than or equal to given value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_stock_financials_vx(ticker: str | None = None, cik: str | None = None, company_name: str | None = None, company_name_search: str | None = None, sic: str | None = 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', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, 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 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.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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(ticker: str | None = None, execution_date=None, reverse_split: bool | None = None, order: str = 'asc', sort: str = 'execution_date', limit: int = 1000, ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, execution_date_lt=None, execution_date_lte=None, execution_date_gt=None, execution_date_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get a list of historical stock splits, including the ticker symbol, the execution date, and the factors of the split ratio. Official Docs
- Parameters:
ticker – Return the stock splits that contain this ticker. defaults to no ticker filter returning all.
execution_date – query by execution date. could be a date, datetime object or a string
YYYY-MM-DD
reverse_split – Query for reverse stock splits. A split ratio where split_from is greater than split_to represents a reverse split. By default this filter is not used.
order – Order results based on the sort field. defaults to ascending. See
polygon.enums.SortOrder
for choicessort – Sort field used for ordering. Defaults to ‘execution_date’. See
polygon.enums.SplitsSortKey
for choices.limit – Limit the size of the response, default is 1000 which is also the max.
Pagination
is supported by the pagination function belowticker_lt – filter where ticker name is less than given value (alphabetically)
ticker_lte – filter where ticker name is less than or equal to given value (alphabetically)
ticker_gt – filter where ticker name is greater than given value (alphabetically)
ticker_gte – filter where ticker name is greater than or equal to given value (alphabetically)
execution_date_lt – filter where execution date is less than given value
execution_date_lte – filter where execution date is less than or equal to given value
execution_date_gt – filter where execution date is greater than given value
execution_date_gte – filter where execution date is greater than or equal to given value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_market_holidays(raw_response: bool = False)
Get upcoming market holidays and their open/close times. Official Docs
- Parameters:
raw_response – whether 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)
Get the current trading status of the exchanges and overall financial markets. Official Docs
- Parameters:
raw_response – whether 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, condition_id=None, sip=None, order=None, limit: int = 50, sort='name', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, 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.condition_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.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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 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
Reference Async Client
- class polygon.reference_apis.reference_api.AsyncReferenceClient(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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. e.g.:
from polygon import ReferenceClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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.
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 data to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.pool_timeout – The pool timeout in seconds. Defaults to 10. Basically the number of seconds to wait while trying to get a connection from connection pool. Do NOT change if you’re unsure of what it implies
max_connections – Max number of connections in the pool. Defaults to NO LIMITS. Do NOT change if you’re unsure of application
max_keepalive – max number of allowable keep alive connections in the pool. Defaults to no limit. Do NOT change if you’re unsure of the applications.
write_timeout – The write timeout in seconds. Defaults to 10. basically the number of seconds to wait for data to be written/posted. Raises a
WriteTimeout
if unable to connect within the specified time limit.
- async get_tickers(symbol: str = '', ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, symbol_type='', market='', exchange: str = '', cusip: str | None = None, cik: str = '', date=None, search: str | None = None, active: bool = True, sort='ticker', order: str = 'asc', limit: int = 1000, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
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 e.g.
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 1000 which is also the max.
Pagination
is supported by the pagination function belowall_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_ticker_types(asset_class=None, locale=None, raw_response: bool = False)
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 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 get_ticker_details(symbol: str, date=None, raw_response: bool = False)
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 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 get_bulk_ticker_details(symbol: str, from_date=None, to_date=None, custom_dates: list | None = None, run_parallel: bool = True, warnings: bool = True, sort='asc', max_concurrent_workers: int = 10) OrderedDict
Get ticker details for a symbol for specified date range and/or dates. Each response will have detailed information about the ticker and the company behind it (on THAT particular date) Official Docs
- Parameters:
symbol – The ticker symbol to get data for
from_date – The start date of the date range. Must be specified if custom_dates is not supplied
to_date – The end date of the date range. Must be specified if custom_dates is not supplied
custom_dates – A list of dates, for which to get data for. You can specify this WITH a range. Each date can be a
date
,datetime
object or a stringYYYY-MM-DD
run_parallel – If true (the default), it will use coroutines/tasks to get the responses in parallel. Set to False to get all responses in sequence (will take time)
warnings – Defaults to True which prints warnings. Set to False to disable warnings.
sort – The order of sorting the final results. Defaults to ascending order of dates. See
polygon.enums.SortOrder
for choicesmax_concurrent_workers – This is only used if run_parallel is set to true. Controls how many worker coroutines are spawned in the internal thread pool. Defaults to
your cpu core count * 5
- Returns:
An OrderedDict where keys are dates, and values are corresponding ticker details.
- async get_option_contract(ticker: str, as_of_date=None, raw_response: bool = False)
get Info about an option contract Official Docs
- Parameters:
ticker – An option ticker in standard format. The lib provides easy functions to build and work with option symbols
as_of_date – Specify a point in time for the contract. You can pass a
datetime
ordate
object or a string in formatYYYY-MM-DD
. Defaults to today’s dateraw_response – whether 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 get_option_contracts(underlying_ticker: str | None = None, ticker: str | None = 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='expiration_date', limit=1000, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False, as_of_date=None)
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. defaults to expiration_datelimit – Limit the size of the response, default is 1000.
Pagination
is supported by the pagination function belowall_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.as_of_date – Specify a point in time for contracts as of this date with format YYYY-MM-DD. Defaults to today’s date.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_ticker_news(symbol: str | None = None, limit: int = 1000, 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, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
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 1000 which is also the max.
Pagination
is supported by the pagination function beloworder – 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
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_stock_dividends(ticker: str | None = None, ex_dividend_date=None, record_date=None, declaration_date=None, pay_date=None, frequency: int | None = None, limit: int = 1000, cash_amount=None, dividend_type=None, sort: str = 'pay_date', order: str = 'asc', ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, ex_dividend_date_lt=None, ex_dividend_date_lte=None, ex_dividend_date_gt=None, ex_dividend_date_gte=None, record_date_lt=None, record_date_lte=None, record_date_gt=None, record_date_gte=None, declaration_date_lt=None, declaration_date_lte=None, declaration_date_gt=None, declaration_date_gte=None, pay_date_lt=None, pay_date_lte=None, pay_date_gt=None, pay_date_gte=None, cash_amount_lt=None, cash_amount_lte=None, cash_amount_gt=None, cash_amount_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get a list of historical cash dividends, including the ticker symbol, declaration date, ex-dividend date, record date, pay date, frequency, and amount. Official Docs
- Parameters:
ticker – Return the dividends that contain this ticker.
ex_dividend_date – Query by ex-dividend date. could be a date, datetime object or a string
YYYY-MM-DD
record_date – Query by record date. could be a date, datetime object or a string
YYYY-MM-DD
declaration_date – Query by declaration date. could be a date, datetime object or a string
YYYY-MM-DD
pay_date – Query by pay date. could be a date, datetime object or a string
YYYY-MM-DD
frequency – Query by the number of times per year the dividend is paid out. No default value applied. see
polygon.enums.PayoutFrequency
for choiceslimit – Limit the size of the response, default is 1000 which is also the max.
Pagination
is supported by the pagination function belowcash_amount – Query by the cash amount of the dividend.
dividend_type – Query by the type of dividend. See
polygon.enums.DividendType
for choicessort – sort key used for ordering. See
polygon.enums.DividendSort
for choices.order – orders of results. defaults to asc. see
polygon.enums.SortOrder
for choicesticker_lt – filter where ticker is less than given value (alphabetically)
ticker_lte – filter where ticker is less than or equal to given value (alphabetically)
ticker_gt – filter where ticker is greater than given value (alphabetically)
ticker_gte – filter where ticker is greater than or equal to given value (alphabetically)
ex_dividend_date_lt – filter where ex-div date is less than given date
ex_dividend_date_lte – filter where ex-div date is less than or equal to given date
ex_dividend_date_gt – filter where ex-div date is greater than given date
ex_dividend_date_gte – filter where ex-div date is greater than or equal to given date
record_date_lt – filter where record date is less than given date
record_date_lte – filter where record date is less than or equal to given date
record_date_gt – filter where record date is greater than given date
record_date_gte – filter where record date is greater than or equal to given date
declaration_date_lt – filter where declaration date is less than given date
declaration_date_lte – filter where declaration date is less than or equal to given date
declaration_date_gt – filter where declaration date is greater than given date
declaration_date_gte – filter where declaration date is greater than or equal to given date
pay_date_lt – filter where pay date is less than given date
pay_date_lte – filter where pay date is less than or equal to given date
pay_date_gt – filter where pay date is greater than given date
pay_date_gte – filter where pay date is greater than or equal to given date
cash_amount_lt – filter where cash amt is less than given value
cash_amount_lte – filter where cash amt is less than or equal to given value
cash_amount_gt – filter where cash amt is greater than given value
cash_amount_gte – filter where cash amt is greater than or equal to given value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_stock_financials_vx(ticker: str | None = None, cik: str | None = None, company_name: str | None = None, company_name_search: str | None = None, sic: str | None = 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', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, 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
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 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.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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 get_stock_splits(ticker: str | None = None, execution_date=None, reverse_split: bool | None = None, order: str = 'asc', sort: str = 'execution_date', limit: int = 1000, ticker_lt=None, ticker_lte=None, ticker_gt=None, ticker_gte=None, execution_date_lt=None, execution_date_lte=None, execution_date_gt=None, execution_date_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get a list of historical stock splits, including the ticker symbol, the execution date, and the factors of the split ratio. Official Docs
- Parameters:
ticker – Return the stock splits that contain this ticker. defaults to no ticker filter returning all.
execution_date – query by execution date. could be a date, datetime object or a string
YYYY-MM-DD
reverse_split – Query for reverse stock splits. A split ratio where split_from is greater than split_to represents a reverse split. By default this filter is not used.
order – Order results based on the sort field. defaults to ascending. See
polygon.enums.SortOrder
for choicessort – Sort field used for ordering. Defaults to ‘execution_date’. See
polygon.enums.SplitsSortKey
for choices.limit – Limit the size of the response, default is 1000 which is also the max.
Pagination
is supported by the pagination function belowticker_lt – filter where ticker name is less than given value (alphabetically)
ticker_lte – filter where ticker name is less than or equal to given value (alphabetically)
ticker_gt – filter where ticker name is greater than given value (alphabetically)
ticker_gte – filter where ticker name is greater than or equal to given value (alphabetically)
execution_date_lt – filter where execution date is less than given value
execution_date_lte – filter where execution date is less than or equal to given value
execution_date_gt – filter where execution date is greater than given value
execution_date_gte – filter where execution date is greater than or equal to given value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_market_holidays(raw_response: bool = False)
Get upcoming market holidays and their open/close times - Async method Official Docs
- Parameters:
raw_response – whether 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 get_market_status(raw_response: bool = False)
Get the current trading status of the exchanges and overall financial markets - Async method Official Docs
- Parameters:
raw_response – whether 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 get_conditions(asset_class=None, data_type=None, condition_id=None, sip=None, order=None, limit: int = 50, sort='name', all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, 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.condition_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.all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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 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 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 Clients
Forex Sync Client
- class polygon.forex.forex_api.SyncForexClient(api_key: str, 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. e.g.:
from polygon import ForexClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, 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.
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: str | int | None = None, limit: int = 500, raw_response: bool = False)
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 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, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get NBBO Quotes for a forex ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want quotes for. e.g.:
C:EUR-USD
. you can pass with or without prefix C:timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.ForexQuotesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_last_quote(from_symbol: str, to_symbol: str, raw_response: bool = False)
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 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, full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False, raw_response: bool = False)
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. e.g.:
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 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.
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for a forex pair. For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the currency pair. e.g.:
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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False)
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 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 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)
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 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 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)
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 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)
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. e.g.:
C:EURUSD
. You can supply with or without prefixC:
.raw_response – whether 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)
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 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)
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 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_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Forex Async Client
- class polygon.forex.forex_api.AsyncForexClient(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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. e.g.:
from polygon import ForexClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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.
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 data to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.pool_timeout – The pool timeout in seconds. Defaults to 10. Basically the number of seconds to wait while trying to get a connection from connection pool. Do NOT change if you’re unsure of what it implies
max_connections – Max number of connections in the pool. Defaults to NO LIMITS. Do NOT change if you’re unsure of application
max_keepalive – max number of allowable keep alive connections in the pool. Defaults to no limit. Do NOT change if you’re unsure of the applications.
write_timeout – The write timeout in seconds. Defaults to 10. basically the number of seconds to wait for data to be written/posted. Raises a
WriteTimeout
if unable to connect within the specified time limit.
- async get_historic_forex_ticks(from_symbol: str, to_symbol: str, date, offset: str | int | None = None, limit: int = 500, raw_response: bool = False)
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 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 get_quotes(symbol: str, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get NBBO Quotes for a forex ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want quotes for. e.g.:
C:EUR-USD
. you can pass with or without prefix C:timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.ForexQuotesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_last_quote(from_symbol: str, to_symbol: str, raw_response: bool = False)
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 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 get_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='day', adjusted: bool = True, sort='asc', limit: int = 5000, full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False, raw_response: bool = False)
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. e.g.:
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 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.
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- async get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for a forex pair. For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the currency pair. e.g.:
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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- async get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_snapshot_all(symbols: list, raw_response: bool = False)
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 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 get_snapshot(symbol: str, raw_response: bool = False)
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. e.g.:
C:EURUSD
. You can supply with or without prefixC:
.raw_response – whether 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 get_gainers_and_losers(direction='gainers', raw_response: bool = False)
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 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 real_time_currency_conversion(from_symbol: str, to_symbol: str, amount: float, precision: int = 2, raw_response: bool = False)
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 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 get_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. Will be ignored iffull_range=True
- Returns:
The response object
- async get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for a forex ticker
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
C:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Crypto Clients
Crypto Sync Client
- class polygon.crypto.crypto_api.SyncCryptoClient(api_key: str, 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. e.g.:
from polygon import CryptoClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, 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.
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: str | int | None = None, limit: int = 500, raw_response: bool = False)
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 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_trades(symbol: str, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get trades for a crypto ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want trades for. e.g.
X:BTC-USD
. you can pass with or without the prefixC:
timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.CryptoTradesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- get_last_trade(from_symbol: str, to_symbol: str, raw_response: bool = False)
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 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)
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 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 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, full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False, raw_response: bool = False)
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. e.g.:
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 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.
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for a crypto pair. For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the currency pair. e.g.:
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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False)
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 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 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)
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. e.g.:
X:BTCUSD
. You can specify with or without the prefixX:
adjusted – whether 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 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)
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 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)
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. e.g.:
X:BTCUSD
. you can specify with or without prefixX:
raw_response – whether 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)
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 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)
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. e.g.:
X:BTCUSD
. You can specify with or without the prefix`X:
raw_response – Whether 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_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
Crypto Async Client
- class polygon.crypto.crypto_api.AsyncCryptoClient(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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. e.g.:
from polygon import CryptoClient
orimport polygon
(which allows you to access all names easily)- __init__(api_key: str, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: int | None = None, max_keepalive: int | None = None, write_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.
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 data to be received. Raises a
ReadTimeout
if unable to connect within the specified time limit.pool_timeout – The pool timeout in seconds. Defaults to 10. Basically the number of seconds to wait while trying to get a connection from connection pool. Do NOT change if you’re unsure of what it implies
max_connections – Max number of connections in the pool. Defaults to NO LIMITS. Do NOT change if you’re unsure of application
max_keepalive – max number of allowable keep alive connections in the pool. Defaults to no limit. Do NOT change if you’re unsure of the applications.
write_timeout – The write timeout in seconds. Defaults to 10. basically the number of seconds to wait for data to be written/posted. Raises a
WriteTimeout
if unable to connect within the specified time limit.
- async get_historic_trades(from_symbol: str, to_symbol: str, date, offset: str | int | None = None, limit: int = 500, raw_response: bool = False)
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 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 get_trades(symbol: str, timestamp: int | None = None, order=None, sort=None, limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get trades for a crypto ticker symbol in a given time range. Official Docs
- Parameters:
symbol – The ticker symbol you want trades for. e.g.
X:BTC-USD
. you can pass with or without the prefixC:
timestamp – Query by trade timestamp. Could be
datetime
ordate
or stringYYYY-MM-DD
or a nanosecond timestamporder – sort order. see
polygon.enums.SortOrder
for available choices. defaults to Nonesort – field key to sort against. Defaults to None. see
polygon.enums.CryptoTradesSort
for choiceslimit – Limit the size of the response, max 50000 and default 5000.
timestamp_lt – return results where timestamp is less than the given value. Can be date or date string or nanosecond timestamp
timestamp_lte – return results where timestamp is less than/equal to the given value. Can be date or date string or nanosecond timestamp
timestamp_gt – return results where timestamp is greater than the given value. Can be date or date string or nanosecond timestamp
timestamp_gte – return results where timestamp is greater than/equal to the given value. Can be date or date string or nanosecond timestamp
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – whether 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. This is ignored if pagination is set to True.
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. If pagination is set to True, will return a merged response of all pages for convenience.
- async get_last_trade(from_symbol: str, to_symbol: str, raw_response: bool = False)
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 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 get_daily_open_close(from_symbol: str, to_symbol: str, date, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='day', adjusted: bool = True, sort='asc', limit: int = 5000, full_range: bool = False, run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False, raw_response: bool = False)
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. e.g.:
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 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.
full_range – Default False. If set to True, it will get the ENTIRE range you specify and merge all the responses and return ONE single list with all data in it. You can control its behavior with the next few arguments.
run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
raw_response – whether 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. Will be ignored iffull_range=True
- Returns:
A JSON decoded Dictionary by default. Make
raw_response=True
to get underlying response object. Iffull_range=True
, will return a single list with all the candles in it.
- async get_full_range_aggregate_bars(symbol: str, from_date, to_date, multiplier: int = 1, timespan='min', adjusted: bool = True, sort='asc', run_parallel: bool = True, max_concurrent_workers: int = 10, info: bool = True, warnings: bool = True, high_volatility: bool = False)
Get BULK full range aggregate bars (OCHLV candles) for a crypto pair. For example, if
timespan=‘minute’
andmultiplier=‘1’
then 5-minute bars will be returned. Official Docs- Parameters:
symbol – The ticker symbol of the currency pair. e.g.:
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 minute candles. see
polygon.enums.Timespan
for choicesadjusted – Whether 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)run_parallel – Only considered if
full_range=True
. If set to true (default True), it will run an internal ThreadPool to get the responses. This is fine to do if you are not running your own ThreadPool. If you have many tickers to get aggs for, it’s better to either use the async version of it OR set this to False and spawn threads for each ticker yourself.max_concurrent_workers – Only considered if
run_parallel=True
. Defaults toyour cpu cores * 5
. controls how many worker threads to use in internal ThreadPoolinfo – Set to False to disable printing mild warnings / informational messages if any when fetching the aggs. E.g. if there was no data in a response but the response had an OK status
warnings – Set to False to disable printing warnings if any when fetching the aggs. Defaults to True.
high_volatility – Specifies whether the symbol/security in question is highly volatile which just means having a very high number of trades or being traded for a high duration (e.g. SPY, Bitcoin) If set to True, the lib will use a smaller chunk of time to ensure we don’t miss any data due to 50k candle limit. Defaults to False.
- Returns:
a single list with all the candles.
- async get_grouped_daily_bars(date, adjusted: bool = True, raw_response: bool = False)
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 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 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 get_previous_close(symbol: str, adjusted: bool = True, raw_response: bool = False)
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. e.g.:
X:BTCUSD
. You can specify with or without the prefixX:
adjusted – whether 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 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 get_snapshot_all(symbols: list, raw_response: bool = False)
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 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 get_snapshot(symbol: str, raw_response: bool = False)
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. e.g.:
X:BTCUSD
. you can specify with or without prefixX:
raw_response – whether 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 get_gainers_and_losers(direction='gainers', raw_response: bool = False)
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 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 get_level2_book(symbol: str, raw_response: bool = False)
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. e.g.:
X:BTCUSD
. You can specify with or without the prefix`X:
.raw_response – whether 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 get_sma(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Simple Moving Average for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the simple moving average are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the simple moving average (SMA). i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the SMA. The default
close
will result in using close prices to calculate the SMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the SMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_ema(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Exponential Moving Average for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the EMA are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the EMA. i.e. a window size of 10 with daily aggregates would result in a 10 day moving average.
series_type – The prices in the aggregate which will be used to calculate the EMA. The default
close
will result in using close prices to calculate the EMA. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the EMA.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_rsi(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, window_size: int = 14, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Relative Strength Index for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the RSI are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.window_size – The window size used to calculate the RSI. i.e. a window size of 14 with daily aggregates would result in a 14 day RSI.
series_type – The prices in the aggregate which will be used to calculate the RSI. The default
close
will result in using close prices to calculate the RSI. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the RSI.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The response object
- async get_macd(symbol: str, timestamp=None, timespan='day', adjusted: bool = True, long_window_size: int = 50, series_type='close', include_underlying: bool = False, order='desc', limit: int = 5000, timestamp_lt=None, timestamp_lte=None, timestamp_gt=None, timestamp_gte=None, short_window_size: int = 50, signal_window_size: int = 50, all_pages: bool = False, max_pages: int | None = None, merge_all_pages: bool = True, verbose: bool = False, raw_page_responses: bool = False, raw_response: bool = False)
Get the Moving Average Convergence/Divergence for a crypto pair
- Parameters:
symbol – The option symbol. You can pass it with or without the prefix
X:
.timestamp – Either a date with the format
YYYY-MM-DD
or a millisecond timestamp.timespan – Size of the aggregate time window. defaults to ‘day’. See
polygon.enums.Timespan
for choicesadjusted – Whether the aggregates used to calculate the MACD are adjusted for splits. By default, aggregates are adjusted. Set this to
False
to get results that are NOT adjusted for splits.long_window_size – The long window size used to calculate the MACD data
series_type – The prices in the aggregate which will be used to calculate the MACD. The default
close
will result in using close prices to calculate the MACD. Seepolygon.enums.SeriesType
for choicesinclude_underlying – Whether to include the OCHLV aggregates used to calculate this indicator in the response. Defaults to False which only returns the MACD.
order – The order in which to return the results, ordered by timestamp. See
polygon.enums.SortOrder
for choices. Defaults to Descending (most recent first)limit – Limit the number of results returned, default is 5000 which is also the max
timestamp_lt – Only use results where timestamp is less than supplied value
timestamp_lte – Only use results where timestamp is less than or equal to supplied value
timestamp_gt – Only use results where timestamp is greater than supplied value
timestamp_gte – Only use results where timestamp is greater than or equal to supplied value
short_window_size – The short window size used to calculate the MACD data
signal_window_size – The window size used to calculate the MACD signal line.
all_pages – Whether to paginate through next/previous pages internally. Defaults to False. If set to True, it will try to paginate through all pages and merge all pages internally for you.
max_pages – how many pages to fetch. Defaults to None which fetches all available pages. Change to an integer to fetch at most that many pages. This param is only considered if
all_pages
is set to Truemerge_all_pages – If this is True, returns a single merged response having all the data. If False, returns a list of all pages received. The list can be either a list of response objects or decoded data itself, controlled by parameter
raw_page_responses
. This argument is Only considered ifall_pages
is set to True. Default: Trueverbose – Set to True to print status messages during the pagination process. Defaults to False.
raw_page_responses – If this is true, the list of pages will be a list of corresponding Response objects. Else, it will be a list of actual data for pages. This parameter is only considered if
merge_all_pages
is set to False. Default: Falseraw_response – Whether 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:
The 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. e.g.:
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 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.', force_uppercase_symbols: bool = True)
Internal Function to send subscribe or unsubscribe requests to websocket. You should prefer using the corresponding methods to subscribe or unsubscribe to stream.
- 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.force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- subscribe_stock_trades(symbols: list | None = None, force_uppercase_symbols: bool = True)
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 marketforce_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_stock_trades(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_quotes(symbols: list | None = None, force_uppercase_symbols: bool = True)
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
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_stock_quotes(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_minute_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
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
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_stock_minute_aggregates(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_second_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
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
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_stock_second_aggregates(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_limit_up_limit_down(symbols: list | None = None, force_uppercase_symbols: bool = True)
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
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_stock_limit_up_limit_down(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_stock_imbalances(symbols: list | None = None, force_uppercase_symbols: bool = True)
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
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_stock_imbalances(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- subscribe_option_trades(symbols: list | None = None, force_uppercase_symbols: bool = True)
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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_option_trades(symbols: list | None = 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_quotes(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Options Quotes 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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_option_quotes(symbols: list | None = None)
Unsubscribe real-time Options Quotes 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: list | None = None, force_uppercase_symbols: bool = True)
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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_option_minute_aggregates(symbols: list | None = 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: list | None = None, force_uppercase_symbols: bool = True)
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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_option_second_aggregates(symbols: list | None = 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: list | None = None, force_uppercase_symbols: bool = True)
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
.force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_forex_quotes(symbols: list | None = 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
.
- subscribe_forex_minute_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
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
.force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_forex_minute_aggregates(symbols: list | None = 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
.
- subscribe_crypto_trades(symbols: list | None = None, force_uppercase_symbols: bool = True)
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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_crypto_trades(symbols: list | None = 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: list | None = None, force_uppercase_symbols: bool = True)
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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_crypto_quotes(symbols: list | None = 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: list | None = None, force_uppercase_symbols: bool = True)
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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_crypto_minute_aggregates(symbols: list | None = 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: list | None = None, force_uppercase_symbols: bool = True)
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:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- unsubscribe_crypto_level2_book(symbols: list | None = 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: WebSocketApp, msg)
Default handler for message processing
- Parameters:
msg – The message as received from the server
- Returns:
None
- static _default_on_close(_ws: 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: 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: 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: str | ~enum.Enum | float | int, allowed_type=<class 'str'>)
Async Streamer Client
- class polygon.streaming.async_streaming.AsyncStreamClient(api_key: str, cluster, host='socket.polygon.io', ping_interval: int | None = 20, ping_timeout: int | None = 19, max_message_size: int = 1048576, max_memory_queue: int | None = 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. e.g.:
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 | None = 20, ping_timeout: int | None = 19, max_message_size: int = 1048576, max_memory_queue: int | None = 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: str | None = 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 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: str | list | None, action: str = 'subscribe', _prefix: str = 'T.', force_uppercase_symbols: bool = True)
Internal Function to send subscribe or unsubscribe requests to websocket. You should prefer using the corresponding methods to subscribe or unsubscribe to stream.
- 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.force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async subscribe_stock_trades(symbols: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_stock_trades(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_stock_quotes(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_stock_minute_aggregates(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_stock_second_aggregates(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_stock_limit_up_limit_down(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_stock_imbalances(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_option_trades(symbols: list | None = 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_quotes(symbols: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
Get Real time options quotes 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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_option_quotes(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_option_minute_aggregates(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_option_second_aggregates(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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
.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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_forex_quotes(symbols: list | None = 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
.- Returns:
None
- async subscribe_forex_minute_aggregates(symbols: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_forex_minute_aggregates(symbols: list | None = 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
.- Returns:
None
- async subscribe_crypto_trades(symbols: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_crypto_trades(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_crypto_quotes(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_crypto_minute_aggregates(symbols: list | None = 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: list | None = None, handler_function=None, force_uppercase_symbols: bool = True)
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.
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- async unsubscribe_crypto_level2_book(symbols: list | None = 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.IndexSnapshotSortKey(value)
Sort field for method:
IndexClient.get_snapshot()
- TICKER = 'ticker'
- 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.PaginationDirection(value)
The direction to paginate in.
- NEXT = 'next'
- FORWARD = 'next'
- PREV = 'previous'
- PREVIOUS = 'previous'
- BACKWARD = 'previous'
- 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.OptionQuotesSort(value)
Sort field used for ordering option quotes. Used for method:
OptionsClient.get_quotes
- TIMESTAMP = 'timestamp'
- class polygon.enums.StocksTradesSort(value)
Sort field used for ordering Stocks trades. Used for method:
StocksClient.get_trades
- TIMESTAMP = 'timestamp'
- class polygon.enums.StocksQuotesSort(value)
Sort field used for ordering Stocks quotes. Used for method:
StocksClient.get_quotes
- TIMESTAMP = 'timestamp'
- class polygon.enums.SplitsSortKey(value)
Sort field used for ordering stock splits. Used for method
ReferenceClient.get_stock_splits
- EXECUTION_DATE = 'execution_date'
- TICKER = 'ticker'
- class polygon.enums.PayoutFrequency(value)
the number of times per year the dividend is paid out. Possible values are 0 (one-time), 1 (annually), 2 (bi-annually), 4 (quarterly), and 12 (monthly). used by method
ReferenceClient.get_stock_dividends
- ONE_TIME = 0
- ANNUALLY = 1
- BI_ANNUALLY = 2
- QUARTERLY = 4
- MONTHLY = 12
- class polygon.enums.DividendType(value)
the type of dividend. Dividends that have been paid and/or are expected to be paid on consistent schedules are denoted as CD. Special Cash dividends that have been paid that are infrequent or unusual, and/or can not be expected to occur in the future are denoted as SC. Used for method
ReferenceClient.get_stock_dividends
- CD = 'CD'
- SC = 'SC'
- LT = 'LT'
- ST = 'ST'
- class polygon.enums.DividendSort(value)
sort field used for ordering dividend results. used for method
ReferenceClient.get_stock_dividends
- EX_DIVIDEND_DATE = 'ex_dividend_date'
- PAY_DATE = 'pay_date'
- DECLARATION_DATE = 'declaration_date'
- RECORD_DATE = 'record_date'
- CASH_AMOUNT = 'cash_amount'
- TICKER = 'ticker'
- class polygon.enums.ForexQuotesSort(value)
Sort field used for ordering Forex quotes. Used for method:
ForexClient.get_quotes
- TIMESTAMP = 'timestamp'
- class polygon.enums.CryptoTradesSort(value)
Sort field used for ordering crypto trades. Used for method:
CryptoClient.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_QUOTES = 'Q'
- OPTION_MINUTE_AGGREGATES = 'AM'
- OPTION_SECOND_AGGREGATES = 'A'
- class polygon.enums.Timespan(value)
The timespan values. Usually meant for aggregates endpoints. It is best to consult the relevant docs before using any value on an endpoint.
- SECOND = 'second'
- MINUTE = 'minute'
- MIN = 'minute'
- HOUR = 'hour'
- DAY = 'day'
- WEEK = 'week'
- MONTH = 'month'
- QUARTER = 'quarter'
- YEAR = 'year'
- class polygon.enums.OptionSymbolFormat(value)
Option symbol formats supported by the library. To be used with functions to build or parse option symbols
- POLYGON = 'polygon'
- TDA = 'tda'
- TD_AMERITRADE = 'tda'
- TOS = 'tos'
- THINK_OR_SWIM = 'tos'
- TRADIER = 'tradier'
- TRADE_STATION = 'trade_station'
- IB = 'ibkr'
- IBKR = 'ibkr'
- INTERACTIVE_BROKERAGE = 'ibkr'