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.

2 Likes

@Dan_Whitnable_Alpaca I found this article to help clarify what I am doing wrong but I am not having any luck.

I am transitioning everything slowly to alpca-py and currently working on get_stock_bars. I am getting this error however:

2024-03-19 10:51:00,559 - ERROR - Error in on_bars: 1 validation error for StockBarsRequest
timeframe
  Input should be an instance of TimeFrame [type=is_instance_of, input_value=<alpaca_trade_api.rest.Ti...t at 0x0000025AF8ADA830>, input_type=TimeFrame]
    For further information visit https://errors.pydantic.dev/2.6/v/is_instance_of

This is my code setup:

current_time = pd.Timestamp.now(tz="America/New_York").floor("1s")
        today_date = current_time.strftime("%Y-%m-%d")
        yesterday_date = (current_time - pd.Timedelta(days=3)).strftime("%Y-%m-%d")

        timeframe_minute = TimeFrame(1, TimeFrameUnit.Minute)

        request_params = StockBarsRequest(
            symbol_or_symbols=[self.symbol],
            timeframe=timeframe_minute,
            start=yesterday_date,
            end=today_date,
            adjustment=Adjustment.RAW,
            feed=DataFeed.SIP
        )

        self.data_bars = alpaca_py_stockdataclient_api.get_stock_bars(request_params).df

I cannot for the life of me see what is going wrong. I can get it working perfectly with get_bars:

self.data_bars = rest_api.get_bars(self.symbol, TimeFrame(1, TimeFrameUnit.Minute), start=yesterday_date, end=today_date, adjustment='raw').df

@FIRMCEO Not sure why your code doesn’t work? I was able to run very similar code without an error

from alpaca.data import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame, TimeFrameUnit
from alpaca.data.enums import DataFeed, Adjustment

client = StockHistoricalDataClient(ALPACA_API_KEY, ALPACA_API_SECRET_KEY)

current_time = pd.Timestamp.now(tz="America/New_York").floor("1s")
today_date = current_time.strftime("%Y-%m-%d")
yesterday_date = (current_time - pd.Timedelta(days=3)).strftime("%Y-%m-%d")

timeframe_minute = TimeFrame(1, TimeFrameUnit.Minute)

request_params = StockBarsRequest(
            symbol_or_symbols='SPY',
            timeframe=timeframe_minute,
            start=yesterday_date,
            end=today_date,
            adjustment=Adjustment.RAW,
            feed=DataFeed.SIP
        )

client.get_stock_bars(request_params).df

Perhaps look at your version of the alpaca-py SDK and make certain it is the latest.

I did the code standalone and I was able to get a printed set of data_bars. Which is wierd because I didn’t change anything with the timeframe, just applied a symbol directly in the symbol_or_symbols.

What is new now, that is brought to my attention, unlike the restAPI, is that even though my ‘end’ is TODAYS date I am only getting yesterday bars, for the 18th and nothing for today the 19th?

current_time = pd.Timestamp.now(tz="America/New_York").floor("1s")
today_date = current_time.strftime("%Y-%m-%d")
print(today_date)
yesterday_date = (current_time - pd.Timedelta(days=3)).strftime("%Y-%m-%d")
print(yesterday_date)

timeframe_minute = TimeFrame(1, TimeFrameUnit.Hour)

request_params = StockBarsRequest(
    symbol_or_symbols=["AAPL"],
    timeframe=timeframe_minute,
    start=yesterday_date,
    end=today_date,
    adjustment=Adjustment.RAW,
    feed=DataFeed.SIP
)

data_bars = alpaca_py_stockdataclient_api.get_stock_bars(request_params).df

print(data_bars)
2024-03-19
2024-03-16
                                     open      high       low    close      volume  trade_count        vwap
symbol timestamp                                                                                           
AAPL   2024-03-18 08:00:00+00:00  173.400  174.0000  173.2700  173.750     57140.0       1343.0  173.644298
       2024-03-18 09:00:00+00:00  173.730  173.9700  173.1500  173.510     27015.0        494.0  173.600521
       2024-03-18 10:00:00+00:00  173.270  173.8600  173.0300  173.110     60022.0       1165.0  173.390566
       2024-03-18 11:00:00+00:00  173.110  174.8000  172.4100  174.640    335775.0       6256.0  173.558252
       2024-03-18 12:00:00+00:00  173.100  175.1900  172.4100  174.680    763990.0      12863.0  174.450807
       2024-03-18 13:00:00+00:00  174.530  177.5800  174.2700  176.758  15385991.0     163908.0  176.357032
       2024-03-18 14:00:00+00:00  176.770  177.7100  176.5850  177.180  11257483.0     199480.0  177.128022
       2024-03-18 15:00:00+00:00  177.180  177.3300  175.6115  175.640   7405847.0     184044.0  176.512867
       2024-03-18 16:00:00+00:00  175.640  175.6500  175.0750  175.080   5750690.0      67657.0  175.365402
       2024-03-18 17:00:00+00:00  175.080  175.4500  174.7400  175.116   5046812.0      59679.0  175.102547
       2024-03-18 18:00:00+00:00  175.120  175.5400  174.8200  174.975   5497583.0      55552.0  175.185205
       2024-03-18 19:00:00+00:00  174.975  175.1760  173.5200  173.700   9622001.0     101460.0  174.448655
       2024-03-18 20:00:00+00:00  173.790  173.7900  173.0000  173.260  14014712.0       5713.0  173.712317
       2024-03-18 21:00:00+00:00  173.231  174.1153  173.2200  173.800    253491.0       2811.0  173.608822
       2024-03-18 22:00:00+00:00  173.800  173.9000  173.4000  173.500     67759.0       1219.0  173.611733
       2024-03-18 23:00:00+00:00  173.420  173.6900  173.3300  173.590     38300.0       1059.0  173.574086

@FIRMCEO The alpaca-py SDK really expects timezone aware datetime objects and not strings for datetime parameters. When it tries to convert strings, which are not timezone aware, to datetimes it 1) assumes the timezone is UTC and then 2) assumes if no time is given that the time is 00:00. So, if it is passed the string “2024-03-19” it assumes it is 2024-03-19 00:00:00Z which is 2024-03-18 20:00:00-0400. That is why you only get hour bars from 03-18.

It’s best to always pass timezone aware datetimes as parameters. Maybe like this

current_time = pd.Timestamp.now(tz="America/New_York")
yesterday_date = current_time - pd.Timedelta(days=3)

request_params = StockBarsRequest(
    symbol_or_symbols=["AAPL"],
    timeframe=TimeFrame(1, TimeFrameUnit.Hour),
    start=yesterday_date,
    end=current_time,
    adjustment=Adjustment.RAW,
    feed=DataFeed.SIP
)

data_bars = alpaca_py_stockdataclient_api.get_stock_bars(request_params).df