Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 get stock data
|
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 |
+
# Prepare the dataset for LSTM
|
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 training and testing sets (80% train, 20% test)
|
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):
|
28 |
+
X.append(data[i:i + time_step])
|
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 |
+
# Building the LSTM model
|
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)),
|
41 |
+
tf.keras.layers.LSTM(50, return_sequences=False),
|
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 |
+
# Training the 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 |
+
# Make predictions
|
56 |
+
def make_predictions(model, X_test, scaler):
|
57 |
+
predictions = model.predict(X_test)
|
58 |
+
return scaler.inverse_transform(predictions)
|
59 |
+
|
60 |
+
# Calculate metrics for buy/sell decisions
|
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 |
+
# Plot historical vs predicted
|
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 app function
|
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 |
+
# Define stock tickers for dropdown
|
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()
|