Python Script: TradeMaster SMA Crossover Trading Bot
Below is the complete Python script for the 'TradeMaster' trading bot. It integrates with the Alpaca API to implement a simple moving average (SMA) crossover strategy. The script is designed to run in a Jupyter Notebook and is self-contained, allowing you to run it directly without additional setup.
# TradeMaster SMA Crossover Trading Bot
# Import necessary libraries
import pandas as pd
import numpy as np
import alpaca_trade_api as tradeapi
import logging
import time
import datetime as dt
import matplotlib.pyplot as plt
# Set up logging to track trades and errors
logging.basicConfig(filename='trademaster.log', level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s')
def get_user_inputs():
"""
Get user inputs for the stock symbol, SMA periods, and initial investment.
Validates the inputs to ensure they are appropriate.
Returns:
symbol (str): Stock ticker symbol.
short_window (int): Period for short-term SMA.
long_window (int): Period for long-term SMA.
initial_investment (float): Amount to invest.
"""
symbol = input("Enter the stock ticker symbol (e.g., AAPL): ").upper()
while True:
try:
short_window = int(input("Enter the short-term SMA period (e.g., 20): "))
if short_window <= 0:
raise ValueError
break
except ValueError:
print("Please enter a positive integer for the short-term SMA period.")
while True:
try:
long_window = int(input("Enter the long-term SMA period (e.g., 50): "))
if long_window <= short_window:
raise ValueError
break
except ValueError:
print("Please enter an integer greater than the short-term period for the long-term SMA period.")
while True:
try:
initial_investment = float(input("Enter the initial investment amount (e.g., 10000): "))
if initial_investment <= 0:
raise ValueError
break
except ValueError:
print("Please enter a positive number for the initial investment amount.")
return symbol, short_window, long_window, initial_investment
def initialize_alpaca_api():
"""
Initialize the Alpaca API using user-provided API keys.
Returns:
api (alpaca_trade_api.REST): Initialized Alpaca API object.
"""
print("Please enter your Alpaca API credentials.")
api_key = input("API Key ID: ").strip()
api_secret = input("Secret Key: ").strip()
base_url = 'https://paper-api.alpaca.markets' # Using paper trading URL
try:
api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')
# Test the API connection
account = api.get_account()
print(f"Connected to Alpaca account ID: {account.id}")
logging.info(f"Connected to Alpaca account ID: {account.id}")
return api
except Exception as e:
print("Failed to connect to Alpaca API. Check your API keys and internet connection.")
logging.error(f"API connection failed: {e}")
raise
def get_historical_data(api, symbol, start_date, end_date):
"""
Fetch historical market data for the given symbol.
Args:
api (alpaca_trade_api.REST): Alpaca API object.
symbol (str): Stock ticker symbol.
start_date (str): Start date for historical data in 'YYYY-MM-DD' format.
end_date (str): End date for historical data in 'YYYY-MM-DD' format.
Returns:
df (DataFrame): Historical price data.
"""
try:
# Fetch daily price data
barset = api.get_bars(symbol, '1Day', start=start_date, end=end_date, limit=1000).df
df = barset[barset['symbol'] == symbol]
df = df.reset_index()
return df
except Exception as e:
print(f"Error fetching historical data: {e}")
logging.error(f"Error fetching historical data for {symbol}: {e}")
raise
def calculate_sma(df, short_window, long_window):
"""
Calculate short-term and long-term simple moving averages.
Args:
df (DataFrame): Historical price data.
short_window (int): Period for short-term SMA.
long_window (int): Period for long-term SMA.
Returns:
df (DataFrame): DataFrame with SMA columns added.
"""
df['SMA_Short'] = df['close'].rolling(window=short_window, min_periods=1).mean()
df['SMA_Long'] = df['close'].rolling(window=long_window, min_periods=1).mean()
return df
def generate_signals(df, short_window):
"""
Generate trading signals based on SMA crossover.
Args:
df (DataFrame): DataFrame with SMA columns.
short_window (int): Period for short-term SMA.
Returns:
df (DataFrame): DataFrame with signals column added.
"""
df['Signal'] = 0
df['Signal'][short_window:] = np.where(df['SMA_Short'][short_window:] > df['SMA_Long'][short_window:], 1, 0)
df['Position'] = df['Signal'].diff()
return df
def backtest_strategy(df, initial_investment):
"""
Backtest the SMA crossover strategy.
Args:
df (DataFrame): DataFrame with signals.
initial_investment (float): Starting capital.
Returns:
df (DataFrame): DataFrame with portfolio value calculated.
performance_metrics (dict): Dictionary of performance metrics.
"""
df['Portfolio Holdings'] = df['close'] * df['Position'].cumsum().fillna(0)
df['Portfolio Cash'] = initial_investment - (df['close'] * df['Position']).cumsum().fillna(0)
df['Portfolio Total'] = df['Portfolio Holdings'] + df['Portfolio Cash']
df['Portfolio Returns'] = df['Portfolio Total'].pct_change().fillna(0)
# Calculate performance metrics
total_return = df['Portfolio Total'].iloc[-1] - initial_investment
win_trades = df[df['Position'] == 1]['Portfolio Returns'] > 0
loss_trades = df[df['Position'] == -1]['Portfolio Returns'] < 0
total_trades = win_trades.sum() + loss_trades.sum()
win_ratio = win_trades.sum() / total_trades if total_trades > 0 else 0
drawdown = df['Portfolio Total'] - df['Portfolio Total'].cummax()
max_drawdown = drawdown.min()
performance_metrics = {
'Total Return': total_return,
'Win Ratio': win_ratio,
'Maximum Drawdown': max_drawdown
}
return df, performance_metrics
def execute_trade(api, symbol, qty, side):
"""
Execute a trade via the Alpaca API.
Args:
api (alpaca_trade_api.REST): Alpaca API object.
symbol (str): Stock ticker symbol.
qty (int): Quantity to trade.
side (str): 'buy' or 'sell'.
"""
try:
order = api.submit_order(symbol=symbol, qty=qty, side=side, type='market', time_in_force='gtc')
logging.info(f"Executed {side} order for {qty} shares of {symbol}.")
except Exception as e:
logging.error(f"Trade execution failed: {e}")
def run_live_trading(api, symbol, short_window, long_window):
"""
Run the live trading loop.
Args:
api (alpaca_trade_api.REST): Alpaca API object.
symbol (str): Stock ticker symbol.
short_window (int): Period for short-term SMA.
long_window (int): Period for long-term SMA.
"""
print("Starting live trading...")
in_position = False
try:
while True:
# Get the latest market data
barset = api.get_barset(symbol, '1Min', limit=long_window).df
df = barset[barset['symbol'] == symbol]
df = df.reset_index()
# Calculate SMAs
df = calculate_sma(df, short_window, long_window)
# Get the last two rows
last_row = df.iloc[-1]
prev_row = df.iloc[-2]
# Check for buy signal
if last_row['SMA_Short'] > last_row['SMA_Long'] and prev_row['SMA_Short'] <= prev_row['SMA_Long']:
if not in_position:
# Place a buy order
execute_trade(api, symbol, qty=1, side='buy')
in_position = True
logging.info("Buy signal generated.")
# Check for sell signal
elif last_row['SMA_Short'] < last_row['SMA_Long'] and prev_row['SMA_Short'] >= prev_row['SMA_Long']:
if in_position:
# Place a sell order
execute_trade(api, symbol, qty=1, side='sell')
in_position = False
logging.info("Sell signal generated.")
# Sleep for a minute before next iteration
time.sleep(60)
except Exception as e:
logging.error(f"Error in live trading loop: {e}")
raise
# Main execution
if __name__ == "__main__":
# Step 1: Get user inputs
symbol, short_window, long_window, initial_investment = get_user_inputs()
# Step 2: Initialize the Alpaca API
api = initialize_alpaca_api()
# Step 3: Get historical data for backtesting
end_date = dt.datetime.now().strftime('%Y-%m-%d')
start_date = (dt.datetime.now() - dt.timedelta(days=365)).strftime('%Y-%m-%d')
df = get_historical_data(api, symbol, start_date, end_date)
# Step 4: Calculate SMAs
df = calculate_sma(df, short_window, long_window)
# Step 5: Generate signals
df = generate_signals(df, short_window)
# Step 6: Backtest the strategy
df, performance_metrics = backtest_strategy(df, initial_investment)
# Step 7: Print performance metrics
print("\nPerformance Metrics:")
for key, value in performance_metrics.items():
print(f"{key}: {value}")
logging.info(f"Performance Metrics: {performance_metrics}")
# Optional: Plot the SMA crossover and portfolio value
plt.figure(figsize=(12, 6))
plt.plot(df['timestamp'], df['close'], label='Close Price', alpha=0.5)
plt.plot(df['timestamp'], df['SMA_Short'], label=f'SMA {short_window}', alpha=0.9)
plt.plot(df['timestamp'], df['SMA_Long'], label=f'SMA {long_window}', alpha=0.9)
plt.title(f'{symbol} Price and SMA Crossover')
plt.legend()
plt.show()
plt.figure(figsize=(12, 6))
plt.plot(df['timestamp'], df['Portfolio Total'], label='Portfolio Value')
plt.title('Portfolio Performance Over Time')
plt.legend()
plt.show()
# Step 8: Ask user if they want to run live trading
live_trading_choice = input("Do you want to start live trading? (yes/no): ").lower()
if live_trading_choice == 'yes':
run_live_trading(api, symbol, short_window, long_window)
else:
print("Live trading not started.")
Instructions and Explanations:
-
Imports and Setup:
- We import necessary libraries, including
alpaca_trade_api for API interactions, pandas and numpy for data handling, logging for logging significant events, and matplotlib.pyplot for plotting.
- The
get_user_inputs() function collects user inputs for the stock symbol, SMA periods, and initial investment, with input validation to ensure correct data types and sensible values.
-
API Initialization:
- The
initialize_alpaca_api() function prompts the user for their Alpaca API credentials and attempts to establish a connection. It uses the paper trading base URL to prevent real trading during testing.
-
Data Retrieval and Processing:
- The
get_historical_data() function fetches historical price data for the specified symbol using Alpaca's API.
- The
calculate_sma() function calculates the short-term and long-term SMAs.
- The
generate_signals() function identifies crossover points to generate buy and sell signals.
-
Backtesting the Strategy:
- The
backtest_strategy() function simulates the trading strategy over the historical data and calculates performance metrics such as total returns, win ratio, and maximum drawdown.
- Performance metrics are printed at the end of the backtesting phase for evaluation.
-
Live Trading Execution:
- The
run_live_trading() function enters a loop where it fetches real-time data, recalculates SMAs, and executes trades when crossover signals are detected.
- Error handling with
try-except blocks ensures the bot can recover from unexpected issues without crashing.
-
Logging:
- The script uses Python's built-in
logging library to log significant events, including API connections, trade executions, and errors.
-
User Interaction and Control:
- After backtesting, the user is prompted to start live trading or exit.
- This approach allows users to test the strategy before deploying it in a live environment.
Setting Up an Alpaca Account and Obtaining API Keys:
-
Sign Up for an Alpaca Account:
- Visit the Alpaca website and sign up for a free account.
- Choose the paper trading account during the sign-up process to avoid real-money trading.
-
Generate API Keys:
- After logging in, navigate to the dashboard.
- Go to the "API Keys" section.
- Click "Generate New Key" to get your API Key ID and Secret Key.
-
Install the Alpaca API Library:
-
Set Up Environment Variables (Optional):
- For security, you can store your API keys in environment variables instead of entering them directly in the script.
Deployment Considerations:
-
Continuous Running:
- To run the bot continuously, consider deploying it to a cloud service like AWS EC2, Heroku, or Azure. Set up the necessary environment and ensure the script runs on a reliable server with minimal downtime.
- Use a process manager like
supervisord or systemd to keep the script running and restart it automatically if it crashes.
-
Environment Setup:
- Ensure that the cloud environment has all necessary libraries installed.
- Secure your API keys by using environment variables or a secure key management service.
Potential Improvements:
Disclaimer:
- Trading involves significant risk, and the provided script is for educational purposes. Test thoroughly using paper trading before deploying with real funds. Always ensure compliance with trading regulations in your jurisdiction.
Feel free to run this script in your Jupyter Notebook, and modify it to suit your specific needs or preferences.