A full-stack web application for predicting NSE (National Stock Exchange) stock prices using linear regression. Built with FastAPI (backend) and React with TypeScript (frontend).
- Historical Data Fetching: Retrieve 1 year of NSE stock data using yfinance
- Linear Regression Model: Train a model on historical data with lag-1 features
- 10-Day Predictions: Forecast stock prices for the next 10 trading days
- Performance Metrics: Display Rยฒ score, RMSE, and MAE for model evaluation
- Interactive Charts: Visualize historical and predicted prices with Recharts
- CORS Enabled: Frontend and backend communicate seamlessly
- Error Handling: Robust error handling and loading states
- Responsive UI: Modern, mobile-friendly interface with Tailwind CSS
- Python 3.8+ (for backend)
- Node.js 16+ (for frontend)
- pip (Python package manager)
- npm or yarn (Node.js package manager)
git clone <repository-url> cd stock-price-forecaster
cd backend
pip install -r requirements.txtpython main.py
The API will be available at http://localhost:8000
Check the interactive API docs: http://localhost:8000/docs
cd frontend
npm installnpm start
The application will open at http://localhost:3000
stock-price-forecaster/
โโโ backend/
โ โโโ main.py # FastAPI application with endpoints
โ โโโ data_pipeline.py # Data fetching and preprocessing
โ โโโ model.py # Linear regression model
โ โโโ requirements.txt # Python dependencies
โ โโโ README.md # Backend documentation
โ
โโโ frontend/
โ โโโ public/
โ โ โโโ index.html
โ โโโ src/
โ โ โโโ components/
โ โ โ โโโ StockSelector.tsx # Stock selection dropdown
โ โ โ โโโ Chart.tsx # Price chart component
โ โ โ โโโ Predictions.tsx # Predictions display
โ โ โ โโโ Metrics.tsx # Model metrics display
โ โ โโโ services/
โ โ โ โโโ api.ts # API service layer
โ โ โโโ types/
โ โ โ โโโ index.ts # TypeScript interfaces
โ โ โโโ App.tsx # Main app component
โ โ โโโ App.css # App styles
โ โ โโโ index.tsx # React entry point
โ โ โโโ index.css # Global styles
โ โโโ package.json
โ โโโ tsconfig.json
โ โโโ README.md # Frontend documentation
โ
โโโ .gitignore
โโโ README.md # This file
Endpoint: POST /fetch-data
Request:
{
"symbol": "RELIANCE.NS"
}Response:
{
"symbol": "RELIANCE.NS",
"data": [
{
"date": "2023-09-01",
"open": 2750.50,
"high": 2760.00,
"low": 2740.00,
"close": 2755.25,
"volume": 5000000
},
...
],
"message": "Successfully fetched 252 days of data for RELIANCE.NS"
}Endpoint: POST /train
Request:
{
"symbol": "RELIANCE.NS"
}Response:
{
"symbol": "RELIANCE.NS",
"metrics": {
"r2_score": 0.8234,
"rmse": 45.67,
"mae": 35.21,
"coefficient": 0.9852,
"intercept": 23.45
},
"message": "Model trained successfully for RELIANCE.NS"
}Endpoint: POST /predict
Request:
{
"symbol": "RELIANCE.NS",
"n_days": 10
}Response:
{
"symbol": "RELIANCE.NS",
"predictions": [2760.50, 2765.25, 2770.00, 2768.50, 2775.00, 2780.25, 2785.00, 2783.50, 2790.00, 2795.25],
"message": "Successfully predicted prices for 10 days"
}Endpoint: GET /metrics/{symbol}
Response:
{
"symbol": "RELIANCE.NS",
"trained": true,
"metrics": {
"r2_score": 0.8234,
"rmse": 45.67,
"mae": 35.21,
"coefficient": 0.9852,
"intercept": 23.45
}
}Endpoint: GET /available-symbols
Response:
{
"symbols": ["RELIANCE.NS", "TCS.NS", "INFY.NS", "WIPRO.NS", "HDFC.NS", ...],
"note": "You can use any valid NSE symbol. Format: SYMBOL.NS"
}The application includes pre-configured symbols:
- RELIANCE.NS - Reliance Industries
- TCS.NS - Tata Consultancy Services
- INFY.NS - Infosys
- WIPRO.NS - Wipro
- HDFC.NS - HDFC Bank
- ICICIBANK.NS - ICICI Bank
- KOTAKBANK.NS - Kotak Mahindra Bank
- AXISBANK.NS - Axis Bank
- MARUTI.NS - Maruti Suzuki
- LT.NS - Larsen & Toubro
You can also use any valid NSE symbol in the format SYMBOL.NS
- Fetch: Retrieve 365 days (1 year) of historical OHLCV data from yfinance
- Preprocess:
- Handle missing values (forward fill, then backward fill)
- Sort data by date in ascending order
- Feature Engineering:
- Create lag-1 feature (previous day's close price)
- Use lag-1 as input feature (X)
- Use current close price as target (y)
- Train/Test Split: 80% training, 20% testing
Linear Regression Model:
Price(t) = coefficient ร Price(t-1) + intercept
- Coefficient: Typically close to 1.0, indicating high correlation between consecutive days
- Intercept: Small value, usually close to 0
-
Rยฒ Score: Coefficient of determination (0-1). Higher is better.
- 0.8+: Excellent
- 0.6-0.8: Good
- 0.4-0.6: Fair
- <0.4: Poor
-
RMSE: Root Mean Square Error (in rupees). Lower is better.
- Average prediction error magnitude
-
MAE: Mean Absolute Error (in rupees). Lower is better.
- Average absolute prediction error
Create a .env file in the backend/ directory:
# Backend configuration
HOST=0.0.0.0
PORT=8000
DEBUG=True
The frontend uses environment variables for API configuration:
REACT_APP_API_URL=http://localhost:8000
Create a .env.local file in the frontend/ directory to override defaults.
cd backend
python -m pytestcd frontend npm test
- Select Stock: Choose a stock symbol from the dropdown
- Fetch Data: Click "Fetch Data" to retrieve 1 year of historical prices
- Train Model: Click "Train Model" to train the linear regression model
- View Metrics: Check Rยฒ, RMSE, MAE to evaluate model performance
- Get Predictions: Click "Predict Prices" to forecast next 10 days
- Analyze Results: View the chart showing historical data + predictions
This forecaster uses a simple linear regression model for educational purposes only.
- Stock prices are affected by numerous unpredictable factors
- Linear regression assumes a linear relationship between consecutive prices
- Actual stock prices may differ significantly from predictions
- This is NOT financial advice. Do not use for real trading decisions.
- Linear regression may not capture complex market dynamics
- Model assumes past price correlation continues (often violated)
- No consideration of market events, news, or fundamental analysis
- Predictions accuracy decreases beyond 3-5 days
To enhance prediction accuracy, consider:
- Using LSTM or GRU neural networks
- Adding technical indicators (MA, RSI, MACD)
- Including volume and volatility data
- Ensemble methods combining multiple models
- Incorporating external data (sentiment, news, fundamentals)
- CORS is configured to accept all origins (
*). For production, restrict to specific domains. - No authentication is currently implemented. Add if exposing to production.
- Input validation should be enhanced for untrusted environments.
Error: Module not found
# Ensure virtual environment is activated and dependencies are installed
pip install -r requirements.txtError: Port 8000 already in use
# Change port in main.py or kill existing process python main.py # Modify the uvicorn.run() call
Error: Cannot find module 'recharts'
# Reinstall dependencies cd frontend npm install
API calls returning 404
- Ensure backend is running on
http://localhost:8000 - Check CORS configuration in
main.py - Verify
REACT_APP_API_URLenvironment variable
- FastAPI: https://fastapi.tiangolo.com/
- React: https://react.dev/
- Recharts: https://recharts.org/
- yfinance: https://yfinance.readthedocs.io/
- scikit-learn: https://scikit-learn.org/
- Tailwind CSS: https://tailwindcss.com/
This project is open source and available under the MIT License.
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
For issues, questions, or suggestions, please open an issue on GitHub.
Built with โค๏ธ for learning and exploration of stock price prediction