File size: 4,103 Bytes
bb80bdc
 
 
 
 
 
 
 
13fdc8c
 
bb80bdc
 
6a782d0
 
bb80bdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26547ea
86bd1a4
 
 
 
 
 
26547ea
86bd1a4
26547ea
86bd1a4
 
 
 
 
26547ea
 
13fdc8c
 
 
bb80bdc
 
13fdc8c
bb80bdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13fdc8c
bb80bdc
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

import gradio as gr
import numpy as np
import pandas as pd
import yfinance as yf
from datetime import datetime
from tensorflow.keras.models import load_model
from joblib import load
import io
from PIL import Image

# Load the saved LSTM model and scaler
lstm_model = load_model('lstm_model.h5')
scaler = load('scaler.joblib')

# Define the list of stocks
stock_list = ['GOOG', 'AAPL', 'TSLA', 'AMZN', 'MSFT']

# Function to get the last row of stock data
def get_last_stock_data(ticker):
    try:
        start_date = '2010-01-01'
        end_date = datetime.now().strftime('%Y-%m-%d')
        data = yf.download(ticker, start=start_date, end=end_date)
        last_row = data.iloc[-1]
        return last_row.to_dict()
    except Exception as e:
        return str(e)

# Function to make predictions
def predict_stock_price(ticker, open_price, high_price, low_price, close_price, adj_close_price, volume):
    try:
        start_date = '2010-01-01'
        end_date = datetime.now().strftime('%Y-%m-%d')
        data = yf.download(ticker, start=start_date, end=end_date)

        # Prepare the data
        data = data[['Close']]
        dataset = data.values
        scaled_data = scaler.transform(dataset)

        # Append the user inputs as the last row in the data
        user_input = np.array([[close_price]])
        user_input_scaled = scaler.transform(user_input)
        scaled_data = np.vstack([scaled_data, user_input_scaled])

        # Prepare the data for LSTM
        x_test_lstm = []
        for i in range(60, len(scaled_data)):
            x_test_lstm.append(scaled_data[i-60:i])

        x_test_lstm = np.array(x_test_lstm)
        x_test_lstm = np.reshape(x_test_lstm, (x_test_lstm.shape[0], x_test_lstm.shape[1], 1))

        # LSTM Predictions
        lstm_predictions = lstm_model.predict(x_test_lstm)
        lstm_predictions = scaler.inverse_transform(lstm_predictions)
        next_day_lstm_price = lstm_predictions[-1][0]
        
        # Plot the data
        plt.figure(figsize=(10, 6))
        plt.plot(data.index, data['Close'], label='Historical Close Prices')
        plt.axvline(x=data.index[-1], color='r', linestyle='--', label='Prediction Date')
        plt.plot([data.index[-1], data.index[-1] + pd.DateOffset(1)], [data['Close'].iloc[-1], next_day_lstm_price], 'go-', label='Predicted Price')
        plt.title(f'Predicted Closing Price for {ticker}')
        plt.xlabel('Date')
        plt.ylabel('Close Price USD ($)')
        plt.legend()

        # Save the plot to a buffer
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        plt.close()
        
      # Load the image from the buffer
        img = Image.open(buf)
        
        result = f"Predicted future price for {ticker}: ${next_day_lstm_price:.2f}"

        return result, img
    except Exception as e:
        return str(e)

# Set up Gradio interface
ticker_input = gr.Dropdown(choices=stock_list, label="Stock Ticker")

def get_user_inputs(ticker):
    last_data = get_last_stock_data(ticker)
    if isinstance(last_data, str):
        return gr.Textbox.update(value=last_data)
    else:
        return gr.update(inputs=[
            gr.Number(value=last_data['Open'], label='Open'),
            gr.Number(value=last_data['High'], label='High'),
            gr.Number(value=last_data['Low'], label='Low'),
            gr.Number(value=last_data['Close'], label='Close'),
            gr.Number(value=last_data['Adj Close'], label='Adj Close'),
            gr.Number(value=last_data['Volume'], label='Volume')
        ])

iface = gr.Interface(
    fn=predict_stock_price,
    inputs=[
        ticker_input,
        gr.Number(label="Open"),
        gr.Number(label="High"),
        gr.Number(label="Low"),
        gr.Number(label="Close"),
        gr.Number(label="Adj Close"),
        gr.Number(label="Volume")
    ],
    outputs=[gr.Textbox(), gr.Image(type="pil")],
    title="Stock Price Predictor",
    description="Select the stock ticker and input the last recorded values to predict the closing price using the LSTM model."
)

iface.launch()