Skip to content

matthewd-so/trading_bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

19 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Stock Trading Engine πŸ“ˆ

Screenshot 2026-01-30 at 12 34 53β€―AM

A professional-grade stock trading bot featuring a modern web dashboard for backtesting trading strategies with interactive visualizations and comprehensive performance analytics.

🎯 Two Interfaces Available

1. Modern Web Dashboard (Recommended) ⭐

Professional Plotly Dash interface with:

  • Interactive candlestick charts with zoom/pan
  • Real-time indicator overlays
  • Dynamic strategy parameter tuning
  • Comprehensive performance metrics
  • Trade log and portfolio visualization

2. Legacy Desktop GUI

Traditional Tkinter interface for basic backtesting


✨ Key Features

πŸ“Š Advanced Visualizations

  • Interactive Candlestick Charts: Fully interactive charts with zoom, pan, and hover capabilities
  • Technical Indicators: Real-time overlay of moving averages, Bollinger Bands, RSI, MACD, and more
  • Buy/Sell Markers: Clear visual indicators for all trade signals
  • Portfolio Tracking: Real-time portfolio value chart with performance tracking

πŸŽ›οΈ 9 Professional Trading Strategies

  1. Moving Average Crossover - Classic trend-following strategy
  2. RSI Strategy - Momentum-based using Relative Strength Index
  3. MACD Strategy - Trend and momentum combined
  4. Bollinger Bands - Volatility-based mean reversion
  5. Stochastic Oscillator - Overbought/oversold momentum indicator
  6. Breakout Strategy - Captures price breakouts with ATR filtering
  7. Mean Reversion - Z-score based statistical arbitrage
  8. EMA Crossover - Exponential moving average trend following
  9. Volume Weighted - Volume-based strategy using On-Balance Volume

🎚️ Hyperparameter Tuning

  • Dynamic Parameter Controls: Each strategy displays its own customizable parameters
  • Real-time Adjustment: Change parameters and instantly re-run backtests
  • Optimization-Ready: Easy experimentation to find optimal settings

πŸ“ˆ Comprehensive Performance Metrics

  • Returns: Total return, final portfolio value
  • Risk Metrics: Sharpe ratio, maximum drawdown, volatility
  • Trade Statistics: Win rate, profit factor, average win/loss
  • Trade Log: Detailed record of all executed trades

πŸ’Ό Backtesting Engine

  • Realistic Simulation: Includes commission costs and slippage
  • Position Tracking: Accurate portfolio and cash management
  • Multiple Timeframes: From intraday (5-min) to multi-year daily data

πŸ› οΈ Technologies Used

Core

  • Python 3.8+: Modern Python with type hints and async support
  • Pandas & NumPy: High-performance data manipulation and numerical computing

Web Dashboard

  • Plotly Dash: Interactive web framework for data applications
  • Dash Bootstrap Components: Professional UI components
  • Plotly: Industry-standard interactive graphing library

Data & Analysis

  • yfinance: Real-time and historical stock data from Yahoo Finance
  • TA-Lib (ta): Technical analysis library with 150+ indicators
  • mplfinance: Financial charting for legacy GUI

Legacy GUI

  • Tkinter: Cross-platform GUI framework
  • Matplotlib: Static chart generation

πŸš€ Quick Start

Installation

  1. Clone the repository
git clone <your-repo-url>
cd trading_bot
  1. Install dependencies
pip install -r requirements.txt

Running the Application

Option 1: Web Dashboard (Recommended)

python run_app.py

The dashboard will automatically open at http://127.0.0.1:8050/

Option 2: Legacy Desktop GUI

python main.py

πŸ“– Usage Guide

Web Dashboard Quick Start

  1. Enter Stock Symbol (e.g., AAPL, TSLA, GOOGL)
  2. Select Timeframe (1d to max)
  3. Choose Trading Strategy from dropdown
  4. Adjust Strategy Parameters in the dynamic controls
  5. Set Initial Capital and commission rate
  6. Click "Run Backtest"
  7. Analyze Results in the charts and metrics

Understanding Results

Performance Metrics

Returns

  • Total Return (%): Overall profit/loss
  • Final Portfolio Value: Ending value after all trades

Risk Metrics

  • Sharpe Ratio: Risk-adjusted returns (higher is better)
    • < 1: Poor risk-adjusted performance
    • 1-2: Good performance
    • > 2: Excellent performance
  • Max Drawdown: Largest peak-to-trough decline (lower is better)
  • Volatility: Annual price volatility

Trade Statistics

  • Win Rate: Percentage of profitable trades
  • Profit Factor: Gross profit / gross loss (> 1 is profitable)
  • Average Win/Loss: Mean profit per winning/losing trade

Strategy Selection Tips

Trending Markets:

  • Moving Average Crossover
  • EMA Crossover
  • MACD Strategy

Range-Bound Markets:

  • Bollinger Bands
  • Mean Reversion
  • RSI Strategy

Volatile Markets:

  • Breakout Strategy
  • Bollinger Bands
  • Stochastic Oscillator

🎯 Strategy Optimization

Hyperparameter Tuning Workflow

  1. Start with defaults - Run initial backtest
  2. Analyze performance - Check metrics and trade quality
  3. Adjust parameters - Modify one parameter at a time
  4. Compare results - Did performance improve?
  5. Iterate - Repeat until satisfied

Key Parameters by Strategy

Moving Average Crossover

  • Short Window (10-50): Fast MA period
  • Long Window (50-200): Slow MA period

RSI Strategy

  • Window (7-21): Calculation period
  • Oversold (20-35): Buy threshold
  • Overbought (65-80): Sell threshold

Bollinger Bands

  • Window (10-30): MA period
  • Std Dev (1.5-3): Band width multiplier

MACD

  • Fast (8-16): Fast EMA
  • Slow (20-30): Slow EMA
  • Signal (6-12): Signal line

See USAGE.md for detailed parameter guides.


πŸ“ Project Structure

trading_bot/
β”œβ”€β”€ app.py                  # Main web dashboard application
β”œβ”€β”€ run_app.py             # Launch script for web dashboard
β”œβ”€β”€ strategies.py          # All trading strategy implementations
β”œβ”€β”€ backtester.py          # Backtesting engine with metrics
β”œβ”€β”€ data_fetcher.py        # Yahoo Finance data fetching
β”œβ”€β”€ gui.py                 # Legacy Tkinter GUI
β”œβ”€β”€ main.py                # Legacy GUI launcher
β”œβ”€β”€ trading_logic.py       # Legacy strategy implementations
β”œβ”€β”€ requirements.txt       # Python dependencies
β”œβ”€β”€ README.md              # This file
└── USAGE.md              # Detailed usage guide

πŸ“Š Strategy Details

Moving Average Crossover

Classic trend-following strategy that buys when short MA crosses above long MA, sells when it crosses below.

Best for: Trending markets, medium to long-term trades

RSI Strategy

Uses Relative Strength Index to identify overbought (>70) and oversold (<30) conditions.

Best for: Range-bound markets, mean reversion

MACD Strategy

Combines trend and momentum using MACD line crossing signal line.

Best for: Identifying trend changes, momentum shifts

Bollinger Bands

Buys when price touches lower band (oversold), sells at upper band (overbought).

Best for: Mean reversion, volatility trading

Stochastic Oscillator

Momentum indicator comparing closing price to price range over period.

Best for: Short-term reversals, overbought/oversold

Breakout Strategy

Captures price movements beyond recent highs/lows with ATR filtering.

Best for: Volatile markets, trend initiation

Mean Reversion

Statistical strategy using z-scores to identify price extremes.

Best for: Stable stocks, range-bound markets

EMA Crossover

Similar to MA crossover but more responsive to recent prices.

Best for: Faster trend identification, active trading

Volume Weighted

Uses On-Balance Volume to confirm price movements with volume.

Best for: High-volume stocks, confirmation signals


⚠️ Disclaimer

This software is for educational and research purposes only.

  • Past performance does not guarantee future results
  • Backtesting has limitations (survivorship bias, overfitting, etc.)
  • Not financial advice - consult professionals before trading
  • Trading involves risk of loss - never invest more than you can afford to lose
  • Authors are not responsible for financial losses from using this software

πŸ”§ Troubleshooting

Common Issues

"Could not fetch data" error

  • Check internet connection
  • Verify stock symbol is valid
  • Try different timeframe

No trades in backtest

  • Parameters may be too conservative
  • Increase timeframe or adjust thresholds
  • Check if sufficient data exists for strategy window

Application won't start

# Reinstall dependencies
pip install --upgrade -r requirements.txt

# Check Python version
python --version  # Should be 3.8+

Port already in use

  • Change port in run_app.py: app.run_server(port=8051)
  • Or kill process using port 8050

πŸš€ Future Enhancements

Potential improvements:

  • Live paper trading mode
  • Multiple position sizing strategies
  • Stop-loss and take-profit orders
  • Portfolio optimization across multiple stocks
  • Machine learning strategy integration
  • Real-time alerts and notifications
  • Strategy combination/ensemble methods
  • Walk-forward analysis
  • Monte Carlo simulation
  • Export reports to PDF

πŸ“š Additional Resources


πŸ“ License

See LICENSE file for details.


🀝 Contributing

Contributions welcome! Areas for improvement:

  • Additional trading strategies
  • Enhanced performance metrics
  • UI/UX improvements
  • Documentation and examples
  • Bug fixes and optimizations

Built with ❀️ for traders and quants

Happy Trading! πŸ“ˆπŸš€

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published