-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsm.py
More file actions
455 lines (373 loc) · 19.1 KB
/
sm.py
File metadata and controls
455 lines (373 loc) · 19.1 KB
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import os
import warnings
warnings.filterwarnings("ignore")
import streamlit as st
import numpy as np
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error
# ─────────────────────────────────────────────
# Page Config
# ─────────────────────────────────────────────
st.set_page_config(
page_title="Stock Market Predictor",
page_icon="📈",
layout="wide",
initial_sidebar_state="expanded",
)
st.markdown("""
<style>
.metric-card {
background: #1e2130;
padding: 16px 20px;
border-radius: 10px;
border-left: 4px solid #4CAF50;
margin-bottom: 8px;
}
.stAlert { border-radius: 8px; }
</style>
""", unsafe_allow_html=True)
# ─────────────────────────────────────────────
# Data Loading
# ─────────────────────────────────────────────
@st.cache_data(show_spinner=False)
def load_data(ticker: str, start: str, end: str) -> pd.DataFrame:
df = yf.download(ticker, start=start, end=end, auto_adjust=True)
if df.empty:
return df
df.columns = df.columns.get_level_values(0)
return df
# ─────────────────────────────────────────────
# Technical Indicators
# ─────────────────────────────────────────────
def add_indicators(df: pd.DataFrame) -> pd.DataFrame:
close = df["Close"].squeeze()
df = df.copy()
# Moving Averages
df["MA20"] = close.rolling(20).mean()
df["MA50"] = close.rolling(50).mean()
df["MA200"] = close.rolling(200).mean()
# Bollinger Bands
std20 = close.rolling(20).std()
df["BB_Upper"] = df["MA20"] + 2 * std20
df["BB_Lower"] = df["MA20"] - 2 * std20
# RSI
delta = close.diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
rs = gain / loss
df["RSI"] = 100 - (100 / (1 + rs))
# MACD
ema12 = close.ewm(span=12, adjust=False).mean()
ema26 = close.ewm(span=26, adjust=False).mean()
df["MACD"] = ema12 - ema26
df["MACD_Signal"] = df["MACD"].ewm(span=9, adjust=False).mean()
df["MACD_Hist"] = df["MACD"] - df["MACD_Signal"]
return df
# ─────────────────────────────────────────────
# Sliding-Window Preprocessing
# ─────────────────────────────────────────────
def build_sequences(data: np.ndarray, time_step: int):
x, y = [], []
for i in range(time_step, len(data)):
x.append(data[i - time_step:i, 0])
y.append(data[i, 0])
return np.array(x).reshape(-1, time_step, 1), np.array(y)
def preprocess(series: np.ndarray, time_step: int, train_ratio: float = 0.80):
scaler = MinMaxScaler()
scaled = scaler.fit_transform(series.reshape(-1, 1))
split = int(len(scaled) * train_ratio)
train_data = scaled[:split]
test_data = scaled[split - time_step:] # keep look-back window
x_train, y_train = build_sequences(train_data, time_step)
x_test, y_test = build_sequences(test_data, time_step)
return x_train, y_train, x_test, y_test, scaler, split
# ─────────────────────────────────────────────
# ML Model — Gradient Boosting Regressor
# ─────────────────────────────────────────────
def create_model(n_estimators: int, max_depth: int, lr: float) -> GradientBoostingRegressor:
return GradientBoostingRegressor(
n_estimators=n_estimators,
max_depth=max_depth,
learning_rate=lr,
subsample=0.8,
random_state=42,
)
def train_model(model: GradientBoostingRegressor,
x_train: np.ndarray, y_train: np.ndarray) -> dict:
"""Fit the model and return a staged MSE loss curve."""
x_flat = x_train.reshape(len(x_train), -1)
model.fit(x_flat, y_train)
loss_curve = [
float(mean_squared_error(y_train, p))
for p in model.staged_predict(x_flat)
]
return {"loss": loss_curve}
def predict(model: GradientBoostingRegressor, x: np.ndarray) -> np.ndarray:
return model.predict(x.reshape(len(x), -1)).reshape(-1, 1)
# ─────────────────────────────────────────────
# Metrics
# ─────────────────────────────────────────────
def compute_metrics(actual: np.ndarray, predicted: np.ndarray) -> dict:
rmse = np.sqrt(mean_squared_error(actual, predicted))
mae = mean_absolute_error(actual, predicted)
mape = np.mean(np.abs((actual - predicted) / (actual + 1e-8))) * 100
direction_actual = np.sign(np.diff(actual.flatten()))
direction_pred = np.sign(np.diff(predicted.flatten()))
dir_acc = np.mean(direction_actual == direction_pred) * 100
return {"RMSE": rmse, "MAE": mae, "MAPE": mape, "Direction Accuracy": dir_acc}
# ─────────────────────────────────────────────
# Future Forecasting
# ─────────────────────────────────────────────
def forecast_future(model, last_sequence: np.ndarray, scaler, n_days: int) -> np.ndarray:
preds = []
seq = last_sequence.copy()
for _ in range(n_days):
inp = seq.reshape(1, len(seq), 1)
pred = float(predict(model, inp)[0, 0])
preds.append(pred)
seq = np.append(seq[1:], pred)
return scaler.inverse_transform(np.array(preds).reshape(-1, 1)).flatten()
# ─────────────────────────────────────────────
# Plotting helpers
# ─────────────────────────────────────────────
def plot_candlestick(df: pd.DataFrame, ticker: str) -> go.Figure:
fig = make_subplots(
rows=3, cols=1,
shared_xaxes=True,
vertical_spacing=0.04,
row_heights=[0.60, 0.20, 0.20],
subplot_titles=(f"{ticker} Price + Bollinger Bands", "RSI (14)", "MACD"),
)
# Candlestick
fig.add_trace(go.Candlestick(
x=df.index,
open=df["Open"].squeeze(), high=df["High"].squeeze(),
low=df["Low"].squeeze(), close=df["Close"].squeeze(),
name="OHLC", increasing_line_color="#26a69a", decreasing_line_color="#ef5350",
), row=1, col=1)
for ma, color in [("MA20", "#FFA726"), ("MA50", "#42A5F5"), ("MA200", "#AB47BC")]:
if ma in df.columns:
fig.add_trace(go.Scatter(x=df.index, y=df[ma].squeeze(), name=ma,
line=dict(color=color, width=1.2)), row=1, col=1)
# Bollinger Bands
fig.add_trace(go.Scatter(x=df.index, y=df["BB_Upper"].squeeze(), name="BB Upper",
line=dict(color="rgba(255,165,0,0.4)", dash="dot"), showlegend=False), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df["BB_Lower"].squeeze(), name="BB Lower",
fill="tonexty", fillcolor="rgba(255,165,0,0.05)",
line=dict(color="rgba(255,165,0,0.4)", dash="dot"), showlegend=False), row=1, col=1)
# RSI
fig.add_trace(go.Scatter(x=df.index, y=df["RSI"].squeeze(), name="RSI",
line=dict(color="#E91E63", width=1.5)), row=2, col=1)
fig.add_hline(y=70, line_dash="dash", line_color="red", opacity=0.5, row=2, col=1)
fig.add_hline(y=30, line_dash="dash", line_color="green", opacity=0.5, row=2, col=1)
# MACD
macd_colors = ["#26a69a" if v >= 0 else "#ef5350" for v in df["MACD_Hist"].squeeze()]
fig.add_trace(go.Bar(x=df.index, y=df["MACD_Hist"].squeeze(),
marker_color=macd_colors, name="MACD Hist"), row=3, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df["MACD"].squeeze(), name="MACD",
line=dict(color="#2196F3", width=1.2)), row=3, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df["MACD_Signal"].squeeze(), name="Signal",
line=dict(color="#FF9800", width=1.2)), row=3, col=1)
fig.update_layout(
height=700, template="plotly_dark",
xaxis_rangeslider_visible=False,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
margin=dict(l=10, r=10, t=40, b=10),
)
return fig
def plot_predictions(df_index, actual_train, actual_test, pred_test, split_idx: int,
time_step: int = 60,
future_dates=None, future_prices=None) -> go.Figure:
fig = go.Figure()
train_idx = df_index[time_step:split_idx] # skip look-back window rows
test_idx = df_index[split_idx:]
fig.add_trace(go.Scatter(x=train_idx, y=actual_train.flatten(),
name="Training Data", line=dict(color="#42A5F5", width=1.5)))
fig.add_trace(go.Scatter(x=test_idx, y=actual_test.flatten(),
name="Actual Price (Test)", line=dict(color="#66BB6A", width=2)))
fig.add_trace(go.Scatter(x=test_idx, y=pred_test.flatten(),
name="GBR Predicted Price", line=dict(color="#FFA726", width=2, dash="dot")))
if future_dates is not None and future_prices is not None:
fig.add_trace(go.Scatter(
x=future_dates, y=future_prices,
name="Future Forecast",
line=dict(color="#EF5350", width=2.5, dash="dash"),
mode="lines+markers",
marker=dict(size=5),
))
fig.add_vrect(
x0=future_dates[0], x1=future_dates[-1],
fillcolor="rgba(239,83,80,0.07)", line_width=0,
annotation_text="Forecast Zone", annotation_position="top left",
)
fig.update_layout(
title="Stock Price Prediction (Gradient Boosting)",
xaxis_title="Date", yaxis_title="Price (USD)",
height=500, template="plotly_dark",
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
margin=dict(l=10, r=10, t=60, b=10),
)
return fig
def plot_loss(history: dict) -> go.Figure:
fig = go.Figure()
fig.add_trace(go.Scatter(y=history["loss"], name="Training MSE (staged)",
line=dict(color="#42A5F5", width=2)))
fig.update_layout(
title="Model Training Loss (Gradient Boosting — staged MSE)",
xaxis_title="Estimator", yaxis_title="MSE Loss",
height=300, template="plotly_dark",
margin=dict(l=10, r=10, t=60, b=10),
)
return fig
# ─────────────────────────────────────────────
# Main App
# ─────────────────────────────────────────────
def main():
# ── Sidebar ──────────────────────────────
with st.sidebar:
st.title("⚙️Settings")
st.markdown("---")
st.subheader(" Stock Selection")
ticker = st.text_input("Ticker Symbol", "AAPL").upper().strip()
col1, col2 = st.columns(2)
with col1:
start_date = st.date_input("Start Date", pd.to_datetime("2018-01-01"))
with col2:
end_date = st.date_input("End Date", pd.to_datetime("2025-12-31"))
st.markdown("---")
st.subheader(" Model Hyperparameters")
time_step = st.slider("Look-back Window (days)", 30, 120, 60, 10)
n_estimators = st.slider("N Estimators (trees)", 50, 500, 200, 50)
max_depth = st.slider("Max Tree Depth", 2, 8, 4, 1)
learning_rate = st.slider("Learning Rate", 0.01, 0.30, 0.10, 0.01)
train_ratio = st.slider("Train Split (%)", 60, 90, 80, 5) / 100
st.markdown("---")
st.subheader(" Forecast Settings")
forecast_days = st.slider("Future Forecast (days)", 0, 90, 30, 5)
st.markdown("---")
run = st.button(" Run Prediction", use_container_width=True, type="primary")
# ── Header ───────────────────────────────
st.title("📈 Stock Market Prediction — ML")
st.caption("Gradient Boosting + sliding-window forecasting with full technical analysis.")
if not run:
st.info("Configure the settings in the sidebar and press **Run Prediction** to begin.")
st.image(
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/1280px-FullMoon2010.jpg",
width="stretch",
)
return
# ── Run Pipeline ─────────────────────────
progress = st.progress(0, text="Fetching data…")
with st.spinner(""):
# 1. Load Data
df_raw = load_data(ticker, str(start_date), str(end_date))
if df_raw.empty:
st.error(f"❌ No data found for **{ticker}**. Check the ticker symbol or date range.")
return
progress.progress(15, text="Computing technical indicators…")
# 2. Indicators
df = add_indicators(df_raw)
# 3. Company Info
try:
info = yf.Ticker(ticker).info
company_name = info.get("longName", ticker)
sector = info.get("sector", "N/A")
market_cap = info.get("marketCap", None)
except Exception:
company_name, sector, market_cap = ticker, "N/A", None
# ── KPI Row
st.markdown(f"## {company_name} ({ticker})")
close_series = df["Close"].squeeze()
latest = float(close_series.iloc[-1])
prev = float(close_series.iloc[-2])
change = latest - prev
pct = (change / prev) * 100
kpi1, kpi2, kpi3, kpi4, kpi5 = st.columns(5)
kpi1.metric("Latest Close", f"${latest:,.2f}", f"{change:+.2f} ({pct:+.2f}%)")
kpi2.metric("52-Week High", f"${float(close_series.tail(252).max()):,.2f}")
kpi3.metric("52-Week Low", f"${float(close_series.tail(252).min()):,.2f}")
kpi4.metric("Sector", sector)
kpi5.metric("Market Cap", f"${market_cap/1e9:.2f}B" if market_cap else "N/A")
st.markdown("---")
# ── Tab layout ──────────────────────
tab_chart, tab_model, tab_forecast = st.tabs(
[" Technical Chart", " ML Model", " Forecast"]
)
# Tab 1 — Candlestick + Indicators
with tab_chart:
st.plotly_chart(plot_candlestick(df, ticker), use_container_width=True)
with st.expander("📋 Raw Data"):
st.dataframe(df.tail(50).sort_index(ascending=False), use_container_width=True)
progress.progress(30, text="Preprocessing data…")
# Tab 2 — ML Model
with tab_model:
close_vals = close_series.values.astype(float)
if len(close_vals) < time_step + 50:
st.error("Not enough data for the selected look-back window. Reduce window or extend date range.")
return
x_train, y_train, x_test, y_test, scaler, split_idx = preprocess(
close_vals, time_step, train_ratio
)
progress.progress(45, text="Training Gradient Boosting model…")
model = create_model(n_estimators, max_depth, learning_rate)
history = train_model(model, x_train, y_train)
progress.progress(80, text="Evaluating model…")
# Predictions
pred_train = scaler.inverse_transform(predict(model, x_train))
pred_test = scaler.inverse_transform(predict(model, x_test))
actual_train = scaler.inverse_transform(y_train.reshape(-1, 1))
actual_test = scaler.inverse_transform(y_test.reshape(-1, 1))
metrics = compute_metrics(actual_test, pred_test)
# Metrics row
m1, m2, m3, m4 = st.columns(4)
m1.metric("RMSE", f"${metrics['RMSE']:.2f}")
m2.metric("MAE", f"${metrics['MAE']:.2f}")
m3.metric("MAPE", f"{metrics['MAPE']:.2f}%")
m4.metric("Direction Accuracy", f"{metrics['Direction Accuracy']:.1f}%")
st.plotly_chart(
plot_predictions(
df.index, actual_train, actual_test, pred_test, split_idx,
time_step=time_step
),
use_container_width=True,
)
st.plotly_chart(plot_loss(history), use_container_width=True)
with st.expander("📐 Model Parameters"):
params = model.get_params()
info_md = "\n".join(f"- **{k}**: `{v}`" for k, v in params.items())
st.markdown(info_md)
# Tab 3 — Forecast
with tab_forecast:
if forecast_days > 0:
progress.progress(90, text="Generating future forecast…")
last_seq = scaler.transform(close_vals[-time_step:].reshape(-1, 1)).flatten()
future_prices = forecast_future(model, last_seq, scaler, forecast_days)
last_date = df.index[-1]
future_dates = pd.bdate_range(start=last_date, periods=forecast_days + 1)[1:]
st.plotly_chart(
plot_predictions(
df.index, actual_train, actual_test, pred_test, split_idx,
time_step=time_step,
future_dates=future_dates, future_prices=future_prices,
),
use_container_width=True,
)
# Forecast table
forecast_df = pd.DataFrame({
"Date": future_dates.strftime("%Y-%m-%d"),
"Forecasted Price ($)": [f"{p:.2f}" for p in future_prices],
"Change from Today ($)": [f"{p - latest:+.2f}" for p in future_prices],
"Change from Today (%)": [f"{(p - latest) / latest * 100:+.2f}%" for p in future_prices],
})
st.dataframe(forecast_df, use_container_width=True, hide_index=True)
else:
st.info("Set **Future Forecast** days > 0 in the sidebar to see a forecast.")
progress.progress(100, text="Done!")
st.success(f"✅ Analysis complete for **{ticker}**")
if __name__ == "__main__":
main()