tvta-vision / src /forward_performance.py
s31EmDe's picture ismailtasdelen's picture
Duplicate from ismailtasdelen/tvta-vision
922bf26
Raw History Blame Contribute Delete
10.6 kB
"""
Forward Performance Calculator
Calculates historical forward returns and signal outcomes.
Uses ONLY future candles (after the chart's final candle) for these calculations.
"""
import numpy as np
import pandas as pd
from typing import Dict, Any, Optional, List
def calculate_forward_performance(
full_df: pd.DataFrame,
chart_end_idx: int,
candles_ahead: list = [1, 5, 10, 20],
) -> Dict[str, Any]:
"""
Calculate forward performance after the chart's final candle.
Parameters
----------
full_df : DataFrame with the full OHLCV series.
chart_end_idx : Index of the last candle in the chart window.
candles_ahead : List of forward periods to calculate.
Returns
-------
Dict with forward returns, MFE, MAE, max drawdown, future volatility.
"""
n = len(full_df)
if chart_end_idx >= n - 1:
return {"insufficient_future_data": True}
close_price = full_df["close"].iloc[chart_end_idx]
if close_price <= 0:
close_price = 1e-10
result = {"insufficient_future_data": False}
# Forward returns
for period in candles_ahead:
future_idx = chart_end_idx + period
if future_idx < n:
future_price = full_df["close"].iloc[future_idx]
ret = (future_price - close_price) / close_price
result[f"return_{period}c"] = round(float(ret), 6)
# Maximum Favorable Excursion (MFE) and Maximum Adverse Excursion (MAE)
max_available = min(50, n - chart_end_idx - 1)
if max_available > 0:
future_highs = full_df["high"].iloc[chart_end_idx + 1:chart_end_idx + 1 + max_available]
future_lows = full_df["low"].iloc[chart_end_idx + 1:chart_end_idx + 1 + max_available]
max_favorable = (future_highs.max() - close_price) / close_price
max_adverse = (future_lows.min() - close_price) / close_price
result["max_favorable_excursion"] = round(float(max_favorable), 6)
result["max_adverse_excursion"] = round(float(max_adverse), 6)
# Maximum drawdown from chart end
future_closes = full_df["close"].iloc[chart_end_idx:chart_end_idx + 1 + max_available]
peak = future_closes.expanding().max()
drawdown = (future_closes - peak) / peak
result["max_drawdown"] = round(float(drawdown.min()), 6)
# Future volatility
if len(future_closes) > 1:
log_returns = np.log(future_closes / future_closes.shift(1)).dropna()
result["future_volatility"] = round(float(log_returns.std() * np.sqrt(252)), 6)
return result
def classify_signal_outcome(
signal_type: str,
forward_perf: Dict[str, Any],
threshold: float = 0.01,
) -> str:
"""
Classify the historical outcome of a technical signal.
Parameters
----------
signal_type : Type of signal (breakout, reversal, pattern, etc.)
forward_perf : Forward performance dict from calculate_forward_performance.
threshold : Minimum return to consider a signal successful (1%).
Returns
-------
Outcome classification string.
"""
if forward_perf.get("insufficient_future_data"):
return "unknown"
ret_10c = forward_perf.get("return_10c", 0)
ret_20c = forward_perf.get("return_20c", 0)
mfe = forward_perf.get("max_favorable_excursion", 0)
mae = forward_perf.get("max_adverse_excursion", 0)
if signal_type == "breakout":
if ret_10c > threshold and mfe > threshold * 1.5:
return "confirmed_breakout"
elif ret_10c < -threshold:
return "failed_breakout"
elif mfe > threshold and ret_10c > 0:
return "breakout_retest_success"
elif mfe > threshold and ret_10c <= 0:
return "breakout_retest_failure"
else:
return "neutral"
elif signal_type == "reversal":
if ret_20c > threshold * 2:
return "successful"
elif ret_20c > threshold:
return "partially_successful"
elif ret_20c < -threshold:
return "failed"
else:
return "neutral"
elif signal_type == "pattern":
if mfe > threshold * 2 and ret_10c > threshold:
return "successful"
elif mfe > threshold and ret_10c > 0:
return "partially_successful"
elif mae < -threshold and ret_10c < 0:
return "failed"
else:
return "neutral"
else:
if ret_10c > threshold:
return "successful"
elif ret_10c < -threshold:
return "failed"
else:
return "neutral"
def calculate_technical_score(
trend: Dict[str, Any],
market_structure: Dict[str, Any],
indicators: Dict[str, Any],
volume_analysis: Dict[str, Any],
patterns: List[Dict[str, Any]],
breakout: Dict[str, Any],
) -> Dict[str, Any]:
"""
Calculate a composite technical score and bias.
"""
score = 0
breakdown = {}
# Trend contribution (-3 to +3)
trend_map = {
"strong_bullish": 3, "bullish": 2, "weak_bullish": 1,
"sideways": 0,
"weak_bearish": -1, "bearish": -2, "strong_bearish": -3,
}
trend_score = trend_map.get(trend.get("classification", "sideways"), 0)
score += trend_score
breakdown["trend"] = trend_score
# Market structure contribution (-2 to +2)
struct_map = {"bullish": 2, "bearish": -2, "mixed": 0, "neutral": 0}
struct_score = struct_map.get(market_structure.get("classification", "neutral"), 0)
if market_structure.get("break_of_structure"):
struct_score += 1 if struct_score >= 0 else -1
score += struct_score
breakdown["market_structure"] = struct_score
# Momentum contribution (-2 to +2)
rsi = indicators.get("rsi", {})
rsi_score = 0
if rsi.get("zone") in ("overbought",):
rsi_score = -1
elif rsi.get("zone") in ("oversold",):
rsi_score = 1
elif rsi.get("zone") == "neutral_bullish":
rsi_score = 1
elif rsi.get("zone") == "neutral_bearish":
rsi_score = -1
macd = indicators.get("macd", {})
macd_score = 1 if "bullish" in macd.get("state", "") else (-1 if "bearish" in macd.get("state", "") else 0)
momentum_score = rsi_score + macd_score
score += momentum_score
breakdown["momentum"] = momentum_score
# Volume contribution (-1 to +1)
vol = volume_analysis.get("current_volume_vs_average", 1.0)
vol_score = 0
if vol > 1.5:
vol_score = 1
elif vol < 0.5:
vol_score = -1
score += vol_score
breakdown["volume"] = vol_score
# Moving average contribution (-2 to +2)
ema = indicators.get("ema_structure", {})
ma_score = 0
if ema.get("alignment") == "bullish":
ma_score = 2
elif ema.get("alignment") == "bearish":
ma_score = -2
score += ma_score
breakdown["moving_averages"] = ma_score
# Pattern contribution (-1 to +1)
pattern_score = 0
for p in patterns:
name = p.get("pattern", "")
if name in ("double_bottom", "bull_flag", "ascending_triangle", "morning_star",
"inverse_head_and_shoulders", "cup_and_handle"):
pattern_score = 1
elif name in ("double_top", "bear_flag", "descending_triangle", "evening_star",
"head_and_shoulders", "inverse_cup_and_handle"):
pattern_score = -1
score += pattern_score
breakdown["pattern"] = pattern_score
# Breakout contribution (-1 to +1)
breakout_score = 0
if breakout.get("status") == "confirmed_breakout":
breakout_score = 1
elif breakout.get("status") == "confirmed_breakdown":
breakout_score = -1
elif breakout.get("status") == "false_breakout":
breakout_score = -1
elif breakout.get("status") == "false_breakdown":
breakout_score = 1
score += breakout_score
breakdown["breakout"] = breakout_score
# Classify bias
if score >= 7:
bias = "strong_bullish"
elif score >= 4:
bias = "bullish"
elif score >= 2:
bias = "slightly_bullish"
elif score >= -1:
bias = "neutral"
elif score >= -3:
bias = "slightly_bearish"
elif score >= -6:
bias = "bearish"
else:
bias = "strong_bearish"
return {
"score": score,
"bias": bias,
"breakdown": breakdown,
}
def calculate_confidence(
trend: Dict[str, Any],
market_structure: Dict[str, Any],
indicators: Dict[str, Any],
patterns: List[Dict[str, Any]],
volume_analysis: Dict[str, Any],
) -> float:
"""
Calculate a confidence score (0.0 - 1.0) for the technical analysis.
"""
factors = []
# Signal agreement
signals = []
if "bullish" in trend.get("classification", ""):
signals.append(1)
elif "bearish" in trend.get("classification", ""):
signals.append(-1)
else:
signals.append(0)
rsi_zone = indicators.get("rsi", {}).get("zone", "")
if rsi_zone in ("neutral_bullish", "oversold"):
signals.append(1)
elif rsi_zone in ("neutral_bearish", "overbought"):
signals.append(-1)
else:
signals.append(0)
macd_state = indicators.get("macd", {}).get("state", "")
if "bullish" in macd_state:
signals.append(1)
elif "bearish" in macd_state:
signals.append(-1)
else:
signals.append(0)
# Agreement ratio
non_zero = [s for s in signals if s != 0]
if non_zero:
agreement = abs(sum(non_zero)) / len(non_zero)
else:
agreement = 0.5
factors.append(agreement)
# Pattern quality
if patterns:
strong_patterns = sum(1 for p in patterns if p.get("strength") == "strong")
factors.append(min(strong_patterns * 0.3, 1.0))
else:
factors.append(0.3)
# Market structure clarity
struct_class = market_structure.get("classification", "neutral")
if struct_class in ("bullish", "bearish"):
factors.append(0.8)
else:
factors.append(0.4)
# Volume confirmation
vol_ratio = volume_analysis.get("current_volume_vs_average", 1.0)
if vol_ratio > 1.5:
factors.append(0.8)
elif vol_ratio > 0.8:
factors.append(0.6)
else:
factors.append(0.3)
# ADX strength
adx = indicators.get("adx", {}).get("value", 20)
if adx > 40:
factors.append(0.9)
elif adx > 25:
factors.append(0.7)
else:
factors.append(0.4)
confidence = round(float(np.mean(factors)), 2)
return min(max(confidence, 0.0), 1.0)