trading-platform/orchestration/tareas/TASK-2026-01-25-ML-TRAINING-ENHANCEMENT/02-ANALISIS.md
Adrian Flores Cortes 7bfcbb978e docs: Add OQI-006 DATA-PIPELINE-SPEC.md and ML-TRAINING-ENHANCEMENT task docs
- Added DATA-PIPELINE-SPEC.md for ML signals module
- Added TASK-2026-01-25-ML-TRAINING-ENHANCEMENT documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 14:32:37 -06:00

688 lines
30 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 02-ANÁLISIS: Mejora Integral de Modelos ML para Trading
**Task ID:** TASK-2026-01-25-ML-TRAINING-ENHANCEMENT
**Fase:** A - Análisis
**Estado:** Completada
**Fecha:** 2026-01-25
---
## 1. COMPORTAMIENTO DESEADO (Perspectiva de Negocio)
### 1.1 Visión del Sistema
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ SISTEMA ML DE TRADING OBJETIVO │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ [Datos de Mercado] → [5 Estrategias ML] → [Metamodelo Ensemble] → [LLM Agent] │
│ ↓ ↓ │
│ [Atención sobre [Decisión │
│ Variación Precio] de Trading] │
│ ↓ │
│ [Ejecución MT4] │
│ ↓ │
│ [80%+ Efectividad] │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
### 1.2 Comportamientos Esperados
| ID | Comportamiento | Descripción |
|----|----------------|-------------|
| B1 | Predicción Multi-Estrategia | El sistema genera predicciones desde 5 estrategias independientes |
| B2 | Atención Dinámica | El modelo aprende a enfocarse en patrones de variación de precio relevantes |
| B3 | Especialización por Activo | Cada activo tiene su propio modelo entrenado |
| B4 | Síntesis Ensemble | Un metamodelo combina las predicciones de todas las estrategias |
| B5 | Decisión LLM Informada | El LLM recibe señales procesadas para tomar decisiones |
| B6 | Agnóstico Temporal | Las predicciones no dependen del horario específico |
| B7 | Efectividad Verificable | Cada operación se puede rastrear a la predicción que la generó |
---
## 2. ANÁLISIS DE ARQUITECTURAS EXISTENTES
### 2.1 Proyecto Antiguo (WorkspaceOld/trading)
#### Fortalezas
- **Ensemble XGBoost + GRU**: Combina gradiente boosting con redes recurrentes
- **22 indicadores técnicos** bien calibrados
- **Horizontes múltiples** (0, 1, 2, 4 períodos)
- **Predicción triple** (high, close, low)
- **Datos históricos extensos** (10+ años)
#### Debilidades
- Sin mecanismos de atención explícitos
- Modelos no especializados por activo
- Sin integración LLM
- Arquitectura monolítica
#### Conocimiento a Migrar
```yaml
indicadores_tecnicos:
momentum:
- MACD (12/26/9)
- RSI (periodo 14)
- ROC (Rate of Change)
volatilidad:
- ATR (periodo 10)
- Bollinger Bands
volumen:
- OBV (On-Balance Volume)
- MFI (Money Flow Index, periodo 14)
- CMF (Chaikin Money Flow, periodo 20)
- volume_z (Z-score, rolling 20)
- volume_anomaly (binario)
estructura:
- SAR (Parabolic SAR)
- Fractal_Alcista (5-bar)
- Fractal_Bajista (5-bar)
- AD (Accumulation/Distribution)
medias:
- SMA_10, SMA_20
ventanas_rodantes:
- 15m (3 velas de 5min)
- 60m (12 velas de 5min)
- 120m (24 velas de 5min)
targets:
- target_pct_hour: (close_hour_final - close) / close
```
### 2.2 Proyecto Actual (trading-platform)
#### Fortalezas
- **Arquitectura jerárquica** (Level 0/1/2)
- **Mecanismos de atención** implementados (Level 0)
- **15 modelos especializados**
- **Integración LLM** existente
- **Backtesting engine** funcional
- **Walk-forward validation**
#### Debilidades
- Solo 1 año de datos (469K bars)
- Level 2 (AssetMetamodel) incompleto
- Accuracy actual ~65-70%
- Estrategia única (no diversificada)
#### Modelos Existentes a Mejorar
```yaml
level_0_attention:
- AttentionScoreModel (flujo de mercado)
- 12 modelos entrenados por símbolo+timeframe
level_1_prediction:
- AMDDetector (fases Smart Money)
- RangePredictor v1/v2 (high/low)
- SignalGenerator (señales trading)
- EnhancedRangePredictor
- TPSLClassifier
level_2_synthesis:
- AssetMetamodel (PENDIENTE)
- DualHorizonEnsemble
- StrategyEnsemble
- NeuralGatingMetamodel
```
---
## 3. DISEÑO DE 5 ESTRATEGIAS DE MODELOS
### 3.1 Estrategia 1: PRICE-VARIATION-ATTENTION (PVA)
**Enfoque:** Atención sobre variación de precio pura, agnóstica al tiempo y activo.
```yaml
nombre: "Price Variation Attention"
codigo: "PVA"
arquitectura:
tipo: "Transformer Encoder + XGBoost Head"
attention_mechanism: "Self-Attention sobre secuencias de retornos"
features:
primarios:
- returns_1: (close[t] - close[t-1]) / close[t-1]
- returns_5: (close[t] - close[t-5]) / close[t-5]
- returns_10: (close[t] - close[t-10]) / close[t-10]
- returns_20: (close[t] - close[t-20]) / close[t-20]
derivados:
- acceleration: returns_1[t] - returns_1[t-1]
- volatility_returns: std(returns_5, window=20)
- skewness_returns: skew(returns_10, window=50)
- kurtosis_returns: kurt(returns_10, window=50)
attention_scores:
- attention_weight_1 a attention_weight_seq_len (aprendidos)
targets:
- future_return_1h: (close[t+12] - close[t]) / close[t] # 12 velas de 5min = 1h
- future_volatility: std(returns próximos 12 períodos)
- direction_confidence: softmax([-1, 0, +1])
entrenamiento:
sequence_length: 100 # velas de contexto
batch_size: 256
learning_rate: 0.0001
epochs: 100
early_stopping: 10
modelo_por_activo: true
ignorar_horario: true # No usar features de sesión
```
### 3.2 Estrategia 2: MOMENTUM-REGIME-DETECTION (MRD)
**Enfoque:** Detectar régimen de mercado (tendencia/rango) y predecir continuación.
```yaml
nombre: "Momentum Regime Detection"
codigo: "MRD"
arquitectura:
tipo: "Hidden Markov Model + LSTM + XGBoost"
hmm_states: 3 # Trend Up, Range, Trend Down
features:
momentum:
- rsi_14, rsi_28
- macd, macd_signal, macd_histogram
- roc_5, roc_10, roc_20
- adx, +di, -di
tendencia:
- ema_crossover_9_21: sign(ema_9 - ema_21)
- ema_crossover_21_50: sign(ema_21 - ema_50)
- price_vs_ema_200: (close - ema_200) / ema_200
regimen:
- hmm_state: [0, 1, 2] # Detectado por HMM
- regime_probability: softmax de HMM
- regime_duration: velas desde último cambio
targets:
- next_regime: estado HMM en t+12
- regime_duration_prediction: cuántas velas durará el régimen
- momentum_continuation: bool (momentum sigue en misma dirección)
entrenamiento:
hmm_iterations: 100
lstm_units: 128
dropout: 0.3
modelo_por_activo: true
incluir_sesion: false # Régimen es agnóstico
```
### 3.3 Estrategia 3: VOLATILITY-BREAKOUT-PREDICTOR (VBP)
**Enfoque:** Predecir breakouts basados en compresión de volatilidad.
```yaml
nombre: "Volatility Breakout Predictor"
codigo: "VBP"
arquitectura:
tipo: "CNN 1D + Attention + XGBoost"
cnn_filters: [32, 64, 128]
kernel_sizes: [3, 5, 7]
features:
volatilidad:
- atr_5, atr_10, atr_20, atr_50
- bb_width: (bb_upper - bb_lower) / bb_middle
- bb_squeeze: bool(bb_width < bb_width.rolling(50).quantile(0.2))
- keltner_squeeze: bb dentro de keltner channels
- historical_volatility: std(returns, window=20) * sqrt(252)
rango:
- hl_range: (high - low) / close
- hl_range_vs_atr: hl_range / atr_10
- compression_score: min(hl_range últimas 10 velas) / max(hl_range últimas 50)
expansion:
- expansion_imminent: compression_score < 0.3
- breakout_direction_bias: sign(close - open de la compresión)
targets:
- breakout_next_12: bool(max(high[t:t+12]) - min(low[t:t+12]) > 2*atr)
- breakout_direction: [-1, 0, +1] (down, no breakout, up)
- breakout_magnitude: (high_max - low_min) / close si breakout
entrenamiento:
imbalanced_sampling: true # Breakouts son raros
oversample_breakouts: 3x
modelo_por_activo: true
```
### 3.4 Estrategia 4: MARKET-STRUCTURE-ANALYSIS (MSA)
**Enfoque:** Análisis de estructura de mercado (ICT/SMC concepts).
```yaml
nombre: "Market Structure Analysis"
codigo: "MSA"
arquitectura:
tipo: "Graph Neural Network + XGBoost"
gnn_layers: 4
node_features: swing_points
features:
estructura:
- swing_high: high mayor que 2 altos anteriores y posteriores
- swing_low: low menor que 2 bajos anteriores y posteriores
- higher_high: swing_high > swing_high anterior
- lower_low: swing_low < swing_low anterior
- bos_up: Break of Structure alcista
- bos_down: Break of Structure bajista
- choch: Change of Character (cambio de tendencia)
zonas:
- order_block_bullish: última vela bajista antes de BOS alcista
- order_block_bearish: última vela alcista antes de BOS bajista
- fvg_bullish: Fair Value Gap alcista
- fvg_bearish: Fair Value Gap bajista
- liquidity_sweep: barrido de liquidez
posicion:
- price_vs_poi: distancia a Point of Interest más cercano
- poi_type: [order_block, fvg, swing, none]
- premium_discount: precio en zona premium (>50%) o discount (<50%)
targets:
- next_bos_direction: [-1, +1] próximo BOS
- poi_reaction: bool (precio reacciona al POI)
- structure_continuation: bool (estructura continúa)
entrenamiento:
graph_attention: true
node_aggregation: "mean"
modelo_por_activo: true
```
### 3.5 Estrategia 5: MULTI-TIMEFRAME-SYNTHESIS (MTS)
**Enfoque:** Síntesis de señales de múltiples timeframes con ponderación dinámica.
```yaml
nombre: "Multi-Timeframe Synthesis"
codigo: "MTS"
arquitectura:
tipo: "Hierarchical Attention Network"
timeframes: [5m, 15m, 1h, 4h]
attention_per_tf: true
features_por_timeframe:
5m:
- all_base_features (momentum, volatility, volume)
- micro_structure (last 50 bars)
15m:
- aggregated_features
- trend_alignment_5m
1h:
- session_context
- intraday_trend
4h:
- swing_structure
- major_trend
synthesis:
- tf_alignment_score: concordancia entre timeframes
- dominant_tf: timeframe con señal más fuerte
- conflict_score: nivel de conflicto entre TFs
targets:
- unified_direction: [-1, 0, +1] consenso de TFs
- confidence_by_alignment: 0-1 basado en concordancia
- optimal_entry_tf: cuál TF da mejor entry
entrenamiento:
hierarchical_loss: true
tf_weights: learnable
modelo_por_activo: true
```
---
## 4. ARQUITECTURA DE ATENCIÓN PROPUESTA
### 4.1 Price-Focused Attention Mechanism
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ PRICE-FOCUSED ATTENTION ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ Input: Secuencia de Retornos [r_1, r_2, ..., r_T] │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Positional Encoding (Learnable) │ │
│ │ SIN usar información temporal real │ │
│ │ Solo posición relativa en secuencia │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Self-Attention Layer x 4 │ │
│ │ │ │
│ │ Q = W_q * X K = W_k * X V = W_v * X │ │
│ │ │ │
│ │ Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) * V │ │
│ │ │ │
│ │ Multi-Head: 8 heads, d_model=256, d_k=32 │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Feed-Forward Network │ │
│ │ FFN(x) = ReLU(xW_1 + b_1)W_2 + b_2 │ │
│ │ d_ff = 1024 │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Attention Score Extraction │ │
│ │ scores = mean(attention_weights, dim=heads) │ │
│ │ top_k_positions = argsort(scores)[-k:] │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ XGBoost Prediction Head │ │
│ │ Input: [attended_features, attention_scores, raw] │ │
│ │ Output: [direction, magnitude, confidence] │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
### 4.2 Características Clave
1. **Sin Información Temporal Explícita:** No usa features de hora/día/sesión
2. **Solo Variación de Precio:** Features basados únicamente en retornos y derivados
3. **Atención Aprendida:** El modelo aprende qué variaciones son relevantes
4. **Agnóstico al Activo:** Arquitectura idéntica para todos los activos (pesos diferentes)
---
## 5. ARQUITECTURA DE METAMODELO ENSEMBLE
### 5.1 Neural Gating Metamodel
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ NEURAL GATING METAMODEL │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ Inputs: │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ PVA │ │ MRD │ │ VBP │ │ MSA │ │ MTS │ │
│ │ pred,conf│ │ pred,conf│ │ pred,conf│ │ pred,conf│ │ pred,conf│ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │ │
│ └────────────┴────────────┴────────────┴────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Gating Network │ │
│ │ Input: [all_predictions, all_confidences, market_ctx] │ │
│ │ Output: weights = softmax(gate_logits) │ │
│ │ Architecture: 3-layer MLP (256, 128, 5) │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Weighted Ensemble │ │
│ │ final_pred = sum(weights * predictions) │ │
│ │ final_conf = weighted_confidence(weights, confs) │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Output │ │
│ │ - direction: [-1, 0, +1] │ │
│ │ - magnitude: expected % move │ │
│ │ - confidence: 0-1 │ │
│ │ - strategy_attribution: which strategy dominated │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
### 5.2 Lógica de Gating
```python
class NeuralGatingMetamodel:
def forward(self, strategy_outputs, market_context):
# Concatenar outputs de todas las estrategias
features = torch.cat([
strategy_outputs['PVA'], # [pred, conf]
strategy_outputs['MRD'],
strategy_outputs['VBP'],
strategy_outputs['MSA'],
strategy_outputs['MTS'],
market_context, # volatility, regime, etc.
], dim=-1)
# Gating network decide pesos
gate_logits = self.gate_network(features)
weights = F.softmax(gate_logits, dim=-1)
# Ensemble ponderado
predictions = torch.stack([
strategy_outputs[s]['prediction'] for s in STRATEGIES
], dim=-1)
final_prediction = (weights * predictions).sum(dim=-1)
return {
'prediction': final_prediction,
'weights': weights,
'confidence': self.confidence_head(features),
}
```
---
## 6. INTEGRACIÓN LLM PROPUESTA
### 6.1 Flujo de Decisión
```
┌─────────────────────────────────────────────────────────────────────────────────┐
│ LLM DECISION INTEGRATION │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ 1. ML Engine genera predicciones │
│ ↓ │
│ 2. Metamodel sintetiza señal final │
│ ↓ │
│ 3. Signal Formatter prepara prompt para LLM │
│ ↓ │
│ 4. LLM analiza contexto + predicciones │
│ ↓ │
│ 5. LLM decide: TRADE / NO_TRADE / WAIT │
│ ↓ │
│ 6. Si TRADE: LLM define entry, SL, TP │
│ ↓ │
│ 7. Trading Agent ejecuta │
│ ↓ │
│ 8. Signal Logger registra resultado │
│ ↓ │
│ 9. Fine-tuning loop (feedback) │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
```
### 6.2 Prompt Structure para LLM
```python
TRADING_DECISION_PROMPT = """
## Market Analysis for {symbol}
### ML Predictions (Ensemble)
- Direction: {direction} (confidence: {confidence}%)
- Predicted Move: {magnitude}%
- Dominant Strategy: {dominant_strategy}
- Strategy Agreement: {agreement_score}/5
### Individual Strategy Signals
| Strategy | Direction | Confidence | Weight |
|----------|-----------|------------|--------|
{strategy_table}
### Current Market Context
- Volatility Regime: {volatility_regime}
- Market Structure: {market_structure}
- Key Levels: {key_levels}
### Risk Parameters
- Account Balance: {balance}
- Max Risk per Trade: {max_risk}%
- Current Open Positions: {open_positions}
### Task
Analyze the above information and decide:
1. Should we take this trade? (YES/NO/WAIT)
2. If YES, provide:
- Entry price (or MARKET)
- Stop Loss level
- Take Profit level(s)
- Position size (% of balance)
3. Reasoning (brief)
Response Format:
DECISION: [YES|NO|WAIT]
ENTRY: [price]
STOP_LOSS: [price]
TAKE_PROFIT: [price1, price2]
POSITION_SIZE: [%]
REASONING: [text]
"""
```
---
## 7. OBJETOS IMPACTADOS
### 7.1 Base de Datos (PostgreSQL)
| Schema | Tabla | Cambio |
|--------|-------|--------|
| ml | model_registry | Agregar campos para 5 estrategias |
| ml | predictions | Agregar columnas por estrategia |
| ml | strategy_weights | NUEVA - pesos del gating |
| ml | training_runs | Agregar metadata de estrategia |
| ml | backtest_results | Agregar resultados por estrategia |
| ml | attention_weights | NUEVA - scores de atención guardados |
### 7.2 Backend (ml-engine)
| Archivo/Directorio | Cambio |
|-------------------|--------|
| `src/models/` | Agregar 5 nuevos modelos de estrategia |
| `src/models/attention/` | Implementar Price-Focused Attention |
| `src/models/metamodel/` | Implementar Neural Gating Metamodel |
| `src/training/` | Agregar trainers por estrategia |
| `src/pipelines/` | Nuevo pipeline multi-estrategia |
| `src/api/` | Nuevos endpoints para predicciones ensemble |
| `config/` | Configuración por estrategia |
### 7.3 Documentación
| Archivo | Cambio |
|---------|--------|
| `docs/02-definicion-modulos/OQI-006-ml-signals/_MAP.md` | Actualizar con nuevas estrategias |
| `docs/02-definicion-modulos/OQI-006-ml-signals/README.md` | Documentar arquitectura ensemble |
| `docs/02-definicion-modulos/OQI-006-ml-signals/especificaciones/` | Nuevas specs técnicas |
| `orchestration/inventarios/ML_INVENTORY.yml` | NUEVO - inventario de modelos |
---
## 8. DEPENDENCIAS IDENTIFICADAS
### 8.1 Dependencias Técnicas
```yaml
dependencias_tecnicas:
python:
- torch>=2.0.0 # Para Transformers
- xgboost>=2.0.0 # Gradient Boosting
- hmmlearn>=0.3.0 # Hidden Markov Models
- torch-geometric>=2.4.0 # Graph Neural Networks (opcional)
- einops>=0.7.0 # Tensor operations
datos:
- Migración de datos históricos de WorkspaceOld (5.6 GB)
- Al menos 5 años de datos para entrenamiento robusto
infraestructura:
- GPU con 16GB+ VRAM (disponible)
- PostgreSQL con espacio para modelos serializados
```
### 8.2 Dependencias de Tareas
```yaml
orden_ejecucion:
fase_1_infraestructura:
- TASK-ML-DATA-PIPELINE # Migrar datos históricos
- TASK-ML-ATTENTION-ARCHITECTURE # Implementar attention base
fase_2_estrategias: # Pueden ejecutarse en paralelo
- TASK-ML-STRATEGY-1-PVA
- TASK-ML-STRATEGY-2-MRD
- TASK-ML-STRATEGY-3-VBP
- TASK-ML-STRATEGY-4-MSA
- TASK-ML-STRATEGY-5-MTS
fase_3_integracion:
- TASK-ML-METAMODEL-ENSEMBLE # Requiere fase 2 completa
- TASK-ML-LLM-INTEGRATION # Requiere metamodel
fase_4_validacion:
- TASK-ML-BACKTESTING-VALIDATION # Requiere todo lo anterior
```
---
## 9. RIESGOS IDENTIFICADOS
| ID | Riesgo | Probabilidad | Impacto | Mitigación |
|----|--------|--------------|---------|------------|
| R1 | Overfitting en modelos complejos | Alta | Alto | Walk-forward validation, regularization |
| R2 | Datos insuficientes para 5 estrategias | Media | Alto | Migrar datos históricos, data augmentation |
| R3 | Latencia excesiva en inference | Media | Medio | Batch prediction, model optimization |
| R4 | Conflicto entre estrategias | Alta | Medio | Gating network aprende a ponderar |
| R5 | LLM toma decisiones incorrectas | Media | Alto | Fine-tuning con feedback, safety limits |
| R6 | Régimen de mercado no visto | Baja | Alto | Ensemble diversificado, fallback rules |
---
## 10. ESTIMACIÓN DE RECURSOS
### 10.1 Cómputo
| Componente | GPU Hours | RAM | Storage |
|------------|-----------|-----|---------|
| Data Pipeline | 0 | 32GB | 10GB |
| PVA Training | 100h | 16GB | 2GB |
| MRD Training | 50h | 16GB | 2GB |
| VBP Training | 30h | 16GB | 1GB |
| MSA Training | 80h | 16GB | 2GB |
| MTS Training | 120h | 16GB | 3GB |
| Metamodel | 20h | 16GB | 1GB |
| Backtesting | 10h | 32GB | 5GB |
| **TOTAL** | **410h** | **32GB** | **26GB** |
### 10.2 Desarrollo (Story Points)
| Subtarea | SP |
|----------|-------|
| Data Pipeline | 8 |
| Attention Architecture | 13 |
| Strategy 1-5 (cada una) | 8 × 5 = 40 |
| Metamodel Ensemble | 13 |
| LLM Integration | 8 |
| Backtesting Validation | 8 |
| **TOTAL** | **90 SP** |
---
**Siguiente Fase:** 03-PLANEACION.md