""" Market Structure, Chart Pattern, and Candlestick Pattern Detector Provides objective, rule-based detection for the TVTA Vision Dataset. """ import numpy as np import pandas as pd from typing import List, Dict, Any, Optional, Tuple # ─── SWING POINT DETECTION ─────────────────────────────────────────────────── def find_swing_highs(lows: pd.Series, highs: pd.Series, order: int = 5) -> List[int]: """Find swing high indices: highs[i] is the highest in [i-order, i+order].""" swing_indices = [] for i in range(order, len(highs) - order): if highs.iloc[i] == highs.iloc[i - order:i + order + 1].max(): swing_indices.append(i) return swing_indices def find_swing_lows(lows: pd.Series, highs: pd.Series, order: int = 5) -> List[int]: """Find swing low indices: lows[i] is the lowest in [i-order, i+order].""" swing_indices = [] for i in range(order, len(lows) - order): if lows.iloc[i] == lows.iloc[i - order:i + order + 1].min(): swing_indices.append(i) return swing_indices # ─── MARKET STRUCTURE ──────────────────────────────────────────────────────── def detect_market_structure( df: pd.DataFrame, swing_order: int = 5 ) -> Dict[str, Any]: """ Detect market structure: HH, HL, LH, LL, BOS, CHoCH. Uses only data up to the final candle (no future leakage). """ highs = df["high"] lows = df["low"] closes = df["close"] swing_highs = find_swing_highs(lows, highs, swing_order) swing_lows = find_swing_lows(lows, highs, swing_order) if len(swing_highs) < 2 and len(swing_lows) < 2: return { "classification": "neutral", "sequence": "", "break_of_structure": False, "change_of_character": False, "swing_highs": len(swing_highs), "swing_lows": len(swing_lows), } # Build structure sequence structure_seq = [] all_swings = [] for idx in swing_highs: all_swings.append(("H", idx, highs.iloc[idx])) for idx in swing_lows: all_swings.append(("L", idx, lows.iloc[idx])) all_swings.sort(key=lambda x: x[1]) # Determine HH/HL/LH/LL prev_high = None prev_low = None seq_labels = [] for swing_type, idx, price in all_swings: if swing_type == "H": if prev_high is not None: if price > prev_high: seq_labels.append("HH") else: seq_labels.append("LH") prev_high = price else: if prev_low is not None: if price > prev_low: seq_labels.append("HL") else: seq_labels.append("LL") prev_low = price sequence_str = "_".join(seq_labels) if seq_labels else "" # Classification hh_count = seq_labels.count("HH") ll_count = seq_labels.count("LL") hl_count = seq_labels.count("HL") lh_count = seq_labels.count("LH") if hh_count > lh_count and hl_count >= ll_count: classification = "bullish" elif ll_count > hl_count and lh_count >= hh_count: classification = "bearish" elif hh_count == ll_count and len(seq_labels) > 0: classification = "mixed" else: classification = "neutral" # Break of Structure (BOS): price breaks the last significant swing level bos = False if len(all_swings) >= 2: last_swing = all_swings[-1] prev_swing = all_swings[-2] if last_swing[0] == "H" and closes.iloc[-1] > last_swing[2]: bos = True elif last_swing[0] == "L" and closes.iloc[-1] < last_swing[2]: bos = True # Change of Character (CHoCH): structure reverses after a clear trend choch = False if len(seq_labels) >= 3: recent = seq_labels[-3:] if classification == "bullish" and "LL" in recent[:2]: choch = True elif classification == "bearish" and "HH" in recent[:2]: choch = True return { "classification": classification, "sequence": sequence_str, "break_of_structure": bos, "change_of_character": choch, "swing_highs": len(swing_highs), "swing_lows": len(swing_lows), } # ─── TREND CLASSIFICATION ─────────────────────────────────────────────────── def classify_trend(df: pd.DataFrame, idx: int = -1) -> Dict[str, Any]: """ Classify the dominant trend using objective rules. """ if idx < 0: idx = len(df) + idx if idx < 0 or idx >= len(df): idx = len(df) - 1 row = df.iloc[idx] close = row.get("close", 0) score = 0 reasons = [] # Moving average alignment ema20 = row.get("ema_20", 0) ema50 = row.get("ema_50", 0) ema200 = row.get("ema_200", 0) if ema20 > ema50 > ema200: score += 2 reasons.append("ema_bullish_alignment") elif ema20 < ema50 < ema200: score -= 2 reasons.append("ema_bearish_alignment") # Price vs MAs if close > ema20: score += 1 else: score -= 1 if close > ema200: score += 1 else: score -= 1 # RSI rsi = row.get("rsi_14", 50) if rsi > 60: score += 1 elif rsi < 40: score -= 1 # MACD macd = row.get("macd", 0) macd_sig = row.get("macd_signal", 0) if macd > macd_sig: score += 1 else: score -= 1 # ADX adx = row.get("adx", 20) trending = adx > 25 # Price structure (last 20 candles) if idx >= 20: recent_highs = df["high"].iloc[idx - 20:idx + 1] recent_lows = df["low"].iloc[idx - 20:idx + 1] if recent_highs.is_monotonic_increasing: score += 1 elif recent_highs.is_monotonic_decreasing: score -= 1 if recent_lows.is_monotonic_increasing: score += 1 elif recent_lows.is_monotonic_decreasing: score -= 1 # Classify if score >= 5: trend = "strong_bullish" elif score >= 3: trend = "bullish" elif score >= 1: trend = "weak_bullish" elif score == 0: trend = "sideways" elif score >= -2: trend = "weak_bearish" elif score >= -4: trend = "bearish" else: trend = "strong_bearish" return { "classification": trend, "score": score, "trending": trending, "adx": round(float(adx), 2), "reasons": reasons, } # ─── SUPPORT AND RESISTANCE ───────────────────────────────────────────────── def find_support_resistance( df: pd.DataFrame, swing_order: int = 5, tolerance_pct: float = 0.01, min_touches: int = 2, ) -> Dict[str, Any]: """ Find significant support and resistance levels from swing points. """ highs = df["high"] lows = df["low"] swing_highs = find_swing_highs(lows, highs, swing_order) swing_lows = find_swing_lows(lows, highs, swing_order) # Cluster swing highs into resistance levels resistance_clusters = _cluster_levels( [highs.iloc[i] for i in swing_highs], tolerance_pct ) support_clusters = _cluster_levels( [lows.iloc[i] for i in swing_lows], tolerance_pct ) # Filter by minimum touches resistance_levels = [] for price, touches in resistance_clusters: if touches >= min_touches: resistance_levels.append({ "price": round(float(price), 2), "strength": _level_strength(touches), "touches": touches, }) support_levels = [] for price, touches in support_clusters: if touches >= min_touches: support_levels.append({ "price": round(float(price), 2), "strength": _level_strength(touches), "touches": touches, }) # Sort by proximity to current price current_price = df["close"].iloc[-1] resistance_levels.sort(key=lambda x: x["price"]) support_levels.sort(key=lambda x: x["price"], reverse=True) # Keep only levels near current price resistance_levels = [ r for r in resistance_levels if r["price"] > current_price * 0.95 and r["price"] < current_price * 1.15 ] support_levels = [ s for s in support_levels if s["price"] < current_price * 1.05 and s["price"] > current_price * 0.85 ] return { "support_levels": support_levels[:5], "resistance_levels": resistance_levels[:5], } def _cluster_levels(prices: List[float], tolerance_pct: float) -> List[Tuple[float, int]]: """Cluster nearby price levels.""" if not prices: return [] prices_sorted = sorted(prices) clusters = [] current_cluster = [prices_sorted[0]] for p in prices_sorted[1:]: cluster_mean = np.mean(current_cluster) if abs(p - cluster_mean) / cluster_mean <= tolerance_pct: current_cluster.append(p) else: clusters.append((np.mean(current_cluster), len(current_cluster))) current_cluster = [p] if current_cluster: clusters.append((np.mean(current_cluster), len(current_cluster))) return clusters def _level_strength(touches: int) -> str: if touches >= 5: return "very_strong" elif touches >= 3: return "strong" elif touches >= 2: return "medium" else: return "weak" # ─── CANDLESTICK PATTERNS ─────────────────────────────────────────────────── def detect_candlestick_patterns(df: pd.DataFrame) -> List[Dict[str, Any]]: """ Detect common candlestick patterns at the most recent candles. """ patterns = [] n = len(df) if n < 5: return patterns o = df["open"].values h = df["high"].values l = df["low"].values c = df["close"].values # Body and shadow sizes body = np.abs(c - o) upper_shadow = h - np.maximum(o, c) lower_shadow = np.minimum(o, c) - l total_range = h - l total_range = np.where(total_range == 0, 1e-10, total_range) avg_body = np.mean(body[-20:]) if n >= 20 else np.mean(body) # Doji: very small body for i in range(max(n - 5, 0), n): if body[i] < 0.1 * total_range[i]: patterns.append({ "pattern": "doji", "index": i, "strength": "medium", }) # Hammer: small body at upper end, long lower shadow for i in range(max(n - 5, 0), n): if (body[i] < 0.3 * total_range[i] and lower_shadow[i] > 2 * body[i] and upper_shadow[i] < 0.1 * total_range[i]): patterns.append({ "pattern": "hammer", "index": i, "strength": "medium", }) # Inverted Hammer: small body at lower end, long upper shadow for i in range(max(n - 5, 0), n): if (body[i] < 0.3 * total_range[i] and upper_shadow[i] > 2 * body[i] and lower_shadow[i] < 0.1 * total_range[i]): patterns.append({ "pattern": "inverted_hammer", "index": i, "strength": "medium", }) # Shooting Star: small body at lower end, long upper shadow, uptrend for i in range(max(n - 5, 0), n): if (body[i] < 0.3 * total_range[i] and upper_shadow[i] > 2 * body[i] and lower_shadow[i] < 0.1 * total_range[i] and c[i - 1] > o[i - 1] if i > 0 else False): patterns.append({ "pattern": "shooting_star", "index": i, "strength": "medium", }) # Bullish Engulfing for i in range(max(n - 5, 1), n): if (c[i - 1] < o[i - 1] and # Previous bearish c[i] > o[i] and # Current bullish o[i] <= c[i - 1] and c[i] >= o[i - 1]): patterns.append({ "pattern": "bullish_engulfing", "index": i, "strength": "strong", }) # Bearish Engulfing for i in range(max(n - 5, 1), n): if (c[i - 1] > o[i - 1] and # Previous bullish c[i] < o[i] and # Current bearish o[i] >= c[i - 1] and c[i] <= o[i - 1]): patterns.append({ "pattern": "bearish_engulfing", "index": i, "strength": "strong", }) # Morning Star (3-candle bullish reversal) for i in range(max(n - 5, 2), n): if (c[i - 2] < o[i - 2] and # Bearish body[i - 1] < 0.3 * body[i - 2] and # Small body c[i] > o[i] and # Bullish c[i] > (o[i - 2] + c[i - 2]) / 2): # Close above midpoint patterns.append({ "pattern": "morning_star", "index": i, "strength": "strong", }) # Evening Star (3-candle bearish reversal) for i in range(max(n - 5, 2), n): if (c[i - 2] > o[i - 2] and # Bullish body[i - 1] < 0.3 * body[i - 2] and # Small body c[i] < o[i] and # Bearish c[i] < (o[i - 2] + c[i - 2]) / 2): # Close below midpoint patterns.append({ "pattern": "evening_star", "index": i, "strength": "strong", }) # Three White Soldiers (3 consecutive bullish candles) for i in range(max(n - 5, 2), n): if (c[i - 2] > o[i - 2] and c[i - 1] > o[i - 1] and c[i] > o[i] and c[i - 2] < c[i - 1] < c[i] and o[i - 2] < o[i - 1] < o[i]): patterns.append({ "pattern": "three_white_soldiers", "index": i, "strength": "strong", }) # Three Black Crows (3 consecutive bearish candles) for i in range(max(n - 5, 2), n): if (c[i - 2] < o[i - 2] and c[i - 1] < o[i - 1] and c[i] < o[i] and c[i - 2] > c[i - 1] > c[i] and o[i - 2] > o[i - 1] > o[i]): patterns.append({ "pattern": "three_black_crows", "index": i, "strength": "strong", }) # Deduplicate: keep only the most recent occurrence of each pattern type seen = set() unique_patterns = [] for p in reversed(patterns): if p["pattern"] not in seen: seen.add(p["pattern"]) unique_patterns.append(p) unique_patterns.reverse() return unique_patterns # ─── CHART PATTERN DETECTION ──────────────────────────────────────────────── def detect_chart_patterns(df: pd.DataFrame) -> List[Dict[str, Any]]: """ Detect chart patterns from price structure. Returns patterns only when structural evidence meets criteria. """ patterns = [] n = len(df) if n < 30: return patterns highs = df["high"].values lows = df["low"].values closes = df["close"].values volumes = df["volume"].values # Find swing points swing_highs = find_swing_highs(df["low"], df["high"], 5) swing_lows = find_swing_lows(df["low"], df["high"], 5) # Double Top: two similar highs with a trough in between if len(swing_highs) >= 2: for i in range(len(swing_highs) - 1): h1 = highs[swing_highs[i]] h2 = highs[swing_highs[i + 1]] if abs(h1 - h2) / h1 < 0.02: # Within 2% trough_idx = swing_highs[i] + np.argmin(lows[swing_highs[i]:swing_highs[i + 1]]) trough = lows[trough_idx] if (h1 - trough) / h1 > 0.03: # At least 3% drop patterns.append({ "pattern": "double_top", "strength": "strong", "neckline": round(float(trough), 2), }) break # Double Bottom: two similar lows with a peak in between if len(swing_lows) >= 2: for i in range(len(swing_lows) - 1): l1 = lows[swing_lows[i]] l2 = lows[swing_lows[i + 1]] if abs(l1 - l2) / l1 < 0.02: peak_idx = swing_lows[i] + np.argmax(highs[swing_lows[i]:swing_lows[i + 1]]) peak = highs[peak_idx] if (peak - l1) / l1 > 0.03: patterns.append({ "pattern": "double_bottom", "strength": "strong", "neckline": round(float(peak), 2), }) break # Head and Shoulders: three highs with the middle highest if len(swing_highs) >= 3: for i in range(len(swing_highs) - 2): left = highs[swing_highs[i]] head = highs[swing_highs[i + 1]] right = highs[swing_highs[i + 2]] if head > left * 1.02 and head > right * 1.02: # Find neckline (lows between shoulders) neck_lows = lows[swing_highs[i]:swing_highs[i + 2] + 1] neckline = np.min(neck_lows) patterns.append({ "pattern": "head_and_shoulders", "strength": "strong", "neckline": round(float(neckline), 2), }) break # Ascending Triangle: rising flat resistance, higher lows if len(swing_highs) >= 2 and len(swing_lows) >= 2: recent_highs = [highs[i] for i in swing_highs[-3:]] recent_lows = [lows[i] for i in swing_lows[-3:]] if (abs(recent_highs[-1] - recent_highs[0]) / recent_highs[0] < 0.01 and recent_lows[-1] > recent_lows[0]): patterns.append({ "pattern": "ascending_triangle", "strength": "medium", }) # Descending Triangle: falling flat support, lower highs if len(swing_highs) >= 2 and len(swing_lows) >= 2: recent_highs = [highs[i] for i in swing_highs[-3:]] recent_lows = [lows[i] for i in swing_lows[-3:]] if (abs(recent_lows[-1] - recent_lows[0]) / recent_lows[0] < 0.01 and recent_highs[-1] < recent_highs[0]): patterns.append({ "pattern": "descending_triangle", "strength": "medium", }) # Bull Flag: strong uptrend followed by consolidation if n >= 20: first_half = closes[:n // 2] second_half = closes[n // 2:] if (first_half[-1] > first_half[0] * 1.05 and # Strong uptrend np.std(second_half) < np.std(first_half) * 0.5): # Consolidation patterns.append({ "pattern": "bull_flag", "strength": "medium", }) # Bear Flag: strong downtrend followed by consolidation if n >= 20: first_half = closes[:n // 2] second_half = closes[n // 2:] if (first_half[-1] < first_half[0] * 0.95 and np.std(second_half) < np.std(first_half) * 0.5): patterns.append({ "pattern": "bear_flag", "strength": "medium", }) # Rectangle/Consolidation: price in a range if n >= 20: recent_high = np.max(highs[-20:]) recent_low = np.min(lows[-20:]) range_pct = (recent_high - recent_low) / recent_low if range_pct < 0.05: # Less than 5% range patterns.append({ "pattern": "rectangle", "strength": "medium", "range_high": round(float(recent_high), 2), "range_low": round(float(recent_low), 2), }) # Deduplicate seen = set() unique = [] for p in patterns: if p["pattern"] not in seen: seen.add(p["pattern"]) unique.append(p) return unique # ─── DIVERGENCE DETECTION ─────────────────────────────────────────────────── def detect_divergence(df: pd.DataFrame) -> List[Dict[str, Any]]: """ Detect RSI and MACD divergence from price. """ divergences = [] n = len(df) if n < 30: return divergences if "rsi_14" not in df.columns: return divergences closes = df["close"].values rsi = df["rsi_14"].values # Find local swing points in price and RSI swing_highs = find_swing_highs(df["low"], df["high"], 5) swing_lows = find_swing_lows(df["low"], df["high"], 5) # Bullish RSI divergence: price makes lower low, RSI makes higher low if len(swing_lows) >= 2: for i in range(len(swing_lows) - 1): if (closes[swing_lows[i + 1]] < closes[swing_lows[i]] and rsi[swing_lows[i + 1]] > rsi[swing_lows[i]]): divergences.append({ "type": "bullish_rsi_divergence", "indicator": "rsi", "strength": "medium", }) break # Bearish RSI divergence: price makes higher high, RSI makes lower high if len(swing_highs) >= 2: for i in range(len(swing_highs) - 1): if (closes[swing_highs[i + 1]] > closes[swing_highs[i]] and rsi[swing_highs[i + 1]] < rsi[swing_highs[i]]): divergences.append({ "type": "bearish_rsi_divergence", "indicator": "rsi", "strength": "medium", }) break # MACD divergence if "macd" in df.columns: macd = df["macd"].values if len(swing_lows) >= 2: for i in range(len(swing_lows) - 1): if (closes[swing_lows[i + 1]] < closes[swing_lows[i]] and macd[swing_lows[i + 1]] > macd[swing_lows[i]]): divergences.append({ "type": "bullish_macd_divergence", "indicator": "macd", "strength": "medium", }) break if len(swing_highs) >= 2: for i in range(len(swing_highs) - 1): if (closes[swing_highs[i + 1]] > closes[swing_highs[i]] and macd[swing_highs[i + 1]] < macd[swing_highs[i]]): divergences.append({ "type": "bearish_macd_divergence", "indicator": "macd", "strength": "medium", }) break return divergences # ─── BREAKOUT DETECTION ───────────────────────────────────────────────────── def detect_breakout(df: pd.DataFrame) -> Dict[str, Any]: """ Detect breakout/breakdown conditions. """ n = len(df) if n < 20: return {"status": "no_breakout"} closes = df["close"].values volumes = df["volume"].values highs = df["high"].values lows = df["low"].values # Recent range recent_high = np.max(highs[-20:-1]) # Exclude last candle recent_low = np.min(lows[-20:-1]) current_close = closes[-1] avg_vol = np.mean(volumes[-20:-1]) current_vol = volumes[-1] result = {"status": "no_breakout"} # Upside breakout if current_close > recent_high: vol_confirm = current_vol > avg_vol * 1.2 if vol_confirm: result = { "status": "confirmed_breakout", "direction": "up", "level": round(float(recent_high), 2), "volume_confirmation": True, } else: result = { "status": "potential_breakout", "direction": "up", "level": round(float(recent_high), 2), "volume_confirmation": False, } # Downside breakdown elif current_close < recent_low: vol_confirm = current_vol > avg_vol * 1.2 if vol_confirm: result = { "status": "confirmed_breakdown", "direction": "down", "level": round(float(recent_low), 2), "volume_confirmation": True, } else: result = { "status": "potential_breakdown", "direction": "down", "level": round(float(recent_low), 2), "volume_confirmation": False, } return result # ─── MARKET REGIME ────────────────────────────────────────────────────────── def classify_market_regime(df: pd.DataFrame) -> Dict[str, Any]: """ Classify the primary market regime. """ n = len(df) if n < 20: return {"primary": "unknown", "secondary": []} closes = df["close"].values volumes = df["volume"].values # Volatility returns = np.diff(np.log(closes)) current_vol = np.std(returns[-20:]) * np.sqrt(252) avg_vol = np.std(returns) * np.sqrt(252) if len(returns) > 0 else current_vol # Trend trend_info = classify_trend(df) trend = trend_info["classification"] # Range detection recent_high = np.max(df["high"].values[-20:]) recent_low = np.min(df["low"].values[-20:]) range_pct = (recent_high - recent_low) / recent_low # Volume pattern vol_mean = np.mean(volumes[-30:]) if n >= 30 else np.mean(volumes) vol_trend = np.mean(volumes[-10:]) / vol_mean if vol_mean > 0 else 1.0 regime = "transition" secondary = [] if current_vol > avg_vol * 1.5: secondary.append("high_volatility") elif current_vol < avg_vol * 0.5: secondary.append("low_volatility") if range_pct < 0.03 and "sideways" in trend: regime = "sideways_range" elif "bullish" in trend and vol_trend > 1.2: regime = "bull_trend" elif "bearish" in trend and vol_trend > 1.2: regime = "bear_trend" elif "bullish" in trend: regime = "accumulation" elif "bearish" in trend: regime = "distribution" elif current_vol > avg_vol * 1.5: regime = "high_volatility" # Breakout regime breakout = detect_breakout(df) if "confirmed_breakout" in breakout.get("status", ""): secondary.append("breakout_regime") elif "confirmed_breakdown" in breakout.get("status", ""): secondary.append("breakdown_regime") return { "primary": regime, "secondary": secondary, "volatility_annualized": round(float(current_vol), 4), }