Mani9045 commited on
Commit
668b3f5
·
verified ·
1 Parent(s): 189f9c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -76
app.py CHANGED
@@ -1,91 +1,89 @@
1
- # Import necessary libraries
2
  import gradio as gr
3
- import yfinance as yf
4
  import pandas as pd
5
- import matplotlib.pyplot as plt
6
- from neuralprophet import NeuralProphet
7
- from datetime import datetime
 
8
 
9
- # Function to fetch historical stock data
10
  def get_stock_data(ticker, start_date, end_date):
11
  stock_data = yf.download(ticker, start=start_date, end=end_date)
12
- stock_data.reset_index(inplace=True) # Reset index to use dates properly
13
  return stock_data
14
 
15
- # Function to preprocess data for NeuralProphet model
16
- def prepare_data_for_neuralprophet(stock_data):
17
  df = stock_data[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'})
18
  return df
19
 
20
- # Function to train NeuralProphet model and make predictions
21
- def predict_stock(stock_data, period):
22
- df = prepare_data_for_neuralprophet(stock_data)
23
- model = NeuralProphet() # Initialize NeuralProphet model
24
- model.fit(df) # Fit the model with the historical stock data
25
-
26
- # Make future predictions
27
- future = model.make_future_dataframe(df, periods=period) # Create a future dataframe for predictions
28
- forecast = model.predict(future) # Predict future stock prices
29
- return forecast[['ds', 'yhat1']]
30
-
31
- # Function to get buy/sell recommendation based on percentage change
32
- def get_recommendation(stock_data):
33
- change_percent = ((stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0]) * 100
34
- if change_percent > 0:
35
- return "Buy"
36
- else:
37
- return "Sell"
38
-
39
- # Function to plot stock data
40
- def plot_stock(stock_data, forecast):
41
- plt.figure(figsize=(10, 5))
42
- plt.plot(stock_data['Date'], stock_data['Close'], label='Historical Closing Price')
43
- plt.plot(forecast['ds'], forecast['yhat1'], label='Predicted Closing Price')
44
- plt.xlabel("Date")
45
- plt.ylabel("Stock Price")
46
- plt.title("Stock Price Prediction")
47
- plt.legend()
48
- plt.grid(True)
49
- plt.savefig("stock_prediction_plot.png") # Save the plot as an image
50
- plt.close()
51
- return "stock_prediction_plot.png"
52
-
53
- # Main function to handle user inputs and return results
54
- def stock_prediction_app(ticker, start_date, end_date, prediction_period):
55
- stock_data = get_stock_data(ticker, start_date, end_date) # Fetch historical stock data
56
- forecast = predict_stock(stock_data, prediction_period) # Predict future prices
57
- recommendation = get_recommendation(stock_data) # Get buy/sell recommendation
58
- plot_file = plot_stock(stock_data, forecast) # Plot stock data and predictions
59
 
60
- # Get the highest and lowest closing prices in the historical data
61
- high = stock_data['Close'].max()
62
- low = stock_data['Close'].min()
63
- percentage_change = ((stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0]) * 100
 
 
64
 
65
- return high, low, percentage_change, recommendation, plot_file
 
 
 
 
66
 
67
- # Define the stock tickers for the dropdown
68
- tickers = ['AAPL', 'GOOGL', 'AMZN', 'MSFT', 'TSLA', 'NFLX', 'NVDA', 'INTC', 'AMD', 'FB']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- # Create the Gradio interface using the latest Gradio API
71
- app = gr.Interface(
72
- fn=stock_prediction_app,
73
- inputs=[
74
- gr.Dropdown(choices=tickers, label="Stock Ticker"),
75
- gr.Textbox(label="Start Date (YYYY-MM-DD)"),
76
- gr.Textbox(label="End Date (YYYY-MM-DD)"),
77
- gr.Slider(1, 365, label="Prediction Period (Days)")
78
- ],
79
- outputs=[
80
- gr.Textbox(label="Highest Value"),
81
- gr.Textbox(label="Lowest Value"),
82
- gr.Textbox(label="Percentage Change"),
83
- gr.Textbox(label="Buy/Sell Recommendation"),
84
- gr.Image(type="filepath", label="Stock Performance and Prediction Graph")
85
- ],
86
- title="AI-Powered Stock Prediction App",
87
- description="Predict future stock prices, calculate highest and lowest prices, percentage change, and get a buy/sell recommendation based on historical data."
88
- )
 
 
 
 
 
 
 
 
89
 
90
- # Launch the Gradio app
91
- app.launch()
 
 
1
  import gradio as gr
 
2
  import pandas as pd
3
+ import numpy as np
4
+ from prophet import Prophet # Using updated Prophet library
5
+ import yfinance as yf # Ensure yfinance is installed
6
+ import datetime
7
 
8
+ # Function to fetch stock data
9
  def get_stock_data(ticker, start_date, end_date):
10
  stock_data = yf.download(ticker, start=start_date, end=end_date)
11
+ stock_data.reset_index(inplace=True)
12
  return stock_data
13
 
14
+ # Function to prepare data for Prophet model
15
+ def prepare_data(stock_data):
16
  df = stock_data[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'})
17
  return df
18
 
19
+ # Function to make predictions using Prophet
20
+ def make_predictions(df, periods=90):
21
+ model = Prophet()
22
+ model.fit(df)
23
+ future = model.make_future_dataframe(periods=periods)
24
+ forecast = model.predict(future)
25
+ return forecast
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ # Function to calculate percentage change
28
+ def calculate_percentage_change(stock_data):
29
+ start_value = stock_data['Close'].iloc[0]
30
+ end_value = stock_data['Close'].iloc[-1]
31
+ percentage_change = ((end_value - start_value) / start_value) * 100
32
+ return percentage_change
33
 
34
+ # Function to get stock statistics (high/low)
35
+ def get_stock_stats(stock_data):
36
+ high_value = stock_data['Close'].max()
37
+ low_value = stock_data['Close'].min()
38
+ return high_value, low_value
39
 
40
+ # Main function for UI
41
+ def stock_prediction(ticker, start_date, end_date):
42
+ stock_data = get_stock_data(ticker, start_date, end_date)
43
+
44
+ # Get statistics
45
+ percentage_change = calculate_percentage_change(stock_data)
46
+ high_value, low_value = get_stock_stats(stock_data)
47
+
48
+ # Prepare data for prediction
49
+ df = prepare_data(stock_data)
50
+ forecast = make_predictions(df)
51
+
52
+ # Generate buy/sell suggestion (simple rule-based)
53
+ suggestion = "Buy" if percentage_change < 0 else "Sell"
54
+
55
+ # Historical stock performance and predicted future trend
56
+ historical_chart = stock_data[['Date', 'Close']]
57
+ predicted_chart = forecast[['ds', 'yhat']]
58
+
59
+ return historical_chart, predicted_chart, percentage_change, high_value, low_value, suggestion
60
 
61
+ # UI setup
62
+ with gr.Blocks() as app:
63
+ gr.Markdown("# Stock Prediction App")
64
+
65
+ stock_ticker = gr.Dropdown(
66
+ label="Select Stock Ticker",
67
+ choices=["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA", "NFLX", "FB", "NVDA", "IBM", "ORCL"]
68
+ )
69
+
70
+ start_date = gr.DatePicker(label="Start Date", value=datetime.date(2023, 1, 1))
71
+ end_date = gr.DatePicker(label="End Date", value=datetime.date.today())
72
+
73
+ historical_chart_output = gr.LinePlot(label="Historical Stock Performance")
74
+ predicted_chart_output = gr.LinePlot(label="Predicted Future Stock Performance")
75
+ percentage_change_output = gr.Textbox(label="Percentage Change")
76
+ high_value_output = gr.Textbox(label="Highest Stock Value")
77
+ low_value_output = gr.Textbox(label="Lowest Stock Value")
78
+ suggestion_output = gr.Textbox(label="Buy/Sell Suggestion")
79
+
80
+ # Button to make predictions
81
+ predict_button = gr.Button("Predict")
82
+
83
+ predict_button.click(
84
+ stock_prediction,
85
+ inputs=[stock_ticker, start_date, end_date],
86
+ outputs=[historical_chart_output, predicted_chart_output, percentage_change_output, high_value_output, low_value_output, suggestion_output]
87
+ )
88
 
89
+ app.launch()