AliHamza852 commited on
Commit
a68dbf2
·
verified ·
1 Parent(s): 2c9919d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ import gradio as gr
5
+ import joblib
6
+
7
+ SEQUENCE_LENGTH = 20
8
+ INPUT_SIZE = 1
9
+ OUTPUT_SIZE = 1
10
+ HIDDEN_SIZE = 50
11
+ device = torch.device('cpu')
12
+
13
+ class SimpleLSTM(nn.Module):
14
+ def __init__(self, input_size, hidden_size, output_size):
15
+ super(SimpleLSTM, self).__init__()
16
+ self.hidden_size = hidden_size
17
+ self.lstm = nn.LSTM(
18
+ input_size=input_size,
19
+ hidden_size=hidden_size,
20
+ batch_first=True
21
+ )
22
+ self.linear = nn.Linear(hidden_size, output_size)
23
+
24
+ def forward(self, x):
25
+ lstm_out, _ = self.lstm(x)
26
+ last_time_step_output = lstm_out[:, -1, :]
27
+ prediction = self.linear(last_time_step_output)
28
+ return prediction
29
+
30
+ model_path = 'stock_model_weights.pth'
31
+ model = SimpleLSTM(INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE).to(device)
32
+ model.load_state_dict(torch.load(model_path, map_location=device))
33
+ model.eval()
34
+
35
+ scaler_path = "scaler.joblib"
36
+ scaler = joblib.load(scaler_path)
37
+
38
+ def predict_stock(input_text):
39
+ try:
40
+ numbers = [float(n.strip()) for n in input_text.split(',')]
41
+
42
+ if len(numbers) != SEQUENCE_LENGTH:
43
+ return f"Error: Please enter exactly {SEQUENCE_LENGTH} numbers."
44
+
45
+ input_data = np.array(numbers).reshape(-1, 1)
46
+
47
+ scaled_input = scaler.transform(input_data)
48
+
49
+ tensor_input = torch.from_numpy(scaled_input).float().reshape(1, SEQUENCE_LENGTH, 1).to(device)
50
+
51
+ with torch.no_grad():
52
+ scaled_prediction = model(tensor_input)
53
+
54
+ prediction = scaler.inverse_transform(scaled_prediction.cpu().numpy())
55
+
56
+ return f"Predicted Next Day's Price: ${prediction[0][0]:.2f}"
57
+
58
+ except Exception as e:
59
+ return f"An error occurred: {str(e)}"
60
+
61
+ demo = gr.Interface(
62
+ fn=predict_stock,
63
+ inputs=gr.Textbox(
64
+ label=f"Input Sequence (Last {SEQUENCE_LENGTH} Days' Close Prices)",
65
+ placeholder="Enter {SEQUENCE_LENGTH} numbers, separated by commas..."
66
+ ),
67
+ outputs=gr.Textbox(label="Prediction"),
68
+ title="Stock Price Predictor",
69
+ description="Enter the last 20 closing prices to predict the next day's price.",
70
+ allow_flagging="never"
71
+ )
72
+
73
+ demo.launch()