- HERENCIA-SIMCO.md actualizado con directivas v3.7 y v3.8 - Agregados documentos de arquitectura y planes Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
244 lines
7.1 KiB
Markdown
244 lines
7.1 KiB
Markdown
# Reporte de Ejecucion Sprint 1
|
|
## Trading Platform - ML Engine Stabilization
|
|
|
|
**Fecha:** 2026-01-07
|
|
**Sprint:** 1 - Estabilizacion ML Engine
|
|
**Estado:** EN PROGRESO (Implementacion Completada, Pendiente Reentrenamiento)
|
|
**Ejecutor:** Claude Opus 4.5 (Technical Lead / ML-SPECIALIST)
|
|
|
|
---
|
|
|
|
## 1. RESUMEN EJECUTIVO
|
|
|
|
### 1.1 Objetivo del Sprint
|
|
Resolver los problemas criticos del ML Engine, especificamente el R^2 negativo en RangePredictor.
|
|
|
|
### 1.2 Estado de Tareas
|
|
|
|
| ID | Tarea | Estado | Cambios Realizados |
|
|
|----|-------|--------|-------------------|
|
|
| S1-T1 | Analizar features RangePredictor | COMPLETADO | Reporte creado |
|
|
| S1-T2 | Implementar normalizacion ATR | COMPLETADO | Codigo modificado |
|
|
| S1-T3 | Verificar data leakage | COMPLETADO | Verificado - OK |
|
|
| S1-T4a | Reducir sample weighting | COMPLETADO | Parametros ajustados |
|
|
| S1-T4b | Ajustar hiperparametros | COMPLETADO | XGBoost optimizado |
|
|
| S1-T5 | Auto-load modelos API | COMPLETADO | Servicio mejorado |
|
|
| S1-T6 | Reentrenar modelos | PENDIENTE | Requiere datos |
|
|
| S1-T7 | Validacion OOS | PENDIENTE | Post-reentrenamiento |
|
|
| S1-T8 | Tests unitarios | PENDIENTE | Proxima tarea |
|
|
|
|
---
|
|
|
|
## 2. CAMBIOS IMPLEMENTADOS
|
|
|
|
### 2.1 Normalizacion de Targets por ATR
|
|
|
|
**Archivo:** `apps/ml-engine/src/training/symbol_timeframe_trainer.py`
|
|
|
|
**Cambios:**
|
|
|
|
1. **Nuevo metodo `_compute_atr()`** (lineas 426-460)
|
|
- Calcula ATR con `shift(1)` para evitar data leakage
|
|
- Periodo configurable (default: 14)
|
|
|
|
```python
|
|
def _compute_atr(self, df: pd.DataFrame, period: int = 14) -> np.ndarray:
|
|
"""Compute ATR with shift(1) to avoid data leakage."""
|
|
# True Range calculation
|
|
tr1 = high - low
|
|
tr2 = abs(high - close.shift(1))
|
|
tr3 = abs(low - close.shift(1))
|
|
true_range = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
|
|
atr = true_range.rolling(period).mean().shift(1)
|
|
return atr.values
|
|
```
|
|
|
|
2. **Modificacion de `_compute_targets()`** (lineas 462-534)
|
|
- Ahora acepta parametro `normalize=True`
|
|
- Retorna targets normalizados por ATR
|
|
- Clip de valores extremos (±5 ATR)
|
|
|
|
```python
|
|
# Antes: target en USD (ej: 0.0005 para GBPUSD)
|
|
# Ahora: target en ATR multiples (ej: 1.2 ATR)
|
|
target_high_norm = target_high / atr_safe
|
|
target_low_norm = target_low / atr_safe
|
|
```
|
|
|
|
**Beneficio:** Targets ahora estan en escala [-5, 5] en lugar de [0, 0.001]
|
|
|
|
---
|
|
|
|
### 2.2 Reduccion de Agresividad de Sample Weighting
|
|
|
|
**Archivo:** `apps/ml-engine/src/training/symbol_timeframe_trainer.py`
|
|
|
|
**Cambios en TrainerConfig** (lineas 124-128):
|
|
|
|
| Parametro | Valor Anterior | Valor Nuevo | Razon |
|
|
|-----------|---------------|-------------|-------|
|
|
| `softplus_beta` | 4.0 | 2.0 | Menos agresivo |
|
|
| `softplus_w_max` | 3.0 | 2.0 | Cap mas bajo |
|
|
|
|
**Beneficio:**
|
|
- Mas samples incluidos en entrenamiento
|
|
- Menor sesgo hacia movimientos extremos
|
|
- Mejor generalizacion
|
|
|
|
---
|
|
|
|
### 2.3 Optimizacion de Hiperparametros XGBoost
|
|
|
|
**Archivo:** `apps/ml-engine/src/training/symbol_timeframe_trainer.py`
|
|
|
|
**Cambios en xgb_params** (lineas 109-122):
|
|
|
|
| Parametro | Anterior | Nuevo | Efecto |
|
|
|-----------|----------|-------|--------|
|
|
| `n_estimators` | 300 | 150 | Menos overfitting |
|
|
| `max_depth` | 6 | 4 | Arboles mas simples |
|
|
| `learning_rate` | 0.03 | 0.02 | Aprendizaje mas lento |
|
|
| `subsample` | 0.8 | 0.7 | Mas regularizacion |
|
|
| `colsample_bytree` | 0.8 | 0.7 | Menos features |
|
|
| `min_child_weight` | 10 | 20 | Hojas mas grandes |
|
|
| `gamma` | 0.1 | 0.3 | Mas poda |
|
|
| `reg_alpha` | 0.1 | 0.5 | L1 mas fuerte |
|
|
| `reg_lambda` | 1.0 | 5.0 | L2 mas fuerte |
|
|
|
|
**Beneficio:** Modelo mas robusto, menos propenso a overfitting
|
|
|
|
---
|
|
|
|
### 2.4 Mejora de Auto-Load de Modelos
|
|
|
|
**Archivo:** `apps/ml-engine/src/services/prediction_service.py`
|
|
|
|
**Cambios en `_load_symbol_trainers()`** (lineas 200-282):
|
|
|
|
1. **Busqueda en multiples directorios:**
|
|
- `models/symbol_timeframe_models/` (prioridad 1 - nuevos modelos)
|
|
- `models/ml_first/` (prioridad 2 - modelos legacy)
|
|
|
|
2. **Soporte para estructura plana y jerarquica:**
|
|
- Detecta automaticamente el tipo de estructura
|
|
- Carga metadata si existe
|
|
|
|
3. **Logging mejorado:**
|
|
- Indica de donde se cargaron los modelos
|
|
- Warnings si no hay modelos disponibles
|
|
|
|
**Beneficio:** API carga modelos automaticamente al iniciar
|
|
|
|
---
|
|
|
|
### 2.5 Actualizacion del Script de Entrenamiento
|
|
|
|
**Archivo:** `apps/ml-engine/scripts/train_symbol_timeframe_models.py`
|
|
|
|
**Cambios** (lineas 374-408):
|
|
- Parametros actualizados para consistencia
|
|
- Comentarios explicativos de las mejoras
|
|
|
|
---
|
|
|
|
## 3. ARCHIVOS MODIFICADOS
|
|
|
|
| Archivo | Lineas Modificadas | Tipo de Cambio |
|
|
|---------|-------------------|----------------|
|
|
| `src/training/symbol_timeframe_trainer.py` | ~150 lineas | Mejoras mayores |
|
|
| `src/services/prediction_service.py` | ~80 lineas | Mejora de carga |
|
|
| `scripts/train_symbol_timeframe_models.py` | ~40 lineas | Sincronizacion |
|
|
|
|
---
|
|
|
|
## 4. DOCUMENTACION CREADA
|
|
|
|
| Documento | Ubicacion | Proposito |
|
|
|-----------|-----------|-----------|
|
|
| REPORTE-ANALISIS-RANGEPREDICTOR-2026-01-07.md | orchestration/reportes/ | Root cause analysis |
|
|
| REPORTE-EJECUCION-SPRINT1-2026-01-07.md | orchestration/reportes/ | Este reporte |
|
|
|
|
---
|
|
|
|
## 5. PROXIMOS PASOS
|
|
|
|
### 5.1 Reentrenamiento de Modelos (S1-T6)
|
|
|
|
Para reentrenar los modelos con las nuevas correcciones:
|
|
|
|
```bash
|
|
cd /home/isem/workspace-v1/projects/trading-platform/apps/ml-engine
|
|
python scripts/train_symbol_timeframe_models.py \
|
|
--symbols XAUUSD,EURUSD,GBPUSD,BTCUSD \
|
|
--timeframes 5m,15m \
|
|
--use-attention
|
|
```
|
|
|
|
**Requisitos:**
|
|
- Base de datos MySQL con datos historicos
|
|
- Configuracion de conexion en `data_config.yaml`
|
|
|
|
### 5.2 Validacion OOS (S1-T7)
|
|
|
|
Despues del reentrenamiento, validar:
|
|
|
|
```bash
|
|
# Verificar metricas
|
|
python scripts/evaluate_models.py --holdout-only
|
|
|
|
# Criterios de exito:
|
|
# - R^2 > 0.05 (minimo aceptable)
|
|
# - R^2 > 0.15 (objetivo)
|
|
```
|
|
|
|
### 5.3 Tests Unitarios (S1-T8)
|
|
|
|
Crear tests para:
|
|
- Normalizacion de targets
|
|
- Calculo de ATR con shift
|
|
- Sample weighting
|
|
- Prediccion con modelos cargados
|
|
|
|
---
|
|
|
|
## 6. RIESGOS Y MITIGACION
|
|
|
|
| Riesgo | Estado | Mitigacion |
|
|
|--------|--------|-----------|
|
|
| R^2 sigue negativo | Pendiente verificacion | Plan B: modelo baseline |
|
|
| Datos no disponibles | Posible | Mock data para tests |
|
|
| Integracion con API | Mitigado | Auto-load implementado |
|
|
|
|
---
|
|
|
|
## 7. METRICAS ESPERADAS POST-REENTRENAMIENTO
|
|
|
|
| Metrica | Valor Actual | Minimo | Objetivo |
|
|
|---------|--------------|--------|----------|
|
|
| RangePredictor R^2 | -0.65 | > 0.05 | > 0.15 |
|
|
| MAE (ATR normalizado) | N/A | < 0.5 | < 0.3 |
|
|
| Direction Accuracy | 98% | > 60% | > 65% |
|
|
| Win Rate Backtest | 42% | > 50% | > 55% |
|
|
|
|
---
|
|
|
|
## 8. CONCLUSION
|
|
|
|
Sprint 1 ha completado la implementacion de todas las correcciones identificadas:
|
|
|
|
1. **Normalizacion de targets** - Implementada con ATR shift(1)
|
|
2. **Sample weighting** - Reducida agresividad
|
|
3. **Hiperparametros** - Optimizados para regularizacion
|
|
4. **Auto-load** - Mejorado para multiples directorios
|
|
|
|
**Estado:** LISTO PARA REENTRENAMIENTO
|
|
|
|
El siguiente paso critico es ejecutar el reentrenamiento y validar que R^2 sea positivo.
|
|
|
|
---
|
|
|
|
**Reporte generado:** 2026-01-07
|
|
**Autor:** Claude Opus 4.5 (Technical Lead)
|
|
**Siguiente paso:** Ejecutar reentrenamiento de modelos
|
|
|