A full-stack, production-grade web application that correlates Indian regional climate data (temperature, heatwave events) with energy sector stock performance, featuring real-time XGBoost ML predictions, AI chatbot, and live PostgreSQL dashboards.
| Feature | Description |
|---|---|
| 📊 Live Dashboard | Real-time temperature vs. stock price area chart, updating every 8 seconds |
| 🤖 ML Prediction Engine | XGBoost model predicts energy stock price from climate inputs |
| 💬 AI Chatbot (ClimateIQ) | Gemini-powered context-aware chatbot grounded in live DB data |
| 📈 Insights Page | Statistical analysis: heatwave impact, price volatility, prediction trends |
| 🌡️ Climate Events Donut | Full-table pie chart showing Normal Days vs. Heatwave Alerts |
| ⚡ Auto DB Seeding | On first run, auto-creates schema and seeds from CSV — zero setup |
Market/
├── backend/ # Node.js Express API server
│ ├── server.js # Main API server (all routes)
│ ├── predict.py # Python XGBoost inference script
│ ├── chat.py # Python Gemini AI chatbot script
│ ├── init_db.sql # PostgreSQL schema (tables definition)
│ ├── init_db.js # Manual DB initializer script
│ ├── seed_csv.js # Manual CSV seeder script
│ ├── list_models.js # Utility to list available Gemini models
│ ├── package.json # Node.js dependencies
│ └── .env # Environment variables (secrets)
│
├── frontend/ # React + Vite frontend
│ ├── src/
│ │ ├── pages/
│ │ │ ├── Dashboard.jsx # Market Overview page (charts + stats)
│ │ │ ├── Prediction.jsx # ML Prediction input & result page
│ │ │ └── Insights.jsx # Statistical insights dashboard
│ │ ├── components/
│ │ │ ├── ChatBot.jsx # Floating AI chat widget
│ │ │ └── ChatBot.css # Chatbot-specific styles
│ │ ├── App.jsx # Root app with routing & sidebar nav
│ │ ├── App.css # App-level layout styles
│ │ └── index.css # Global CSS design system & variables
│ ├── index.html
│ └── package.json
│
├── final_processed_data.csv # Historical climate + stock dataset
├── xgb_stock_prediction_model_raw.pkl # Pre-trained XGBoost regressor (price prediction)
├── rf_classifier_20k_model.pkl # Pre-trained Random Forest classifier (trend classification)
├── inspect_model.py # Utility to inspect model features
└── README.md # This file
| Technology | Purpose |
|---|---|
| Node.js + Express | REST API server |
| PostgreSQL | Persistent database for all historical and prediction data |
| Python 3 | XGBoost inference (predict.py) and Gemini AI bridge (chat.py) |
| XGBoost | Pre-trained ML model for stock price prediction |
| Google Gemini API | Powers the ClimateIQ AI chat assistant |
| dotenv | Manages environment variables |
| Technology | Purpose |
|---|---|
| React 18 + Vite | Modern SPA framework |
| Recharts | Area charts, pie/donut charts for data visualization |
| Axios | HTTP client for API calls |
| Lucide React | Icon library |
| Vanilla CSS | Custom CSS design system (no frameworks) |
The PostgreSQL database Stockmarket has three core tables:
| Column | Type | Description |
|---|---|---|
id |
SERIAL PK | Unique ID |
name |
TEXT | Company name (e.g., Reliance) |
symbol |
TEXT UNIQUE | Stock ticker symbol |
sector |
TEXT | Always Energy for this dataset |
| Column | Type | Description |
|---|---|---|
id |
SERIAL PK | Unique ID |
date |
DATE | Record date |
region |
TEXT | Region (default Unknown) |
avg_temperature |
NUMERIC | Temperature in °C |
heatwave_flag |
BOOLEAN | true if heatwave day |
| Column | Type | Description |
|---|---|---|
id |
SERIAL PK | Unique ID |
company_id |
INT FK | References companies.id |
date |
DATE | Record date |
open_price |
NUMERIC | Open price (₹) |
close_price |
NUMERIC | Close price (₹) |
high_price |
NUMERIC | Day high (₹) |
low_price |
NUMERIC | Day low (₹) |
volume |
BIGINT | Trade volume |
| Column | Type | Description |
|---|---|---|
id |
SERIAL PK | Unique ID |
company_id |
INT FK | References companies.id |
date |
DATE | Prediction date |
input_temperature |
NUMERIC | Temperature used as input (°C) |
predicted_price |
NUMERIC | XGBoost predicted price (₹) |
predicted_trend |
TEXT | Bullish, Bearish, or Neutral |
confidence_score |
NUMERIC | Model confidence (0–100%) |
The prediction engine uses two complementary ML models working together:
Model file: xgb_stock_prediction_model_raw.pkl
Trained on Indian energy sector historical data combining climate and financial features. Predicts the next-day stock closing price (₹).
Model file: rf_classifier_20k_model.pkl
A 20,000-tree Random Forest classifier that predicts the market trend direction (Bullish / Bearish / Neutral) and provides probability-based confidence scores via predict_proba.
| Feature | Description |
|---|---|
Temperature |
Regional average temperature (°C) |
CDD |
Cooling Degree Days (proxy: max(0, Temp - 25)) |
CDD_7 |
7-day CDD accumulator |
Heatwave |
Binary flag: 1 = heatwave day |
Return_Lag1 |
1-day return lag |
Return_Lag3 |
3-day return lag |
Return_Lag5 |
5-day return lag |
Temp_Anomaly |
Deviation from 30°C baseline |
CDD_Lag1 |
CDD 1-day lag |
CDD_Lag3 |
CDD 3-day lag |
MA_5 |
5-day moving average of close price |
Volatility |
Historical volatility |
Demand_Trend |
Energy demand trend index |
Trend |
Market trend signal |
Volatility_Change |
Change in volatility |
- Predicted Close Price (₹) — from XGBoost regressor
- Trend (Bullish/Bearish/Neutral) — from RF classifier
- Confidence Score (%) — from RF classifier's
predict_proba
All endpoints are served on http://localhost:5000.
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/stocks |
Fetch all companies |
GET |
/api/temperature |
Latest 30 temperature records |
GET |
/api/dashboard |
Time-offset merged climate + stock data (30 rows) |
POST |
/api/predict |
Run XGBoost prediction with climate inputs |
GET |
/api/insights |
Aggregated statistical insights from DB |
GET |
/api/climate-summary |
Full-table heatwave/normal day counts |
POST |
/api/chat |
Send message to ClimateIQ AI chatbot |
{
"temperature": 38.5,
"heatwave_flag": true,
"company_id": 1
}{
"prediction": 872.34,
"trend": "Bullish",
"confidence": 78.5,
"returnPct": 2.45,
"volatility": 0.0415
}{
"message": "How do heatwaves affect energy stocks?",
"history": []
}Create a .env file inside the backend/ folder:
# PostgreSQL Database
DB_NAME=Stockmarket
DB_USER=postgres
DB_PASSWORD=your_password_here
DB_HOST=localhost
DB_PORT=5432
# Server
PORT=5000
# Google Gemini API Key (for AI chatbot)
GEMINI_API_KEY=your_gemini_api_key_here
# JWT (for future auth)
JWT_SECRET=your_secret_key_here
⚠️ Never commit your.envfile to Git. Add it to.gitignore.
Make sure the following are installed on your system:
- Node.js
v18+ - Python
3.8+ - PostgreSQL
v14+ - Python packages:
xgboost,pandas,numpy,scikit-learn
pip install xgboost pandas numpy scikit-learnCreate the database in PostgreSQL:
CREATE DATABASE Stockmarket;Then update your backend/.env file with the correct credentials.
cd backend
npm install
node server.jsOn first start, the server will automatically:
- Connect to PostgreSQL
- Create all tables (from
init_db.sql) - Seed data from
final_processed_data .csv
You should see:
✅ Connected to PostgreSQL Database successfully!
✅ Schema created successfully.
⌛ Inserting records (this may take a minute)...
✅ Successfully seeded XXXXX records!
Server running on port 5000
Open a new terminal:
cd frontend
npm install
npm run devVisit: http://localhost:5173
The dataset contains historical Indian energy sector climate-finance data.
| Column | Description |
|---|---|
Date |
Trading date |
Stock |
Company ticker symbol |
CLOSE |
Closing stock price (₹) |
Temperature |
Regional temperature (°C) |
Heatwave |
Binary: 1 if heatwave day, 0 otherwise |
The data covers multiple Indian energy companies including Reliance Industries, Tata Power, NTPC, Adani Green, and Power Grid Corp.
Run the inspection utility to see model feature names and type:
python inspect_model.py- 3 Stat Cards: Avg Temperature, Latest Stock Price, Climate Risk Score
- Area Chart: Temperature (°C, left axis) vs. Stock Price (₹, right axis) — live 8s refresh
- Donut Chart: Climate Events split — Normal Days vs. Heatwave Alerts
- Input form: Temperature (°C), Heatwave toggle, Company selector
- Circular progress indicator for Confidence Score (color-coded: Green/Orange/Red)
- Displays: Predicted Price, Trend (Bullish/Bearish/Neutral), Return %, Volatility
- Temperature statistics: Avg, Max, Min, Standard Deviation
- Stock price analysis: Heatwave-day vs. Normal-day averages, Volatility %
- Prediction history: Total predictions, Bullish/Bearish/Neutral distribution
- Floating chat widget available on all pages
- Context-aware: grounded in live PostgreSQL data (avg temp, stock price, predictions)
- Powered by Google Gemini via Python bridge
Files are staged for deletion in Git. Run in the Market folder:
git restore --staged .Make sure Python is added to your system PATH, or use python3:
python3 --version- Verify PostgreSQL service is running
- Check
DB_PASSWORDandDB_USERinbackend/.env - Ensure database
Stockmarketexists:CREATE DATABASE Stockmarket;
Change the port in backend/.env:
PORT=5001And update API URLs in frontend pages from 5000 to 5001.
Ensure both xgb_stock_prediction_model_raw.pkl and rf_classifier_20k_model.pkl are in the root Market/ directory (not inside backend/).
# Dependencies
node_modules/
__pycache__/
*.pyc
# Environment
.env
# Build output
dist/
build/
# Data & Models (optional, large files)
*.pkl
final_processed_data .csv- Fork the repository
- Create your feature branch:
git checkout -b feature/your-feature - Commit your changes:
git commit -m 'Add some feature' - Push to the branch:
git push origin feature/your-feature - Open a Pull Request
This project is for academic and research purposes.
Bhargav — Full-Stack Developer
ClimateStock India Predictor · Built with ❤️ using React, Node.js, Python & XGBoost