5 min read
Alpaca Stock Trading Bot

Alpaca Trading Bot

This is an advanced algorithmic trading bot built with Python that executes automated buy and sell orders on the Alpaca trading platform. The bot implements sophisticated trading strategies with risk management, portfolio optimization, and real-time market analysis capabilities.

Features

  • Automated Trading - Execute buy/sell orders automatically based on strategies
  • Multiple Strategies - Moving averages, RSI, MACD, and custom strategies
  • Risk Management - Position sizing, stop-loss, and take-profit orders
  • Real-time Data - Live market data streaming and analysis
  • Portfolio Management - Multi-asset portfolio tracking and rebalancing
  • Backtesting - Historical strategy testing and performance analysis
  • Performance Analytics - Comprehensive trading metrics and reporting
  • Paper Trading - Risk-free testing with paper trading mode

Tech Stack

  • Python - Primary programming language
  • Alpaca API - Commission-free trading platform integration
  • Pandas - Data manipulation and analysis
  • NumPy - Numerical computations and calculations
  • Matplotlib/Plotly - Data visualization and charts
  • yfinance - Market data fetching and analysis
  • TA-Lib - Technical analysis indicators
  • SQLite/PostgreSQL - Data storage and logging

Trading Strategies Implemented

1. Moving Average Crossover

  • Fast MA (10-day) vs Slow MA (30-day)
  • Buy Signal - Fast MA crosses above Slow MA
  • Sell Signal - Fast MA crosses below Slow MA
  • Risk Management - 2% stop-loss, 6% take-profit

2. RSI (Relative Strength Index)

  • Oversold - RSI < 30 (Buy signal)
  • Overbought - RSI > 70 (Sell signal)
  • Neutral Zone - RSI between 30-70 (Hold)

3. MACD (Moving Average Convergence Divergence)

  • Bullish Signal - MACD line crosses above signal line
  • Bearish Signal - MACD line crosses below signal line
  • Divergence Detection - Price vs MACD divergence analysis

4. Custom Mean Reversion Strategy

  • Bollinger Bands - Price channel analysis
  • Mean Reversion - Buy at lower band, sell at upper band
  • Volatility Adjustment - Dynamic position sizing based on volatility

Risk Management System

Position Sizing

  • Kelly Criterion - Optimal position sizing based on win rate
  • Fixed Percentage - 1-2% of portfolio per trade
  • Volatility Adjusted - Position size based on asset volatility

Stop-Loss & Take-Profit

  • Trailing Stop-Loss - Dynamic stop-loss adjustment
  • Fixed Stop-Loss - 2-3% maximum loss per trade
  • Take-Profit Targets - Multiple profit targets (2R, 3R, 5R)

Portfolio Diversification

  • Asset Allocation - Multiple stocks across sectors
  • Correlation Analysis - Low-correlation asset selection
  • Sector Rotation - Dynamic sector allocation

Performance Metrics

  • Total Return - Overall portfolio performance
  • Sharpe Ratio - Risk-adjusted returns
  • Maximum Drawdown - Largest peak-to-trough decline
  • Win Rate - Percentage of profitable trades
  • Profit Factor - Gross profit / Gross loss ratio
  • Calmar Ratio - Annual return / Maximum drawdown

Installation & Setup

  1. Clone the repository:

    git clone https://github.com/1cbyc/1cbyc-trading-bot.git
    cd 1cbyc-trading-bot
    
  2. Install dependencies:

    pip install -r requirements.txt
    
  3. Configure environment variables:

    cp .env.example .env
    # Add your Alpaca API credentials
    ALPACA_API_KEY=your_api_key
    ALPACA_SECRET_KEY=your_secret_key
    ALPACA_BASE_URL=https://paper-api.alpaca.markets
    
  4. Configure trading parameters:

    # config/trading_config.py
    SYMBOLS = ['AAPL', 'GOOGL', 'MSFT', 'TSLA']
    STRATEGY = 'moving_average_crossover'
    POSITION_SIZE = 0.02  # 2% of portfolio
    STOP_LOSS = 0.02      # 2% stop-loss
    TAKE_PROFIT = 0.06    # 6% take-profit
    
  5. Run the bot:

    python main.py
    

Strategy Configuration

Moving Average Strategy

strategy_config = {
    'fast_period': 10,
    'slow_period': 30,
    'min_holding_period': 5,
    'max_holding_period': 30
}

RSI Strategy

rsi_config = {
    'period': 14,
    'oversold': 30,
    'overbought': 70,
    'rsi_smoothing': 3
}

Backtesting Results

Sample Performance (2023-2024):

  • Total Return: 23.4%
  • Sharpe Ratio: 1.67
  • Maximum Drawdown: 8.2%
  • Win Rate: 68.5%
  • Profit Factor: 2.1
  • Total Trades: 156

Real-time Monitoring

Dashboard Features:

  • Live Portfolio Value - Real-time portfolio tracking
  • Active Positions - Current open positions
  • Trade History - Complete trade log
  • Performance Charts - Interactive performance visualization
  • Risk Metrics - Real-time risk assessment

Alerts & Notifications:

  • Trade Executions - Email/SMS notifications
  • Risk Alerts - Portfolio risk warnings
  • Performance Updates - Daily/weekly performance reports

Future Enhancements

  • Machine Learning Integration - ML-based signal generation
  • Multi-Exchange Support - Support for other exchanges
  • Options Trading - Options strategy implementation
  • Crypto Trading - Cryptocurrency support
  • Mobile App - iOS/Android mobile application
  • Cloud Deployment - AWS/Azure cloud deployment
  • Advanced Analytics - Enhanced performance analytics

Security & Compliance

  • API Key Security - Encrypted API key storage
  • Paper Trading - Risk-free testing environment
  • Compliance - Trading regulations compliance
  • Audit Trail - Complete trade audit logging
  • Data Protection - Secure data handling and storage

How to Use my Bot