Update app.py
Browse files
app.py
CHANGED
@@ -1,104 +1,117 @@
|
|
1 |
import yfinance as yf
|
2 |
import pandas as pd
|
3 |
-
import numpy as np
|
4 |
-
import matplotlib.pyplot as plt
|
5 |
-
from sklearn.preprocessing import MinMaxScaler
|
6 |
-
from tensorflow.keras.models import Sequential
|
7 |
-
from tensorflow.keras.layers import Dense, LSTM
|
8 |
|
9 |
-
# Fetch stock data
|
10 |
def get_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 |
-
# Example usage
|
15 |
ticker = 'AAPL'
|
16 |
-
start_date = '
|
17 |
-
end_date = '
|
18 |
-
|
19 |
-
print(
|
20 |
-
|
21 |
-
scaler = MinMaxScaler(feature_range=(0, 1))
|
22 |
-
scaled_data = scaler.fit_transform(data[['Close']].values)
|
23 |
-
return scaled_data, scaler
|
24 |
|
25 |
# Preprocess stock data
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
def create_lstm_model(input_shape):
|
28 |
model = Sequential()
|
29 |
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
|
30 |
model.add(LSTM(units=50))
|
31 |
-
model.add(Dense(units=1)) #
|
32 |
model.compile(optimizer='adam', loss='mean_squared_error')
|
33 |
return model
|
34 |
|
35 |
-
#
|
36 |
def train_model(stock_data, window_size=60):
|
37 |
X_train, y_train = [], []
|
38 |
for i in range(window_size, len(stock_data)):
|
39 |
X_train.append(stock_data[i-window_size:i, 0])
|
40 |
y_train.append(stock_data[i, 0])
|
41 |
X_train, y_train = np.array(X_train), np.array(y_train)
|
42 |
-
X_train =
|
43 |
-
|
44 |
model = create_lstm_model((X_train.shape[1], 1))
|
45 |
-
model.fit(X_train, y_train, epochs=
|
46 |
-
|
47 |
return model
|
48 |
|
49 |
-
# Train
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
for _ in range(
|
57 |
-
|
58 |
-
|
59 |
-
input_data = np.append(input_data[:, 1:], [[
|
60 |
-
|
61 |
-
#
|
62 |
-
predicted_prices = scaler.inverse_transform(np.array(
|
63 |
return predicted_prices
|
64 |
|
65 |
-
# Predict future prices
|
66 |
-
|
67 |
-
future_prices =
|
68 |
import gradio as gr
|
|
|
69 |
|
70 |
-
|
|
|
71 |
stock_data = get_stock_data(ticker, start_date, end_date)
|
72 |
scaled_data, scaler = preprocess_data(stock_data)
|
|
|
|
|
73 |
model = train_model(scaled_data)
|
74 |
-
future_prices = make_prediction(model, scaler, scaled_data, scaled_data[-60:])
|
75 |
|
76 |
-
#
|
77 |
-
|
78 |
-
|
79 |
-
|
|
|
|
|
|
|
80 |
plt.plot(future_dates, future_prices, label='Predicted Prices', linestyle='--')
|
81 |
-
plt.title(f
|
82 |
plt.xlabel('Date')
|
83 |
plt.ylabel('Price')
|
84 |
plt.legend()
|
85 |
-
plt.savefig('
|
86 |
-
|
|
|
87 |
|
88 |
-
# Define
|
89 |
tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
92 |
|
93 |
-
ticker = gr.Dropdown(tickers, label="Stock Ticker")
|
94 |
start_date = gr.Date(label="Start Date")
|
95 |
end_date = gr.Date(label="End Date")
|
96 |
|
97 |
-
|
98 |
|
99 |
-
|
100 |
-
|
101 |
|
102 |
-
|
103 |
|
104 |
app.launch()
|
|
|
1 |
import yfinance as yf
|
2 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
# Fetch stock data from Yahoo Finance
|
5 |
def get_stock_data(ticker, start_date, end_date):
|
6 |
stock_data = yf.download(ticker, start=start_date, end=end_date)
|
7 |
+
if stock_data.empty:
|
8 |
+
raise ValueError("No data found for the given ticker and date range.")
|
9 |
return stock_data
|
10 |
|
11 |
+
# Example usage
|
12 |
ticker = 'AAPL'
|
13 |
+
start_date = '2023-01-01'
|
14 |
+
end_date = '2024-01-01'
|
15 |
+
data = get_stock_data(ticker, start_date, end_date)
|
16 |
+
print(data.head())
|
17 |
+
from sklearn.preprocessing import MinMaxScaler
|
|
|
|
|
|
|
18 |
|
19 |
# Preprocess stock data
|
20 |
+
def preprocess_data(stock_data):
|
21 |
+
scaler = MinMaxScaler(feature_range=(0, 1)) # Normalizing the close prices
|
22 |
+
scaled_data = scaler.fit_transform(stock_data[['Close']].values)
|
23 |
+
return scaled_data, scaler
|
24 |
+
|
25 |
+
# Preprocess the stock data
|
26 |
+
scaled_data, scaler = preprocess_data(data)
|
27 |
+
from tensorflow.keras.models import Sequential
|
28 |
+
from tensorflow.keras.layers import LSTM, Dense
|
29 |
+
|
30 |
+
# Define and train an LSTM model
|
31 |
def create_lstm_model(input_shape):
|
32 |
model = Sequential()
|
33 |
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
|
34 |
model.add(LSTM(units=50))
|
35 |
+
model.add(Dense(units=1)) # Predicting stock price
|
36 |
model.compile(optimizer='adam', loss='mean_squared_error')
|
37 |
return model
|
38 |
|
39 |
+
# Prepare data for training the model
|
40 |
def train_model(stock_data, window_size=60):
|
41 |
X_train, y_train = [], []
|
42 |
for i in range(window_size, len(stock_data)):
|
43 |
X_train.append(stock_data[i-window_size:i, 0])
|
44 |
y_train.append(stock_data[i, 0])
|
45 |
X_train, y_train = np.array(X_train), np.array(y_train)
|
46 |
+
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
|
47 |
+
|
48 |
model = create_lstm_model((X_train.shape[1], 1))
|
49 |
+
model.fit(X_train, y_train, epochs=10, batch_size=32)
|
|
|
50 |
return model
|
51 |
|
52 |
+
# Train the LSTM model
|
53 |
+
lstm_model = train_model(scaled_data)
|
54 |
+
import numpy as np
|
55 |
+
|
56 |
+
def predict_future_prices(model, scaler, recent_data, days_to_predict=90):
|
57 |
+
predictions = []
|
58 |
+
input_data = recent_data[-60:].reshape(1, 60, 1) # Using the last 60 days to predict
|
59 |
+
for _ in range(days_to_predict):
|
60 |
+
pred_price = model.predict(input_data)[0, 0]
|
61 |
+
predictions.append(pred_price)
|
62 |
+
input_data = np.append(input_data[:, 1:, :], [[pred_price]], axis=1)
|
63 |
+
|
64 |
+
# Inverse transform to get the original prices
|
65 |
+
predicted_prices = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))
|
66 |
return predicted_prices
|
67 |
|
68 |
+
# Predict future stock prices
|
69 |
+
recent_data = scaled_data[-60:]
|
70 |
+
future_prices = predict_future_prices(lstm_model, scaler, recent_data)
|
71 |
import gradio as gr
|
72 |
+
import matplotlib.pyplot as plt
|
73 |
|
74 |
+
# Gradio function to predict stock prices and display results
|
75 |
+
def stock_prediction_app(ticker, start_date, end_date):
|
76 |
stock_data = get_stock_data(ticker, start_date, end_date)
|
77 |
scaled_data, scaler = preprocess_data(stock_data)
|
78 |
+
|
79 |
+
# Train the model on the selected stock data
|
80 |
model = train_model(scaled_data)
|
|
|
81 |
|
82 |
+
# Make predictions for the next 90 days
|
83 |
+
future_prices = predict_future_prices(model, scaler, scaled_data)
|
84 |
+
|
85 |
+
# Plot the historical and future stock prices
|
86 |
+
plt.figure(figsize=(10, 6))
|
87 |
+
plt.plot(stock_data.index, stock_data['Close'], label='Historical Prices')
|
88 |
+
future_dates = pd.date_range(end=stock_data.index[-1], periods=90)
|
89 |
plt.plot(future_dates, future_prices, label='Predicted Prices', linestyle='--')
|
90 |
+
plt.title(f'{ticker} Stock Price Prediction')
|
91 |
plt.xlabel('Date')
|
92 |
plt.ylabel('Price')
|
93 |
plt.legend()
|
94 |
+
plt.savefig('stock_prediction.png')
|
95 |
+
|
96 |
+
return f"The predicted stock price for the next 3 months is shown in the graph.", 'stock_prediction.png'
|
97 |
|
98 |
+
# Define Gradio interface
|
99 |
tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
|
100 |
+
|
101 |
+
app = gr.Blocks()
|
102 |
+
|
103 |
+
with app:
|
104 |
+
gr.Markdown("# Stock Buy/Sell Prediction App")
|
105 |
|
106 |
+
ticker = gr.Dropdown(tickers, label="Select Stock Ticker")
|
107 |
start_date = gr.Date(label="Start Date")
|
108 |
end_date = gr.Date(label="End Date")
|
109 |
|
110 |
+
predict_button = gr.Button("Predict")
|
111 |
|
112 |
+
output_text = gr.Textbox(label="Prediction Result")
|
113 |
+
output_image = gr.Image(label="Stock Price Graph")
|
114 |
|
115 |
+
predict_button.click(fn=stock_prediction_app, inputs=[ticker, start_date, end_date], outputs=[output_text, output_image])
|
116 |
|
117 |
app.launch()
|