Get cryptobars data

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?

Hi :waving_hand:

I’m guessing you’re using an old version of alpaca-trade-api. You can check this by running

pip show alpaca-trade-api

To upgrade it run

pip install --upgrade alpaca-trade-api

After that you will get another error when running your code:

Error fetching historical data for BTC/USD: expected list, str found

To fix that, change the symbol parameter in the get_crypto_bars call to symbol=[symbol]. With that, your code will run successfully :white_check_mark:

By the way, the whole alpaca-trade-api-python SDK has been deprecated, if you’re just starting with Alpaca, it’s recommended to use alpaca-py instead.