A professional-grade stock trading bot featuring a modern web dashboard for backtesting trading strategies with interactive visualizations and comprehensive performance analytics.
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
Traditional Tkinter interface for basic backtesting
- 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
- Moving Average Crossover - Classic trend-following strategy
- RSI Strategy - Momentum-based using Relative Strength Index
- MACD Strategy - Trend and momentum combined
- Bollinger Bands - Volatility-based mean reversion
- Stochastic Oscillator - Overbought/oversold momentum indicator
- Breakout Strategy - Captures price breakouts with ATR filtering
- Mean Reversion - Z-score based statistical arbitrage
- EMA Crossover - Exponential moving average trend following
- Volume Weighted - Volume-based strategy using On-Balance Volume
- 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
- 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
- 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
- Python 3.8+: Modern Python with type hints and async support
- Pandas & NumPy: High-performance data manipulation and numerical computing
- Plotly Dash: Interactive web framework for data applications
- Dash Bootstrap Components: Professional UI components
- Plotly: Industry-standard interactive graphing library
- 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
- Tkinter: Cross-platform GUI framework
- Matplotlib: Static chart generation
- Clone the repository
git clone <your-repo-url>
cd trading_bot- Install dependencies
pip install -r requirements.txtpython run_app.pyThe dashboard will automatically open at http://127.0.0.1:8050/
python main.py- Enter Stock Symbol (e.g., AAPL, TSLA, GOOGL)
- Select Timeframe (1d to max)
- Choose Trading Strategy from dropdown
- Adjust Strategy Parameters in the dynamic controls
- Set Initial Capital and commission rate
- Click "Run Backtest"
- Analyze Results in the charts and 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
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
- Start with defaults - Run initial backtest
- Analyze performance - Check metrics and trade quality
- Adjust parameters - Modify one parameter at a time
- Compare results - Did performance improve?
- Iterate - Repeat until satisfied
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.
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
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
Uses Relative Strength Index to identify overbought (>70) and oversold (<30) conditions.
Best for: Range-bound markets, mean reversion
Combines trend and momentum using MACD line crossing signal line.
Best for: Identifying trend changes, momentum shifts
Buys when price touches lower band (oversold), sells at upper band (overbought).
Best for: Mean reversion, volatility trading
Momentum indicator comparing closing price to price range over period.
Best for: Short-term reversals, overbought/oversold
Captures price movements beyond recent highs/lows with ATR filtering.
Best for: Volatile markets, trend initiation
Statistical strategy using z-scores to identify price extremes.
Best for: Stable stocks, range-bound markets
Similar to MA crossover but more responsive to recent prices.
Best for: Faster trend identification, active trading
Uses On-Balance Volume to confirm price movements with volume.
Best for: High-volume stocks, confirmation signals
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
"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
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
- Documentation: See USAGE.md for comprehensive guide
- Strategy Theory: Research technical analysis and quantitative trading
- Python Libraries:
See LICENSE file for details.
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! ππ