File size: 75,819 Bytes
c687548
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "29f93930",
   "metadata": {
    "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
    "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
    "execution": {
     "iopub.execute_input": "2025-06-30T18:33:21.460315Z",
     "iopub.status.busy": "2025-06-30T18:33:21.459991Z",
     "iopub.status.idle": "2025-06-30T18:33:22.876157Z",
     "shell.execute_reply": "2025-06-30T18:33:22.875331Z"
    },
    "papermill": {
     "duration": 1.420892,
     "end_time": "2025-06-30T18:33:22.877295",
     "exception": false,
     "start_time": "2025-06-30T18:33:21.456403",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/kaggle/input/drw-crypto-market-prediction/sample_submission.csv\n",
      "/kaggle/input/drw-crypto-market-prediction/train.parquet\n",
      "/kaggle/input/drw-crypto-market-prediction/test.parquet\n"
     ]
    }
   ],
   "source": [
    "# This Python 3 environment comes with many helpful analytics libraries installed\n",
    "# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n",
    "# For example, here's several helpful packages to load\n",
    "\n",
    "import numpy as np # linear algebra\n",
    "import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n",
    "\n",
    "# Input data files are available in the read-only \"../input/\" directory\n",
    "# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n",
    "\n",
    "import os\n",
    "for dirname, _, filenames in os.walk('/kaggle/input'):\n",
    "    for filename in filenames:\n",
    "        print(os.path.join(dirname, filename))\n",
    "\n",
    "# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n",
    "# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "722ea210",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-06-30T18:33:22.882612Z",
     "iopub.status.busy": "2025-06-30T18:33:22.882260Z",
     "iopub.status.idle": "2025-07-01T04:45:09.686323Z",
     "shell.execute_reply": "2025-07-01T04:45:09.685475Z"
    },
    "papermill": {
     "duration": 36706.813726,
     "end_time": "2025-07-01T04:45:09.693024",
     "exception": false,
     "start_time": "2025-06-30T18:33:22.879298",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using device: cpu\n",
      "Loaded data - Train: (525887, 32), Test: (538150, 31), Submission: (538150, 2)\n",
      "\n",
      "=== Outlier Analysis ===\n",
      "    Strategy 'reduce': Adjusted 525 outliers (0.1% of data)\n",
      "\n",
      "Total outliers detected: 525 (0.10%)\n",
      "\n",
      "Label statistics:\n",
      "  Normal samples - Mean: 0.0379, Std: 0.9730\n",
      "  Outlier samples - Mean: -1.7577, Std: 8.4272\n",
      "  Label range - Normal: [-15.8988, 20.7403]\n",
      "  Label range - Outliers: [-24.4166, 13.1532]\n",
      "\n",
      "Top features with extreme values in outliers:\n",
      "  X345: 974.9% difference (outlier: -0.2079, normal: 0.0238)\n",
      "  X598: 688.8% difference (outlier: -0.1776, normal: 0.0302)\n",
      "  buy_qty: 367.4% difference (outlier: 613.4614, normal: 131.2453)\n",
      "  X385: 121.7% difference (outlier: -0.0153, normal: 0.0704)\n",
      "  X168: 82.7% difference (outlier: 0.0255, normal: 0.1475)\n",
      "  X603: 82.2% difference (outlier: 0.2858, normal: 0.1568)\n",
      "  X174: 79.9% difference (outlier: 0.0296, normal: 0.1474)\n",
      "  X302: 72.7% difference (outlier: 0.0634, normal: 0.2318)\n",
      "  X415: 61.9% difference (outlier: 0.0684, normal: 0.1798)\n",
      "  X862: 58.3% difference (outlier: -0.8237, normal: -0.5202)\n",
      "\n",
      "=== Training XGBoost Models with Outlier Strategy Comparison ===\n",
      "\n",
      "==================================================\n",
      "Testing outlier strategy: REDUCE\n",
      "==================================================\n",
      "\n",
      "--- Fold 1/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 350591\n",
      "  Training slice: last_85pct, samples: 350591\n",
      "  Training slice: last_80pct, samples: 350591\n",
      "  Training slice: oldest_25pct, samples: 0\n",
      "    Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "    Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 350591\n",
      "    Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 350591\n",
      "    Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 350591\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 0\n",
      "\n",
      "--- Fold 2/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 298003\n",
      "  Training slice: last_85pct, samples: 271708\n",
      "  Training slice: last_80pct, samples: 245414\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "    Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "    Strategy 'reduce': Adjusted 298 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298003\n",
      "    Strategy 'reduce': Adjusted 271 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271708\n",
      "    Strategy 'reduce': Adjusted 245 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245414\n",
      "    Strategy 'reduce': Adjusted 131 outliers (0.1% of data)\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "--- Fold 3/3 ---\n",
      "  Training slice: full_data, samples: 350592\n",
      "  Training slice: last_90pct, samples: 298004\n",
      "  Training slice: last_85pct, samples: 271709\n",
      "  Training slice: last_80pct, samples: 245415\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "    Strategy 'reduce': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350592\n",
      "    Strategy 'reduce': Adjusted 298 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298004\n",
      "    Strategy 'reduce': Adjusted 271 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271709\n",
      "    Strategy 'reduce': Adjusted 245 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245415\n",
      "    Strategy 'reduce': Adjusted 131 outliers (0.1% of data)\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "REDUCE Strategy - Weighted Ensemble Pearson: 0.1101\n",
      "  full_data_outlier_adj: 0.1077 (weight: 0.112)\n",
      "  last_90pct_outlier_adj: 0.1096 (weight: 0.112)\n",
      "  last_85pct_outlier_adj: 0.1010 (weight: 0.112)\n",
      "  last_80pct_outlier_adj: 0.0992 (weight: 0.112)\n",
      "  oldest_25pct_outlier_adj: 0.0727 (weight: 0.025)\n",
      "\n",
      "==================================================\n",
      "Testing outlier strategy: REMOVE\n",
      "==================================================\n",
      "\n",
      "--- Fold 1/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 350591\n",
      "  Training slice: last_85pct, samples: 350591\n",
      "  Training slice: last_80pct, samples: 350591\n",
      "  Training slice: oldest_25pct, samples: 0\n",
      "    Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "    Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 350591\n",
      "    Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 350591\n",
      "    Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 350591\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 0\n",
      "\n",
      "--- Fold 2/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 298003\n",
      "  Training slice: last_85pct, samples: 271708\n",
      "  Training slice: last_80pct, samples: 245414\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "    Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "    Strategy 'remove': Adjusted 298 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298003\n",
      "    Strategy 'remove': Adjusted 271 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271708\n",
      "    Strategy 'remove': Adjusted 245 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245414\n",
      "    Strategy 'remove': Adjusted 131 outliers (0.1% of data)\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "--- Fold 3/3 ---\n",
      "  Training slice: full_data, samples: 350592\n",
      "  Training slice: last_90pct, samples: 298004\n",
      "  Training slice: last_85pct, samples: 271709\n",
      "  Training slice: last_80pct, samples: 245415\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "    Strategy 'remove': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350592\n",
      "    Strategy 'remove': Adjusted 298 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298004\n",
      "    Strategy 'remove': Adjusted 271 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271709\n",
      "    Strategy 'remove': Adjusted 245 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245415\n",
      "    Strategy 'remove': Adjusted 131 outliers (0.1% of data)\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "REMOVE Strategy - Weighted Ensemble Pearson: 0.1107\n",
      "  full_data_outlier_adj: 0.1092 (weight: 0.112)\n",
      "  last_90pct_outlier_adj: 0.1140 (weight: 0.112)\n",
      "  last_85pct_outlier_adj: 0.1009 (weight: 0.112)\n",
      "  last_80pct_outlier_adj: 0.0978 (weight: 0.112)\n",
      "  oldest_25pct_outlier_adj: 0.0738 (weight: 0.025)\n",
      "\n",
      "==================================================\n",
      "Testing outlier strategy: DOUBLE\n",
      "==================================================\n",
      "\n",
      "--- Fold 1/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 350591\n",
      "  Training slice: last_85pct, samples: 350591\n",
      "  Training slice: last_80pct, samples: 350591\n",
      "  Training slice: oldest_25pct, samples: 0\n",
      "    Strategy 'double': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "    Strategy 'double': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 350591\n",
      "    Strategy 'double': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 350591\n",
      "    Strategy 'double': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 350591\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 0\n",
      "\n",
      "--- Fold 2/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 298003\n",
      "  Training slice: last_85pct, samples: 271708\n",
      "  Training slice: last_80pct, samples: 245414\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "    Strategy 'double': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "    Strategy 'double': Adjusted 298 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298003\n",
      "    Strategy 'double': Adjusted 271 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271708\n",
      "    Strategy 'double': Adjusted 245 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245414\n",
      "    Strategy 'double': Adjusted 131 outliers (0.1% of data)\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "--- Fold 3/3 ---\n",
      "  Training slice: full_data, samples: 350592\n",
      "  Training slice: last_90pct, samples: 298004\n",
      "  Training slice: last_85pct, samples: 271709\n",
      "  Training slice: last_80pct, samples: 245415\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "    Strategy 'double': Adjusted 350 outliers (0.1% of data)\n",
      "  Training slice: full_data_outlier_adj, samples: 350592\n",
      "    Strategy 'double': Adjusted 298 outliers (0.1% of data)\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298004\n",
      "    Strategy 'double': Adjusted 271 outliers (0.1% of data)\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271709\n",
      "    Strategy 'double': Adjusted 245 outliers (0.1% of data)\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245415\n",
      "    Strategy 'double': Adjusted 131 outliers (0.1% of data)\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "DOUBLE Strategy - Weighted Ensemble Pearson: 0.1108\n",
      "  full_data_outlier_adj: 0.1085 (weight: 0.112)\n",
      "  last_90pct_outlier_adj: 0.1073 (weight: 0.112)\n",
      "  last_85pct_outlier_adj: 0.1060 (weight: 0.112)\n",
      "  last_80pct_outlier_adj: 0.1007 (weight: 0.112)\n",
      "  oldest_25pct_outlier_adj: 0.0684 (weight: 0.025)\n",
      "\n",
      "==================================================\n",
      "Testing outlier strategy: NONE\n",
      "==================================================\n",
      "\n",
      "--- Fold 1/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 350591\n",
      "  Training slice: last_85pct, samples: 350591\n",
      "  Training slice: last_80pct, samples: 350591\n",
      "  Training slice: oldest_25pct, samples: 0\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "  Training slice: last_90pct_outlier_adj, samples: 350591\n",
      "  Training slice: last_85pct_outlier_adj, samples: 350591\n",
      "  Training slice: last_80pct_outlier_adj, samples: 350591\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 0\n",
      "\n",
      "--- Fold 2/3 ---\n",
      "  Training slice: full_data, samples: 350591\n",
      "  Training slice: last_90pct, samples: 298003\n",
      "  Training slice: last_85pct, samples: 271708\n",
      "  Training slice: last_80pct, samples: 245414\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "  Training slice: full_data_outlier_adj, samples: 350591\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298003\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271708\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245414\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "--- Fold 3/3 ---\n",
      "  Training slice: full_data, samples: 350592\n",
      "  Training slice: last_90pct, samples: 298004\n",
      "  Training slice: last_85pct, samples: 271709\n",
      "  Training slice: last_80pct, samples: 245415\n",
      "  Training slice: oldest_25pct, samples: 131471\n",
      "  Training slice: full_data_outlier_adj, samples: 350592\n",
      "  Training slice: last_90pct_outlier_adj, samples: 298004\n",
      "  Training slice: last_85pct_outlier_adj, samples: 271709\n",
      "  Training slice: last_80pct_outlier_adj, samples: 245415\n",
      "  Training slice: oldest_25pct_outlier_adj, samples: 131471\n",
      "\n",
      "NONE Strategy - Weighted Ensemble Pearson: 0.1106\n",
      "  full_data_outlier_adj: 0.1121 (weight: 0.112)\n",
      "  last_90pct_outlier_adj: 0.1084 (weight: 0.112)\n",
      "  last_85pct_outlier_adj: 0.1032 (weight: 0.112)\n",
      "  last_80pct_outlier_adj: 0.1004 (weight: 0.112)\n",
      "  oldest_25pct_outlier_adj: 0.0737 (weight: 0.025)\n",
      "\n",
      "==================================================\n",
      "OUTLIER STRATEGY COMPARISON SUMMARY\n",
      "==================================================\n",
      "REDUCE: 0.1101 \n",
      "REMOVE: 0.1107 \n",
      "DOUBLE: 0.1108 ← BEST\n",
      "NONE: 0.1106 \n",
      "\n",
      "Relative performance vs 'reduce' strategy:\n",
      "  remove: +0.59%\n",
      "  double: +0.65%\n",
      "  none: +0.50%\n",
      "\n",
      "XGB Weighted Ensemble Pearson: 0.1108\n",
      "\n",
      "Individual slice OOF scores and weights:\n",
      "  full_data: 0.1121 (weight: 0.124)\n",
      "  last_90pct: 0.1084 (weight: 0.124)\n",
      "  last_85pct: 0.1032 (weight: 0.124)\n",
      "  last_80pct: 0.1004 (weight: 0.124)\n",
      "  oldest_25pct: 0.0737 (weight: 0.031)\n",
      "  full_data_outlier_adj: 0.1085 (weight: 0.112)\n",
      "  last_90pct_outlier_adj: 0.1073 (weight: 0.112)\n",
      "  last_85pct_outlier_adj: 0.1060 (weight: 0.112)\n",
      "  last_80pct_outlier_adj: 0.1007 (weight: 0.112)\n",
      "  oldest_25pct_outlier_adj: 0.0684 (weight: 0.025)\n",
      "\n",
      "Saved: submission_xgboost_double.csv\n",
      "\n",
      "=== Training MLP Model ===\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 1/10: 100%|██████████| 13/13 [00:07<00:00,  1.68it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 16059.1512\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.93it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.0700 | Loss: 15180.1740\n",
      "✅ New best model saved with Pearson: 0.0700\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 2/10: 100%|██████████| 13/13 [00:06<00:00,  2.02it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 15595.0242\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  3.01it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.0838 | Loss: 15198.4545\n",
      "✅ New best model saved with Pearson: 0.0838\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 3/10: 100%|██████████| 13/13 [00:06<00:00,  1.91it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 15456.7179\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  3.01it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.0992 | Loss: 15219.1834\n",
      "✅ New best model saved with Pearson: 0.0992\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 4/10: 100%|██████████| 13/13 [00:06<00:00,  2.04it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 15348.7826\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.97it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.1021 | Loss: 15224.5020\n",
      "✅ New best model saved with Pearson: 0.1021\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 5/10: 100%|██████████| 13/13 [00:06<00:00,  2.01it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 15229.8266\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.84it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.1045 | Loss: 15242.1837\n",
      "✅ New best model saved with Pearson: 0.1045\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 6/10: 100%|██████████| 13/13 [00:06<00:00,  1.89it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 15138.1736\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.99it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.1075 | Loss: 15256.6681\n",
      "✅ New best model saved with Pearson: 0.1075\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 7/10: 100%|██████████| 13/13 [00:06<00:00,  1.96it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 15046.1952\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.80it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.1046 | Loss: 15321.9877\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 8/10: 100%|██████████| 13/13 [00:06<00:00,  1.91it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 14938.4061\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.91it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.1099 | Loss: 15279.2798\n",
      "✅ New best model saved with Pearson: 0.1099\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 9/10: 100%|██████████| 13/13 [00:06<00:00,  1.89it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 14854.4186\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.88it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.1111 | Loss: 15291.8269\n",
      "✅ New best model saved with Pearson: 0.1111\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Epoch 10/10: 100%|██████████| 13/13 [00:07<00:00,  1.85it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training Loss: 14737.5036\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Validation: 100%|██████████| 4/4 [00:01<00:00,  2.71it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Validation Pearson Coef: 0.1117 | Loss: 15297.1565\n",
      "✅ New best model saved with Pearson: 0.1117\n",
      "Model loaded from best_mlp_model.pt with best Pearson: 0.1117\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Predicting: 100%|██████████| 17/17 [00:04<00:00,  3.75it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Saved: submission_mlp.csv\n",
      "\n",
      "Saved: submission_ensemble_double.csv (XGBoost: 90.0%, MLP: 10.0%)\n",
      "\n",
      "============================================================\n",
      "FINAL SUMMARY\n",
      "============================================================\n",
      "\n",
      "Best outlier strategy: DOUBLE\n",
      "Best XGBoost CV score: 0.1108\n",
      "\n",
      "Strategy comparison (XGBoost ensemble scores):\n",
      "  reduce: 0.1101\n",
      "  remove: 0.1107\n",
      "  double: 0.1108\n",
      "  none: 0.1106\n",
      "\n",
      "Created submission files:\n",
      "1. submission_xgboost_double.csv - XGBoost with double strategy\n",
      "2. submission_mlp.csv - MLP only\n",
      "3. submission_ensemble_double.csv - 90% XGBoost + 10% MLP\n",
      "\n",
      "Sample predictions (first 10 rows):\n",
      "   ID   XGBoost       MLP  Ensemble\n",
      "0   1  0.035090  0.217608  0.053342\n",
      "1   2  0.018095 -0.070474  0.009238\n",
      "2   3  0.136497  0.070964  0.129943\n",
      "3   4 -0.085066 -0.007894 -0.077348\n",
      "4   5  0.211597  0.238769  0.214314\n",
      "5   6 -0.172887 -0.198609 -0.175459\n",
      "6   7 -0.419656 -0.523997 -0.430090\n",
      "7   8 -0.154374 -0.422084 -0.181145\n",
      "8   9  0.222065 -0.204875  0.179371\n",
      "9  10  0.096913  0.106206  0.097842\n",
      "\n",
      "============================================================\n",
      "RECOMMENDATIONS\n",
      "============================================================\n",
      "\n",
      "1. Outlier Handling Impact:\n",
      "   ! Doubling outlier weights performs better\n",
      "   → This suggests outliers contain valuable signal for extreme movements\n",
      "\n",
      "2. Overfitting Risk Assessment:\n",
      "   ✓ Emphasizing outliers improves performance\n",
      "   → Model benefits from learning extreme patterns\n",
      "\n",
      "3. Next Steps:\n",
      "   • Test different outlier fractions (0.05%, 0.2%, 0.5%)\n",
      "   • Try adaptive outlier detection per time slice\n",
      "   • Consider feature-specific outlier handling\n",
      "   • Monitor LB score vs CV score for overfitting signs\n",
      "\n",
      "4. Outlier Insights:\n",
      "   • Detected 525 outliers (0.10% of data)\n",
      "   • Consider creating synthetic outliers if 'double' strategy works well\n",
      "   • Analyze time distribution of outliers for market regime insights\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import KFold, train_test_split\n",
    "from xgboost import XGBRegressor\n",
    "from scipy.stats import pearsonr\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from tqdm import tqdm\n",
    "import random\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n",
    "\n",
    "# Deep Learning imports\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torch.utils.data import DataLoader, TensorDataset\n",
    "\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "print(f\"Using device: {device}\")\n",
    "\n",
    "# =========================\n",
    "# Configuration\n",
    "# =========================\n",
    "class Config:\n",
    "    TRAIN_PATH = \"/kaggle/input/drw-crypto-market-prediction/train.parquet\"\n",
    "    TEST_PATH = \"/kaggle/input/drw-crypto-market-prediction/test.parquet\"\n",
    "    SUBMISSION_PATH = \"/kaggle/input/drw-crypto-market-prediction/sample_submission.csv\"\n",
    "\n",
    "    FEATURES = [\n",
    "        \"X863\", \"X856\", \"X598\", \"X862\", \"X385\", \"X852\", \"X603\", \"X860\", \"X674\",\n",
    "        \"X415\", \"X345\", \"X855\", \"X174\", \"X302\", \"X178\", \"X168\", \"X612\", \"bid_qty\",\n",
    "        \"ask_qty\", \"buy_qty\", \"sell_qty\", \"volume\", \"X888\", \"X421\", \"X333\",\"X817\", \n",
    "        \"X586\",  \"X292\"\n",
    "    ]\n",
    "    \n",
    "    # Features for MLP (subset)\n",
    "    MLP_FEATURES = [\n",
    "        \"X863\", \"X856\", \"X344\", \"X598\", \"X862\", \"X385\", \"X852\", \"X603\", \"X860\", \"X674\",\n",
    "        \"X415\", \"X345\", \"X137\", \"X855\", \"X174\", \"X302\", \"X178\", \"X532\", \"X168\", \"X612\",\n",
    "        \"bid_qty\", \"ask_qty\", \"buy_qty\", \"sell_qty\", \"volume\"\n",
    "    ]\n",
    "\n",
    "    LABEL_COLUMN = \"label\"\n",
    "    N_FOLDS = 3\n",
    "    RANDOM_STATE = 42\n",
    "    OUTLIER_FRACTION = 0.001  # 0.1% of records\n",
    "    \n",
    "    # Outlier handling strategies to test\n",
    "    OUTLIER_STRATEGIES = [\"reduce\", \"remove\", \"double\", \"none\"]\n",
    "\n",
    "XGB_PARAMS = {\n",
    "    \"tree_method\": \"hist\",\n",
    "    \"device\": \"gpu\" if torch.cuda.is_available() else \"cpu\",\n",
    "    \"colsample_bylevel\": 0.4778,\n",
    "    \"colsample_bynode\": 0.3628,\n",
    "    \"colsample_bytree\": 0.7107,\n",
    "    \"gamma\": 1.7095,\n",
    "    \"learning_rate\": 0.02213,\n",
    "    \"max_depth\": 20,\n",
    "    \"max_leaves\": 12,\n",
    "    \"min_child_weight\": 16,\n",
    "    \"n_estimators\": 1667,\n",
    "    \"subsample\": 0.06567,\n",
    "    \"reg_alpha\": 39.3524,\n",
    "    \"reg_lambda\": 75.4484,\n",
    "    \"verbosity\": 0,\n",
    "    \"random_state\": Config.RANDOM_STATE,\n",
    "    \"n_jobs\": -1\n",
    "}\n",
    "\n",
    "LEARNERS = [\n",
    "    {\"name\": \"xgb\", \"Estimator\": XGBRegressor, \"params\": XGB_PARAMS}\n",
    "]\n",
    "\n",
    "# =========================\n",
    "# Deep Learning Components\n",
    "# =========================\n",
    "def set_seed(seed=42):\n",
    "    random.seed(seed)\n",
    "    np.random.seed(seed)\n",
    "    torch.manual_seed(seed)\n",
    "    torch.cuda.manual_seed(seed)\n",
    "    torch.cuda.manual_seed_all(seed)\n",
    "    torch.backends.cudnn.deterministic = True\n",
    "    torch.backends.cudnn.benchmark = False\n",
    "\n",
    "def get_activation_function(name):\n",
    "    \"\"\"Return the activation function based on the name.\"\"\"\n",
    "    if name == None:\n",
    "        return None\n",
    "    name = name.lower()\n",
    "    if name == 'relu':\n",
    "        return nn.ReLU()\n",
    "    elif name == 'tanh':\n",
    "        return nn.Tanh()\n",
    "    elif name == 'sigmoid':\n",
    "        return nn.Sigmoid()\n",
    "    else:\n",
    "        raise ValueError(f\"Unsupported activation function: {name}\")\n",
    "\n",
    "class MLP(nn.Module):\n",
    "    def __init__(self, dropout_rate=0.6, \n",
    "                 layers=[128, 64], activation='relu', last_activation=None):\n",
    "        super(MLP, self).__init__()\n",
    "        \n",
    "        self.linears = nn.ModuleList()\n",
    "        self.activation = get_activation_function(activation)\n",
    "        self.last_activation = get_activation_function(last_activation)\n",
    "\n",
    "        for i in range(len(layers) - 1):\n",
    "            self.linears.append(nn.Linear(layers[i], layers[i + 1]))\n",
    "\n",
    "        self.dropout = nn.Dropout(dropout_rate)\n",
    "\n",
    "    def forward(self, x):\n",
    "        for k in range(len(self.linears) - 1):\n",
    "            x = self.activation(self.linears[k](x))\n",
    "            x = self.dropout(x)\n",
    "        x = self.linears[-1](x)\n",
    "        if self.last_activation is not None:\n",
    "            x = self.last_activation(x)\n",
    "        return x\n",
    "\n",
    "class Checkpointer:\n",
    "    def __init__(self, path=\"best_model.pt\"):\n",
    "        self.path = path\n",
    "        self.best_pearson = -np.inf\n",
    "\n",
    "    def load(self, model):\n",
    "        \"\"\"Load the best model weights.\"\"\"\n",
    "        model.load_state_dict(torch.load(self.path, map_location=device))\n",
    "        print(f\"Model loaded from {self.path} with best Pearson: {self.best_pearson:.4f}\")\n",
    "        return model\n",
    "\n",
    "    def __call__(self, pearson_coef, model):\n",
    "        \"\"\"Call method to save the model if the Pearson coefficient is better than the best one.\"\"\"\n",
    "        if pearson_coef > self.best_pearson:\n",
    "            self.best_pearson = pearson_coef\n",
    "            torch.save(model.state_dict(), self.path)\n",
    "            print(f\"✅ New best model saved with Pearson: {pearson_coef:.4f}\")\n",
    "\n",
    "def get_dataloaders(X, Y, hparams, device, shuffle=True):\n",
    "    \"\"\"Create DataLoader for training and validation datasets.\"\"\"\n",
    "    X_tensor = torch.tensor(X, dtype=torch.float32, device=device)\n",
    "    if Y is not None:\n",
    "        Y_tensor = torch.tensor(Y.values if hasattr(Y, 'values') else Y, \n",
    "                                dtype=torch.float32, device=device).unsqueeze(1)\n",
    "        dataset = TensorDataset(X_tensor, Y_tensor)\n",
    "    else:\n",
    "        dataset = TensorDataset(X_tensor)\n",
    "    \n",
    "    dataloader = DataLoader(dataset, batch_size=hparams[\"batch_size\"], shuffle=shuffle, \n",
    "                            generator=torch.Generator().manual_seed(hparams[\"seed\"]))\n",
    "    return dataloader\n",
    "\n",
    "# =========================\n",
    "# Feature Engineering\n",
    "# =========================\n",
    "def add_features(df):\n",
    "    # Original features\n",
    "    df['bid_ask_interaction'] = df['bid_qty'] * df['ask_qty']\n",
    "    df['bid_buy_interaction'] = df['bid_qty'] * df['buy_qty']\n",
    "    df['bid_sell_interaction'] = df['bid_qty'] * df['sell_qty']\n",
    "    df['ask_buy_interaction'] = df['ask_qty'] * df['buy_qty']\n",
    "    df['ask_sell_interaction'] = df['ask_qty'] * df['sell_qty']\n",
    "\n",
    "    df['volume_weighted_sell'] = df['sell_qty'] * df['volume']\n",
    "    df['buy_sell_ratio'] = df['buy_qty'] / (df['sell_qty'] + 1e-10)\n",
    "    df['selling_pressure'] = df['sell_qty'] / (df['volume'] + 1e-10)\n",
    "    df['log_volume'] = np.log1p(df['volume'])\n",
    "\n",
    "    df['effective_spread_proxy'] = np.abs(df['buy_qty'] - df['sell_qty']) / (df['volume'] + 1e-10)\n",
    "    df['bid_ask_imbalance'] = (df['bid_qty'] - df['ask_qty']) / (df['bid_qty'] + df['ask_qty'] + 1e-10)\n",
    "    df['order_flow_imbalance'] = (df['buy_qty'] - df['sell_qty']) / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n",
    "    df['liquidity_ratio'] = (df['bid_qty'] + df['ask_qty']) / (df['volume'] + 1e-10)\n",
    "    \n",
    "    # === NEW MICROSTRUCTURE FEATURES ===\n",
    "    \n",
    "    # Price Pressure Indicators\n",
    "    df['net_order_flow'] = df['buy_qty'] - df['sell_qty']\n",
    "    df['normalized_net_flow'] = df['net_order_flow'] / (df['volume'] + 1e-10)\n",
    "    df['buying_pressure'] = df['buy_qty'] / (df['volume'] + 1e-10)\n",
    "    df['volume_weighted_buy'] = df['buy_qty'] * df['volume']\n",
    "    \n",
    "    # Liquidity Depth Measures\n",
    "    df['total_depth'] = df['bid_qty'] + df['ask_qty']\n",
    "    df['depth_imbalance'] = (df['bid_qty'] - df['ask_qty']) / (df['total_depth'] + 1e-10)\n",
    "    df['relative_spread'] = np.abs(df['bid_qty'] - df['ask_qty']) / (df['total_depth'] + 1e-10)\n",
    "    df['log_depth'] = np.log1p(df['total_depth'])\n",
    "    \n",
    "    # Order Flow Toxicity Proxies\n",
    "    df['kyle_lambda'] = np.abs(df['net_order_flow']) / (df['volume'] + 1e-10)\n",
    "    df['flow_toxicity'] = np.abs(df['order_flow_imbalance']) * df['volume']\n",
    "    df['aggressive_flow_ratio'] = (df['buy_qty'] + df['sell_qty']) / (df['total_depth'] + 1e-10)\n",
    "    \n",
    "    # Market Activity Indicators\n",
    "    df['volume_depth_ratio'] = df['volume'] / (df['total_depth'] + 1e-10)\n",
    "    df['activity_intensity'] = (df['buy_qty'] + df['sell_qty']) / (df['volume'] + 1e-10)\n",
    "    df['log_buy_qty'] = np.log1p(df['buy_qty'])\n",
    "    df['log_sell_qty'] = np.log1p(df['sell_qty'])\n",
    "    df['log_bid_qty'] = np.log1p(df['bid_qty'])\n",
    "    df['log_ask_qty'] = np.log1p(df['ask_qty'])\n",
    "    \n",
    "    # Microstructure Volatility Proxies\n",
    "    df['realized_spread_proxy'] = 2 * np.abs(df['net_order_flow']) / (df['volume'] + 1e-10)\n",
    "    df['price_impact_proxy'] = df['net_order_flow'] / (df['total_depth'] + 1e-10)\n",
    "    df['quote_volatility_proxy'] = np.abs(df['depth_imbalance'])\n",
    "    \n",
    "    # Complex Interaction Terms\n",
    "    df['flow_depth_interaction'] = df['net_order_flow'] * df['total_depth']\n",
    "    df['imbalance_volume_interaction'] = df['order_flow_imbalance'] * df['volume']\n",
    "    df['depth_volume_interaction'] = df['total_depth'] * df['volume']\n",
    "    df['buy_sell_spread'] = np.abs(df['buy_qty'] - df['sell_qty'])\n",
    "    df['bid_ask_spread'] = np.abs(df['bid_qty'] - df['ask_qty'])\n",
    "    \n",
    "    # Information Asymmetry Measures\n",
    "    df['trade_informativeness'] = df['net_order_flow'] / (df['bid_qty'] + df['ask_qty'] + 1e-10)\n",
    "    df['execution_shortfall_proxy'] = df['buy_sell_spread'] / (df['volume'] + 1e-10)\n",
    "    df['adverse_selection_proxy'] = df['net_order_flow'] / (df['total_depth'] + 1e-10) * df['volume']\n",
    "    \n",
    "    # Market Efficiency Indicators\n",
    "    df['fill_probability'] = df['volume'] / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n",
    "    df['execution_rate'] = (df['buy_qty'] + df['sell_qty']) / (df['total_depth'] + 1e-10)\n",
    "    df['market_efficiency'] = df['volume'] / (df['bid_ask_spread'] + 1e-10)\n",
    "    \n",
    "    # Non-linear Transformations\n",
    "    df['sqrt_volume'] = np.sqrt(df['volume'])\n",
    "    df['sqrt_depth'] = np.sqrt(df['total_depth'])\n",
    "    df['volume_squared'] = df['volume'] ** 2\n",
    "    df['imbalance_squared'] = df['order_flow_imbalance'] ** 2\n",
    "    \n",
    "    # Relative Measures\n",
    "    df['bid_ratio'] = df['bid_qty'] / (df['total_depth'] + 1e-10)\n",
    "    df['ask_ratio'] = df['ask_qty'] / (df['total_depth'] + 1e-10)\n",
    "    df['buy_ratio'] = df['buy_qty'] / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n",
    "    df['sell_ratio'] = df['sell_qty'] / (df['buy_qty'] + df['sell_qty'] + 1e-10)\n",
    "    \n",
    "    # Market Stress Indicators\n",
    "    df['liquidity_consumption'] = (df['buy_qty'] + df['sell_qty']) / (df['total_depth'] + 1e-10)\n",
    "    df['market_stress'] = df['volume'] / (df['total_depth'] + 1e-10) * np.abs(df['order_flow_imbalance'])\n",
    "    df['depth_depletion'] = df['volume'] / (df['bid_qty'] + df['ask_qty'] + 1e-10)\n",
    "    \n",
    "    # Directional Indicators\n",
    "    df['net_buying_ratio'] = df['net_order_flow'] / (df['volume'] + 1e-10)\n",
    "    df['directional_volume'] = df['net_order_flow'] * np.log1p(df['volume'])\n",
    "    df['signed_volume'] = np.sign(df['net_order_flow']) * df['volume']\n",
    "    \n",
    "    # Replace infinities and NaNs\n",
    "    df = df.replace([np.inf, -np.inf], 0).fillna(0)\n",
    "    \n",
    "    return df\n",
    "\n",
    "def create_time_decay_weights(n: int, decay: float = 0.9) -> np.ndarray:\n",
    "    positions = np.arange(n)\n",
    "    normalized = positions / (n - 1) if n > 1 else positions\n",
    "    weights = decay ** (1.0 - normalized)\n",
    "    return weights * n / weights.sum()\n",
    "\n",
    "def detect_outliers_and_adjust_weights(X, y, sample_weights, outlier_fraction=0.001, strategy=\"reduce\"):\n",
    "    \"\"\"\n",
    "    Detect outliers based on prediction residuals and adjust their weights.\n",
    "    \n",
    "    Strategies:\n",
    "    - \"reduce\": Current approach - reduce weights to 0.2-0.8x\n",
    "    - \"remove\": Set outlier weights to 0 (effectively removing them)\n",
    "    - \"double\": Double the weights of outliers\n",
    "    - \"none\": No adjustment\n",
    "    \"\"\"\n",
    "    if strategy == \"none\":\n",
    "        return sample_weights, np.zeros(len(y), dtype=bool)\n",
    "    \n",
    "    # Ensure we have at least some samples to detect outliers\n",
    "    n_samples = len(y)\n",
    "    if n_samples < 100:  # Not enough samples for meaningful outlier detection\n",
    "        print(f\"    Too few samples ({n_samples}) for outlier detection\")\n",
    "        return sample_weights, np.zeros(n_samples, dtype=bool)\n",
    "    \n",
    "    # Train a simple model to get residuals\n",
    "    rf = RandomForestRegressor(n_estimators=50, max_depth=10, random_state=42, n_jobs=-1)\n",
    "    rf.fit(X, y, sample_weight=sample_weights)\n",
    "    \n",
    "    # Calculate residuals\n",
    "    predictions = rf.predict(X)\n",
    "    residuals = np.abs(y - predictions)\n",
    "    \n",
    "    # Find threshold for top outlier_fraction\n",
    "    # Ensure we have at least 1 outlier\n",
    "    n_outliers = max(1, int(len(residuals) * outlier_fraction))\n",
    "    \n",
    "    # Sort residuals and get threshold\n",
    "    sorted_residuals = np.sort(residuals)\n",
    "    threshold = sorted_residuals[-n_outliers] if n_outliers <= len(residuals) else sorted_residuals[-1]\n",
    "    \n",
    "    # Create outlier mask\n",
    "    outlier_mask = residuals >= threshold\n",
    "    \n",
    "    # Ensure we have exactly n_outliers (handle ties at threshold)\n",
    "    if np.sum(outlier_mask) > n_outliers:\n",
    "        # If we have too many due to ties, randomly select to get exact number\n",
    "        outlier_indices = np.where(outlier_mask)[0]\n",
    "        np.random.seed(42)\n",
    "        selected_indices = np.random.choice(outlier_indices, n_outliers, replace=False)\n",
    "        outlier_mask = np.zeros(len(y), dtype=bool)\n",
    "        outlier_mask[selected_indices] = True\n",
    "    \n",
    "    # Adjust weights based on strategy\n",
    "    adjusted_weights = sample_weights.copy()\n",
    "    \n",
    "    if outlier_mask.any():\n",
    "        if strategy == \"reduce\":\n",
    "            # Original approach: reduce weights proportionally\n",
    "            outlier_residuals = residuals[outlier_mask]\n",
    "            min_outlier_res = outlier_residuals.min()\n",
    "            max_outlier_res = outlier_residuals.max()\n",
    "            \n",
    "            if max_outlier_res > min_outlier_res:\n",
    "                normalized_residuals = (outlier_residuals - min_outlier_res) / (max_outlier_res - min_outlier_res)\n",
    "            else:\n",
    "                normalized_residuals = np.ones_like(outlier_residuals)\n",
    "            \n",
    "            weight_factors = 0.8 - 0.6 * normalized_residuals\n",
    "            adjusted_weights[outlier_mask] *= weight_factors\n",
    "            \n",
    "        elif strategy == \"remove\":\n",
    "            # Set outlier weights to 0\n",
    "            adjusted_weights[outlier_mask] = 0\n",
    "            \n",
    "        elif strategy == \"double\":\n",
    "            # Double the weights of outliers\n",
    "            adjusted_weights[outlier_mask] *= 2.0\n",
    "        \n",
    "        print(f\"    Strategy '{strategy}': Adjusted {n_outliers} outliers ({outlier_fraction*100:.1f}% of data)\")\n",
    "    \n",
    "    return adjusted_weights, outlier_mask\n",
    "\n",
    "def load_data():\n",
    "    # Load data with all features available\n",
    "    all_features = list(set(Config.FEATURES + Config.MLP_FEATURES))\n",
    "    train_df = pd.read_parquet(Config.TRAIN_PATH, columns=all_features + [Config.LABEL_COLUMN])\n",
    "    test_df = pd.read_parquet(Config.TEST_PATH, columns=all_features)\n",
    "    submission_df = pd.read_csv(Config.SUBMISSION_PATH)\n",
    "    print(f\"Loaded data - Train: {train_df.shape}, Test: {test_df.shape}, Submission: {submission_df.shape}\")\n",
    "\n",
    "    # Add features\n",
    "    train_df = add_features(train_df)\n",
    "    test_df = add_features(test_df)\n",
    "\n",
    "    # Update Config.FEATURES with new features\n",
    "    Config.FEATURES += [\n",
    "        \"log_volume\", 'bid_ask_interaction', 'bid_buy_interaction', 'bid_sell_interaction', \n",
    "        'ask_buy_interaction', 'ask_sell_interaction', 'net_order_flow', 'normalized_net_flow',\n",
    "        'buying_pressure', 'volume_weighted_buy', 'total_depth', 'depth_imbalance',\n",
    "        'relative_spread', 'log_depth', 'kyle_lambda', 'flow_toxicity', 'aggressive_flow_ratio',\n",
    "        'volume_depth_ratio', 'activity_intensity', 'log_buy_qty', 'log_sell_qty',\n",
    "        'log_bid_qty', 'log_ask_qty', 'realized_spread_proxy', 'price_impact_proxy',\n",
    "        'quote_volatility_proxy', 'flow_depth_interaction', 'imbalance_volume_interaction',\n",
    "        'depth_volume_interaction', 'buy_sell_spread', 'bid_ask_spread', 'trade_informativeness',\n",
    "        'execution_shortfall_proxy', 'adverse_selection_proxy', 'fill_probability',\n",
    "        'execution_rate', 'market_efficiency', 'sqrt_volume', 'sqrt_depth', 'volume_squared',\n",
    "        'imbalance_squared', 'bid_ratio', 'ask_ratio', 'buy_ratio', 'sell_ratio',\n",
    "        'liquidity_consumption', 'market_stress', 'depth_depletion', 'net_buying_ratio',\n",
    "        'directional_volume', 'signed_volume'\n",
    "    ]\n",
    "\n",
    "    return train_df.reset_index(drop=True), test_df.reset_index(drop=True), submission_df\n",
    "\n",
    "def get_model_slices(n_samples: int):\n",
    "    # Original 5 slices\n",
    "    base_slices = [\n",
    "        {\"name\": \"full_data\", \"cutoff\": 0, \"is_oldest\": False, \"outlier_adjusted\": False},\n",
    "        {\"name\": \"last_90pct\", \"cutoff\": int(0.10 * n_samples), \"is_oldest\": False, \"outlier_adjusted\": False},\n",
    "        {\"name\": \"last_85pct\", \"cutoff\": int(0.15 * n_samples), \"is_oldest\": False, \"outlier_adjusted\": False},\n",
    "        {\"name\": \"last_80pct\", \"cutoff\": int(0.20 * n_samples), \"is_oldest\": False, \"outlier_adjusted\": False},\n",
    "        {\"name\": \"oldest_25pct\", \"cutoff\": int(0.25 * n_samples), \"is_oldest\": True, \"outlier_adjusted\": False},\n",
    "    ]\n",
    "    \n",
    "    # Duplicate slices with outlier adjustment\n",
    "    outlier_adjusted_slices = []\n",
    "    for slice_info in base_slices:\n",
    "        adjusted_slice = slice_info.copy()\n",
    "        adjusted_slice[\"name\"] = f\"{slice_info['name']}_outlier_adj\"\n",
    "        adjusted_slice[\"outlier_adjusted\"] = True\n",
    "        outlier_adjusted_slices.append(adjusted_slice)\n",
    "    \n",
    "    return base_slices + outlier_adjusted_slices\n",
    "\n",
    "# =========================\n",
    "# Outlier Analysis Functions\n",
    "# =========================\n",
    "def analyze_outliers(train_df):\n",
    "    \"\"\"Analyze outliers in the training data\"\"\"\n",
    "    print(\"\\n=== Outlier Analysis ===\")\n",
    "    \n",
    "    X = train_df[Config.FEATURES].values\n",
    "    y = train_df[Config.LABEL_COLUMN].values\n",
    "    \n",
    "    # Get base weights\n",
    "    sample_weights = create_time_decay_weights(len(train_df))\n",
    "    \n",
    "    # Detect outliers\n",
    "    _, outlier_mask = detect_outliers_and_adjust_weights(\n",
    "        X, y, sample_weights, outlier_fraction=Config.OUTLIER_FRACTION, strategy=\"reduce\"\n",
    "    )\n",
    "    \n",
    "    # Analyze outlier characteristics\n",
    "    outlier_indices = np.where(outlier_mask)[0]\n",
    "    n_outliers = len(outlier_indices)\n",
    "    \n",
    "    print(f\"\\nTotal outliers detected: {n_outliers} ({n_outliers/len(train_df)*100:.2f}%)\")\n",
    "    \n",
    "    if n_outliers > 0:\n",
    "        # Statistical analysis\n",
    "        outlier_labels = y[outlier_mask]\n",
    "        normal_labels = y[~outlier_mask]\n",
    "        \n",
    "        print(f\"\\nLabel statistics:\")\n",
    "        print(f\"  Normal samples - Mean: {normal_labels.mean():.4f}, Std: {normal_labels.std():.4f}\")\n",
    "        print(f\"  Outlier samples - Mean: {outlier_labels.mean():.4f}, Std: {outlier_labels.std():.4f}\")\n",
    "        print(f\"  Label range - Normal: [{normal_labels.min():.4f}, {normal_labels.max():.4f}]\")\n",
    "        print(f\"  Label range - Outliers: [{outlier_labels.min():.4f}, {outlier_labels.max():.4f}]\")\n",
    "        \n",
    "        # Feature analysis for outliers\n",
    "        print(f\"\\nTop features with extreme values in outliers:\")\n",
    "        feature_names = Config.FEATURES[:20]  # Analyze first 20 features\n",
    "        outlier_features = train_df.iloc[outlier_indices][feature_names]\n",
    "        normal_features = train_df.iloc[~outlier_mask][feature_names]\n",
    "        \n",
    "        feature_diffs = []\n",
    "        for feat in feature_names:\n",
    "            outlier_mean = outlier_features[feat].mean()\n",
    "            normal_mean = normal_features[feat].mean()\n",
    "            if normal_mean != 0:\n",
    "                rel_diff = abs(outlier_mean - normal_mean) / abs(normal_mean)\n",
    "                feature_diffs.append((feat, rel_diff, outlier_mean, normal_mean))\n",
    "        \n",
    "        feature_diffs.sort(key=lambda x: x[1], reverse=True)\n",
    "        for feat, diff, out_mean, norm_mean in feature_diffs[:10]:\n",
    "            print(f\"  {feat}: {diff*100:.1f}% difference (outlier: {out_mean:.4f}, normal: {norm_mean:.4f})\")\n",
    "    else:\n",
    "        print(\"\\nNo outliers detected with current threshold. Consider adjusting outlier_fraction.\")\n",
    "    \n",
    "    return outlier_indices\n",
    "\n",
    "# =========================\n",
    "# XGBoost Training with Outlier Strategy Comparison\n",
    "# =========================\n",
    "def train_xgboost_with_outlier_comparison(train_df, test_df):\n",
    "    \"\"\"Train XGBoost with different outlier handling strategies and compare results\"\"\"\n",
    "    n_samples = len(train_df)\n",
    "    \n",
    "    # Store results for each strategy\n",
    "    strategy_results = {strategy: {\"oof_scores\": [], \"slice_scores\": {}} \n",
    "                       for strategy in Config.OUTLIER_STRATEGIES}\n",
    "    \n",
    "    # For final ensemble\n",
    "    best_strategy = \"reduce\"  # Default to current approach\n",
    "    best_score = -np.inf\n",
    "    best_oof_preds = None\n",
    "    best_test_preds = None\n",
    "    \n",
    "    for strategy in Config.OUTLIER_STRATEGIES:\n",
    "        print(f\"\\n{'='*50}\")\n",
    "        print(f\"Testing outlier strategy: {strategy.upper()}\")\n",
    "        print(f\"{'='*50}\")\n",
    "        \n",
    "        # Get model slices for this strategy\n",
    "        model_slices = get_model_slices(n_samples)\n",
    "        \n",
    "        oof_preds = {\n",
    "            learner[\"name\"]: {s[\"name\"]: np.zeros(n_samples) for s in model_slices}\n",
    "            for learner in LEARNERS\n",
    "        }\n",
    "        test_preds = {\n",
    "            learner[\"name\"]: {s[\"name\"]: np.zeros(len(test_df)) for s in model_slices}\n",
    "            for learner in LEARNERS\n",
    "        }\n",
    "        \n",
    "        full_weights = create_time_decay_weights(n_samples)\n",
    "        kf = KFold(n_splits=Config.N_FOLDS, shuffle=False)\n",
    "        \n",
    "        for fold, (train_idx, valid_idx) in enumerate(kf.split(train_df), start=1):\n",
    "            print(f\"\\n--- Fold {fold}/{Config.N_FOLDS} ---\")\n",
    "            X_valid = train_df.iloc[valid_idx][Config.FEATURES]\n",
    "            y_valid = train_df.iloc[valid_idx][Config.LABEL_COLUMN]\n",
    "            \n",
    "            for s in model_slices:\n",
    "                cutoff = s[\"cutoff\"]\n",
    "                slice_name = s[\"name\"]\n",
    "                is_oldest = s[\"is_oldest\"]\n",
    "                outlier_adjusted = s.get(\"outlier_adjusted\", False)\n",
    "                \n",
    "                if is_oldest:\n",
    "                    subset = train_df.iloc[:cutoff].reset_index(drop=True)\n",
    "                    rel_idx = train_idx[train_idx < cutoff]\n",
    "                    sw = np.ones(len(rel_idx))\n",
    "                else:\n",
    "                    subset = train_df.iloc[cutoff:].reset_index(drop=True)\n",
    "                    rel_idx = train_idx[train_idx >= cutoff] - cutoff\n",
    "                    sw = create_time_decay_weights(len(subset))[rel_idx] if cutoff > 0 else full_weights[train_idx]\n",
    "                \n",
    "                X_train = subset.iloc[rel_idx][Config.FEATURES]\n",
    "                y_train = subset.iloc[rel_idx][Config.LABEL_COLUMN]\n",
    "                \n",
    "                # Apply outlier strategy if this is an outlier-adjusted slice\n",
    "                if outlier_adjusted and len(X_train) > 100:\n",
    "                    sw, _ = detect_outliers_and_adjust_weights(\n",
    "                        X_train.values, \n",
    "                        y_train.values, \n",
    "                        sw, \n",
    "                        outlier_fraction=Config.OUTLIER_FRACTION,\n",
    "                        strategy=strategy\n",
    "                    )\n",
    "                \n",
    "                print(f\"  Training slice: {slice_name}, samples: {len(X_train)}\")\n",
    "                \n",
    "                for learner in LEARNERS:\n",
    "                    model = learner[\"Estimator\"](**learner[\"params\"])\n",
    "                    model.fit(X_train, y_train, sample_weight=sw, eval_set=[(X_valid, y_valid)], verbose=False)\n",
    "                    \n",
    "                    if is_oldest:\n",
    "                        oof_preds[learner[\"name\"]][slice_name][valid_idx] = model.predict(\n",
    "                            train_df.iloc[valid_idx][Config.FEATURES]\n",
    "                        )\n",
    "                    else:\n",
    "                        mask = valid_idx >= cutoff\n",
    "                        if mask.any():\n",
    "                            idxs = valid_idx[mask]\n",
    "                            oof_preds[learner[\"name\"]][slice_name][idxs] = model.predict(\n",
    "                                train_df.iloc[idxs][Config.FEATURES]\n",
    "                            )\n",
    "                        if cutoff > 0 and (~mask).any():\n",
    "                            base_slice_name = slice_name.replace(\"_outlier_adj\", \"\")\n",
    "                            if base_slice_name == slice_name:\n",
    "                                fallback_slice = \"full_data\"\n",
    "                            else:\n",
    "                                fallback_slice = \"full_data_outlier_adj\"\n",
    "                            oof_preds[learner[\"name\"]][slice_name][valid_idx[~mask]] = oof_preds[learner[\"name\"]][fallback_slice][\n",
    "                                valid_idx[~mask]\n",
    "                            ]\n",
    "                    \n",
    "                    test_preds[learner[\"name\"]][slice_name] += model.predict(test_df[Config.FEATURES])\n",
    "        \n",
    "        # Normalize test predictions\n",
    "        for learner_name in test_preds:\n",
    "            for slice_name in test_preds[learner_name]:\n",
    "                test_preds[learner_name][slice_name] /= Config.N_FOLDS\n",
    "        \n",
    "        # Evaluate this strategy\n",
    "        learner_name = 'xgb'\n",
    "        \n",
    "        # Weights for ensemble\n",
    "        weights = np.array([\n",
    "            1.0,   # full_data\n",
    "            1.0,   # last_90pct\n",
    "            1.0,   # last_85pct\n",
    "            1.0,   # last_80pct\n",
    "            0.25,  # oldest_25pct\n",
    "            0.9,   # full_data_outlier_adj\n",
    "            0.9,   # last_90pct_outlier_adj\n",
    "            0.9,   # last_85pct_outlier_adj\n",
    "            0.9,   # last_80pct_outlier_adj\n",
    "            0.2    # oldest_25pct_outlier_adj\n",
    "        ])\n",
    "        weights = weights / weights.sum()\n",
    "        \n",
    "        oof_weighted = pd.DataFrame(oof_preds[learner_name]).values @ weights\n",
    "        test_weighted = pd.DataFrame(test_preds[learner_name]).values @ weights\n",
    "        score_weighted = pearsonr(train_df[Config.LABEL_COLUMN], oof_weighted)[0]\n",
    "        \n",
    "        print(f\"\\n{strategy.upper()} Strategy - Weighted Ensemble Pearson: {score_weighted:.4f}\")\n",
    "        \n",
    "        # Store individual slice scores\n",
    "        slice_names = list(oof_preds[learner_name].keys())\n",
    "        for i, slice_name in enumerate(slice_names):\n",
    "            score = pearsonr(train_df[Config.LABEL_COLUMN], oof_preds[learner_name][slice_name])[0]\n",
    "            strategy_results[strategy][\"slice_scores\"][slice_name] = score\n",
    "            if \"outlier_adj\" in slice_name:\n",
    "                print(f\"  {slice_name}: {score:.4f} (weight: {weights[i]:.3f})\")\n",
    "        \n",
    "        strategy_results[strategy][\"oof_scores\"].append(score_weighted)\n",
    "        strategy_results[strategy][\"ensemble_score\"] = score_weighted\n",
    "        strategy_results[strategy][\"oof_preds\"] = oof_weighted\n",
    "        strategy_results[strategy][\"test_preds\"] = test_weighted\n",
    "        \n",
    "        # Track best strategy\n",
    "        if score_weighted > best_score:\n",
    "            best_score = score_weighted\n",
    "            best_strategy = strategy\n",
    "            best_oof_preds = oof_preds\n",
    "            best_test_preds = test_preds\n",
    "    \n",
    "    # Print comparison summary\n",
    "    print(f\"\\n{'='*50}\")\n",
    "    print(\"OUTLIER STRATEGY COMPARISON SUMMARY\")\n",
    "    print(f\"{'='*50}\")\n",
    "    \n",
    "    for strategy in Config.OUTLIER_STRATEGIES:\n",
    "        score = strategy_results[strategy][\"ensemble_score\"]\n",
    "        print(f\"{strategy.upper()}: {score:.4f} {'← BEST' if strategy == best_strategy else ''}\")\n",
    "    \n",
    "    # Analyze differences\n",
    "    print(f\"\\nRelative performance vs 'reduce' strategy:\")\n",
    "    reduce_score = strategy_results[\"reduce\"][\"ensemble_score\"]\n",
    "    for strategy in Config.OUTLIER_STRATEGIES:\n",
    "        if strategy != \"reduce\":\n",
    "            score = strategy_results[strategy][\"ensemble_score\"]\n",
    "            diff = (score - reduce_score) / reduce_score * 100\n",
    "            print(f\"  {strategy}: {diff:+.2f}%\")\n",
    "    \n",
    "    return best_oof_preds, best_test_preds, model_slices, strategy_results, best_strategy\n",
    "\n",
    "# =========================\n",
    "# MLP Training (unchanged)\n",
    "# =========================\n",
    "def train_mlp(train_df, test_df):\n",
    "    print(\"\\n=== Training MLP Model ===\")\n",
    "    \n",
    "    # Hyperparameters\n",
    "    hparams = {\n",
    "        \"seed\": 42,\n",
    "        \"num_epochs\": 10,\n",
    "        \"batch_size\": 1024 * 8 * 4,\n",
    "        \"learning_rate\": 0.001,\n",
    "        \"weight_decay\": 1e-3,\n",
    "        \"dropout_rate\": 0.6,\n",
    "        \"layers\": [len(Config.MLP_FEATURES), 256, 64, 1],\n",
    "        \"hidden_activation\": None,\n",
    "        \"activation\": \"relu\",\n",
    "        \"delta\": 5,\n",
    "        \"noise_factor\": 0.005\n",
    "    }\n",
    "    \n",
    "    set_seed(hparams[\"seed\"])\n",
    "    \n",
    "    # Prepare data for MLP\n",
    "    X_train_full = train_df[Config.MLP_FEATURES].values\n",
    "    y_train_full = train_df[Config.LABEL_COLUMN].values\n",
    "    \n",
    "    # Split for validation\n",
    "    X_train, X_val, y_train, y_val = train_test_split(\n",
    "        X_train_full, y_train_full, test_size=0.2, shuffle=False, random_state=42\n",
    "    )\n",
    "    \n",
    "    # Scale data\n",
    "    scaler = StandardScaler()\n",
    "    X_train = scaler.fit_transform(X_train)\n",
    "    X_val = scaler.transform(X_val)\n",
    "    X_test = scaler.transform(test_df[Config.MLP_FEATURES].values)\n",
    "    \n",
    "    # Create dataloaders\n",
    "    train_loader = get_dataloaders(X_train, y_train, hparams, device, shuffle=True)\n",
    "    val_loader = get_dataloaders(X_val, y_val, hparams, device, shuffle=False)\n",
    "    test_loader = get_dataloaders(X_test, None, hparams, device, shuffle=False)\n",
    "    \n",
    "    # Initialize model\n",
    "    model = MLP(\n",
    "        layers=hparams[\"layers\"],\n",
    "        dropout_rate=hparams[\"dropout_rate\"],\n",
    "        activation=hparams[\"activation\"],\n",
    "        last_activation=hparams[\"hidden_activation\"],\n",
    "    ).to(device)\n",
    "    \n",
    "    criterion = nn.HuberLoss(delta=hparams[\"delta\"], reduction='sum')\n",
    "    optimizer = optim.Adam(model.parameters(), lr=hparams[\"learning_rate\"], \n",
    "                          weight_decay=hparams[\"weight_decay\"])\n",
    "    \n",
    "    checkpointer = Checkpointer(path=\"best_mlp_model.pt\")\n",
    "    \n",
    "    # Training loop\n",
    "    num_epochs = hparams[\"num_epochs\"]\n",
    "    for epoch in range(num_epochs):\n",
    "        model.train()\n",
    "        running_loss = 0.0\n",
    "\n",
    "        for inputs, targets in tqdm(train_loader, desc=f\"Epoch {epoch+1}/{num_epochs}\"):\n",
    "            inputs, targets = inputs.to(device), targets.to(device)\n",
    "            \n",
    "            # Add noise for robustness\n",
    "            inputs = inputs + torch.randn_like(inputs) * hparams[\"noise_factor\"]\n",
    "            \n",
    "            optimizer.zero_grad()\n",
    "            outputs = model(inputs)\n",
    "            loss = criterion(outputs, targets)\n",
    "            \n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "            \n",
    "            running_loss += loss.item() * inputs.size(0)\n",
    "            \n",
    "        running_loss = running_loss / len(train_loader.dataset)\n",
    "        print(f\"Training Loss: {running_loss:.4f}\")\n",
    "\n",
    "        # Validation phase\n",
    "        model.eval()\n",
    "        val_loss = 0.0\n",
    "        preds = []\n",
    "        trues = []\n",
    "        with torch.no_grad():\n",
    "            for inputs, targets in tqdm(val_loader, desc=\"Validation\"):\n",
    "                inputs, targets = inputs.to(device), targets.to(device)\n",
    "                outputs = model(inputs)\n",
    "                loss = criterion(outputs, targets)\n",
    "                val_loss += loss.item() * inputs.size(0)\n",
    "                preds.append(outputs.cpu().numpy())\n",
    "                trues.append(targets.cpu().numpy())\n",
    "\n",
    "        val_loss /= len(val_loader.dataset)\n",
    "        preds = np.concatenate(preds).flatten()\n",
    "        trues = np.concatenate(trues).flatten()\n",
    "        pearson_coef = pearsonr(preds, trues)[0]\n",
    "        print(f\"Validation Pearson Coef: {pearson_coef:.4f} | Loss: {val_loss:.4f}\")\n",
    "\n",
    "        checkpointer(pearson_coef, model)\n",
    "    \n",
    "    # Load best model and make predictions\n",
    "    model = checkpointer.load(model)\n",
    "    model.eval()\n",
    "    predictions = []\n",
    "    with torch.no_grad():\n",
    "        for inputs in tqdm(test_loader, desc=\"Predicting\"):\n",
    "            inputs = inputs[0].to(device)\n",
    "            outputs = model(inputs)\n",
    "            predictions.append(outputs.cpu().numpy())\n",
    "\n",
    "    predictions = np.concatenate(predictions).flatten()\n",
    "    \n",
    "    return predictions\n",
    "\n",
    "# =========================\n",
    "# Ensemble & Submission Functions\n",
    "# =========================\n",
    "def create_xgboost_submission(train_df, oof_preds, test_preds, submission_df, strategy=\"reduce\"):\n",
    "    learner_name = 'xgb'\n",
    "    \n",
    "    # Weights for 10 slices\n",
    "    weights = np.array([\n",
    "        1.0,   # full_data\n",
    "        1.0,   # last_90pct\n",
    "        1.0,   # last_85pct\n",
    "        1.0,   # last_80pct\n",
    "        0.25,  # oldest_25pct\n",
    "        0.9,   # full_data_outlier_adj\n",
    "        0.9,   # last_90pct_outlier_adj\n",
    "        0.9,   # last_85pct_outlier_adj\n",
    "        0.9,   # last_80pct_outlier_adj\n",
    "        0.2    # oldest_25pct_outlier_adj\n",
    "    ])\n",
    "    \n",
    "    # Normalize weights\n",
    "    weights = weights / weights.sum()\n",
    "\n",
    "    oof_weighted = pd.DataFrame(oof_preds[learner_name]).values @ weights\n",
    "    test_weighted = pd.DataFrame(test_preds[learner_name]).values @ weights\n",
    "    score_weighted = pearsonr(train_df[Config.LABEL_COLUMN], oof_weighted)[0]\n",
    "    print(f\"\\n{learner_name.upper()} Weighted Ensemble Pearson: {score_weighted:.4f}\")\n",
    "\n",
    "    # Print individual slice scores and weights for analysis\n",
    "    print(\"\\nIndividual slice OOF scores and weights:\")\n",
    "    slice_names = list(oof_preds[learner_name].keys())\n",
    "    for i, slice_name in enumerate(slice_names):\n",
    "        score = pearsonr(train_df[Config.LABEL_COLUMN], oof_preds[learner_name][slice_name])[0]\n",
    "        print(f\"  {slice_name}: {score:.4f} (weight: {weights[i]:.3f})\")\n",
    "\n",
    "    # Save XGBoost submission\n",
    "    xgb_submission = submission_df.copy()\n",
    "    xgb_submission[\"prediction\"] = test_weighted\n",
    "    xgb_submission.to_csv(f\"submission_xgboost_{strategy}.csv\", index=False)\n",
    "    print(f\"\\nSaved: submission_xgboost_{strategy}.csv\")\n",
    "    \n",
    "    return test_weighted\n",
    "\n",
    "def create_ensemble_submission(xgb_predictions, mlp_predictions, submission_df, \n",
    "                             xgb_weight=0.9, mlp_weight=0.1, suffix=\"\"):\n",
    "    # Ensemble predictions\n",
    "    ensemble_predictions = (xgb_weight * xgb_predictions + \n",
    "                          mlp_weight * mlp_predictions)\n",
    "    \n",
    "    # Save ensemble submission\n",
    "    ensemble_submission = submission_df.copy()\n",
    "    ensemble_submission[\"prediction\"] = ensemble_predictions\n",
    "    filename = f\"submission_ensemble{suffix}.csv\"\n",
    "    ensemble_submission.to_csv(filename, index=False)\n",
    "    print(f\"\\nSaved: {filename} (XGBoost: {xgb_weight*100}%, MLP: {mlp_weight*100}%)\")\n",
    "    \n",
    "    return ensemble_predictions\n",
    "\n",
    "# =========================\n",
    "# Main Execution\n",
    "# =========================\n",
    "if __name__ == \"__main__\":\n",
    "    # Load data\n",
    "    train_df, test_df, submission_df = load_data()\n",
    "    \n",
    "    # Analyze outliers\n",
    "    outlier_indices = analyze_outliers(train_df)\n",
    "    \n",
    "    # Train XGBoost with outlier comparison\n",
    "    print(\"\\n=== Training XGBoost Models with Outlier Strategy Comparison ===\")\n",
    "    best_oof_preds, best_test_preds, model_slices, strategy_results, best_strategy = \\\n",
    "        train_xgboost_with_outlier_comparison(train_df, test_df)\n",
    "    \n",
    "    # Create XGBoost submission with best strategy\n",
    "    xgb_predictions = create_xgboost_submission(\n",
    "        train_df, best_oof_preds, best_test_preds, submission_df, strategy=best_strategy\n",
    "    )\n",
    "    \n",
    "    # Train MLP model\n",
    "    mlp_predictions = train_mlp(train_df, test_df)\n",
    "    \n",
    "    # Save MLP submission\n",
    "    mlp_submission = submission_df.copy()\n",
    "    mlp_submission[\"prediction\"] = mlp_predictions\n",
    "    mlp_submission.to_csv(\"submission_mlp.csv\", index=False)\n",
    "    print(\"\\nSaved: submission_mlp.csv\")\n",
    "    \n",
    "    # Create ensemble submission\n",
    "    ensemble_predictions = create_ensemble_submission(\n",
    "        xgb_predictions, mlp_predictions, submission_df,\n",
    "        xgb_weight=0.9, mlp_weight=0.1, suffix=f\"_{best_strategy}\"\n",
    "    )\n",
    "    \n",
    "    # Print final summary\n",
    "    print(\"\\n\" + \"=\"*60)\n",
    "    print(\"FINAL SUMMARY\")\n",
    "    print(\"=\"*60)\n",
    "    print(f\"\\nBest outlier strategy: {best_strategy.upper()}\")\n",
    "    print(f\"Best XGBoost CV score: {strategy_results[best_strategy]['ensemble_score']:.4f}\")\n",
    "    \n",
    "    print(\"\\nStrategy comparison (XGBoost ensemble scores):\")\n",
    "    for strategy in Config.OUTLIER_STRATEGIES:\n",
    "        score = strategy_results[strategy][\"ensemble_score\"]\n",
    "        print(f\"  {strategy}: {score:.4f}\")\n",
    "    \n",
    "    print(\"\\nCreated submission files:\")\n",
    "    print(f\"1. submission_xgboost_{best_strategy}.csv - XGBoost with {best_strategy} strategy\")\n",
    "    print(f\"2. submission_mlp.csv - MLP only\")\n",
    "    print(f\"3. submission_ensemble_{best_strategy}.csv - 90% XGBoost + 10% MLP\")\n",
    "    \n",
    "    # Show sample predictions\n",
    "    print(\"\\nSample predictions (first 10 rows):\")\n",
    "    comparison_df = pd.DataFrame({\n",
    "        'ID': submission_df['ID'][:10],\n",
    "        'XGBoost': xgb_predictions[:10],\n",
    "        'MLP': mlp_predictions[:10],\n",
    "        'Ensemble': ensemble_predictions[:10]\n",
    "    })\n",
    "    print(comparison_df)\n",
    "    \n",
    "    # Provide recommendations\n",
    "    print(\"\\n\" + \"=\"*60)\n",
    "    print(\"RECOMMENDATIONS\")\n",
    "    print(\"=\"*60)\n",
    "    \n",
    "    reduce_score = strategy_results[\"reduce\"][\"ensemble_score\"]\n",
    "    remove_score = strategy_results[\"remove\"][\"ensemble_score\"]\n",
    "    double_score = strategy_results[\"double\"][\"ensemble_score\"]\n",
    "    none_score = strategy_results[\"none\"][\"ensemble_score\"]\n",
    "    \n",
    "    print(\"\\n1. Outlier Handling Impact:\")\n",
    "    if best_strategy == \"reduce\":\n",
    "        print(\"   ✓ Current approach (reduce weights) is optimal\")\n",
    "    elif best_strategy == \"remove\":\n",
    "        print(\"   ! Removing outliers completely performs better\")\n",
    "        print(\"   → This suggests outliers are noise rather than informative extremes\")\n",
    "    elif best_strategy == \"double\":\n",
    "        print(\"   ! Doubling outlier weights performs better\")\n",
    "        print(\"   → This suggests outliers contain valuable signal for extreme movements\")\n",
    "    else:\n",
    "        print(\"   ! No outlier adjustment performs better\")\n",
    "        print(\"   → This suggests the model can handle outliers naturally\")\n",
    "    \n",
    "    print(\"\\n2. Overfitting Risk Assessment:\")\n",
    "    if remove_score > reduce_score and remove_score > double_score:\n",
    "        print(\"   ⚠ Removing outliers improves CV but may increase overfitting risk\")\n",
    "        print(\"   → Consider using reduce strategy for better generalization\")\n",
    "    elif double_score > reduce_score:\n",
    "        print(\"   ✓ Emphasizing outliers improves performance\")\n",
    "        print(\"   → Model benefits from learning extreme patterns\")\n",
    "    \n",
    "    print(\"\\n3. Next Steps:\")\n",
    "    print(\"   • Test different outlier fractions (0.05%, 0.2%, 0.5%)\")\n",
    "    print(\"   • Try adaptive outlier detection per time slice\")\n",
    "    print(\"   • Consider feature-specific outlier handling\")\n",
    "    print(\"   • Monitor LB score vs CV score for overfitting signs\")\n",
    "    \n",
    "    # Additional insights based on outlier analysis\n",
    "    if len(outlier_indices) > 0:\n",
    "        print(f\"\\n4. Outlier Insights:\")\n",
    "        print(f\"   • Detected {len(outlier_indices)} outliers ({len(outlier_indices)/len(train_df)*100:.2f}% of data)\")\n",
    "        print(\"   • Consider creating synthetic outliers if 'double' strategy works well\")\n",
    "        print(\"   • Analyze time distribution of outliers for market regime insights\")"
   ]
  }
 ],
 "metadata": {
  "kaggle": {
   "accelerator": "none",
   "dataSources": [
    {
     "databundleVersionId": 11418275,
     "sourceId": 96164,
     "sourceType": "competition"
    }
   ],
   "isGpuEnabled": false,
   "isInternetEnabled": true,
   "language": "python",
   "sourceType": "notebook"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  },
  "papermill": {
   "default_parameters": {},
   "duration": 36715.5898,
   "end_time": "2025-07-01T04:45:13.424631",
   "environment_variables": {},
   "exception": null,
   "input_path": "__notebook__.ipynb",
   "output_path": "__notebook__.ipynb",
   "parameters": {},
   "start_time": "2025-06-30T18:33:17.834831",
   "version": "2.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}