|
import yfinance as yf |
|
import numpy as np |
|
import pandas as pd |
|
import tensorflow as tf |
|
from sklearn.preprocessing import MinMaxScaler |
|
import gradio as gr |
|
import matplotlib.pyplot as plt |
|
import os |
|
|
|
|
|
tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'META', 'NFLX', 'NVDA', 'INTC', 'IBM'] |
|
|
|
|
|
def stock_prediction_app(ticker, start_date, end_date): |
|
|
|
stock_data = yf.download(ticker, start=start_date, end=end_date) |
|
|
|
|
|
if stock_data.empty: |
|
return "No data available for the selected date range.", None |
|
|
|
|
|
df_close = stock_data[['Close', 'Open', 'High', 'Low', 'Volume']] |
|
scaler = MinMaxScaler(feature_range=(0, 1)) |
|
scaled_data = scaler.fit_transform(df_close) |
|
|
|
|
|
def create_dataset(data, time_step=60): |
|
X_train, y_train = [], [] |
|
for i in range(len(data)-time_step-1): |
|
X_train.append(data[i:(i+time_step), :]) |
|
y_train.append(data[i + time_step, 0]) |
|
return np.array(X_train), np.array(y_train) |
|
|
|
X_train, y_train = create_dataset(scaled_data) |
|
|
|
|
|
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2]) |
|
|
|
|
|
lstm_model = tf.keras.Sequential([ |
|
tf.keras.layers.LSTM(100, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])), |
|
tf.keras.layers.Dropout(0.2), |
|
tf.keras.layers.LSTM(100, return_sequences=False), |
|
tf.keras.layers.Dropout(0.2), |
|
tf.keras.layers.Dense(25), |
|
tf.keras.layers.Dense(1) |
|
]) |
|
|
|
|
|
lstm_model.compile(optimizer='adam', loss='mean_squared_error') |
|
|
|
|
|
lstm_model.fit(X_train, y_train, batch_size=32, epochs=50, verbose=0) |
|
|
|
|
|
predictions = lstm_model.predict(X_train) |
|
predictions = scaler.inverse_transform(np.concatenate((predictions, np.zeros((predictions.shape[0], scaled_data.shape[1]-1))), axis=1))[:, 0] |
|
|
|
|
|
plt.figure(figsize=(10, 5)) |
|
plt.plot(df_close['Close'].values, label='Actual Stock Price', color='blue') |
|
plt.plot(predictions, label='Predicted Stock Price', color='orange') |
|
plt.title(f'{ticker} Stock Price Prediction') |
|
plt.xlabel('Days') |
|
plt.ylabel('Stock Price') |
|
plt.legend() |
|
|
|
|
|
plot_path = 'stock_prediction_plot.png' |
|
plt.savefig(plot_path) |
|
plt.close() |
|
|
|
|
|
return f"Prediction complete for {ticker} from {start_date} to {end_date}", plot_path |
|
|
|
|
|
app = gr.Blocks() |
|
|
|
with app: |
|
gr.Markdown("# Stock Buy/Sell Prediction App") |
|
|
|
|
|
ticker = gr.Dropdown(tickers, label="Select Stock Ticker") |
|
|
|
|
|
start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)") |
|
end_date = gr.Textbox(label="End Date (YYYY-MM-DD)") |
|
|
|
|
|
predict_button = gr.Button("Predict") |
|
|
|
|
|
output_text = gr.Textbox(label="Prediction Result", interactive=False) |
|
output_image = gr.Image(label="Stock Price Graph") |
|
|
|
|
|
predict_button.click(fn=stock_prediction_app, inputs=[ticker, start_date, end_date], outputs=[output_text, output_image]) |
|
|
|
|
|
app.launch() |
|
|