File size: 6,419 Bytes
d53dc44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

ml/adaptive.py — Online / adaptive learning module.



Prevents concept drift by:

  1. Rolling retraining every N days with expanding+rolling window hybrid

  2. Recency-weighted sampling (newer data weighted higher)

  3. Performance-triggered emergency retraining

  4. Exponential decay weighting on training samples

"""
from __future__ import annotations

import logging
from dataclasses import dataclass, field

import numpy as np

logger = logging.getLogger("trading_system.ml.adaptive")


@dataclass
class RetrainDecision:
    """Encapsulates whether and why to retrain."""
    should_retrain: bool
    reason: str
    bars_since_last: int
    performance_trigger: bool = False
    staleness_trigger: bool = False


@dataclass
class AdaptiveConfig:
    """Configuration for adaptive learning."""
    retrain_interval_bars: int = 200      # retrain every N bars
    min_train_samples: int = 1000         # minimum samples to train on
    max_train_samples: int = 10_000       # cap to prevent slow training
    recency_halflife: float = 500.0       # half-life for exponential decay weights
    expanding_floor_pct: float = 0.50     # minimum fraction of total history to keep
    perf_lookback: int = 100              # bars to check recent performance
    perf_sharpe_floor: float = 0.0        # retrain if rolling Sharpe drops below
    perf_winrate_floor: float = 0.40      # retrain if win rate drops below
    gap_bars: int = 78                    # purge gap between train/test (1 trading day)


class AdaptiveLearner:
    """Manages when and how to retrain ML models adaptively.



    Uses an expanding+rolling hybrid window:

      - Always include at least `expanding_floor_pct` of all history

      - Within window, apply exponential recency weighting

      - Retrain triggered by staleness or performance decay

    """

    def __init__(self, config: AdaptiveConfig | None = None):
        self.config = config or AdaptiveConfig()
        self._last_retrain_idx: int = 0
        self._retrain_count: int = 0
        self._performance_history: list[float] = []
        self._recent_returns: list[float] = []

    def check_retrain(self, current_idx: int) -> RetrainDecision:
        """Decide if model should be retrained at current bar index."""
        bars_since = current_idx - self._last_retrain_idx
        staleness = bars_since >= self.config.retrain_interval_bars

        # Performance trigger
        perf_trigger = False
        if len(self._recent_returns) >= self.config.perf_lookback:
            recent = np.array(self._recent_returns[-self.config.perf_lookback:])
            if len(recent) > 0 and np.std(recent) > 0:
                rolling_sharpe = (np.mean(recent) / np.std(recent)) * np.sqrt(252)
                if rolling_sharpe < self.config.perf_sharpe_floor:
                    perf_trigger = True

            wins = np.sum(recent > 0)
            total = np.sum(recent != 0)
            if total > 20:
                win_rate = wins / total
                if win_rate < self.config.perf_winrate_floor:
                    perf_trigger = True

        should = staleness or perf_trigger

        reason = []
        if staleness:
            reason.append(f"stale ({bars_since} bars)")
        if perf_trigger:
            reason.append("performance decay")
        if not reason:
            reason.append("not due yet")

        return RetrainDecision(
            should_retrain=should,
            reason="; ".join(reason),
            bars_since_last=bars_since,
            performance_trigger=perf_trigger,
            staleness_trigger=staleness,
        )

    def get_train_window(

        self, total_bars: int, current_idx: int,

    ) -> tuple[int, int, np.ndarray]:
        """Compute training window and sample weights.



        Returns:

            (start_idx, end_idx, sample_weights)

            end_idx is exclusive, respects gap_bars before current_idx.

        """
        end_idx = current_idx - self.config.gap_bars
        if end_idx <= 0:
            end_idx = max(1, current_idx // 2)

        # Expanding floor: keep at least N% of all history
        min_start = 0
        floor_samples = int(end_idx * self.config.expanding_floor_pct)
        rolling_start = max(0, end_idx - self.config.max_train_samples)

        # Hybrid: max of expanding floor and rolling cap
        start_idx = min(rolling_start, end_idx - floor_samples)
        start_idx = max(start_idx, 0)

        # Ensure minimum samples
        n_samples = end_idx - start_idx
        if n_samples < self.config.min_train_samples:
            start_idx = max(0, end_idx - self.config.min_train_samples)

        # Compute recency weights (exponential decay)
        n = end_idx - start_idx
        if n <= 0:
            return start_idx, end_idx, np.array([])

        positions = np.arange(n, dtype=float)
        # Recency: most recent sample is at position n-1
        distance_from_end = (n - 1) - positions
        weights = np.exp(-distance_from_end * np.log(2) / self.config.recency_halflife)
        weights /= weights.sum()  # normalize

        return start_idx, end_idx, weights

    def record_retrain(self, idx: int):
        """Mark that a retrain occurred at this index."""
        self._last_retrain_idx = idx
        self._retrain_count += 1

    def record_trade_return(self, ret: float):
        """Record a trade return for performance monitoring."""
        self._recent_returns.append(ret)
        # Keep bounded
        if len(self._recent_returns) > 5000:
            self._recent_returns = self._recent_returns[-3000:]

    @property
    def retrain_count(self) -> int:
        return self._retrain_count


def apply_sample_weights(

    X: np.ndarray, y: np.ndarray, weights: np.ndarray,

) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Apply sample weights via resampling for models that don't support weights natively.



    Returns resampled (X, y, uniform_weights) with size = len(X).

    """
    n = len(X)
    if len(weights) != n or n == 0:
        return X, y, np.ones(n) / max(n, 1)

    # Resample proportional to weights
    rng = np.random.default_rng(42)
    indices = rng.choice(n, size=n, replace=True, p=weights)
    return X[indices], y[indices], np.ones(n) / n