import alpaca_trade_api as tradeapi
import json
import pandas as pd
from datetime import datetime, timedelta, timezone
def get_historical_data(symbol, timeframe="1Hour", limit=100):
# Load API credentials from config.json
with open("config.json", "r") as f:
config = json.load(f)
api_key = config["API_KEY"]
api_secret = config["API_SECRET"]
base_url = config["BASE_URL"]
# Initialize Alpaca API
api = tradeapi.REST(api_key, api_secret, base_url, api_version="v2")
try:
# Define the start and end dates for the historical data
end_date = datetime.now(timezone.utc)
start_date = end_date - timedelta(days=7) # Fetch data for the last 7 days
# Fetch historical data for the given symbol
bars = api.get_crypto_bars(
symbol=symbol,
timeframe=timeframe,
start=start_date.isoformat(),
end=end_date.isoformat(),
limit=limit
).df
print(f"\nHistorical Data for {symbol}:\n")
print(bars)
return bars
except Exception as e:
print(f"Error fetching historical data for {symbol}: {e}")
return pd.DataFrame()
if __name__ == "__main__":
# Example usage
symbol = "BTC/USD" # Replace with the desired symbol
timeframe = "1Hour" # Replace with the desired timeframe
limit = 100 # Number of data points to fetch
get_historical_data(symbol, timeframe, limit)
Error fetching historical data for BTC/USD:
404 Client Error: Not Found for URL:
https://data.alpaca.markets/v1beta1/crypto/BTC/USD/bars?timeframe=1Hour&start=2025-03-15T07%3A47%3A13.365406%2B00%3A00&end=2025-03-22T07%3A47%3A13.365406%2B00%3A00&limit=100
So, here’s the question, what’s the deal? Why when specifying v2, I don’t see v2? Why can’t I get what I need according to the documentation?