How to get only open market data?

Hi,

I want to get only the data when the market is open. Like 9:30 AM to 4:00 PM EST.

Can you help me to convert my script?
Thanks

data_client = StockHistoricalDataClient(KEY_ID, SECRET_KEY)

start_time = pd.to_datetime(“2024-03-20”).tz_localize(‘America/New_York’)
end_time = pd.to_datetime(“2024-03-21”).tz_localize(‘America/New_York’)

request_params = StockBarsRequest(
symbol_or_symbols=[“PARA”, “AAPL”],
timeframe=TimeFrame(15, TimeFrameUnit.Minute),
start=start_time,
end=end_time
)

bars_df = data_client.get_stock_bars(request_params).df.tz_convert(‘America/New_York’, level=1)
bars_df

@huseyin There is a handy pandas method between_time which can be used to get just market bars. The issue however is this method doesn’t work with a multi-index. So, the trick is to reset the index, fetch the market hour data, then put the index back. Something like this

market_bars = (bars_df
                 .reset_index('symbol')
                 .between_time('9:30', '16:00')
                 .reset_index()
                 .set_index(['symbol', 'timestamp'])
               )

I am getting the data with 15 mins intervals. For some tickers some intervals are missing. For example for AZO it jumps from 13:00 to 13:30. 13:15 row is missing?
What is the meaning of it?

@huseyin Bars are only created if there are ‘valid’ trades during the bar. No valid trades then no bar. That is why some bars appear to be ‘missing’. You may want to take a look at this article for a bit more explanation how bars are calculated.

If one is using IEX data (provided with a Free Market Data subscription) the only trades used in bar calculations are trades which occurred on the IEX exchange. There are some symbols which barely trade, if at all, on the IEX exchange. This can further exacersbate the number of ‘missing’ bars. It’s best to always specify feed=DataFeed.SIP to ensure one is fetching full market SIP data.

1 Like