Spaces:
Runtime error
Runtime error
| import yfinance as yf | |
| import gradio as gr | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.ensemble import RandomForestRegressor | |
| import matplotlib.pyplot as plt | |
| # Function to fetch stock data from Yahoo Finance | |
| def get_stock_data(ticker, start, end): | |
| try: | |
| stock = yf.Ticker(ticker) | |
| data = stock.history(start=start, end=end) | |
| if data.empty: | |
| return None, "Error: No data found for the selected date range." | |
| return data, None | |
| except Exception as e: | |
| return None, f"Error fetching stock data: {str(e)}" | |
| # Function to train the model | |
| def train_model(data): | |
| data['Returns'] = data['Close'].pct_change().dropna() # Calculate percentage change in close prices | |
| # Prepare data for training | |
| X = np.arange(len(data)).reshape(-1, 1) # Use time index as a feature | |
| y = data['Close'].values | |
| model = RandomForestRegressor(n_estimators=100, random_state=42) | |
| model.fit(X, y) | |
| return model | |
| # Function to predict future stock prices | |
| def predict_future(model, data, future_days=90): | |
| future_X = np.arange(len(data), len(data) + future_days).reshape(-1, 1) | |
| future_predictions = model.predict(future_X) | |
| return future_predictions | |
| # Function to generate a plot for stock prices | |
| def generate_graph(data, future_predictions): | |
| plt.figure(figsize=(10,5)) | |
| plt.plot(data['Close'], label='Historical Prices', color='blue') | |
| plt.plot(np.arange(len(data), len(data) + len(future_predictions)), | |
| future_predictions, label='Predicted Prices', linestyle='--', color='red') | |
| plt.xlabel('Days') | |
| plt.ylabel('Stock Price') | |
| plt.title('Stock Price Prediction') | |
| plt.legend() | |
| plt.grid(True) | |
| plt.tight_layout() | |
| plt.savefig('stock_prediction.png') # Save plot for display in the app | |
| # Main function to be used with Gradio | |
| def stock_prediction_app(ticker, start_date, end_date): | |
| data, error = get_stock_data(ticker, start=start_date, end=end_date) | |
| if error: | |
| return error, None, None, None, None, None | |
| model = train_model(data) | |
| future_predictions = predict_future(model, data) | |
| # Generate graph | |
| generate_graph(data, future_predictions) | |
| # Calculate key metrics | |
| highest_value = data['Close'].max() | |
| lowest_value = data['Close'].min() | |
| percent_change = ((data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]) * 100 | |
| recommendation = "Buy" if future_predictions[-1] > data['Close'].iloc[-1] else "Sell" | |
| return highest_value, lowest_value, percent_change, recommendation, 'stock_prediction.png' | |
| # List of stock tickers for dropdown menu | |
| stock_tickers = ['AAPL', 'GOOGL', 'AMZN', 'MSFT', 'TSLA', 'NFLX', 'META', 'NVDA', 'JPM', 'DIS'] | |
| # Gradio Interface | |
| interface = gr.Interface( | |
| fn=stock_prediction_app, | |
| inputs=[ | |
| gr.Dropdown(choices=stock_tickers, label="Stock Ticker"), | |
| gr.components.Date(label="Start Date"), | |
| gr.components.Date(label="End Date") | |
| ], | |
| outputs=[ | |
| gr.Textbox(label="Highest Stock Price"), | |
| gr.Textbox(label="Lowest Stock Price"), | |
| gr.Textbox(label="Percentage Change"), | |
| gr.Textbox(label="Buy or Sell Recommendation"), | |
| gr.Image(label="Stock Price Prediction Graph") | |
| ], | |
| title="Stock Prediction App" | |
| ) | |
| interface.launch(share=True) | |