The code below (just getting historic stock prices for TQQQ) returns
“Error fetching data: {“message”: “endpoint not found.”}”
I have tried data.alpaca.markets/, data.alpaca.markets/v1, data.alpaca.markets/v2
what should I be using?
import requests
Alpaca API endpoint
BASE_URL = “https://data.alpaca.markets/”
Your Alpaca API credentials
API_KEY = “xxx”
SECRET_KEY = “xxx”
Symbol and time frame for historical data
symbol = “TQQQ”
start_date = “2023-01-01”
end_date = “2023-05-13”
Request headers
headers = {
“APCA-API-KEY-ID”: API_KEY,
“APCA-API-SECRET-KEY”: SECRET_KEY
}
Fetch historical stock data
def get_historical_data(symbol, start_date, end_date):
endpoint = f"{BASE_URL}/bars/1D"
params = {
“symbols”: symbol,
“start”: start_date,
“end”: end_date,
“limit”: 1000
}
response = requests.get(endpoint, headers=headers, params=params)
if response.status_code == 200:
return response.json()
else:
print("Error fetching data:", response.text)
return None
Call the function to get historical data
historical_data = get_historical_data(symbol, start_date, end_date)
Print the retrieved data
if historical_data:
for bar in historical_data[symbol]:
date = bar[“t”]
open_price = bar[“o”]
high_price = bar[“h”]
low_price = bar[“l”]
close_price = bar[“c”]
volume = bar[“v”]
print(f"Date: {date}")
print(f"Open: {open_price}, High: {high_price}, Low: {low_price}, Close: {close_price}")
print(f"Volume: {volume}")
print()