# Import necessary libraries import gradio as gr import yfinance as yf import pandas as pd import matplotlib.pyplot as plt from neuralprophet import NeuralProphet from datetime import datetime # Function to fetch historical stock data def get_stock_data(ticker, start_date, end_date): stock_data = yf.download(ticker, start=start_date, end=end_date) stock_data.reset_index(inplace=True) # Reset index to use dates properly return stock_data # Function to preprocess data for NeuralProphet model def prepare_data_for_neuralprophet(stock_data): df = stock_data[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'}) return df # Function to train NeuralProphet model and make predictions def predict_stock(stock_data, period): df = prepare_data_for_neuralprophet(stock_data) model = NeuralProphet() # Initialize NeuralProphet model model.fit(df) # Fit the model with the historical stock data # Make future predictions future = model.make_future_dataframe(df, periods=period) # Create a future dataframe for predictions forecast = model.predict(future) # Predict future stock prices return forecast[['ds', 'yhat1']] # Function to get buy/sell recommendation based on percentage change def get_recommendation(stock_data): change_percent = ((stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0]) * 100 if change_percent > 0: return "Buy" else: return "Sell" # Function to plot stock data def plot_stock(stock_data, forecast): plt.figure(figsize=(10, 5)) plt.plot(stock_data['Date'], stock_data['Close'], label='Historical Closing Price') plt.plot(forecast['ds'], forecast['yhat1'], label='Predicted Closing Price') plt.xlabel("Date") plt.ylabel("Stock Price") plt.title("Stock Price Prediction") plt.legend() plt.grid(True) plt.savefig("stock_prediction_plot.png") # Save the plot as an image plt.close() return "stock_prediction_plot.png" # Main function to handle user inputs and return results def stock_prediction_app(ticker, start_date, end_date, prediction_period): stock_data = get_stock_data(ticker, start_date, end_date) # Fetch historical stock data forecast = predict_stock(stock_data, prediction_period) # Predict future prices recommendation = get_recommendation(stock_data) # Get buy/sell recommendation plot_file = plot_stock(stock_data, forecast) # Plot stock data and predictions # Get the highest and lowest closing prices in the historical data high = stock_data['Close'].max() low = stock_data['Close'].min() percentage_change = ((stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0]) * 100 return high, low, percentage_change, recommendation, plot_file # Define the stock tickers for the dropdown tickers = ['AAPL', 'GOOGL', 'AMZN', 'MSFT', 'TSLA', 'NFLX', 'NVDA', 'INTC', 'AMD', 'FB'] # Create the Gradio interface using the latest Gradio API app = gr.Interface( fn=stock_prediction_app, inputs=[ gr.Dropdown(choices=tickers, label="Stock Ticker"), gr.Textbox(label="Start Date (YYYY-MM-DD)"), gr.Textbox(label="End Date (YYYY-MM-DD)"), gr.Slider(1, 365, label="Prediction Period (Days)") ], outputs=[ gr.Textbox(label="Highest Value"), gr.Textbox(label="Lowest Value"), gr.Textbox(label="Percentage Change"), gr.Textbox(label="Buy/Sell Recommendation"), gr.Image(type="filepath", label="Stock Performance and Prediction Graph") ], title="AI-Powered Stock Prediction App", description="Predict future stock prices, calculate highest and lowest prices, percentage change, and get a buy/sell recommendation based on historical data." ) # Launch the Gradio app app.launch()