HTTPError: 400 Client Error: Bad Request for url

from this link , i got the code to fetching Historical Bars data ,
(How to Fetch Historical Data in Alpaca Market Data API v2)
but i keep receving this error:

HTTPError: 400 Client Error: Bad Request for url: https://data.alpaca.markets/v2/stocks/AAPL/bars?timeframe=day&adjustment=raw&limit=5

my code:


!pip install alpaca_trade_api

import alpaca_trade_api as tradeapi
import time
symbol = 'AAPL'
APCA_API_KEY_ID = '******************'
APCA_API_SECRET_KEY = '*****************************'
APCA_API_BASE_URL = f"https://data.alpaca.markets/v2/stocks/{symbol}/bars"

api = tradeapi.REST(APCA_API_KEY_ID,
                    APCA_API_SECRET_KEY,
                    base_url=APCA_API_BASE_URL,
                    api_version="v2")

#get daily price for aaple over the last 5 days
barset = api.get_bars(symbol, 'day', limit=5)
Apple_bars = barset[symbol]

#See how muvh apple moved in that timeframe
week_open = Apple_bars[0].o
week_close = Apple_bars[-1].c
percent_change = (week_close - week_open) / week_open
print('AAPL moved {}% over the last 5 days'.format(percent_change))

can somebody explain what’s exatctly am i doing wrong?
Any help for a newbie appreciated.

@Nayrouz_Hamdy A few things to do to ge your code working…

The initial error is because you specified ‘day’ and not a quantity of days ‘1day’ (which the method expects). However, that still won’t exactly be what you want. You need to specify a ‘start’ date. The method defaults to the start and end dates as the current datetime. Without specifying a start you only get 1 day (ie today thru today). I personally like the pandas datetime methods (rather trhan time) so I’d do this (including a few other fixes).

!pip install alpaca_trade_api

import alpaca_trade_api as tradeapi
import pandas as pd

APCA_API_KEY_ID = 'PK8M3BTPX6BXKWMCZBMS'
APCA_API_SECRET_KEY = 'tA79R6MOjvhOIFGIdhfYubUkHiYhJ1wgX691f9jE'

APCA_API_BASE_URL = f"https://data.alpaca.markets/v2/stocks/{symbol}/bars"

api = tradeapi.REST(APCA_API_KEY_ID,
                    APCA_API_SECRET_KEY,
                    base_url=APCA_API_BASE_URL,
                    api_version="v2")


# set today and a day far enough back in time to account for weekends and non-trading days
LOOKBACK = 5
today = pd.to_datetime('today', utc=True).tz_convert('America/New_York')
today_minus_lookback = today - pd.Timedelta(LOOKBACK+5, 'D')

barset = api.get_bars(symbol,
                      '1day', 
                      start=today_minus_lookback.isoformat(),
                      end=today.isoformat() ,
                      limit=LOOKBACK+1).df

percent_change = barset.close.pct_change(LOOKBACK)[-1]

print('AAPL moved {}% over the last 5 days'.format(percent_change))