Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import yfinance as yf
|
2 |
+
import gradio as gr
|
3 |
+
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 |
+
# Load stock data using Yahoo Finance
|
13 |
+
def load_stock_data(ticker, start, end):
|
14 |
+
stock = yf.download(ticker, start=start, end=end)
|
15 |
+
return stock
|
16 |
+
|
17 |
+
# Data Preprocessing
|
18 |
+
def preprocess_data(stock):
|
19 |
+
data = stock[['Close']]
|
20 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
21 |
+
scaled_data = scaler.fit_transform(data)
|
22 |
+
|
23 |
+
x_train, y_train = [], []
|
24 |
+
for i in range(60, len(scaled_data)):
|
25 |
+
x_train.append(scaled_data[i-60:i, 0])
|
26 |
+
y_train.append(scaled_data[i, 0])
|
27 |
+
|
28 |
+
x_train, y_train = np.array(x_train), np.array(y_train)
|
29 |
+
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
|
30 |
+
|
31 |
+
return x_train, y_train, scaler
|
32 |
+
|
33 |
+
# Build the LSTM model
|
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 |
+
# Training and prediction
|
45 |
+
def train_model(ticker, start, end):
|
46 |
+
# Load stock data
|
47 |
+
stock_data = load_stock_data(ticker, start, end)
|
48 |
+
|
49 |
+
# Preprocess the data
|
50 |
+
x_train, y_train, scaler = preprocess_data(stock_data)
|
51 |
+
|
52 |
+
# Build and train the model
|
53 |
+
model = build_model()
|
54 |
+
model.fit(x_train, y_train, batch_size=1, epochs=1)
|
55 |
+
|
56 |
+
return model, scaler, stock_data
|
57 |
+
|
58 |
+
# Predict stock prices
|
59 |
+
def predict_stock(model, scaler, stock_data, ticker, start, end):
|
60 |
+
# Load real-time stock data for future predictions
|
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 |
+
# Plotting the results
|
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(f'{ticker} Stock Price Prediction')
|
79 |
+
plt.xlabel('Date')
|
80 |
+
plt.ylabel('Price')
|
81 |
+
plt.legend()
|
82 |
+
plt.show()
|
83 |
+
|
84 |
+
return predictions[-1][0]
|
85 |
+
|
86 |
+
# Gradio Interface
|
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
|
98 |
+
highest_price = stock_data['Close'].max()
|
99 |
+
lowest_price = stock_data['Close'].min()
|
100 |
+
|
101 |
+
return {
|
102 |
+
"Predicted Next Price": prediction,
|
103 |
+
"Percentage Change": percent_change,
|
104 |
+
"Highest Price": highest_price,
|
105 |
+
"Lowest Price": lowest_price
|
106 |
+
}
|
107 |
+
|
108 |
+
# Gradio UI
|
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=[
|
116 |
+
gr.inputs.Dropdown(choices=tickers, label="Select Stock Ticker"),
|
117 |
+
gr.inputs.Date(label="Start Date", default=start_default),
|
118 |
+
gr.inputs.Date(label="End Date", default=end_default),
|
119 |
+
],
|
120 |
+
outputs=[
|
121 |
+
gr.outputs.JSON(label="Prediction and Analysis")
|
122 |
+
],
|
123 |
+
live=True
|
124 |
+
)
|
125 |
+
|
126 |
+
if __name__ == "__main__":
|
127 |
+
iface.launch()
|