Skip to content

Devguru-codes/Stock-AI-Forecaster

Repository files navigation

Stock AI-Forecaster

A comprehensive stock analysis platform combining LSTM neural networks with AI-powered insights for professional financial analysis.

πŸš€ Features

  • βœ… Real-Time Stock Data Integration - Fetches live data using yfinance (Yahoo Finance)
  • βœ… Intelligent Price Forecasting - LSTM neural network generates 7-day price predictions
  • βœ… Real Closing Prices - Shows actual closing prices when available, not model predictions
  • βœ… AI-Powered Analysis - Google Gemini Flash 2.5 provides market sentiment and technical analysis
  • βœ… Comprehensive Technical Indicators - RSI, MACD, Bollinger Bands, Simple Moving Averages (SMA 20/50)
  • βœ… Interactive Charts - Beautiful visualizations with Recharts and dynamic trend coloring
  • βœ… Professional Report Generation - Export detailed analysis reports in Word or PDF format
  • βœ… Fallback Simulation Mode - Continues working even when backend services are unavailable
  • βœ… Modern Responsive UI - Built with React 19, TypeScript, and Tailwind CSS

πŸ—οΈ Architecture

  • Frontend: React 19 + TypeScript + Vite + Tailwind CSS + Recharts
  • Backend: FastAPI + Python + TensorFlow/Keras + Uvicorn
  • Data Source: Yahoo Finance API (yfinance)
  • AI Analysis: Google Gemini Flash 2.5
  • Model: Pre-trained LSTM neural network for time series forecasting
  • Supported Tickers: AAPL, GOOGL, MSFT, AMZN, TSLA

πŸ“‹ Prerequisites

  • Python 3.8+ with pip
  • Node.js 18+ with npm
  • Trained LSTM Model (lstm_stock_predictor.keras) in project root
  • Internet Connection for real-time data fetching

πŸ› οΈ Installation & Setup

1. Clone the Repository

git clone <repository-url>
cd stock-ai-forecaster

2. Backend Setup (Python)

# Create virtual environment (recommended)
python -m venv venv
venv\Scripts\activate  # On Windows
# source venv/bin/activate  # On macOS/Linux

# Install Python dependencies
pip install -r requirements.txt

3. Frontend Setup (Node.js)

# Install Node.js dependencies
npm install

4. Environment Configuration

Create a .env.local file in the root directory:

VITE_GEMINI_API_KEY=your_gemini_api_key_here
GEMINI_API_KEY=your_gemini_api_key_here
GEMINI_API_KEY2=your_backup_gemini_api_key_here

πŸš€ Running the Application

This is a full-stack application requiring both backend and frontend to run simultaneously.

1. Start the Python Backend (Terminal 1)

python server.py

Expected Output:

LSTM model loaded successfully
INFO:     Started server process [PID] on http://0.0.0.0:8000

2. Start the React Frontend (Terminal 2)

npm run dev

Expected Output:

VITE v6.2.0 ready in XXXX ms
➜ Local:   http://localhost:5173/
➜ Network: http://192.168.X.X:5173/

3. Access the Application

Open your browser and navigate to http://localhost:5173/

πŸ“š API Endpoints

GET /predict?ticker={TICKER}

Returns historical data and price forecasts for a given stock ticker.

Parameters:

  • ticker (string): Stock symbol (AAPL, GOOGL, MSFT, AMZN, TSLA)

Response:

{
  "history": [
    {
      "date": "2024-01-01",
      "open": 150.25,
      "high": 152.10,
      "low": 149.80,
      "close": 151.50,
      "volume": 12345678
    }
  ],
  "forecast": [
    {
      "date": "2024-01-01",
      "price": 151.50,
      "isForecast": false
    },
    {
      "date": "2024-01-02",
      "price": 153.25,
      "isForecast": true
    }
  ]
}

GET /report/{TICKER}?format={FORMAT}

Generates comprehensive stock analysis reports.

Parameters:

  • ticker (string): Stock symbol
  • format (string): "word" or "pdf"

Response: File download

GET /health

Health check endpoint.

Response:

{
  "status": "healthy",
  "model_loaded": true
}

πŸ”§ Configuration

Environment Variables

  • VITE_GEMINI_API_KEY: Primary Gemini API key for frontend
  • GEMINI_API_KEY: Primary Gemini API key for backend
  • GEMINI_API_KEY2: Backup Gemini API key

Model Configuration

  • Look-back Period: 60 days of historical data for predictions
  • Forecast Horizon: 7 days of price predictions
  • Supported Tickers: AAPL, GOOGL, MSFT, AMZN, TSLA

πŸ› Troubleshooting

Backend Issues

"Model not loaded"

  • Ensure lstm_stock_predictor.keras exists in the project root
  • Check file permissions
  • Verify TensorFlow installation: python -c "import tensorflow as tf; print(tf.__version__)"

"Server Disconnected (Simulated Mode)"

  • Backend server not running on port 8000
  • Check for firewall blocking port 8000
  • Verify FastAPI is running: curl http://localhost:8000/health

"Could not fetch data for {ticker}"

  • Check internet connection
  • Verify ticker symbol is supported
  • Yahoo Finance API may be temporarily unavailable

Frontend Issues

"Failed to fetch" errors

  • Backend server not running
  • CORS issues (check browser console)
  • Wrong API endpoint URL

Blank charts or missing data

  • Check browser console for JavaScript errors
  • Ensure backend is responding correctly
  • Verify ticker selection

AI Analysis Issues

"Market sentiment analysis currently unavailable"

  • Invalid or missing Gemini API key
  • API quota exceeded
  • Temporary Gemini service issues

Performance Issues

Slow loading times

  • Large historical data sets (180 days)
  • Network latency for data fetching
  • Heavy LSTM model computations

πŸ“ Project Structure

stock-ai-forecaster/
β”œβ”€β”€ components/           # React components
β”‚   β”œβ”€β”€ MainChart.tsx    # Price and forecast visualization
β”‚   β”œβ”€β”€ ForecastCard.tsx # AI analysis display
β”‚   β”œβ”€β”€ IndicatorPanel.tsx # Technical indicators
β”‚   └── MacdPanel.tsx    # MACD indicator
β”œβ”€β”€ services/            # API and external services
β”‚   β”œβ”€β”€ apiService.ts    # Backend API calls
β”‚   β”œβ”€β”€ dataService.ts   # Fallback data simulation
β”‚   └── geminiService.ts # AI analysis
β”œβ”€β”€ utils/               # Utility functions
β”‚   └── financialMath.ts # Technical calculations
β”œβ”€β”€ server.py            # FastAPI backend server
β”œβ”€β”€ update.py            # Model update utilities
β”œβ”€β”€ grounding_search.py  # Google search integration
β”œβ”€β”€ lstm_stock_predictor.keras # Trained model
β”œβ”€β”€ predictions_cache.csv     # Forecast cache
└── requirements.txt     # Python dependencies

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/new-feature
  3. Commit changes: git commit -am 'Add new feature'
  4. Push to branch: git push origin feature/new-feature
  5. Submit a pull request

πŸ“„ License

This project is for educational and research purposes. Please ensure compliance with API terms of service and financial regulations.

⚠️ Disclaimer

This application is for educational purposes only and should not be considered as financial advice. Always consult with qualified financial advisors before making investment decisions. Past performance does not guarantee future results.


Built with ❀️ using modern web technologies and machine learning

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published