Mmanikandan commited on
Commit
4f283e7
Β·
verified Β·
1 Parent(s): 3d823a0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import pandas as pd
4
+ import datetime
5
+ import yfinance as yf
6
+ import streamlit as st
7
+ from sklearn.preprocessing import MinMaxScaler
8
+ from tensorflow.keras.models import load_model
9
+ import matplotlib.pyplot as plt
10
+
11
+ # ── Disable GPU so TensorFlow runs on CPU ────────────────────────────────
12
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
13
+
14
+ # ── Mapping sectors to .h5 model filenames ───────────────────────────────
15
+ MODEL_DIR = "models/"
16
+ sector_model_map = {
17
+ "Technology": "Technology.h5",
18
+ "Financial Services": "finance_model.h5",
19
+ "Healthcare": "Healthcare.h5",
20
+ "Energy": "Energy.h5",
21
+ "Consumer Defensive": "Consumer Goods.h5",
22
+ "Consumer Cyclical": "Consumer Services.h5",
23
+ "Industrials": "industrials.h5",
24
+ "Real Estate": "Real Estate.h5",
25
+ "Communication Services": "communication.h5",
26
+ "Utilities": "Utilities.h5",
27
+ "Basic Materials": "Material.h5"
28
+ }
29
+
30
+ # ── Get sector via Yahoo Finance ─────────────────────────────────────────
31
+ def get_sector(ticker: str) -> str:
32
+ try:
33
+ info = yf.Ticker(ticker).info
34
+ return info.get("sector", "Technology")
35
+ except Exception:
36
+ return "Technology"
37
+
38
+ # ── Load Keras .h5 model on CPU without compiling ────────────────────────
39
+ def load_model_keras(sector: str):
40
+ model_file = sector_model_map.get(sector)
41
+ if not model_file:
42
+ return None
43
+ path = os.path.join(MODEL_DIR, model_file)
44
+ if not os.path.exists(path):
45
+ return None
46
+ return load_model(path, compile=False)
47
+
48
+ # ── Fetch historical stock data ──────────────────────────────────────────
49
+ def fetch_stock_data(ticker: str, days: int = 50) -> pd.DataFrame | None:
50
+ end_date = datetime.datetime.today()
51
+ start_date = end_date - datetime.timedelta(days=days * 2)
52
+ df = yf.download(ticker, start=start_date, end=end_date)
53
+ return df.tail(days).reset_index() if not df.empty else None
54
+
55
+ # ── Scale features and pad if needed ─────────────────────────────────────
56
+ def prepare_data(df: pd.DataFrame):
57
+ feature_cols = ["Open", "High", "Low", "Close", "Volume"]
58
+ data = df[feature_cols].values
59
+ scaler = MinMaxScaler()
60
+ data_scaled = scaler.fit_transform(data)
61
+
62
+ # Pad to 12 features
63
+ expected_features = 12
64
+ padded_data = np.pad(
65
+ data_scaled,
66
+ ((0, 0), (0, expected_features - data_scaled.shape[1])),
67
+ mode='constant'
68
+ )
69
+
70
+ return padded_data, scaler
71
+
72
+ # ── Predict next N days ──────────────────────────────────────────────────
73
+ def predict_next_days(model, data_scaled, seq_length: int, scaler, days: int = 5):
74
+ preds = []
75
+ last_seq = np.expand_dims(data_scaled[-seq_length:], axis=0)
76
+ last_known_row = data_scaled[-1].copy()
77
+ expected_features = data_scaled.shape[1]
78
+
79
+ for _ in range(days):
80
+ scaled_pred = model.predict(last_seq, verbose=0)[0, 0]
81
+ new_row = last_known_row.copy()
82
+ if expected_features >= 4:
83
+ new_row[3] = scaled_pred # 'Close'
84
+
85
+ inv_input = new_row[:5]
86
+ inv_scaled = scaler.inverse_transform([inv_input])[0]
87
+ actual_close = inv_scaled[3]
88
+ preds.append(actual_close)
89
+
90
+ padded = np.pad(inv_scaled, (0, expected_features-5), mode='constant')
91
+ last_seq = np.concatenate([last_seq[:,1:,:], padded.reshape(1,1,-1)], axis=1)
92
+ last_known_row = padded
93
+
94
+ return preds
95
+
96
+ # ── Streamlit UI ─────────────────────────────────────────────────────────
97
+ st.set_page_config(page_title="πŸ“ˆ Stock Predictor", layout="centered")
98
+ st.title("πŸ“Š Sector‑Based Stock Price Predictor ")
99
+
100
+ ticker = st.text_input("Enter Stock Ticker (e.g. AAPL, MSFT, TSLA):").upper()
101
+ if st.button("Predict"):
102
+ if not ticker:
103
+ st.warning("⚠️ Please enter a stock ticker.")
104
+ st.stop()
105
+
106
+ df = fetch_stock_data(ticker)
107
+ if df is None or len(df) < 50:
108
+ st.error("❌ Not enough data to predict. Try another ticker.")
109
+ st.stop()
110
+
111
+ sector = get_sector(ticker)
112
+ model = load_model_keras(sector)
113
+ if model is None:
114
+ st.error(f"❌ No model found for sector: {sector}")
115
+ st.stop()
116
+ st.success(f"βœ… Sector: {sector}")
117
+
118
+ data_scaled, scaler = prepare_data(df)
119
+ preds = predict_next_days(model, data_scaled, seq_length=50, scaler=scaler, days=5)
120
+
121
+ # Prepare dates
122
+ df["Date"] = pd.to_datetime(df["Date"])
123
+ actual_dates = df["Date"].tail(30)
124
+ actual_prices = df["Close"].tail(30).values
125
+
126
+ last_date = actual_dates.iloc[-1]
127
+ future_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=5, freq="B")
128
+
129
+ # Show result table
130
+ result_df = pd.DataFrame({
131
+ "Date": future_dates,
132
+ "Predicted Close Price": np.round(preds, 2)
133
+ })
134
+ st.write(result_df)
135
+
136
+ # Plot with Matplotlib
137
+ fig, ax = plt.subplots(figsize=(10, 5))
138
+ # Past 30 days
139
+ ax.plot(actual_dates, actual_prices,
140
+ color="blue", marker="o", linestyle="-", label="Actual (30d)", markersize=8)
141
+ # Next 5 days
142
+ ax.plot(future_dates, preds,
143
+ color="red", marker="o", linestyle="-", label="Predicted (5d)", markersize=8)
144
+ # Formatting
145
+ ax.set_title(f"{ticker} Close Price: Last 30 Days & Next 5 Days Forecast")
146
+ ax.set_xlabel("Date")
147
+ ax.set_ylabel("Close Price")
148
+ ax.legend()
149
+ fig.autofmt_xdate()
150
+ ax.grid(True)
151
+
152
+ st.pyplot(fig)
153
+
models/Consumer Goods.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9514605eda1e29a8ce7661d51ff7679fc58b4a91b705baec42bb8876c57de09c
3
+ size 1611744
models/Consumer Services.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1278246ded80173c42fce1eafcb3680c30324abd744887f9cd5af011136649a
3
+ size 1611808
models/Energy.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:644deb96cbb912d987f7885572ea58d47757f3d232e391e53c0e8d0d7f699905
3
+ size 1611744
models/Healthcare.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e70abe03522cec27eb4eef00caadfe44950cfae07d78ac748a61dc0b317e72e
3
+ size 1611744
models/Material.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4eeea5515544bfdac2b73a815711d3889fda8282269c3554c02f46c33f1a4cf
3
+ size 1611808
models/Real Estate.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25606d9b7a9d67e8a389294e63a1254f3e32a0fa84cced94ffdfb0520cd7e4a8
3
+ size 1611808
models/Technology.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f708e973bd025439c61786849c190a5a7663e7b4efe80e682471e858b9b95f6
3
+ size 1613640
models/Utilities.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57babfe3b7edbc4afdd44c3eae25ba4e896ae40c363a2e3eebc49b3813f8eabb
3
+ size 1611808
models/communication.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1851bf2ad94764cf60a53bea705b36bf064791fc127e11d360620f5306d697b
3
+ size 1611808
models/finance_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26937b0f6b8eef46e2f9737c78dfa669c0c3b0e324f054b2a061bdd4523728c1
3
+ size 1611744
models/industrials.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fcba5c9f11d2a96a5d8bf7c4f1816b2a4ad8d9758b0ad9c8f20f01bbd3db322
3
+ size 1611808
requirements.txt ADDED
Binary file (4.33 kB). View file