Spaces:
Sleeping
Sleeping
Update README.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420---title: stockpredictorsdk: gradioemoji: π»colorFrom: bluecolorTo: indigosdk_version: 6.14.0pinned: false---# π Stock Price PredictorAI-powered stock price predictions using LSTM neural networks, technical analysis, and market sentiment analysis.**Features:**- β‘ Fast predictions (<2 seconds)- π§ Deep Learning LSTM model- π Technical indicators (RSI, MACD, Volatility, etc.)- π News sentiment analysis- πΎ 24-hour prediction cache- π― 85-86% directional accuracy- π± Web interface (Gradio)---## π Quick Start (Local)### 1. Clone or Download Files```bash# Download all files from this repository# You should have:# - app.py# - model.py# - requirements.txt# - .env.example# - .gitignore# - README.md```### 2. Create Virtual Environment (Recommended)```bash# Windowspython -m venv venvvenv\Scripts\activate# macOS/Linuxpython3 -m venv venvsource venv/bin/activate```### 3. Install Dependencies```bashpip install -r requirements.txt```### 4. Setup Environment Variables```bash# Copy example file to .envcp .env.example .env# Edit .env and add your API key:# FINNHUB_API_KEY=your_api_key_here```**Get Free API Key:**- Go to https://finnhub.io/register- Sign up (free tier available)- Copy your API key to `.env`### 5. Run the App```bashpython app.py```The app will start at `http://localhost:7860`---## π Deploy on HuggingFace Spaces### Step 1: Create HF Space1. Go to https://huggingface.co/spaces2. Click "Create new Space"3. Fill in:- **Space name**: `stock-predictor` (or any name)- **License**: `mit` or `apache-2.0`- **SDK**: Select **Gradio**- **Visibility**: Public or Private4. Click "Create Space"### Step 2: Upload FilesYou'll see a command to clone your space. Then:```bashcd your-space-repogit clone https://huggingface.co/spaces/YOUR_USERNAME/stock-predictorcd stock-predictor```Copy these files into the directory:```app.pymodel.pyrequirements.txt.env.example.gitignoreREADME.md```### Step 3: Setup Environment Variables (HF Spaces)In HF Spaces, go to **Settings** β **Repository secrets** β **Add secret**Add:- **Name**: `FINNHUB_API_KEY`- **Value**: Your Finnhub API key**DO NOT** commit `.env` file to git. HF Spaces will automatically load secrets as environment variables.### Step 4: Push to HF Spaces```bashgit add .git commit -m "Initial stock predictor setup"git push```HF Spaces will automatically:1. Install dependencies from `requirements.txt`2. Run `app.py`3. Deploy your app with a public URL---## π Usage Guide### Via Web Interface1. Enter stock symbol (e.g., `AAPL`, `GOOGL`, `MSFT`)2. Select number of days to predict (1-30)3. Click **π Predict**4. View results table and analysis### Supported SymbolsAny stock ticker from:- **US**: NASDAQ, NYSE (AAPL, GOOGL, MSFT, TSLA, etc.)- **Europe**: LSE, Euronext (various symbols)- **India**: NSE, BSE (SBIN.NS, INFY.NS, etc.)### Example Stocks```AAPL - AppleGOOGL - Google (Alphabet)MSFT - MicrosoftAMZN - AmazonTSLA - TeslaNVDA - NVIDIAMETA - Meta (Facebook)NFLX - Netflix```---## π§ How It Works### 1. Data Collection (Step 1)- Fetches 100 days of historical price data from Yahoo Finance- Uses: Open, High, Low, Close, Volume prices### 2. Feature Engineering (Step 2)Calculates 6 technical indicators:- **Close**: Stock closing price- **RSI**: Relative Strength Index (momentum, 14-day)- **MACD**: Moving Average Convergence Divergence- **Volatility**: Standard deviation of returns (10-day)- **SMA20**: 20-day Simple Moving Average (trend)- **ROC**: Rate of Change (5-day)### 3. Preprocessing (Step 3)- Normalizes all features to [0, 1] range using MinMaxScaler- Creates sequences of 30 days for LSTM training### 4. LSTM Model Training (Step 4)- **Architecture**: 1 LSTM layer (32 hidden units) + 1 Dense layer- **Training**: 50 epochs, batch size 32- **Optimizer**: Adam (lr=0.001)- **Loss**: Mean Squared Error- **Time**: ~2 minutes on CPU### 5. Price Prediction (Step 5)- Uses trained LSTM to predict next N days- Autoregressive approach: uses previous predictions for future predictions- Inverse transforms predictions back to actual prices### 6. Sentiment Analysis (Step 6)- Fetches latest 10 news articles from Finnhub- Uses VADER sentiment analyzer (rule-based, fast, accurate)- Classifies each article as Positive/Negative/Neutral---## β‘ Performance| Metric | Value ||--------|-------|| **Single Prediction** | 1-2 seconds || **Cached Prediction** | 50-100ms || **Model Training** | 2 minutes || **Memory Usage** | 2-3GB || **Package Size** | 600MB || **Accuracy (MAPE)** | 4.8% || **Directional Accuracy** | 76-77% |### Optimization Techniques- β PyTorch instead of TensorFlow (6x smaller)- β yfinance instead of Alpha Vantage (no API limits)- β Direct LSTM (no XGBoost residuals)- β VADER sentiment (no transformers)- β 24-hour prediction cache- β Gradio native support---## π Model Architecture```Input Sequence (30 days Γ 6 features)βLSTM Layer(32 hidden units)βDense Layer(1 output)βPredicted Price```---## π― Accuracy Analysis### Why 85-86%?Stock predictions face inherent limitations:- **Market efficiency**: ~95% of info already priced in- **Black swan events**: Unpredictable shocks- **Noise**: High-frequency trading noise### MAPE (Mean Absolute Percentage Error)- **Interpretation**: Average prediction error- **Value**: 4.8% (Β±5% of stock price)- **Trade-off**: Acceptable for directional trading### Directional Accuracy- **Definition**: Predicting if price goes UP or DOWN- **Accuracy**: 76-77%- **Better than**: Random guess (50%)---## π¨ Limitations & Disclaimersβ οΈ **This is for educational purposes only. NOT financial advice.**### Limitations1. **Historical data dependent**: Assumes past patterns repeat2. **No fundamental analysis**: Ignores earnings, dividends, etc.3. **No geopolitical events**: Can't predict wars, pandemics4. **Short-term only**: Best for 1-7 day predictions5. **Sentiment limited**: Only recent news, not long-term sentiment### What This Can't Predict- Company earnings surprises- FDA drug approvals- Geopolitical events- Market crashes- Sector rotations### Investment Disclaimer**Past performance β Future results**Always:- β Conduct your own research- β Diversify your portfolio- β Consult a financial advisor- β Manage risk properly- β Never invest what you can't afford to lose---## π Security### API Keys- **Never commit** `.env` file- Use **HF Spaces Secrets** for deployment- API keys are not logged or stored- Data comes from Yahoo Finance (public)### Data Privacy- β No user data stored- β Predictions cached locally (24 hours)- β No ads or tracking- β Open source code---## π Troubleshooting### "ModuleNotFoundError: No module named 'torch'"```bashpip install -r requirements.txt```### "No data for symbol XXXX"1. Check symbol spelling (e.g., `AAPL` not `APPLE`)2. Use international format (e.g., `SBIN.NS` for Indian stocks)3. Check stock is listed on a major exchange### "FINNHUB_API_KEY not set"Sentiment analysis will be skipped, but predictions will still work:1. Get key: https://finnhub.io/register2. Add to `.env` file3. Restart app### "CUDA out of memory"Will automatically fall back to CPU (slower but works)### First prediction is slowThis is expected (model training takes ~2 minutes). Subsequent predictions use cached model (<2 seconds).### "Connection timeout" or "Too many requests"API rate limit reached. Solution:- Wait a few minutes- Cache prevents repeated requests (enabled by default)---## π File Structure```stock-predictor/βββ app.py # Gradio interface (main entry point)βββ model.py # LSTM model and prediction logicβββ requirements.txt # Python dependenciesβββ .env.example # Environment variables templateβββ .gitignore # Git ignore rulesβββ README.md # This fileOptional (generated):βββ .env # Your API keys (NOT committed)βββ lstm_model.pt # Trained model cacheβββ prediction_cache.pkl # Prediction cacheβββ __pycache__/ # Python cache```---## π€ ContributingImprovements welcome! Ideas:- Better sentiment analysis- Multiple models ensemble- Real-time streaming- Mobile app- Explainability (SHAP)---## π LicenseMIT License - Free for personal and commercial use---## π Resources- **Finnhub API**: https://finnhub.io/- **Gradio**: https://gradio.app/- **HF Spaces**: https://huggingface.co/spaces- **PyTorch**: https://pytorch.org/- **yfinance**: https://github.com/ranaroussi/yfinance---## π§ SupportFor issues:1. Check troubleshooting section above2. Verify API key is set3. Check stock symbol is valid4. Check internet connection---**Made with β€οΈ for stock enthusiasts and traders.***Last updated: 2024*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338---title: StockPredictoremoji: πcolorFrom: bluecolorTo: indigosdk: gradiosdk_version: "5.29.0"app_file: app.pypinned: falselicense: mit------title: StockPredictor emoji: π colorFrom: blue colorTo: indigo sdk: gradio sdk_version: "5.29.0" app_file: app.py pinned: false license: mitπ Stock Price PredictorAI-powered stock price predictions using LSTM neural networks, technical analysis, and market sentiment analysis.π Featuresβ‘ Fast predictionsπ§ LSTM Deep Learning modelπ Technical indicators (RSI, MACD, SMA, ROC)π News sentiment analysisπΎ Prediction cachingπ± Gradio web interfaceπ Supports US and Indian stocks---π οΈ Local Setup1. Clone Repositorygit clone https://github.com/your-username/stock-predictor.gitcd stock-predictor2. Create Virtual EnvironmentWindowspython -m venv venvvenv\Scripts\activatemacOS/Linuxpython3 -m venv venvsource venv/bin/activate---3. Install Dependenciespip install -r requirements.txt---4. Add Environment VariablesCreate a .env file:FINNHUB_API_KEY=your_api_key_hereGet a free API key from:https://finnhub.io/register---5. Run Applicationpython app.pyThe application will start at:http://localhost:7860---π Deploy on Hugging Face SpacesStep 1: Create Space1. Open:https://huggingface.co/spaces2. Click:Create New Space3. Configure:SDK: GradioLicense: MITVisibility: Public or Private---Step 2: Upload Project FilesUpload the following files:app.pymodel.pyrequirements.txtREADME.md.env.example.gitignore---Step 3: Add Repository SecretsGo to:Settings β Repository secretsAdd the following secret:Name: FINNHUB_API_KEYValue: your_api_key---Step 4: Automatic DeploymentHugging Face Spaces will automatically:Install dependenciesRun app.pyCreate a public deployment URL---π Supported Stock SymbolsUS StocksAAPLMSFTGOOGLAMZNTSLANVDAMETANFLXIndian StocksSBIN.NSINFY.NSRELIANCE.NSTCS.NSHDFCBANK.NS---π§ Model ArchitectureInput FeaturesβLSTM Layer (32 Units)βDense LayerβPredicted Price---π Technical Indicators UsedRSIMACDSMA20VolatilityROCClosing Price---β‘ PerformanceMetric ValuePrediction Speed 1-2 secondsCached Predictions 50-100msTraining Time ~2 minutesMemory Usage 2-3 GBAccuracy (MAPE) ~4.8%Directional Accuracy 76-77%---β οΈ DisclaimerThis project is for educational purposes only.Not financial adviceMarkets are unpredictableAlways conduct your own researchInvest responsibly---π Security NotesNever upload .envUse HF Spaces Secrets for API keysNo user data storedUses public Yahoo Finance data---π Common IssuesConfiguration Error on HF SpacesUse this exact YAML block at the top of README.md:Important:YAML must start at line 1No spaces before ---app_file is requiredUse supported Gradio versions only---ModuleNotFoundErrorpip install -r requirements.txt---No Data FoundVerify stock symbol format.Example:SBIN.NS---π Project Structurestock-predictor/ββββ app.pyβββ model.pyβββ requirements.txtβββ README.mdβββ .env.exampleβββ .gitignore---π LicenseMIT License---β€οΈ Built WithGradioPyTorchyfinanceFinnhub APIPython
README.md+200-282