|
import yfinance as yf |
|
import pandas as pd |
|
import numpy as np |
|
import matplotlib.pyplot as plt |
|
from sklearn.preprocessing import MinMaxScaler |
|
from tensorflow.keras.models import Sequential |
|
from tensorflow.keras.layers import Dense, LSTM |
|
|
|
|
|
def get_stock_data(ticker, start_date, end_date): |
|
stock_data = yf.download(ticker, start=start_date, end=end_date) |
|
return stock_data |
|
|
|
|
|
ticker = 'AAPL' |
|
start_date = '2022-01-01' |
|
end_date = '2023-01-01' |
|
stock_data = get_stock_data(ticker, start_date, end_date) |
|
print(stock_data.head()) |
|
def preprocess_data(data): |
|
scaler = MinMaxScaler(feature_range=(0, 1)) |
|
scaled_data = scaler.fit_transform(data[['Close']].values) |
|
return scaled_data, scaler |
|
|
|
|
|
scaled_data, scaler = preprocess_data(stock_data) |
|
def create_lstm_model(input_shape): |
|
model = Sequential() |
|
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape)) |
|
model.add(LSTM(units=50)) |
|
model.add(Dense(units=1)) |
|
model.compile(optimizer='adam', loss='mean_squared_error') |
|
return model |
|
|
|
|
|
def train_model(stock_data, window_size=60): |
|
X_train, y_train = [], [] |
|
for i in range(window_size, len(stock_data)): |
|
X_train.append(stock_data[i-window_size:i, 0]) |
|
y_train.append(stock_data[i, 0]) |
|
X_train, y_train = np.array(X_train), np.array(y_train) |
|
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) |
|
|
|
model = create_lstm_model((X_train.shape[1], 1)) |
|
model.fit(X_train, y_train, epochs=5, batch_size=32) |
|
|
|
return model |
|
|
|
|
|
model = train_model(scaled_data) |
|
def make_prediction(model, scaler, stock_data, last_data, prediction_days=90): |
|
|
|
input_data = last_data[-60:].reshape(1, 60, 1) |
|
predicted_prices = [] |
|
|
|
for _ in range(prediction_days): |
|
predicted_price = model.predict(input_data) |
|
predicted_prices.append(predicted_price[0, 0]) |
|
input_data = np.append(input_data[:, 1:], [[predicted_price]], axis=1) |
|
|
|
|
|
predicted_prices = scaler.inverse_transform(np.array(predicted_prices).reshape(-1, 1)) |
|
return predicted_prices |
|
|
|
|
|
last_data = scaled_data[-60:] |
|
future_prices = make_prediction(model, scaler, scaled_data, last_data) |
|
import gradio as gr |
|
|
|
def predict_stock(ticker, start_date, end_date): |
|
stock_data = get_stock_data(ticker, start_date, end_date) |
|
scaled_data, scaler = preprocess_data(stock_data) |
|
model = train_model(scaled_data) |
|
future_prices = make_prediction(model, scaler, scaled_data, scaled_data[-60:]) |
|
|
|
|
|
plt.figure(figsize=(14,5)) |
|
plt.plot(stock_data['Close'], label='Historical Prices') |
|
future_dates = pd.date_range(end=end_date, periods=90, freq='B') |
|
plt.plot(future_dates, future_prices, label='Predicted Prices', linestyle='--') |
|
plt.title(f"Stock Prices for {ticker}") |
|
plt.xlabel('Date') |
|
plt.ylabel('Price') |
|
plt.legend() |
|
plt.savefig('stock_plot.png') |
|
return future_prices, 'stock_plot.png' |
|
|
|
|
|
tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM'] |
|
with gr.Blocks() as app: |
|
gr.Markdown("## Stock Buy/Sell Prediction App") |
|
|
|
ticker = gr.Dropdown(tickers, label="Stock Ticker") |
|
start_date = gr.Date(label="Start Date") |
|
end_date = gr.Date(label="End Date") |
|
|
|
predict_btn = gr.Button("Predict") |
|
|
|
predicted_values = gr.Textbox(label="Predicted Stock Values") |
|
stock_plot = gr.Image(label="Stock Performance Graph") |
|
|
|
predict_btn.click(fn=predict_stock, inputs=[ticker, start_date, end_date], outputs=[predicted_values, stock_plot]) |
|
|
|
app.launch() |
|
|