-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
774 lines (690 loc) · 29.8 KB
/
app.py
File metadata and controls
774 lines (690 loc) · 29.8 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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
import os
import time
import math
from datetime import datetime, timedelta, timezone
import numpy as np
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
import streamlit as st
# Optional/soft imports guarded at runtime
try:
from kiteconnect import KiteConnect
except Exception:
KiteConnect = None
# MGARCH via arch, with safe fallback
try:
from arch.univariate import ConstantMean, GARCH as UGARCH, Normal
from arch.multivariate import DynamicConditionalCorrelation as DCC
ARCH_AVAILABLE = True
except Exception:
ARCH_AVAILABLE = False
# -----------------------------
# App Constants
# -----------------------------
APP_TITLE = "Volatility-Aware Trading Assistant"
SECTORS = {
"Nifty 50": {"symbol": "NIFTY 50"},
"Nifty IT": {"symbol": "NIFTY IT"},
"Nifty FMCG": {"symbol": "NIFTY FMCG"},
}
TIMEZONE_IST = timezone(timedelta(hours=5, minutes=30))
# -----------------------------
# Streamlit Page Config & Theming
# -----------------------------
st.set_page_config(
page_title=APP_TITLE,
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded",
)
# Inject custom CSS for modern finance dark theme (glassmorphism style)
CUSTOM_CSS = """
<style>
:root {
--bg: #0a1020; /* deep navy */
--card: rgba(20, 28, 48, 0.6); /* glass */
--accent: #00c28b; /* emerald */
--accent-2: #f0b90b; /* gold */
--text: #e6edf3;
--muted: #9aa4b2;
}
/* Background */
.block-container {
padding-top: 1.5rem;
}
/* Header bar */
.header-bar {
position: sticky;
top: 0;
z-index: 1000;
background: linear-gradient(135deg, rgba(10,16,32,0.95) 0%, rgba(20,28,48,0.75) 100%);
border: 1px solid rgba(255,255,255,0.06);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 16px 20px;
box-shadow: 0 6px 20px rgba(0,0,0,0.35);
margin-bottom: 18px;
}
/* Cards */
.card {
background: var(--card);
border: 1px solid rgba(255,255,255,0.06);
border-radius: 16px;
padding: 16px;
box-shadow: 0 6px 18px rgba(0,0,0,0.25);
}
.kpi {
display: flex; align-items: center; gap: 12px;
padding: 14px 16px; border-radius: 14px;
background: linear-gradient(180deg, rgba(0,0,0,0.15), rgba(0,0,0,0.35));
border: 1px solid rgba(255,255,255,0.06);
}
.kpi .icon {
width: 42px; height: 42px; border-radius: 12px;
display: grid; place-items: center; font-size: 18px;
background: rgba(0,0,0,0.3);
color: var(--accent);
}
.kpi .value { font-size: 22px; color: var(--text); font-weight: 700; }
.kpi .label { font-size: 12px; color: var(--muted); }
/* Tabs accent */
.stTabs [data-baseweb="tab-list"] {
gap: 8px;
}
.stTabs [data-baseweb="tab"] {
background: rgba(255,255,255,0.05);
border-radius: 12px;
padding-top: 8px; padding-bottom: 8px;
}
/* Sidebar */
section[data-testid="stSidebar"] {
background: linear-gradient(180deg, rgba(10,16,32,1) 0%, rgba(10,16,32,0.75) 100%);
border-right: 1px solid rgba(255,255,255,0.05);
}
/* Footer */
.footer {
text-align: center; color: var(--muted); font-size: 12px; margin-top: 30px;
}
</style>
"""
st.markdown(CUSTOM_CSS, unsafe_allow_html=True)
# -----------------------------
# Utilities
# -----------------------------
@st.cache_data(show_spinner=False)
def compute_rolling_vol(df_prices: pd.DataFrame, window: int = 20) -> pd.DataFrame:
returns = df_prices.pct_change().dropna()
vol = returns.rolling(window).std() * np.sqrt(252) * 100.0
return vol
@st.cache_data(show_spinner=False)
def compute_correlations(df_prices: pd.DataFrame, window: int = 20) -> pd.DataFrame:
returns = df_prices.pct_change().dropna()
corr_ts = returns.rolling(window).corr().dropna()
# corr_ts has MultiIndex (date, symbol)
return corr_ts
def ist_now_str() -> str:
now = datetime.now(TIMEZONE_IST)
return now.strftime("%d %b %Y, %I:%M:%S %p IST")
# -----------------------------
# Zerodha (Kite Connect) helpers
# -----------------------------
def get_kite_client(api_key: str, access_token: str | None = None):
if KiteConnect is None:
return None
kite = KiteConnect(api_key=api_key)
if access_token:
kite.set_access_token(access_token)
return kite
@st.cache_data(show_spinner=False)
def kite_find_instrument_token(_kite, tradingsymbol: str) -> int | None:
try:
instruments = _kite.instruments(exchange="NSE")
df = pd.DataFrame(instruments)
# Indices often have segment 'INDICES' and exchange 'NSE'
candidates = df[(df["segment"].str.contains("INDICES", na=False)) &
(df["tradingsymbol"].str.fullmatch(tradingsymbol, case=False, na=False))]
if not candidates.empty:
return int(candidates.iloc[0]["instrument_token"])
# Fallback: partial match by name
candidates = df[df["name"].str.contains(tradingsymbol.split()[0], na=False)]
if not candidates.empty:
return int(candidates.iloc[0]["instrument_token"])
except Exception:
return None
return None
@st.cache_data(show_spinner=True)
def kite_get_history(_kite, instrument_token: int, from_dt: datetime, to_dt: datetime, interval: str = "day") -> pd.DataFrame:
try:
data = _kite.historical_data(instrument_token, from_dt, to_dt, interval, oi=False)
df = pd.DataFrame(data)
if not df.empty:
df["date"] = pd.to_datetime(df["date"])
df.set_index("date", inplace=True)
return df
except Exception:
return pd.DataFrame()
# -----------------------------
# Data sourcing with demo fallback
# -----------------------------
@st.cache_data(show_spinner=True)
def load_prices(_kite, days: int = 400, interval: str = "day") -> pd.DataFrame:
end = datetime.now(TIMEZONE_IST).replace(hour=15, minute=30, second=0, microsecond=0)
start = end - timedelta(days=days)
frames = []
for label, meta in SECTORS.items():
symbol = meta["symbol"]
if _kite is not None:
token = kite_find_instrument_token(_kite, symbol)
if token:
df = kite_get_history(_kite, token, start, end, interval=interval)
if not df.empty:
frames.append(df[["close"]].rename(columns={"close": label}))
continue
# Demo fallback: synthetic but stable series to keep UI functional
idx = pd.date_range(start=start, end=end, freq="B")
rng = np.random.default_rng(abs(hash(label)) % (2**32))
steps = rng.normal(loc=0.0004, scale=0.01, size=len(idx))
prices = 1000 * np.exp(np.cumsum(steps))
frames.append(pd.DataFrame({label: prices}, index=idx))
prices = pd.concat(frames, axis=1).sort_index().ffill().dropna()
return prices
# -----------------------------
# MGARCH (DCC) Forecasting with safe fallback
# -----------------------------
@st.cache_data(show_spinner=True)
def forecast_volatility_mgarch(prices: pd.DataFrame, horizon_days: int = 1):
returns = prices.pct_change().dropna() * 100.0 # percent returns for arch
cols = list(returns.columns)
if ARCH_AVAILABLE and returns.shape[1] >= 2:
try:
# Fit univariate mean/vol models for each series
fitted = []
for c in cols:
cm = ConstantMean(returns[c].dropna())
cm.volatility = UGARCH(1, 1)
cm.distribution = Normal()
res = cm.fit(disp="off")
fitted.append(res)
dcc = DCC(fitted)
dcc_res = dcc.fit(disp="off")
# Next-step conditional variances (percent^2). Convert to annualized volatility %
fc_var = {}
for i, c in enumerate(cols):
# Extract last conditional volatility for series i (in %)
h_t = dcc_res.conditional_volatility[:, i]
last_sigma = h_t[-1]
# Forecast scale: simple sqrt(horizon)
fc_sigma = last_sigma * math.sqrt(horizon_days)
# Annualize
annual_sigma = fc_sigma * math.sqrt(252)
fc_var[c] = float(max(0.0, annual_sigma))
# Correlation matrix (last period)
corr_mat = pd.DataFrame(
dcc_res.corr[-1], index=cols, columns=cols
)
return fc_var, corr_mat
except Exception:
pass
# Fallback: univariate GARCH for each series, correlations via recent Pearson
fc_var = {}
window = 60
for c in cols:
r = returns[c].dropna()
if ARCH_AVAILABLE and len(r) > 100:
try:
cm = ConstantMean(r)
cm.volatility = UGARCH(1, 1)
cm.distribution = Normal()
res = cm.fit(disp="off")
sigma = res.conditional_volatility.iloc[-1]
fc_sigma = sigma * math.sqrt(horizon_days)
annual_sigma = fc_sigma * math.sqrt(252)
fc_var[c] = float(max(0.0, annual_sigma))
continue
except Exception:
pass
# naive fallback: rolling std
sigma = r.tail(window).std()
annual_sigma = float(sigma * math.sqrt(252))
fc_var[c] = annual_sigma
corr_mat = returns.tail(window).corr()
return fc_var, corr_mat
# -----------------------------
# Risk and Sizing Utilities
# -----------------------------
def compute_stop_loss(vol_pct: float, multiplier: float = 1.2) -> float:
# Simple: SL% proportional to forecast vol
return round(vol_pct * multiplier, 2)
def suggest_position_size(capital: float, risk_per_trade_pct: float, sl_pct: float, price: float) -> int:
# Risk per trade in currency
risk_amt = max(1.0, capital * (risk_per_trade_pct / 100.0))
# Amount at risk per unit
unit_risk = price * (sl_pct / 100.0)
if unit_risk <= 0:
return 0
qty = int(risk_amt // unit_risk)
return max(0, qty)
# -----------------------------
# UI Components
# -----------------------------
def header_bar():
col1, col2 = st.columns([0.7, 0.3])
with col1:
st.markdown(f"""
<div class="header-bar">
<div style="display:flex;align-items:center;gap:12px;">
<div style="font-size:20px;">📈</div>
<div>
<div style="font-size:22px;font-weight:800;color:#e6edf3;">{APP_TITLE}</div>
<div style="font-size:12px;color:#9aa4b2;">Volatility forecasting • Risk insights • Trade simulation</div>
</div>
</div>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown(
f"<div class='card' style='text-align:right;'>🕒 <b>{ist_now_str()}</b></div>",
unsafe_allow_html=True,
)
def kpi_card(icon: str, label: str, value: str, tooltip: str = ""):
st.markdown(
f"""
<div class="kpi" title="{tooltip}">
<div class="icon">{icon}</div>
<div>
<div class="value">{value}</div>
<div class="label">{label}</div>
</div>
</div>
""",
unsafe_allow_html=True,
)
# -----------------------------
# Sidebar Controls
# -----------------------------
def sidebar_controls():
with st.sidebar:
st.markdown("### ⚙️ Settings")
st.markdown("— Model, data, and trading parameters")
# Kite Connect login
st.markdown("#### 🔐 Zerodha Login")
api_key = st.text_input("API Key", type="default", key="api_key")
api_secret = st.text_input("API Secret", type="password", key="api_secret")
kite = None
access_token = st.session_state.get("kite_access_token")
if api_key:
kite = get_kite_client(api_key, access_token)
if kite and not access_token:
try:
login_url = kite.login_url() if hasattr(kite, "login_url") else None
except Exception:
login_url = None
if login_url:
st.markdown(f"[Open Kite Login]({login_url})")
request_token = st.text_input("Paste Request Token after login", type="default")
if st.button("Generate Access Token") and request_token and api_secret:
try:
data = kite.generate_session(request_token, api_secret=api_secret)
kite.set_access_token(data["access_token"])
st.session_state["kite_access_token"] = data["access_token"]
st.success("Kite access token set.")
except Exception as e:
st.error(f"Kite auth failed: {e}")
else:
st.info("Enter API key/secret to enable live Zerodha data and real trading.")
st.markdown("---")
st.markdown("#### 📊 Model Settings")
vol_window = st.slider("Rolling Volatility Window (days)", 10, 120, 20, 1, help="Window used for rolling volatility and correlations.")
conf_level = st.slider("Confidence Level (%)", 80, 99, 95, 1, help="For risk interpretations (display only).")
st.markdown("- Data Interval")
data_interval = st.selectbox("Data Interval", ["day", "15minute", "5minute", "minute"], index=0, help="Historical candle interval to fetch (requires Kite for intraday).")
days_back = st.number_input("Lookback Days", min_value=30, max_value=1500, value=420, step=10)
st.markdown("---")
st.markdown("#### 🧠 Strategy Parameters")
risk_tolerance = st.slider("Risk per Trade (%)", 0.1, 5.0, 1.0, 0.1, help="Percentage of capital risked per trade.")
sl_multiplier = st.slider("Stop-loss Multiplier", 0.5, 3.0, 1.2, 0.1, help="Stop-loss as multiple of forecast volatility.")
st.markdown("---")
st.markdown("#### 💱 Tradable Mapping (for Real Orders)")
st.caption("Map indices to tradable symbols like ETFs or futures.")
map_nifty = st.text_input("Nifty 50 →", value="NIFTYBEES", help="e.g., NIFTYBEES")
map_it = st.text_input("Nifty IT →", value="ITBEES", help="e.g., ITBEES")
map_fmcg = st.text_input("Nifty FMCG →", value="FMCGBEES", help="e.g., FMCGBEES")
st.markdown("---")
st.markdown("#### 🚨 Alerts")
enable_alerts = st.toggle("Enable Alerts", value=False)
vol_spike_thresh = st.number_input("Volatility Spike Threshold (%)", min_value=0.0, value=35.0, step=0.5, help="Trigger if any sector forecast vol exceeds this.")
corr_break_thresh = st.slider("Correlation Break |corr| <", 0.0, 1.0, 0.2, 0.05, help="Trigger if absolute correlation drops below this.")
telegram_url = st.text_input("Telegram/Webhook URL (optional)", value="", help="POST JSON to this URL on alert.")
if enable_alerts and telegram_url and st.button("Test Alert Now"):
try:
import requests
requests.post(telegram_url, json={"message": "Test alert from Volatility-Aware Trading Assistant."}, timeout=5)
st.success("Test alert sent.")
except Exception as e:
st.error(f"Failed to send test alert: {e}")
st.markdown("---")
st.markdown("#### 🔄 Data Refresh")
auto_refresh = st.toggle("Auto-refresh every minute", value=False)
if st.button("Manual Refresh"):
st.cache_data.clear()
st.rerun()
return {
"kite": kite,
"vol_window": vol_window,
"conf_level": conf_level,
"data_interval": data_interval,
"days_back": int(days_back),
"risk_tolerance": risk_tolerance,
"sl_multiplier": sl_multiplier,
"auto_refresh": auto_refresh,
"mapping": {"Nifty 50": map_nifty, "Nifty IT": map_it, "Nifty FMCG": map_fmcg},
"alerts": {
"enabled": enable_alerts,
"vol_spike": vol_spike_thresh,
"corr_break": corr_break_thresh,
"webhook": telegram_url,
},
}
# -----------------------------
# Visualizations
# -----------------------------
def plot_vol_trends(prices: pd.DataFrame, vol_window: int):
vol = compute_rolling_vol(prices, vol_window)
fig = go.Figure()
for c in vol.columns:
fig.add_trace(go.Scatter(x=vol.index, y=vol[c], mode="lines", name=c))
fig.update_layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
height=420,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
margin=dict(l=10, r=10, t=30, b=10),
)
fig.update_yaxes(title_text="Rolling Volatility (%)")
st.plotly_chart(fig, use_container_width=True)
def plot_corr_heatmap_over_time(prices: pd.DataFrame, vol_window: int):
returns = prices.pct_change().dropna()
# Build correlation over time snapshot every N days
step = max(5, vol_window // 2)
times, mats = [], []
for i in range(vol_window, len(returns), step):
window_ret = returns.iloc[max(0, i - vol_window):i]
corr = window_ret.corr()
mats.append(corr)
times.append(returns.index[i-1])
if not mats:
st.info("Not enough data to compute correlation heatmap.")
return
# Animate using frames
zmax = 1.0
zmin = -1.0
base = mats[0]
fig = go.Figure(
data=go.Heatmap(z=base.values, x=base.columns, y=base.index, zmin=zmin, zmax=zmax, colorscale="Viridis"),
layout=go.Layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
height=420, margin=dict(l=10, r=10, t=30, b=10),
updatemenus=[dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None, {"frame": {"duration": 600, "redraw": True}, "fromcurrent": True}])])]
),
frames=[go.Frame(data=[go.Heatmap(z=m.values, x=m.columns, y=m.index, zmin=zmin, zmax=zmax, colorscale="Viridis")], name=f"frame{k}") for k, m in enumerate(mats)]
)
st.plotly_chart(fig, use_container_width=True)
def plot_corr_over_time(prices: pd.DataFrame, vol_window: int):
returns = prices.pct_change().dropna()
cols = returns.columns
# Use pairwise rolling correlation between first and others for a simple view
base = cols[0]
fig = go.Figure()
for c in cols[1:]:
series = returns[base].rolling(vol_window).corr(returns[c])
fig.add_trace(go.Scatter(x=series.index, y=series, mode="lines", name=f"{base} vs {c}"))
fig.update_layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
height=380, margin=dict(l=10, r=10, t=30, b=10),
)
fig.update_yaxes(range=[-1, 1])
st.plotly_chart(fig, use_container_width=True)
# -----------------------------
# Trade Simulation
# -----------------------------
@st.cache_resource(show_spinner=False)
def get_trade_store():
return [] # simple in-memory store
def simulate_trades(prices: pd.DataFrame, forecasts: dict, capital: float, risk_pct: float, sl_mult: float):
# Simple rule: go long next day if forecast vol < median vol; else no trade
last_prices = prices.iloc[-1]
median_vol = np.median(list(forecasts.values())) if forecasts else 0
trades = []
for name, price in last_prices.items():
fc_vol = forecasts.get(name, 0)
action = "BUY" if fc_vol <= median_vol else "HOLD"
sl_pct = compute_stop_loss(fc_vol, sl_mult)
qty = suggest_position_size(capital, risk_pct, sl_pct, price)
if action == "BUY" and qty > 0:
trades.append({
"time": ist_now_str(),
"symbol": name,
"action": action,
"price": round(float(price), 2),
"forecast_vol_%": round(fc_vol, 2),
"stop_loss_%": sl_pct,
"qty": int(qty),
})
return trades
def place_real_orders(kite, trades: list, mapping: dict):
results = []
if kite is None:
return results
for t in trades:
try:
# Place a simple market CNC buy order (indices are not directly tradable; in practice map to ETFs/futures)
tradable = mapping.get(t["symbol"]) or mapping.get(str(t["symbol"]))
if not tradable:
res = {"symbol": t["symbol"], "status": "skipped", "reason": "No mapping provided."}
else:
# Note: Adjust product/variety/exchange per your preference
order = kite.place_order(
variety=getattr(kite, "VARIETY_REGULAR", "regular"),
exchange="NSE",
tradingsymbol=tradable,
transaction_type=getattr(kite, "TRANSACTION_TYPE_BUY", "BUY"),
quantity=int(t.get("qty", 1)),
product=getattr(kite, "PRODUCT_CNC", "CNC"),
order_type=getattr(kite, "ORDER_TYPE_MARKET", "MARKET"),
price=None,
)
res = {"symbol": t["symbol"], "mapped_to": tradable, "status": "placed", "order": order}
except Exception as e:
res = {"symbol": t["symbol"], "status": "error", "error": str(e)}
results.append(res)
return results
def maybe_send_alerts(alert_cfg: dict, forecasts: dict, corr_mat: pd.DataFrame):
if not alert_cfg or not alert_cfg.get("enabled"):
return
messages = []
# Volatility spike
vs = alert_cfg.get("vol_spike", 0)
if forecasts:
for name, v in forecasts.items():
if v >= vs > 0:
messages.append(f"Volatility spike: {name} {v:.2f}% >= {vs:.2f}%")
# Correlation break
cb = alert_cfg.get("corr_break", 0.0)
if corr_mat is not None and not corr_mat.empty and cb > 0:
pairs = []
for i in corr_mat.index:
for j in corr_mat.columns:
if i < j:
pairs.append((i, j, corr_mat.loc[i, j]))
for i, j, c in pairs:
if abs(float(c)) < cb:
messages.append(f"Correlation break: |corr({i},{j})|={abs(float(c)):.2f} < {cb:.2f}")
if not messages:
return
# Send via webhook if available
url = alert_cfg.get("webhook", "").strip()
if not url:
st.warning("Alerts triggered, but no webhook URL provided.")
for m in messages:
st.info(m)
return
try:
import requests
payload = {"messages": messages, "time": ist_now_str()}
requests.post(url, json=payload, timeout=5)
st.success("Alerts sent.")
except Exception as e:
st.error(f"Failed to send alerts: {e}")
# -----------------------------
# Main App
# -----------------------------
def main():
if st.session_state.get("_last_refresh_ts") is None:
st.session_state["_last_refresh_ts"] = time.time()
header_bar()
controls = sidebar_controls()
kite = controls["kite"]
vol_window = controls["vol_window"]
conf_level = controls["conf_level"]
data_interval = controls["data_interval"]
days_back = controls["days_back"]
risk_pct = controls["risk_tolerance"]
sl_mult = controls["sl_multiplier"]
mapping = controls["mapping"]
alert_cfg = controls["alerts"]
if controls["auto_refresh"]:
if time.time() - st.session_state["_last_refresh_ts"] > 60:
st.session_state["_last_refresh_ts"] = time.time()
st.cache_data.clear()
st.rerun()
with st.spinner("Loading market data..."):
prices = load_prices(kite, days=days_back, interval=data_interval)
# Compute MGARCH forecast and correlations
with st.spinner("Forecasting volatility with MGARCH (DCC) ..."):
forecasts, corr_mat = forecast_volatility_mgarch(prices, horizon_days=1)
# KPIs row
st.markdown("#### Key Metrics")
k1, k2, k3, k4 = st.columns(4)
# Market mood heuristic
mood = "Bullish" if np.mean(list(forecasts.values())) < np.median(list(forecasts.values())) else "Bearish"
with k1:
avg_vol = np.mean(list(forecasts.values())) if forecasts else 0
kpi_card("📉", "Avg Forecast Volatility", f"{avg_vol:.2f}%", "Average annualized volatility forecast across sectors.")
with k2:
# Show one example SL based on Nifty 50
ref_vol = forecasts.get("Nifty 50", 0.0)
sl = compute_stop_loss(ref_vol, sl_mult)
kpi_card("🛡️", "Suggested Stop-loss", f"{sl:.2f}%", "Stop-loss derived from forecasted volatility and multiplier.")
with k3:
# Position size example with 1L capital and Nifty 50 price
capital_demo = 100000.0
price_demo = float(prices.iloc[-1]["Nifty 50"]) if "Nifty 50" in prices.columns else float(prices.iloc[-1, 0])
qty = suggest_position_size(capital_demo, risk_pct, sl, price_demo)
kpi_card("📦", "Position Size (demo)", f"{qty} units", "Illustrative size using ₹100,000 capital and Nifty 50 price.")
with k4:
kpi_card("🌤️", "Today’s Market Mood", mood, "Heuristic based on cross-sector volatility.")
# Tabs section
tabs = st.tabs(["📈 Volatility Trends", "🔥 Correlations", "💼 Trade Simulator", "🤖 LSTM vs MGARCH"])
# Tab 1: Volatility Trends
with tabs[0]:
st.markdown("##### Prices")
fig_prices = go.Figure()
for c in prices.columns:
fig_prices.add_trace(go.Scatter(x=prices.index, y=prices[c], mode="lines", name=c))
fig_prices.update_layout(template="plotly_dark", paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", height=420, margin=dict(l=10,r=10,t=30,b=10))
st.plotly_chart(fig_prices, use_container_width=True)
st.markdown("##### Rolling Volatility")
plot_vol_trends(prices, vol_window)
# Tab 2: Correlations
with tabs[1]:
st.markdown("##### Latest Correlation Heatmap")
if corr_mat is not None and not corr_mat.empty:
fig = px.imshow(corr_mat, text_auto=True, aspect="auto", color_continuous_scale="Viridis", zmin=-1, zmax=1)
fig.update_layout(template="plotly_dark", paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", height=380, margin=dict(l=10,r=10,t=30,b=10))
st.plotly_chart(fig, use_container_width=True)
else:
st.info("Correlation matrix unavailable. Using rolling correlations below.")
st.markdown("##### Correlation Over Time")
plot_corr_over_time(prices, vol_window)
st.markdown("##### Animated Heatmap")
plot_corr_heatmap_over_time(prices, vol_window)
# Tab 3: Trade Simulator
with tabs[2]:
st.markdown("##### Paper Trading")
cap = st.number_input("Capital (₹)", min_value=1000.0, value=100000.0, step=1000.0)
if st.button("Generate Paper Trades"):
trades = simulate_trades(prices, forecasts, cap, risk_pct, sl_mult)
store = get_trade_store()
store.extend(trades)
if trades:
st.success(f"Generated {len(trades)} simulated trade(s).")
else:
st.info("No trades generated by current rules.")
store = get_trade_store()
if store:
st.dataframe(pd.DataFrame(store).iloc[::-1].reset_index(drop=True), use_container_width=True)
st.markdown("---")
st.markdown("##### Real Trading (Use with Caution)")
st.caption("Requires Zerodha login. Indices are not directly tradable; map to ETFs/futures.")
enable_real = st.toggle("Enable Real Orders", value=False)
if enable_real and kite is not None:
if st.button("Place Real Orders"):
res = place_real_orders(kite, get_trade_store(), mapping)
st.write(res)
elif enable_real:
st.warning("Login to Zerodha first.")
# Tab 4: LSTM vs MGARCH (optional)
with tabs[3]:
st.markdown("##### LSTM-based Volatility Prediction")
try:
import tensorflow as tf # noqa: F401
TF_AVAILABLE = True
except Exception:
TF_AVAILABLE = False
if not TF_AVAILABLE:
st.info("TensorFlow not available. Install tensorflow to enable LSTM comparison.")
else:
st.caption("Quick demo: trains a tiny LSTM on returns to predict next absolute return as a proxy for volatility.")
# Prepare data (use first sector)
target_col = prices.columns[0]
ret = prices[target_col].pct_change().dropna().values.reshape(-1, 1)
# Simple LSTM dataset
lookback = 20
X, y = [], []
for i in range(lookback, len(ret)):
X.append(ret[i-lookback:i])
y.append(abs(ret[i]))
if len(X) < 100:
st.warning("Not enough data for LSTM demo.")
else:
X = np.array(X)
y = np.array(y)
# Build model
from tensorflow.keras import Sequential
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.optimizers import Adam
model = Sequential([LSTM(16, input_shape=(lookback, 1)), Dense(1)])
model.compile(optimizer=Adam(0.01), loss='mse')
model.fit(X[:-50], y[:-50], epochs=5, batch_size=32, verbose=0)
y_pred = model.predict(X[-50:], verbose=0).flatten()
# Compare to MGARCH proxy (convert annualized % to daily abs return proxy)
mgarch_vol_pct = forecasts.get(target_col, np.nan)
if not np.isnan(mgarch_vol_pct):
mgarch_daily = (mgarch_vol_pct/100.0)/np.sqrt(252)
else:
mgarch_daily = np.nan
st.write({"sector": target_col, "LSTM_mean_abs_ret": float(np.mean(y_pred)), "MGARCH_daily_vol_proxy": float(mgarch_daily) if not np.isnan(mgarch_daily) else None})
# Alerts after analytics computed
maybe_send_alerts(alert_cfg, forecasts, corr_mat)
# Footer
st.markdown("---")
st.markdown(
"<div class='footer'>Developed by Maithili Sharma | Department of AI, Vishwakarma University</div>",
unsafe_allow_html=True,
)
if __name__ == "__main__":
main()