Skip to content

This project predicts future stock prices based on historical data using machine learning techniques. The model analyzes trends and patterns in past stock performance to forecast upcoming prices, helping users understand potential market movements.

Notifications You must be signed in to change notification settings

ishansurdi/Predictr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

📈 Stock Price Prediction & Portfolio Management System

Python Flask TensorFlow MongoDB License

A comprehensive AI-powered stock market analysis and prediction platform with real-time portfolio management, LSTM-based forecasting, and intelligent market insights powered by Google Gemini AI.

FeaturesInstallationConfigurationUsageArchitectureAPI Documentation


👨‍💻 Developers

Ishan Surdi
Ishan Surdi

🔗 GitHub
Vrushali Deshpande
Vrushali Deshpande

🔗 GitHub

📋 Table of Contents


🌟 Overview

Stock Price Prediction & Portfolio Management System is an advanced web-based platform that combines artificial intelligence, machine learning, and real-time data analysis to provide investors with powerful tools for stock market analysis and portfolio management.

Key Highlights:

  • 🤖 LSTM Neural Networks for accurate stock price predictions
  • 📊 Real-time Portfolio Tracking with multi-currency support
  • 🎯 AI-Powered Market Insights using Google Gemini AI
  • 💼 Virtual Trading Simulation with ₹100,000 starting capital
  • 📈 Live Stock Data integration via Yahoo Finance API
  • 🔐 Secure Authentication with OTP-based email verification
  • 📧 Email Notifications for account activities and updates

✨ Features

🔐 User Authentication & Management

  • Email-based Registration: Secure signup with email verification
  • OTP Verification: 6-digit OTP sent via email for account confirmation
  • Session Management: Secure user sessions with Flask session handling
  • Password Security: Werkzeug password hashing for data protection

📊 Portfolio Management

  • Real-time Portfolio Tracking: Monitor your investments with live market data
  • Multi-Currency Support: View portfolio values in INR, USD, EUR, and more
  • Profit/Loss Calculations: Automatic P/L tracking for each stock
  • Win Rate Analytics: Calculate percentage of profitable trades
  • Portfolio Diversification: Track multiple stocks across different sectors

🎯 Trading Simulation

  • Virtual Trading: Start with ₹100,000 virtual cash
  • Live Market Prices: Real-time stock price updates from Yahoo Finance
  • Trade History: Complete log of all buy/sell transactions
  • Performance Metrics: Total trades, winning/losing trades, average trade size
  • Best/Worst Trade Tracking: Identify your most profitable and loss-making trades

🤖 AI-Powered Predictions

  • LSTM Neural Network: Deep learning model for stock price forecasting
  • 30-Day Predictions: Forecast stock prices up to 30 days in advance
  • Risk Assessment: AI-calculated risk levels (Low/Medium/High)
  • ROI Estimation: Predicted return on investment percentages
  • Model Training: Automated model training for new stock symbols

💡 Market Insights (Gemini AI)

  • Portfolio Analysis: AI-powered recommendations based on your holdings
  • Market Trends: Real-time analysis of market conditions
  • Stock Recommendations: Intelligent buy/sell/hold suggestions
  • Risk Warnings: AI-generated alerts for high-risk positions
  • Custom Queries: Ask questions about stocks, market trends, and strategies

📈 Stock Search & Analysis

  • Global Stock Search: Search stocks from NYSE, NASDAQ, NSE, BSE
  • Company Information: Detailed company profiles and financials
  • Historical Data: Access to historical stock price data
  • Technical Indicators: Moving averages, volatility analysis
  • Price Charts: Interactive 30-day performance charts

🛠 Technology Stack

Backend

  • Framework: Flask 3.0.0 (Python web framework)
  • Database: MongoDB 4.6+ (NoSQL database)
  • Authentication: Flask-Session, Werkzeug Security
  • Email Service: Flask-Mail (SMTP integration)
  • API Integration: RESTful API architecture

Machine Learning

  • Framework: TensorFlow 2.15.0, Keras 2.15.0
  • Model: LSTM (Long Short-Term Memory) Neural Network
  • Data Processing: NumPy 1.26.3, Scikit-learn 1.4.0
  • Stock Data: yfinance 0.2.35 (Yahoo Finance API)

AI Integration

  • AI Model: Google Gemini AI API
  • Use Cases: Market insights, portfolio analysis, stock recommendations
  • API Client: Custom integration via HTTP requests

Frontend

  • HTML5/CSS3: Modern responsive design
  • JavaScript: Vanilla JS for dynamic interactions
  • Tailwind CSS: Utility-first CSS framework
  • Chart.js: Interactive data visualizations

Development Tools

  • Environment Management: python-dotenv
  • Testing: pytest, pytest-flask
  • Production Server: Gunicorn (WSGI HTTP Server)
  • CORS: Flask-CORS for cross-origin requests

🏗 Project Architecture

Stock-Price-Prediction/
│
├── backend_process/               # Core backend application
│   ├── app.py                    # Main Flask application entry point
│   ├── extensions.py             # Flask extensions initialization (Mail, etc.)
│   ├── train_model.py            # LSTM model training logic
│   ├── predict_stock.py          # Stock price prediction engine
│   │
│   ├── routes/                   # API route handlers
│   │   ├── auth_routes.py       # Authentication endpoints (/auth/signup, /auth/login)
│   │   ├── otp_routes.py        # OTP verification endpoints
│   │   ├── StockRoutes.py       # Stock management APIs (add/delete/update stocks)
│   │   ├── FetchStock.py        # Stock data fetching from Yahoo Finance
│   │   ├── fetch_stock_details.py # Detailed stock information retrieval
│   │   ├── predict_route.py     # ML prediction endpoints
│   │   ├── gemini_routes.py     # AI-powered insights endpoints
│   │   ├── simulation_routes.py # Trading simulation APIs
│   │   └── search_company.py    # Company search functionality
│   │
│   ├── utils/                    # Helper utilities
│   │   ├── user_helpers.py      # User management functions
│   │   ├── stock_helpers.py     # Stock portfolio management
│   │   ├── email_utils.py       # Email sending utilities
│   │   ├── email_helpers.py     # Additional email functions
│   │   ├── otp_utils.py         # OTP generation and validation
│   │   └── gemini_helpers.py    # Gemini AI integration helpers
│   │
│   └── models/                   # Trained LSTM models storage
│       ├── AAPL_lstm.h5         # Apple Inc. trained model
│       ├── TSLA_lstm.h5         # Tesla Inc. trained model
│       └── RPOWER.NS_lstm.h5    # Reliance Power trained model
│
├── db_connection/                # Database configuration
│   ├── __init__.py              # Package initialization
│   └── db.py                    # MongoDB connection and collections setup
│
├── public-pages/                 # HTML frontend templates
│   ├── index.html               # Landing page
│   ├── signup.html              # User registration page
│   ├── login.html               # User login page
│   ├── verify_otp.html          # OTP verification page
│   ├── dashboard.html           # Main dashboard (Portfolio, Simulation, AI Chat)
│   └── contact.html             # Contact page
│
├── static/                       # Static assets
│   ├── styles/                  # CSS stylesheets
│   │   ├── login.css
│   │   ├── sign-in.css
│   │   └── otp.css
│   └── assets/                  # Images, logos, fonts
│       ├── logo_file/           # Brand assets (PNG, SVG, PDF)
│       └── elements/            # UI elements
│
├── models/                       # Additional model storage
│   └── *.h5                     # Pre-trained LSTM models
│
├── requirements.txt              # Python dependencies
├── .env.example                 # Environment variables template
└── README.md                    # Project documentation


📥 Installation

Prerequisites

Before you begin, ensure you have the following installed:

Step 1: Clone the Repository

# Clone the repository
git clone https://github.com/ishansurdi/Stock-Price-Prediction.git

# Navigate to project directory
cd Stock-Price-Prediction

Step 2: Create Virtual Environment (Recommended)

For Windows:

# Create virtual environment
python -m venv venv

# Activate virtual environment
venv\Scripts\activate

For Linux/macOS:

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate

Step 3: Install Dependencies

# Upgrade pip to latest version
pip install --upgrade pip

# Install all required packages
pip install -r requirements.txt

Package Installation Breakdown:

  • Flask & Extensions: Web framework and CORS support
  • MongoDB Driver: Database connectivity
  • TensorFlow/Keras: Machine learning framework
  • yfinance: Stock market data retrieval
  • NumPy/Scikit-learn: Data processing and scaling
  • Requests: HTTP API calls
  • Flask-Mail: Email functionality
  • python-dotenv: Environment variable management

Step 4: Set Up MongoDB

Option A: MongoDB Atlas (Cloud - Recommended)

  1. Create free account at MongoDB Atlas
  2. Create a new cluster (Free tier available)
  3. Create a database user with password
  4. Whitelist your IP address (or use 0.0.0.0/0 for all IPs)
  5. Get your connection string (e.g., mongodb+srv://username:password@cluster.mongodb.net/predictr_db)

Option B: Local MongoDB Installation

  1. Install MongoDB Community Server

  2. Start MongoDB Service

    Windows:

    # Start MongoDB service
    net start MongoDB

    Linux/macOS:

    # Start MongoDB daemon
    sudo systemctl start mongod
  3. Verify MongoDB is Running

    # Connect to MongoDB shell
    mongo
    
    # Or with newer versions
    mongosh

Your local connection string will be: mongodb://localhost:27017/predictr_db


⚙ Configuration

Step 1: Create Environment File

Create a .env file in the project root directory:

# For Windows
copy .env.example .env

# For Linux/macOS
cp .env.example .env

Step 2: Configure Environment Variables

Open .env file and add the following configurations:

# ============================================
# DATABASE CONFIGURATION
# ============================================
MONGO_URI=mongodb://localhost:27017/predictr_db
# For MongoDB Atlas, use:
# MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/predictr_db

# ============================================
# FLASK CONFIGURATION
# ============================================
SECRET_KEY=your-super-secret-key-here-change-this-in-production
FLASK_ENV=development
FLASK_DEBUG=True

# ============================================
# EMAIL CONFIGURATION (Gmail SMTP)
# ============================================
MAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
MAIL_USE_TLS=True
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-specific-password
MAIL_DEFAULT_SENDER=your-email@gmail.com

# ============================================
# GOOGLE GEMINI AI API
# ============================================
GEMINI_API_KEY=your-gemini-api-key-here

# ============================================
# EXCHANGE RATE API (Optional)
# ============================================
EXCHANGE_RATE_API_KEY=your-exchange-rate-api-key

Step 3: Get Required API Keys

🔑 Gmail App Password (For Email OTP)

  1. Go to Google Account Security
  2. Enable 2-Step Verification
  3. Go to App Passwords section
  4. Generate new app password for "Mail"
  5. Copy the 16-character password and paste in MAIL_PASSWORD

🤖 Google Gemini AI API Key

  1. Visit Google AI Studio
  2. Sign in with Google account
  3. Click "Create API Key"
  4. Copy the API key and paste in GEMINI_API_KEY

💱 Exchange Rate API Key (Optional)

  1. Visit ExchangeRate-API
  2. Sign up for free account
  3. Get your API key from dashboard
  4. Paste in EXCHANGE_RATE_API_KEY

🚀 Usage

Starting the Application

Method 1: Development Mode

# Ensure virtual environment is activated
# On Windows: venv\Scripts\activate
# On Linux/macOS: source venv/bin/activate

# Run Flask application
python backend_process/app.py

The application will start at: http://localhost:5000

Method 2: Production Mode (Gunicorn)

# Install Gunicorn (already in requirements.txt)
pip install gunicorn

# Run with Gunicorn (Linux/macOS)
gunicorn -w 4 -b 0.0.0.0:8000 backend_process.app:app

# For Windows, use waitress instead
pip install waitress
waitress-serve --listen=0.0.0.0:8000 backend_process.app:app

Accessing the Platform

  1. Landing Page: http://localhost:5000/
  2. Sign Up: http://localhost:5000/signup-page
  3. Login: http://localhost:5000/login-page
  4. Dashboard: http://localhost:5000/dashboard/view (after login)
  5. Contact: http://localhost:5000/contact

Using the Platform

1️⃣ User Registration

  • Navigate to signup page
  • Enter name, email, and password
  • Verify email with 6-digit OTP sent to your inbox
  • Complete registration

2️⃣ Adding Stocks to Portfolio

  • Login to dashboard
  • Use search bar to find stocks (e.g., "AAPL", "TSLA", "RELIANCE.NS")
  • Click "Add to Portfolio"
  • Enter quantity and purchase price
  • Stock will be added to your portfolio

3️⃣ View Portfolio Analysis

  • Dashboard shows:
    • Total Portfolio Value
    • Total Profit/Loss
    • Individual stock performance
    • Win Rate percentage

4️⃣ Trading Simulation

  • Click on "Simulation" tab
  • View Virtual Cash (₹100,000 starting balance)
  • Monitor Portfolio Value and Total P/L
  • Run simulations with stock predictions
  • View Recent Trades and Trading Stats

5️⃣ AI Market Insights

  • Click on "AI Assistant" tab
  • Ask questions like:
    • "Should I buy AAPL stock?"
    • "Analyze my portfolio performance"
    • "What are the market trends today?"
  • Get AI-powered recommendations

6️⃣ Stock Price Predictions

  • Select a stock from your portfolio
  • Click "Predict" button
  • View LSTM model predictions for next 30 days
  • See risk assessment and ROI estimates

📁 Folder Structure (Detailed)

backend_process/ - Core Backend

app.py

Main Flask application initialization and configuration.

  • Initializes Flask app with template and static folders
  • Configures CORS for cross-origin requests
  • Sets up Flask-Mail for email functionality
  • Registers all blueprints (routes)
  • Defines page routes (home, signup, login, dashboard)
  • Runs development server on port 5000

extensions.py

Centralizes Flask extension objects to avoid circular imports.

  • Initializes Flask-Mail instance
  • Shared across the application

train_model.py

LSTM model training pipeline for stock price prediction.

  • Fetches historical stock data from Yahoo Finance
  • Preprocesses data using MinMaxScaler
  • Creates time-series sequences (60-day lookback)
  • Builds LSTM neural network (2 LSTM layers + Dense layers)
  • Trains model with early stopping
  • Saves trained model as .h5 file
  • Stores model metadata in MongoDB

Key Functions:

  • train_lstm_model(symbol): Trains LSTM model for given stock symbol

predict_stock.py

Stock price prediction engine using trained LSTM models.

  • Loads pre-trained LSTM models
  • Fetches recent stock data for prediction
  • Generates 30-day price forecasts
  • Calculates risk scores and ROI
  • Returns predictions with confidence intervals

Key Functions:

  • predict_stock_price(symbol, days=30): Predicts future stock prices

routes/ - API Endpoints

auth_routes.py

User authentication and session management.

  • /auth/signup - POST: User registration with password hashing
  • /auth/login - POST: User login with password verification
  • /auth/logout - GET: User logout and session clearing
  • Session validation and user verification

otp_routes.py

OTP-based email verification system.

  • /otp/send - POST: Generate and email 6-digit OTP
  • /otp/verify - POST: Verify OTP and activate account
  • OTP expiry management (5 minutes)
  • Resend OTP functionality

StockRoutes.py

User stock portfolio management APIs.

  • /api/stocks/add - POST: Add stock to user portfolio
  • /api/stocks/delete - POST: Remove stock from portfolio
  • /api/stocks/user - GET: Fetch all stocks for logged-in user
  • /api/stocks/update - POST: Update stock details
  • Real-time price fetching from Yahoo Finance

FetchStock.py

Stock data retrieval from Yahoo Finance API.

  • /api/fetch-stock - GET: Get current stock price and details
  • /api/stock-history - GET: Fetch historical price data
  • Company information and financials
  • Error handling for invalid stock symbols

predict_route.py

ML prediction API endpoints.

  • /api/predict - POST: Generate stock price predictions
  • Integrates with predict_stock.py
  • Returns JSON predictions with dates and prices

gemini_routes.py

Google Gemini AI integration for market insights.

  • /api/ai/chat - POST: General AI queries
  • /api/ai/portfolio-analysis - POST: Analyze user portfolio with AI
  • /api/ai/stock-recommendation - POST: Get AI stock recommendations
  • Context-aware responses with market data

simulation_routes.py

Virtual trading simulation APIs.

  • /api/simulation/portfolio - GET: Get simulation portfolio summary
  • /api/simulation/run - POST: Run ML-based trading simulation
  • /api/simulation/trades - GET: Fetch recent trades history
  • /api/simulation/stats - GET: Get trading statistics
  • /api/simulation/performance - GET: Portfolio performance chart data
  • Virtual cash management (₹100,000 starting balance)

search_company.py

Company search functionality.

  • /api/search-company - GET: Search stocks by name or symbol
  • Fuzzy matching for stock symbols
  • Returns matching companies with details

utils/ - Helper Functions

user_helpers.py

User management utilities.

  • generate_user_id(): Creates unique user IDs
  • validate_user_session(): Verifies user authentication
  • get_user_id_by_email(): Retrieves user ID from email
  • User data formatting and validation

stock_helpers.py

Stock portfolio helper functions.

  • add_user_stock(): Adds stock to user portfolio
  • delete_user_stock(): Removes stock from portfolio
  • get_user_stocks(): Fetches all user stocks
  • calculate_portfolio_value(): Computes total portfolio worth
  • Profit/loss calculations

email_utils.py & email_helpers.py

Email sending utilities.

  • send_otp_email(): Sends OTP verification email
  • send_welcome_email(): Sends welcome email after registration
  • HTML email templates
  • SMTP error handling

otp_utils.py

OTP generation and validation.

  • generate_otp(): Creates 6-digit random OTP
  • validate_otp(): Verifies OTP and checks expiry
  • OTP storage in database

gemini_helpers.py

Google Gemini AI integration helpers.

  • get_market_insights_ai(): Fetches AI-powered market analysis
  • get_direct_ai_response(): Direct AI query handler
  • API request formatting
  • Response parsing and error handling

db_connection/ - Database Layer

db.py

MongoDB connection and collections setup.

  • Establishes MongoDB connection using PyMongo
  • Defines database collections:
    • users: User accounts and authentication
    • UserStocks: User stock portfolios
    • trained_models: ML model metadata
    • predictions: Stock prediction history
    • SimulationPortfolios: Trading simulation data
    • counters: Auto-increment counters
  • Creates indexes for performance optimization
  • Database initialization and validation

Collections Schema:

users Collection:

{
  _id: ObjectId,
  user_id: String (unique),
  name: String,
  email: String (unique),
  password: String (hashed),
  created_at: DateTime,
  verified: Boolean,
  otp: String,
  otp_expiry: DateTime
}

UserStocks Collection:

{
  _id: ObjectId,
  user_id: String,
  symbol: String,
  name: String,
  qty: Number,
  buy_price: Number,
  current_price: Number,
  currency: String,
  exchange: String,
  date: String,
  created_at: DateTime,
  updated_at: DateTime,
  ip_address: String
}

trained_models Collection:

{
  _id: ObjectId,
  symbol: String,
  model_path: String,
  training_date: DateTime,
  accuracy: Number,
  epochs: Number,
  loss: Number
}

public-pages/ - Frontend Templates

index.html

Landing page with platform overview and features.

  • Hero section with call-to-action
  • Feature highlights
  • Technology stack showcase
  • Footer with links

signup.html

User registration form.

  • Name, email, password input fields
  • Form validation
  • Links to login page
  • Responsive design

login.html

User authentication form.

  • Email and password fields
  • Remember me checkbox
  • Forgot password link
  • Session handling

verify_otp.html

OTP verification page.

  • 6-digit OTP input
  • Resend OTP button
  • Auto-redirect after verification

dashboard.html

Main application dashboard (3000+ lines).

  • Portfolio Section: Stock listings, P/L tracking
  • Simulation Section: Virtual trading interface
  • AI Chat: Gemini AI integration
  • Stock Search: Real-time stock lookup
  • Charts & Graphs: Portfolio performance visualization
  • User Profile: Account settings and logout
  • Real-time data updates using JavaScript
  • Responsive grid layout with Tailwind CSS

contact.html

Contact page for support and inquiries.

  • Contact form
  • Email and social links
  • Support information

static/ - Static Assets

styles/

CSS stylesheets for custom styling.

  • login.css: Login page styles
  • sign-in.css: Signup page styles
  • otp.css: OTP verification styles

assets/

Images, logos, and brand assets.

  • logo_file/: Company logos in PNG, SVG, PDF formats
  • elements/: UI elements and icons

models/ - Trained LSTM Models

Pre-trained .h5 model files for various stocks:

  • AAPL_lstm.h5: Apple Inc. model
  • TSLA_lstm.h5: Tesla Inc. model
  • RPOWER.NS_lstm.h5: Reliance Power model

These models are loaded by predict_stock.py for real-time predictions.


🔌 API Endpoints

Authentication APIs

Method Endpoint Description Request Body
POST /auth/signup User registration { name, email, password }
POST /auth/login User login { email, password }
GET /auth/logout User logout -

OTP Verification APIs

Method Endpoint Description Request Body
POST /otp/send Send OTP to email { email }
POST /otp/verify Verify OTP { email, otp }

Stock Management APIs

Method Endpoint Description Parameters
POST /api/stocks/add Add stock to portfolio { symbol, qty, buy_price }
POST /api/stocks/delete Delete stock { stock_id }
GET /api/stocks/user Get user stocks user_id (session)
POST /api/stocks/update Update stock { stock_id, qty, price }

Stock Data APIs

Method Endpoint Description Query Params
GET /api/fetch-stock Get stock details symbol
GET /api/stock-history Historical data symbol, period
GET /api/search-company Search stocks query

Prediction APIs

Method Endpoint Description Request Body
POST /api/predict Stock price prediction { symbol, days }
POST /api/train-model Train new model { symbol }

AI Integration APIs

Method Endpoint Description Request Body
POST /api/ai/chat AI chat query { message }
POST /api/ai/portfolio-analysis Analyze portfolio { user_id }
POST /api/ai/stock-recommendation Stock recommendation { symbol }

Simulation APIs

Method Endpoint Description Query Params
GET /api/simulation/portfolio Simulation summary currency
POST /api/simulation/run Run simulation { symbol, qty, price }
GET /api/simulation/trades Recent trades limit
GET /api/simulation/stats Trading statistics currency
GET /api/simulation/performance Performance chart currency

🧠 Machine Learning Model

LSTM Architecture

The stock price prediction model uses a Long Short-Term Memory (LSTM) neural network architecture:

Model Structure:
├── Input Layer: 60 timesteps × 1 feature (closing price)
├── LSTM Layer 1: 50 units, return_sequences=True
├── Dropout Layer: 20% dropout rate
├── LSTM Layer 2: 50 units, return_sequences=False
├── Dropout Layer: 20% dropout rate
├── Dense Layer 1: 25 units, activation='relu'
├── Dense Layer 2: 1 unit (prediction output)
└── Optimizer: Adam, Loss: MSE

Training Process

  1. Data Collection: Fetch 5 years historical data from Yahoo Finance
  2. Preprocessing: Normalize data using MinMaxScaler (0-1 range)
  3. Sequence Creation: Create 60-day lookback sequences
  4. Train/Test Split: 80% training, 20% testing
  5. Model Training: Train with early stopping (patience=10)
  6. Model Saving: Save as .h5 file in models/ directory
  7. Metadata Storage: Store training metrics in MongoDB

Prediction Workflow

  1. Load pre-trained model for stock symbol
  2. Fetch latest 60 days of stock data
  3. Normalize data using same scaler
  4. Generate predictions for next N days
  5. Inverse transform predictions to actual prices
  6. Calculate risk score and ROI
  7. Return predictions with confidence intervals

Model Performance Metrics

  • Mean Squared Error (MSE): Measures prediction accuracy
  • R² Score: Model goodness-of-fit
  • Training Accuracy: Tracked during training
  • Validation Loss: Monitored to prevent overfitting

💾 Database Schema

MongoDB Collections

users Collection

Stores user account information.

{
  _id: ObjectId("..."),
  user_id: "USR001",
  name: "John Doe",
  email: "john@example.com",
  password: "hashed_password",
  created_at: ISODate("2025-11-10T10:30:00Z"),
  verified: true,
  otp: "123456",
  otp_expiry: ISODate("2025-11-10T10:35:00Z"),
  preferred_currency: "INR"
}

UserStocks Collection

Stores user stock portfolios.

{
  _id: ObjectId("..."),
  user_id: "USR001",
  symbol: "AAPL",
  name: "Apple Inc.",
  qty: 10,
  buy_price: 250.00,
  current_price: 268.47,
  currency: "USD",
  exchange: "NASDAQ",
  date: "2025-11-10",
  created_at: ISODate("2025-11-10T10:30:00Z"),
  updated_at: ISODate("2025-11-10T15:45:00Z"),
  ip_address: "127.0.0.1"
}

trained_models Collection

Stores ML model metadata.

{
  _id: ObjectId("..."),
  symbol: "AAPL",
  model_path: "models/AAPL_lstm.h5",
  training_date: ISODate("2025-11-10T12:00:00Z"),
  accuracy: 0.95,
  epochs: 50,
  loss: 0.0023,
  data_range: {
    start_date: "2020-11-10",
    end_date: "2025-11-10"
  }
}

predictions Collection

Stores prediction history.

{
  _id: ObjectId("..."),
  user_id: "USR001",
  symbol: "AAPL",
  prediction_date: ISODate("2025-11-10T14:00:00Z"),
  predictions: [
    { date: "2025-11-11", price: 270.50 },
    { date: "2025-11-12", price: 272.30 }
  ],
  risk_score: 0.35,
  roi_estimate: 8.5
}

SimulationPortfolios Collection

Stores virtual trading data.

{
  _id: ObjectId("..."),
  user_id: "USR001",
  virtual_cash: 96500.00,
  total_invested: 3500.00,
  portfolio_value: 6979.90,
  total_pl: 3479.90,
  trades: [
    {
      symbol: "TSLA",
      qty: 10,
      buy_price: 100.00,
      current_price: 429.52,
      profit: 3295.20
    }
  ],
  updated_at: ISODate("2025-11-10T16:00:00Z")
}

🧪 Testing

Running Tests

# Install testing dependencies (already in requirements.txt)
pip install pytest pytest-flask

# Run all tests
pytest

# Run specific test file
pytest test_full_integration.py

# Run with verbose output
pytest -v

# Run with coverage report
pytest --cov=backend_process

Test Files

  • test_full_integration.py: End-to-end integration tests
  • test_user_session.py: User authentication tests
  • test_user_stocks.py: Portfolio management tests
  • test_gemini_integration.py: AI integration tests
  • test_dashboard_access.py: Dashboard functionality tests

🤝 Contributing

We welcome contributions from the community! Here's how you can help:

How to Contribute

  1. Fork the Repository

    # Click "Fork" button on GitHub
  2. Clone Your Fork

    git clone https://github.com/YOUR_USERNAME/Stock-Price-Prediction.git
    cd Stock-Price-Prediction
  3. Create Feature Branch

    git checkout -b feature/your-feature-name
  4. Make Changes

    • Write clean, documented code
    • Follow PEP 8 style guide for Python
    • Add comments for complex logic
  5. Test Your Changes

    pytest
  6. Commit Changes

    git add .
    git commit -m "Add: Description of your changes"
  7. Push to GitHub

    git push origin feature/your-feature-name
  8. Create Pull Request

    • Go to original repository
    • Click "New Pull Request"
    • Describe your changes
    • Wait for review

Contribution Guidelines

  • Follow existing code structure and naming conventions
  • Write unit tests for new features
  • Update documentation for API changes
  • Keep commits focused and descriptive
  • Ensure all tests pass before submitting PR

📄 License

This project is licensed under the MIT License.

MIT License

Copyright (c) 2025 Ishan Surdi & Vrushali Deshpande

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

🙏 Acknowledgments

  • Yahoo Finance API for real-time stock data
  • Google Gemini AI for intelligent market insights
  • MongoDB for robust database management
  • TensorFlow/Keras for machine learning framework
  • Flask community for excellent web framework
  • Open Source Community for various libraries and tools

📧 Contact & Support

Developers

Ishan Surdi
GitHub: @ishansurdi
Vrushali Deshpande
GitHub: @vrushalideshpande

Report Issues

Found a bug or have a feature request? Please open an issue on GitHub:

Project Links


Developed by Ishan Surdi & Vrushali Deshpande

© 2025 Predictr. All Rights Reserved.

⬆ Back to Top

About

This project predicts future stock prices based on historical data using machine learning techniques. The model analyzes trends and patterns in past stock performance to forecast upcoming prices, helping users understand potential market movements.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •