Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
import time
import datetime
import numpy as np
import pandas as pd
from alpaca_trade_api import REST, TimeFrame
from sklearn.ensemble import RandomForestClassifier
-----------------------
Configuration
-----------------------
API_KEY_ID = "YOUR_API_KEY_ID"
API_SECRET_KEY = "YOUR_API_SECRET_KEY"
BASE_URL = "https://paper-api.alpaca.markets" # Paper trading endpoint
SYMBOL = "AAPL" # Symbol to trade
BAR_TIMEFRAME = TimeFrame.Minute
WINDOW_SIZE = 20 # Number of past bars to consider for features
TRAIN_INTERVAL = 60 # Retrain the model every 60 iterations (example)
QUANTITY = 1 # Number of shares to trade per signal
Initialize API
api = REST(API_KEY_ID, API_SECRET_KEY, base_url=BASE_URL)
-----------------------
Utility Functions
-----------------------
def get_historical_data(symbol, limit=200):
"""Fetch historical bar data for the symbol."""
end = pd.Timestamp.now(tz='America/New_York')
start = end - pd.Timedelta('2 days') # get enough data for training
bars = api.get_bars(symbol, BAR_TIMEFRAME, start.isoformat(), end.isoformat(), limit=limit).df
bars = bars[bars['symbol'] == symbol]
bars = bars.sort_index()
return bars
def generate_features(data):
"""
Given a pandas DataFrame of historical bars with columns ['open','high','low','close','volume'],
generate features for the ML model.
"""
# Example features:
# - Past returns
# - Simple rolling means
data['returns'] = data['close'].pct_change()
data['rolling_mean'] = data['close'].rolling(5).mean()
data['rolling_std'] = data['close'].rolling(5).std()
data['rolling_volume_mean'] = data['volume'].rolling(5).mean()
def prepare_training_data(data, window_size=20):
"""
Prepare X, y for training.
We predict whether the close price in the next bar is higher than current close.
"""
# Shift the close forward by one to get the "future" close for the target.
data['future_close'] = data['close'].shift(-1)
data = data.dropna()
def place_order(symbol, qty, side):
"""Place an order via Alpaca."""
try:
order = api.submit_order(
symbol=symbol,
qty=qty,
side=side,
type='market',
time_in_force='day'
)
print(f"Placed {side} order for {qty} shares of {symbol}.")
return order
except Exception as e:
print(f"Error placing order: {e}")
return None
-----------------------
Main Bot Logic
-----------------------
if name == "main":
# Initial data and model training
data = get_historical_data(SYMBOL, limit=1000)
data = generate_features(data)
X, y = prepare_training_data(data, window_size=WINDOW_SIZE)