Abhisesh7 commited on
Commit
9e7913b
·
verified ·
1 Parent(s): 2d9c259

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -128
app.py CHANGED
@@ -1,137 +1,80 @@
 
1
  import yfinance as yf
2
- import pandas as pd
3
  import numpy as np
4
- import tensorflow as tf
5
- import gradio as gr
6
  import matplotlib.pyplot as plt
7
- from sklearn.preprocessing import MinMaxScaler
8
 
9
- # Function to fetch stock data from Yahoo Finance
10
- def fetch_stock_data(ticker, start_date, end_date):
11
  stock_data = yf.download(ticker, start=start_date, end=end_date)
12
- if stock_data.empty:
13
- return None
14
  return stock_data
15
 
16
- # Function to prepare the data for LSTM
17
- def prepare_data(data):
18
- scaler = MinMaxScaler(feature_range=(0, 1))
19
- scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
20
-
21
- # Create sequences for LSTM
22
- def create_sequences(data, time_step=60):
23
- X, y = [], []
24
- for i in range(len(data) - time_step - 1):
25
- X.append(data[i:i + time_step])
26
- y.append(data[i + time_step])
27
- return np.array(X), np.array(y)
28
-
29
- # Train-test split (80% train, 20% test)
30
- train_size = int(len(scaled_data) * 0.8)
31
- train_data, test_data = scaled_data[:train_size], scaled_data[train_size:]
32
-
33
- X_train, y_train = create_sequences(train_data)
34
- X_test, y_test = create_sequences(test_data)
35
-
36
- return X_train, y_train, X_test, y_test, scaler
37
-
38
- # Function to build LSTM model
39
- def build_lstm_model(input_shape):
40
- model = tf.keras.Sequential([
41
- tf.keras.layers.LSTM(50, return_sequences=True, input_shape=(input_shape[1], 1)),
42
- tf.keras.layers.LSTM(50, return_sequences=False),
43
- tf.keras.layers.Dense(25),
44
- tf.keras.layers.Dense(1)
45
- ])
46
- model.compile(optimizer='adam', loss='mean_squared_error')
47
- return model
48
-
49
- # Function to train the LSTM model
50
- def train_model(X_train, y_train):
51
- model = build_lstm_model(X_train.shape)
52
- model.fit(X_train, y_train, batch_size=1, epochs=1)
53
- return model
54
-
55
- # Function to make predictions using the trained model
56
- def make_predictions(model, X_test, scaler):
57
- predictions = model.predict(X_test)
58
- return scaler.inverse_transform(predictions)
59
-
60
- # Function to calculate the metrics (percentage change, highest, lowest, buy/sell)
61
- def calculate_metrics(data, predictions):
62
- start_value = data['Close'][0]
63
- end_value = predictions[-1][0]
64
- percentage_change = ((end_value - start_value) / start_value) * 100
65
-
66
- highest_value = data['Close'].max()
67
- lowest_value = data['Close'].min()
68
-
69
- decision = "Buy" if end_value > start_value else "Sell"
70
-
71
- return percentage_change, highest_value, lowest_value, decision
72
-
73
- # Function to plot the graph of historical vs predicted data
74
- def plot_graph(data, predictions, ticker):
75
- plt.figure(figsize=(12, 6))
76
- plt.plot(data.index, data['Close'], label="Historical Prices", color='blue')
77
- plt.plot(data.index[len(data) - len(predictions):], predictions, label="Predicted Prices", color='red')
78
- plt.title(f'{ticker} Stock Price Prediction')
79
- plt.xlabel('Date')
80
- plt.ylabel('Price (USD)')
81
  plt.legend()
82
  plt.grid(True)
83
- plt.show()
84
-
85
- # Gradio interface function
86
- def stock_predictor(ticker, start_date, end_date):
87
- stock_data = fetch_stock_data(ticker, start_date, end_date)
88
-
89
- if stock_data is None or len(stock_data) == 0:
90
- return "Error: No data found. Please select a valid date range."
91
-
92
- # Prepare data for LSTM
93
- X_train, y_train, X_test, y_test, scaler = prepare_data(stock_data)
94
-
95
- # Train the model
96
- model = train_model(X_train, y_train)
97
-
98
- # Make predictions
99
- predictions = make_predictions(model, X_test, scaler)
100
-
101
- # Calculate buy/sell decision and metrics
102
- percentage_change, highest_value, lowest_value, decision = calculate_metrics(stock_data, predictions)
103
-
104
- # Plot the historical vs predicted data
105
- plot_graph(stock_data, predictions, ticker)
106
-
107
- # Return the calculated metrics
108
- return {
109
- "Percentage Change": f"{percentage_change:.2f}%",
110
- "Highest Value": f"${highest_value:.2f}",
111
- "Lowest Value": f"${lowest_value:.2f}",
112
- "Prediction (Buy/Sell)": decision
113
- }
114
-
115
- # List of stock tickers for the dropdown
116
- tickers = ['AAPL', 'GOOGL', 'AMZN', 'MSFT', 'TSLA', 'NFLX', 'NVDA', 'META', 'BABA', 'INTC']
117
-
118
- # Gradio interface design
119
- gr_interface = gr.Interface(
120
- fn=stock_predictor,
121
- inputs=[
122
- gr.Dropdown(choices=tickers, label="Select Stock Ticker"),
123
- gr.inputs.Date(label="Start Date"),
124
- gr.inputs.Date(label="End Date")
125
- ],
126
- outputs=[
127
- gr.Label(label="Percentage Change"),
128
- gr.Label(label="Highest Value"),
129
- gr.Label(label="Lowest Value"),
130
- gr.Label(label="Prediction (Buy/Sell)"),
131
- ],
132
- title="Stock Prediction App",
133
- description="This app predicts stock prices and helps users decide whether to buy or sell."
134
- )
135
-
136
- # Launch the Gradio interface
137
- gr_interface.launch()
 
1
+ import gradio as gr
2
  import yfinance as yf
 
3
  import numpy as np
4
+ import pandas as pd
 
5
  import matplotlib.pyplot as plt
6
+ from sklearn.linear_model import LinearRegression
7
 
8
+ # Function to fetch data
9
+ def fetch_data(ticker, start_date, end_date):
10
  stock_data = yf.download(ticker, start=start_date, end=end_date)
 
 
11
  return stock_data
12
 
13
+ # Function to predict future prices
14
+ def predict_stock(ticker, start_date, end_date):
15
+ stock_data = fetch_data(ticker, start_date, end_date)
16
+
17
+ stock_data['Date'] = pd.to_datetime(stock_data.index)
18
+ stock_data['Days'] = (stock_data['Date'] - stock_data['Date'].min()).dt.days
19
+
20
+ X = stock_data['Days'].values.reshape(-1, 1)
21
+ y = stock_data['Close'].values
22
+
23
+ model = LinearRegression()
24
+ model.fit(X, y)
25
+
26
+ future_days = np.array(range(stock_data['Days'].max() + 1, stock_data['Days'].max() + 90)).reshape(-1, 1)
27
+ future_prices = model.predict(future_days)
28
+
29
+ return future_prices, stock_data
30
+
31
+ # Function to visualize stock data
32
+ def plot_stock_data(ticker, start_date, end_date):
33
+ future_prices, stock_data = predict_stock(ticker, start_date, end_date)
34
+
35
+ plt.figure(figsize=(10, 6))
36
+ plt.plot(stock_data['Date'], stock_data['Close'], label="Historical Prices")
37
+ future_dates = pd.date_range(stock_data['Date'].max() + pd.Timedelta(days=1), periods=90)
38
+ plt.plot(future_dates, future_prices, label="Predicted Future Prices")
39
+
40
+ plt.title(f"{ticker} Stock Price Prediction")
41
+ plt.xlabel("Date")
42
+ plt.ylabel("Price")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  plt.legend()
44
  plt.grid(True)
45
+
46
+ return plt.gcf()
47
+
48
+ # Gradio Interface
49
+ def stock_prediction_interface(ticker, start_date, end_date):
50
+ stock_data = fetch_data(ticker, start_date, end_date)
51
+ price_change = (stock_data['Close'].iloc[-1] - stock_data['Close'].iloc[0]) / stock_data['Close'].iloc[0] * 100
52
+ highest_price = stock_data['High'].max()
53
+ lowest_price = stock_data['Low'].min()
54
+
55
+ future_prices, _ = predict_stock(ticker, start_date, end_date)
56
+ decision = "Buy" if future_prices[-1] > stock_data['Close'].iloc[-1] else "Sell"
57
+
58
+ graph = plot_stock_data(ticker, start_date, end_date)
59
+
60
+ return f"Percentage Change: {price_change:.2f}%\nHighest Price: {highest_price}\nLowest Price: {lowest_price}\nDecision: {decision}", graph
61
+
62
+ # Gradio app UI
63
+ ticker_list = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA', 'META', 'NFLX', 'NVDA', 'BABA', 'INTC']
64
+
65
+ # Update to use gr.components instead of gr.inputs
66
+ with gr.Blocks() as demo:
67
+ ticker_input = gr.components.Dropdown(choices=ticker_list, label="Stock Ticker")
68
+ start_date_input = gr.components.Date(label="Start Date")
69
+ end_date_input = gr.components.Date(label="End Date")
70
+
71
+ output_text = gr.components.Textbox(label="Prediction Results")
72
+ output_plot = gr.components.Plot(label="Stock Price Plot")
73
+
74
+ gr.components.Button("Predict").click(
75
+ stock_prediction_interface,
76
+ inputs=[ticker_input, start_date_input, end_date_input],
77
+ outputs=[output_text, output_plot]
78
+ )
79
+
80
+ demo.launch()