File size: 5,875 Bytes
c289a82
17351a2
41a31e6
 
 
 
 
 
2a072fa
141412b
480b75f
141412b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289a82
 
141412b
 
480b75f
c289a82
141412b
480b75f
 
141412b
 
c289a82
480b75f
c289a82
480b75f
141412b
 
480b75f
c289a82
480b75f
c289a82
 
3e8e62b
 
c289a82
 
 
141412b
63a496e
c289a82
d93f225
480b75f
c289a82
141412b
63a496e
abc4c00
c289a82
3e8e62b
480b75f
63a496e
c289a82
141412b
c289a82
28fbe3d
c289a82
28fbe3d
 
 
c289a82
141412b
 
c289a82
141412b
 
c289a82
141412b
 
 
c289a82
 
2a072fa
c289a82
2a072fa
 
 
c289a82
 
 
2a072fa
c289a82
 
 
 
 
abc4c00
2a072fa
 
c289a82
 
 
 
 
 
2a072fa
141412b
480b75f
141412b
 
c289a82
141412b
 
 
 
d93f225
 
141412b
63a496e
c289a82
 
2a072fa
 
 
 
 
63a496e
 
c289a82
141412b
 
63a496e
141412b
c289a82
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# Import required libraries
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

# Step 1: Fetch stock data from yfinance
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

# Step 2: Prepare data for the LSTM model
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

# Step 3: Build the LSTM model
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

# Step 4: Train the LSTM 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

# Step 5: Predict stock prices
def predict_future(model, last_data, scaler, steps=1):
    predictions = []
    input_data = last_data[-60:].reshape(1, -1)

    # Generate predictions for the specified number of future days
    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)  # Reverse scaling
    return predicted_prices

# Step 6: Plot historical and predicted stock prices
def plot_predictions(data, predicted_prices):
    # Create a figure for the plot
    plt.figure(figsize=(14, 6))
    
    # Plot historical stock prices
    plt.plot(data['Date'], data['Close'], label="Historical Prices", color='blue')

    # Generate future date for predicted prices
    future_date = pd.to_datetime(data['Date'].iloc[-1]) + pd.Timedelta(days=1)  # Tomorrow's date
    plt.scatter(future_date, predicted_prices[0][0], color='red', label="Predicted Price for Tomorrow")  # Red dot for prediction

    # Adding labels and title to the graph
    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='--')  # Horizontal line for predicted price
    plt.legend()
    plt.grid(True)

    # Save the plot as an image file for Gradio to display
    plt.savefig("stock_prediction.png")
    plt.close()

    return "stock_prediction.png"  # Return the path to the saved image

# Step 7: Gradio interface function
def stock_prediction_app(ticker, start_date_str, end_date_str):
    # Convert input strings to datetime objects
    start_date = datetime.strptime(start_date_str, "%Y-%m-%d").date()
    end_date = datetime.strptime(end_date_str, "%Y-%m-%d").date()

    # Fetch stock data from yfinance
    data = fetch_stock_data(ticker, start_date, end_date)
    
    # Prepare data for LSTM model
    scaled_data, scaler = prepare_data(data)
    
    # Build and train the LSTM model
    model = build_model((60, 1))
    model = train_model(model, scaled_data)
    
    # Predict stock price for tomorrow (1 day)
    predicted_price = predict_future(model, scaled_data, scaler, steps=1)

    # Current, highest, lowest prices, and percentage change
    current_price = data['Close'].iloc[-1]
    highest_price = data['Close'].max()
    lowest_price = data['Close'].min()
    
    # Calculate percentage change
    percentage_change = ((predicted_price[0][0] - current_price) / current_price) * 100

    # Buy/Sell recommendation
    recommendation = "Buy" if predicted_price[0][0] > current_price else "Sell"

    # Generate and return the plot with historical and predicted prices
    plot_path = plot_predictions(data, predicted_price)
    
    return (
        plot_path, 
        predicted_price[0][0],  # Tomorrow's predicted price
        current_price,           # Current price
        highest_price,           # Highest price
        lowest_price,            # Lowest price
        percentage_change,       # Percentage change
        recommendation            # Buy/Sell recommendation
    )

# Step 8: Gradio UI setup
tickers = ["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA", "META", "NFLX", "NVDA", "BABA", "BA"]

# Define the Gradio interface
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"),  # Return the file path for the generated graph
        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."
)

# Launch the Gradio app
ui.launch()