trading-platform/docs/02-definicion-modulos/OQI-006-ml-signals/_MAP.md
Adrian Flores Cortes f1174723ed feat: Add comprehensive analysis and integration plan for trading-platform
- Created TASK-2026-01-26-ANALYSIS-INTEGRATION-PLAN with complete CAPVED documentation
- Orchestrated 5 specialized Explore agents in parallel (85% time reduction)
- Identified 7 coherence gaps (DDL↔Backend↔Frontend)
- Identified 4 P0 blockers preventing GO-LIVE
- Documented 58 missing documentation items
- Created detailed roadmap Q1-Q4 2026 (2,500h total)
- Added 6 new ET specs for ML strategies (PVA, MRD, VBP, MSA, MTS, Backtesting)
- Updated _INDEX.yml with new analysis task

Hallazgos críticos:
- E-COH-001 to E-COH-007: Coherence gaps (6.5h to fix)
- BLOCKER-001 to 004: Token refresh, PCI-DSS, Video upload, MT4 Gateway (380h)
- Documentation gaps: 8 ET specs, 8 US, 34 Swagger docs (47.5h)

Roadmap phases:
- Q1: Security & Blockers (249h)
- Q2: Core Features + GO-LIVE (542h)
- Q3: Scalability & Performance (380h)
- Q4: Innovation & Advanced Features (1,514h)

ROI: $223k investment → $750k revenue → $468k net profit (165% ROI)

Next: Execute ST1 (Coherencia Fixes P0)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 16:40:56 -06:00

364 lines
13 KiB
Markdown

---
id: "MAP-OQI-006-ml-signals"
title: "Mapa de OQI-006-ml-signals"
type: "Index"
project: "trading-platform"
updated_date: "2026-01-25"
---
# _MAP: OQI-006 - Senales ML
**Ultima actualizacion:** 2026-01-25
**Estado:** Implementado (Multi-Strategy Ensemble)
**Version:** 3.0.0
---
## Propósito
Esta épica implementa el sistema de predicciones y señales de trading basado en Machine Learning, utilizando modelos XGBoost para predecir rangos de precio y generar señales de entrada/salida.
---
## Contenido del Directorio
```
OQI-006-ml-signals/
├── README.md # Documentación técnica existente
├── _MAP.md # Este archivo - índice
├── requerimientos/ # Documentos de requerimientos funcionales
│ ├── RF-ML-001-predicciones.md # Predicción de precios
│ ├── RF-ML-002-senales.md # Generación de señales
│ ├── RF-ML-003-indicadores.md # Indicadores técnicos
│ ├── RF-ML-004-entrenamiento.md # Pipeline de entrenamiento
│ └── RF-ML-005-notificaciones.md # Alertas de señales
├── especificaciones/ # Especificaciones técnicas
│ ├── ET-ML-001-arquitectura.md # Arquitectura ML
│ ├── ET-ML-002-modelos.md # Modelos XGBoost
│ ├── ET-ML-003-features.md # Feature engineering
│ ├── ET-ML-004-api.md # FastAPI endpoints
│ ├── ET-ML-005-integracion.md # Integración con backend
│ ├── ET-ML-006-enhanced-range-predictor.md # Enhanced Range Predictor
│ └── ET-ML-007-hierarchical-attention.md # Hierarchical Attention Architecture (Nivel 0-1-2)
├── historias-usuario/ # User Stories (5 prioritarias documentadas)
│ ├── US-ML-001-ver-prediccion.md # ✅ P0 - 5 SP
│ ├── US-ML-002-ver-senal.md # ✅ P0 - 5 SP
│ ├── US-ML-004-ver-accuracy.md # ✅ P1 - 3 SP
│ ├── US-ML-006-senal-en-chart.md # ✅ P0 - 5 SP
│ └── US-ML-007-historial-senales.md # ✅ P1 - 3 SP
└── implementacion/ # Trazabilidad de implementación
├── TRACEABILITY.yml
└── PLAN-ENHANCED-RANGE-PREDICTOR.md # ✅ NEW - Plan de ejecución
```
---
## Requerimientos Funcionales
| ID | Nombre | Prioridad | SP | Estado |
|----|--------|-----------|-----|--------|
| RF-ML-001 | Predicción de Precios | P0 | 10 | ✅ Implementado + Documentado |
| RF-ML-002 | Generación de Señales | P0 | 10 | ✅ Implementado + Documentado |
| RF-ML-003 | Indicadores Técnicos | P1 | 5 | ✅ Implementado + Documentado |
| RF-ML-004 | Pipeline de Entrenamiento | P1 | 8 | ✅ Implementado + Documentado |
| RF-ML-005 | Alertas de Señales | P2 | 7 | ✅ Documentado |
**Total:** 40 SP (100% documentados)
---
## Especificaciones Técnicas
| ID | Nombre | Componente | Estado |
|----|--------|------------|--------|
| ET-ML-001 | Arquitectura | ML Engine | Documentado |
| ET-ML-002 | Modelos XGBoost | ML Engine | Documentado |
| ET-ML-003 | Feature Engineering | ML Engine | Documentado |
| ET-ML-004 | FastAPI Endpoints | FastAPI | Documentado |
| ET-ML-005 | Integracion Backend | Backend | Documentado |
| ET-ML-006 | Enhanced Range Predictor | ML Engine | Documentado + Implementado |
| ET-ML-007 | Hierarchical Attention Architecture | ML Engine | Documentado + Implementado |
| ET-ML-008 | Frontend Components | Frontend | Documentado |
| ET-ML-008-ict | ICT Analysis Card | Frontend | Documentado |
| ET-ML-009 | Multi-Strategy Ensemble | ML Engine | **Documentado + Implementado** |
| ET-ML-009-ensemble | Ensemble Signal | ML Engine | Documentado |
| ET-ML-010 | PVA Strategy (Transformer+XGBoost) | ML Engine | **Documentado + Implementado** |
| ET-ML-011 | MRD Strategy (HMM+LSTM+XGBoost) | ML Engine | **Documentado + Implementado** |
| ET-ML-012 | VBP Strategy (CNN+Attention+XGBoost) | ML Engine | **Documentado + Implementado** |
| ET-ML-013 | MSA Strategy (Market Structure) | ML Engine | **Documentado + Implementado** |
| ET-ML-014 | MTS Strategy (Hierarchical Attention) | ML Engine | **Documentado + Implementado** |
| ET-ML-015 | Backtesting Framework | ML Engine | **Documentado + Implementado** |
**Total:** 17 ET (100% documentados, 11 implementados)
### Especificaciones de Estrategias ML (TASK-2026-01-25-ML-TRAINING-ENHANCEMENT)
Las especificaciones ET-ML-010 a ET-ML-015 fueron creadas como parte de la mejora integral de modelos ML:
| Estrategia | Arquitectura | Objetivo | Archivos |
|------------|--------------|----------|----------|
| **PVA** | Transformer (4 layers) + XGBoost | Price variation time-agnostic | `strategies/pva/` |
| **MRD** | HMM (3 states) + LSTM + XGBoost | Regime detection | `strategies/mrd/` |
| **VBP** | CNN 1D + Attention + XGBoost | Volatility breakout | `strategies/vbp/` |
| **MSA** | XGBoost (ICT/SMC) | Market structure | `strategies/msa/` |
| **MTS** | Hierarchical Attention Network | Multi-timeframe synthesis | `strategies/mts/` |
**Neural Gating Metamodel:** Combina las 5 estrategias con pesos dinámicos.
**Objetivo:** 80% de efectividad en operaciones.
---
## Historias de Usuario
### Historias Prioritarias (Documentadas)
| ID | Historia | Prioridad | SP | Estado |
|----|----------|-----------|-----|--------|
| US-ML-001 | Ver predicción de precio | P0 | 5 | ✅ Documentado |
| US-ML-002 | Ver señal de trading | P0 | 5 | ✅ Documentado |
| US-ML-004 | Ver accuracy del modelo | P1 | 3 | ✅ Documentado |
| US-ML-006 | Ver señal en el chart | P0 | 5 | ✅ Documentado |
| US-ML-007 | Ver historial de señales | P1 | 3 | ✅ Documentado |
**Subtotal:** 21 SP documentados
### Historias Adicionales (Pendientes)
| ID | Historia | Prioridad | SP | Estado |
|----|----------|-----------|-----|--------|
| US-ML-003 | Configurar alertas de señales | P1 | 3 | Pendiente |
| US-ML-005 | Ver indicadores técnicos | P1 | 3 | Pendiente |
| US-ML-008 | Filtrar por confianza | P2 | 2 | Pendiente |
| US-ML-009 | Exportar señales a CSV | P2 | 2 | Pendiente |
| US-ML-010 | Recibir notificación push | P2 | 5 | Pendiente |
**Total:** 40 SP (21 documentados + 19 restantes)
---
## Modelos Implementados
### Hierarchical Attention Architecture (NEW - 2026-01-07)
- **Arquitectura:** 3 niveles jerarquicos
- **Nivel 0 - AttentionScoreModel:**
- Algoritmo: XGBoost dual (regresion + clasificacion)
- Features: 9 (volume_ratio, volume_z, ATR, ATR_ratio, CMF, MFI, OBV_delta, BB_width, displacement)
- Output: attention_score (0-3) + attention_class (low/medium/high)
- Target: move_multiplier = future_range / rolling_median(range)
- Estado: **Implementado**
- **Nivel 1 - SymbolTimeframeModel:**
- Modelos base con attention features (52 features = 50 base + 2 attention)
- Estado: **Implementado**
- **Nivel 2 - AssetMetamodel:**
- Sintetiza predicciones de 5m y 15m
- Estado: **Pendiente**
- **Archivos:**
- `src/models/attention_score_model.py`
- `src/training/attention_trainer.py`
- `src/training/symbol_timeframe_trainer.py` (modificado)
- `scripts/train_attention_model.py`
- `scripts/train_symbol_timeframe_models.py` (modificado)
### EnhancedRangePredictor (2026-01-05)
- **Algoritmo:** Dual Horizon XGBoost Ensemble
- **Predice:** ΔHigh/ΔLow en múltiplos de factor base (5 USD para XAUUSD)
- **Features:** ~40 (volatilidad, momentum, sesión, ATR)
- **Arquitectura:**
- Modelo largo plazo (5 años): patrones estructurales
- Modelo corto plazo (3 meses): adaptación a régimen actual
- **Atención:** Pesos por sesión (London/NY overlap 2x) + ATR
- **Filtro:** R:R ratio mínimo 2:1
- **Archivos:**
- `src/data/corrected_targets.py`
- `src/training/sample_weighting.py`
- `src/training/session_volatility_weighting.py`
- `src/models/dual_horizon_ensemble.py`
- `src/models/enhanced_range_predictor.py`
- `scripts/train_enhanced_model.py`
### RangePredictor (v2.0 - Enhanced 2026-01-05)
- **Algoritmo:** XGBoost Regressor
- **Predice:** ΔHigh/ΔLow (rango de precio)
- **Features:** 21 + session features
- **Accuracy:** MAE 0.1% - 2%
- **v2.0 Mejoras:**
- Sample weighting por magnitud de movimiento
- Session weighting (London/NY overlap prioritarios)
- ATR-based volatility weighting
- Enhanced session features (cyclical encoding)
### MovementMagnitudePredictor (v2.0 - Enhanced 2026-01-05)
- **Algoritmo:** XGBoost Regressor (dual HIGH/LOW)
- **Predice:** Magnitud de movimiento en USD
- **Features:** ~50 (range, momentum, volatility, session)
- **v2.0 Mejoras:**
- Sample weighting integrado
- Session/volatility weighting
- Asymmetry-based opportunity detection
### AMDDetectorML (v2.0 - Enhanced 2026-01-05)
- **Algoritmo:** XGBoost Classifier (multi-class)
- **Predice:** Fase AMD (Accumulation, Manipulation, Distribution)
- **Features:** ~40 (volume, price action, structure, order flow)
- **v2.0 Mejoras:**
- Sample weighting por movimiento forward
- Session weighting integrado
- Enhanced session features
### TPSLClassifier
- **Algoritmo:** XGBoost Classifier
- **Predice:** Take Profit vs Stop Loss primero
- **Features:** 15
- **Accuracy:** 68%
### SignalGenerator
- **Algoritmo:** Ensemble
- **Predice:** Señales de entrada (buy/sell/hold)
- **Features:** 21
- **Accuracy:** 65%
---
## Módulos de Ponderación (v2.0)
Módulos compartidos para atención/weighting en todos los modelos:
### sample_weighting.py
- **Ubicación:** `src/training/sample_weighting.py`
- **Propósito:** Ponderar muestras por magnitud de movimiento
- **Configuración:**
- `min_movement_threshold`: Umbral mínimo en USD
- `large_movement_weight`: Peso para movimientos grandes (3.0x)
- `small_movement_weight`: Peso para movimientos pequeños (0.3x)
- `use_continuous_weighting`: Ponderación continua vs binaria
- `min_rr_ratio`: R:R mínimo para validez
### session_volatility_weighting.py
- **Ubicación:** `src/training/session_volatility_weighting.py`
- **Propósito:** Ponderar muestras por volatilidad (ATR)
- **Configuración por defecto:**
- `use_session_weighting: False` (deshabilitado - no pesos por hora)
- `use_atr_weighting: True` (habilitado)
- **Volatilidad (ATR) - ACTIVO:**
| Condición | Peso |
|-----------|------|
| ATR > P75 (alta volatilidad) | 1.5x |
| ATR < P25 (lateral/consolidación) | 0.3x |
| Normal | 1.0x |
- **Sesiones (DESHABILITADO por defecto):**
- Pesos por hora de sesión están deshabilitados
- Se pueden habilitar con `use_session_weighting=True` si se desea
---
## Features Implementadas
### Volatilidad
- `volatility_5`, `volatility_10`, `volatility_20`, `volatility_50`
- `atr_5`, `atr_10`, `atr_20`, `atr_50`
### Momentum
- `momentum_5`, `momentum_10`, `momentum_20`
- `roc_5`, `roc_10`, `roc_20`
### Medias Móviles
- `sma_5`, `sma_10`, `sma_20`, `sma_50`
- `ema_5`, `ema_10`, `ema_20`, `ema_50`
- `sma_ratio_*`
### Indicadores
- `rsi_14` - Relative Strength Index
- `macd`, `macd_signal`, `macd_histogram`
- `bb_position` - Bollinger Bands
---
## Horizontes de Predicción
| Horizonte | Candles (5min) | Tiempo | Uso |
|-----------|----------------|--------|-----|
| Scalping | 6 | 30 min | Trading rápido |
| Intraday | 18 | 90 min | Day trading |
| Swing | 36 | 3 horas | Swing trading |
| Position | 72 | 6 horas | Posiciones largas |
---
## Dependencias
### Depende de:
- **OQI-001:** Autenticación - Completado
- **OQI-003:** Trading/Charts - Para mostrar señales
### Bloquea:
- **OQI-004:** Investment (agentes usan señales)
---
## Stack Técnico
| Capa | Tecnología | Uso |
|------|------------|-----|
| ML Engine | Python 3.11 + FastAPI | API de predicciones |
| Models | XGBoost 2.x | Algoritmos ML |
| Data | Pandas + NumPy | Procesamiento |
| Market Data | Binance API | Datos en tiempo real |
---
## Límites por Plan
| Plan | Señales/día | Horizontes | Símbolos |
|------|-------------|------------|----------|
| Free | 3 | Scalping | BTCUSDT |
| Basic | 10 | Scalping, Intraday | BTC, ETH |
| Pro | Ilimitado | Todos | Todos |
| Premium | Ilimitado + API | Todos + Custom | Todos |
---
## Criterios de Aceptación
### Funcionales
- [ ] Predicciones disponibles para BTCUSDT y ETHUSDT
- [ ] 4 horizontes temporales funcionando
- [ ] Señales con nivel de confianza
- [ ] Indicadores técnicos en tiempo real
- [ ] Alertas configurables por usuario
- [ ] Señales mostradas en charts
### No Funcionales
- [ ] Predicción en < 500ms
- [ ] Entrenamiento automático diario
- [ ] 99.5% uptime del ML Engine
### Técnicos
- [ ] Cobertura de tests > 70%
- [ ] Métricas de accuracy en dashboard admin
- [ ] Logs de predicciones para auditoría
---
## Hitos
| Hito | Entregables | Target |
|------|-------------|--------|
| M1 | ML Engine funcionando | Sprint 7 ✅ |
| M2 | Integración con backend | Sprint 7 |
| M3 | Señales en charts | Sprint 8 |
| M4 | Alertas + notificaciones | Sprint 8 |
---
## Referencias
- [README Técnico](./README.md)
- [Vision del Producto](../../00-vision-general/VISION-PRODUCTO.md)
- [_MAP Fase MVP](../_MAP.md)
- [ML Engine Config](../../../../apps/ml-engine/config/)