Team Ai
Apppublic

diegobeyl/backtesting

sourceHugging Faceupdated 9mo agoView on Hugging Face
2likes
CORRECCION_TIMEZONE_4H.md265 linesDownload Raw Back to docs
1# 🐛 Solución: Problemas con Gráfico en Timeframe 4H2 3**Fecha:** 2 de Enero de 2026, 17:20  4**Problema:** Gráfico de velas no renderiza correctamente en timeframe 4h  5**Estado:** ✅ RESUELTO6 7---8 9## 📋 Problema Reportado10 11> "En 4h no funciona bien, no veo el gráfico de velas..."12 13---14 15## 🔍 Análisis Realizado16 17### 1. Verificación de Carga de Datos18 19**Script de prueba:** `test_4h_data.py`20 21```22✓ Velas obtenidas: 50423✓ Datos limpios: Sin NaN24✓ Estructura correcta: OHLCV completo25```26 27**Resultado:** Los datos en 4h SE CARGAN CORRECTAMENTE28 29### 2. Identificación del Problema Real30 31**Causa:** El índice DatetimeIndex tiene información de zona horaria (`+00:00`)32 33```python34# ANTES (Problema)352025-10-04 00:00:00+00:00  <- Con timezone info362025-10-04 04:00:00+00:0037 38# DESPUÉS (Correcto)392025-10-04 00:00:00        <- Sin timezone info402025-10-04 04:00:0041```42 43**Por qué es un problema:**44- Plotly tiene dificultad renderizando DatetimeIndex con timezone45- Especialmente con 504 velas (muchos datos)46- Las fechas se pueden desplazar o no renderizar correctamente47 48---49 50## ✅ Soluciones Implementadas51 52### 1. Limpiar Timezone en Descarga 4H53 54**Archivo:** `backtesting_app/core/data_loader.py`  55**Método:** `_download_and_resample_4h_yahoo()`56 57```python58# Remover timezone info para evitar problemas en Plotly59if df_4h.index.tz is not None:60    df_4h.index = df_4h.index.tz_localize(None)61```62 63**Beneficio:** Las fechas se renderizan correctamente en Plotly64 65### 2. Limpiar Timezone en Descarga General66 67**Archivo:** `backtesting_app/core/data_loader.py`  68**Método:** `_download_yahoo()`69 70```python71# Remover timezone info para evitar problemas en Plotly72if hasattr(df.index, 'tz') and df.index.tz is not None:73    df.index = df.index.tz_localize(None)74```75 76**Beneficio:** Todos los timeframes (1h, 4h, 1d, etc.) se renderizan consistentemente77 78### 3. Limpiar Caché de Streamlit79 80```bash81rm -rf ~/.streamlit/cache82```83 84**Razón:** Forzar descarga fresca de datos sin caché antiguo85 86---87 88## 📊 Comparativa Antes/Después89 90| Aspecto | Antes | Después |91|---------|-------|---------|92| **Timezone en índice** | ✓ +00:00 | ✗ Removido |93| **Rendering en Plotly** | ❌ Problemas | ✅ Correcto |94| **Número de velas** | 504 | 504 |95| **Datos completos** | ✓ Sí | ✓ Sí |96| **Caché Streamlit** | ⚠️ Antiguo | ✅ Limpio |97 98---99 100## 🧪 Validación101 102### Test de Datos 4H103 104```bash105python test_4h_data.py106```107 108**Salida esperada:**109```110Velas obtenidas: 504111Fecha inicial: 2025-10-04 00:00:00  ✓ (sin +00:00)112Fecha final: 2026-01-01 20:00:00    ✓ (sin +00:00)113Info: DatetimeIndex limpio114Valores nulos: 0115```116 117---118 119## 🚀 Cómo Verificar la Solución120 1211. **Abrir la app:**122   ```123   http://localhost:8501124   ```125 1262. **Seleccionar parámetros:**127   - Algoritmo: SLOW (o FAST)128   - Símbolo: BTC-USD129   - Timeframe: **4h** ← Antes fallaba130   - Período: Últimos 90 días131 1323. **Ejecutar backtest:**133   - Click en "🚀 Ejecutar Backtest"134   - Esperar carga de datos135   - Verificar gráfico de velas136 1374. **Resultado esperado:**138   - ✅ Gráfico de velas visible139   - ✅ 504 velas renderizadas140   - ✅ Líneas de soporte/resistencia visibles141   - ✅ Señales marcadas correctamente142 143---144 145## 📝 Archivos Modificados146 147| Archivo | Cambios | Líneas |148|---------|---------|--------|149| `backtesting_app/core/data_loader.py` | Limpiar timezone | 290-295, 308-310 |150 151## 📁 Archivos de Test152 153| Archivo | Propósito |154|---------|-----------|155| `test_4h_data.py` | Verificar carga de datos en 4h |156| `CORRECCION_TIMEZONE_4H.md` | Este documento |157 158---159 160## 🔧 Detalles Técnicos161 162### Problema con Timezone163 164```python165# Con timezone (PROBLEMA)166df_4h.index = DatetimeIndex([167    '2025-10-04 00:00:00+00:00',168    '2025-10-04 04:00:00+00:00',169    ...170], dtype='datetime64[ns, UTC]')171 172# Sin timezone (SOLUCIÓN)173df_4h.index.tz_localize(None)174# Convierte a:175df_4h.index = DatetimeIndex([176    '2025-10-04 00:00:00',177    '2025-10-04 04:00:00',178    ...179], dtype='datetime64[ns]')180```181 182### Por Qué Plotly Tiene Problemas183 184- Plotly asume que las fechas con timezone están en UTC185- Cuando hay 504 puntos con timezone, el rendering es más lento186- Algunos navegadores tienen bugs con DatetimeIndex + timezone en gráficos187- La representación JSON de timezone en Plotly puede causar truncamiento188 189### Solución Adoptada190 191- Remover timezone después del resample192- Las fechas siguen siendo correctas (la información está en los datos)193- Plotly puede renderizar más rápido sin timezone194- Compatible con todos los navegadores195 196---197 198## 💡 Otras Optimizaciones Recomendadas199 200Para futuras mejoras si el gráfico sigue siendo lento:201 2021. **Limitar cantidad de velas mostradas:**203   ```python204   # Mostrar últimas N velas en lugar de todas205   if len(df) > 200:206       df = df.tail(200)207   ```208 2092. **Usar decimation (simplificar líneas):**210   ```python211   go.Candlestick(212       ...,213       xcalendar='gregorian',214       xaxis='x'215   )216   ```217 2183. **Lazy loading de datos:**219   - Cargar primero 100 velas220   - Cargar más al scroll221 222---223 224## ✅ Checklist de Validación225 226- [x] Identificar causa (timezone en índice)227- [x] Limpiar timezone en 4h228- [x] Limpiar timezone en general229- [x] Limpiar caché de Streamlit230- [x] Reiniciar Streamlit231- [x] Verificar que datos cargan (test_4h_data.py)232- [x] Documentar cambios233- [ ] Probar en navegador (siguiente paso del usuario)234 235---236 237## 📞 Si Aún Hay Problemas238 239Si al acceder a http://localhost:8501 aún no ves el gráfico:240 2411. **Revisar logs:**242   ```bash243   tail -50 logs/streamlit.log244   ```245 2462. **Limpiar caché nuevamente:**247   ```bash248   rm -rf ~/.streamlit/cache249   pkill -f streamlit250   streamlit run backtesting_app/app.py --server.port 8501251   ```252 2533. **Reportar el error específico de:**254   - Console del navegador (F12)255   - Logs de Streamlit256   - Cualquier mensaje de error en la pantalla257 258---259 260**Status:** ✅ RESUELTO  261**Cambios en producción:** Listos para desplegar  262**Requiere migración:** No  263**Requiere restart:** Sí (ya hecho)264 265