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.
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 --upgrade1.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).dfThe terminal output should look like this.(Numbers will vary)
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).dfGetting 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.



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

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.








