Market Data

TD Ameritrade provides various endpoints to obtain Market Data for various instruments and markets across asset classes.

Endpoints

  1. Quotes
  2. Market Movers
  3. Market Hours
  4. Option Chains
  5. Price History
  6. Fundamentals

Quotes

The Get Quote and Get Quotes endpoints provide real-time and delayed quotes. Access is provided by pyTD through the top-level function get_quotes, which combines functionality of the two endpoints.

pyTD.market.get_quotes(*args, **kwargs)

Function for retrieving quotes from the Get Quotes endpoint.

Parameters:
  • symbols (str, array-like object (list, tuple, Series), or DataFrame) – Single stock symbol (ticker), array-like object of symbols or DataFrame with index containing up to 100 stock symbols.
  • output_format (str, default 'pandas', optional) – Desired output format (json or DataFrame)
  • kwargs (additional request parameters (see _TDBase class)) –

Examples

Single Stock

In [1]: from pyTD.market import get_quotes

In [2]: get_quotes("AAPL").head()
Out[2]: 
            AAPL
52WkHigh  233.47
52WkLow      142
askId          P
askPrice   152.6
askSize     2500

Multiple Stocks

In [3]: get_quotes(["AAPL", "TSLA"]).head()
Out[3]: 
            AAPL    TSLA
52WkHigh  233.47  387.46
52WkLow      142  244.59
askId          P       K
askPrice   152.6     290
askSize     2500     200

Movers

The Get Movers endpoint provides market movers (up or down) for a specified index. Access is provided by pyTD through the top-level function get_movers.

Format - ‘json’ (dictionary) or ‘pandas’ (Pandas DataFrame)

pyTD.market.get_movers(*args, **kwargs)

Function for retrieving market moveers from the Movers endpoint

Parameters:
  • index (str) – The index symbol to get movers from
  • direction (str, default up, optional) – Return up or down movers
  • change (str, default percent, optional) – Return movers by percent change or value change
  • output_format (str, default 'pandas', optional) – Desired output format (json or DataFrame)
  • kwargs (additional request parameters (see _TDBase class)) –

Note

The desired index should be prefixed with $. For instance, the Dow Jones Industrial Average is $DJI.

Warning

This endpoint may return empty outside of Market Hours.

Examples

In [4]: from pyTD.market import get_movers

In [5]: get_movers("$DJI")
Out[5]: 
          change     ...     totalVolume
symbol               ...                
CVX     0.018942     ...         8470714
V       0.008540     ...         4925199
MCD     0.008437     ...         3214190
TRV     0.006294     ...         1621000
CAT     0.005158     ...         3943630
CSCO    0.002200     ...        17360572
HD      0.002035     ...         3860309
NKE     0.001863     ...         4753325
MMM     0.001196     ...         1582949
GS      0.001067     ...         2632011

[10 rows x 5 columns]

Hours

The Get Market Hours endpoint provides market hours for various markets, including equities, options, and foreign exchange (forex). Access is provided by pyTD through the top-level function get_market_hours.

By default, get_market_hours returns the market hours of the current date, but can do so for any past or future date when passed the optional keyword argument date.

pyTD.market.get_market_hours(*args, **kwargs)

Function to retrieve market hours for a given market from the Market Hours endpoint

Parameters:
  • market (str, default EQUITY, optional) – The market to retrieve operating hours for
  • date (string or DateTime object, (defaults to today's date)) – Operating date, timestamp. Parses many different kind of date representations (e.g., ‘JAN-01-2015’, ‘1/1/15’, ‘Jan, 1, 1980’)
  • output_format (str, default 'pandas', optional) – Desired output format (json or DataFrame)
  • kwargs (additional request parameters (see _TDBase class)) –

Examples

In [6]: from pyTD.market import get_market_hours

In [7]: get_market_hours("EQUITY")
Out[7]: 
                                                         equity
category                                                   NULL
date                                                 2019-01-24
exchange                                                   NULL
isOpen                                                     True
marketType                                               EQUITY
product                                                      EQ
productName                                              equity
sessionHours  {'preMarket': [{'start': '2019-01-24T07:00:00-...

Option Chains

The Get Option Chains endpoint provides option chains for optionable equities symbols. Access is provided by pyTD through the top-level function get_option_chains.

get_option_chains accepts a variety of arguments, which allow filtering of the results by criteria such as strike price, moneyness, and expiration date, among others. Futher, it is possible to specify certain parameters to be used in calculations for analytical strategy chains.

pyTD.market.get_option_chains(*args, **kwargs)

Function to retrieve option chains for a given symbol from the Option Chains endpoint

Parameters:
  • contractType (str, default ALL, optional) – Desired contract type (CALL, PUT, ALL)
  • strikeCount (int, optional) – Number of strikes to return above and below the at-the-money price
  • includeQuotes (bool, default False, optional) – Include quotes for options in the option chain
  • strategy (str, default None, optional) – Passing a value returns a strategy chain (SINGLE or ANALYTICAL)
  • interval (int, optional) – Strike interval for spread strategy chains
  • strike (float, optional) – Filter options that only have a certain strike price
  • range (str, optional) – Returns options for a given range (ITM, OTM, etc.)
  • fromDate (str or datetime.datetime object, optional) – Only return options after this date
  • toDate (str or datetime.datetime object, optional) – Only return options before this date
  • volatility (float, optional) – Volatility to use in calculations (for analytical strategy chains)
  • underlyingPrice (float, optional) – Underlying price to use in calculations (for analytical strategy chains)
  • interestRate (float, optional) – Interest rate to use in calculations (for analytical strategy chains)
  • daysToExpiration (int, optional) – Days to expiration to use in calulations (for analytical strategy chains)
  • expMonth (str, optional) – Expiration month (format JAN, FEB, etc.) to use in calculations (for analytical strategy chains), default ALL
  • optionType (str, optional) – Type of contracts to return (S: standard, NS: nonstandard, ALL: all contracts)
  • output_format (str, optional, default 'pandas') – Desired output format
  • api (pyTD.api.api object, optional) – A pyTD api object. If not passed, API requestor defaults to pyTD.api.default_api
  • kwargs (additional request parameters (see _TDBase class)) –

Examples

Simple

In [8]: from pyTD.market import get_option_chains

In [9]: get_option_chains("AAPL")
Out[9]: 
               calls                  ...                puts                  
                 ask askSize   bid    ...     tradeTimeInLong   vega volatility
2019-01-25:1    0.02      26     0    ...       1548348107270      0       -999
2019-02-01:8    0.03      10     0    ...       1548171196325      0          0
2019-02-08:15   0.06      20     0    ...       1546549089108  0.052     84.281
2019-02-15:22   0.02       1     0    ...       1541102017668   0.09    228.023
2019-02-22:29   0.07     138     0    ...       1548257873767  0.071     62.597
2019-03-01:36   0.06      55     0    ...                   0  0.081     66.067
2019-03-08:43   0.18      11     0    ...                   0  0.086     51.935
2019-03-15:50   0.03      26     0    ...       1548356841862  0.129    135.031
2019-04-18:84   0.01       1     0    ...       1544625016275  0.207    189.663
2019-06-21:148  0.03      40  0.02    ...       1544625016466  0.242    101.109
2019-07-19:176  0.11      73     0    ...                   0  0.233     70.135
2020-01-17:358  0.13      50  0.12    ...       1547828507327  0.366     68.034
2020-06-19:512  0.52     508  0.32    ...       1547220323708   0.43       58.6
2021-01-15:722  0.61      18  0.51    ...       1548261076782  0.534      60.54
2021-06-18:876   2.4       1  2.05    ...                   0  0.493     39.123

[15 rows x 92 columns]

Historical Prices

The Get Price History endpoint provides historical pricing data for symbols across asset classes. Access is provided by pyTD through the top-level function get_price_history.

pyTD.market.get_price_history(*args, **kwargs)

Function to retrieve price history for a given symbol over a given period

Parameters:
  • symbols (string, array-like object (list, tuple, Series), or DataFrame) – Desired symbols for retrieval
  • periodType (str, default DAY, optional) – The type of period to show
  • period (int, optional) – The number of periods to show
  • frequencyType (str, optional) – The type of frequency with which a new candle is formed
  • frequency (int, optional) – The number of frequencyType to includ with each candle
  • startDate (string or DateTime object, optional) – Starting date, timestamp. Parses many different kind of date representations (e.g., ‘JAN-01-2015’, ‘1/1/15’, ‘Jan, 1, 1980’)
  • endDate (string or DateTime object, optional) – Ending date, timestamp. Parses many different kind of date representations (e.g., ‘JAN-01-2015’, ‘1/1/15’, ‘Jan, 1, 1980’)
  • extended (str or bool, default 'True'/True, optional) – True to return extended hours data, False for regular hours only
  • output_format (str, default 'pandas', optional) – Desired output format (json or DataFrame)

Examples

In [10]: import datetime

In [11]: from pyTD.market import get_price_history

In [12]: start = datetime.datetime(2017, 1, 1)

In [13]: end = datetime.datetime(2018, 1, 1)

In [14]: get_price_history("AAPL", start_date=start, end_date=end).head()
Out[14]: 
                      close      high     low    open    volume
datetime                                                       
2017-01-03 06:00:00  116.15  116.3300  114.76  115.80  28781865
2017-01-04 06:00:00  116.02  116.5100  115.75  115.85  21118116
2017-01-05 06:00:00  116.61  116.8642  115.81  115.92  22193587
2017-01-06 06:00:00  117.91  118.1600  116.47  116.78  31751900
2017-01-09 06:00:00  118.99  119.4300  117.94  117.95  33561948

Fundamental Data

Fundamental data can also be accesed through get_fundamentals, which wraps pyTD.instruments.get_instruments for convenience.

In [15]: from pyTD.market import get_fundamentals

In [16]: get_fundamentals("AAPL").head()
Out[16]: 
                       AAPL
beta                1.09174
bookValuePerShare   2.79895
currentRatio        1.12384
divGrowthRate3Year        0
dividendAmount         2.92