Update app.py
Browse files
app.py
CHANGED
@@ -1,111 +1,90 @@
|
|
1 |
import numpy as np
|
2 |
import pandas as pd
|
3 |
import yfinance as yf
|
4 |
-
|
5 |
-
from tensorflow
|
6 |
-
from tensorflow.keras
|
7 |
import gradio as gr
|
8 |
import matplotlib.pyplot as plt
|
9 |
-
from
|
|
|
10 |
|
11 |
-
#
|
12 |
def fetch_data(ticker, start_date, end_date):
|
13 |
data = yf.download(ticker, start=start_date, end=end_date)
|
|
|
14 |
return data
|
15 |
|
16 |
-
#
|
17 |
-
def
|
18 |
-
|
19 |
-
data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
21 |
scaled_data = scaler.fit_transform(data)
|
22 |
|
23 |
-
#
|
24 |
-
|
25 |
-
|
26 |
-
x_train.append(scaled_data[i-60:i, 0])
|
27 |
-
y_train.append(scaled_data[i, 0])
|
28 |
-
x_train, y_train = np.array(x_train), np.array(y_train)
|
29 |
|
30 |
-
#
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
|
35 |
-
# Build the LSTM model
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
model.add(Dropout(0.2))
|
42 |
-
model.add(Dense(units=25))
|
43 |
-
model.add(Dense(units=1)) # Output layer for price prediction
|
44 |
-
model.compile(optimizer='adam', loss='mean_squared_error')
|
45 |
-
return model
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
data = fetch_data(ticker, start_date, end_date)
|
50 |
-
x_train, y_train, scaler = preprocess_data(data)
|
51 |
-
|
52 |
-
model = build_model()
|
53 |
-
model.fit(x_train, y_train, batch_size=1, epochs=1)
|
54 |
-
|
55 |
-
return model, scaler, data
|
56 |
|
57 |
-
|
58 |
-
def predict_next_day(model, scaler, data):
|
59 |
-
last_60_days = data['Close'][-60:].values
|
60 |
-
last_60_days_scaled = scaler.transform(last_60_days.reshape(-1, 1))
|
61 |
-
|
62 |
-
x_test = []
|
63 |
-
x_test.append(last_60_days_scaled)
|
64 |
-
x_test = np.array(x_test)
|
65 |
-
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
tomorrow = datetime.now() + timedelta(days=1)
|
76 |
-
plt.scatter(tomorrow, predicted_price, label='Predicted Price for Tomorrow', color='red')
|
77 |
-
plt.title('Stock Price Prediction')
|
78 |
-
plt.xlabel('Date')
|
79 |
-
plt.ylabel('Price')
|
80 |
-
plt.legend()
|
81 |
-
plt.grid()
|
82 |
-
plt.xticks(rotation=45)
|
83 |
-
plt.tight_layout()
|
84 |
-
plt.savefig('/mnt/data/stock_prediction_graph.png') # Save the graph
|
85 |
-
plt.close()
|
86 |
|
87 |
-
|
88 |
-
|
89 |
-
model, scaler, data = train_model(ticker, start_date, end_date)
|
90 |
-
predicted_price = predict_next_day(model, scaler, data)
|
91 |
-
create_graph(data, predicted_price)
|
92 |
-
|
93 |
-
return f'The predicted stock price for tomorrow is ${predicted_price:.2f}', '/mnt/data/stock_prediction_graph.png'
|
94 |
|
95 |
-
|
96 |
-
stock_tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'FB', 'TSLA', 'NFLX', 'NVDA', 'INTC', 'AMD']
|
97 |
|
98 |
-
#
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
title="Stock Price Prediction App",
|
108 |
-
description="Predict tomorrow's stock price based on historical data.",
|
109 |
)
|
|
|
|
|
110 |
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import numpy as np
|
2 |
import pandas as pd
|
3 |
import yfinance as yf
|
4 |
+
import tensorflow as tf
|
5 |
+
from tensorflow import keras
|
6 |
+
from tensorflow.keras import layers
|
7 |
import gradio as gr
|
8 |
import matplotlib.pyplot as plt
|
9 |
+
from sklearn.preprocessing import MinMaxScaler
|
10 |
+
import datetime
|
11 |
|
12 |
+
# Function to fetch and preprocess data
|
13 |
def fetch_data(ticker, start_date, end_date):
|
14 |
data = yf.download(ticker, start=start_date, end=end_date)
|
15 |
+
data = data[['Close']]
|
16 |
return data
|
17 |
|
18 |
+
# Function to create datasets for training
|
19 |
+
def create_dataset(data, time_step=1):
|
20 |
+
X, y = [], []
|
21 |
+
for i in range(len(data) - time_step - 1):
|
22 |
+
a = data[i:(i + time_step), 0]
|
23 |
+
X.append(a)
|
24 |
+
y.append(data[i + time_step, 0])
|
25 |
+
return np.array(X), np.array(y)
|
26 |
+
|
27 |
+
# Function to build and train the LSTM model
|
28 |
+
def train_model(data, time_step=10):
|
29 |
+
# Scale the data
|
30 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
31 |
scaled_data = scaler.fit_transform(data)
|
32 |
|
33 |
+
# Create datasets
|
34 |
+
X, y = create_dataset(scaled_data, time_step)
|
35 |
+
X = X.reshape(X.shape[0], X.shape[1], 1) # Reshape for LSTM input
|
|
|
|
|
|
|
36 |
|
37 |
+
# Split the data into training and testing sets
|
38 |
+
split = int(len(X) * 0.8)
|
39 |
+
X_train, X_test = X[:split], X[split:]
|
40 |
+
y_train, y_test = y[:split], y[split:]
|
41 |
|
42 |
+
# Build the LSTM model
|
43 |
+
model = keras.Sequential([
|
44 |
+
layers.LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
|
45 |
+
layers.LSTM(50, return_sequences=False),
|
46 |
+
layers.Dense(1)
|
47 |
+
])
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
50 |
+
model.fit(X_train, y_train, epochs=50, batch_size=32, verbose=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
+
return model, scaler
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
+
# Function to predict the stock price
|
55 |
+
def predict_price(ticker, start_date, end_date):
|
56 |
+
data = fetch_data(ticker, start_date, end_date)
|
57 |
+
model, scaler = train_model(data.values)
|
58 |
+
last_30_days = data['Close'][-30:].values
|
59 |
+
last_30_days_scaled = scaler.transform(last_30_days.reshape(-1, 1))
|
60 |
|
61 |
+
X_test = []
|
62 |
+
X_test.append(last_30_days_scaled)
|
63 |
+
X_test = np.array(X_test)
|
64 |
+
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
+
predicted_price = model.predict(X_test)
|
67 |
+
predicted_price = scaler.inverse_transform(predicted_price)
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
+
return predicted_price[0][0]
|
|
|
70 |
|
71 |
+
# UI for Gradio
|
72 |
+
def stock_prediction(ticker, start_date, end_date):
|
73 |
+
predicted_price = predict_price(ticker, start_date, end_date)
|
74 |
+
return f"Predicted price for {ticker} on {end_date}: ${predicted_price:.2f}"
|
75 |
|
76 |
+
# Create the Gradio interface
|
77 |
+
ticker_input = gr.inputs.Dropdown(
|
78 |
+
choices=["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA", "FB", "NFLX", "NVDA", "BA", "DIS"],
|
79 |
+
label="Select Stock Ticker"
|
|
|
|
|
80 |
)
|
81 |
+
start_date_input = gr.inputs.Date(label="Start Date")
|
82 |
+
end_date_input = gr.inputs.Date(label="End Date")
|
83 |
|
84 |
+
gr.Interface(
|
85 |
+
fn=stock_prediction,
|
86 |
+
inputs=[ticker_input, start_date_input, end_date_input],
|
87 |
+
outputs="text",
|
88 |
+
title="Stock Price Prediction",
|
89 |
+
description="Enter a stock ticker, start date, and end date to predict the stock price."
|
90 |
+
).launch()
|