Sajidahamed commited on
Commit
6770707
·
verified ·
1 Parent(s): 11413dc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -0
app.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from sklearn.preprocessing import MinMaxScaler
6
+ import os
7
+
8
+ # --- 1. Load the Pre-trained Model and Scaler ---
9
+
10
+ # Load the trained LSTM model from the .h5 file
11
+ model = tf.keras.models.load_model('lstm_model.h5')
12
+
13
+ # We need to re-create the scaler that was used during training.
14
+ # To do this, we load the original dataset.
15
+ data = pd.read_csv("TSLA.csv")
16
+ close_prices = data[['Close']].values
17
+
18
+ # Create and fit the scaler on the same data it was trained on.
19
+ # This ensures our predictions can be correctly inverse-transformed.
20
+ scaler = MinMaxScaler(feature_range=(0, 1))
21
+ scaler.fit(close_prices)
22
+
23
+ # The time step used during model training
24
+ TIME_STEP = 60
25
+
26
+ # --- 2. Define the Prediction Function ---
27
+
28
+ def predict_stock(days_to_forecast):
29
+ """
30
+ Takes the number of days to forecast as input, predicts future stock prices,
31
+ and returns them in a pandas DataFrame.
32
+ """
33
+
34
+ # Get the last TIME_STEP days from the original dataset to start the prediction
35
+ last_60_days = close_prices[-TIME_STEP:]
36
+
37
+ # Scale the input data using the same scaler
38
+ last_60_days_scaled = scaler.transform(last_60_days)
39
+
40
+ # This will be our initial input for prediction
41
+ X_input = last_60_days_scaled.reshape(1, TIME_STEP, 1)
42
+
43
+ # List to store the scaled predicted prices
44
+ predicted_prices_scaled = []
45
+
46
+ # Loop to predict for the number of days specified by the user
47
+ for i in range(int(days_to_forecast)):
48
+ # Predict the next day's price
49
+ predicted_price = model.predict(X_input)
50
+
51
+ # Append the scaled prediction to our list
52
+ predicted_prices_scaled.append(predicted_price[0, 0])
53
+
54
+ # Update the input sequence: remove the first day and add the new prediction at the end
55
+ new_input = np.append(X_input[0, 1:, 0], predicted_price[0, 0])
56
+ X_input = new_input.reshape(1, TIME_STEP, 1)
57
+
58
+ # Inverse transform the scaled predictions to get actual price values
59
+ final_predictions = scaler.inverse_transform(np.array(predicted_prices_scaled).reshape(-1, 1))
60
+
61
+ # Create a DataFrame to display the results nicely
62
+ forecast_df = pd.DataFrame({
63
+ "Day": range(1, int(days_to_forecast) + 1),
64
+ "Predicted Close Price (USD)": [f"${price[0]:,.2f}" for price in final_predictions]
65
+ })
66
+
67
+ return forecast_df
68
+
69
+ # --- 3. Create the Gradio Interface ---
70
+
71
+ with gr.Blocks(theme=gr.themes.Soft()) as iface:
72
+ gr.Markdown(
73
+ """
74
+ # Stock Price Forecaster: DataSynthis_ML_JobTask
75
+ This application uses a trained LSTM model to forecast future stock prices for TSLA.
76
+ Use the slider to select how many days into the future you'd like to predict.
77
+ """
78
+ )
79
+
80
+ days_input = gr.Slider(
81
+ minimum=1,
82
+ maximum=30,
83
+ step=1,
84
+ value=7,
85
+ label="Days to Forecast",
86
+ info="Select the number of days you want to forecast."
87
+ )
88
+
89
+ predict_button = gr.Button("Forecast Prices")
90
+
91
+ output_dataframe = gr.DataFrame(
92
+ headers=["Day", "Predicted Close Price (USD)"],
93
+ label="Forecasted Prices"
94
+ )
95
+
96
+ predict_button.click(
97
+ fn=predict_stock,
98
+ inputs=days_input,
99
+ outputs=output_dataframe
100
+ )
101
+
102
+ # --- 4. Launch the App ---
103
+ iface.launch()
104
+