Update app.py
Browse files
app.py
CHANGED
|
@@ -4,17 +4,16 @@ import numpy as np
|
|
| 4 |
import pandas as pd
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
-
from sklearn.model_selection import train_test_split
|
| 8 |
from sklearn.preprocessing import MinMaxScaler
|
| 9 |
from tensorflow.keras.models import Sequential
|
| 10 |
from tensorflow.keras.layers import Dense, LSTM
|
| 11 |
|
| 12 |
-
#
|
| 13 |
def load_stock_data(ticker, start, end):
|
| 14 |
stock = yf.download(ticker, start=start, end=end)
|
| 15 |
return stock
|
| 16 |
|
| 17 |
-
#
|
| 18 |
def preprocess_data(stock):
|
| 19 |
data = stock[['Close']]
|
| 20 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
|
@@ -30,18 +29,18 @@ def preprocess_data(stock):
|
|
| 30 |
|
| 31 |
return x_train, y_train, scaler
|
| 32 |
|
| 33 |
-
#
|
| 34 |
def build_model():
|
| 35 |
model = Sequential()
|
| 36 |
model.add(LSTM(units=50, return_sequences=True, input_shape=(60, 1)))
|
| 37 |
model.add(LSTM(units=50, return_sequences=False))
|
| 38 |
model.add(Dense(units=25))
|
| 39 |
model.add(Dense(units=1))
|
| 40 |
-
|
| 41 |
model.compile(optimizer='adam', loss='mean_squared_error')
|
| 42 |
return model
|
| 43 |
|
| 44 |
-
#
|
| 45 |
def train_model(ticker, start, end):
|
| 46 |
# Load stock data
|
| 47 |
stock_data = load_stock_data(ticker, start, end)
|
|
@@ -55,27 +54,28 @@ def train_model(ticker, start, end):
|
|
| 55 |
|
| 56 |
return model, scaler, stock_data
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
def predict_stock(model, scaler, stock_data
|
| 60 |
-
#
|
| 61 |
test_data = stock_data[['Close']][-60:].values
|
| 62 |
test_data_scaled = scaler.transform(test_data)
|
| 63 |
|
| 64 |
x_test = []
|
| 65 |
x_test.append(test_data_scaled)
|
| 66 |
-
|
| 67 |
x_test = np.array(x_test)
|
| 68 |
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
|
| 69 |
|
|
|
|
| 70 |
predictions = model.predict(x_test)
|
| 71 |
predictions = scaler.inverse_transform(predictions)
|
| 72 |
|
| 73 |
-
#
|
| 74 |
plt.figure(figsize=(10, 6))
|
| 75 |
plt.plot(stock_data.index, stock_data['Close'], label="Historical Prices")
|
| 76 |
future_dates = [stock_data.index[-1] + timedelta(days=i) for i in range(1, 91)]
|
| 77 |
plt.plot(future_dates, predictions.flatten(), label="Predicted Prices")
|
| 78 |
-
plt.title(
|
| 79 |
plt.xlabel('Date')
|
| 80 |
plt.ylabel('Price')
|
| 81 |
plt.legend()
|
|
@@ -83,15 +83,11 @@ def predict_stock(model, scaler, stock_data, ticker, start, end):
|
|
| 83 |
|
| 84 |
return predictions[-1][0]
|
| 85 |
|
| 86 |
-
# Gradio
|
| 87 |
def stock_prediction(ticker, start, end):
|
| 88 |
-
# Train the model
|
| 89 |
model, scaler, stock_data = train_model(ticker, start, end)
|
|
|
|
| 90 |
|
| 91 |
-
# Make prediction for the next 3 months
|
| 92 |
-
prediction = predict_stock(model, scaler, stock_data, ticker, start, end)
|
| 93 |
-
|
| 94 |
-
# Stock performance data
|
| 95 |
start_price = stock_data['Close'].iloc[0]
|
| 96 |
end_price = stock_data['Close'].iloc[-1]
|
| 97 |
percent_change = ((end_price - start_price) / start_price) * 100
|
|
@@ -105,11 +101,12 @@ def stock_prediction(ticker, start, end):
|
|
| 105 |
"Lowest Price": lowest_price
|
| 106 |
}
|
| 107 |
|
| 108 |
-
#
|
| 109 |
tickers = ['AAPL', 'GOOG', 'MSFT', 'TSLA', 'AMZN', 'NFLX', 'META', 'NVDA', 'BABA', 'INTC']
|
| 110 |
start_default = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d")
|
| 111 |
end_default = datetime.now().strftime("%Y-%m-%d")
|
| 112 |
|
|
|
|
| 113 |
iface = gr.Interface(
|
| 114 |
fn=stock_prediction,
|
| 115 |
inputs=[
|
|
@@ -121,5 +118,6 @@ iface = gr.Interface(
|
|
| 121 |
live=True
|
| 122 |
)
|
| 123 |
|
|
|
|
| 124 |
if __name__ == "__main__":
|
| 125 |
-
iface.launch()
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
from datetime import datetime, timedelta
|
|
|
|
| 7 |
from sklearn.preprocessing import MinMaxScaler
|
| 8 |
from tensorflow.keras.models import Sequential
|
| 9 |
from tensorflow.keras.layers import Dense, LSTM
|
| 10 |
|
| 11 |
+
# Function to load stock data
|
| 12 |
def load_stock_data(ticker, start, end):
|
| 13 |
stock = yf.download(ticker, start=start, end=end)
|
| 14 |
return stock
|
| 15 |
|
| 16 |
+
# Function to preprocess the data for model training
|
| 17 |
def preprocess_data(stock):
|
| 18 |
data = stock[['Close']]
|
| 19 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
|
|
|
| 29 |
|
| 30 |
return x_train, y_train, scaler
|
| 31 |
|
| 32 |
+
# Function to build the LSTM model
|
| 33 |
def build_model():
|
| 34 |
model = Sequential()
|
| 35 |
model.add(LSTM(units=50, return_sequences=True, input_shape=(60, 1)))
|
| 36 |
model.add(LSTM(units=50, return_sequences=False))
|
| 37 |
model.add(Dense(units=25))
|
| 38 |
model.add(Dense(units=1))
|
| 39 |
+
|
| 40 |
model.compile(optimizer='adam', loss='mean_squared_error')
|
| 41 |
return model
|
| 42 |
|
| 43 |
+
# Function to train the model
|
| 44 |
def train_model(ticker, start, end):
|
| 45 |
# Load stock data
|
| 46 |
stock_data = load_stock_data(ticker, start, end)
|
|
|
|
| 54 |
|
| 55 |
return model, scaler, stock_data
|
| 56 |
|
| 57 |
+
# Function to predict stock prices
|
| 58 |
+
def predict_stock(model, scaler, stock_data):
|
| 59 |
+
# Use the last 60 days of data for predictions
|
| 60 |
test_data = stock_data[['Close']][-60:].values
|
| 61 |
test_data_scaled = scaler.transform(test_data)
|
| 62 |
|
| 63 |
x_test = []
|
| 64 |
x_test.append(test_data_scaled)
|
| 65 |
+
|
| 66 |
x_test = np.array(x_test)
|
| 67 |
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
|
| 68 |
|
| 69 |
+
# Make predictions
|
| 70 |
predictions = model.predict(x_test)
|
| 71 |
predictions = scaler.inverse_transform(predictions)
|
| 72 |
|
| 73 |
+
# Plot historical and predicted prices
|
| 74 |
plt.figure(figsize=(10, 6))
|
| 75 |
plt.plot(stock_data.index, stock_data['Close'], label="Historical Prices")
|
| 76 |
future_dates = [stock_data.index[-1] + timedelta(days=i) for i in range(1, 91)]
|
| 77 |
plt.plot(future_dates, predictions.flatten(), label="Predicted Prices")
|
| 78 |
+
plt.title("Stock Price Prediction")
|
| 79 |
plt.xlabel('Date')
|
| 80 |
plt.ylabel('Price')
|
| 81 |
plt.legend()
|
|
|
|
| 83 |
|
| 84 |
return predictions[-1][0]
|
| 85 |
|
| 86 |
+
# Gradio interface function
|
| 87 |
def stock_prediction(ticker, start, end):
|
|
|
|
| 88 |
model, scaler, stock_data = train_model(ticker, start, end)
|
| 89 |
+
prediction = predict_stock(model, scaler, stock_data)
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
start_price = stock_data['Close'].iloc[0]
|
| 92 |
end_price = stock_data['Close'].iloc[-1]
|
| 93 |
percent_change = ((end_price - start_price) / start_price) * 100
|
|
|
|
| 101 |
"Lowest Price": lowest_price
|
| 102 |
}
|
| 103 |
|
| 104 |
+
# Define stock tickers and default dates
|
| 105 |
tickers = ['AAPL', 'GOOG', 'MSFT', 'TSLA', 'AMZN', 'NFLX', 'META', 'NVDA', 'BABA', 'INTC']
|
| 106 |
start_default = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d")
|
| 107 |
end_default = datetime.now().strftime("%Y-%m-%d")
|
| 108 |
|
| 109 |
+
# Gradio interface
|
| 110 |
iface = gr.Interface(
|
| 111 |
fn=stock_prediction,
|
| 112 |
inputs=[
|
|
|
|
| 118 |
live=True
|
| 119 |
)
|
| 120 |
|
| 121 |
+
# Launch the Gradio app
|
| 122 |
if __name__ == "__main__":
|
| 123 |
+
iface.launch()
|