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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
)
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
print(f" PASS: basic levels = SL {result['sl_pct']}%, TP1 {result['tp1_pct']}%")
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def test_dynamic_levels_bull_low_vol():
|
| 28 |
-
"""Bullish low-vol regime should have tighter stop, wider target."""
|
| 29 |
-
sideways = compute_dynamic_levels(1000, 10, "SIDEWAYS")
|
| 30 |
-
bull = compute_dynamic_levels(1000, 10, "BULL_LOW_VOL")
|
| 31 |
-
assert bull["sl_price"] > sideways["sl_price"], "Bull SL should be tighter (higher)"
|
| 32 |
-
assert bull["tp1_pct"] >= sideways["tp1_pct"], "Bull TP should be >= Sideways TP"
|
| 33 |
-
assert bull["include_tp2"] is True, "BULL_LOW_VOL should include TP2"
|
| 34 |
-
print(f" PASS: BULL_LOW_VOL SL={bull['sl_pct']}%, TP1={bull['tp1_pct']}%")
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def test_dynamic_levels_bear_high_vol():
|
| 38 |
-
"""Bear regime should have wider stop, tighter target."""
|
| 39 |
-
bear = compute_dynamic_levels(1000, 10, "BEAR_HIGH_VOL")
|
| 40 |
-
sideways = compute_dynamic_levels(1000, 10, "SIDEWAYS")
|
| 41 |
-
assert bear["sl_price"] < sideways["sl_price"], "Bear SL should be wider (lower)"
|
| 42 |
-
assert bear["include_tp2"] is False, "BEAR should not include TP2"
|
| 43 |
-
print(f" PASS: BEAR_HIGH_VOL SL={bear['sl_pct']}%, TP1={bear['tp1_pct']}%")
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def test_dynamic_levels_ipo():
|
| 47 |
-
"""IPO stocks should get boosted targets and tighter stop."""
|
| 48 |
-
normal = compute_dynamic_levels(1000, 10, "BULL_LOW_VOL", is_ipo=False)
|
| 49 |
-
ipo = compute_dynamic_levels(1000, 10, "BULL_LOW_VOL", is_ipo=True)
|
| 50 |
-
assert ipo["tp1_pct"] >= normal["tp1_pct"], "IPO TP should be >= normal"
|
| 51 |
-
assert ipo["include_tp2"] is True, "IPO should include TP2"
|
| 52 |
-
print(f" PASS: IPO TP1={ipo['tp1_pct']}% vs normal TP1={normal['tp1_pct']}%")
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def test_regime_bullish_low_vol():
|
| 56 |
-
"""VIX < 18 + Nifty bullish + bullish stock signals."""
|
| 57 |
-
regime = detect_market_regime(
|
| 58 |
-
indicators={"RSI": 35, "price": 100, "Supertrend_Dir": 1, "MACD": 1, "MACD_Signal": 0},
|
| 59 |
-
vix={"vix_level": 14.0},
|
| 60 |
-
nifty={"trend": "bullish"},
|
| 61 |
)
|
| 62 |
-
assert regime["regime"] == "BULL_LOW_VOL", f"Expected BULL_LOW_VOL, got {regime['regime']}"
|
| 63 |
-
print(f" PASS: regime={regime['regime']}, entry_threshold={regime['entry_threshold']}")
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 85 |
-
assert regime["regime"] == "SIDEWAYS", f"Expected SIDEWAYS, got {regime['regime']}"
|
| 86 |
-
print(f" PASS: regime={regime['regime']}")
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def test_regime_no_data():
|
| 90 |
-
"""No indicators, VIX, or Nifty data — should default to SIDEWAYS."""
|
| 91 |
-
regime = detect_market_regime()
|
| 92 |
-
assert regime["regime"] == "SIDEWAYS", f"Expected SIDEWAYS, got {regime['regime']}"
|
| 93 |
-
print(f" PASS: no-data regime={regime['regime']}")
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def test_risk_position_size():
|
| 97 |
-
"""Position size should cap loss at ~1% of capital."""
|
| 98 |
-
balance = 1_000_000.0
|
| 99 |
-
entry = 1000.0
|
| 100 |
-
sl = 985.0 # 15 rupees risk per share
|
| 101 |
-
shares = risk_check_position_size(balance, entry, sl)
|
| 102 |
-
max_loss = shares * (entry - sl)
|
| 103 |
-
assert max_loss <= balance * 0.015 + 1, f"Max loss {max_loss} exceeds 1.5% of capital"
|
| 104 |
-
assert shares > 0, "Should buy at least 1 share"
|
| 105 |
-
print(f" PASS: shares={shares}, max_loss={max_loss:.0f} ({max_loss/balance*100:.2f}% of capital)")
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
if __name__ == "__main__":
|
| 109 |
-
tests = [
|
| 110 |
-
("Dynamic levels — basic", test_dynamic_levels_basic),
|
| 111 |
-
("Dynamic levels — BULL_LOW_VOL", test_dynamic_levels_bull_low_vol),
|
| 112 |
-
("Dynamic levels — BEAR_HIGH_VOL", test_dynamic_levels_bear_high_vol),
|
| 113 |
-
("Dynamic levels — IPO", test_dynamic_levels_ipo),
|
| 114 |
-
("Regime — BULL_LOW_VOL", test_regime_bullish_low_vol),
|
| 115 |
-
("Regime — BEAR_HIGH_VOL", test_regime_bear_high_vol),
|
| 116 |
-
("Regime — SIDEWAYS", test_regime_sideways),
|
| 117 |
-
("Regime — no data", test_regime_no_data),
|
| 118 |
-
("Risk position sizing", test_risk_position_size),
|
| 119 |
-
]
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
passed += 1
|
| 128 |
-
except Exception as e:
|
| 129 |
-
print(f" FAIL: {e}")
|
| 130 |
-
failed += 1
|
| 131 |
-
|
| 132 |
-
print(f"\n{'='*50}")
|
| 133 |
-
print(f"Results: {passed} passed, {failed} failed out of {len(tests)} tests")
|
| 134 |
-
if failed == 0:
|
| 135 |
-
print("All tests passed!")
|
| 136 |
else:
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
Intraday XGBoost model for short-term price movement forecasting.
|
| 3 |
+
Predicts next 3-5 bar (minute) returns using tabular features.
|
| 4 |
+
Used exclusively by the Auto Trade tab.
|
| 5 |
+
|
| 6 |
+
Includes:
|
| 7 |
+
- In-memory model cache (10-min TTL) to avoid retraining every tick
|
| 8 |
+
- Sector-strength feature
|
| 9 |
+
- generate_intraday_signal() - full pipeline producing structured signals
|
| 10 |
"""
|
| 11 |
|
| 12 |
+
import time
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
from xgboost import XGBRegressor
|
| 16 |
+
from sklearn.model_selection import TimeSeriesSplit
|
| 17 |
+
from sklearn.metrics import mean_squared_error
|
| 18 |
+
from stock_data import (
|
| 19 |
+
fetch_intraday_data,
|
| 20 |
+
add_intraday_indicators,
|
| 21 |
+
fetch_india_vix,
|
| 22 |
+
fetch_nifty_trend,
|
| 23 |
+
detect_ipo_stock,
|
| 24 |
+
)
|
| 25 |
+
from trader import (
|
| 26 |
+
compute_dynamic_levels,
|
| 27 |
+
detect_market_regime,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Features the model uses (must match columns from add_intraday_indicators)
|
| 32 |
+
FEATURE_COLS = [
|
| 33 |
+
# Price & returns
|
| 34 |
+
"returns_1bar", "returns_5bar", "returns_15bar",
|
| 35 |
+
# Moving average distances
|
| 36 |
+
"price_vs_ema9", "price_vs_ema21", "price_vs_sma50",
|
| 37 |
+
# Momentum
|
| 38 |
+
"RSI", "MACD", "MACD_Signal", "MACD_Hist",
|
| 39 |
+
# Volatility
|
| 40 |
+
"ATR", "BB_Width", "BB_Position",
|
| 41 |
+
# Volume
|
| 42 |
+
"volume_ratio", "price_vs_vwap",
|
| 43 |
+
# Trend
|
| 44 |
+
"Supertrend_Dir", "supertrend_dist",
|
| 45 |
+
# Time
|
| 46 |
+
"minute_of_day", "is_first_hour", "is_last_hour",
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
# Market context features (appended at prediction time)
|
| 50 |
+
MARKET_FEATURES = ["vix_level", "vix_change_5d", "nifty_trend_dir", "sector_strength"]
|
| 51 |
+
|
| 52 |
+
FORWARD_BARS = 5 # Predict return over next 5 minutes
|
| 53 |
+
MODEL_CACHE_TTL = 600 # 10 minutes in seconds
|
| 54 |
+
|
| 55 |
+
# --- In-memory model cache ---
|
| 56 |
+
_model_cache: dict = {} # ticker -> {model, feature_names, metrics, timestamp}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _cache_valid(ticker: str) -> bool:
|
| 60 |
+
"""Check if cached model for ticker is still within TTL."""
|
| 61 |
+
if ticker not in _model_cache:
|
| 62 |
+
return False
|
| 63 |
+
return (time.time() - _model_cache[ticker]["timestamp"]) < MODEL_CACHE_TTL
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# --- Sector strength helper ---
|
| 67 |
+
SECTOR_INDEX_MAP = {
|
| 68 |
+
"Financial Services": "^NSEBANK",
|
| 69 |
+
"Information Technology": "^CNXIT",
|
| 70 |
+
"Pharmaceuticals": "^CNXPHARMA",
|
| 71 |
+
"Energy": "^CNXENERGY",
|
| 72 |
+
"Automobile": "^CNXAUTO",
|
| 73 |
+
"FMCG": "^CNXFMCG",
|
| 74 |
+
"Metals & Mining": "^CNXMETAL",
|
| 75 |
+
"Realty": "^CNXREALTY",
|
| 76 |
+
"Media": "^CNXMEDIA",
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _fetch_sector_strength(ticker: str) -> float:
|
| 81 |
+
"""
|
| 82 |
+
Compute sector relative strength vs Nifty 50 over last 5 days.
|
| 83 |
+
Returns a float: >0 means sector outperforming, <0 underperforming.
|
| 84 |
+
"""
|
| 85 |
+
import yfinance as yf
|
| 86 |
+
try:
|
| 87 |
+
stock_info = yf.Ticker(ticker).info
|
| 88 |
+
sector = stock_info.get("sector", "")
|
| 89 |
+
idx_symbol = SECTOR_INDEX_MAP.get(sector)
|
| 90 |
+
if not idx_symbol:
|
| 91 |
+
return 0.0
|
| 92 |
+
|
| 93 |
+
idx = yf.Ticker(idx_symbol)
|
| 94 |
+
hist = idx.history(period="5d")
|
| 95 |
+
if len(hist) < 2:
|
| 96 |
+
return 0.0
|
| 97 |
+
|
| 98 |
+
sector_ret = (float(hist["Close"].iloc[-1]) / float(hist["Close"].iloc[0]) - 1) * 100
|
| 99 |
+
|
| 100 |
+
nifty = yf.Ticker("^NSEI")
|
| 101 |
+
nh = nifty.history(period="5d")
|
| 102 |
+
if len(nh) < 2:
|
| 103 |
+
return 0.0
|
| 104 |
+
nifty_ret = (float(nh["Close"].iloc[-1]) / float(nh["Close"].iloc[0]) - 1) * 100
|
| 105 |
+
|
| 106 |
+
return round(sector_ret - nifty_ret, 4)
|
| 107 |
+
except Exception:
|
| 108 |
+
return 0.0
|
| 109 |
+
|
| 110 |
|
| 111 |
+
# --- Core model functions ---
|
| 112 |
|
| 113 |
+
def _build_target(df: pd.DataFrame, forward_bars: int = FORWARD_BARS) -> pd.Series:
|
| 114 |
+
"""Target = percentage return over the next N bars."""
|
| 115 |
+
future_close = df["Close"].shift(-forward_bars)
|
| 116 |
+
target = ((future_close - df["Close"]) / df["Close"]) * 100
|
| 117 |
+
return target
|
| 118 |
|
| 119 |
+
|
| 120 |
+
def _add_market_context(df: pd.DataFrame, vix: dict, nifty: dict,
|
| 121 |
+
sector_strength: float = 0.0) -> pd.DataFrame:
|
| 122 |
+
"""Append market-level context features to every row."""
|
| 123 |
+
df["vix_level"] = vix.get("vix_level", 15.0)
|
| 124 |
+
df["vix_change_5d"] = vix.get("vix_change_5d", 0.0)
|
| 125 |
+
trend_map = {"bullish": 1, "flat": 0, "bearish": -1}
|
| 126 |
+
df["nifty_trend_dir"] = trend_map.get(nifty.get("trend", "flat"), 0)
|
| 127 |
+
df["sector_strength"] = sector_strength
|
| 128 |
+
return df
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _prepare_features(df: pd.DataFrame) -> tuple:
|
| 132 |
+
"""Select feature columns and return X matrix + available column names."""
|
| 133 |
+
all_cols = FEATURE_COLS + MARKET_FEATURES
|
| 134 |
+
available = [c for c in all_cols if c in df.columns]
|
| 135 |
+
X = df[available].values.astype(np.float32)
|
| 136 |
+
return X, available
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def train_intraday_model(df: pd.DataFrame, vix: dict, nifty: dict,
|
| 140 |
+
sector_strength: float = 0.0) -> dict:
|
| 141 |
+
"""
|
| 142 |
+
Train an XGBoost regressor on intraday data.
|
| 143 |
+
Returns dict with model, scaler info, feature names, and metrics.
|
| 144 |
+
"""
|
| 145 |
+
df = _add_market_context(df, vix, nifty, sector_strength)
|
| 146 |
+
|
| 147 |
+
# Build target
|
| 148 |
+
df["target"] = _build_target(df, FORWARD_BARS)
|
| 149 |
+
|
| 150 |
+
# Drop rows where target is NaN (last FORWARD_BARS rows)
|
| 151 |
+
df_clean = df.dropna(subset=["target"]).copy()
|
| 152 |
+
|
| 153 |
+
if len(df_clean) < 100:
|
| 154 |
+
raise ValueError(f"Insufficient data for training: {len(df_clean)} rows (need >=100)")
|
| 155 |
+
|
| 156 |
+
X, feature_names = _prepare_features(df_clean)
|
| 157 |
+
y = df_clean["target"].values.astype(np.float32)
|
| 158 |
+
|
| 159 |
+
# Replace any remaining NaN/inf in features
|
| 160 |
+
X = np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0)
|
| 161 |
+
|
| 162 |
+
# Time-series split: train on first 80%, test on last 20%
|
| 163 |
+
split_idx = int(len(X) * 0.8)
|
| 164 |
+
X_train, X_test = X[:split_idx], X[split_idx:]
|
| 165 |
+
y_train, y_test = y[:split_idx], y[split_idx:]
|
| 166 |
+
|
| 167 |
+
model = XGBRegressor(
|
| 168 |
+
n_estimators=200,
|
| 169 |
+
max_depth=5,
|
| 170 |
+
learning_rate=0.05,
|
| 171 |
+
subsample=0.8,
|
| 172 |
+
colsample_bytree=0.8,
|
| 173 |
+
min_child_weight=5,
|
| 174 |
+
reg_alpha=0.1,
|
| 175 |
+
reg_lambda=1.0,
|
| 176 |
+
random_state=42,
|
| 177 |
+
verbosity=0,
|
| 178 |
)
|
| 179 |
+
|
| 180 |
+
model.fit(
|
| 181 |
+
X_train, y_train,
|
| 182 |
+
eval_set=[(X_test, y_test)],
|
| 183 |
+
verbose=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
)
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
# Evaluate
|
| 187 |
+
y_pred = model.predict(X_test)
|
| 188 |
+
mse = mean_squared_error(y_test, y_pred)
|
| 189 |
+
rmse = float(np.sqrt(mse))
|
| 190 |
+
|
| 191 |
+
# Directional accuracy (did we predict the right direction?)
|
| 192 |
+
dir_correct = np.sum(np.sign(y_pred) == np.sign(y_test))
|
| 193 |
+
dir_accuracy = float(dir_correct / len(y_test)) * 100 if len(y_test) > 0 else 0
|
| 194 |
+
|
| 195 |
+
return {
|
| 196 |
+
"model": model,
|
| 197 |
+
"feature_names": feature_names,
|
| 198 |
+
"rmse": round(rmse, 4),
|
| 199 |
+
"dir_accuracy": round(dir_accuracy, 1),
|
| 200 |
+
"train_samples": len(X_train),
|
| 201 |
+
"test_samples": len(X_test),
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def compute_confidence(expected_return: float, rmse: float,
|
| 206 |
+
dir_accuracy: float, regime_str: str) -> float:
|
| 207 |
+
"""
|
| 208 |
+
Compute a confidence score (0-100) for the prediction.
|
| 209 |
+
Factors: magnitude of expected return vs model RMSE,
|
| 210 |
+
directional accuracy, and current market regime.
|
| 211 |
+
"""
|
| 212 |
+
# Signal-to-noise ratio: how big is the predicted move vs model error
|
| 213 |
+
snr = abs(expected_return) / rmse if rmse > 0 else 0
|
| 214 |
+
snr_score = min(40, snr * 20) # 0-40 points
|
| 215 |
|
| 216 |
+
# Directional accuracy contribution
|
| 217 |
+
dir_score = min(35, max(0, (dir_accuracy - 45) * 0.7)) # 0-35 points
|
| 218 |
+
|
| 219 |
+
# Regime bonus/penalty
|
| 220 |
+
regime_bonus = {
|
| 221 |
+
"BULL_LOW_VOL": 15,
|
| 222 |
+
"BULL_HIGH_VOL": 10,
|
| 223 |
+
"SIDEWAYS": 0,
|
| 224 |
+
"BEAR_HIGH_VOL": -5,
|
| 225 |
+
}.get(regime_str, 5)
|
| 226 |
+
|
| 227 |
+
# Return-direction bonus: predicted returns in the direction we'd trade
|
| 228 |
+
dir_bonus = 10 if expected_return > 0.3 else (5 if expected_return > 0 else 0)
|
| 229 |
+
|
| 230 |
+
confidence = snr_score + dir_score + regime_bonus + dir_bonus
|
| 231 |
+
return round(max(0, min(100, confidence)), 1)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def intraday_predict(ticker: str) -> dict:
|
| 235 |
+
"""
|
| 236 |
+
Full pipeline: fetch data -> add indicators -> add market context ->
|
| 237 |
+
train XGBoost -> predict next bars -> return raw prediction data.
|
| 238 |
+
Uses cache when available.
|
| 239 |
+
"""
|
| 240 |
+
# 1. Fetch intraday data
|
| 241 |
+
df = fetch_intraday_data(ticker, period="5d", interval="1m")
|
| 242 |
+
df = add_intraday_indicators(df)
|
| 243 |
+
|
| 244 |
+
if len(df) < 120:
|
| 245 |
+
return {
|
| 246 |
+
"ticker": ticker,
|
| 247 |
+
"status": "insufficient_data",
|
| 248 |
+
"message": f"Only {len(df)} bars available (need >=120)",
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
# 2. Fetch market context
|
| 252 |
+
vix = fetch_india_vix()
|
| 253 |
+
nifty = fetch_nifty_trend()
|
| 254 |
+
sector_str = _fetch_sector_strength(ticker)
|
| 255 |
+
|
| 256 |
+
# 3. Train model or use cache
|
| 257 |
+
if _cache_valid(ticker):
|
| 258 |
+
cached = _model_cache[ticker]
|
| 259 |
+
model = cached["model"]
|
| 260 |
+
feature_names = cached["feature_names"]
|
| 261 |
+
result_metrics = {
|
| 262 |
+
"rmse": cached["rmse"],
|
| 263 |
+
"dir_accuracy": cached["dir_accuracy"],
|
| 264 |
+
"train_samples": cached["train_samples"],
|
| 265 |
+
"test_samples": cached["test_samples"],
|
| 266 |
+
}
|
| 267 |
+
else:
|
| 268 |
+
try:
|
| 269 |
+
result = train_intraday_model(df.copy(), vix, nifty, sector_str)
|
| 270 |
+
except ValueError as e:
|
| 271 |
+
return {"ticker": ticker, "status": "train_error", "message": str(e)}
|
| 272 |
+
|
| 273 |
+
model = result["model"]
|
| 274 |
+
feature_names = result["feature_names"]
|
| 275 |
+
result_metrics = {
|
| 276 |
+
"rmse": result["rmse"],
|
| 277 |
+
"dir_accuracy": result["dir_accuracy"],
|
| 278 |
+
"train_samples": result["train_samples"],
|
| 279 |
+
"test_samples": result["test_samples"],
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
# Cache the trained model
|
| 283 |
+
_model_cache[ticker] = {
|
| 284 |
+
"model": model,
|
| 285 |
+
"feature_names": feature_names,
|
| 286 |
+
"timestamp": time.time(),
|
| 287 |
+
**result_metrics,
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
# 4. Predict on latest bar
|
| 291 |
+
df_latest = _add_market_context(df, vix, nifty, sector_str)
|
| 292 |
+
X_latest, _ = _prepare_features(df_latest)
|
| 293 |
+
X_latest = np.nan_to_num(X_latest, nan=0.0, posinf=0.0, neginf=0.0)
|
| 294 |
+
|
| 295 |
+
# Predict for the last bar
|
| 296 |
+
last_features = X_latest[-1:].reshape(1, -1)
|
| 297 |
+
expected_return = float(model.predict(last_features)[0])
|
| 298 |
+
|
| 299 |
+
# 5. Get current indicators for the signal
|
| 300 |
+
last_row = df.iloc[-1]
|
| 301 |
+
current_price = float(last_row["Close"])
|
| 302 |
+
current_atr = float(last_row["ATR"])
|
| 303 |
+
current_rsi = float(last_row["RSI"])
|
| 304 |
+
current_supertrend_dir = int(last_row["Supertrend_Dir"])
|
| 305 |
+
current_vwap = float(last_row["VWAP"])
|
| 306 |
+
current_volume_ratio = float(last_row["volume_ratio"])
|
| 307 |
+
|
| 308 |
+
# 6. Feature importances (top 5)
|
| 309 |
+
importances = model.feature_importances_
|
| 310 |
+
top_indices = np.argsort(importances)[-5:][::-1]
|
| 311 |
+
top_features = [
|
| 312 |
+
{"name": feature_names[i], "importance": round(float(importances[i]), 3)}
|
| 313 |
+
for i in top_indices if i < len(feature_names)
|
| 314 |
+
]
|
| 315 |
+
|
| 316 |
+
return {
|
| 317 |
+
"ticker": ticker,
|
| 318 |
+
"status": "ok",
|
| 319 |
+
"expected_return_pct": round(expected_return, 4),
|
| 320 |
+
"forward_bars": FORWARD_BARS,
|
| 321 |
+
"current_price": round(current_price, 2),
|
| 322 |
+
"current_atr": round(current_atr, 4),
|
| 323 |
+
"current_rsi": round(current_rsi, 2),
|
| 324 |
+
"supertrend_dir": current_supertrend_dir,
|
| 325 |
+
"vwap": round(current_vwap, 2),
|
| 326 |
+
"volume_ratio": round(current_volume_ratio, 2),
|
| 327 |
+
"model_rmse": result_metrics["rmse"],
|
| 328 |
+
"model_dir_accuracy": result_metrics["dir_accuracy"],
|
| 329 |
+
"train_samples": result_metrics["train_samples"],
|
| 330 |
+
"vix": vix,
|
| 331 |
+
"nifty_trend": nifty,
|
| 332 |
+
"sector_strength": sector_str,
|
| 333 |
+
"top_features": top_features,
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# --- Full signal generator ---
|
| 338 |
+
|
| 339 |
+
def generate_intraday_signal(ticker: str) -> dict:
|
| 340 |
+
"""
|
| 341 |
+
Full pipeline: predict -> detect regime -> compute dynamic SL/TP ->
|
| 342 |
+
apply entry threshold -> return structured trading signal.
|
| 343 |
+
|
| 344 |
+
Output example:
|
| 345 |
+
{
|
| 346 |
+
"action": "BUY",
|
| 347 |
+
"ticker": "RELIANCE.NS",
|
| 348 |
+
"entry_price": 2987.40,
|
| 349 |
+
"sl_price": 2952.20, "sl_pct": -1.18,
|
| 350 |
+
"tp1_price": 3024.60, "tp1_pct": 1.24,
|
| 351 |
+
"tp2_price": 3057.80, "tp2_pct": 2.35,
|
| 352 |
+
"confidence": 67.3,
|
| 353 |
+
"expected_return_pct": 1.12,
|
| 354 |
+
"regime": "BULL_LOW_VOL",
|
| 355 |
+
...
|
| 356 |
+
}
|
| 357 |
+
"""
|
| 358 |
+
# 1. Get raw prediction
|
| 359 |
+
pred = intraday_predict(ticker)
|
| 360 |
+
|
| 361 |
+
if pred.get("status") != "ok":
|
| 362 |
+
return {
|
| 363 |
+
"action": "SKIP",
|
| 364 |
+
"ticker": ticker,
|
| 365 |
+
"reason": pred.get("message", "Prediction failed"),
|
| 366 |
+
"status": pred.get("status", "error"),
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
expected_return = pred["expected_return_pct"]
|
| 370 |
+
current_price = pred["current_price"]
|
| 371 |
+
current_atr = pred["current_atr"]
|
| 372 |
+
|
| 373 |
+
# 2. Build stock-level indicators for regime detection
|
| 374 |
+
stock_indicators = {
|
| 375 |
+
"RSI": pred["current_rsi"],
|
| 376 |
+
"price": current_price,
|
| 377 |
+
"Supertrend_Dir": pred["supertrend_dir"],
|
| 378 |
+
"MACD": 0,
|
| 379 |
+
"MACD_Signal": 0,
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
# 3. Detect regime (uses VIX + Nifty + stock signals)
|
| 383 |
+
regime_info = detect_market_regime(
|
| 384 |
+
indicators=stock_indicators,
|
| 385 |
+
vix=pred["vix"],
|
| 386 |
+
nifty=pred["nifty_trend"],
|
| 387 |
)
|
| 388 |
+
regime = regime_info["regime"]
|
| 389 |
+
entry_threshold = regime_info["entry_threshold"]
|
| 390 |
+
min_confidence = regime_info["min_confidence"]
|
| 391 |
+
|
| 392 |
+
# 4. Check IPO status
|
| 393 |
+
ipo_info = detect_ipo_stock(ticker)
|
| 394 |
+
is_ipo = ipo_info.get("is_ipo", False)
|
| 395 |
|
| 396 |
+
# 5. Compute dynamic SL/TP
|
| 397 |
+
levels = compute_dynamic_levels(current_price, current_atr, regime, is_ipo)
|
| 398 |
|
| 399 |
+
# 6. Compute confidence
|
| 400 |
+
confidence = compute_confidence(
|
| 401 |
+
expected_return,
|
| 402 |
+
pred["model_rmse"],
|
| 403 |
+
pred["model_dir_accuracy"],
|
| 404 |
+
regime,
|
| 405 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
+
# 7. Apply entry threshold
|
| 408 |
+
if expected_return >= entry_threshold and confidence >= min_confidence:
|
| 409 |
+
action = "BUY"
|
| 410 |
+
elif expected_return > 0 and confidence >= min_confidence * 1.3:
|
| 411 |
+
# Relaxed entry if confidence is very high
|
| 412 |
+
action = "BUY"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
else:
|
| 414 |
+
action = "WAIT"
|
| 415 |
+
|
| 416 |
+
# Build reason string for WAIT
|
| 417 |
+
reason = None
|
| 418 |
+
if action == "WAIT":
|
| 419 |
+
parts = []
|
| 420 |
+
if expected_return < entry_threshold:
|
| 421 |
+
parts.append(
|
| 422 |
+
f"Expected return {expected_return:.2f}% < threshold {entry_threshold}%"
|
| 423 |
+
)
|
| 424 |
+
if confidence < min_confidence:
|
| 425 |
+
parts.append(
|
| 426 |
+
f"Confidence {confidence} < minimum {min_confidence}"
|
| 427 |
+
)
|
| 428 |
+
reason = "; ".join(parts) if parts else "Conditions not met"
|
| 429 |
+
|
| 430 |
+
signal = {
|
| 431 |
+
"action": action,
|
| 432 |
+
"ticker": ticker,
|
| 433 |
+
"entry_price": current_price,
|
| 434 |
+
"sl_price": levels["sl_price"],
|
| 435 |
+
"sl_pct": levels["sl_pct"],
|
| 436 |
+
"tp1_price": levels["tp1_price"],
|
| 437 |
+
"tp1_pct": levels["tp1_pct"],
|
| 438 |
+
"tp2_price": levels["tp2_price"] if levels["include_tp2"] else None,
|
| 439 |
+
"tp2_pct": levels["tp2_pct"] if levels["include_tp2"] else None,
|
| 440 |
+
"confidence": confidence,
|
| 441 |
+
"expected_return_pct": round(expected_return, 4),
|
| 442 |
+
"regime": regime,
|
| 443 |
+
"regime_details": regime_info,
|
| 444 |
+
"is_ipo": is_ipo,
|
| 445 |
+
"ipo_age_days": ipo_info.get("ipo_age_days"),
|
| 446 |
+
"current_atr": pred["current_atr"],
|
| 447 |
+
"current_rsi": pred["current_rsi"],
|
| 448 |
+
"supertrend_dir": pred["supertrend_dir"],
|
| 449 |
+
"vwap": pred["vwap"],
|
| 450 |
+
"volume_ratio": pred["volume_ratio"],
|
| 451 |
+
"sector_strength": pred.get("sector_strength", 0),
|
| 452 |
+
"model_metrics": {
|
| 453 |
+
"rmse": pred["model_rmse"],
|
| 454 |
+
"dir_accuracy": pred["model_dir_accuracy"],
|
| 455 |
+
"train_samples": pred["train_samples"],
|
| 456 |
+
},
|
| 457 |
+
"top_features": pred["top_features"],
|
| 458 |
+
"vix": pred["vix"],
|
| 459 |
+
"nifty_trend": pred["nifty_trend"],
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
if reason:
|
| 463 |
+
signal["reason"] = reason
|
| 464 |
+
|
| 465 |
+
return signal
|