|
|
|
|
|
import yfinance as yf |
|
|
import pandas as pd |
|
|
import numpy as np |
|
|
import tensorflow as tf |
|
|
from sklearn.preprocessing import MinMaxScaler |
|
|
import matplotlib.pyplot as plt |
|
|
import gradio as gr |
|
|
from datetime import datetime |
|
|
|
|
|
|
|
|
def fetch_stock_data(ticker, start_date, end_date): |
|
|
stock_data = yf.download(ticker, start=start_date, end=end_date) |
|
|
stock_data.reset_index(inplace=True) |
|
|
return stock_data |
|
|
|
|
|
|
|
|
def prepare_data(df): |
|
|
scaler = MinMaxScaler(feature_range=(0, 1)) |
|
|
close_prices = df['Close'].values.reshape(-1, 1) |
|
|
scaled_data = scaler.fit_transform(close_prices) |
|
|
return scaled_data, scaler |
|
|
|
|
|
|
|
|
def build_model(input_shape): |
|
|
model = tf.keras.Sequential([ |
|
|
tf.keras.layers.LSTM(50, return_sequences=True, input_shape=input_shape), |
|
|
tf.keras.layers.LSTM(50, return_sequences=False), |
|
|
tf.keras.layers.Dense(25), |
|
|
tf.keras.layers.Dense(1) |
|
|
]) |
|
|
model.compile(optimizer='adam', loss='mean_squared_error') |
|
|
return model |
|
|
|
|
|
|
|
|
def train_model(model, train_data, epochs=5): |
|
|
X_train, y_train = [], [] |
|
|
for i in range(60, len(train_data)): |
|
|
X_train.append(train_data[i-60:i, 0]) |
|
|
y_train.append(train_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.fit(X_train, y_train, epochs=epochs, batch_size=32, verbose=0) |
|
|
return model |
|
|
|
|
|
|
|
|
def predict_future(model, last_data, scaler, steps=1): |
|
|
predictions = [] |
|
|
input_data = last_data[-60:].reshape(1, -1) |
|
|
|
|
|
|
|
|
for _ in range(steps): |
|
|
input_reshaped = input_data.reshape(1, 60, 1) |
|
|
predicted_price = model.predict(input_reshaped, verbose=0) |
|
|
predictions.append(predicted_price[0][0]) |
|
|
input_data = np.append(input_data[0][1:], predicted_price) |
|
|
|
|
|
predicted_prices = np.array(predictions).reshape(-1, 1) |
|
|
predicted_prices = scaler.inverse_transform(predicted_prices) |
|
|
return predicted_prices |
|
|
|
|
|
|
|
|
def plot_predictions(data, predicted_prices): |
|
|
|
|
|
plt.figure(figsize=(14, 6)) |
|
|
|
|
|
|
|
|
plt.plot(data['Date'], data['Close'], label="Historical Prices", color='blue') |
|
|
|
|
|
|
|
|
future_date = pd.to_datetime(data['Date'].iloc[-1]) + pd.Timedelta(days=1) |
|
|
plt.scatter(future_date, predicted_prices[0][0], color='red', label="Predicted Price for Tomorrow") |
|
|
|
|
|
|
|
|
plt.title("Stock Price Prediction for Tomorrow") |
|
|
plt.xlabel("Date") |
|
|
plt.ylabel("Stock Price (USD)") |
|
|
plt.axhline(y=predicted_prices[0][0], color='red', linestyle='--') |
|
|
plt.legend() |
|
|
plt.grid(True) |
|
|
|
|
|
|
|
|
plt.savefig("stock_prediction.png") |
|
|
plt.close() |
|
|
|
|
|
return "stock_prediction.png" |
|
|
|
|
|
|
|
|
def stock_prediction_app(ticker, start_date_str, end_date_str): |
|
|
|
|
|
start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date() |
|
|
end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date() |
|
|
|
|
|
|
|
|
data = fetch_stock_data(ticker, start_date, end_date) |
|
|
|
|
|
|
|
|
scaled_data, scaler = prepare_data(data) |
|
|
|
|
|
|
|
|
model = build_model((60, 1)) |
|
|
model = train_model(model, scaled_data) |
|
|
|
|
|
|
|
|
predicted_price = predict_future(model, scaled_data, scaler, steps=1) |
|
|
|
|
|
|
|
|
current_price = data['Close'].iloc[-1] |
|
|
highest_price = data['Close'].max() |
|
|
lowest_price = data['Close'].min() |
|
|
|
|
|
|
|
|
percentage_change = ((predicted_price[0][0] - current_price) / current_price) * 100 |
|
|
|
|
|
|
|
|
recommendation = "Buy" if predicted_price[0][0] > current_price else "Sell" |
|
|
|
|
|
|
|
|
plot_path = plot_predictions(data, predicted_price) |
|
|
|
|
|
return ( |
|
|
plot_path, |
|
|
predicted_price[0][0], |
|
|
current_price, |
|
|
highest_price, |
|
|
lowest_price, |
|
|
percentage_change, |
|
|
recommendation |
|
|
) |
|
|
|
|
|
|
|
|
tickers = ["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA", "META", "NFLX", "NVDA", "BABA", "BA"] |
|
|
|
|
|
|
|
|
ui = gr.Interface( |
|
|
fn=stock_prediction_app, |
|
|
inputs=[ |
|
|
gr.Dropdown(tickers, label="Select Stock Ticker"), |
|
|
gr.Textbox(label="Start Date (YYYY-MM-DD)"), |
|
|
gr.Textbox(label="End Date (YYYY-MM-DD)") |
|
|
], |
|
|
outputs=[ |
|
|
gr.Image(type="filepath"), |
|
|
gr.Number(label="Predicted Price for Tomorrow (USD)"), |
|
|
gr.Number(label="Current Price (USD)"), |
|
|
gr.Number(label="Highest Price (USD)"), |
|
|
gr.Number(label="Lowest Price (USD)"), |
|
|
gr.Number(label="Percentage Change (%)"), |
|
|
gr.Textbox(label="Recommendation") |
|
|
], |
|
|
title="Stock Price Prediction App", |
|
|
description="Predict future stock price for tomorrow based on historical data." |
|
|
) |
|
|
|
|
|
|
|
|
ui.launch() |
|
|
|
|
|
|