File size: 3,853 Bytes
bfaa7c5
 
5fd0b8c
 
 
bfaa7c5
ca8eb38
 
bfaa7c5
ca8eb38
bfaa7c5
 
 
ca8eb38
bfaa7c5
 
 
 
 
 
 
 
 
 
ca8eb38
bfaa7c5
 
 
 
5fd0b8c
bfaa7c5
 
 
 
 
 
 
5fd0b8c
bfaa7c5
 
 
 
 
 
 
 
 
 
 
 
 
ca8eb38
bfaa7c5
 
 
 
 
 
ca8eb38
bfaa7c5
 
 
 
ca8eb38
bfaa7c5
5fd0b8c
bfaa7c5
 
5fd0b8c
bfaa7c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca8eb38
bfaa7c5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# 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()