|
import yfinance as yf |
|
import tensorflow as tf |
|
import numpy as np |
|
import pandas as pd |
|
import matplotlib.pyplot as plt |
|
import gradio as gr |
|
from datetime import datetime |
|
|
|
|
|
stock_tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'NFLX', 'FB', 'NVDA', 'JPM', 'BAC'] |
|
|
|
|
|
def fetch_stock_data(ticker, start_date, end_date): |
|
data = yf.download(ticker, start=start_date, end=end_date) |
|
return data |
|
|
|
|
|
def train_lstm(data): |
|
|
|
data['Close'] = data['Close'].fillna(method='ffill') |
|
scaled_data = data['Close'].values.reshape(-1, 1) |
|
training_data = scaled_data[:int(len(scaled_data) * 0.8)] |
|
test_data = scaled_data[int(len(scaled_data) * 0.8):] |
|
|
|
|
|
def create_sequences(data, seq_length): |
|
X, y = [], [] |
|
for i in range(len(data) - seq_length): |
|
X.append(data[i:i + seq_length]) |
|
y.append(data[i + seq_length]) |
|
return np.array(X), np.array(y) |
|
|
|
seq_length = 60 |
|
X_train, y_train = create_sequences(training_data, seq_length) |
|
|
|
|
|
model = tf.keras.Sequential([ |
|
tf.keras.layers.LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)), |
|
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') |
|
model.fit(X_train, y_train, batch_size=1, epochs=1) |
|
|
|
|
|
X_test, _ = create_sequences(test_data, seq_length) |
|
predictions = model.predict(X_test) |
|
|
|
return predictions, data.index[-len(predictions):] |
|
|
|
|
|
def plot_stock_data(data, predictions, pred_dates): |
|
plt.figure(figsize=(10,6)) |
|
plt.plot(data['Close'], label='Historical Data') |
|
plt.plot(pred_dates, predictions, label='Predicted Data') |
|
plt.xlabel('Date') |
|
plt.ylabel('Close Price (USD)') |
|
plt.legend() |
|
plt.grid() |
|
plt.show() |
|
|
|
|
|
def stock_prediction(ticker, start_date, end_date): |
|
data = fetch_stock_data(ticker, start_date, end_date) |
|
predictions, pred_dates = train_lstm(data) |
|
plot_stock_data(data, predictions, pred_dates) |
|
|
|
|
|
percentage_change = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100 |
|
highest_value = data['Close'].max() |
|
lowest_value = data['Close'].min() |
|
|
|
|
|
decision = 'Buy' if predictions[-1] > data['Close'][-1] else 'Sell' |
|
|
|
return f"Percentage Change: {percentage_change:.2f}%", f"Highest Value: {highest_value:.2f}", f"Lowest Value: {lowest_value:.2f}", f"Decision: {decision}" |
|
|
|
|
|
interface = gr.Interface( |
|
fn=stock_prediction, |
|
inputs=[ |
|
gr.inputs.Dropdown(choices=stock_tickers, label="Select Stock Ticker"), |
|
gr.inputs.Date(label="Start Date"), |
|
gr.inputs.Date(label="End Date") |
|
], |
|
outputs=[ |
|
gr.outputs.Textbox(label="Percentage Change"), |
|
gr.outputs.Textbox(label="Highest Value"), |
|
gr.outputs.Textbox(label="Lowest Value"), |
|
gr.outputs.Textbox(label="Prediction: Buy/Sell") |
|
], |
|
title="Stock Prediction App", |
|
description="Predict if you should buy or sell a stock based on historical performance." |
|
) |
|
|
|
interface.launch() |
|
|
|
|