(Remember: At the moment Alpaca uses different symbols for executing orders such as “BTC/USD” and checking portfolio positions such as “BTCUSD”.)
KEY_ID = "your API KEY" #replace it with your own KEY_ID from Alpaca: https://alpaca.markets/
SECRET_KEY = "your SECRET KEY" #replace it with your own SECRET_KEY from Alpaca
import warnings
warnings.filterwarnings('ignore')
Step 1: Alpaca Setup & Python Environment
Sign up for an Alpaca account: https://alpaca.markets/
Get your API Key ID and Secret Key from your paper trading account dashboard.
Install necessary Python libraries:
pip install alpaca-trade-api pandas scikit-learn xgboost numpy pandas-ta
Set up API credentials (environment variables are best):
import os
import alpaca_trade_api as tradeapi
import pandas as pd
from datetime import datetime, timedelta
import time
# For Paper Trading
os.environ['APCA_API_BASE_URL'] = 'https://paper-api.alpaca.markets'
# Replace with your actual keys or set them as environment variables
os.environ['APCA_API_KEY_ID'] = "your API KEY" #replace it with your own KEY_ID from Alpaca: https://alpaca.markets/
os.environ['APCA_API_SECRET_KEY'] = "your SECRET KEY" #replace it with your own SECRET_KEY from Alpaca
API_KEY = os.getenv('APCA_API_KEY_ID')
API_SECRET = os.getenv('APCA_API_SECRET_KEY')
BASE_URL = os.getenv('APCA_API_BASE_URL')
api = tradeapi.REST(API_KEY, API_SECRET, BASE_URL, api_version='v2')
print("Connected to Alpaca Paper Trading.")
# Check account
# account = api.get_account()
# print(f"Account status: {account.status}")
Step 2: Data Acquisition
def fetch_data(symbol, timeframe, start_date_str, end_date_str=None):
"""Fetches historical crypto data from Alpaca."""
if end_date_str is None:
end_date_str = datetime.now().strftime('%Y-%m-%d')
# Alpaca API expects ISO 8601 format for start/end times
# And it has a limit on how many bars can be fetched per request (e.g., 10000 for crypto)
# So we may need to fetch in chunks if requesting a long period.
all_bars = []
start_dt = pd.to_datetime(start_date_str, utc=True)
end_dt = pd.to_datetime(end_date_str, utc=True)
# Fetch data in chunks to avoid hitting API limits for very long periods
# For 1-minute data, 10000 bars is about 7 days.
# Let's fetch data in smaller chunks, e.g., 5 days at a time.
current_start = start_dt
while current_start < end_dt:
chunk_end = min(current_start + timedelta(days=5), end_dt) # Adjust chunk size as needed
print(f"Fetching data from {current_start.isoformat()} to {chunk_end.isoformat()}")
# Alpaca's get_crypto_bars expects start and end in ISO format
bars = api.get_crypto_bars(
symbol,
timeframe,
start=current_start.isoformat(),
end=chunk_end.isoformat(),
limit=10000 # Max limit per request
).df
if bars.empty:
print(f"No data found for chunk starting {current_start.isoformat()}")
if current_start + timedelta(days=5) > end_dt and not all_bars: # if first chunk and no data
break
current_start += timedelta(days=5) # Move to next chunk period
time.sleep(1) # Be nice to the API
continue
all_bars.append(bars)
# Update current_start to the timestamp of the last bar fetched + 1 minute
# to avoid overlap and to ensure we move forward.
if not bars.index.empty:
current_start = bars.index[-1] + pd.Timedelta(minutes=1)
else: # Should not happen if bars is not empty, but as a safeguard
current_start += timedelta(days=5)
time.sleep(1) # Respect API rate limits
if not all_bars:
print("No data fetched. Check your date range or symbol.")
return pd.DataFrame()
df = pd.concat(all_bars)
df = df[~df.index.duplicated(keep='first')] # Remove potential duplicates from chunking
df = df.sort_index() # Ensure chronological order
df = df[df.index <= end_dt] # Ensure we don't go past the requested end_dt
return df
# Example usage:
symbol = "BTC/USD" # Alpaca uses "BTC/USD" for crypto pairs
timeframe = tradeapi. টাইমফ্রেম.মিনিট # or "1Min" for older SDK versions
# Fetch last 30 days of data for example
start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
# end_date = datetime.now().strftime('%Y-%m-%d') # Fetches up to now
btc_data = fetch_data(symbol, timeframe, start_date)
if not btc_data.empty:
print(f"Fetched {len(btc_data)} rows of {symbol} data.")
print(btc_data.head())
print(btc_data.tail())
else:
print("Failed to fetch data.")
super ai .:. thegod .:. improve yourself .:. improve your business .:. improve the world .:. about .:. contact .:. general ai .:. ai / ml courses .:. ai art gallery