Options

Read this page to know everything you need to know about using the various Options HTTP endpoints.

See Async Support for REST endpoints for asynchronous use cases.

Docs below assume you have already read getting started page and know how to create the client. If you do not know how to create the client, first see General guide for clients and create client as below. As always you can have all 5 different clients together.

import polygon

options_client = polygon.OptionsClient('KEY')  # for usual sync client
async_options_client = polygon.OptionsClient('KEY', True)  # for an async client

here is how the client initializer looks like:

polygon.options.options.OptionsClient(api_key: str, use_async: bool = False, connect_timeout: int = 10, read_timeout: int = 10, pool_timeout: int = 10, max_connections: Optional[int] = None, max_keepalive: Optional[int] = None, write_timeout: int = 10)

Initiates a Client to be used to access all REST options endpoints.

Parameters
  • api_key – Your API Key. Visit your dashboard to get yours.

  • use_async – Set it to True to get async client. Defaults to usual non-async client.

  • connect_timeout – The connection timeout in seconds. Defaults to 10. basically the number of seconds to wait for a connection to be established. Raises a ConnectTimeout if unable to connect within specified time limit.

  • read_timeout – The read timeout in seconds. Defaults to 10. basically the number of seconds to wait for date to be received. Raises a ReadTimeout if unable to connect within the specified time limit.

  • 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.

NOTE if you don’t want to use the option symbol helper functions, then you can just go to the desired endpoint documentation from the list to left

Creating Option Symbols

So when you’re working with options (rest/websockets), you’ll certainly need the option symbols which contain the information about their underlying symbol, expiry, call_or_put and the strike price in a certain format. Many organizations tend to use different formats to represent these.

Polygon.io tends to use This Format . For those who want to understand how this formatting works, Here is a guide (thanks to Ian from their support team).

Fortunately for you, the library comes with a few functions to help ya out with it. first function in that list is creating an option symbol

The library also has two bonus functions which allow you to create and parse option symbols using the format supported by TD Ameritrade. See below for more info on how to use them.

Building polygon formatted option symbols

Note that polygon has a rest endpoint in reference API to get all active contracts which you can filter based on many values.

You might have noticed (you didn’t notice, did ya?) that polygon endpoints expect a prefix: O: before option symbols. For convenience, this library handles all of it internally. what that means for you is that you can pass in option symbols with or without the prefix O: and both will be handled. In the below function, you can make the argument prefix_o=True to get the prefix in the output. By defaults it returns this format: AMD211205P00149000 (example symbol)

here is how the function looks. just supply the details.

polygon.options.options.build_option_symbol(underlying_symbol: str, expiry, call_or_put, strike_price, prefix_o: bool = False)

Build the option symbol from the details provided.

Parameters
  • underlying_symbol – The underlying stock ticker symbol.

  • expiry – The expiry date for the option. You can pass this argument as datetime.datetime or datetime.date object. Or a string in format: YYMMDD. Using datetime objects is recommended.

  • call_or_put – The option type. You can specify: c or call or p or put. Capital letters are also supported.

  • strike_price – The strike price for the option. ALWAYS pass this as one number. 145, 240.5, 15.003, 56, 129.02 are all valid values. It shouldn’t have more than three numbers after decimal point.

  • prefix_o – Whether or not to prefix the symbol with ‘O:’. It is needed by polygon endpoints. However all the library functions will automatically add this prefix if you pass in symbols without this prefix.

Returns

The option symbol in the format specified by polygon

Example use:

from polygon import build_option_symbol

symbol = build_option_symbol('AMD', date(year=2021, month=12, day=5), 'c', 158)  # date is just a datetime.date object

# another one!
symbol = build_option_symbol('NVDA', '211205', 'call', 124.56)
# you can use these variable as you like on polygon's endpoints

Building TDA formatted option symbols

don’t use this formatting on polygon endpoints. only on td ameritrade. this is just a bonus function.

polygon.options.options.build_option_symbol_for_tda(underlying_symbol: str, expiry, call_or_put, strike_price, format_: str = 'underscore')

Only use this function if you need to create option symbol for TD ameritrade API. This function is just a bonus.

Parameters
  • underlying_symbol – The underlying stock ticker symbol.

  • expiry – The expiry date for the option. You can pass this argument as datetime.datetime or datetime.date object. Or a string in format: MMDDYY. Using datetime objects is recommended.

  • call_or_put – The option type. You can specify: c or call or p or put. 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.

  • format – tda has two formats. one having an underscore in between (used by TDA API). and other starts with a dot (.). Defaults to the underscore format. If you’re not sure, leave to default. Pass 'dot' to get dot format.

Returns

The option symbol built in the format supported by TD Ameritrade.

Example use:

from polygon import build_option_symbol_for_tda

symbol = build_option_symbol_for_tda('AMD', date(year=2021, month=12, day=5), 'c', 158)  # date is just a datetime.date object

# another one!
symbol = build_option_symbol_for_tda('NVDA', '120522', 'call', 124.56)

Parsing Option Symbols

So the above function was to build an option symbol from details. This function would help you do the opposite. That is, extracting information from an option symbol.

This function parses the symbol based on This spec. Note that you can pass the value with or without the O: prefix. The lib would handle that like it does everywhere else.

parsing Polygon formatted option symbols

Important So it appears that some option symbols as returned by polygon endpoints happen to have a correction number within the symbol. The additional number is always between the underlying symbol and expiry. The lib handles that for you and hence returns the corrected parsed symbol.

To elaborate: sometimes you’d see something like: MS1221015C00234000. Notice the extra 1 right after symbol MS and before expiry 221015. This symbol should actually be MS221015C00234000 without that 1 (which could be any number based on the info I have from support team).

If you ever need to get the corrected symbol without that additional number, use the lib to parse the symbol and the attribute option_symbol would contain the full option symbol without the extra number and any prefixes.

By default the expiry date in the results would be a datetime.date object. Change it to string to get a string in format YYYY-MM-DD

You can choose to get your output in any one out of 3 different formats provided by the lib. To change the format, change the output_format arg in the function below.

The OptionSymbol object (default)

by default it would return a polygon.options.options.OptionSymbol object. The object would allow you to access values using attributes. For example: parsed_symbol.expiry, parsed_symbol.underlying_symbol, parsed_symbol.strike_price, parsed_symbol.call_or_put and parse_symbol.option_symbol

output as a list

You can also choose to get your output as a list. The list would just have all the parsed values as: [underlying_symbol, expiry, call_or_put, strike_price, option_symbol]

output as a dict

You can also choose to get your results as a dict. The dict will have all the values as usual pairs. keys would be: 'underlying_symbol', 'strike_price', 'expiry', 'call_or_put', 'option_symbol'

While other values are self explanatory, the value option_symbol in parsed symbol is simply the full option symbol without any extra correction numbers or prefixes. For example if you passed in MS221015C00234000, option_symbol attribute will have the exact same value supplied. If you passed MS1221015C00234000 or O:MS221015C00234000, option_symbol would have MS221015C00234000 removing those extra numbers and prefixes.

here is how the function looks.

polygon.options.options.parse_option_symbol(option_symbol: str, output_format='object', expiry_format='date')

Function to parse an option symbol.

Parameters
  • option_symbol – the symbol you want to parse. Both TSLA211015P125000 and O:TSLA211015P125000 are valid

  • output_format – Output format of the result. defaults to object. Set it to dict or list as needed.

  • expiry_format – The format for the expiry date in the results. Defaults to date object. change this param to string to get the value as a string: YYYY-MM-DD

Returns

The parsed values either as an object, list or a dict as indicated by output_format.

Example use:

from polygon import (build_option_symbol, parse_option_symbol)

parsed_details = parse_option_symbol('AMD211205C00156000')

# another one!
parsed_details = parse_option_symbol('AMD211205C00156000', output_format=list)

# another one!
parsed_details = parse_option_symbol('AMD211205C00156000', dict, expiry_format=str)

parsing TDA formatted option symbols

don’t use this function on polygon endpoints. this is a bonus function meant for td ameritrade formatting.

The output_format and expiry_format have the same behavior as above. Only difference is in the formatting.

the dot format (symbol starting with a ., usually found when you export some file through ThinkOrSwim or similar tda tool) is also supported

polygon.options.options.parse_option_symbol_from_tda(option_symbol: str, output_format='object', expiry_format='date')

Function to parse an option symbol in format supported by TD Ameritrade.

Parameters
  • option_symbol – the symbol you want to parse. Both TSLA211015P125000 and O:TSLA211015P125000 are valid

  • output_format – Output format of the result. defaults to object. Set it to dict or list as needed.

  • expiry_format – The format for the expiry date in the results. Defaults to date object. change this param to string to get the value as a string: YYYY-MM-DD

Returns

The parsed values either as an object, list or a dict as indicated by output_format.

Example use:

from polygon import parse_option_symbol_from_tda

parsed_details = parse_option_symbol_from_tda('GOOG_012122P620')

# another one!
parsed_details = parse_option_symbol_from_tda('.AMD220128P81', output_format=list)  # DOT format from ThinkOrSwim

# another one!
parsed_details = parse_option_symbol_from_tda('SPY_121622C335', dict, expiry_format=str)

Converting option symbol formats

As a bonus function in the library, you can use the below functions to convert from polygon.io option symbol format to the TD Ameritrade option symbol format and vice versa.

this is useful for people who use TDA API for brokerage and polygon as their data source. If you need a python package to work with TDA API, check out tda-api by Alex Golec.

Converting from polygon to TDA format

you might wanna use this when you want to place a trade on TDA for example using data from polygon.

polygon.options.options.convert_from_polygon_to_tda_format(option_symbol: str, format_: str = 'underscore')

Helper function to convert from polygon.io symbol format to TD Ameritrade symbol format. Useful for writing applications which make use of both the APIs

Parameters
  • option_symbol – The option symbol. This must be in the format supported by polygon.io

  • format – tda has two formats. one having an underscore in between (used by TDA API). and other starts with a dot (.). Defaults to the underscore format. If you’re not sure, leave to default. Pass 'dot' to get dot format.

Returns

The formatted symbol converted to TDA symbol format.

Converting from TDA to polygon format

for when you grab a option symbol from tda, and want to get relevant data from polygon

polygon.options.options.convert_from_tda_to_polygon_format(option_symbol: str, prefix_o: bool = False)

Helper function to convert from TD Ameritrade symbol format to polygon format. Useful for writing applications which make use of both the APIs

Parameters
  • option_symbol – The option symbol. This must be in the format supported by TD Ameritrade

  • prefix_o – Whether or not to add the prefix O: in front of created symbol

Returns

The formatted symbol converted to polygon’s symbol format.

Detecting what format is a symbol in

as the name suggests, when you want to programmatically determine what format is a symbol in. Might be useful for symbol lookups, for instance.

polygon.options.options.detect_symbol_format(option_symbol: str) Union[str, bool]

Detect what format a symbol is formed in. Returns polygon or tda depending on which format the symbol is in. Returns False if the format doesn’t match any of the two supported.

Parameters

option_symbol – The option symbol to check.

Returns

tda or polygon if format is recognized. False otherwise.

Endpoints

To use any of the below method, simply call it on the client you created above. so if you named your client client, you’d call the methods as client.get_trades and so on. Async methods will need to be awaited, see Async Support for REST endpoints.

Get Trades

This endpoint supports pagination. Passing all_pages=True enables it. See Pagination Support for better info

SyncOptionsClient.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: Optional[int] = 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 eg O:TSLA210903C00700000. you can pass the symbol with or without the prefix O:

  • timestamp – Query by trade timestamp. You can supply a date, datetime object or a nanosecond 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. See polygon.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 True

  • merge_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 if all_pages is set to True. Default: True

  • verbose – 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: False

  • raw_response – Whether or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary. 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

This endpoint supports pagination. Passing all_pages=True enables it. See Pagination Support for better info

SyncOptionsClient.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: Optional[int] = 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 eg O:TSLA210903C00700000. you can pass the symbol with or without the prefix O:

  • timestamp – Query by quote timestamp. You can supply a date, datetime object or a nanosecond 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. See polygon.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 True

  • merge_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 if all_pages is set to True. Default: True

  • verbose – 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: False

  • raw_response – Whether or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary. 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

SyncOptionsClient.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 or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.

Returns

Either a Dictionary or a Response object depending on value of raw_response. Defaults to Dict.

Get Daily Open Close

SyncOptionsClient.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. eg O:FB210903C00700000. You can pass it with or without the prefix O:

  • date – The date/day of the daily-OCHLV to retrieve. Could be datetime or date or string YYYY-MM-DD

  • adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.

  • raw_response – Whether or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.

Returns

A JSON decoded Dictionary by default. Make raw_response=True to get underlying response object

Get Aggregate Bars

The library added a better aggregate function if you’re looking to get data for large time frames at minute/hour granularity.

(for example 15 years historical data , 1 minute candles)

See Better Aggregate Bars function for complete details on how to use it well and control how it behaves.

SyncOptionsClient.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, 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’ and multiplier = ‘5’ then 5-minute bars will be returned. Official Docs

Parameters
  • symbol – The ticker symbol of the contract. eg O:FB210903C00700000. You can pass in with or without the prefix O:

  • from_date – The start of the aggregate time window. Could be datetime or date or string YYYY-MM-DD

  • to_date – The end of the aggregate time window. Could be datetime or date or string YYYY-MM-DD

  • adjusted – Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.

  • sort – Sort the results by timestamp. See polygon.enums.SortOrder for choices. asc default.

  • limit – Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000. 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 to day

  • 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 to your cpu cores * 5. controls how many worker threads to use in internal ThreadPool

  • 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 (eg 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 or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary. Will be ignored if full_range=True

Returns

A JSON decoded Dictionary by default. Make raw_response=True to get underlying response object. If full_range=True, will return a single list with all the candles in it.

Get Previous Close

SyncOptionsClient.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 or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.

  • raw_response – Whether or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary.

Returns

Either a Dictionary or a Response object depending on value of raw_response. Defaults to Dict.

Get Snapshot

This endpoint supports pagination. Passing all_pages=True enables it. See Pagination Support for better info

SyncOptionsClient.get_snapshot(underlying_symbol: str, option_symbol: str, all_pages: bool = False, max_pages: Optional[int] = 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. eg AMD

  • option_symbol – the option symbol. You can use use the Creating 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 True

  • merge_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 if all_pages is set to True. Default: True

  • verbose – 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: False

  • raw_response – Whether or not to return the Response Object. Useful for when you need to say check the status code or inspect the headers. Defaults to False which returns the json decoded dictionary. 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.