py_alpaca_api.stock

Submodules

Classes

Assets

Auctions

Handles historical auction data retrieval from Alpaca API.

History

LatestQuote

Logos

Handles company logo retrieval from Alpaca API.

Metadata

Market metadata API for condition codes and exchange codes.

Predictor

Quotes

Handles historical quote data retrieval from Alpaca API.

Screener

Snapshots

Trades

Market

Stock

Package Contents

class py_alpaca_api.stock.Assets(base_url: str, headers: dict[str, str])[source]
get(symbol: str) py_alpaca_api.models.asset_model.AssetModel[source]

Retrieves an AssetModel for the specified symbol.

Parameters:

symbol (str) – The symbol of the asset to retrieve.

Returns:

The AssetModel for the specified asset.

Return type:

AssetModel

Raises:

Exception – If the asset is not a US Equity (stock).

get_all(status: str = 'active', exchange: str = '', excluded_exchanges: list[str] | None = None) pandas.DataFrame[source]

Retrieves a DataFrame of all active, fractionable, and tradable assets.

Excluding those from the OTC exchange.

Parameters:
  • status (str, optional) – The status of the assets to retrieve. Defaults to “active”.

  • exchange (str, optional) – The exchange to filter the assets by. Defaults to an empty string, which retrieves assets from all exchanges.

  • excluded_exchanges (List[str], optional) – A list of exchanges to exclude from the results. Defaults to [“OTC”].

Returns:

A DataFrame containing the retrieved assets.

Return type:

pd.DataFrame

class py_alpaca_api.stock.Auctions(headers: dict[str, str])[source]

Handles historical auction data retrieval from Alpaca API.

get_auctions(symbols: str | list[str], start: str, end: str, limit: int = 10000, asof: str | None = None, feed: str = 'iex', page_token: str | None = None, sort: str = 'asc') pandas.DataFrame | dict[str, pandas.DataFrame][source]

Get historical auction data for one or more symbols.

Retrieves auction prices (opening and closing auctions) between specified dates.

Parameters:
  • symbols – Symbol(s) to get auction data for. Can be a string for single symbol or list of strings for multiple symbols.

  • start – Start date/time in ISO 8601 format (e.g., “2021-01-01” or “2021-01-01T00:00:00Z”).

  • end – End date/time in ISO 8601 format.

  • limit – Maximum number of auctions to return per symbol. Defaults to 10000.

  • asof – As-of date for corporate actions adjustments in YYYY-MM-DD format.

  • feed – The data feed to use (“iex”, “sip”, or “otc”). Defaults to “iex”.

  • page_token – Pagination token from previous request.

  • sort – Sort order for results (“asc” or “desc”). Defaults to “asc”.

Returns:

pd.DataFrame with auction data. For multiple symbols: dict mapping symbols to DataFrames with auction data.

Return type:

For single symbol

Raises:
get_daily_auctions(symbols: str | list[str], start: str, end: str, feed: str = 'iex') pandas.DataFrame | dict[str, pandas.DataFrame][source]

Get daily auction summary for one or more symbols.

Retrieves opening and closing auction prices aggregated by day.

Parameters:
  • symbols – Symbol(s) to get auction data for.

  • start – Start date in YYYY-MM-DD format.

  • end – End date in YYYY-MM-DD format.

  • feed – The data feed to use. Defaults to “iex”.

Returns:

DataFrame or dict of DataFrames with daily auction summaries.

class py_alpaca_api.stock.History(data_url: str, headers: dict[str, str], asset: py_alpaca_api.stock.assets.Assets)[source]
BATCH_SIZE = 200
check_if_stock(symbol: str) py_alpaca_api.models.asset_model.AssetModel[source]

Check if the asset corresponding to the symbol is a stock.

Parameters:

symbol (str) – The symbol of the asset to be checked.

Returns:

The asset information for the given symbol.

Return type:

AssetModel

Raises:

ValueError – If there is an error getting the asset information or if the asset is not a stock.

get_stock_data(symbol: str | list[str], start: str, end: str, timeframe: str = '1d', feed: str = 'sip', currency: str = 'USD', limit: int = 1000, sort: str = 'asc', adjustment: str = 'raw') pandas.DataFrame[source]

Retrieves historical stock data for one or more symbols within a specified date range and timeframe.

Parameters:
  • symbol – The stock symbol(s) to fetch data for. Can be a single symbol string or list of symbols.

  • start – The start date for historical data in the format “YYYY-MM-DD”.

  • end – The end date for historical data in the format “YYYY-MM-DD”.

  • timeframe – The timeframe for the historical data. Default is “1d”.

  • feed – The data feed source. Default is “sip”.

  • currency – The currency for historical data. Default is “USD”.

  • limit – The number of data points to fetch per symbol. Default is 1000.

  • sort – The sort order for the data. Default is “asc”.

  • adjustment – The adjustment for historical data. Default is “raw”.

Returns:

A pandas DataFrame containing the historical stock data for the given symbol(s) and time range.

Raises:

ValueError – If the given timeframe is not one of the allowed values.

static preprocess_multi_data(symbols_data: dict[str, list[collections.defaultdict]]) pandas.DataFrame[source]

Preprocess data for multiple symbols.

Parameters:

symbols_data – A dictionary mapping symbols to their bar data.

Returns:

A pandas DataFrame containing the preprocessed historical stock data for all symbols.

static preprocess_data(symbol_data: list[collections.defaultdict], symbol: str) pandas.DataFrame[source]

Prepross data Preprocesses the given symbol data by converting it to a pandas DataFrame and performing various data transformations.

Parameters:
  • symbol_data – A list of defaultdict objects representing the JSON response data.

  • symbol – A string representing the symbol or ticker for the stock data.

Returns:

A pandas DataFrame containing the preprocessed historical stock data.

get_historical_data(symbols: list[str], url: str, params: dict, is_single: bool) dict[str, list[collections.defaultdict]][source]

Retrieves historical data for given symbol(s).

Parameters:
  • symbols – List of symbols for which to retrieve historical data.

  • url – The URL to send the request to.

  • params – Additional parameters to include in the request.

  • is_single – Whether this is a single-symbol request.

Returns:

A dictionary mapping symbols to their historical data.

Return type:

dict[str, list[defaultdict]]

get_latest_bars(symbols: str | list[str], feed: str = 'iex', currency: str = 'USD') pandas.DataFrame | dict[str, pandas.DataFrame][source]

Get the latest bars for one or more symbols.

The latest bars endpoint returns the most recent minute bar for each requested symbol.

Parameters:
  • symbols – Symbol(s) to get latest bars for. Can be a string for single symbol or list of strings for multiple symbols.

  • feed – The data feed to use (“iex”, “sip”, or “otc”). Defaults to “iex”.

  • currency – The currency for the returned prices. Defaults to “USD”.

Returns:

pd.DataFrame with the latest bar data. For multiple symbols: dict mapping symbols to DataFrames with latest bar data.

Return type:

For single symbol

Raises:
  • ValueError – If feed is invalid or symbols is empty.

  • Exception – If the API request fails or returns no data.

class py_alpaca_api.stock.LatestQuote(headers: dict[str, str])[source]
BATCH_SIZE = 200
get(symbol: list[str] | str | None, feed: str = 'iex', currency: str = 'USD') list[py_alpaca_api.models.quote_model.QuoteModel] | py_alpaca_api.models.quote_model.QuoteModel[source]

Get latest quotes for one or more symbols.

Parameters:
  • symbol – A string or list of strings representing the stock symbol(s).

  • feed – The data feed source. Default is “iex”.

  • currency – The currency for the quotes. Default is “USD”.

Returns:

A single QuoteModel or list of QuoteModel objects.

Raises:

ValueError – If symbol is None/empty or if feed is invalid.

class py_alpaca_api.stock.Logos(headers: dict[str, str])[source]

Handles company logo retrieval from Alpaca API.

Get the logo for a specific symbol.

Retrieves the company logo as binary image data.

Parameters:
  • symbol – The stock symbol to get the logo for.

  • placeholder – If True, returns a placeholder image when logo is not available. Defaults to False.

Returns:

The logo image as binary data.

Return type:

bytes

Raises:
get_logo_url(symbol: str, placeholder: bool = False) str[source]

Get the URL for a symbol’s logo.

This method returns the direct URL to fetch the logo, which can be used in HTML img tags or for direct browser access.

Parameters:
  • symbol – The stock symbol to get the logo URL for.

  • placeholder – If True, includes placeholder parameter in URL. Defaults to False.

Returns:

The URL to the logo image.

Return type:

str

Raises:

ValidationError – If the symbol is invalid.

Save a symbol’s logo to a file.

Downloads the logo and saves it to the specified file path.

Parameters:
  • symbol – The stock symbol to get the logo for.

  • filepath – The path where the logo should be saved.

  • placeholder – If True, saves a placeholder image when logo is not available. Defaults to False.

Raises:
  • ValidationError – If the symbol or filepath is invalid.

  • Exception – If the API request fails or file cannot be written.

get_logo_base64(symbol: str, placeholder: bool = False) str[source]

Get the logo as a base64 encoded string.

Useful for embedding logos directly in HTML or JSON responses.

Parameters:
  • symbol – The stock symbol to get the logo for.

  • placeholder – If True, returns a placeholder image when logo is not available. Defaults to False.

Returns:

The logo image as a base64 encoded string.

Return type:

str

Raises:
get_multiple_logos(symbols: list[str], placeholder: bool = False) dict[str, bytes | None][source]

Get logos for multiple symbols.

Retrieves logos for multiple symbols in a single batch operation.

Parameters:
  • symbols – List of stock symbols to get logos for.

  • placeholder – If True, returns placeholder images when logos are not available. Defaults to False.

Returns:

Dictionary mapping symbols to their logo binary data.

Symbols without logos will have None as value unless placeholder is True.

Return type:

dict

Raises:

ValidationError – If symbols list is invalid.

class py_alpaca_api.stock.Metadata(headers: dict[str, str])[source]

Market metadata API for condition codes and exchange codes.

get_exchange_codes(use_cache: bool = True) dict[str, str][source]

Get the mapping between exchange codes and exchange names.

Parameters:

use_cache – Whether to use cached data if available. Defaults to True.

Returns:

Dictionary mapping exchange codes to exchange names.

Raises:

APIRequestError – If the API request fails.

get_condition_codes(ticktype: str = 'trade', tape: str = 'A', use_cache: bool = True) dict[str, str][source]

Get the mapping between condition codes and condition names.

Parameters:
  • ticktype – Type of conditions to retrieve (“trade” or “quote”). Defaults to “trade”.

  • tape – Market tape (“A” for NYSE, “B” for NASDAQ, “C” for other). Defaults to “A”.

  • use_cache – Whether to use cached data if available. Defaults to True.

Returns:

Dictionary mapping condition codes to condition descriptions.

Raises:
get_all_condition_codes(use_cache: bool = True) dict[str, dict[str, dict[str, str]]][source]

Get all condition codes for all tick types and tapes.

Parameters:

use_cache – Whether to use cached data if available. Defaults to True.

Returns:

{
“trade”: {

“A”: {condition_code: description, …}, “B”: {condition_code: description, …}, “C”: {condition_code: description, …}

}, “quote”: {

”A”: {condition_code: description, …}, “B”: {condition_code: description, …}, “C”: {condition_code: description, …}

}

}

Return type:

Nested dictionary with structure

Raises:

APIRequestError – If any API request fails.

clear_cache() None[source]

Clear all cached metadata.

This forces the next request to fetch fresh data from the API.

lookup_exchange(code: str) str | None[source]

Look up an exchange name by its code.

Parameters:

code – The exchange code to look up.

Returns:

The exchange name if found, None otherwise.

lookup_condition(code: str, ticktype: str = 'trade', tape: str = 'A') str | None[source]

Look up a condition description by its code.

Parameters:
  • code – The condition code to look up.

  • ticktype – Type of condition (“trade” or “quote”). Defaults to “trade”.

  • tape – Market tape (“A”, “B”, or “C”). Defaults to “A”.

Returns:

The condition description if found, None otherwise.

class py_alpaca_api.stock.Predictor(history: py_alpaca_api.stock.history.History, screener: py_alpaca_api.stock.screener.Screener)[source]
get_stock_data(symbol: str, timeframe: str = '1d', start: str = four_years_ago, end: str = yesterday) pandas.DataFrame[source]

Retrieves historical stock data for a given symbol within a specified timeframe.

Parameters:
  • symbol (str) – The stock symbol to retrieve data for.

  • timeframe (str, optional) – The timeframe for the data. Defaults to “1d”.

  • start (str, optional) – The start date for the data. Defaults to four_years_ago.

  • end (str, optional) – The end date for the data. Defaults to yesterday.

Returns:

A DataFrame containing the historical stock data with columns “ds” (date) and “y” (vwap).

Return type:

pd.DataFrame

static train_prophet_model(data)[source]

Trains a Prophet model using the provided data.

Parameters:

data – The input data used for training the model.

Returns:

The trained Prophet model.

static generate_forecast(model, future_periods=14)[source]

Generates a forecast using the specified model for a given number of future periods.

Parameters:
  • model – The model used for forecasting.

  • future_periods – The number of future periods to forecast.

Returns:

The forecasted value for the next two weeks.

get_losers_to_gainers(gain_ratio: float = 10.0, losers_to_scan: int = 200, future_periods: int = 5) list[source]
class py_alpaca_api.stock.Quotes(headers: dict[str, str])[source]

Handles historical quote data retrieval from Alpaca API.

get_historical_quotes(symbols: str | list[str], start: str, end: str, limit: int = 10000, asof: str | None = None, feed: str = 'iex', page_token: str | None = None, sort: str = 'asc') pandas.DataFrame | dict[str, pandas.DataFrame][source]

Get historical quote data for one or more symbols.

Retrieves historical quote (bid/ask) data between specified dates.

Parameters:
  • symbols – Symbol(s) to get quote data for. Can be a string for single symbol or list of strings for multiple symbols.

  • start – Start date/time in ISO 8601 format (e.g., “2021-01-01” or “2021-01-01T00:00:00Z”).

  • end – End date/time in ISO 8601 format.

  • limit – Maximum number of quotes to return per symbol. Defaults to 10000.

  • asof – As-of date for corporate actions adjustments in YYYY-MM-DD format.

  • feed – The data feed to use (“iex”, “sip”, or “otc”). Defaults to “iex”.

  • page_token – Pagination token from previous request.

  • sort – Sort order for results (“asc” or “desc”). Defaults to “asc”.

Returns:

pd.DataFrame with quote data. For multiple symbols: dict mapping symbols to DataFrames with quote data.

Return type:

For single symbol

Raises:
class py_alpaca_api.stock.Screener(data_url: str, headers: dict[str, str], asset: py_alpaca_api.stock.assets.Assets, market: py_alpaca_api.trading.market.Market)[source]
filter_stocks(price_greater_than: float, change_condition: collections.abc.Callable[[pandas.DataFrame], pandas.Series], volume_greater_than: int, trade_count_greater_than: int, total_returned: int, ascending_order: bool) pandas.DataFrame[source]

Filter stocks based on given parameters.

Parameters:
  • price_greater_than – The minimum price threshold for the stocks.

  • change_condition – A callable function that takes in a DataFrame and returns a boolean Series. This function is used to filter the stocks based on a specific change condition.

  • volume_greater_than – The minimum volume threshold for the stocks.

  • trade_count_greater_than – The minimum trade count threshold for the stocks.

  • total_returned – The number of stocks to return.

  • ascending_order – A boolean value indicating whether to sort the stocks in ascending order by change value.

Returns:

A pandas DataFrame containing the filtered stocks.

losers(price_greater_than: float = 5.0, change_less_than: float = -2.0, volume_greater_than: int = 20000, trade_count_greater_than: int = 2000, total_losers_returned: int = 100) pandas.DataFrame[source]

Returns a filtered DataFrame of stocks that meet the specified conditions for losers.

Parameters:
  • price_greater_than (float) – The minimum price threshold for stocks to be considered losers. Default is 5.0.

  • change_less_than (float) – The maximum change threshold for stocks to be considered losers. Default is -2.0.

  • volume_greater_than (int) – The minimum volume threshold for stocks to be considered losers. Default is

  • 20000.

  • trade_count_greater_than (int) – The minimum trade count threshold for stocks to be considered losers. Default is 2000.

  • total_losers_returned (int) – The maximum number of losers to be returned. Default is 100.

Returns:

A filtered DataFrame containing stocks that meet the specified conditions for losers.

Return type:

pd.DataFrame

gainers(price_greater_than: float = 5.0, change_greater_than: float = 2.0, volume_greater_than: int = 20000, trade_count_greater_than: int = 2000, total_gainers_returned: int = 100) pandas.DataFrame[source]
Parameters:
  • price_greater_than (float) – The minimum price threshold for the stocks to be included in the gainers list.

  • 5.0. (Default is)

  • change_greater_than (float) – The minimum change (in percentage) threshold for the stocks to be included in

  • list. (the gainers)

  • 2.0. (Default is)

  • volume_greater_than (int) – The minimum volume threshold for the stocks to be included in the gainers list. Default is 20000.

  • trade_count_greater_than (int) – The minimum trade count threshold for the stocks to be included in the

  • 2000. (gainers list. Default is)

  • total_gainers_returned (int) – The maximum number of gainers to be returned. Default is 100.

Returns:

A Pandas DataFrame containing the stocks that satisfy the criteria for being gainers.

Return type:

pd.DataFrame

set_dates()[source]

Sets the dates for the screener.

This method retrieves the last two trading dates from the market calendar and assigns them to the yesterday and day_before_yesterday attributes.

Returns:

None

class py_alpaca_api.stock.Snapshots(headers: dict[str, str])[source]
get_snapshot(symbol: str, feed: str = 'iex') py_alpaca_api.models.snapshot_model.SnapshotModel[source]

Get a snapshot of a single stock symbol.

The snapshot includes the latest trade, latest quote, minute bar, daily bar, and previous daily bar data.

Parameters:
  • symbol – The stock symbol to get snapshot for.

  • feed – The data feed to use (“iex”, “sip”, or “otc”). Defaults to “iex”.

Returns:

A SnapshotModel containing the snapshot data.

Raises:
get_snapshots(symbols: list[str] | str, feed: str = 'iex') list[py_alpaca_api.models.snapshot_model.SnapshotModel] | dict[str, py_alpaca_api.models.snapshot_model.SnapshotModel][source]

Get snapshots for multiple stock symbols.

The snapshot includes the latest trade, latest quote, minute bar, daily bar, and previous daily bar data for each symbol.

Parameters:
  • symbols – A list of stock symbols or comma-separated string of symbols.

  • feed – The data feed to use (“iex”, “sip”, or “otc”). Defaults to “iex”.

Returns:

A dictionary mapping symbols to their SnapshotModel objects, or a list of SnapshotModel objects if only one symbol is provided.

Raises:
class py_alpaca_api.stock.Trades(headers: dict[str, str])[source]
get_trades(symbol: str, start: str, end: str, limit: int = 1000, feed: Literal['iex', 'sip', 'otc'] | None = None, page_token: str | None = None, asof: str | None = None) py_alpaca_api.models.trade_model.TradesResponse[source]

Retrieve historical trades for a symbol.

Parameters:
  • symbol – The stock symbol to retrieve trades for

  • start – Start time in RFC-3339 format (YYYY-MM-DDTHH:MM:SSZ)

  • end – End time in RFC-3339 format (YYYY-MM-DDTHH:MM:SSZ)

  • limit – Number of trades to return (1-10000, default 1000)

  • feed – Data feed to use (iex, sip, otc)

  • page_token – Token for pagination

  • asof – As-of time for historical data in RFC-3339 format

Returns:

TradesResponse with list of trades and pagination token

Raises:
get_latest_trade(symbol: str, feed: Literal['iex', 'sip', 'otc'] | None = None, asof: str | None = None) py_alpaca_api.models.trade_model.TradeModel[source]

Get the latest trade for a symbol.

Parameters:
  • symbol – The stock symbol to retrieve latest trade for

  • feed – Data feed to use (iex, sip, otc)

  • asof – As-of time for historical data in RFC-3339 format

Returns:

TradeModel with the latest trade data

Raises:
get_trades_multi(symbols: list[str], start: str, end: str, limit: int = 1000, feed: Literal['iex', 'sip', 'otc'] | None = None, page_token: str | None = None, asof: str | None = None) dict[str, py_alpaca_api.models.trade_model.TradesResponse][source]

Retrieve historical trades for multiple symbols.

Parameters:
  • symbols – List of stock symbols (max 100)

  • start – Start time in RFC-3339 format

  • end – End time in RFC-3339 format

  • limit – Number of trades per symbol (1-10000, default 1000)

  • feed – Data feed to use

  • page_token – Token for pagination

  • asof – As-of time for historical data

Returns:

Dictionary mapping symbols to TradesResponse objects

Raises:
get_latest_trades_multi(symbols: list[str], feed: Literal['iex', 'sip', 'otc'] | None = None, asof: str | None = None) dict[str, py_alpaca_api.models.trade_model.TradeModel][source]

Get latest trades for multiple symbols.

Parameters:
  • symbols – List of stock symbols (max 100)

  • feed – Data feed to use

  • asof – As-of time for historical data

Returns:

Dictionary mapping symbols to their latest TradeModel

Raises:
get_all_trades(symbol: str, start: str, end: str, feed: Literal['iex', 'sip', 'otc'] | None = None, asof: str | None = None) list[py_alpaca_api.models.trade_model.TradeModel][source]

Retrieve all trades for a symbol with automatic pagination.

Parameters:
  • symbol – The stock symbol

  • start – Start time in RFC-3339 format

  • end – End time in RFC-3339 format

  • feed – Data feed to use

  • asof – As-of time for historical data

Returns:

List of all TradeModel objects across all pages

Raises:
class py_alpaca_api.stock.Market(base_url: str, headers: dict[str, str])[source]
clock() py_alpaca_api.models.clock_model.ClockModel[source]

Retrieves the current market clock.

Returns:

A model containing the current market clock data.

Return type:

ClockModel

calendar(start_date: str, end_date: str) pandas.DataFrame[source]

Retrieves the market calendar for the specified date range.

Parameters:
  • start_date (str) – The start date of the calendar range in the format “YYYY-MM-DD”.

  • end_date (str) – The end date of the calendar range in the format “YYYY-MM-DD”.

Returns:

A DataFrame containing the market calendar data, with columns for the date, settlement date, open time, and close time.

Return type:

pd.DataFrame

class py_alpaca_api.stock.Stock(api_key: str, api_secret: str, api_paper: bool, market: py_alpaca_api.trading.market.Market)[source]