How to get bars within 30 mins time frame?

I already know how to get market data for 1 hour and 1 min,

but how do I get 30mins time frame data? Anybody could show the python code?

Thanks

@sheep Setting the timeframe depends upon the python SDK you are using

If one uses the alpaca-py SDK then one must create a TimeFrame object and then pass it as a parameter to the get_stock_bars method. The TimeFrame class is documented here.

!pip install alpaca-py

from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.timeframe import TimeFrame, TimeFrameUnit
from alpaca.data.requests import StockBarsRequest

ALPACA_API_KEY_ID = 'xxxxx'
ALPACA_API_SECRET_KEY = 'xxxxx'

# Create a data client to fetch historical data
data_client = StockHistoricalDataClient(ALPACA_API_KEY_ID, ALPACA_API_SECRET_KEY)

# Set parameters
symbols=['AIU', 'AMD', 'MSFT', 'NVDA', 'TOVX']

start_date = pd.to_datetime("2022-01-03").tz_localize('America/New_York')
end_date = pd.to_datetime("2022-01-04").tz_localize('America/New_York')

timeframe_30_min = TimeFrame(30, TimeFrameUnit.Minute)

request_parameters = StockBarsRequest(
                symbol_or_symbols=symbols,
                timeframe=timeframe_30_min,
                start=start_date,
                end=end_date,
                )

# Fetch data and convert to dataframe
min_30_bars = data_client.get_stock_bars(request_parameters).df

It’s much more straightforward using the alpaca-trade-api. One can simply use strings like “30Min”, “10Min”, or “2Hour” to specify the bars.

!pip install alpaca-trade-api
import alpaca_trade_api as alpacaapi

ALPACA_API_KEY_ID = 'xxxxx'
ALPACA_API_SECRET_KEY = 'xxxxx'

api_data = alpacaapi.REST(ALPACA_API_KEY_ID, ALPACA_API_SECRET_KEY)

# Set parameters
symbols=['AIU', 'AMD', 'MSFT', 'NVDA', 'TOVX']

start_date = pd.to_datetime("2022-01-03").tz_localize('America/New_York')
end_date = pd.to_datetime("2022-01-04").tz_localize('America/New_York')

min_30_bars = api_data.get_bars(symbols,
                         '30Min',
                         start=start_date.isoformat(),
                         end=end_date.isoformat(),
                         ).df

Hope that helps.

1 Like