Repository navigation
Expand file tree
/
Copy pathtrain.py
More file actions
983 lines (832 loc) · 43.5 KB
/
Copy pathtrain.py
File metadata and controls
983 lines (832 loc) · 43.5 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
"""
train.py — NSE AI Trader | v3.1 (all errors fixed)
═══════════════════════════════════════════════════════════════════════════════
Fixes applied:
[1] cv="prefit" crash → version-safe calibrate_model() works on ALL sklearn
[2] Dead sector ETFs removed (0P0001IHWT.BO, ^CNXFINANCE) → working symbols
[3] Python 3.9 type hint syntax fixed (dict[x,y] → dict, list[x] → list)
Upgrades over v2:
1. Probability calibration — isotonic, works on all sklearn versions
2. Walk-forward backtesting — Sharpe, drawdown, win-rate, OOS accuracy
3. SHAP feature importance — falls back to feature_importances_ if needed
4. Kelly position sizing — fractional Kelly per symbol
5. ATR flat-move target filter — removes ambiguous labels
6. Class balance logging — UP% printed per stock
7. Sector relative-strength — 12 working NIFTY sector indices
8. 3-state volatility regime — low / mid / high one-hot
9. Transaction-cost backtest — 0.1% round-trip
10. Purged CV — embargo gap prevents label leakage
═══════════════════════════════════════════════════════════════════════════════
"""
import os
import sys
import warnings
import time
import pickle
import numpy as np
import pandas as pd
import pandas_ta as ta
import yfinance as yf
os.environ["PYTHONWARNINGS"] = "ignore"
warnings.filterwarnings("ignore")
# ── sklearn ───────────────────────────────────────────────────────────────────
from sklearn.ensemble import (
RandomForestClassifier,
GradientBoostingClassifier,
ExtraTreesClassifier,
)
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.calibration import CalibratedClassifierCV
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import accuracy_score, brier_score_loss, log_loss
# ── Optional boosters ─────────────────────────────────────────────────────────
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
# ── Optional SHAP ─────────────────────────────────────────────────────────────
try:
import shap
HAS_SHAP = True
except ImportError:
HAS_SHAP = False
# ══════════════════════════════════════════════════════════════════════════════
# CONSTANTS
# ══════════════════════════════════════════════════════════════════════════════
PRED_HORIZON_DAYS = 2 # predict 2-day forward
FLAT_ATR_MULT = 0.6 # moves smaller than 0.6×ATR → labelled FLAT (excluded)
TRAIN_RATIO = 0.68
VAL_RATIO = 0.16 # remaining 0.16 → test
TRANSACTION_COST = 0.001 # 0.1% round-trip (brokerage + STT)
EMBARGO_DAYS = 5 # purged CV embargo gap
MARKET_SYMBOL = "^NSEI"
_MARKET_CACHE = None # populated once, shared across all stocks
# ── FIX [2]: only verified-working NSE index symbols ─────────────────────────
SECTOR_ETFS = {
"BANK" : "^NSEBANK",
"AUTO" : "^CNXAUTO",
"PHARMA" : "^CNXPHARMA",
"FMCG" : "^CNXFMCG",
"METAL" : "^CNXMETAL",
"ENERGY" : "^CNXENERGY",
"REALTY" : "^CNXREALTY",
"INFRA" : "^CNXINFRA",
"IT" : "^CNXIT",
"MNC" : "^CNXMNC",
"MEDIA" : "^CNXMEDIA",
"PSU" : "^CNXPSUBANK",
}
_SECTOR_CACHE = {}
# ── Load stock list ────────────────────────────────────────────────────────────
if not os.path.exists("nse_stocks.pkl"):
print("Run python stocks_list.py first!")
sys.exit(1)
with open("nse_stocks.pkl", "rb") as f:
STOCK_MAP = pickle.load(f)
STOCKS = [v["yf_symbol"] for v in STOCK_MAP.values()]
print(f"Loaded {len(STOCKS)} stocks\n")
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE LIST
# ══════════════════════════════════════════════════════════════════════════════
BASE_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",
"VolState_low", "VolState_mid", "VolState_high",
"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",
]
SECTOR_FEATURES = (
[f"SecRel_{k}_5" for k in SECTOR_ETFS] +
[f"SecRel_{k}_20" for k in SECTOR_ETFS]
)
FEATURES = BASE_FEATURES + SECTOR_FEATURES
# ══════════════════════════════════════════════════════════════════════════════
# 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):
match = [c for c in df.columns if c.startswith(prefix)]
if not match:
raise KeyError(f"No column with prefix '{prefix}'")
return match[0]
# ══════════════════════════════════════════════════════════════════════════════
# FIX [1]: VERSION-SAFE CALIBRATION
# Works on sklearn < 1.2 (no cv="prefit") AND sklearn >= 1.2
# ══════════════════════════════════════════════════════════════════════════════
def calibrate_model(fitted_model, X_val, y_val):
"""
Isotonic calibration on a held-out validation set.
Tries cv='prefit' first (sklearn >= 1.2).
Falls back to cv=2 on the val set (all sklearn versions).
Falls back to uncalibrated if everything fails.
"""
# Attempt 1 — cv='prefit' (sklearn >= 1.2)
try:
cal = CalibratedClassifierCV(fitted_model, method="isotonic", cv="prefit")
cal.fit(X_val, y_val)
return cal
except Exception:
pass
# Attempt 2 — cv=2 on val set (sklearn < 1.2)
try:
cal = CalibratedClassifierCV(fitted_model, method="isotonic", cv=2)
cal.fit(X_val, y_val)
return cal
except Exception:
pass
# Attempt 3 — sigmoid (simpler, always works)
try:
cal = CalibratedClassifierCV(fitted_model, method="sigmoid", cv=2)
cal.fit(X_val, y_val)
return cal
except Exception:
pass
# Last resort — return uncalibrated
return fitted_model
# ══════════════════════════════════════════════════════════════════════════════
# MARKET & SECTOR DATA
# ══════════════════════════════════════════════════════════════════════════════
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()
def load_sector_data(end_date):
"""Load NIFTY sector indices once; gracefully skip unavailable symbols."""
if _SECTOR_CACHE:
return _SECTOR_CACHE
for name, sym in SECTOR_ETFS.items():
try:
s = yf.download(sym, start="2014-01-01", end=end_date,
progress=False, auto_adjust=True)
if s is not None and not s.empty:
s = flatten_columns(s)
if "Close" in s.columns:
_SECTOR_CACHE[name] = s["Close"].copy()
except Exception:
pass # symbol unavailable → feature filled with 0
return _SECTOR_CACHE
# ══════════════════════════════════════════════════════════════════════════════
# FEATURE ENGINEERING
# ══════════════════════════════════════════════════════════════════════════════
def add_features(df):
close = df["Close"]
high = df["High"]
low = df["Low"]
volume = df["Volume"]
open_ = df["Open"]
# RSI
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
macd = ta.macd(close)
if macd is None:
raise ValueError("MACD returned 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)
# Moving averages
for length, label in [(10,"SMA_10"),(20,"SMA_20"),(50,"SMA_50"),(200,"SMA_200")]:
df[label] = ta.sma(close, length=length)
for length, label in [(9,"EMA_9"),(21,"EMA_21"),(50,"EMA_50")]:
df[label] = ta.ema(close, length=length)
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)
# Bollinger Bands
bb = ta.bbands(close, length=20)
if bb is None:
raise ValueError("BB returned 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)
# Volatility / ATR
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)
# Volume
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)
# Momentum / ROC
df["ROC_5"] = ta.roc(close, length=5)
df["ROC_10"] = ta.roc(close, length=10)
df["ROC_20"] = ta.roc(close, length=20)
for n in [1, 2, 3, 5, 10, 20]:
df[f"Return_{n}d"] = close.pct_change(n)
# Price position (10d / 20d / 52w range)
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)
# Candlestick geometry
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)
# Stochastic
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
# Williams %R
willr = ta.willr(high, low, close)
df["WILLR"] = willr if willr is not None else -50.0
# CCI
cci = ta.cci(high, low, close)
df["CCI"] = cci if cci is not None else 0.0
# ADX
adx = ta.adx(high, low, close)
if adx is not None:
ac = [c for c in adx.columns if c.startswith("ADX_")]
pc = [c for c in adx.columns if c.startswith("DMP_")]
nc = [c for c in adx.columns if c.startswith("DMN_")]
df["ADX"] = adx[ac[0]] if ac else 25.0
df["DI_plus"] = adx[pc[0]] if pc else 25.0
df["DI_minus"] = adx[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)
# Ichimoku
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)
# Regime / structure
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)
# 3-state volatility regime (one-hot)
rv = df["Volatility_20"].rolling(252)
vlo = rv.quantile(0.33)
vhi = rv.quantile(0.67)
df["VolState_low"] = (df["Volatility_20"] <= vlo).astype(int)
df["VolState_high"] = (df["Volatility_20"] >= vhi).astype(int)
df["VolState_mid"] = (
(df["Volatility_20"] > vlo) & (df["Volatility_20"] < vhi)
).astype(int)
# Time features
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 col in null_cols:
df[col] = 0.0
return df
m = market_df.reindex(df.index).copy()
mclose = m["Close"]
m["ret1"] = mclose.pct_change(1)
m["MKT_rsi_14"] = ta.rsi(mclose, length=14)
m["sma20"] = ta.sma(mclose, length=20)
m["sma50"] = ta.sma(mclose, length=50)
m["MKT_trend_20_50"] = (m["sma20"] > m["sma50"]).astype(float)
m["MKT_vol_10"] = m["ret1"].rolling(10).std()
df["MKT_ret_1d"] = m["ret1"]
df["MKT_ret_3d"] = mclose.pct_change(3)
df["MKT_ret_5d"] = mclose.pct_change(5)
df["MKT_rsi_14"] = m["MKT_rsi_14"]
df["MKT_trend_20_50"] = m["MKT_trend_20_50"]
df["MKT_vol_10"] = m["MKT_vol_10"]
sret = df["Close"].pct_change(1)
df["Rel_5"] = df["Close"].pct_change(5) - mclose.pct_change(5)
df["Rel_20"] = df["Close"].pct_change(20) - mclose.pct_change(20)
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
def add_sector_features(df, sector_data):
for name, sec_close in sector_data.items():
sec = sec_close.reindex(df.index)
for window in [5, 20]:
feat = f"SecRel_{name}_{window}"
df[feat] = df["Close"].pct_change(window) - sec.pct_change(window)
for feat in SECTOR_FEATURES:
if feat not in df.columns:
df[feat] = 0.0
return df
# ══════════════════════════════════════════════════════════════════════════════
# PURGED CROSS-VALIDATION (embargo gap prevents label leakage)
# ══════════════════════════════════════════════════════════════════════════════
def purged_ts_splits(n, n_splits=5, embargo=EMBARGO_DAYS):
fold_size = n // (n_splits + 1)
for k in range(n_splits):
test_start = (k + 1) * fold_size
test_end = test_start + fold_size
train_end = test_start - embargo
if train_end < 50 or test_end > n:
continue
yield np.arange(0, train_end), np.arange(test_start, min(test_end, n))
# ══════════════════════════════════════════════════════════════════════════════
# ENSEMBLE WEIGHT TUNER
# ══════════════════════════════════════════════════════════════════════════════
def tune_weighted_ensemble(val_probs, y_val, n_random=300):
n_models = len(val_probs)
rng = np.random.default_rng(42)
candidates = [np.ones(n_models) / n_models]
for i in range(n_models):
w = np.zeros(n_models)
w[i] = 1.0
candidates.append(w)
for _ in range(n_random):
candidates.append(rng.dirichlet(np.ones(n_models)))
best_w = candidates[0].copy()
best_thr = 0.50
best_acc = -1.0
for w in candidates:
ens = sum(w[i] * val_probs[i] for i in range(n_models))
for thr in np.arange(0.38, 0.63, 0.01):
acc = accuracy_score(y_val, (ens > thr).astype(int))
if acc > best_acc:
best_acc = acc
best_w = w.copy()
best_thr = thr
return best_w.tolist(), float(best_thr), float(best_acc)
# ══════════════════════════════════════════════════════════════════════════════
# WALK-FORWARD BACKTEST (with transaction costs)
# ══════════════════════════════════════════════════════════════════════════════
def walk_forward_backtest(df_full, X_all, y_all, n_windows=6, tc=TRANSACTION_COST):
n = len(X_all)
min_train = max(300, n // (n_windows + 2))
chunk = (n - min_train) // n_windows
if chunk < 30:
return {"error": "not enough data for walk-forward"}
oos_accs = []
daily_rets = []
last_pos = 0
for w in range(n_windows):
tr_end = min_train + w * chunk
te_end = tr_end + chunk
if te_end > n:
break
X_tr = X_all.iloc[:tr_end]; y_tr = y_all.iloc[:tr_end]
X_te = X_all.iloc[tr_end:te_end]; y_te = y_all.iloc[tr_end:te_end]
m = RandomForestClassifier(
n_estimators=200, max_depth=12, min_samples_split=15,
class_weight="balanced_subsample", random_state=42, n_jobs=-1
)
m.fit(X_tr, y_tr)
preds = m.predict(X_te)
probs = m.predict_proba(X_te)[:, 1]
oos_accs.append(accuracy_score(y_te, preds))
idx_range = df_full.index[tr_end:te_end]
actual_ret = df_full["Close"].pct_change(PRED_HORIZON_DAYS).reindex(idx_range)
for i, (pred, prob, ret) in enumerate(zip(preds, probs, actual_ret)):
if np.isnan(ret):
continue
new_pos = 1 if pred == 1 else -1
cost = tc if new_pos != last_pos else 0.0
daily_rets.append((idx_range[i], new_pos * ret - cost))
last_pos = new_pos
if not daily_rets:
return {"error": "no trades generated"}
idx, rets = zip(*daily_rets)
rs = pd.Series(list(rets), index=list(idx))
cum_log = np.log1p(rs).cumsum()
sharpe = float((rs.mean() / (rs.std() + 1e-9)) * np.sqrt(252))
cum = (1 + rs).cumprod()
max_dd = float(((cum - cum.cummax()) / (cum.cummax() + 1e-9)).min())
win_rate = float((rs > 0).mean())
tot_ret = float(np.expm1(cum_log.iloc[-1]) * 100)
return {
"pnl_curve" : cum_log,
"sharpe" : round(sharpe, 3),
"max_drawdown" : round(max_dd, 4),
"win_rate" : round(win_rate, 4),
"n_trades" : len(daily_rets),
"oos_accuracy" : round(float(np.mean(oos_accs)) * 100, 2),
"total_return" : round(tot_ret, 2),
}
# ══════════════════════════════════════════════════════════════════════════════
# SHAP FEATURE IMPORTANCE
# ══════════════════════════════════════════════════════════════════════════════
def compute_shap_importance(model, X_sample):
"""Mean |SHAP|. Falls back to feature_importances_ if shap unavailable."""
if not HAS_SHAP:
fi = getattr(model, "feature_importances_", None)
if fi is not None:
return dict(zip(X_sample.columns, fi.tolist()))
return {}
try:
exp = shap.TreeExplainer(model)
sv = exp.shap_values(X_sample)
if isinstance(sv, list):
sv = sv[1]
return dict(zip(X_sample.columns, np.abs(sv).mean(axis=0).tolist()))
except Exception:
fi = getattr(model, "feature_importances_", None)
if fi is not None:
return dict(zip(X_sample.columns, fi.tolist()))
return {}
# ══════════════════════════════════════════════════════════════════════════════
# KELLY CRITERION
# ══════════════════════════════════════════════════════════════════════════════
def kelly_fraction(win_rate, avg_win, avg_loss, fraction=0.25):
if avg_loss < 1e-9 or avg_win < 1e-9:
return 0.0
odds = avg_win / avg_loss
full_k = odds * win_rate - (1.0 - win_rate) / odds
return float(np.clip(full_k * fraction, 0.0, 1.0))
# ══════════════════════════════════════════════════════════════════════════════
# MAIN TRAINING FUNCTION
# ══════════════════════════════════════════════════════════════════════════════
def train_stock(symbol):
"""
Full pipeline for one symbol.
Returns ((result_dict, models_pkg), None) on success
or (None, error_string) on failure.
"""
t0 = time.time()
# ── Download ──────────────────────────────────────────────────────────────
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) < 450:
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()
# ── Feature engineering ───────────────────────────────────────────────────
try:
df = add_features(df)
except Exception as e:
return None, f"feature error: {e}"
market_df = load_market_data(end_date)
sector_data = load_sector_data(end_date)
df = add_market_features(df, market_df)
df = add_sector_features(df, sector_data)
df = df.replace([np.inf, -np.inf], np.nan)
# ── Target (2-day, ATR flat-move filtered) ────────────────────────────────
fc = df["Close"].shift(-PRED_HORIZON_DAYS)
fr = (fc - df["Close"]) / (df["Close"] + 1e-9)
flat_cut = (df["ATR_pct"] * FLAT_ATR_MULT).clip(lower=0.001)
df["Target"]= np.where(fc.notna() & (fr.abs() > flat_cut),
(fc > df["Close"]).astype(int), np.nan)
df.dropna(subset=["Target"], inplace=True)
df["Target"] = df["Target"].astype(int)
# ── Feature matrix (guarantee all features present) ───────────────────────
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) < 350:
return None, "too little usable data"
up_pct = int(y.mean() * 100)
# ── Purged CV ─────────────────────────────────────────────────────────────
cv_scores = []
for tr_idx, te_idx in purged_ts_splits(len(X), n_splits=5):
rf_cv = RandomForestClassifier(
n_estimators=120, class_weight="balanced_subsample",
random_state=42, n_jobs=-1
)
rf_cv.fit(X.iloc[tr_idx], y.iloc[tr_idx])
cv_scores.append(accuracy_score(y.iloc[te_idx], rf_cv.predict(X.iloc[te_idx])))
cv_acc = float(np.mean(cv_scores)) * 100 if cv_scores else 0.0
# ── Train / Val / Test split ──────────────────────────────────────────────
n = len(X)
tr_end = int(n * TRAIN_RATIO)
va_end = int(n * (TRAIN_RATIO + VAL_RATIO))
if tr_end < 220 or (va_end - tr_end) < 50 or (n - va_end) < 50:
return None, "insufficient samples after filtering"
X_tr, y_tr = X.iloc[:tr_end], y.iloc[:tr_end]
X_va, y_va = X.iloc[tr_end:va_end], y.iloc[tr_end:va_end]
X_te, y_te = X.iloc[va_end:], y.iloc[va_end:]
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)
# ── Train + calibrate each model ──────────────────────────────────────────
models = {}
val_probs = []
test_probs = []
lat_probs = []
model_names = []
def _add(name, raw, Xf, yf, Xv, Xt, Xl, do_cal=True):
raw.fit(Xf, yf)
fitted = calibrate_model(raw, Xv, y_va) if do_cal else raw
models[name] = fitted
val_probs.append(fitted.predict_proba(Xv)[:, 1])
test_probs.append(fitted.predict_proba(Xt)[:, 1])
lat_probs.append(float(fitted.predict_proba(Xl)[0][1]))
model_names.append(name)
# 1 — Random Forest
_add("rf",
RandomForestClassifier(
n_estimators=600, max_depth=16, min_samples_split=12,
min_samples_leaf=4, max_features="sqrt",
class_weight="balanced_subsample", random_state=42, n_jobs=-1),
X_tr, y_tr, X_va, X_te, latest)
# 2 — Extra Trees
_add("et",
ExtraTreesClassifier(
n_estimators=400, max_depth=14, min_samples_split=14,
class_weight="balanced", random_state=42, n_jobs=-1),
X_tr, y_tr, X_va, X_te, latest)
# 3 — Gradient Boosting (naturally calibrated — skip isotonic)
_add("gb",
GradientBoostingClassifier(
n_estimators=250, max_depth=3, learning_rate=0.04,
subsample=0.8, random_state=42),
X_tr, y_tr, X_va, X_te, latest, do_cal=False)
# 4 — Logistic Regression (scaled — skip isotonic)
_add("lr",
LogisticRegression(max_iter=1200, class_weight="balanced",
random_state=42, n_jobs=-1),
X_tr_sc, y_tr, X_va_sc, X_te_sc, latest_sc, do_cal=False)
# 5 — XGBoost
if HAS_XGB:
try:
xgb_r = XGBClassifier(
n_estimators=300, max_depth=5, learning_rate=0.04,
subsample=0.85, colsample_bytree=0.85,
reg_lambda=1.2, reg_alpha=0.1,
objective="binary:logistic", eval_metric="logloss",
random_state=42, n_jobs=-1, verbosity=0,
)
xgb_r.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=False)
cal = calibrate_model(xgb_r, X_va, y_va)
models["xgb"] = cal
val_probs.append(cal.predict_proba(X_va)[:, 1])
test_probs.append(cal.predict_proba(X_te)[:, 1])
lat_probs.append(float(cal.predict_proba(latest)[0][1]))
model_names.append("xgb")
print("xgb✓", end=" ", flush=True)
except Exception as e:
print(f"xgb_err({e})", end=" ", flush=True)
# 6 — LightGBM
if HAS_LGBM:
try:
lgbm_r = LGBMClassifier(
n_estimators=300, learning_rate=0.04, num_leaves=31,
subsample=0.85, colsample_bytree=0.85,
class_weight="balanced", random_state=42, verbose=-1,
)
lgbm_r.fit(X_tr, y_tr)
cal = calibrate_model(lgbm_r, X_va, y_va)
models["lgbm"] = cal
val_probs.append(cal.predict_proba(X_va)[:, 1])
test_probs.append(cal.predict_proba(X_te)[:, 1])
lat_probs.append(float(cal.predict_proba(latest)[0][1]))
model_names.append("lgbm")
print("lgbm✓", end=" ", flush=True)
except Exception as e:
print(f"lgbm_err({e})", end=" ", flush=True)
# ── Ensemble weights + threshold ──────────────────────────────────────────
best_weights, best_thr, best_val_acc = tune_weighted_ensemble(val_probs, y_va)
ens_test = sum(best_weights[i] * test_probs[i] for i in range(len(test_probs)))
final_pred = (ens_test > best_thr).astype(int)
final_acc = accuracy_score(y_te, final_pred) * 100
brier = round(float(brier_score_loss(y_te, ens_test)), 4)
ll = round(float(log_loss(y_te, ens_test)), 4)
# ── Latest prediction ─────────────────────────────────────────────────────
prob_up = float(sum(best_weights[i] * lat_probs[i] for i in range(len(lat_probs))))
pred = "UP" if prob_up > best_thr else "DOWN"
if prob_up > best_thr:
conf = round(((prob_up - best_thr) / (1.0 - best_thr + 1e-9)) * 100, 2)
else:
conf = round(((best_thr - prob_up) / (best_thr + 1e-9)) * 100, 2)
# ── Walk-forward backtest ─────────────────────────────────────────────────
wf = walk_forward_backtest(df, X, y, n_windows=6)
# ── Kelly fraction ────────────────────────────────────────────────────────
kelly = 0.0
if "win_rate" in wf:
te_rets = df["Close"].pct_change(PRED_HORIZON_DAYS).iloc[-len(y_te):]
up_r = te_rets[final_pred == 1]
dn_r = te_rets[final_pred == 0]
avg_win = float(up_r[up_r > 0].mean()) if len(up_r[up_r > 0]) > 0 else 0.01
avg_loss = float(abs(dn_r[dn_r < 0].mean())) if len(dn_r[dn_r < 0]) > 0 else 0.01
kelly = kelly_fraction(wf["win_rate"], avg_win, avg_loss, fraction=0.25)
# ── SHAP importance ───────────────────────────────────────────────────────
base_rf = getattr(models["rf"], "estimator", models["rf"])
shap_sample = X_te.iloc[:min(200, len(X_te))]
fi = compute_shap_importance(base_rf, shap_sample)
# ── Chart data (last 2 years) ─────────────────────────────────────────────
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")
for c in chart_df.select_dtypes("int64").columns:
chart_df[c] = chart_df[c].astype("int32")
# ── Result ────────────────────────────────────────────────────────────────
result = {
"symbol" : symbol,
"accuracy" : round(final_acc, 2),
"cv_accuracy" : round(cv_acc, 2),
"val_accuracy" : round(best_val_acc * 100, 2),
"brier_score" : brier,
"log_loss" : ll,
"prediction" : pred,
"confidence" : conf,
"prob_up" : round(prob_up * 100, 2),
"threshold" : round(best_thr, 3),
"ensemble_models" : model_names,
"ensemble_weights" : [round(float(w), 3) for w in best_weights],
"backtest" : {k: v for k, v in wf.items() if k != "pnl_curve"},
"pnl_curve" : wf.get("pnl_curve"),
"kelly_fraction" : round(kelly, 4),
"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),
"vol_state" : ("high" if df["VolState_high"].iloc[-1]
else "low" if df["VolState_low"].iloc[-1] else "mid"),
"class_balance_up" : up_pct,
"samples_train" : int(len(X_tr)),
"samples_val" : int(len(X_va)),
"samples_test" : int(len(X_te)),
"n_features" : len(FEATURES),
"feature_importance": fi,
"df" : chart_df,
"trained_at" : time.strftime("%Y-%m-%d %H:%M"),
"elapsed_sec" : round(time.time() - t0, 1),
}
models_pkg = {
"models" : models,
"scaler" : scaler,
"features" : FEATURES,
"threshold" : best_thr,
"ensemble_weights" : best_weights,
"ensemble_models" : model_names,
}
return (result, models_pkg), None
# ══════════════════════════════════════════════════════════════════════════════
# BATCH TRAINING MAIN
# ══════════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
os.makedirs("models", exist_ok=True)
results_path = "models/all_results.pkl"
FORCE_RETRAIN = os.environ.get("FORCE_RETRAIN", "0") == "1"
if os.path.exists(results_path) and not FORCE_RETRAIN:
with open(results_path, "rb") as f:
all_results = pickle.load(f)
print(f"Resuming — {len(all_results)} already done")
else:
all_results = {}
print("Starting fresh" + (" (FORCE_RETRAIN)" if FORCE_RETRAIN else ""))
remaining = [s for s in STOCKS if s not in all_results]
total = len(STOCKS)
done = len(all_results)
est_hrs = len(remaining) * 5.5 / 60
print(f"\nTotal : {total}")
print(f"Done : {done}")
print(f"Left : {len(remaining)}")
print(f"Est. : {est_hrs:.1f} hours")
print(f"Start : {time.strftime('%H:%M:%S')}")
print(f"Finish : {time.strftime('%H:%M', time.localtime(time.time() + est_hrs * 3600))}")
print("=" * 70 + "\n")
if not remaining:
print("All done! Run: python -m streamlit run app.py")
sys.exit(0)
t_start = time.time()
failed = []
saved_n = 0
for i, stock in enumerate(remaining, 1):
idx = done + i
print(f"[{idx}/{total}] {stock}", end=" ", flush=True)
out, err = train_stock(stock)
if err:
print(f"SKIP — {err}")
failed.append((stock, err))
continue
result, models_pkg = out
all_results[stock] = result
model_path = os.path.join("models", stock.replace(".", "_") + ".pkl")
with open(model_path, "wb") as f:
pickle.dump(models_pkg, f)
saved_n += 1
if saved_n % 10 == 0:
with open(results_path, "wb") as f:
pickle.dump(all_results, f)
print(f"\n [Checkpoint: {len(all_results)}/{total}]\n")
elapsed = (time.time() - t_start) / 60
eta = (len(remaining) - i) * (elapsed / i)
bt = result.get("backtest", {})
print(
f"Acc:{result['accuracy']:.1f}% "
f"CV:{result['cv_accuracy']:.1f}% "
f"Brier:{result['brier_score']:.3f} "
f"Sharpe:{bt.get('sharpe', 0):.2f} "
f"WinR:{bt.get('win_rate', 0):.2f} "
f"Kelly:{result['kelly_fraction']:.3f} "
f"UP%:{result['class_balance_up']}% "
f"{result['prediction']}({result['confidence']:.0f}%) "
f"ETA:{eta:.0f}m"
)
with open(results_path, "wb") as f:
pickle.dump(all_results, f)
mins = (time.time() - t_start) / 60
print(f"\nDONE — Trained {len(all_results)} stocks in {mins:.0f} min")
print(f"Failed : {len(failed)}")
for s, e in failed[:15]:
print(f" {s}: {e}")
print("\nNext step: python -m streamlit run app.py")