--- title: Stocks Platform emoji: 🚀 colorFrom: red colorTo: red sdk: docker app_port: 8501 tags: - streamlit pinned: false short_description: h2h assignment --- # 📈 Complete Stock Trading & Prediction Platform A sophisticated web-based stock trading platform that combines machine learning price predictions with rule-based trading strategies. Built with Streamlit, this platform offers comprehensive technical analysis, backtesting capabilities, and interactive visualizations for Indian stock markets. ![Platform Demo](https://img.shields.io/badge/Platform-Streamlit-red) ![Python](https://img.shields.io/badge/Python-3.8+-blue) ![License](https://img.shields.io/badge/License-MIT-green) ![Status](https://img.shields.io/badge/Status-Active-brightgreen) ## 🌟 Features ### 🔮 Price Prediction Engine - **Machine Learning Model**: Logistic regression with 59+ technical features - **Advanced Features**: Volatility ratios, momentum indicators, lag features - **Confidence Analysis**: Prediction probability with visual confidence gauge - **Technical Indicators**: RSI, MACD, SMA, EMA, Bollinger Bands ### 📊 Trading Dashboard - **Multiple Strategies**: SMA-based and EMA-based trading strategies - **Comprehensive Backtesting**: Historical performance analysis with risk metrics - **Risk Management**: Configurable stop-loss, take-profit, and position sizing - **Interactive Visualizations**: Plotly-powered charts and analysis tools ### 📈 Technical Analysis - **50+ Indian Stocks**: Pre-configured NSE stock symbols - **Real-time Data**: Yahoo Finance integration with reliable data fetching - **Multiple Timeframes**: Customizable periods for technical indicators - **Advanced Charts**: Candlestick patterns, volume analysis, drawdown charts ## 🚀 Quick Start ### Prerequisites ```bash Python 3.8+ pip package manager ``` ### Installation 1. **Clone the repository** ```bash git clone https://github.com/yourusername/stock-trading-platform.git cd stock-trading-platform ``` 2. **Install dependencies** ```bash pip install -r requirements.txt ``` 3. **Set up the project structure** ```bash mkdir -p src/logs src/models ``` 4. **Download or train the ML models** ```bash # Place your trained models in src/models/ # - logistic_regression_model.pkl # - scaler.pkl ``` 5. **Run the application** ```bash streamlit run app.py ``` 6. **Access the platform** ``` Open your browser and navigate to http://localhost:8501 ``` ## 📁 Project Structure ``` stock-trading-platform/ │ ├── app.py # Main Streamlit application ├── requirements.txt # Python dependencies ├── README.md # Project documentation │ ├── src/ │ ├── indicators/ # Technical indicator modules │ │ ├── __init__.py │ │ ├── rsi.py # RSI calculation │ │ ├── sma.py # Simple Moving Average │ │ ├── ema.py # Exponential Moving Average │ │ ├── macd.py # MACD indicator │ │ └── enhanced_features.py # Advanced feature engineering │ │ │ ├── strategy/ # Trading strategy modules │ │ ├── __init__.py │ │ └── rule_based_strategy.py # SMA/EMA trading strategies │ │ │ ├── utils/ # Utility modules │ │ ├── __init__.py │ │ ├── backtester.py # Backtesting engine │ │ └── logger.py # Logging configuration │ │ │ ├── models/ # ML models and scalers │ │ ├── logistic_regression_model.pkl │ │ └── scaler.pkl │ │ │ └── logs/ # Application logs │ └── trading_app.log │ └── data/ # Data storage (optional) └── processed/ ``` ## 🛠️ Dependencies ### Core Libraries ```python streamlit>=1.28.0 # Web application framework pandas>=1.5.0 # Data manipulation numpy>=1.24.0 # Numerical computing plotly>=5.15.0 # Interactive visualizations yfinance>=0.2.18 # Stock data fetching scikit-learn>=1.3.0 # Machine learning ``` ### Additional Dependencies ```python curl-cffi>=0.5.10 # HTTP requests with browser impersonation pickle>=4.0 # Model serialization datetime # Date/time handling warnings # Warning management logging # Application logging ``` ## 📊 Supported Stocks The platform supports 50+ major Indian stocks including: **Banking & Finance** - HDFCBANK.NS, ICICIBANK.NS, AXISBANK.NS, KOTAKBANK.NS, SBIN.NS **Technology** - TCS.NS, INFY.NS, HCLTECH.NS, TECHM.NS, WIPRO.NS **Energy & Materials** - RELIANCE.NS, ONGC.NS, COALINDIA.NS, NTPC.NS, POWERGRID.NS **Consumer Goods** - HINDUNILVR.NS, ITC.NS, NESTLEIND.NS, TATACONSUM.NS, BRITANNIA.NS **And many more...** ## 🔧 Configuration ### Technical Indicators - **RSI Period**: 5-30 days (default: 14) - **Short-term SMA/EMA**: 5-50 days (default: 20) - **Long-term SMA/EMA**: 50-200 days (default: 50) ### Trading Parameters - **Initial Capital**: ₹10,000 - ₹10,00,000 (default: ₹1,00,000) - **Transaction Cost**: 0.0% - 1.0% (default: 0.1%) - **Stop Loss**: 0% - 20% (default: 5%) - **Take Profit**: 0% - 50% (default: 15%) ### Risk Management - Position sizing based on available capital - Automatic stop-loss and take-profit execution - Transaction cost simulation - Drawdown analysis and monitoring ## 🎯 Usage Guide ### 1. Price Prediction 1. Select a stock from the dropdown menu 2. Choose your date range and technical indicator periods 3. View the ML model's next-day price prediction 4. Analyze confidence levels and technical charts 5. Export prediction data for further analysis ### 2. Trading Dashboard 1. Configure your trading strategy (SMA or EMA based) 2. Set backtesting parameters and risk management rules 3. Run the backtest and analyze performance metrics 4. Compare strategy performance vs buy-and-hold 5. Review detailed trade analysis and export results ### 3. Technical Analysis 1. Examine multiple technical indicators simultaneously 2. Identify trading signals and market trends 3. Analyze volume patterns and momentum indicators 4. Use Bollinger Bands for volatility analysis 5. Monitor drawdown and risk metrics ## 📈 Model Performance ### Machine Learning Metrics - **Accuracy**: 55.0% - **F1 Score**: 0.4839 - **AUC Score**: 0.5370 - **Average Precision**: 0.5300 ### Feature Engineering - **Total Features**: 59 technical indicators - **Feature Categories**: Price, Volume, Volatility, Momentum, Position - **Data Processing**: StandardScaler normalization - **Model Type**: Logistic Regression with regularization ## 🔍 Advanced Features ### Enhanced Technical Analysis - **Volatility Features**: Multi-timeframe volatility ratios and rankings - **Lag Features**: Historical price and indicator dependencies - **Volume Analysis**: Volume-price relationships and momentum - **Position Features**: Price position relative to historical ranges ### Backtesting Engine - **Performance Metrics**: Sharpe ratio, maximum drawdown, win rate - **Trade Analysis**: Individual trade performance and statistics - **Risk Assessment**: Drawdown analysis and volatility measures - **Comparison Tools**: Strategy vs buy-and-hold performance ### Interactive Visualizations - **Real-time Charts**: Dynamic price action with technical overlays - **Signal Visualization**: Buy/sell signals on price charts - **Performance Tracking**: Portfolio value progression over time - **Distribution Analysis**: Trade returns and risk metrics ## 🚨 Disclaimer **Important**: This platform is designed for educational and research purposes only. Stock market investments carry inherent risks, and past performance does not guarantee future results. **Risk Warning**: - Always conduct your own research before making investment decisions - Consider consulting with a qualified financial advisor - Never invest more than you can afford to lose - Markets can be volatile and unpredictable ## 🤝 Contributing We welcome contributions to improve the platform! Here's how you can help: ### Areas for Contribution - **New Trading Strategies**: Implement additional algorithmic strategies - **Enhanced ML Models**: Add new prediction models and features - **UI/UX Improvements**: Enhance the user interface and experience - **Performance Optimization**: Improve code efficiency and speed - **Bug Fixes**: Report and fix issues in the codebase ### Contribution Process 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 ## 📝 License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## 👨‍💻 Author **Zane Vijay Falcao** - Email: zanefalcao@example.com - LinkedIn: [Your LinkedIn Profile] - GitHub: [Your GitHub Profile] ## 🙏 Acknowledgments - **Yahoo Finance** for providing reliable stock market data - **Streamlit** for the excellent web application framework - **Plotly** for interactive visualization capabilities - **Scikit-learn** for machine learning tools and utilities ## 📞 Support If you encounter any issues or have questions: 1. **Check the Documentation**: Review this README and code comments 2. **Search Issues**: Look through existing GitHub issues 3. **Create New Issue**: Submit a detailed bug report or feature request 4. **Contact Developer**: Reach out via email for urgent matters --- ⭐ **Star this repository if you find it helpful!** ⭐ --- *Last Updated: August 2025*