Skip to content

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 analytics.

License

Notifications You must be signed in to change notification settings

Tuhin-SnapD/Real-Time-Stock-Trading-Simulator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Real-Time Stock Trading Simulator

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.

Trading Simulator Dashboard Python Version Flask Version License

πŸš€ Features

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 seamlessly 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: Robust 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

πŸ“ Project Structure

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)

  1. Clone the repository

    git clone https://github.com/yourusername/real-time-stock-trading-simulator.git
    cd real-time-stock-trading-simulator
  2. Run installation script

    install.bat
  3. Run the application

    run.bat
  4. Open in browser Navigate to http://localhost:5000

Manual Installation (All Platforms)

  1. Clone the repository

    git clone https://github.com/yourusername/real-time-stock-trading-simulator.git
    cd real-time-stock-trading-simulator
  2. Create virtual environment

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Run the application

    python app.py
  5. 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

  1. Select Stock: Choose from 40+ available stocks and ETFs
  2. Configure Parameters: Set interval, period, and initial cash amount
  3. Start Simulation: Click "Start Simulator" to begin real-time trading
  4. Monitor Results: Watch live charts and trade updates
  5. Stop Simulation: Click "Stop Simulator" when finished

Historical Mode

  1. Enable Historical Mode: Check the "Historical Mode" checkbox
  2. Select Date: Choose a specific date for backtesting
  3. 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 < 75 + positive momentum
  • Sell Signal: When short MA crosses below 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 dashboard
  • GET /api/simulator-status - Get simulation status

Trading Endpoints

  • POST /api/start-simulator - Start trading simulation
  • POST /api/stop-simulator - Stop simulation
  • POST /api/clear-trades - Clear all trades

Data Endpoints

  • GET /api/stock-data - Get current stock data and signals
  • GET /api/trades - Get trade history
  • GET /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

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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

πŸ”„ 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.

About

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 analytics.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published