quantdata.massive.client#
quantdata.massive.client#
A simple client wrapper for the www.massive.com API.
Access#
You will require a massive.com token to access the data.
Set the token in the MASSIVE_TOKEN environment variable, e.g. by adding the following line to your ~/.bashrc or ~/.zshrc file:
export MASSIVE_TOKEN="your_token"
Once installed, use is straightforward, e.g. to fetch trades and quotes for Apple 150 call expiring on 2023-06-16:
from quantdata.massive import MassiveClient
client = MassiveClient()
trades = client.fetch_trades("AAPL230616C00150000", date(2023,6,16))
quotes = client.fetch_quotes("AAPL230616C00150000", date(2023,6,16))
...
- class quantdata.massive.client.MassiveClient(temp_caching_topic=None, fmt=Format.PICKLE)[source]#
Bases:
objectWrapper around massive.com connectivity.
Standard usage:: from quantdata.massive import MassiveClient client = MassiveClient() trades = client.fetch_trades("AAPL230616C00150000", date(2023,6,16)) quotes = client.fetch_quotes("AAPL230616C00150000", date(2023,6,16)) **Temporary Caching** This client supports in-session caching. Unlike the overall caching framework for quantdata, this caching scheme is temporary and is not guaranteed to persist between machine reboots (e.g. in Linux the root temporary directory is /tmp/massive). This can be useful for speeding up repeated requests during an active session but should not be relied upon for long-term storage of data. To enable temporary caching in a, say, "work" context:: handle = MassiveClient("work") .. !! processed by numpydoc !!- BASE_URL = 'https://api.massive.com'#
Base URL for requests.
.. !! processed by numpydoc !!
- START_DATE = datetime.date(2022, 3, 7)#
Start date for quote and trade requests for options. See massive.com (https://massive.com/docs/rest/options/trades-quotes/quotes)
.. !! processed by numpydoc !!
- TIME_SPANS = {'day', 'hour', 'minute', 'month', 'quarter', 'second', 'week', 'year'}#
Standard massive time spans (https://massive.com/docs/rest/stocks/aggregates/custom-bars)
.. !! processed by numpydoc !!
- static get_token()[source]#
Reads massive token from the MASSIVE_TOKEN environment variable
.. !! processed by numpydoc !!
- static get_rest_client()[source]#
Returns a massive.RESTClient instance with the current token, defined by the MASSIVE_TOKEN environment variable.
.. !! processed by numpydoc !!
- paginate(initial_url, params=None)[source]#
Handle v3-style pagination (https://massive.com/blog/api-pagination-patterns) (quotes, trades, contracts), c.f.
.. !! processed by numpydoc !!
- property session#
Return the HTTP session for this MassiveClient. Note that a session is shared within a process
.. !! processed by numpydoc !!
- clear_temp()[source]#
Clear the temporary directory for this MassiveClient.
.. !! processed by numpydoc !!
- has_any_quotes_or_trades(ticker, d)[source]#
Whether ticker has any quotes or trades on date d. Returns tuple (has_quotes, has_trades).
.. !! processed by numpydoc !!
- has_any_quotes(ticker, d)[source]#
Whether ticker has any quotes on date d.
.. !! processed by numpydoc !!
- has_any_trades(ticker, d)[source]#
Whether ticker has any trades on date d.
.. !! processed by numpydoc !!
- SCHEMA_TRADES = {'price': Float64, 'sequence_number': UInt64, 'size': Float64, 'trade_code': UInt32, 'ts_ns': Datetime(time_unit='ns', time_zone='America/New_York')}#
Schema of the polars.DataFrame returned by fetch_trades.
.. !! processed by numpydoc !!
- fetch_trades(ticker, d)[source]#
Gets trades from /v3/trades/{ticker} sorted by sip_timestamp asc.
Used both for options and underlyings. The returned polars.DataFrame has the following columns: * ts_ns: Datetime[ns, tz]: time zone information with nanonsecond resolutuin. * price: Float64 * size: Float64 * trade_code: UInt32. Compressed & Packed trade conditions, see quantdata.massive.trade_conds.pack_conditions. It is recommended to remove trades with uncommon conditions, see quantdata.massive.trade_conds.NORMAL_TRADE_EXCLUDE_FLAGS. * sequence_number: UInt64. Sequence number of the trade for a given timestamp, useful for ordering trades with the same timestamp. :param ticker: Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16. :type ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param d: Date for which to fetch trades. :type d: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :returns: **Result** -- Returns a data frame with schema MassiveClient.SCHEMA_TRADES. The dataframe can have length zero (but it will have the correct data schema). * ts_ns: Datetime[ns, tz] * price: Float64 * size: Float64 * trade_code: UInt32. Compressed & Packed trade conditions, see quantdata.massive.trade_conds.pack_conditions. * sequence_number: UInt64. Sequence number of the trade for a given timestamp. Trades will be sorted by (ts_ns, sequence_number) asc. :rtype: polars.DataFrame .. !! processed by numpydoc !!
- SCHEMA_QUOTES = {'ask_price': Float64, 'ask_size': Float64, 'bid_price': Float64, 'bid_size': Float64, 'sequence_number': UInt64, 'ts_ns': Datetime(time_unit='ns', time_zone='America/New_York')}#
Schema of the polars.DataFrame returned by fetch_quotes.
.. !! processed by numpydoc !!
- fetch_quotes(ticker, d)[source]#
Fetches quotes from “/v3/quotes/{ticker}” sorted by sip_timestamp (and sequence_number) asc.
Used both for options and underlyings. :param ticker: Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16. :type ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param d: Date for which to fetch quotes. :type d: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :returns: **Result** -- Returns a data frame with schema MassiveClient.SCHEMA_QUOTES. The dataframe can have length zero (but it will have the correct data schema). * ts_ns: Datetime[ns, tz] * bid_price: Float64 * bid_size: Float64 * ask_price: Float64 * ask_size: Float64 * sequence_number: UInt64. Sequence number of the quote for a given timestamp. Quotes will be sorted by (ts_ns, sequence_number) asc. :rtype: polars.DataFrame .. !! processed by numpydoc !!
- SCHEMA_BARS = {'close': Float64, 'high': Float64, 'low': Float64, 'num_trades': Int64, 'open': Float64, 'ts_ms': Datetime(time_unit='ms', time_zone='America/New_York'), 'volume': Float64, 'vwap': Float64}#
Schema of the polars.DataFrame returned by fetch_bars.
.. !! processed by numpydoc !!
- fetch_bars(ticker, start, end, adjusted, timespan)[source]#
Download daily bars for a ticker accross a number of dates; convert timestamp to datetime in NY/ns.
See custom bars documentation (https://massive.com/docs/rest/stocks/aggregates/custom-bars) :param ticker: Ticker symbol, e.g. "AAPL" for Apple. :type ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param start: Start date for bars. :type start: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param end: End date for bars. :type end: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param adjusted: Whether to fetch adjusted bars. :type adjusted: :sphinx_autodoc_typehints_type:\:py\:class\:\bool\ :param timespan: Timespan for the bars, e.g. "day", "week", "month". Must be one of 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'. :type timespan: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :returns: **Result** -- Data frame wiwh schema MassiveClient.SCHEMA_BARS. The dataframe can have length zero (but it will have the correct data schema). - ts_ms: Datetime[ms, tz]: time zone information with millisecond precision - close: Float64 - open: Float64 - high: Float64 - low: Float64 - volume: Float64 - vwap: Float64 - num_trades: Int64 :rtype: polars.DataFrame .. !! processed by numpydoc !!
- fetch_day_summary(ticker, d, *, adjusted, can_be_none=False)[source]#
Fetch open/close/volume/high/low for ticker on date d.
Returns dict with keys: open, close, low, high, volume, adjusted and optionally afterHours and preMarket if available. See daily ticker summary documentation (https://massive.com/docs/rest/options/aggregates/daily-ticker-summary). If no trade was recorded raise an exception except of can_be_none is True, in which case return None. :param ticker: Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16. :type ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param d: Date for which to fetch open/close/volume. :type d: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param adjusted: Whether to fetch adjusted or unadjusted open/close/volume. :type adjusted: :sphinx_autodoc_typehints_type:\:py\:class\:\bool\ :param can_be_none: If True, return None if no trade was recorded for the day. If False, raise an exception if no trade was recorded for the day. :type can_be_none: :sphinx_autodoc_typehints_type:\:py\:class\:\bool\ :returns: **Result** -- Dict with keys: * open [float] * close [float] * low [float] * high [float] * volume [float] * adjusted [bool] * afterHours [floatNone] (optional) * preMarket [floatNone] (optional) :rtype: dict .. !! processed by numpydoc !!
- list_all_contracts_expiring_after_day(underlying, d, max_dte=None)[source]#
Download ALL option contracts with expiration_date at or past d, with an optional upper bound.
:param underlying: Underlying ticker symbol, e.g. "AAPL" for Apple. :type underlying: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param d: Date for which to fetch contracts. Only contracts with expiration_date >= d are returned. :type d: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param max_dte: If not None, only return contracts with expiration_date <= d + max_dte in business days. This is computed using quantdata.biz_calendar.add_business_days with the NYSE calendar *including half days*. :type max_dte: :sphinx_autodoc_typehints_type:\:py\:class\:\int\ :param Returns: :param -------: :param Result: See v3/reference/options/contracts documentation (https://massive.com/docs/rest/options/contracts). :type Result: dict .. !! processed by numpydoc !!
- option_contract_overview(opt_ticker, as_of=None)[source]#
Download option contract overview data (https://massive.com/docs/rest/options/contracts/contract-overview)
for a given options ticker. :param opt_ticker: Option ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16. :type opt_ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param as_of: If not None, fetch the contract overview as of this date. Otherwise, fetch the latest. :type as_of: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ \ \:py\:obj\:\None\ :returns: **Result** -- See v3/reference/options/contract overview documentation (https://massive.com/docs/rest/options/contracts/contract-overview). :rtype: dict .. !! processed by numpydoc !!
- list_all_contracts_for_expiry(underlying, d, expiry)[source]#
Download ALL option contracts with expiration_date at or past d, with an optional upper bound.
:param underlying: Underlying ticker symbol, e.g. "AAPL" for Apple. :type underlying: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param d: Date for which to fetch contracts. Only contracts with expiration_date >= d are returned. :type d: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param expiry: Expiration date for which to fetch contracts. Only contracts with expiration_date equal to expiry are returned. :type expiry: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param Returns: :param -------: :param Result: See v3/reference/options/contracts documentation (https://massive.com/docs/rest/options/contracts). :type Result: dict .. !! processed by numpydoc !!
- adjustment_factors(ticker, start, end)[source]#
Downloads daily adjusted and unadjusted close, and computes the adjustment factor as adj_close / unadj_close.
See custom bars documentation (https://massive.com/docs/rest/stocks/aggregates/custom-bars) Returns a Polars frame with: * date * close_unadj * close_adj * factor_close = close_adj / close_unadj Notes: * Uses NY timezone to derive the trading date from 't'. * Uses only 'close' as requested. * If you later want volume/cash-vol invariance checks, also download 'v' and compute factors similarly. .. !! processed by numpydoc !!
- ticker_reference_data(ticker)[source]#
Return reference data for a given ticker.
See ticker overview documentation (https://massive.com/docs/rest/stocks/tickers/ticker-overview) for details. This function converts boolean, integer, floats and dates. :param ticker: Ticker symbol, e.g. "AAPL230616C00150000" for Apple 150 call expiring on 2023-06-16. :type ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :returns: **Result** -- Dict with reference data for the ticker. See ticker overview documentation (https://massive.com/docs/rest/stocks/tickers/ticker-overview) for details. The following conversions will be performed: * active [boolNone] * list_date [dateNone] * delisted_utc [dateNone] * market_cap [floatNone] * round_lot [intNone] * total_employees [intNone] * weighted_shares_outstanding [intNone] * share_class_shares_outstanding [intNone] :rtype: dict :raises Ticker not found: FileNotFoundError: If the request for reference data from massive did not yield any results. .. !! processed by numpydoc !!
- SCHEMA_DIVIDENDS = {'cash_amount': Float64, 'currency': String, 'declaration_date': Date, 'distribution_type': String, 'ex_dividend_date': Date, 'frequency': Int16, 'historical_adjustment_factor': Float64, 'id': String, 'pay_date': Date, 'record_date': Date, 'split_adjusted_cash_amount': Float64}#
Schema of the polars.DataFrame returned by get_dividends.
.. !! processed by numpydoc !!
- get_dividends(ticker, start, end)[source]#
Retrieve dividends which go ex div between two dates from /stocks/v1/dividends (https://massive.com/docs/rest/stocks/corporate-actions/dividends).
:param ticker: Ticker symbol, e.g. "AAPL" for Apple. :type ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param start: Start date for dividends. :type start: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param end: End date for dividends. :type end: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :returns: DataFrame with dividend information using schema MassiveClient.SCHEMA_DIVIDENDS. The dataframe can have length zero (but it will have the correct data schema). :rtype: polars.DataFrame .. !! processed by numpydoc !!
- SCHEMA_SPLITS = {'adjustment_type': String, 'execution_date': Date, 'historical_adjustment_factor': Float64, 'id': String, 'split_from': Int32, 'split_to': Int32}#
Schema of the polars.DataFrame returned by get_splits.
.. !! processed by numpydoc !!
- get_splits(ticker, start, end)[source]#
Retrieve stock splits between two dates from /stocks/v1/splits (https://massive.com/docs/rest/stocks/corporate-actions/splits).
.. !! processed by numpydoc !!
- SCHEMA_HAS_TICKER_CHANGES = {'date': Date, 'has_ticker_change': Boolean}#
Schema of the polars.DataFrame returned by has_ticker_changes.
.. !! processed by numpydoc !!
- has_ticker_changes(ticker, start, end)[source]#
Find dates at which an underlying had ticker changes.
If the endpoint is not available return an empty frame. At the moment ticker changes are the only events massive.com supports (https://massive.com/docs/rest/stocks/corporate-actions/ticker-events). .. !! processed by numpydoc !!
- consistent_prev_close(ticker, d, *, prev_d=None, exclude_half_days=True)[source]#
Computes the previous day close consistent with today’s unadjusted prices.
It computes S_{\mathrm{t-1}} := S^{\mathrm{adjusted}}_{\mathrm{t-1}} \cdot \frac{S^{\mathrm{unadjusted}}_{\mathrm{t}}}{S^{\mathrm{adjusted}}_{\mathrm{t}}} :param ticker: Ticker symbol, e.g. "AAPL". :type ticker: :sphinx_autodoc_typehints_type:\:py\:class\:\str\ :param d: Date for which to compute the previous close. :type d: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ :param prev_d: If not None, use this date as the previous day instead of computing it as the previous business day. :type prev_d: :sphinx_autodoc_typehints_type:\:py\:class\:\\~datetime.date\ \ \:py\:obj\:\None\ :param exclude_half_days: Whether to exclude half days when computing the previous business day. This is used if prev_d is None. :type exclude_half_days: :sphinx_autodoc_typehints_type:\:py\:class\:\bool\ :returns: **Close** -- The previous day's close, consistent with today's unadjusted prices. :rtype: float .. !! processed by numpydoc !!