Premarket data in python

I heard that u can get pre-market data from Alpaca markets.api can anyone pls show me how to get pre-market data in python pls

@python_stuff There isn’t anything special that needs to be done to fetch pre-market data. If the request is for times outside of regular market hours, and there is available data, then it will be returned.

Below would fetch all data (pre-market, market, and post-market) bars for SPY and IBM.

# import needed packages
!pip install -q alpaca-py
import pandas as pd
from alpaca.data import StockHistoricalDataClient, TimeFrame, TimeFrameUnit
from alpaca.data.requests import StockBarsRequest

# instantiate a 'client' to store data needed for API calls
ALPACA_API_KEY = 'xxxxx'
ALPACA_API_SECRET_KEY = 'xxxxx'

data_client = StockHistoricalDataClient(ALPACA_API_KEY, ALPACA_API_SECRET_KEY)

# set the start and end times and symbols
start = pd.to_datetime("2024-03-25").tz_localize('America/New_York')
end = pd.to_datetime("2024-03-26").tz_localize('America/New_York')
symbols = ["SPY", "IBM"]

# fetch 1 hour bars and convert to dataframe with the market timezone
bars = data_client.get_stock_bars(StockBarsRequest(
            symbol_or_symbols = symbols,
            timeframe=TimeFrame(amount=1, unit=TimeFrameUnit.Hour),
            start = start,
            end = end,
            feed = 'sip',
          )).df.tz_convert('America/New_York', level= 'timestamp')

Here is the result. Note that there may not be bars if there are no ‘valid’ trades. This is especially true for pre and post market where trading can be very light. Notice the first bar for IBM isn’t until 6:00 while the first bar for SPY is right at the open of pre-market hours at 4:00.

1 Like

when I change the date to today i get an error saying my supriction does not permit that

@python_stuff If one only has the Free Market Data subscription then the most recent 15 minutes are not available. A query for that time will result in an error. To avoid this, one can simply set the end datetime to not include the most recent 15 minutes. Perhaps like this.

# set the start and end times and symbols
current_time = pd.Timestamp('now', tz="America/New_York")

start = pd.to_datetime("2024-03-25").tz_localize('America/New_York')
end = current_time - pd.Timedelta('15Min')
symbols = ["SPY", "IBM"]

# fetch 1 hour bars and convert to dataframe with the market timezone
bars = data_client.get_stock_bars(StockBarsRequest(
            symbol_or_symbols = symbols,
            timeframe=TimeFrame(amount=1, unit=TimeFrameUnit.Hour),
            start = start,
            end = end,
            feed = 'sip',
          )).df.tz_convert('America/New_York', level= 'timestamp')
2 Likes