Backend & APIs / Real-Time-Stock-Trading-Simulator
Real-Time Stock Trading Simulator
A sophisticated Python-based real-time stock trading simulator that demonstrates automated trading system development with live market data integration, advanced strategy implementation, and comprehensive performance…
Open the full technical write-up
A modern, professional web-based real-time stock trading simulator with interactive charts, live data visualization, and advanced trading strategies. Built with Flask, Plotly, and Yahoo Finance API.
What the project includes
Core Trading Features
- Real-time Stock Data: Live stock price monitoring with Yahoo Finance integration
- Advanced Trading Strategy: Enhanced moving average crossover strategy with RSI, momentum, and risk management
- Portfolio Tracking: Real-time portfolio value updates and performance metrics
- Historical Mode: Run simulations on historical data for backtesting
- Multiple Stocks: Support for 40+ popular stocks and ETFs
- Risk Management: Built-in stop-loss and profit-taking mechanisms
User Interface
- Interactive Charts: Beautiful Plotly charts showing price movements and trading signals
- Responsive Design: Modern UI that works direct on desktop and mobile
- Real-time Updates: Live data updates with smooth animations
- Dark Mode Support: Automatic dark mode detection and styling
- Professional Dashboard: Clean, intuitive interface with comprehensive trading information
Technical Features
- Modular Architecture: Well-organized codebase with separation of concerns
- API-First Design: RESTful API endpoints for all trading operations
- Error Handling: reliable error handling and retry mechanisms
- Configuration Management: Environment-based configuration system
- Testing Suite: Comprehensive unit tests for core functionality
- Performance Optimization: Efficient data processing and caching
How files are organized
Real-Time-Stock-Trading-Simulator/
├── src/ # Main source code
│ ├── core/ # Core trading functionality
│ │ ├── __init__.py
│ │ ├── data_fetcher.py # Stock data fetching
│ │ └── strategy.py # Enhanced trading strategy implementation
│ ├── api/ # API endpoints
│ │ ├── __init__.py
│ │ └── routes.py # Flask routes and API handlers
│ ├── utils/ # Utility functions
│ │ ├── __init__.py
│ │ └── config.py # Configuration management
│ └── models/ # Data models
│ ├── __init__.py
│ └── trade.py # Trade and portfolio models
├── static/ # Static assets
│ ├── css/ # Stylesheets
│ │ └── main.css # Main application styles
│ ├── js/ # JavaScript files
│ │ └── app.js # Main application logic
│ ├── images/ # Image assets
│ └── templates/ # HTML templates
│ └── index.html # Main dashboard template
├── docs/ # Documentation
│ └── API.md # API documentation
├── app.py # Main application entry point
├── requirements.txt # Python dependencies
├── setup.py # Package setup
├── Makefile # Development tasks
├── env.example # Environment variables example
└── README.md # This file
Installation
Prerequisites
- Python 3.8 or higher
- pip (Python package installer)
Quick Start
Windows (Recommended)
-
Clone the repository
git clone https://github.com/yourusername/real-time-stock-trading-simulator.git cd real-time-stock-trading-simulator -
Run installation script
install.bat -
Run the application
run.bat -
Open in browser Navigate to
http://localhost:5000
Manual Installation (All Platforms)
-
Clone the repository
git clone https://github.com/yourusername/real-time-stock-trading-simulator.git cd real-time-stock-trading-simulator -
Create virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate -
Install dependencies
pip install -r requirements.txt -
Run the application
python app.py -
Open in browser Navigate to
http://localhost:5000
Development Setup
For development with additional tools:
# Install development dependencies
make install-dev
# Run tests
make test
# Format code
make format
# Lint code
make lint
Usage
Basic Trading
- Select Stock: Choose from 40+ available stocks and ETFs
- Configure Parameters: Set interval, period, and initial cash amount
- Start Simulation: Click "Start Simulator" to begin real-time trading
- Monitor Results: Watch live charts and trade updates
- Stop Simulation: Click "Stop Simulator" when finished
Historical Mode
- Enable Historical Mode: Check the "Historical Mode" checkbox
- Select Date: Choose a specific date for backtesting
- Run Simulation: Start the simulator to see how your strategy would have performed
Enhanced Trading Strategy
The simulator uses an Advanced Moving Average Crossover strategy with multiple confirmations:
Core Strategy Components:
- Moving Average Crossover: Golden cross (buy) and death cross (sell) signals
- RSI Filter: Relative Strength Index to avoid overbought/oversold conditions
- Momentum Analysis: Price and moving average momentum confirmation
- Risk Management: Automatic stop-loss and profit-taking mechanisms
Strategy Parameters:
- Short Window: Fast moving average period (default: 5)
- Long Window: Slow moving average period (default: 20)
- Profit Threshold: Target profit percentage (default: 2%)
- Stop Loss: Maximum loss percentage (default: 1%)
- RSI Window: RSI calculation period (default: 14)
Signal Generation:
- Buy Signal: When short MA crosses above long MA + RSI 25 + stop-loss/profit-taking
- Position Sizing: Risk-based position sizing (2% risk per trade)
Configuration
Environment Variables
Copy env.example to .env and modify as needed:
# Flask Configuration
FLASK_DEBUG=True
SECRET_KEY=your-secret-key-here
HOST=0.0.0.0
PORT=5000
# Trading Configuration
DEFAULT_SYMBOL=AAPL
DEFAULT_INTERVAL=1m
DEFAULT_PERIOD=1d
DEFAULT_INITIAL_CASH=50000
# Strategy Configuration
DEFAULT_SHORT_WINDOW=5
DEFAULT_LONG_WINDOW=20
DEFAULT_PROFIT_THRESHOLD=0.02
DEFAULT_STOP_LOSS=0.01
Available Stocks
The simulator supports 40+ popular stocks and ETFs including:
- Technology: AAPL, MSFT, GOOGL, AMZN, TSLA, META, NVDA
- Finance: JPM, BAC, WFC, GS, MS, C
- Healthcare: JNJ, PFE, UNH
- Consumer: HD, DIS, V, MA, PG, KO, PEP, WMT, COST
- And many more...
API Endpoints
Core Endpoints
GET /- Main dashboardGET /api/simulator-status- Get simulation status
Trading Endpoints
POST /api/start-simulator- Start trading simulationPOST /api/stop-simulator- Stop simulationPOST /api/clear-trades- Clear all trades
Data Endpoints
GET /api/stock-data- Get current stock data and signalsGET /api/trades- Get trade historyGET /api/portfolio-values- Get portfolio value history
Testing
Run the test suite:
# Run all tests
make test
# Run tests with coverage
make test-coverage
# Run specific test file
python -m pytest tests/test_data_fetcher.py -v
Deployment
Local Development
make run-dev
Production
# Set production environment
export FLASK_DEBUG=False
export SECRET_KEY=your-production-secret-key
# Run application
python app.py
Docker Deployment
# Build Docker image
make docker-build
# Run Docker container
make docker-run
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Follow PEP 8 style guidelines
- Write tests for new features
- Update documentation as needed
- Use meaningful commit messages
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Yahoo Finance: For providing real-time stock data
- Plotly: For interactive charting capabilities
- Flask: For the web framework
- Bootstrap: For responsive UI components
Support
- Issues: GitHub Issues
- Documentation: Project Wiki
- Email: your.email@example.com
Changelog
Version 1.1.0 (Latest)
- Enhanced trading strategy with RSI and momentum indicators
- Improved risk management with stop-loss and profit-taking
- Better signal generation with multiple confirmations
- Performance optimizations and bug fixes
Version 1.0.0
- Initial release with real-time trading simulation
- Interactive charts and portfolio tracking
- Historical mode for backtesting
- Modular architecture and comprehensive testing
Disclaimer: This is a simulation tool for educational purposes only. It does not provide financial advice or guarantee investment returns. Always do your own research before making investment decisions.