import pandas as pd import numpy as np from config import settings def check_long_entry( prev_k: float, prev_d: float, curr_k: float, curr_d: float, volume: float, volume_sma: float, close: float, ema_200: float ) -> bool: """ Check if all LONG entry conditions are met. Conditions: 1. Previous candle: K < D and K <= 20 (oversold) 2. Current candle: K crosses above D and K <= 30 3. Volume > 1.5 * Volume SMA(20) 4. Close > EMA(200) (trend filter) """ if pd.isna(prev_k) or pd.isna(curr_k) or pd.isna(ema_200): return False # StochRSI conditions was_oversold = prev_k <= settings.STOCH_OVERSOLD was_below_d = prev_k < prev_d crossed_above = curr_k > curr_d still_low = curr_k <= settings.STOCH_ENTRY_MAX stoch_signal = was_oversold and was_below_d and crossed_above and still_low # Volume condition volume_ok = volume > settings.VOLUME_MULTIPLIER * volume_sma # Trend condition trend_ok = close > ema_200 return stoch_signal and volume_ok and trend_ok def check_exit_signal(curr_k: float, curr_d: float) -> bool: """ Check if early exit condition is met. Exit when StochRSI K crosses below D above 70 (overbought zone). """ if pd.isna(curr_k) or pd.isna(curr_d): return False return curr_k < curr_d and curr_k > settings.STOCH_OVERBOUGHT - 10 def generate_signals(df: pd.DataFrame) -> pd.DataFrame: """ Generate trading signals for the entire dataframe. Adds columns: - signal: 1 for LONG entry, 0 for no signal - exit_signal: 1 for early exit, 0 otherwise Returns: DataFrame with signal columns added """ df = df.copy() df["signal"] = 0 df["exit_signal"] = 0 for i in range(1, len(df)): prev = df.iloc[i - 1] curr = df.iloc[i] # Check entry signal if check_long_entry( prev_k=prev["stoch_k"], prev_d=prev["stoch_d"], curr_k=curr["stoch_k"], curr_d=curr["stoch_d"], volume=curr["volume"], volume_sma=curr["volume_sma"], close=curr["close"], ema_200=curr["ema_200"] ): df.iloc[i, df.columns.get_loc("signal")] = 1 # Check exit signal if check_exit_signal(curr["stoch_k"], curr["stoch_d"]): df.iloc[i, df.columns.get_loc("exit_signal")] = 1 return df