Skip to content

About

"ML-based stock price movement predictor using technical indicators and ensemble learning"

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

πŸ“ˆ Stock Price Predictor

A complete end-to-end Machine Learning system that predicts whether a stock's closing price will go UP ↑ or DOWN ↓ the next trading day.

Status: βœ… Production Ready | Version: 2.0 + Phase 1 | Last Updated: May 2026


🎯 Quick Overview

This project combines real-world ML best practices with financial prediction to create an intelligent trading signal system:

  • 10+ Production Modules: 5,600+ lines of production code
  • 40+ Technical Indicators: Comprehensive market feature engineering
  • Multiple ML Models: Logistic Regression, Random Forest, XGBoost, LSTM + Ensemble
  • 11 Streamlit UI Tabs: Interactive web application for analysis and visualization
  • Complete Backtesting: Historical performance validation with detailed metrics
  • Smart Decision Making: BUY/SELL/NO TRADE with confidence scoring (0-100%)
  • Multi-Channel Alerts: Email, SMS, console notifications
  • Professional Exports: CSV, Excel, JSON, HTML reporting
  • Market Intelligence: VIX awareness, earnings calendar, global market context

πŸš€ Quick Start

Installation (5 minutes)

# Clone/navigate to project
cd c:\Projects\Stocks_predication

# Create virtual environment
python -m venv venv
venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Run Application

streamlit run app.py

The app opens at http://localhost:8501


πŸ“Š Features & Capabilities

Signal Generation

βœ… Weighted ensemble model (XGBoost 50%, RF 20%, MLP 20%, LR 10%) βœ… Dynamic confidence scoring (0-100%) βœ… 23 optimized market-aware features βœ… VIX-adjusted for market conditions βœ… Earnings-aware to avoid high-risk dates

Decision Making

βœ… Strong Buy (>75% confidence) βœ… Buy (60-75% confidence) βœ… No Trade (<60% confidence) βœ… Risk levels: LOW / MEDIUM / HIGH βœ… Position sizing recommendations

Insights & Transparency

βœ… Complete explanations (why the signal occurred) βœ… Supporting indicators and evidence βœ… Beginner-friendly & advanced analysis βœ… Indicator tooltips and definitions

Validation & Backtesting

βœ… Historical trade simulation βœ… Win rate, P&L, Sharpe ratio, max drawdown βœ… Trade-by-trade detailed analysis βœ… Performance comparison across time periods

Alerts & Notifications

βœ… Real-time console alerts βœ… Email notifications (Gmail, custom SMTP) βœ… SMS alerts (Twilio-ready) βœ… Alert history tracking

Professional Exports

βœ… CSV (all data and results) βœ… Excel workbooks (multi-sheet) βœ… JSON (API-friendly) βœ… HTML (client-ready reports)


πŸ“š Project Structure

Stocks_predication/
β”œβ”€β”€ README.md                          ← Start here!
β”œβ”€β”€ PROJECT_INFORMATION.txt            ← Complete documentation
β”œβ”€β”€ requirements.txt                   ← Python dependencies
β”œβ”€β”€ main_pipeline.py                   ← Script-based interface
β”‚
β”œβ”€β”€ 🎨 USER INTERFACES
β”œβ”€β”€ app.py                             ← Main Streamlit app (11 tabs)
β”œβ”€β”€ streamlit_app.py                   ← Alternative UI
β”‚
β”œβ”€β”€ πŸ“¦ SOURCE CODE (src/)
β”‚   β”œβ”€β”€ DATA PIPELINE
β”‚   β”œβ”€β”€ data_fetching.py               ← Yahoo Finance integration
β”‚   β”œβ”€β”€ preprocessing.py               ← Data cleaning
β”‚   β”œβ”€β”€ technical_indicators.py        ← 40+ indicators
β”‚   β”œβ”€β”€ candlestick_patterns.py        ← Pattern detection
β”‚   β”œβ”€β”€ sentiment_analysis.py          ← FinBERT sentiment
β”‚   β”‚
β”‚   β”œβ”€β”€ MACHINE LEARNING
β”‚   β”œβ”€β”€ model.py                       ← Baseline models
β”‚   β”œβ”€β”€ model_training_v2.py           ← v2.0 ensemble
β”‚   β”œβ”€β”€ lstm_neural_network.py         ← Deep learning
β”‚   β”œβ”€β”€ evaluation.py                  ← Metrics & evaluation
β”‚   β”œβ”€β”€ ablation_study.py              ← Feature importance
β”‚   β”‚
β”‚   β”œβ”€β”€ DECISION INTELLIGENCE
β”‚   β”œβ”€β”€ feature_optimization.py        ← 23 optimized features
β”‚   β”œβ”€β”€ decision_engine.py             ← Trading decisions
β”‚   β”œβ”€β”€ market_analysis.py             ← Market context
β”‚   β”œβ”€β”€ vix_analyzer.py                ← Volatility analysis
β”‚   β”œβ”€β”€ explanation_engine.py          ← Signal explanations
β”‚   β”‚
β”‚   β”œβ”€β”€ EXECUTION & VALIDATION
β”‚   β”œβ”€β”€ backtester.py                  ← Historical simulation
β”‚   β”œβ”€β”€ alerts_manager.py              ← Notifications
β”‚   β”œβ”€β”€ export_utils.py                ← Data exports
β”‚   └── visualization.py               ← Interactive charts
β”‚
β”œβ”€β”€ πŸ““ NOTEBOOKS
β”œβ”€β”€ notebooks/stock_prediction_pipeline.ipynb
β”‚
└── πŸ“ DATA & MODELS
    β”œβ”€β”€ data/                          ← Data storage
    β”œβ”€β”€ models/                        ← Saved models
    └── exports/                       ← Export outputs

πŸ“– How to Use

Via Streamlit Web App

  1. Configure (left sidebar):

    • Enter stock symbol (e.g., AAPL, RELIANCE.NS, TCS.NS)
    • Select date range (default: 3 years)
    • Choose models to run
  2. Analyze (click "πŸš€ Fetch & Analyze"):

    • Fetches historical data
    • Calculates indicators
    • Trains ML models
    • Generates predictions
  3. Explore Results (11 tabs):

    • πŸ“Š Price Chart: Interactive candlestick
    • πŸ“ˆ Technical Indicators: RSI, MACD, Bollinger Bands
    • 🎯 Predictions: UP/DOWN with confidence
    • πŸ“‰ Model Performance: Accuracy metrics
    • πŸ” Feature Analysis: Feature importance
    • πŸ’¬ Sentiment Analysis: News sentiment
    • πŸ•―οΈ Candlestick Patterns: Pattern detection
    • πŸ“₯ Export Results: CSV/Excel/JSON
    • πŸ”” Alerts: Set up notifications
    • πŸ“… Earnings Calendar: Risk awareness
    • πŸ“Š VIX Analysis: Market volatility

Via Python Script

from src.data_fetching import fetch_stock_data
from src.feature_engineering import add_technical_indicators, create_target
from src.model_training_v2 import WeightedEnsemble

# 1. Fetch data
df = fetch_stock_data('AAPL', '2023-01-01', '2024-01-01')

# 2. Add indicators
df = add_technical_indicators(df)

# 3. Create target
df = create_target(df)

# 4. Train model
model = WeightedEnsemble()
model.fit(X_train, y_train)

# 5. Predict
predictions = model.predict(X_test)
confidence = model.predict_proba(X_test)

πŸ”¬ Technical Details

Data Pipeline

Raw Stock Data
    ↓ (fetch from Yahoo Finance)
Historical OHLCV Data
    ↓ (clean, handle missing values)
Preprocessing
    ↓ (add 40+ technical indicators)
Feature Engineering
    ↓ (create UP/DOWN target)
Target Generation
    ↓ (train-test split, normalize)
ML Training
    ↓ (XGBoost, RF, LSTM, LR ensemble)
Predictions & Signals
    ↓ (confidence scoring, decision making)
Trading Signals (BUY/SELL/HOLD)

Technical Indicators (40+)

Trend Analysis:

  • Simple & Exponential Moving Averages (5, 10, 20 day)
  • MACD (Moving Average Convergence Divergence)
  • ADX (Average Directional Index)

Momentum:

  • RSI (Relative Strength Index)
  • Stochastic Oscillator
  • Daily Returns

Volatility:

  • Bollinger Bands (Upper, Lower, Width, Position)
  • ATR (Average True Range)
  • Standard Deviation

Volume:

  • Volume Change %
  • On-Balance Volume (OBV)
  • Chaikin Money Flow (CMF)

Price Structure:

  • Close-Open Difference
  • Price vs Moving Average Distance
  • High-Low Range

Machine Learning Models

Model Type Strengths Use Case
Logistic Regression Linear Fast, interpretable, good baseline Quick predictions, feature analysis
Random Forest Ensemble Non-linear, feature importance General-purpose predictions
XGBoost Boosting State-of-the-art, handles complexity High-accuracy predictions
LSTM Deep Learning Temporal dependencies Complex pattern recognition
Ensemble (v2.0) Combined Best of all (weighted voting) Final production predictions

v2.0 Ensemble Weighting:

  • XGBoost: 50% (primary model)
  • Random Forest: 20%
  • MLP/LSTM: 20%
  • Logistic Regression: 10%

Evaluation Metrics

Classification Metrics:

  • Accuracy, Precision, Recall, F1-Score
  • ROC-AUC (Receiver Operating Characteristic)
  • Confusion Matrix (TP, FP, TN, FN)

Business Metrics:

  • Win Rate: % of profitable trades
  • Sharpe Ratio: Risk-adjusted returns
  • Max Drawdown: Largest peak-to-trough decline
  • P&L: Total profit/loss

πŸ“‹ Supported Stocks

Indian Stocks (NSE)

RELIANCE.NS, TCS.NS, INFY.NS, WIPRO.NS, HDFC.NS, ICICIBANK.NS, AXISBANK.NS, SBIN.NS, MARUTI.NS, BAJAJFINSV.NS

US Stocks (NASDAQ/NYSE)

AAPL, MSFT, GOOGL, AMZN, TSLA, META, NVIDIA, JPM, V, WMT

Note: Any stock supported by Yahoo Finance can be used


🎯 Performance (v2.0 Improvements)

Metric Before (v1.0) After (v2.0) Improvement
Overall Accuracy 60% 60-65% βœ… +5%
Precision 54.8% 65-70% βœ… +10-15%
False Positive Rate ~50% ~30% βœ… -40%
Features 54 (noisy) 23 (optimized) βœ… Better quality
Confidence Threshold 0.5 0.6 βœ… Quality filter

πŸ› οΈ Dependencies

Data: pandas>=2.2.0, numpy>=2.0.0, scipy>=1.12.0
ML: scikit-learn>=1.4.0, xgboost>=2.0.0, tensorflow>=2.14.0
Finance: yfinance>=0.2.35, pandas-ta>=0.3.14b0
NLP: transformers>=4.36.0 (FinBERT)
Viz: matplotlib>=3.8.4, plotly>=5.18.0
Web: streamlit>=1.31.0

See requirements.txt for complete list.


⚠️ Important Disclaimers

  • This is a PREDICTION tool, not financial advice
  • Historical performance β‰  Future results
  • Always use proper risk management (stop losses, position sizing)
  • Start with paper trading before real capital
  • Monitor model performance continuously
  • Be aware of earnings dates and major news events
  • Combine signals with fundamental analysis

πŸ“š Documentation

  • PROJECT_INFORMATION.txt ← Complete documentation (start here!)
  • ARCHITECTURE.md ← System design and data flow
  • MODEL_AND_ALGORITHM_GUIDE.md ← Detailed ML explanations
  • API_REFERENCE.md ← Function documentation
  • QUICKSTART.md ← Quick start guide
  • TROUBLESHOOTING.md ← Common issues

πŸ› Troubleshooting

"No module named 'src'"

import sys
sys.path.insert(0, 'src')

"yfinance: No data found"

  • Check symbol format (e.g., RELIANCE.NS for NSE stocks)

"Streamlit connection reset"

  • Clear browser cache or restart terminal

"Model accuracy is low"

  • Check if market is sideways (low ADX)
  • Verify feature scaling

See TROUBLESHOOTING.md for more solutions.


πŸ—“οΈ Roadmap

Phase 2: Multi-stock portfolio optimization, options strategies Phase 3: Deep reinforcement learning, sector rotation, crypto support Phase 4: Federated learning, advanced NLP, FastAPI deployment


πŸ’‘ Key Learnings

  1. Time-Series Data: Never shuffle! Use TimeSeriesSplit for proper validation
  2. Feature Engineering: Quality over quantity (54 β†’ 23 features improved accuracy)
  3. Ensemble Models: Different models excel in different market regimes
  4. Confidence Scoring: Threshold reduces false positives significantly
  5. Market Context: VIX integration and earnings awareness improve decisions

πŸ“ž Support

  • Issues: Check TROUBLESHOOTING.md
  • Questions: Review API_REFERENCE.md or ARCHITECTURE.md
  • Examples: See notebooks/stock_prediction_pipeline.ipynb

About

"ML-based stock price movement predictor using technical indicators and ensemble learning"

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages