Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1169 lines (1044 loc) · 57.1 KB
/
Copy pathapp.py
File metadata and controls
1169 lines (1044 loc) · 57.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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
app.py — NSE AI Trader | Final Presentation Version
Clean, professional Streamlit app with built-in AI Stock Chat Assistant.
"""
import os
import sys
import time
import pickle
from datetime import datetime, time as dtime
import numpy as np
import pandas as pd
import yfinance as yf
import pandas_ta as ta
import streamlit as st
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from dateutil import tz
from sklearn.ensemble import (RandomForestClassifier, ExtraTreesClassifier,
GradientBoostingClassifier)
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import accuracy_score
try:
from xgboost import XGBClassifier; HAS_XGB = True
except ImportError:
HAS_XGB = False
try:
from lightgbm import LGBMClassifier; HAS_LGBM = True
except ImportError:
HAS_LGBM = False
# ── dotenv + requests for OpenRouter chat ────────────────
import requests
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # .env loading is optional; os.environ still works
# ══════════════════════════════════════════════════════════
# CONFIG
# ══════════════════════════════════════════════════════════
st.set_page_config(
page_title="NSE AI Trader",
page_icon="📈",
layout="wide",
initial_sidebar_state="expanded",
)
# Custom CSS — dark, professional, presentation-ready
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=DM+Mono:wght@400;500&display=swap');
html, body, [class*="css"] {
font-family: 'DM Sans', sans-serif;
}
.stApp { background: #0a0e1a; color: #e2e8f0; }
/* Cards */
.metric-card {
background: linear-gradient(135deg, #111827 0%, #1e293b 100%);
border: 1px solid #1e3a5f;
border-radius: 12px;
padding: 20px;
text-align: center;
margin-bottom: 12px;
}
.signal-up { color: #10b981; font-weight: 700; font-size: 1.3rem; }
.signal-down { color: #f43f5e; font-weight: 700; font-size: 1.3rem; }
.signal-neutral { color: #f59e0b; font-weight: 700; font-size: 1.3rem; }
/* Chat messages */
.chat-user {
background: #1e3a5f;
border-radius: 16px 16px 4px 16px;
padding: 12px 16px;
margin: 8px 0 8px 40px;
color: #e2e8f0;
font-size: 0.93rem;
}
.chat-ai {
background: #111827;
border: 1px solid #1e3a5f;
border-radius: 16px 16px 16px 4px;
padding: 12px 16px;
margin: 8px 40px 8px 0;
color: #e2e8f0;
font-size: 0.93rem;
line-height: 1.6;
}
.chat-label-user { color: #60a5fa; font-size: 0.75rem; font-weight: 600; margin-bottom: 4px; }
.chat-label-ai { color: #10b981; font-size: 0.75rem; font-weight: 600; margin-bottom: 4px; }
/* Indicator pills */
.pill-bull { background: #052e16; color: #10b981; border: 1px solid #10b981;
border-radius: 20px; padding: 3px 10px; font-size: 0.78rem; display: inline-block; margin: 3px; }
.pill-bear { background: #2d0a0a; color: #f43f5e; border: 1px solid #f43f5e;
border-radius: 20px; padding: 3px 10px; font-size: 0.78rem; display: inline-block; margin: 3px; }
.pill-neutral { background: #1c1a07; color: #f59e0b; border: 1px solid #f59e0b;
border-radius: 20px; padding: 3px 10px; font-size: 0.78rem; display: inline-block; margin: 3px; }
/* Hide Streamlit branding */
#MainMenu, footer, header { visibility: hidden; }
.block-container { padding-top: 1rem; }
/* Sidebar */
[data-testid="stSidebar"] { background: #060b14; border-right: 1px solid #1e293b; }
/* Tabs */
.stTabs [data-baseweb="tab-list"] { background: #111827; border-radius: 8px; gap: 4px; }
.stTabs [data-baseweb="tab"] { color: #94a3b8; border-radius: 6px; }
.stTabs [data-baseweb="tab"][aria-selected="true"] { background: #1e3a5f; color: #60a5fa; }
/* Buttons */
.stButton > button {
background: linear-gradient(135deg, #1e3a5f, #1e40af);
color: white; border: none; border-radius: 8px;
font-family: 'DM Sans', sans-serif; font-weight: 500;
transition: all 0.2s;
}
.stButton > button:hover { opacity: 0.85; transform: translateY(-1px); }
/* Input */
.stTextInput > div > div > input {
background: #111827; color: #e2e8f0;
border: 1px solid #1e3a5f; border-radius: 8px;
font-family: 'DM Mono', monospace;
}
/* Metrics */
[data-testid="metric-container"] {
background: #111827;
border: 1px solid #1e293b;
border-radius: 10px;
padding: 12px 16px;
}
</style>
""", unsafe_allow_html=True)
# ══════════════════════════════════════════════════════════
# CONSTANTS & STOCK LIST
# ══════════════════════════════════════════════════════════
ALL_RESULTS_PATH = "models/all_results.pkl"
MARKET_SYMBOL = "^NSEI"
_MARKET_CACHE = None
if os.path.exists("nse_stocks.pkl"):
with open("nse_stocks.pkl", "rb") as f:
STOCK_MAP = pickle.load(f)
STOCKS = [v["yf_symbol"] for v in STOCK_MAP.values()]
else:
STOCKS = ["RELIANCE.NS","TCS.NS","HDFCBANK.NS","INFY.NS","ICICIBANK.NS",
"HINDUNILVR.NS","SBIN.NS","BAJFINANCE.NS","ADANIENT.NS","WIPRO.NS"]
FEATURES = [
"RSI_7","RSI_14","RSI_21","RSI_diff",
"MACD","MACD_sig","MACD_hist","MACD_cross",
"SMA_10","SMA_20","SMA_50","SMA_200",
"EMA_9","EMA_21","EMA_50",
"SMA_cross_10_50","SMA_cross_20_200","Price_SMA20","Price_SMA50","Price_SMA200",
"BB_upper","BB_lower","BB_width","BB_pos","BB_squeeze",
"ATR","ATR_pct","ATR_ratio",
"Vol_ratio","Vol_SMA_ratio","OBV","OBV_slope","VWAP_dist",
"ROC_5","ROC_10","ROC_20",
"Return_1d","Return_2d","Return_3d","Return_5d","Return_10d","Return_20d",
"Pos_10","Pos_20","Pos_52w",
"Body","Shadow_up","Shadow_dn","Body_ratio","Higher_high","Lower_low",
"STOCH_k","STOCH_d","WILLR","CCI",
"ADX","DI_plus","DI_minus","ADX_trend",
"TENKAN","KIJUN","SENKOU_A","SENKOU_B","ICH_cloud_pos",
"Trend_strength","Volatility_20","Vol_regime","Breakout_20","Breakdown_20","Gap_pct",
"MKT_ret_1d","MKT_ret_3d","MKT_ret_5d","MKT_rsi_14","MKT_trend_20_50","MKT_vol_10",
"Rel_5","Rel_20","Beta_60","Corr_20",
"Day_of_week","Month","Quarter","Week_of_year",
"Is_month_start","Is_month_end","Is_quarter_end",
]
# ══════════════════════════════════════════════════════════
# HELPERS
# ══════════════════════════════════════════════════════════
def flatten_columns(df):
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
return df
def get_col(df, prefix):
m = [c for c in df.columns if c.startswith(prefix)]
if not m: raise KeyError(f"No column with prefix '{prefix}'")
return m[0]
def market_is_open(now_utc=None):
if now_utc is None:
now_utc = datetime.utcnow().replace(tzinfo=tz.tzutc())
ist = now_utc.astimezone(tz.gettz('Asia/Kolkata'))
if ist.weekday() >= 5: return False, ist
return (dtime(9,15) <= ist.time() <= dtime(15,30)), ist
def load_market_data(end_date):
global _MARKET_CACHE
if _MARKET_CACHE is not None and not _MARKET_CACHE.empty:
return _MARKET_CACHE.copy()
mkt = yf.download(MARKET_SYMBOL, start="2014-01-01", end=end_date,
progress=False, auto_adjust=True)
if mkt is None or mkt.empty:
_MARKET_CACHE = pd.DataFrame(); return _MARKET_CACHE.copy()
mkt = flatten_columns(mkt)
mkt = mkt[[c for c in ["Open","High","Low","Close","Volume"] if c in mkt.columns]].copy()
mkt = mkt.replace([np.inf,-np.inf], np.nan).dropna()
_MARKET_CACHE = mkt
return _MARKET_CACHE.copy()
# ══════════════════════════════════════════════════════════
# FEATURE ENGINEERING
# ══════════════════════════════════════════════════════════
def add_features(df):
close = df["Close"]; high = df["High"]
low = df["Low"]; volume = df["Volume"]; open_ = df["Open"]
df["RSI_7"] = ta.rsi(close, length=7)
df["RSI_14"] = ta.rsi(close, length=14)
df["RSI_21"] = ta.rsi(close, length=21)
df["RSI_diff"] = df["RSI_14"] - df["RSI_14"].shift(1)
macd = ta.macd(close)
if macd is None: raise ValueError("MACD None")
df["MACD"] = macd[get_col(macd,"MACD_")]
df["MACD_sig"] = macd[get_col(macd,"MACDs_")]
df["MACD_hist"] = macd[get_col(macd,"MACDh_")]
df["MACD_cross"] = (df["MACD"] > df["MACD_sig"]).astype(int)
for l,n in [(10,"SMA_10"),(20,"SMA_20"),(50,"SMA_50"),(200,"SMA_200")]:
df[n] = ta.sma(close, length=l)
for l,n in [(9,"EMA_9"),(21,"EMA_21"),(50,"EMA_50")]:
df[n] = ta.ema(close, length=l)
df["SMA_cross_10_50"] = (df["SMA_10"] > df["SMA_50"]).astype(int)
df["SMA_cross_20_200"] = (df["SMA_20"] > df["SMA_200"]).astype(int)
df["Price_SMA20"] = (close > df["SMA_20"]).astype(int)
df["Price_SMA50"] = (close > df["SMA_50"]).astype(int)
df["Price_SMA200"] = (close > df["SMA_200"]).astype(int)
bb = ta.bbands(close, length=20)
if bb is None: raise ValueError("BB None")
df["BB_upper"] = bb[get_col(bb,"BBU_")]
df["BB_lower"] = bb[get_col(bb,"BBL_")]
df["BB_mid"] = bb[get_col(bb,"BBM_")]
df["BB_width"] = (df["BB_upper"] - df["BB_lower"]) / (df["BB_mid"] + 1e-9)
df["BB_pos"] = (close - df["BB_lower"]) / (df["BB_upper"] - df["BB_lower"] + 1e-9)
df["BB_squeeze"] = (df["BB_width"] < df["BB_width"].rolling(20).mean()).astype(int)
df["ATR"] = ta.atr(high, low, close, length=14)
df["ATR_pct"] = df["ATR"] / (close + 1e-9)
df["ATR_ratio"] = df["ATR"] / (df["ATR"].rolling(20).mean() + 1e-9)
df["Vol_SMA20"] = ta.sma(volume, length=20)
df["Vol_ratio"] = volume / (df["Vol_SMA20"] + 1e-9)
df["Vol_SMA_ratio"] = df["Vol_SMA20"] / (df["Vol_SMA20"].rolling(5).mean() + 1e-9)
df["OBV"] = ta.obv(close, volume)
df["OBV_slope"] = df["OBV"].diff(5)
tp = (high + low + close) / 3
df["VWAP_dist"] = (close - (tp * volume).cumsum() / (volume.cumsum() + 1e-9)) / (close + 1e-9)
for l,n in [(5,"ROC_5"),(10,"ROC_10"),(20,"ROC_20")]:
df[n] = ta.roc(close, length=l)
for n in [1,2,3,5,10,20]:
df[f"Return_{n}d"] = close.pct_change(n)
for win,suf in [(10,"_10"),(20,"_20"),(252,"_52w")]:
df[f"High{suf}"] = high.rolling(win).max()
df[f"Low{suf}"] = low.rolling(win).min()
df[f"Pos{suf}"] = (close-df[f"Low{suf}"]) / (df[f"High{suf}"]-df[f"Low{suf}"]+1e-9)
mx = pd.concat([close,open_],axis=1).max(axis=1)
mn = pd.concat([close,open_],axis=1).min(axis=1)
df["Body"] = (close-open_) / (open_+1e-9)
df["Shadow_up"] = (high-mx) / (open_+1e-9)
df["Shadow_dn"] = (mn-low) / (open_+1e-9)
ba = abs(df["Body"])
df["Body_ratio"] = ba / (df["Shadow_up"]+df["Shadow_dn"]+ba+1e-9)
df["Higher_high"] = (high > high.shift(1)).astype(int)
df["Lower_low"] = (low < low.shift(1)).astype(int)
stoch = ta.stoch(high, low, close)
if stoch is not None:
kc = [c for c in stoch.columns if c.startswith("STOCHk")]
dc = [c for c in stoch.columns if c.startswith("STOCHd")]
df["STOCH_k"] = stoch[kc[0]] if kc else 50.0
df["STOCH_d"] = stoch[dc[0]] if dc else 50.0
else:
df["STOCH_k"] = df["STOCH_d"] = 50.0
willr = ta.willr(high, low, close)
df["WILLR"] = willr if willr is not None else -50.0
cci = ta.cci(high, low, close)
df["CCI"] = cci if cci is not None else 0.0
adx_df = ta.adx(high, low, close)
if adx_df is not None:
ac = [c for c in adx_df.columns if c.startswith("ADX_")]
pc = [c for c in adx_df.columns if c.startswith("DMP_")]
nc = [c for c in adx_df.columns if c.startswith("DMN_")]
df["ADX"] = adx_df[ac[0]] if ac else 25.0
df["DI_plus"] = adx_df[pc[0]] if pc else 25.0
df["DI_minus"] = adx_df[nc[0]] if nc else 25.0
else:
df["ADX"] = df["DI_plus"] = df["DI_minus"] = 25.0
df["ADX_trend"] = (df["ADX"] > 25).astype(int)
ich = ta.ichimoku(high, low, close)
if ich is not None and isinstance(ich, tuple) and ich[0] is not None and not ich[0].empty:
ic = ich[0]; cols = ic.columns.tolist()
def pick(p):
m = [c for c in cols if c.startswith(p)]
return ic[m[0]] if m else pd.Series(close.values, index=close.index)
df["TENKAN"] = pick("ITS_"); df["KIJUN"] = pick("IKS_")
df["SENKOU_A"] = pick("ISA_"); df["SENKOU_B"] = pick("ISB_")
else:
for c in ["TENKAN","KIJUN","SENKOU_A","SENKOU_B"]: df[c] = close
df["ICH_cloud_pos"] = (close > df[["SENKOU_A","SENKOU_B"]].max(axis=1)).astype(int)
df["Trend_strength"] = (df["EMA_21"] - df["EMA_50"]) / (close + 1e-9)
df["Volatility_20"] = close.pct_change().rolling(20).std()
df["Vol_regime"] = df["Volatility_20"] / (df["Volatility_20"].rolling(100).mean() + 1e-9)
df["Breakout_20"] = (close > high.shift(1).rolling(20).max()).astype(int)
df["Breakdown_20"] = (close < low.shift(1).rolling(20).min()).astype(int)
df["Gap_pct"] = (open_ - close.shift(1)) / (close.shift(1) + 1e-9)
df["Day_of_week"] = df.index.dayofweek
df["Month"] = df.index.month
df["Quarter"] = df.index.quarter
df["Week_of_year"] = df.index.isocalendar().week.astype(int)
df["Is_month_start"] = df.index.is_month_start.astype(int)
df["Is_month_end"] = df.index.is_month_end.astype(int)
df["Is_quarter_end"] = df.index.is_quarter_end.astype(int)
return df
def add_market_features(df, market_df):
null_cols = ["MKT_ret_1d","MKT_ret_3d","MKT_ret_5d","MKT_rsi_14",
"MKT_trend_20_50","MKT_vol_10","Rel_5","Rel_20","Beta_60","Corr_20"]
if market_df is None or market_df.empty:
for c in null_cols: df[c] = 0.0
return df
m = market_df.reindex(df.index).ffill()
m["ret1"] = m["Close"].pct_change(1)
m["rsi14"] = ta.rsi(m["Close"], length=14)
m["sma20"] = ta.sma(m["Close"], length=20)
m["sma50"] = ta.sma(m["Close"], length=50)
df["MKT_ret_1d"] = m["ret1"]
df["MKT_ret_3d"] = m["Close"].pct_change(3)
df["MKT_ret_5d"] = m["Close"].pct_change(5)
df["MKT_rsi_14"] = m["rsi14"]
df["MKT_trend_20_50"] = (m["sma20"] > m["sma50"]).astype(float)
df["MKT_vol_10"] = m["ret1"].rolling(10).std()
df["Rel_5"] = df["Close"].pct_change(5) - m["Close"].pct_change(5)
df["Rel_20"] = df["Close"].pct_change(20) - m["Close"].pct_change(20)
sret = df["Close"].pct_change(1)
cov = sret.rolling(60).cov(m["ret1"])
var = m["ret1"].rolling(60).var()
df["Beta_60"] = cov / (var + 1e-9)
df["Corr_20"] = sret.rolling(20).corr(m["ret1"])
return df
# ══════════════════════════════════════════════════════════
# CACHED DATA LOADERS
# ══════════════════════════════════════════════════════════
@st.cache_data(ttl=3600)
def load_all_results():
if os.path.exists(ALL_RESULTS_PATH):
with open(ALL_RESULTS_PATH,"rb") as f:
return pickle.load(f)
return {}
@st.cache_data(ttl=3600)
def load_model_result(symbol):
if os.path.exists(ALL_RESULTS_PATH):
try:
with open(ALL_RESULTS_PATH,"rb") as f:
allr = pickle.load(f)
if symbol in allr:
return allr[symbol]
except Exception:
pass
fn = os.path.join("models", symbol.replace('.','_') + ".pkl")
if os.path.exists(fn):
try:
with open(fn,"rb") as f: return pickle.load(f)
except Exception:
pass
return None
@st.cache_data(ttl=60)
def fetch_live_price(symbol):
try:
t = yf.Ticker(symbol)
hist = t.history(period="2d", interval="1m")
if hist is not None and not hist.empty:
last = hist['Close'].iloc[-1]
prev = hist['Close'].iloc[-2] if len(hist) > 1 else last
return round(float(last),2), round(float(last-prev),2)
except Exception:
pass
try:
h = yf.download(symbol, period='5d', progress=False, auto_adjust=True)
if not h.empty:
last = h['Close'].iloc[-1]; prev = h['Close'].iloc[-2] if len(h)>1 else last
return round(float(last),2), round(float(last-prev),2)
except Exception:
pass
return None, None
# ══════════════════════════════════════════════════════════
# TRAIN STOCK (on-demand)
# ══════════════════════════════════════════════════════════
def train_stock(symbol):
t0 = time.time()
end_date = (pd.Timestamp.utcnow() + pd.Timedelta(days=1)).strftime("%Y-%m-%d")
df = yf.download(symbol, start="2014-01-01", end=end_date,
progress=False, auto_adjust=True)
if df is None or df.empty or len(df) < 400: return None, "not enough data"
df = flatten_columns(df)
needed = [c for c in ["Open","High","Low","Close","Volume"] if c in df.columns]
if len(needed) < 5: return None, "missing OHLCV"
df = df[needed].copy().replace([np.inf,-np.inf],np.nan).dropna()
try: df = add_features(df)
except Exception as e: return None, f"feature error: {e}"
df = add_market_features(df, load_market_data(end_date))
df = df.replace([np.inf,-np.inf], np.nan)
future = df["Close"].shift(-2)
df["Target"] = np.where(future.notna(), (future > df["Close"]).astype(int), np.nan)
df.dropna(subset=["Target"], inplace=True)
df["Target"] = df["Target"].astype(int)
for f in FEATURES:
if f not in df.columns: df[f] = 0.0
X = df[FEATURES].copy().fillna(df[FEATURES].median()).replace([np.inf,-np.inf],0)
y = df["Target"].copy()
if len(X) < 300: return None, "too little data"
tscv = TimeSeriesSplit(n_splits=5); scores=[]
for tr,te in tscv.split(X):
m = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
m.fit(X.iloc[tr], y.iloc[tr])
scores.append(accuracy_score(y.iloc[te], m.predict(X.iloc[te])))
cv_acc = np.mean(scores)*100
n = len(X); tr_end = int(n*0.70); va_end = int(n*0.85)
X_tr=X.iloc[:tr_end]; y_tr=y.iloc[:tr_end]
X_va=X.iloc[tr_end:va_end]; y_va=y.iloc[tr_end:va_end]
X_te=X.iloc[va_end:]; y_te=y.iloc[va_end:]
if len(X_tr)<200 or len(X_va)<40 or len(X_te)<40: return None,"not enough samples"
scaler=StandardScaler()
X_tr_sc=scaler.fit_transform(X_tr); X_va_sc=scaler.transform(X_va); X_te_sc=scaler.transform(X_te)
latest=X.iloc[-1:].fillna(X.median()); latest_sc=scaler.transform(latest)
models={}; val_probs=[]; test_probs=[]; lat_probs=[]
rf = RandomForestClassifier(n_estimators=500, max_depth=15, min_samples_split=15,
min_samples_leaf=5, max_features="sqrt",
class_weight="balanced_subsample", random_state=42, n_jobs=-1)
rf.fit(X_tr, y_tr); models["rf"]=rf
val_probs.append(rf.predict_proba(X_va)[:,1]); test_probs.append(rf.predict_proba(X_te)[:,1])
lat_probs.append(rf.predict_proba(latest)[0][1])
et = ExtraTreesClassifier(n_estimators=400, max_depth=12, min_samples_split=20,
class_weight="balanced", random_state=42, n_jobs=-1)
et.fit(X_tr, y_tr); models["et"]=et
val_probs.append(et.predict_proba(X_va)[:,1]); test_probs.append(et.predict_proba(X_te)[:,1])
lat_probs.append(et.predict_proba(latest)[0][1])
gb = GradientBoostingClassifier(n_estimators=200, max_depth=4, learning_rate=0.05,
subsample=0.8, random_state=42)
gb.fit(X_tr, y_tr); models["gb"]=gb
val_probs.append(gb.predict_proba(X_va)[:,1]); test_probs.append(gb.predict_proba(X_te)[:,1])
lat_probs.append(gb.predict_proba(latest)[0][1])
lr = LogisticRegression(max_iter=1000, class_weight="balanced", random_state=42, n_jobs=-1)
lr.fit(X_tr_sc, y_tr); models["lr"]=lr
val_probs.append(lr.predict_proba(X_va_sc)[:,1]); test_probs.append(lr.predict_proba(X_te_sc)[:,1])
lat_probs.append(lr.predict_proba(latest_sc)[0][1])
if HAS_XGB:
try:
xgb = XGBClassifier(n_estimators=300, max_depth=5, learning_rate=0.05,
subsample=0.85, colsample_bytree=0.85, eval_metric="logloss",
random_state=42, n_jobs=-1, verbosity=0)
xgb.fit(X_tr, y_tr, eval_set=[(X_va,y_va)], verbose=False)
models["xgb"]=xgb; val_probs.append(xgb.predict_proba(X_va)[:,1])
test_probs.append(xgb.predict_proba(X_te)[:,1]); lat_probs.append(xgb.predict_proba(latest)[0][1])
except Exception: pass
if HAS_LGBM:
try:
lgbm = LGBMClassifier(n_estimators=300, learning_rate=0.05, num_leaves=31,
subsample=0.85, colsample_bytree=0.85,
class_weight="balanced", random_state=42, verbose=-1)
lgbm.fit(X_tr, y_tr); models["lgbm"]=lgbm
val_probs.append(lgbm.predict_proba(X_va)[:,1]); test_probs.append(lgbm.predict_proba(X_te)[:,1])
lat_probs.append(lgbm.predict_proba(latest)[0][1])
except Exception: pass
n_m = len(val_probs); best_w=[1/n_m]*n_m; best_acc=-1.0
rng = np.random.default_rng(42)
cands = [np.ones(n_m)/n_m]
for i in range(n_m):
w=np.zeros(n_m); w[i]=1.0; cands.append(w)
for _ in range(200): cands.append(rng.dirichlet(np.ones(n_m)))
for w in cands:
ens = sum(w[i]*val_probs[i] for i in range(n_m))
acc = accuracy_score(y_va, (ens>0.5).astype(int))
if acc > best_acc: best_acc=acc; best_w=w.tolist()
ens_test = sum(best_w[i]*test_probs[i] for i in range(n_m))
final_pred = (ens_test>0.5).astype(int)
final_acc = accuracy_score(y_te, final_pred)*100
prob_up = float(sum(best_w[i]*lat_probs[i] for i in range(n_m)))
pred = "UP" if prob_up>0.5 else "DOWN"
conf = round(max(prob_up,1-prob_up)*100, 2)
fi = dict(zip(FEATURES, rf.feature_importances_))
chart_cols = ["Open","High","Low","Close","Volume","SMA_20","SMA_50","SMA_200",
"BB_upper","BB_lower","RSI_14","STOCH_k","STOCH_d",
"MACD","MACD_sig","MACD_hist","Vol_SMA20","ADX","DI_plus","DI_minus"]
avail = [c for c in chart_cols if c in df.columns]
chart_df = df[avail].tail(520).copy()
for c in chart_df.select_dtypes("float64").columns:
chart_df[c] = chart_df[c].astype("float32")
result = {
"symbol": symbol, "accuracy": round(final_acc,2), "cv_accuracy": round(cv_acc,2),
"val_accuracy": round(best_acc*100,2), "prediction": pred, "confidence": conf,
"prob_up": round(prob_up*100,2), "ensemble_models": list(models.keys()),
"ensemble_weights": [round(float(w),3) for w in best_w],
"current_price": round(float(df["Close"].iloc[-1]),2),
"rsi": round(float(df["RSI_14"].iloc[-1]),2),
"macd": round(float(df["MACD"].iloc[-1]),4),
"sma_20": round(float(df["SMA_20"].iloc[-1]),2),
"sma_50": round(float(df["SMA_50"].iloc[-1]),2),
"sma_200": round(float(df["SMA_200"].iloc[-1]),2),
"bb_pos": round(float(df["BB_pos"].iloc[-1]),2),
"bb_squeeze": int(df["BB_squeeze"].iloc[-1]),
"vol_ratio": round(float(df["Vol_ratio"].iloc[-1]),2),
"atr_pct": round(float(df["ATR_pct"].iloc[-1]),4),
"adx": round(float(df["ADX"].iloc[-1]),2),
"stoch_k": round(float(df["STOCH_k"].iloc[-1]),2),
"willr": round(float(df["WILLR"].iloc[-1]),2),
"cci": round(float(df["CCI"].iloc[-1]),2),
"ich_cloud_pos": int(df["ICH_cloud_pos"].iloc[-1]),
"obv_slope": round(float(df["OBV_slope"].iloc[-1]),0),
"df": chart_df, "feature_importance": fi,
"trained_at": time.strftime("%Y-%m-%d %H:%M"),
"elapsed_sec": round(time.time()-t0,1),
}
return (result, models, scaler), None
# ══════════════════════════════════════════════════════════
# AI CHAT ENGINE
# ══════════════════════════════════════════════════════════
def build_stock_context(symbol, result, live_price):
"""Build rich context string about the stock for the AI."""
if not isinstance(result, dict):
return f"Stock: {symbol}. No trained model data available yet."
pred = result.get("prediction","—")
conf = result.get("confidence", 0)
prob_up = result.get("prob_up", 50)
price = live_price or result.get("current_price", 0)
rsi = result.get("rsi", 50)
adx = result.get("adx", 20)
macd = result.get("macd", 0)
stoch_k = result.get("stoch_k", 50)
willr = result.get("willr", -50)
cci = result.get("cci", 0)
bb_pos = result.get("bb_pos", 0.5)
bb_sq = result.get("bb_squeeze", 0)
vol_r = result.get("vol_ratio", 1)
atr_pct = result.get("atr_pct", 0.02)
sma20 = result.get("sma_20", 0)
sma50 = result.get("sma_50", 0)
sma200 = result.get("sma_200", 0)
ich = result.get("ich_cloud_pos", 0)
acc = result.get("accuracy", 0)
cv_acc = result.get("cv_accuracy", 0)
models = result.get("ensemble_models", [])
atr_pts = price * atr_pct if price else 0
stop = round(price - 1.5*atr_pts, 2) if pred=="UP" else round(price + 1.5*atr_pts, 2)
tgt1 = round(price + 2.0*atr_pts, 2) if pred=="UP" else round(price - 2.0*atr_pts, 2)
tgt2 = round(price + 3.5*atr_pts, 2) if pred=="UP" else round(price - 3.5*atr_pts, 2)
rr = round(abs(tgt1-price) / (abs(price-stop)+1e-9), 2)
return f"""
STOCK ANALYSIS CONTEXT FOR {symbol}:
CURRENT DATA:
- Live Price: ₹{price}
- AI Prediction (2-day): {pred} with {conf:.1f}% confidence
- Probability of UP move: {prob_up:.1f}%
- Model Test Accuracy: {acc:.1f}%, CV Accuracy: {cv_acc:.1f}%
- Ensemble: {'+'.join(models)}
TECHNICAL INDICATORS:
- RSI(14): {rsi:.1f} {'(Oversold - Bullish)' if rsi<30 else '(Overbought - Bearish)' if rsi>70 else '(Neutral)'}
- MACD: {macd:.4f} {'(Positive - Bullish)' if macd>0 else '(Negative - Bearish)'}
- ADX: {adx:.1f} {'(Strong Trend)' if adx>25 else '(Weak/Choppy)'}
- Stochastic %K: {stoch_k:.1f} {'(Oversold)' if stoch_k<20 else '(Overbought)' if stoch_k>80 else '(Neutral)'}
- Williams %R: {willr:.1f} {'(Oversold)' if willr<-80 else '(Overbought)' if willr>-20 else '(Neutral)'}
- CCI: {cci:.1f}
- Bollinger Position: {bb_pos:.2f} {'(Near Lower Band - Bullish)' if bb_pos<0.2 else '(Near Upper Band - Bearish)' if bb_pos>0.8 else '(Mid Band)'}
- BB Squeeze: {'YES - Big move expected!' if bb_sq else 'No'}
- Volume Ratio: {vol_r:.2f}x average {'(High - Strong conviction)' if vol_r>1.5 else '(Low)' if vol_r<0.7 else '(Normal)'}
- Ichimoku Cloud: {'Above cloud (Bullish)' if ich else 'Below cloud (Bearish)'}
- Price vs SMA: SMA20=₹{sma20}, SMA50=₹{sma50}, SMA200=₹{sma200}
RISK MANAGEMENT (ATR-based):
- ATR per day: ₹{atr_pts:.2f}
- Suggested Stop-Loss: ₹{stop} (1.5× ATR)
- Target 1: ₹{tgt1} (2× ATR) | Target 2: ₹{tgt2} (3.5× ATR)
- Risk:Reward ratio: 1:{rr}
Use this data to answer user questions accurately. Be specific with numbers.
Always mention this is for educational purposes and not SEBI financial advice.
Keep answers concise and clear. For position sizing questions, use Kelly criterion concepts
or simple percentage-of-capital rules (e.g., risk only 1-2% of capital per trade).
"""
def get_ai_response(messages, stock_context):
"""
Call OpenRouter API (OpenAI-compatible endpoint).
API key is loaded from .env file as OPENROUTER_API_KEY.
"""
api_key = os.environ.get("OPENROUTER_API_KEY", "")
if not api_key:
return (
"⚠️ OpenRouter API key not found.\n\n"
"Add this line to your `.env` file in the project folder:\n"
"```\nOPENROUTER_API_KEY=sk-or-your-key-here\n```\n"
"Then restart the app."
)
system_prompt = f"""You are an expert NSE stock market analyst and AI trading assistant.
You have access to real-time technical analysis data for the selected stock.
Answer questions about buying/selling decisions, position sizing, risk management,
and technical analysis. Be direct, specific, and use the data provided.
{stock_context}
Guidelines:
- Give specific buy/sell/hold recommendations based on the data
- For "how much to buy" questions: suggest risking 1-2% of capital per trade,
calculate position size as: Shares = (Capital × Risk%) / (Entry Price - Stop-Loss)
Example: Capital ₹1,00,000 × 2% risk = ₹2,000 risk budget ÷ (Entry - StopLoss) = shares to buy
- Always mention the specific stop-loss and target levels from the data
- Keep responses focused and under 200 words unless detailed analysis is asked
- End with a bold one-line summary
- Mention this is educational only, not SEBI-registered financial advice"""
# Build OpenAI-compatible messages with system prompt injected
or_messages = [{"role": "system", "content": system_prompt}]
for m in messages:
or_messages.append({"role": m["role"], "content": m["content"]})
try:
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://nse-ai-trader.app", # optional, shown in OpenRouter dashboard
"X-Title": "NSE AI Trader", # optional, shown in OpenRouter dashboard
},
json={
"model": "meta-llama/llama-3.3-70b-instruct", # fast + free tier available
"messages": or_messages,
"max_tokens": 600,
"temperature": 0.4,
},
timeout=30,
)
response.raise_for_status()
data = response.json()
return data["choices"][0]["message"]["content"]
except requests.exceptions.Timeout:
return "⏱️ Request timed out. Please try again."
except requests.exceptions.HTTPError as e:
status = e.response.status_code if e.response else "?"
if status == 401:
return "❌ Invalid API key. Check your OPENROUTER_API_KEY in the .env file."
elif status == 402:
return "❌ Insufficient OpenRouter credits. Add credits at openrouter.ai."
else:
return f"❌ API error {status}: {str(e)}"
except Exception as e:
return f"❌ Chat error: {str(e)}"
# ══════════════════════════════════════════════════════════
# GAUGE CHART
# ══════════════════════════════════════════════════════════
def semicircle_gauge(conf, pred):
color = "#10b981" if pred == "UP" else "#f43f5e"
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=conf,
domain={'x':[0,1],'y':[0,1]},
gauge={
'shape': "angular",
'axis': {'range':[0,100],'tickwidth':1,'tickcolor':'#475569'},
'bar': {'color': color, 'thickness': 0.3},
'bgcolor': "#111827",
'borderwidth': 0,
'steps': [
{'range':[0,50], 'color':'#1e293b'},
{'range':[50,100],'color':'#1e3a5f'},
],
},
number={'font':{'color':color,'size':28,'family':'DM Sans'}, 'suffix':'%'}
))
fig.update_layout(
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
margin=dict(l=10,r=10,t=10,b=10),
height=180,
font={'color':'#94a3b8'}
)
return fig
# ══════════════════════════════════════════════════════════
# MAIN APP
# ══════════════════════════════════════════════════════════
def main():
# ── Sidebar ───────────────────────────────────────────
with st.sidebar:
st.markdown("## 📈 NSE AI Trader")
st.markdown("---")
selected = st.selectbox("Select Stock", STOCKS, index=0, key="sel_stock")
# Market status
open_flag, ist = market_is_open()
status_color = "#10b981" if open_flag else "#f43f5e"
status_label = "● Market Open" if open_flag else "● Market Closed"
st.markdown(f"<span style='color:{status_color};font-size:0.85rem;font-weight:600'>{status_label}</span>", unsafe_allow_html=True)
st.caption(ist.strftime('%d %b %Y %H:%M IST'))
st.markdown("---")
# Top picks
allr = load_all_results()
if allr:
st.markdown("### 🏆 Top Signals")
items = [(k, v.get('confidence',0)) for k,v in allr.items() if isinstance(v,dict)]
top5 = sorted(items, key=lambda x: x[1], reverse=True)[:5]
for sym, conf in top5:
pred = allr[sym].get('prediction','—')
icon = "🟢" if pred=="UP" else "🔴"
if st.button(f"{icon} {sym} {conf:.0f}%", key=f"top_{sym}", use_container_width=True):
st.session_state.sel_stock = sym
st.markdown("---")
if st.button(f"🔄 Retrain {selected}", use_container_width=True):
with st.spinner(f"Training {selected}..."):
out, err = train_stock(selected)
if err:
st.error(f"Failed: {err}")
else:
result, models, scaler = out
os.makedirs("models", exist_ok=True)
with open(f"models/{selected.replace('.','_')}.pkl","wb") as f:
pickle.dump({"models":models,"scaler":scaler,"features":FEATURES,
"weights":result["ensemble_weights"],
"model_names":result["ensemble_models"]}, f)
all_r = {}
if os.path.exists(ALL_RESULTS_PATH):
with open(ALL_RESULTS_PATH,"rb") as f: all_r = pickle.load(f)
all_r[selected] = result
with open(ALL_RESULTS_PATH,"wb") as f: pickle.dump(all_r, f)
st.success(f"✅ Acc: {result['accuracy']:.1f}%")
st.cache_data.clear()
st.rerun()
# ── Load data ─────────────────────────────────────────
result = load_model_result(selected)
live_price, delta = fetch_live_price(selected)
price = live_price or (result.get("current_price",0) if isinstance(result,dict) else 0)
# ── Header ────────────────────────────────────────────
st.markdown(f"<h1 style='color:#e2e8f0;font-size:1.8rem;margin-bottom:0'>{selected}</h1>", unsafe_allow_html=True)
if result is None:
st.warning(f"No model found for **{selected}**. Click **Retrain** in the sidebar.")
return
pred = result.get("prediction","—")
conf = result.get("confidence", 0)
# ── Key metrics row ───────────────────────────────────
c1,c2,c3,c4,c5,c6 = st.columns(6)
with c1:
change_str = f"{delta:+.2f}" if delta is not None else "—"
dc = "normal" if (delta or 0) >= 0 else "inverse"
st.metric("Live Price", f"₹{price:,.2f}", change_str, delta_color=dc)
with c2:
st.metric("Prediction", f"{'🟢' if pred=='UP' else '🔴'} {pred}")
with c3:
st.metric("Confidence", f"{conf:.1f}%")
with c4:
st.metric("Test Accuracy", f"{result.get('accuracy',0):.1f}%")
with c5:
st.metric("CV Accuracy", f"{result.get('cv_accuracy',0):.1f}%")
with c6:
atr_pts = price * result.get('atr_pct',0.02)
stop = round(price - 1.5*atr_pts,2) if pred=="UP" else round(price + 1.5*atr_pts,2)
st.metric("Stop-Loss", f"₹{stop:,.2f}")
# ── Gauge + Indicator pills ───────────────────────────
g1, g2 = st.columns([1,3])
with g1:
st.plotly_chart(semicircle_gauge(conf, pred), use_container_width=True)
with g2:
rsi = result.get('rsi',50); adx = result.get('adx',20)
macd_v = result.get('macd',0); stoch_k = result.get('stoch_k',50)
bb_pos = result.get('bb_pos',0.5); vol_r = result.get('vol_ratio',1)
ich = result.get('ich_cloud_pos',0); bb_sq = result.get('bb_squeeze',0)
def pill(label, val, condition):
cls = "pill-bull" if condition=="bull" else "pill-bear" if condition=="bear" else "pill-neutral"
return f'<span class="{cls}">{label}: {val}</span>'
pills_html = ""
pills_html += pill("RSI", f"{rsi:.1f}", "bull" if rsi<40 else "bear" if rsi>65 else "neutral")
pills_html += pill("MACD", f"{macd_v:+.4f}", "bull" if macd_v>0 else "bear")
pills_html += pill("ADX", f"{adx:.1f}", "bull" if adx>25 else "neutral")
pills_html += pill("Stoch", f"{stoch_k:.1f}", "bull" if stoch_k<25 else "bear" if stoch_k>75 else "neutral")
pills_html += pill("BB Pos", f"{bb_pos:.2f}", "bull" if bb_pos<0.3 else "bear" if bb_pos>0.7 else "neutral")
pills_html += pill("Volume", f"{vol_r:.2f}x", "bull" if vol_r>1.5 else "neutral")
pills_html += pill("Cloud", "Above" if ich else "Below", "bull" if ich else "bear")
if bb_sq: pills_html += '<span class="pill-neutral">⚡ BB Squeeze</span>'
st.markdown(f"<div style='padding-top:20px'>{pills_html}</div>", unsafe_allow_html=True)
# ATR-based levels
atr_pts = price * result.get('atr_pct',0.02)
tgt1 = round(price + 2.0*atr_pts,2) if pred=="UP" else round(price - 2.0*atr_pts,2)
tgt2 = round(price + 3.5*atr_pts,2) if pred=="UP" else round(price - 3.5*atr_pts,2)
rr = round(abs(tgt1-price)/(abs(price-stop)+1e-9),2)
st.markdown(
f"<div style='margin-top:12px;color:#94a3b8;font-size:0.83rem'>"
f"🎯 Target 1: <b style='color:#10b981'>₹{tgt1:,.2f}</b> | "
f"🏆 Target 2: <b style='color:#10b981'>₹{tgt2:,.2f}</b> | "
f"⚖️ R:R = 1:{rr} | "
f"📐 ATR/day = ₹{atr_pts:.2f}</div>",
unsafe_allow_html=True
)
st.markdown("---")
# ══════════════════════════════════════════════════════
# TABS
# ══════════════════════════════════════════════════════
tabs = st.tabs(["🤖 AI Chat", "📊 Charts", "🔍 Compare", "💼 Portfolio", "🧠 Model Info"])
# ══════════════════════════════════════════════════════
# TAB 0 — AI CHAT
# ══════════════════════════════════════════════════════
with tabs[0]:
st.markdown("### 🤖 AI Stock Assistant")
st.caption(f"Ask anything about **{selected}** — buy/sell decisions, position sizing, risk levels, technical analysis.")
# Init chat history per stock
chat_key = f"chat_{selected}"
if chat_key not in st.session_state:
st.session_state[chat_key] = []
# Suggested questions
st.markdown("**Quick questions:**")
sq_cols = st.columns(3)
suggestions = [
"Should I buy this stock now?",
"How much should I invest?",
"What is the stop-loss level?",
"Is the trend strong?",
"What do the indicators say?",
"Is this a good risk-reward?",
]
for i, sq in enumerate(suggestions):
with sq_cols[i % 3]:
if st.button(sq, key=f"sq_{i}_{selected}", use_container_width=True):
st.session_state[chat_key].append({"role":"user","content":sq})
# Chat history display
chat_container = st.container()
with chat_container:
for msg in st.session_state[chat_key]:
if msg["role"] == "user":
st.markdown(
f'<div class="chat-label-user">You</div>'
f'<div class="chat-user">{msg["content"]}</div>',
unsafe_allow_html=True
)
else:
st.markdown(
f'<div class="chat-label-ai">🤖 AI Analyst</div>'
f'<div class="chat-ai">{msg["content"]}</div>',
unsafe_allow_html=True
)
# Auto-respond to new user messages without a reply yet
history = st.session_state[chat_key]
if history and history[-1]["role"] == "user":
with st.spinner("Analysing..."):
ctx = build_stock_context(selected, result, live_price)
api_msgs = [{"role": m["role"], "content": m["content"]}
for m in history]
reply = get_ai_response(api_msgs, ctx)
st.session_state[chat_key].append({"role":"assistant","content":reply})
st.rerun()
# Input box
st.markdown("<div style='height:8px'></div>", unsafe_allow_html=True)
with st.form(key=f"chat_form_{selected}", clear_on_submit=True):
col_inp, col_btn = st.columns([5, 1])
with col_inp:
user_input = st.text_input(
"Ask about this stock...",
placeholder="e.g. Should I buy RELIANCE.NS today? How much should I invest?",
label_visibility="collapsed"
)
with col_btn:
submitted = st.form_submit_button("Send →", use_container_width=True)
if submitted and user_input.strip():
st.session_state[chat_key].append({"role":"user","content":user_input.strip()})
st.rerun()
# Clear chat
if st.session_state[chat_key]:
if st.button("🗑️ Clear Chat", key=f"clr_{selected}"):
st.session_state[chat_key] = []
st.rerun()
# API key notice
if not os.environ.get("OPENROUTER_API_KEY"):
st.info(
"💡 **OpenRouter API key not set.**\n\n"
"Create a file named `.env` in your project folder and add:\n"
"```\nOPENROUTER_API_KEY=sk-or-your-key-here\n```\n"
"Get a free key at [openrouter.ai](https://openrouter.ai) → then restart the app."
)
# ══════════════════════════════════════════════════════
# TAB 1 — CHARTS
# ══════════════════════════════════════════════════════
with tabs[1]:
chart_df = result.get('df') if isinstance(result,dict) else None
if chart_df is None:
st.warning("Chart data not available. Please retrain the model.")
else:
dfc = chart_df.copy()
dfc.index = pd.to_datetime(dfc.index)
# Candlestick + Volume
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
row_heights=[0.72,0.28], vertical_spacing=0.02,
specs=[[{"type":"candlestick"}],[{"type":"bar"}]])
fig.add_trace(go.Candlestick(
x=dfc.index, open=dfc['Open'], high=dfc['High'],
low=dfc['Low'], close=dfc['Close'], name='Price',
increasing_line_color='#10b981', decreasing_line_color='#f43f5e'), row=1,col=1)
for col_n, color, nm in [('SMA_20','#f59e0b','SMA20'),('SMA_50','#60a5fa','SMA50'),('SMA_200','#c084fc','SMA200')]:
if col_n in dfc.columns:
fig.add_trace(go.Scatter(x=dfc.index, y=dfc[col_n], mode='lines',
name=nm, line=dict(color=color,width=1.2)), row=1,col=1)
if 'BB_upper' in dfc.columns and 'BB_lower' in dfc.columns:
fig.add_trace(go.Scatter(x=dfc.index, y=dfc['BB_upper'], mode='lines',
name='BB Upper', line=dict(color='#475569',dash='dot',width=1)), row=1,col=1)
fig.add_trace(go.Scatter(x=dfc.index, y=dfc['BB_lower'], mode='lines',
name='BB Lower', fill='tonexty',
fillcolor='rgba(71,85,105,0.1)',
line=dict(color='#475569',dash='dot',width=1)), row=1,col=1)
vol_colors = ['#10b981' if dfc['Close'].iloc[i]>=dfc['Close'].iloc[max(0,i-1)] else '#f43f5e'
for i in range(len(dfc))]
fig.add_trace(go.Bar(x=dfc.index, y=dfc['Volume'], name='Volume',
marker_color=vol_colors, opacity=0.7), row=2,col=1)