This tutorial will be a step by step demonstration of how to get market data using the Alpaca API. We will move forward assuming that you’ve registered on Alpaca.

💡 Before You Begin

To get the most out of this guide, explore the following resources first:

Alpaca provides market data from various sources. Check the Market Data API doc to learn more about your data options.

Step 1: Setup

1-1. Install / Update Alpaca-py

!uv pip install alpaca-py --upgrade

1.2 Import Necessary Packages

from alpaca.data.historical.stock import StockHistoricalDataClient

Step 2: setup stock historical data client

stock_historical_data_client = StockHistoricalDataClient(ALPACA_API_KEY, ALPACA_SECRET_KEY)

Similarly let’s create a function to get market data for Apple(AAPL). Within this function we print out how much AAPL has moved in the specific timeframe.

One can find similar code in the Alpaca Docs

# get historical bars by symbol
# ref. https://docs.alpaca.markets/reference/stockbars-1
now = datetime.now(ZoneInfo("America/New_York"))
req = StockBarsRequest(
    symbol_or_symbols = [symbol],
    timeframe=TimeFrame(amount = 1, unit = TimeFrameUnit.Hour), # specify timeframe
    start = now - timedelta(days = 5),                          # specify start datetime, default=the beginning of the current day.
    # end=None,                                        # specify end datetime, default=now
    limit = 2,                                               # specify limit
)
stock_historical_data_client.get_stock_bars(req).df

The terminal output should look like this.(Numbers will vary)

Terminal Output

Getting Historical Trades by Symbol

# get historical trades by symbol
req = StockTradesRequest(
    symbol_or_symbols = [symbol],
    # specify start datetime, default=the beginning of the current day.
    start = now - timedelta(days = 5),
    # specify end datetime, default=now
    # end=None,
    # specify limit
    limit = 2,                                                
)
stock_historical_data_client.get_stock_trades(req).df

Getting Historical Quotes by Symbol

req = StockQuotesRequest(
    symbol_or_symbols = [symbol],
    start = now - timedelta(days = 5),                      # specify start datetime, default=the beginning of the current day.
    # end=None,                                             # specify end datetime, default=now
    limit = 2,                                              # specify limit
)
stock_historical_data_client.get_stock_quotes(req).df


Thank you for using Alpaca. Here are a couple more links that you might be interested in.

Alpaca GitHub repository

Alpaca
Alpaca builds an API for free stock trading. Alpaca has 39 repositories available. Follow their code on GitHub.

Alpaca Blog

Alpaca Blog | API for Stock Trading
Alpaca Blog for product updates, new integration, and more. Alpaca’s commission-free trading API is built for algorithmic trading and building apps

Alpaca Forum

Alpaca Community Forum
Alpaca user forum for FAQ, feature requests, many discussions around Alpaca stock trading API

Alpaca API documentation

Documentation | Alpaca
Alpaca API lets you build and trade with real-time market data for free.

Sign up for the weekly newsletter to keep up with the API updates and upcoming competitions, job opportunities by clicking here.

Alpaca Launches its Newsletter for Quants & Developers
In Alpaca Newsletter for quants & developers, we will keep you updated on our product and community developments, market and research updates as well as list jobs and internships.

You can also follow Alpaca and our weekly updates on our LinkedIn, Alpaca Community Slack and @AlpacaHQ on Twitter!

Commission-Free trading means that there are no commission charges for Alpaca self-directed individual cash brokerage accounts that trade U.S. listed securities through an API. Relevant SEC and FINRA fees may apply.

Brokerage services are provided by Alpaca Securities LLC ("Alpaca"), memberFINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.