Update app.py
Browse files
app.py
CHANGED
@@ -6,22 +6,19 @@ import gradio as gr
|
|
6 |
import matplotlib.pyplot as plt
|
7 |
from sklearn.preprocessing import MinMaxScaler
|
8 |
|
9 |
-
# Function to
|
10 |
def fetch_stock_data(ticker, start_date, end_date):
|
11 |
stock_data = yf.download(ticker, start=start_date, end=end_date)
|
|
|
|
|
12 |
return stock_data
|
13 |
|
14 |
-
#
|
15 |
def prepare_data(data):
|
16 |
-
# Scaling data
|
17 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
18 |
-
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1,1))
|
19 |
|
20 |
-
# Create
|
21 |
-
train_size = int(len(scaled_data) * 0.8)
|
22 |
-
train_data, test_data = scaled_data[:train_size], scaled_data[train_size:]
|
23 |
-
|
24 |
-
# Create sequences for LSTM (last 60 days used to predict the next one)
|
25 |
def create_sequences(data, time_step=60):
|
26 |
X, y = [], []
|
27 |
for i in range(len(data) - time_step - 1):
|
@@ -29,12 +26,16 @@ def prepare_data(data):
|
|
29 |
y.append(data[i + time_step])
|
30 |
return np.array(X), np.array(y)
|
31 |
|
|
|
|
|
|
|
|
|
32 |
X_train, y_train = create_sequences(train_data)
|
33 |
X_test, y_test = create_sequences(test_data)
|
34 |
|
35 |
return X_train, y_train, X_test, y_test, scaler
|
36 |
|
37 |
-
#
|
38 |
def build_lstm_model(input_shape):
|
39 |
model = tf.keras.Sequential([
|
40 |
tf.keras.layers.LSTM(50, return_sequences=True, input_shape=(input_shape[1], 1)),
|
@@ -42,22 +43,21 @@ def build_lstm_model(input_shape):
|
|
42 |
tf.keras.layers.Dense(25),
|
43 |
tf.keras.layers.Dense(1)
|
44 |
])
|
45 |
-
|
46 |
model.compile(optimizer='adam', loss='mean_squared_error')
|
47 |
return model
|
48 |
|
49 |
-
#
|
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 |
-
#
|
56 |
def make_predictions(model, X_test, scaler):
|
57 |
predictions = model.predict(X_test)
|
58 |
return scaler.inverse_transform(predictions)
|
59 |
|
60 |
-
#
|
61 |
def calculate_metrics(data, predictions):
|
62 |
start_value = data['Close'][0]
|
63 |
end_value = predictions[-1][0]
|
@@ -70,61 +70,68 @@ def calculate_metrics(data, predictions):
|
|
70 |
|
71 |
return percentage_change, highest_value, lowest_value, decision
|
72 |
|
73 |
-
#
|
74 |
def plot_graph(data, predictions, ticker):
|
75 |
-
plt.figure(figsize=(12,6))
|
76 |
-
plt.plot(data.index, data['Close'], label="Historical")
|
77 |
-
plt.plot(data.index[len(data) - len(predictions):], predictions, label="Predicted")
|
78 |
plt.title(f'{ticker} Stock Price Prediction')
|
79 |
plt.xlabel('Date')
|
80 |
-
plt.ylabel('Price')
|
81 |
plt.legend()
|
82 |
plt.grid(True)
|
83 |
plt.show()
|
84 |
|
85 |
-
# Gradio
|
86 |
def stock_predictor(ticker, start_date, end_date):
|
87 |
stock_data = fetch_stock_data(ticker, start_date, end_date)
|
88 |
-
|
89 |
-
if len(stock_data) == 0:
|
90 |
return "Error: No data found. Please select a valid date range."
|
91 |
-
|
|
|
92 |
X_train, y_train, X_test, y_test, scaler = prepare_data(stock_data)
|
93 |
-
|
|
|
94 |
model = train_model(X_train, y_train)
|
95 |
-
|
|
|
96 |
predictions = make_predictions(model, X_test, scaler)
|
97 |
-
|
|
|
98 |
percentage_change, highest_value, lowest_value, decision = calculate_metrics(stock_data, predictions)
|
99 |
-
|
|
|
100 |
plot_graph(stock_data, predictions, ticker)
|
101 |
-
|
|
|
102 |
return {
|
103 |
-
"Percentage Change": percentage_change,
|
104 |
-
"Highest Value": highest_value,
|
105 |
-
"Lowest Value": lowest_value,
|
106 |
"Prediction (Buy/Sell)": decision
|
107 |
}
|
108 |
|
109 |
-
#
|
110 |
tickers = ['AAPL', 'GOOGL', 'AMZN', 'MSFT', 'TSLA', 'NFLX', 'NVDA', 'META', 'BABA', 'INTC']
|
111 |
|
112 |
-
# Gradio interface
|
113 |
gr_interface = gr.Interface(
|
114 |
fn=stock_predictor,
|
115 |
inputs=[
|
116 |
gr.Dropdown(choices=tickers, label="Select Stock Ticker"),
|
117 |
-
gr.Date(label="Start Date"),
|
118 |
-
gr.Date(label="End Date")
|
119 |
],
|
120 |
outputs=[
|
121 |
gr.Label(label="Percentage Change"),
|
122 |
gr.Label(label="Highest Value"),
|
123 |
gr.Label(label="Lowest Value"),
|
124 |
gr.Label(label="Prediction (Buy/Sell)"),
|
125 |
-
gr.Plot(label="Stock Performance")
|
126 |
],
|
127 |
-
title="Stock Prediction App"
|
|
|
128 |
)
|
129 |
|
|
|
130 |
gr_interface.launch()
|
|
|
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):
|
|
|
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)),
|
|
|
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]
|
|
|
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()
|