-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlined_ipo_scanner.py
More file actions
4703 lines (4051 loc) · 220 KB
/
Copy pathstreamlined_ipo_scanner.py
File metadata and controls
4703 lines (4051 loc) · 220 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
streamlined_ipo_scanner.py
Optimized IPO breakout scanner:
- Dynamic symbol list (recent IPOs + active positions)
- Enhanced entry filters and grading
- Dynamic partial profit taking by grade
- SuperTrend trailing stops for winners
- Smart exit logic (stop-loss, persistent losers)
- Weekly and monthly summary commands
- Dry-run and heartbeat modes
"""
SCANNER_VERSION = "3.3.0" # v3.3.0: Volume floor, base-duration guard fix, 20-day patience stop, Limit Buy alerts
LOG_SCHEMA_VERSION = "2026-04-23.v1"
import os
import sys
import argparse
import pickle
import pandas as pd
import numpy as np
import requests
import time
from datetime import datetime, timedelta, timezone
from dotenv import load_dotenv
import threading
IST = timezone(timedelta(hours=5, minutes=30))
# Institutional Analytics & Enrichment (Phase 2.2 Upgrade)
try:
from core.repository import MongoRepository
from integration.signal_builder import SignalBuilder
from lifecycle.tracker import LifecycleTracker
from lifecycle.evaluator import evaluate_signal_outcome
ANALYTICS_AVAILABLE = True
except ImportError as e:
print(f"⚠️ Analytics modules not found: {e}")
ANALYTICS_AVAILABLE = False
# Try to import yfinance, fallback if not available
try:
import yfinance as yf
YFINANCE_AVAILABLE = True
except ImportError:
YFINANCE_AVAILABLE = False
class IntegrationBridge:
"""Bridge between legacy scanner loops and v2 institutional telemetry."""
def __init__(self):
try:
from core.repository import MongoRepository
from integration.signal_builder import SignalBuilder
self.repo = MongoRepository()
self.builder = SignalBuilder()
self.active = True
except Exception as e:
# We don't want to crash the main scanner if bridge fails
import logging
logging.getLogger(__name__).warning(f"🏛️ Institutional Bridge failed to initialize: {e}")
self.active = False
def save_signal(self, raw_payload, candle=None, history=None, base_candles=None):
"""Builds and saves an institutional signal from raw scanner data."""
if not self.active:
return False
try:
# Fallback for data objects if not passed explicitly
c = candle if candle is not None else raw_payload.get('_candle')
h = history if history is not None else raw_payload.get('_history')
b = base_candles if base_candles is not None else raw_payload.get('_base_candles', h)
# Fetch sector/industry if missing
if 'sector' not in raw_payload or raw_payload['sector'] == 'Unknown':
try:
import yfinance as yf
ticker = yf.Ticker(f"{raw_payload['symbol']}.NS")
raw_payload['sector'] = ticker.info.get('sector', 'Unknown')
raw_payload['industry'] = ticker.info.get('industry', 'Unknown')
except:
pass
# Use global SCANNER_VERSION
signal_v2 = self.builder.build_signal(raw_payload, c, h, b, SCANNER_VERSION)
self.repo.save_signal(signal_v2)
return True
except Exception as e:
import logging
logging.getLogger(__name__).error(f"🏛️ IntegrationBridge Save Failed: {e}")
return False
# ── Research Metadata Helpers (Phase 2.3) ──────────────────────────────────
# Pattern archetypes are observational labels ONLY — not separate strategies.
PATTERN_IPO_DISCOVERY = "PATTERN_IPO_DISCOVERY"
PATTERN_CONSOLIDATION_BREAKOUT = "PATTERN_CONSOLIDATION_BREAKOUT"
PATTERN_RUNAWAY_GAP = "PATTERN_RUNAWAY_GAP"
PATTERN_EARLY_CONTINUATION = "PATTERN_EARLY_CONTINUATION"
PATTERN_RECOVERY_BREAKOUT = "PATTERN_RECOVERY_BREAKOUT"
# --- Phase 3: Model Validation Buckets (Scientific Research Refactor) ---
BUCKET_ALIGNED = "ALIGNED" # Meets all current heuristic alpha rules
BUCKET_EXTENDED = "EXTENDED" # Structurally valid but Out-of-Sample (for research)
BUCKET_BROKEN = "BROKEN" # Structurally flawed or erratic action
# --- Reason Codes (Hard Fields for Analytics) ---
RC_OK = "OK"
RC_PRNG_LIMIT = "PRNG_LIMIT" # PRNG > 25.0
RC_VOL_LIMIT = "VOL_LIMIT" # Volume ratio < 1.2
RC_NON_IPO_CONTEXT = "NON_IPO_CONTEXT" # Days since listing > LISTING_MAX_DAYS_SINCE_LISTING
RC_STRUCTURE_FAILED = "STRUCTURE_FAILED" # Price broke base low during window
RC_ERRATIC_VOLATILITY = "ERRATIC_VOLATILITY" # PRNG > 45.0 (No longer a base)
RC_LIQUIDITY_TRAP = "LIQUIDITY_TRAP" # Low turnover or frequent circuits
RC_MICROCAP_PENALTY = "MICROCAP_PENALTY" # Market cap below floor
def categorize_signal_bucket(metrics: dict, days_since_listing: int) -> tuple:
"""
Objective signal categorization into ALIGNED, EXTENDED, or BROKEN.
Returns (bucket, reason_codes_list).
"""
reasons = []
prng = metrics.get("prng", 0)
vol_ratio = metrics.get("vol_ratio", 0)
# 1. Structural Checks (BROKEN)
if prng > 45.0:
reasons.append(RC_ERRATIC_VOLATILITY)
if days_since_listing > LISTING_MAX_DAYS_SINCE_LISTING:
reasons.append(RC_NON_IPO_CONTEXT)
if reasons:
return BUCKET_BROKEN, reasons
# 2. Heuristic Alignment Checks (EXTENDED)
if prng > 25.0:
reasons.append(RC_PRNG_LIMIT)
if vol_ratio < 1.2:
reasons.append(RC_VOL_LIMIT)
if reasons:
return BUCKET_EXTENDED, reasons
# 3. Strategy Alignment (EXTENDED)
if days_since_listing < MIN_AGE_DAYS:
reasons.append("ULTRA_FRESH_IPO")
# 4. Institutional Liquidity Hardening (Phase 2.5)
mcap = metrics.get("market_cap_cr", 0)
turnover = metrics.get("avg_turnover_cr", 0)
circuits = metrics.get("circuit_days_15", 0)
if turnover > 0 and turnover < MIN_DAILY_TURNOVER_CR:
reasons.append(RC_LIQUIDITY_TRAP)
if circuits >= 3:
reasons.append(f"{RC_LIQUIDITY_TRAP}_CIRCUITS")
if mcap > 0 and mcap < MIN_MARKET_CAP_CR:
reasons.append(RC_MICROCAP_PENALTY)
if reasons:
# If it's a liquidity trap or microcap, it's BROKEN (Avoid capital lock-in)
if RC_LIQUIDITY_TRAP in reasons or f"{RC_LIQUIDITY_TRAP}_CIRCUITS" in reasons:
return BUCKET_BROKEN, reasons
return BUCKET_EXTENDED, reasons
return BUCKET_ALIGNED, [RC_OK]
def classify_pattern_type(grade: str, days_since_listing: int, vol_ratio: float, prng: float) -> str:
"""Assign an observational pattern archetype. Classification ONLY — no live logic."""
if grade == "LISTING_BREAKOUT" or days_since_listing <= 10:
return PATTERN_IPO_DISCOVERY
if vol_ratio >= 5.0 and prng < 8:
return PATTERN_RUNAWAY_GAP
if days_since_listing <= 30 and prng < 15:
return PATTERN_EARLY_CONTINUATION
if prng > 25:
return PATTERN_RECOVERY_BREAKOUT
return PATTERN_CONSOLIDATION_BREAKOUT
# Global cache for Nifty data to avoid redundant API calls
_nifty_regime_cache = {}
# ---------------------------------------------------------------------------
# Winner Trait Classifier
# Derived from DB quality analysis (2026-05-21):
# • Grade B+ outperforms C by +7% avg PnL
# • Windows 10 & 20 avg +3.85% / +3.38%; window 40 avg -17.93%
# • 72% of signals fired in Nifty downtrend (slope<0) → most losses
# • Tight base (<18%) + high volume (>1.5x) = institutional fingerprint
# ---------------------------------------------------------------------------
def classify_winner_traits(
grade: str,
consolidation_window: int,
volume_ratio: float,
consolidation_range_pct: float,
nifty_slope: float = None,
) -> dict:
"""
Score a new signal against known winner-pattern criteria.
Returns a dict with:
winner_label : 'POSSIBLE_WINNER_EXPERIMENTAL' | 'STANDARD' | 'WATCHLIST_ONLY'
winner_score : 0-5 integer (one point per criterion met)
winner_criteria : list of criteria that were met
winner_flags : list of criteria that FAILED (for transparency)
"""
criteria_met = []
criteria_fail = []
# Criterion 1 — Grade must be B or better
if grade in ('A+', 'A', 'B'):
criteria_met.append('grade_B_or_better')
else:
criteria_fail.append('grade_below_B')
# Criterion 2 — Short/medium consolidation window (10 or 20 days)
if consolidation_window in (10, 20):
criteria_met.append('window_10_or_20')
else:
criteria_fail.append(f'window_{consolidation_window}_not_preferred')
# Criterion 3 — Strong volume confirmation (>1.5x avg)
if volume_ratio is not None and volume_ratio >= 1.5:
criteria_met.append('volume_ratio_gte_1_5')
else:
criteria_fail.append('volume_ratio_weak')
# Criterion 4 — Tight base (<18% consolidation range)
if consolidation_range_pct is not None and consolidation_range_pct < 18.0:
criteria_met.append('tight_base_lt_18pct')
else:
criteria_fail.append('base_too_wide')
# Criterion 5 — Bullish Nifty regime (slope > 0, optional field)
if nifty_slope is not None:
if nifty_slope > 0:
criteria_met.append('nifty_bullish_slope')
else:
criteria_fail.append('nifty_bearish_slope')
# If slope is unknown we neither reward nor penalise
score = len(criteria_met)
if score >= 4:
label = 'POSSIBLE_WINNER_EXPERIMENTAL'
elif score >= 2:
label = 'STANDARD'
else:
label = 'WATCHLIST_ONLY'
return {
'winner_label': label,
'winner_score': score,
'winner_criteria': criteria_met,
'winner_flags': criteria_fail,
}
def get_market_regime(target_date=None):
"""
Automated Nifty-based regime detection with 3-day Time-based Confirmation.
Classification:
- BULL: Price > 20-EMA (with buffer) and 20-EMA > 50-EMA
- WEAK_BULL: Price > 50-EMA (with buffer) but below 20-EMA
- RANGE: Price within 0.2% of either EMA (Transition zone)
- CORRECTION: Price below 50-EMA (with buffer)
- UNKNOWN: Data fetch failed
Stabilization: A regime shift is only confirmed and applied if the new regime
persists for 3 consecutive trading days. This reduces historical whipsaws from 72% to 7.9%.
"""
try:
TOLERANCE = 0.002
CONFIRMATION_DAYS = 3
# Default to today if no date provided
if target_date is None:
target_date = datetime.today().date()
elif hasattr(target_date, 'date'):
target_date = target_date.date()
# Check cache (key is date string)
date_key = target_date.strftime('%Y-%m-%d')
if date_key in _nifty_regime_cache:
return _nifty_regime_cache[date_key]
# Fetch Nifty data (^NSEI for Nifty 50)
# Fetch 180 days to ensure a sufficiently long series to build confirmation history
start_dt = target_date - timedelta(days=180)
end_dt = target_date + timedelta(days=1)
try:
from utils import fetch_nifty_from_upstox
# Convert target_date to datetime to match fetch_nifty_from_upstox requirements
start_dt_dt = datetime.combine(start_dt, datetime.min.time())
end_dt_dt = datetime.combine(end_dt, datetime.min.time())
df_nifty = fetch_nifty_from_upstox(start_dt_dt, end_dt_dt)
except Exception as ex:
logger.warning(f"Could not fetch Nifty from Upstox in scanner: {ex}")
df_nifty = None
if df_nifty is None or df_nifty.empty:
logger.warning("Upstox fetching for Nifty in scanner failed or returned no data, falling back to yfinance...")
# Use yfinance with auto_adjust=False to avoid FutureWarnings
df_nifty = yf.download("^NSEI", start=start_dt, end=end_dt, progress=False, auto_adjust=False)
if df_nifty is None or df_nifty.empty:
return "UNKNOWN"
# 1. Reset index if MultiIndex columns or if index name contains 'date' or is type DatetimeIndex
if isinstance(df_nifty.columns, pd.MultiIndex):
df_nifty.columns = [c[0] for c in df_nifty.columns]
index_name = df_nifty.index.name
is_date_index = False
if index_name and 'date' in str(index_name).lower():
is_date_index = True
elif isinstance(df_nifty.index, pd.DatetimeIndex):
is_date_index = True
if is_date_index:
df_nifty = df_nifty.reset_index()
# 2. Identify the date column
# Preference:
# a. Exact case-insensitive match for 'date'
# b. A single column containing 'date'
# Otherwise raise ValueError
cols = list(df_nifty.columns)
date_col = None
exact_matches = [c for c in cols if str(c).lower() == 'date']
if len(exact_matches) == 1:
date_col = exact_matches[0]
elif len(exact_matches) > 1:
raise ValueError(f"Ambiguous date columns (multiple exact case-insensitive matches): {exact_matches}")
else:
contains_matches = [c for c in cols if 'date' in str(c).lower()]
if len(contains_matches) == 1:
date_col = contains_matches[0]
elif len(contains_matches) > 1:
raise ValueError(f"Ambiguous date columns (multiple columns containing 'date'): {contains_matches}")
if not date_col:
raise ValueError(f"Could not find any date column in Nifty DataFrame. Columns: {cols}")
# Rename identified date column to 'Date'
df_nifty = df_nifty.rename(columns={date_col: 'Date'})
# 3. Standardize other key columns: Open, High, Low, Close, Volume
key_mapping = {}
for col in df_nifty.columns:
col_lower = str(col).lower()
if col_lower == 'open':
key_mapping[col] = 'Open'
elif col_lower == 'high':
key_mapping[col] = 'High'
elif col_lower == 'low':
key_mapping[col] = 'Low'
elif col_lower == 'close':
key_mapping[col] = 'Close'
elif col_lower == 'volume':
key_mapping[col] = 'Volume'
df_nifty = df_nifty.rename(columns=key_mapping)
# Verify required columns are present
required = ['Date', 'Open', 'High', 'Low', 'Close']
missing = [col for col in required if col not in df_nifty.columns]
if missing:
raise ValueError(f"Missing required columns in Nifty DataFrame: {missing}. Available: {list(df_nifty.columns)}")
# Enforce pd.to_datetime on 'Date'
df_nifty['Date'] = pd.to_datetime(df_nifty['Date'])
# Sort ascending by Date and reset index
df_nifty = df_nifty.sort_values('Date').reset_index(drop=True)
if len(df_nifty) < 55:
return "UNKNOWN"
# Calculate EMAs
df_nifty['EMA20'] = df_nifty['Close'].ewm(span=20, adjust=False).mean()
df_nifty['EMA50'] = df_nifty['Close'].ewm(span=50, adjust=False).mean()
# Calculate raw regimes for all indices
raw_regimes = []
for i in range(len(df_nifty)):
price = float(df_nifty['Close'].iat[i])
ema20 = float(df_nifty['EMA20'].iat[i])
ema50 = float(df_nifty['EMA50'].iat[i])
# Calculate distance from EMAs
dist_20 = (price / ema20) - 1
dist_50 = (price / ema50) - 1
# Priority 1: Range/Neutral check
if abs(dist_20) < TOLERANCE or abs(dist_50) < TOLERANCE:
reg = "RANGE"
# Priority 2: Directional trends
elif price > ema20 and ema20 > ema50:
reg = "BULL"
elif price > ema50:
reg = "WEAK_BULL"
else:
reg = "CORRECTION"
raw_regimes.append(reg)
# Run confirmation filter chronologically
confirmed_regimes = []
current_confirmed = "UNKNOWN"
for i in range(len(df_nifty)):
if i < CONFIRMATION_DAYS - 1:
confirmed_regimes.append("UNKNOWN")
continue
# Check last 3 raw regimes
history = raw_regimes[i - CONFIRMATION_DAYS + 1: i + 1]
first = history[0]
if all(x == first for x in history):
current_confirmed = first
confirmed_regimes.append(current_confirmed)
# Store confirmed regimes in cache for all dates calculated
for i in range(len(df_nifty)):
d_key = df_nifty['Date'].iloc[i].strftime('%Y-%m-%d')
if confirmed_regimes[i] != "UNKNOWN":
_nifty_regime_cache[d_key] = confirmed_regimes[i]
# Return target date's confirmed regime
target_key = target_date.strftime('%Y-%m-%d')
return _nifty_regime_cache.get(target_key, confirmed_regimes[-1])
except Exception as e:
logger.warning(f"⚠️ Market regime detection failed: {e}")
return "UNKNOWN"
# Global rate limiters for APIs
_upstox_last_request = 0.0
_upstox_lock = threading.Lock()
_yfinance_last_request = 0.0
_yfinance_lock = threading.Lock()
_yfinance_min_delay = 0.2 # 200ms minimum delay between yfinance requests
def auto_refresh_upstox_token():
"""Automatically refresh Upstox token before the scan runs if refresh token is present."""
refresh_token = os.getenv('UPSTOX_REFRESH_TOKEN')
client_id = os.getenv('UPSTOX_API_KEY') or os.getenv('UPSTOX_CLIENT_ID')
client_secret = os.getenv('UPSTOX_API_SECRET') or os.getenv('UPSTOX_CLIENT_SECRET')
redirect_uri = os.getenv('UPSTOX_REDIRECT_URI', 'https://127.0.0.1')
if not refresh_token or not client_id or not client_secret:
return
url = 'https://api.upstox.com/v2/login/authorization/token'
headers = {
'accept': 'application/json',
'Api-Version': '2.0',
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'code': '',
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': 'refresh_token',
'refresh_token': refresh_token
}
try:
response = requests.post(url, headers=headers, data=data, timeout=10)
if response.status_code == 200:
token_data = response.json()
new_access_token = token_data.get('access_token')
if new_access_token:
# Update environment variable for the current process
os.environ['UPSTOX_ACCESS_TOKEN'] = new_access_token
logger.info("✅ Successfully refreshed Upstox access token")
else:
logger.error(f"❌ Failed to refresh Upstox token: {response.status_code} {response.text}")
except Exception as e:
logger.error(f"❌ Error refreshing Upstox token: {e}")
from fetch import fetch_recent_ipo_symbols
# Import only the functions we need, not the entire module
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Import functions without executing hybrid.py
def supertrend(df, p=10, m=3.0):
hl = (df['HIGH']+df['LOW'])/2
tr = pd.concat([df['HIGH']-df['LOW'],
abs(df['HIGH']-df['CLOSE'].shift()),
abs(df['LOW']-df['CLOSE'].shift())], axis=1).max(axis=1)
atr = tr.rolling(p).mean()
ub, lb = hl + m*atr, hl - m*atr
# Explicit dtype avoids pandas FutureWarning for empty Series default dtype
st = pd.Series(index=df.index, dtype="float64")
for i in range(1, len(df)):
if df['CLOSE'].iat[i] <= lb.iat[i]:
st.iat[i] = ub.iat[i]
elif df['CLOSE'].iat[i] >= ub.iat[i]:
st.iat[i] = lb.iat[i]
else:
st.iat[i] = st.iat[i-1]
return st
import pandas as pd
import numpy as np
def sanitize_metric(val):
"""Cast pandas/numpy variables to python natives for clean JSON logging"""
if pd.isna(val) or val is None:
return None
try:
if hasattr(val, 'item'):
return val.item()
if isinstance(val, (int, float, bool, str)):
return val
return float(val)
except:
return str(val)
def compute_grade_hybrid(df, idx, w, avg_vol):
score=0
low, high = df['LOW'].tail(w).min(), df['HIGH'].tail(w).max()
prng = (high-low)/low*100
if prng<=18: score+=1
vol_ratio = df['VOLUME'].iat[idx]/avg_vol if avg_vol>0 else 0
if df['VOLUME'].iat[idx]>=2.5*avg_vol and df['VOLUME'].iloc[idx-2:idx+1].sum()>=4*avg_vol: score+=1
ret20 = (df['CLOSE'].iat[idx]/df['CLOSE'].iat[max(0,idx-20)]-1)
percentile=np.percentile((df['CLOSE']-df['CLOSE'].shift(20))/df['CLOSE'].shift(20).fillna(0),85)
rs_percentile_met = bool(ret20>=percentile)
if rs_percentile_met: score+=1
ema20,ema50 = df['CLOSE'].ewm(20).mean().iat[idx], df['CLOSE'].ewm(50).mean().iat[idx]
macd = df['CLOSE'].ewm(12).mean().iat[idx] - df['CLOSE'].ewm(26).mean().iat[idx]
sig = pd.Series(df['CLOSE'].ewm(12).mean()-df['CLOSE'].ewm(26).mean()).ewm(9).mean().iat[idx]
rsi = 100-100/(1+(df['CLOSE'].diff().clip(lower=0).rolling(14).mean()/
df['CLOSE'].diff().clip(upper=0).abs().rolling(14).mean())).iat[idx]
trend_alignment = bool(macd>sig and rsi>65 and ema20>ema50)
if trend_alignment: score+=1
if idx+1<len(df) and (df['OPEN'].iat[idx+1]/df['CLOSE'].iat[idx]-1)>=0.04: score+=1
metrics_dict = {
"metric_prng": sanitize_metric(prng),
"metric_vol_ratio": sanitize_metric(vol_ratio),
"metric_rsi": sanitize_metric(rsi),
"metric_base_width": sanitize_metric(w),
"metric_rs_percentile_met": sanitize_metric(rs_percentile_met),
"metric_trend_alignment": sanitize_metric(trend_alignment)
}
return score, metrics_dict
def assign_grade(score):
if score>=4: return 'A+'
if score>=2: return 'B'
if score>=1: return 'C'
return 'D'
# Helper for live-grade filtering
GRADE_ORDER = ["D", "C", "B", "A", "A+"]
def is_live_grade_allowed(grade: str) -> bool:
"""Return True if grade meets MIN_LIVE_GRADE threshold for LIVE signals."""
try:
return GRADE_ORDER.index(grade) >= GRADE_ORDER.index(MIN_LIVE_GRADE)
except ValueError:
# Unknown grade: be conservative and reject
return False
# NSE official trading holidays for 2025 and 2026
# Source: NSE India holiday calendar
NSE_HOLIDAYS = {
# 2025 holidays
"2025-01-26", # Republic Day
"2025-02-26", # Mahashivratri
"2025-03-14", # Holi
"2025-04-10", # Id-Ul-Fitr (Ramadan Eid)
"2025-04-14", # Dr. Baba Saheb Ambedkar Jayanti
"2025-04-18", # Good Friday
"2025-05-01", # Maharashtra Day
"2025-08-15", # Independence Day
"2025-08-27", # Ganesh Chaturthi
"2025-10-02", # Mahatma Gandhi Jayanti
"2025-10-02", # Dussehra
"2025-10-24", # Diwali Laxmi Pujan
"2025-10-28", # Diwali Balipratipada
"2025-11-05", # Prakash Gurpurb Sri Guru Nanak Dev Ji
"2025-11-15", # ?
"2025-12-25", # Christmas
# 2026 holidays
"2026-01-26", # Republic Day
"2026-02-19", # Chhatrapati Shivaji Maharaj Jayanti
"2026-03-03", # Holi
"2026-03-19", # Gudi Padwa
"2026-03-26", # Shri Ram Navami
"2026-03-31", # Shri Mahavir Jayanti
"2026-04-03", # Good Friday
"2026-04-14", # Dr. Baba Saheb Ambedkar Jayanti
"2026-05-01", # Maharashtra Day
"2026-05-28", # Bakri Id
"2026-06-26", # Muharram
"2026-08-15", # Independence Day
"2026-08-26", # Id-E-Milad
"2026-09-14", # Ganesh Chaturthi
"2026-10-02", # Mahatma Gandhi Jayanti
"2026-10-20", # Dussehra
"2026-11-10", # Diwali Balipratipada
"2026-11-24", # Prakash Gurpurb Sri Guru Nanak Dev Ji
"2026-12-25", # Christmas
}
def is_market_day() -> bool:
"""Check if today is an NSE trading day (not a weekend, not a holiday).
Returns True if the market is open today, False otherwise."""
try:
from datetime import timezone, timedelta as td
ist = timezone(td(hours=5, minutes=30))
now_ist = datetime.now(ist)
today_str = now_ist.strftime("%Y-%m-%d")
# Check weekend (0=Monday, 6=Sunday)
if now_ist.weekday() >= 5:
return False
# Check NSE holiday list
if today_str in NSE_HOLIDAYS:
return False
return True
except Exception:
# If check fails, assume market is open (fail-open)
return True
def is_market_hours() -> bool:
"""Check if current IST time is within Indian market hours (9:15 AM - 3:30 PM IST)
AND today is an NSE trading day (not a weekend or holiday).
Returns True if within market hours on a trading day, False otherwise."""
try:
from datetime import timezone, timedelta as td
ist = timezone(td(hours=5, minutes=30))
now_ist = datetime.now(ist)
# Check if today is a trading day first
if not is_market_day():
return False
market_open = now_ist.replace(hour=9, minute=15, second=0, microsecond=0)
market_close = now_ist.replace(hour=15, minute=30, second=0, microsecond=0)
return market_open <= now_ist <= market_close
except Exception:
# If timezone calculation fails, assume market is open (fail-open)
return True
def calculate_target_price(entry_price, consolidation_low, consolidation_high, grade):
"""Calculate target price based on pattern and grade"""
# Calculate consolidation range
consolidation_range = consolidation_high - consolidation_low
# Base target multipliers by grade
target_multipliers = {
"A+": 1.5, # 50% above consolidation high
"A": 1.4, # 40% above consolidation high
"B": 1.3, # 30% above consolidation high
"C": 1.2, # 20% above consolidation high
"D": 1.15 # 15% above consolidation high
}
multiplier = target_multipliers.get(grade, 1.2)
# Target = consolidation high + (range * multiplier)
target = consolidation_high + (consolidation_range * multiplier)
# Ensure minimum 10% return
min_target = entry_price * 1.10
target = max(target, min_target)
return target
def calculate_grade_based_stop_loss(entry_price, consolidation_low, grade):
"""Calculate stop loss based on grade and IPO volatility"""
# Grade-based stop loss percentages (more appropriate for IPO volatility)
grade_stop_pcts = {
"A+": 0.05, # 5% - High confidence, tighter stop
"A": 0.07, # 7% - Good confidence
"B": 0.10, # 10% - Medium confidence, more room for volatility
"C": 0.12, # 12% - Lower confidence, more volatile
"D": 0.15, # 15% - High risk, very volatile
"LISTING_BREAKOUT": 0.10 # 10% - Explicit trailing stop for listing breakouts
}
stop_pct = grade_stop_pcts.get(grade, 0.10) # Default 10% for unknown grades
# Calculate stop below entry price
stop_below_entry = entry_price * (1 - stop_pct)
# Calculate stop below consolidation low (safer)
stop_below_consolidation = consolidation_low * (1 - stop_pct)
# Use the higher (safer) of the two
stop_loss = max(stop_below_entry, stop_below_consolidation)
# Ensure stop loss is not more than 20% below entry (maximum risk)
max_risk_stop = entry_price * 0.80
stop_loss = max(stop_loss, max_risk_stop)
return stop_loss, stop_pct
import logging
# Load environment
load_dotenv()
# Helper functions for environment variables with robust defaults
def get_env_int(key, default):
"""Get environment variable as integer with fallback"""
try:
return int(os.getenv(key, default) or default)
except (ValueError, TypeError):
print(f"Warning: Invalid {key} value, using default: {default}")
return default
def get_env_float(key, default):
"""Get environment variable as float with fallback"""
try:
return float(os.getenv(key, default) or default)
except (ValueError, TypeError):
print(f"Warning: Invalid {key} value, using default: {default}")
return default
def get_liquidity_metrics(symbol, df):
"""
Calculate turnover and detect circuit days from historical data.
Returns (avg_turnover_cr, circuit_days_15, market_cap_cr)
"""
global _yfinance_last_request
try:
# 1. Avg Turnover in Crores (Last 20 sessions)
df_copy = df.copy()
df_copy['turnover'] = df_copy['CLOSE'] * df_copy['VOLUME']
avg_turnover = df_copy['turnover'].tail(20).mean()
avg_turnover_cr = round(avg_turnover / 10000000, 2)
# 2. Circuit Days in last 15 sessions
# Heuristic: High == Low and Volume > 0
df_copy['is_circuit'] = (df_copy['HIGH'] == df_copy['LOW']) & (df_copy['VOLUME'] > 0)
circuit_days = int(df_copy['is_circuit'].tail(15).sum())
# 3. Market Cap from cache or yfinance
mcap_cr = _market_cap_cache.get(symbol, 0)
if mcap_cr != 0:
# -1 is a cached failure, return 0.0 for calculations while retaining cache bypass
return avg_turnover_cr, circuit_days, max(0.0, mcap_cr)
if YFINANCE_AVAILABLE:
with _yfinance_lock:
current_time = time.time()
time_since_last = current_time - _yfinance_last_request
if time_since_last < _yfinance_min_delay:
time.sleep(_yfinance_min_delay - time_since_last)
try:
ticker = yf.Ticker(f"{symbol}.NS")
mcap = ticker.info.get('marketCap')
if mcap:
mcap_cr = round(mcap / 10000000, 2)
else:
mcap_cr = -1.0
_market_cap_cache[symbol] = mcap_cr
# Save to MongoDB cache
try:
from db import update_cached_market_cap
update_cached_market_cap(symbol, mcap_cr)
except Exception as cache_err:
logger.debug(f"Could not update cached market cap for {symbol}: {cache_err}")
except Exception as e:
logger.debug(f"Could not fetch market cap for {symbol}: {e}")
# Cache the failure permanently as -1.0
mcap_cr = -1.0
_market_cap_cache[symbol] = mcap_cr
try:
from db import update_cached_market_cap
update_cached_market_cap(symbol, mcap_cr)
except:
pass
_yfinance_last_request = time.time()
return avg_turnover_cr, circuit_days, max(0.0, mcap_cr)
except Exception as e:
logger.warning(f"⚠️ Error calculating liquidity metrics for {symbol}: {e}")
return 0, 0, 0
def get_env_float(key, default):
"""Get environment variable as float with fallback"""
try:
return float(os.getenv(key, default) or default)
except (ValueError, TypeError):
print(f"Warning: Invalid {key} value, using default: {default}")
return default
def get_env_list(key, default, separator=","):
"""Get environment variable as list with fallback"""
try:
value = os.getenv(key, default)
return [int(x.strip()) for x in value.split(separator) if x.strip()]
except (ValueError, TypeError):
print(f"Warning: Invalid {key} value, using default: {default}")
return [int(x.strip()) for x in default.split(separator)]
# Environment variables with robust defaults
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
# Core configuration
# Global Scanner Constants
IPO_YEARS_BACK = get_env_int("IPO_YEARS_BACK", 3)
STOP_PCT = get_env_float("STOP_PCT", 0.07) # Default 7% for IPO volatility
# Dynamic partial take per grade
PT_A_PLUS = get_env_float("PT_A_PLUS", 0.15)
PT_B = get_env_float("PT_B", 0.12)
PT_C = get_env_float("PT_C", 0.10)
# Trading parameters
CONSOL_WINDOWS = get_env_list("CONSOL_WINDOWS", "10,20") # 2026-07-05: narrowed to 10/20d only — 40/80/120d showed negative expectancy in 64-trade analysis
MAX_PRNG = get_env_float("MAX_PRNG", 25.0)
VOL_MULT = get_env_float("VOL_MULT", 1.2)
ABS_VOL_MIN = get_env_int("ABS_VOL_MIN", 3000000)
LOOKAHEAD = get_env_int("LOOKAHEAD", 80)
MAX_DAYS = get_env_int("MAX_DAYS", 200)
# Institutional Universe Logic
LISTING_MAX_DAYS_SINCE_LISTING = get_env_int("LISTING_MAX_DAYS_SINCE_LISTING", 750)
MIN_AGE_DAYS = get_env_int("MIN_AGE_DAYS", 60)
# --- Phase 4: Institutional Liquidity Hardening (Phase 2.5) ---
MIN_DAILY_TURNOVER_CR = get_env_float("MIN_DAILY_TURNOVER_CR", 1.0)
MIN_DAILY_TURNOVER_SMALL_CAP_CR = get_env_float("MIN_DAILY_TURNOVER_SMALL_CAP_CR", 0.75)
SMALL_CAP_THRESHOLD_CR = get_env_float("SMALL_CAP_THRESHOLD_CR", 3000.0)
def get_turnover_floor(mcap_cr: float) -> float:
"""Resolve the appropriate daily turnover floor based on market cap."""
if mcap_cr > 0 and mcap_cr < SMALL_CAP_THRESHOLD_CR:
return MIN_DAILY_TURNOVER_SMALL_CAP_CR
return MIN_DAILY_TURNOVER_CR
MIN_MARKET_CAP_CR = get_env_float("MIN_MARKET_CAP_CR", 500.0)
CIRCUIT_DAY_THRESHOLD = get_env_int("CIRCUIT_DAY_THRESHOLD", 3)
MIN_ENTRY_PRICE_RS = get_env_float("MIN_ENTRY_PRICE_RS", 25.0)
# Risk / reward and trailing configuration (tunable via .env)
# - MAX_ENTRY_ABOVE_BREAKOUT_PCT: max % above breakout/high we'll accept as entry
# - MIN_RISK_REWARD: minimum acceptable reward:risk ratio
# - MIN_PNL_FOR_TRAIL: minimum open P&L % before we start trailing the stop
# - MIN_TRAIL_MOVE_PCT: minimum % of entry price by which stop must improve to send an update
# - MIN_DAYS_BETWEEN_SIGNALS: cooldown between new signals for same symbol
# - MIN_LIVE_GRADE: minimum grade allowed for LIVE signals (D < C < B < A < A+)
MAX_ENTRY_ABOVE_BREAKOUT_PCT = get_env_float("MAX_ENTRY_ABOVE_BREAKOUT_PCT", 8.0)
MIN_RISK_REWARD = get_env_float("MIN_RISK_REWARD", 1.3)
MIN_PNL_FOR_TRAIL = get_env_float("MIN_PNL_FOR_TRAIL", 5.0)
MIN_TRAIL_MOVE_PCT = get_env_float("MIN_TRAIL_MOVE_PCT", 1.0)
MIN_DAYS_BETWEEN_SIGNALS = get_env_int("MIN_DAYS_BETWEEN_SIGNALS", 10)
MIN_LIVE_GRADE = os.getenv("MIN_LIVE_GRADE", "B") # 2026-07-05: raised from C → B; Grade C avg -2.64%, median -5.55% across 64-trade history
# --- Capital Allocation, Velocity Gates, and Sizing Configurations (Phase 2.6) ---
MAX_ACTIVE_POSITIONS = get_env_int("MAX_ACTIVE_POSITIONS", 5)
HARD_ACTIVE_POSITIONS = get_env_int("HARD_ACTIVE_POSITIONS", MAX_ACTIVE_POSITIONS + 2)
# Dead-money speed gate thresholds by archetype
DEAD_MONEY_DAYS_IPO = get_env_int("DEAD_MONEY_DAYS_IPO", 20)
DEAD_MONEY_RUNUP_IPO = get_env_float("DEAD_MONEY_RUNUP_IPO", 4.0)
DEAD_MONEY_DAYS_CONSOL = get_env_int("DEAD_MONEY_DAYS_CONSOL", 21)
DEAD_MONEY_RUNUP_CONSOL = get_env_float("DEAD_MONEY_RUNUP_CONSOL", 5.0)
DEAD_MONEY_DAYS_OTHER = get_env_int("DEAD_MONEY_DAYS_OTHER", 30)
DEAD_MONEY_RUNUP_OTHER = get_env_float("DEAD_MONEY_RUNUP_OTHER", 5.0)
# Soft regime sizing weights
REGIME_SIZE_MULT = {
"BULL": get_env_float("REGIME_SIZE_MULT_BULL", 1.0),
"WEAK_BULL": get_env_float("REGIME_SIZE_MULT_WEAK_BULL", 0.75),
"CORRECTION": get_env_float("REGIME_SIZE_MULT_CORRECTION", 0.5),
"RANGE": get_env_float("REGIME_SIZE_MULT_RANGE", 0.5),
"UNKNOWN": get_env_float("REGIME_SIZE_MULT_UNKNOWN", 0.5)
}
# --- Meta-Observability: Config Drift Detection ──────────────────────────────
def get_last_trading_day(target_date=None):
"""Calculate the most recent date that was NOT a weekend or NSE holiday."""
if target_date is None:
target_date = datetime.today().date()
check_date = target_date - timedelta(days=1)
while True:
# Check if weekend
if check_date.weekday() >= 5: # 5=Sat, 6=Sun
check_date -= timedelta(days=1)
continue
# Check if holiday
if check_date.strftime("%Y-%m-%d") in NSE_HOLIDAYS:
check_date -= timedelta(days=1)
continue
return check_date
def get_last_expected_data_date():
"""
Returns the date of the most recent trading session that should have EOD data.
- If today is a trading day and it's after 6:30 PM IST, today is the last expected date.
- Otherwise, it's the previous trading day.
"""
from datetime import timezone, timedelta as td
ist = timezone(td(hours=5, minutes=30))
now_ist = datetime.now(ist)
today = now_ist.date()
# After 6:30 PM IST, today's EOD data should be available on most providers
if is_market_day() and (now_ist.hour > 18 or (now_ist.hour == 18 and now_ist.minute >= 30)):
return today
# Otherwise, return the previous trading day
return get_last_trading_day(today)
def check_config_drift():
"""Warn if .env overrides are significantly diverging from institutional baselines."""
recommendations = {
"IPO_YEARS_BACK": (3, "Too short lookback blinds scanner to mature Stage-2 bases."),
"LISTING_MAX_DAYS_SINCE_LISTING": (750, "Tight age filters kill institutional accumulation detection."),
"MIN_AGE_DAYS": (60, "Scanning ultra-fresh IPOs (<60d) risks being trapped in post-listing distribution.")
}
# We check globals for the values established by get_env_int/float
for key, (recommended, reason) in recommendations.items():
val = globals().get(key)
if val is not None and val < recommended:
logger.warning(f"⚠️ [CONFIG DRIFT] {key} is set to {val}. Recommended is >= {recommended}.")
logger.warning(f" Reason: {reason}")
# Logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
logger = logging.getLogger(__name__)
# Initialize Config Audit
check_config_drift()
# ─────────────────────────────────────────────────────────────────────────────
# --- Cohort Definitions for Comparative Research ---
# These define the logical "buckets" for expectancy analysis.
RESEARCH_COHORTS = {
"PERMISSIVE": {
"max_prng": 60.0,
"min_window": 10,
"min_grade": "C",
"vol_follow": 0.8
},
"STRICT": {
"max_prng": 35.0,
"min_window": 20,
"min_grade": "C",
"vol_follow": 1.0
},
"ULTRA_STRICT": {
"max_prng": 25.0,
"min_window": 30,
"min_grade": "B",
"vol_follow": 1.0
}
}
# File paths
CACHE_FILE = os.getenv("CACHE_FILE", "ipo_cache.pkl")
# Metadata & State (Legacy CSVs removed, using MongoDB)
# System parameters
HEARTBEAT_RUNS = get_env_int("HEARTBEAT_RUNS", 0)
# Log yfinance availability after logger is initialized
if not YFINANCE_AVAILABLE:
logger.warning("yfinance not available. Install with: pip install yfinance")
import json
def write_daily_log(scanner_name, symbol, action, details=None, candle_timestamp=None, log_type="ACCEPTED"):
"""Write scanner telemetry to MongoDB only (single-write path)."""
try:
from datetime import timezone, timedelta as td
ist = timezone(td(hours=5, minutes=30))
now_ist = datetime.now(ist)
# DB-only write: use provided candle_timestamp if available, else fall back to now_ist
try:
from db import insert_log, db_metrics
effective_candle_ts = candle_timestamp if candle_timestamp is not None else now_ist
insert_log(
scanner=scanner_name, symbol=symbol, action=action,
candle_timestamp=effective_candle_ts,