File size: 10,581 Bytes
922bf26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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)