Skip to content

Commit

Permalink
feat: Support options market data api (historical bars/trades and exc…
Browse files Browse the repository at this point in the history
…hange codes) (#420)

* feat: support get_option_bars/get_option_trades/get_option_exchange_codes

* doc: update for market data api

* doc: use df for options data in example
  • Loading branch information
hiohiohio authored Mar 15, 2024
1 parent 16b7298 commit bd58705
Show file tree
Hide file tree
Showing 14 changed files with 716 additions and 11 deletions.
75 changes: 74 additions & 1 deletion alpaca/data/historical/option.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@
format_snapshot_data,
parse_obj_as_symbol_dict,
)
from alpaca.data.models.bars import BarSet
from alpaca.data.models.quotes import Quote
from alpaca.data.models.snapshots import Snapshot
from alpaca.data.models.trades import Trade
from alpaca.data.models.trades import Trade, TradeSet
from alpaca.data.requests import (
OptionBarsRequest,
OptionChainRequest,
OptionLatestQuoteRequest,
OptionLatestTradeRequest,
OptionSnapshotRequest,
OptionTradesRequest,
)


Expand Down Expand Up @@ -70,6 +73,50 @@ def __init__(
raw_data=raw_data,
)

def get_option_bars(
self, request_params: OptionBarsRequest
) -> Union[BarSet, RawData]:
"""Returns bar data for an option contract or list of option contracts over a given
time period and timeframe.
Args:
request_params (OptionBarsRequest): The request object for retrieving option bar data.
Returns:
Union[BarSet, RawData]: The bar data either in raw or wrapped form
"""
params = request_params.to_request_fields()

# paginated get request for market data api
raw_bars = self._data_get(
endpoint_data_type="bars",
endpoint_asset_class="options",
api_version=self._api_version,
**params,
)

if self._use_raw_data:
return raw_bars

return BarSet(raw_bars)

def get_option_exchange_codes(self) -> RawData:
"""Returns the mapping between the option exchange codes and the corresponding exchanges names.
Args:
None
Returns:
RawData: The mapping between the option exchange codes and the corresponding exchanges names.
"""
path = "/options/meta/exchanges"
raw_exchange_code = self.get(
path=path,
api_version=self._api_version,
)

return raw_exchange_code

def get_option_latest_quote(
self, request_params: OptionLatestQuoteRequest
) -> Union[Dict[str, Quote], RawData]:
Expand Down Expand Up @@ -122,6 +169,32 @@ def get_option_latest_trade(

return parse_obj_as_symbol_dict(Trade, raw_latest_quotes)

def get_option_trades(
self, request_params: OptionTradesRequest
) -> Union[TradeSet, RawData]:
"""The historical option trades API provides trade data for a list of contract symbols between the specified dates up to 7 days ago.
Args:
request_params (OptionTradesRequest): The request object for retrieving option trade data.
Returns:
Union[TradeSet, RawData]: The trade data either in raw or wrapped form
"""
params = request_params.to_request_fields()

# paginated get request for market data api
raw_trades = self._data_get(
endpoint_data_type="trades",
endpoint_asset_class="options",
api_version=self._api_version,
**params,
)

if self._use_raw_data:
return raw_trades

return TradeSet(raw_trades)

def get_option_snapshot(
self, request_params: OptionSnapshotRequest
) -> Union[Dict[str, Snapshot], RawData]:
Expand Down
8 changes: 5 additions & 3 deletions alpaca/data/models/bars.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from datetime import datetime
from typing import Optional, Dict, List
from typing import Dict, List, Optional

from pydantic import ConfigDict

from alpaca.common.types import RawData
from alpaca.common.models import ValidateBaseModel as BaseModel
from alpaca.data.models.base import TimeSeriesMixin, BaseDataSet
from alpaca.common.types import RawData
from alpaca.data.mappings import BAR_MAPPING
from alpaca.data.models.base import BaseDataSet, TimeSeriesMixin


class Bar(BaseModel):
Expand Down Expand Up @@ -62,6 +62,8 @@ class BarSet(BaseDataSet, TimeSeriesMixin):
data (Dict[str, List[Bar]]): The collection of Bars keyed by symbol.
"""

data: Dict[str, List[Bar]] = {}

def __init__(
self,
raw_data: RawData,
Expand Down
8 changes: 5 additions & 3 deletions alpaca/data/models/quotes.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from datetime import datetime
from typing import Optional, Dict, List, Union
from typing import Dict, List, Optional, Union

from pydantic import ConfigDict

from alpaca.common.types import RawData
from alpaca.common.models import ValidateBaseModel as BaseModel
from alpaca.common.types import RawData
from alpaca.data.enums import Exchange
from alpaca.data.mappings import QUOTE_MAPPING
from alpaca.data.models.base import TimeSeriesMixin, BaseDataSet
from alpaca.data.models.base import BaseDataSet, TimeSeriesMixin


class Quote(BaseModel):
Expand Down Expand Up @@ -63,6 +63,8 @@ class QuoteSet(BaseDataSet, TimeSeriesMixin):
data (Dict[str, List[Quote]]): The collection of Quotes keyed by symbol.
"""

data: Dict[str, List[Quote]] = {}

def __init__(self, raw_data: RawData) -> None:
"""Instantiates a QuoteSet.
Expand Down
8 changes: 5 additions & 3 deletions alpaca/data/models/trades.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from datetime import datetime
from typing import Optional, Dict, List, Union
from typing import Dict, List, Optional, Union

from pydantic import ConfigDict

from alpaca.common.types import RawData
from alpaca.common.models import ValidateBaseModel as BaseModel
from alpaca.common.types import RawData
from alpaca.data.enums import Exchange
from alpaca.data.mappings import TRADE_MAPPING
from alpaca.data.models.base import TimeSeriesMixin, BaseDataSet
from alpaca.data.models.base import BaseDataSet, TimeSeriesMixin


class Trade(BaseModel):
Expand Down Expand Up @@ -59,6 +59,8 @@ class TradeSet(BaseDataSet, TimeSeriesMixin):
data (Dict[str, List[Trade]]]): The collection of Trades keyed by symbol.
"""

data: Dict[str, List[Trade]] = {}

def __init__(self, raw_data: RawData) -> None:
"""Instantiates a TradeSet - a collection of Trades.
Expand Down
35 changes: 35 additions & 0 deletions alpaca/data/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ class StockBarsRequest(BaseBarsRequest):
Attributes:
symbol_or_symbols (Union[str, List[str]]): The ticker identifier or list of ticker identifiers.
timeframe (TimeFrame): The period over which the bars should be aggregated. (i.e. 5 Min bars, 1 Day bars)
start (Optional[datetime]): The beginning of the time interval for desired data. Timezone naive inputs assumed to be in UTC.
end (Optional[datetime]): The end of the time interval for desired data. Defaults to now. Timezone naive inputs assumed to be in UTC.
limit (Optional[int]): Upper limit of number of data points to return. Defaults to None.
Expand All @@ -111,6 +112,7 @@ class CryptoBarsRequest(BaseBarsRequest):
Attributes:
symbol_or_symbols (Union[str, List[str]]): The ticker identifier or list of ticker identifiers.
timeframe (TimeFrame): The period over which the bars should be aggregated. (i.e. 5 Min bars, 1 Day bars)
start (Optional[datetime]): The beginning of the time interval for desired data. Timezone naive inputs assumed to be in UTC.
end (Optional[datetime]): The end of the time interval for desired data. Defaults to now. Timezone naive inputs assumed to be in UTC.
limit (Optional[int]): Upper limit of number of data points to return. Defaults to None.
Expand All @@ -120,6 +122,22 @@ class CryptoBarsRequest(BaseBarsRequest):
pass


class OptionBarsRequest(BaseBarsRequest):
"""
The request model for retrieving bar data for option contracts.
See BaseBarsRequest for more information on available parameters.
Attributes:
symbol_or_symbols (Union[str, List[str]]): The ticker identifier or list of ticker identifiers.
timeframe (TimeFrame): The period over which the bars should be aggregated. (i.e. 5 Min bars, 1 Day bars)
start (Optional[datetime]): The beginning of the time interval for desired data. Timezone naive inputs assumed to be in UTC.
end (Optional[datetime]): The end of the time interval for desired data. Defaults to now. Timezone naive inputs assumed to be in UTC.
limit (Optional[int]): Upper limit of number of data points to return. Defaults to None.
sort (Optional[Sort]): The chronological order of response based on the timestamp. Defaults to ASC.
"""


# ############################## Quotes ################################# #


Expand Down Expand Up @@ -179,6 +197,23 @@ class CryptoTradesRequest(BaseTimeseriesDataRequest):
pass


class OptionTradesRequest(BaseTimeseriesDataRequest):
"""
This request class is used to submit a request for option trade data.
See BaseTimeseriesDataRequest for more information on available parameters.
Attributes:
symbol_or_symbols (Union[str, List[str]]): The option identifier or list of option identifiers.
start (Optional[datetime]): The beginning of the time interval for desired data. Timezone naive inputs assumed to be in UTC.
end (Optional[datetime]): The end of the time interval for desired data. Defaults to now. Timezone naive inputs assumed to be in UTC.
limit (Optional[int]): Upper limit of number of data points to return. Defaults to None.
sort (Optional[Sort]): The chronological order of response based on the timestamp. Defaults to ASC.
"""

pass


# ############################## Latest Endpoints ################################# #


Expand Down
9 changes: 9 additions & 0 deletions docs/api_reference/data/common.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Common
======

This module represents a bunch of classes that have common/shared functionality across the stock/crypto/options

.. toctree::
:maxdepth: 2

common/requests
15 changes: 15 additions & 0 deletions docs/api_reference/data/common/requests.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
========
Requests
========


BaseTimeseriesDataRequest
-------------------------

.. autoclass:: alpaca.data.requests.BaseTimeseriesDataRequest


BaseBarsRequest
---------------

.. autoclass:: alpaca.data.requests.BaseBarsRequest
6 changes: 6 additions & 0 deletions docs/api_reference/data/crypto/requests.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ Requests
========


BaseCryptoLatestDataRequest
---------------------------

.. autoclass:: alpaca.data.requests.BaseCryptoLatestDataRequest


CryptoBarsRequest
-----------------

Expand Down
18 changes: 18 additions & 0 deletions docs/api_reference/data/option/historical.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,24 @@ OptionHistoricalDataClient
:members: __init__


Get Option Bars
---------------

.. automethod:: alpaca.data.historical.option.OptionHistoricalDataClient.get_option_bars


Get Option Trades
-----------------

.. automethod:: alpaca.data.historical.option.OptionHistoricalDataClient.get_option_trades


Get Option Exchange Codes
-------------------------

.. automethod:: alpaca.data.historical.option.OptionHistoricalDataClient.get_option_exchange_codes


Get Option Latest Quote
-----------------------

Expand Down
18 changes: 18 additions & 0 deletions docs/api_reference/data/option/requests.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,24 @@ Requests
========


BaseOptionLatestDataRequest
---------------------------

.. autoclass:: alpaca.data.requests.BaseOptionLatestDataRequest


OptionBarsRequest
-----------------

.. autoclass:: alpaca.data.requests.OptionBarsRequest


OptionTradesRequest
-------------------

.. autoclass:: alpaca.data.requests.OptionTradesRequest


OptionLatestQuoteRequest
------------------------

Expand Down
6 changes: 6 additions & 0 deletions docs/api_reference/data/stock/requests.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ Requests
========


BaseStockLatestDataRequest
--------------------------

.. autoclass:: alpaca.data.requests.BaseStockLatestDataRequest


StockBarsRequest
----------------

Expand Down
1 change: 1 addition & 0 deletions docs/api_reference/data_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Market Data Reference
.. toctree::
:maxdepth: 2

data/common
data/stock
data/crypto
data/option
Expand Down
Loading

0 comments on commit bd58705

Please sign in to comment.