""" Stock Price Prediction - Gradio App for HuggingFace Spaces This is the main entry point that will be automatically executed """ import gradio as gr import pandas as pd import numpy as np from model import predict_stock, get_supported_symbols from datetime import datetime import json # Custom CSS for better styling custom_css = """ .container { max-width: 1200px; margin: 0 auto; } .prediction-table { font-size: 14px; } .positive { color: #10b981; font-weight: bold; } .negative { color: #ef4444; font-weight: bold; } .neutral { color: #6b7280; } """ def format_prediction_result(result): """Format prediction result for display""" if not result or 'predictions' not in result: return None, "❌ No prediction data available" # Create predictions dataframe pred_data = [] for pred in result['predictions']: pred_data.append({ 'Date': pred['date'], 'Predicted Price': f"${pred['price']:.2f}", 'Change %': f"{pred['change_pct']:+.2f}%", 'Day': f"Day {pred['day']}" }) pred_df = pd.DataFrame(pred_data) # Create detailed analysis text symbol = result['symbol'] last_price = result['last_price'] last_date = result['last_date'] # Get first and last predictions first_pred = result['predictions'][0]['price'] last_pred = result['predictions'][-1]['price'] # Calculate overall trend overall_change = ((last_pred - last_price) / last_price) * 100 trend = "📈 Uptrend" if overall_change > 0 else "📉 Downtrend" if overall_change < 0 else "➡️ Neutral" # Sentiment analysis sentiment = result['sentiment'] sentiment_score = result['sentiment_score'] sentiment_text = "Positive 📈" if sentiment_score > 0.2 else "Negative 📉" if sentiment_score < -0.2 else "Neutral ➡️" # Build summary summary = f""" ### 📈 Stock Price Prediction for {symbol} **Current Status:** - Current Price: **${last_price:.2f}** - Last Updated: **{last_date}** - Prediction Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')} **Price Trend:** - Overall Trend: **{trend}** - Expected Change: **{overall_change:+.2f}%** - Price Range: ${min(first_pred, last_pred):.2f} - ${max(first_pred, last_pred):.2f}** **Market Sentiment:** - Sentiment: **{sentiment_text}** - Sentiment Score: **{sentiment_score:.2f}** - Articles Analyzed: - 📈 Positive: {sentiment['positive']} - 📉 Negative: {sentiment['negative']} - ➡️ Neutral: {sentiment['neutral']} **Model Information:** - Algorithm: LSTM (Long Short-Term Memory) Neural Network - Features: Close Price, RSI, MACD, Volatility, SMA20, ROC - Training Period: Last 100 days - Look-back Period: 30 days --- **⚠️ Disclaimer:** These predictions are based on historical price patterns and current market sentiment. Stock markets are unpredictable, and past performance does not guarantee future results. Always conduct your own research and consult with a financial advisor before making investment decisions. """ return pred_df, summary def predict_stock_interface(symbol, days_ahead): """Main prediction interface function""" try: # Validate inputs symbol = symbol.upper().strip() days_ahead = int(days_ahead) if not symbol: return None, "❌ Please enter a stock symbol" if days_ahead < 1 or days_ahead > 30: return None, "❌ Days ahead must be between 1 and 30" # Run prediction print(f"\n{'='*60}") print(f"Predicting {symbol} for {days_ahead} days ahead") print(f"{'='*60}") result = predict_stock(symbol, days_ahead, use_cache=True) # Format and return results pred_df, summary = format_prediction_result(result) return pred_df, summary except Exception as e: error_msg = f"❌ Error: {str(e)}" print(f"Error occurred: {error_msg}") return None, error_msg def clear_cache(): """Clear prediction cache""" from model import cache try: cache.cache = {} cache.save_cache() return "✅ Cache cleared successfully!" except Exception as e: return f"❌ Error clearing cache: {str(e)}" # Create Gradio interface with gr.Blocks(title="Stock Price Predictor", css=custom_css) as demo: # Header gr.HTML("""
AI-powered stock price predictions using LSTM neural networks and technical analysis
⚠️ For educational purposes only. Not financial advice.