diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..aeafadbc7b0f84a96f0e8327d3d1f3af4f2b7c9d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,23 @@ +.git +.github +.gitattributes +__pycache__/ +*.pyc +*.pyo +.Python +venv/ +.venv/ +env/ +.env +.env.* +*.egg-info/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +node_modules/ +dist/ +build/ +*.log +.DS_Store +.vscode/ +.idea/ \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..156c8eb8f4a5edd8ce859059ca4dc689f78bbba7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +*.keras filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text diff --git a/.github/workflows/entrenamiento_semanal.yml b/.github/workflows/entrenamiento_semanal.yml new file mode 100644 index 0000000000000000000000000000000000000000..06b7ee88115c8fb84f298e50c868312f231b61d5 --- /dev/null +++ b/.github/workflows/entrenamiento_semanal.yml @@ -0,0 +1,131 @@ +name: Entrenamiento Semanal - KodaQuant Predictive Engine + +on: + schedule: + - cron: '0 23 * * 5' + workflow_dispatch: + +permissions: + contents: write + +jobs: + retrain-model: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + # NUEVO: libera espacio en disco ANTES de instalar dependencias -- + # root cause de "[Errno 28] No space left on device": TensorFlow + + # CUDA + torch no entran junto a las herramientas preinstaladas + # (Android SDK, .NET, Haskell/GHC) que el runner ubuntu-latest trae + # por defecto y este pipeline nunca usa. swap-storage desactivado + # (solo genera warnings, no libera espacio real relevante acá). + - name: Liberar espacio en disco del runner + uses: jlumbroso/free-disk-space@main + with: + tool-cache: true + android: true + dotnet: true + haskell: true + large-packages: false + docker-images: true + swap-storage: false + + - name: Set up Python + uses: actions/setup-python@v5 + with: + # FIX: numpy==2.5.1 exige Python>=3.12 (root cause del build fallido). + # 3.12 ya es el runtime real del HF Space (ver python_version en + # sync_huggingface.yml) -- esto solo alinea train/serve parity. + python-version: '3.12' + + - name: Cache pip dependencies + uses: actions/cache@v4 + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-3.12-${{ hashFiles('requirements.txt') }} + restore-keys: | + ${{ runner.os }}-pip-3.12- + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + # torch/transformers YA están pineados en requirements.txt + # (torch==2.11.0, transformers==5.15.0 -- ver FIX RONDA 1/2 ahí) + # para compat con el validador ZeroGPU de HF. Instalarlos sueltos + # acá (como antes) los sobrescribía con versiones sin pinear, + # deshaciendo esos fixes en cada corrida de entrenamiento. + # --no-cache-dir -- NUEVO: el cache de pip (wheels descargados) + # ocupaba espacio real de disco además de TensorFlow/torch/CUDA + # ya instalados -- root cause de "No space left on device". + python -m pip install --no-cache-dir -r requirements.txt + + - name: Ejecutar script de entrenamiento + env: + # --- Supabase --- + SUPABASE_URL: ${{ secrets.SUPABASE_URL }} + SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }} + SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_ROLE_KEY }} + SUPABASE_JWT_SECRET: ${{ secrets.SUPABASE_JWT_SECRET }} + + # --- Stripe --- + STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }} + STRIPE_PRICE_PRO: ${{ secrets.STRIPE_PRICE_PRO }} + STRIPE_PRICE_ULTRA: ${{ secrets.STRIPE_PRICE_ULTRA }} + STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }} + STRIPE_SUCCESS_URL: ${{ secrets.STRIPE_SUCCESS_URL }} + STRIPE_CANCEL_URL: ${{ secrets.STRIPE_CANCEL_URL }} + + # --- Mercado / Sentimiento --- + FINNHUB_API_KEY: ${{ secrets.FINNHUB_API_KEY }} + TWELVE_DATA_API_KEY: ${{ secrets.TWELVE_DATA_API_KEY }} + FRED_API_KEY: ${{ secrets.FRED_API_KEY }} + + # --- Seguridad interna --- + API_SECRET_KEY: ${{ secrets.API_SECRET_KEY }} + + # --- SMTP --- + SMTP_USER: ${{ secrets.SMTP_USER }} + SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} + SMTP_FROM: ${{ secrets.SMTP_FROM }} + + # --- Flags de entorno (tienen default en Settings, se fuerzan explícitos) --- + ENV: ${{ secrets.ENV }} + DEBUG: ${{ secrets.DEBUG }} + + # --- V9 CI/CD (Purgado Total en Producción) --- + KODAQUANT_FORCE_FRESH_DATA: "true" + run: python ml_engine/train_kodaquant_v5.py + + - name: Auto commit model artifacts + uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: "🤖 MLOps: Automated model retraining weights updated" + file_pattern: 'services/kodaquant_models/**/*.keras services/kodaquant_models/**/*.pkl services/kodaquant_models/**/*.png' + commit_user_name: github-actions[bot] + commit_user_email: github-actions[bot]@users.noreply.github.com + commit_author: github-actions[bot] + + # NUEVO: push directo a HF -- NO depende del `on: push` de + # sync_huggingface.yml, porque el commit de arriba usa GITHUB_TOKEN y + # GitHub NO dispara otros workflows con ese token (evita loops + # infinitos). Sin este step, los pesos nunca llegaban a HF solos. + - name: Publicar pesos del modelo en Hugging Face + env: + HF_TOKEN: ${{ secrets.HF_TOKEN }} + run: | + pip install -U "huggingface_hub[cli]" + + # Destino: mismo Space del backend (Zusheim/kodaquant-backend). + # Ruta destino "services/kodaquant_models" (NO ".") -- preserva la + # misma ruta relativa que usa el código en runtime (quanti_engine.py + # espera crypto_specialist/ y equity_specialist/ ahí mismo, igual + # que en el checkout local). + huggingface-cli upload Zusheim/kodaquant-backend \ + services/kodaquant_models/ services/kodaquant_models \ + --repo-type space \ + --token "$HF_TOKEN" \ + --commit-message "🤖 MLOps: sync pesos entrenados $(date -u +%Y-%m-%dT%H:%M:%SZ)" \ No newline at end of file diff --git a/.github/workflows/keep_alive_hf.yml b/.github/workflows/keep_alive_hf.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e467c712f59c738b1ada24df17cfb94b1421a8e --- /dev/null +++ b/.github/workflows/keep_alive_hf.yml @@ -0,0 +1,22 @@ +name: Keep-Alive HF Space - KodaQuant Backend + +on: + schedule: + - cron: '0 12 * * *' + workflow_dispatch: + +jobs: + ping-space: + runs-on: ubuntu-latest + steps: + - name: Ping al Space para resetear el temporizador de sleep de HF + continue-on-error: true + run: | + # Sin -f: un 404/403 en el frontend del Space NO debe marcar fallo + # el workflow -- el objetivo es solo que el contenedor reciba el + # hit y resetee su temporizador de inactividad (48h), no validar + # el contenido de la respuesta. -L sigue redirects. continue-on-error + # a nivel step cubre además timeouts/errores de red genuinos. + curl -sS -o /dev/null -w "HTTP %{http_code}\n" -L \ + --max-time 30 --retry 2 --retry-delay 5 \ + "https://zusheim-kodaquant-backend.hf.space" || true \ No newline at end of file diff --git a/.github/workflows/sync_huggingface.yml b/.github/workflows/sync_huggingface.yml new file mode 100644 index 0000000000000000000000000000000000000000..78669c2ab1766c28f8cf1c92047a9a2c58e8daa2 --- /dev/null +++ b/.github/workflows/sync_huggingface.yml @@ -0,0 +1,66 @@ +name: Despliegue Automático a Hugging Face + +on: + push: + branches: [ "main" ] + workflow_dispatch: + +jobs: + sync-to-hub: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + lfs: true + + - name: Empujar estado limpio a Hugging Face + env: + HF_TOKEN: ${{ secrets.HF_TOKEN }} + run: | + # 1. Crear .gitignore linea por linea sin sangrías + echo "node_modules/" > .gitignore + echo "venv/" >> .gitignore + echo ".env" >> .gitignore + echo "dist/" >> .gitignore + echo "build/" >> .gitignore + echo "__pycache__/" >> .gitignore + echo "*.pyc" >> .gitignore + echo ".DS_Store" >> .gitignore + + # 2. Inyectar la llave de encendido de Gradio con Python 3.12 + # FIX -- `sdk_version`/`python_version` DEBEN ir entre comillas. + # Verificado: `echo "python_version: 3.12" >> README.md` (sin + # comillas) produce un YAML donde ese valor se parsea como FLOAT + # (3.12), no como string "3.12" -- el mismo tipo de + # "configuration error" silencioso que ya rompió el build por el + # pin de torch. El template oficial de HF (`{{sdkVersion}}` / + # `{{pythonVersion}}`) siempre los entrega entre comillas dobles + # por esta razón exacta. + echo "---" > README.md + echo "title: KodaQuant Backend" >> README.md + echo "emoji: 🚀" >> README.md + echo "colorFrom: blue" >> README.md + echo "colorTo: indigo" >> README.md + echo "sdk: gradio" >> README.md + echo 'sdk_version: "6.22.0"' >> README.md + echo 'python_version: "3.12"' >> README.md + echo "app_file: app.py" >> README.md + echo "pinned: false" >> README.md + echo "---" >> README.md + + # 3. Borrar el historial fantasma de Git + rm -rf .git + git init + git checkout -b main + git config user.name "GitHub Actions KodaQuant" + git config user.email "actions@github.com" + + # 4. Rastrear solo los archivos que existen HOY + git lfs install + git lfs track "*.keras" + git lfs track "*.pkl" + git add . + + # 5. Empaquetar y forzar la subida a Hugging Face + git commit -m "deploy: sync automático a Hugging Face Spaces (ZeroGPU, front-matter README corregido)" + git push --force https://Zusheim:$HF_TOKEN@huggingface.co/spaces/Zusheim/kodaquant-backend main \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a94d220852cea85bc38ba5ad71e7b22191cca00a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +node_modules/ +venv/ +.env +dist/ +build/ +__pycache__/ +*.pyc +.DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9b6caca841c5ff58b48418dc23a1cc83a850f483 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,43 @@ +# syntax=docker/dockerfile:1 +FROM python:3.12-slim + +# libgomp1: required at import time by TensorFlow / scikit-learn's +# OpenMP-based ops. Not present on python:slim -> silent ImportError +# on `import tensorflow` without it. +RUN apt-get update && apt-get install -y --no-install-recommends \ + libgomp1 \ + && rm -rf /var/lib/apt/lists/* + +# Hugging Face Spaces containers run as uid 1000 — mirror that so file +# ownership matches what the platform expects instead of fighting it. +RUN useradd -m -u 1000 user +USER user + +ENV HOME=/home/user \ + PATH="/home/user/.local/bin:${PATH}" \ + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + # Keras / HF-hub / Matplotlib all try to write cache files at + # import time. Only /tmp and WORKDIR are guaranteed writable on + # Spaces, so caches are redirected there defensively. + KERAS_HOME=/tmp/.keras \ + HF_HOME=/tmp/.huggingface \ + XDG_CACHE_HOME=/tmp/.cache \ + MPLCONFIGDIR=/tmp/.matplotlib + +WORKDIR /app + +# Dependencies installed before the rest of the source is copied, so +# `docker build` only reinstalls TensorFlow/pandas/etc. when +# requirements.txt actually changes, not on every code push. +COPY --chown=user requirements.txt . +RUN pip install --no-cache-dir --upgrade pip \ + && pip install --no-cache-dir -r requirements.txt + +COPY --chown=user . . + +EXPOSE 7860 + +CMD ["python", "app.py"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..118aa2fa3135597c655a2a55c027e7d9aac12e39 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +--- +title: KodaQuant Backend +emoji: 🚀 +colorFrom: blue +colorTo: indigo +sdk: gradio +sdk_version: "6.22.0" +python_version: "3.12" +app_file: app.py +pinned: false +--- diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/api/auth.py b/api/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..48cd43e18a437e4105d8881ff236b65a5365c15e --- /dev/null +++ b/api/auth.py @@ -0,0 +1,377 @@ +""" +api/auth.py + +Módulo de autenticación para KodaQuant Terminal. +Responsable de exponer los endpoints de registro de usuarios delegando +la persistencia y validación de credenciales a Supabase Auth. + +Arquitectura: + - Cliente Supabase inicializado a partir de credenciales centralizadas en core.config. + - Esquemas de entrada/salida validados con Pydantic. + - Manejo explícito de errores de Supabase mapeados a HTTPException. +""" +import hashlib +from datetime import datetime, timezone +from core.security import ( + generate_verification_token, + send_verification_email, + generate_password_reset_token, + send_password_reset_email, +) +from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, status +from pydantic import BaseModel, EmailStr, Field, field_validator +from core.supabase_client import supabase, supabase_admin +from core.rate_limiter import enforce_rate_limit + + +def _hash_token(token: str) -> str: + """Hash de un solo sentido para tokens de un solo uso antes de persistirlos. + El token crudo viaja SOLO por el link del correo — nunca en texto plano en DB.""" + return hashlib.sha256(token.encode()).hexdigest() + +# --------------------------------------------------------------------------- +# Router +# --------------------------------------------------------------------------- +router = APIRouter( + tags=["Authentication"], +) + + +# --------------------------------------------------------------------------- +# Esquemas Pydantic +# --------------------------------------------------------------------------- +class UserRegisterRequest(BaseModel): + """Payload de entrada para el registro de un nuevo usuario.""" + + email: EmailStr = Field(..., description="Correo electrónico del usuario.") + full_name: str = Field(..., min_length=2, max_length=120, description="Nombre completo del usuario.") + password: str = Field( + ..., + min_length=8, + description="Contraseña del usuario. Mínimo 8 caracteres.", + ) + terms_accepted: bool = Field( + ..., description="Debe ser true: aceptación explícita de T&C y Aviso de Privacidad." + ) + + @field_validator("terms_accepted") + @classmethod + def validate_terms_accepted(cls, value: bool) -> bool: + if value is not True: + raise ValueError("Debes aceptar los Términos y Condiciones y el Aviso de Privacidad.") + return value + + @field_validator("password") + @classmethod + def validate_password_strength(cls, value: str) -> str: + # El hashing de la contraseña NO se hace acá: Supabase Auth (GoTrue) + # la hashea con bcrypt del lado del servidor dentro de auth.sign_up(). + # Hashear manualmente antes de enviarla duplicaría el trabajo y + # rompería la verificación posterior en sign_in_with_password. + """Valida requisitos mínimos de robustez antes de llamar a Supabase.""" + if not any(char.isdigit() for char in value): + raise ValueError("La contraseña debe contener al menos un número.") + if not any(char.isupper() for char in value): + raise ValueError("La contraseña debe contener al menos una letra mayúscula.") + return value + + +class UserRegisterResponse(BaseModel): + """Respuesta devuelta tras un registro exitoso.""" + + id: str + email: EmailStr + message: str = "Usuario registrado exitosamente. Verifica tu correo electrónico." + + +# --------------------------------------------------------------------------- +# Endpoint: Registro de usuario +# --------------------------------------------------------------------------- +@router.post( + "/register", + response_model=UserRegisterResponse, + status_code=status.HTTP_201_CREATED, + summary="Registrar un nuevo usuario", + description="Crea una nueva cuenta de usuario en Supabase Auth para KodaQuant Terminal.", +) +async def register_user( + payload: UserRegisterRequest, request: Request, background_tasks: BackgroundTasks +) -> UserRegisterResponse: + """ + Registra un nuevo usuario en Supabase Auth. + + Args: + payload (UserRegisterRequest): Credenciales del usuario (email, password, + full_name y terms_accepted). + + Returns: + UserRegisterResponse: Datos básicos del usuario creado. + + Raises: + HTTPException 409: Si el correo ya está registrado. + HTTPException 422: Si la contraseña es rechazada por Supabase (débil). + HTTPException 429: Si se excede el límite de intentos (fuerza bruta). + HTTPException 500: Ante cualquier error inesperado del proveedor de auth + o si falla la inicialización del perfil en `profiles`. + """ + await enforce_rate_limit(request, "register") + + try: + # FIX: `full_name` va anidado bajo "options.data", no como key de nivel + # superior. supabase-py solo escribe en auth.users.raw_user_meta_data + # cuando el metadata llega dentro de "options" -- con la forma anterior + # ({"data": {...}} al mismo nivel que "email"/"password"), el SDK la + # ignora silenciosamente y raw_user_meta_data queda vacío, sin error. + result = supabase.auth.sign_up( + { + "email": payload.email, + "password": payload.password, + "options": {"data": {"full_name": payload.full_name}}, + } + ) + except Exception as exc: + error_message = str(exc).lower() + + if "already registered" in error_message or "already exists" in error_message: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="El correo electrónico ya se encuentra registrado.", + ) from exc + + if "password" in error_message and ( + "weak" in error_message or "short" in error_message or "should be" in error_message + ): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="La contraseña no cumple con los requisitos mínimos de seguridad.", + ) from exc + + print(f"[ERROR] Fallo inesperado en registro (user={payload.email}): {exc}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="No se pudo completar el registro. Intenta nuevamente más tarde.", + ) from exc + + user = getattr(result, "user", None) + if user is None or getattr(user, "id", None) is None: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Supabase no devolvió información válida del usuario creado.", + ) + + # --- FIX: detección de correo duplicado silencioso --- + # Cuando la confirmación por email está activada en Supabase, sign_up() + # con un correo YA existente no lanza excepción: devuelve un "user" con + # identities=[] vacío (medida anti-enumeración de Supabase). Sin este + # chequeo, el backend responde 201 como si hubiera creado una cuenta nueva. + identities = getattr(user, "identities", None) + if identities is not None and len(identities) == 0: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Este correo ya está registrado.", + ) + + token, expires_at = generate_verification_token() + + # FIX (root cause del 500 / PGRST204): requiere que exista + # public.profiles.full_name (ver migración SQL adjunta). Además, esta + # escritura ahora está aislada en su propio try/except: para este punto + # el usuario YA existe en Auth (sign_up ya se ejecutó con éxito), así que + # un fallo acá NO debe propagarse como un AttributeError/KeyError crudo -- + # se loguea con detalle y se responde un 500 explícito y accionable, en + # vez de dejar a la cuenta en un estado a medio inicializar sin avisar. + try: + supabase_admin.table("profiles").update({ + "full_name": payload.full_name, + "is_verified": False, + "verification_token": _hash_token(token), + "verification_token_expires_at": expires_at.isoformat(), + }).eq("id", user.id).execute() + except Exception as exc: + print(f"[ERROR] No se pudo inicializar el perfil en 'profiles' (user_id={user.id}): {exc}") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=( + "Tu cuenta se creó pero hubo un problema al configurar tu perfil. " + "Contacta a soporte antes de intentar registrarte de nuevo." + ), + ) from exc + + # FIX (root cause de "el registro tarda demasiado" / SMTP timeout en + # línea): antes esto era `await send_verification_email(...)` dentro de + # un try/except -- el cliente HTTP esperaba a que el SMTP conectara (o + # tronara) ANTES de recibir el 201. Con el puerto bloqueado y sin timeout + # explícito eso eran hasta 60s de espera real por request. Ahora se + # agenda como BackgroundTask: la respuesta 201 sale apenas termina lo de + # arriba, y el envío corre después, con su propio techo de 3s + # (core/security.py::_send_mail_message) que nunca vuelve a tocar este + # request. + background_tasks.add_task(send_verification_email, payload.email, token) + + return UserRegisterResponse( + id=user.id, + email=payload.email, + ) + +class VerifyEmailRequest(BaseModel): + token: str + +@router.post("/verify-email") +async def verify_email(payload: VerifyEmailRequest): + result = ( + supabase_admin.table("profiles") + .select("id, is_verified, verification_token_expires_at") + .eq("verification_token", _hash_token(payload.token)) + .maybe_single() + .execute() + ) + profile = result.data + if not profile: + raise HTTPException(status_code=400, detail="Token de verificación inválido.") + if profile.get("is_verified"): + return {"message": "El correo ya estaba verificado."} + + expires_at = profile.get("verification_token_expires_at") + if expires_at and datetime.fromisoformat(expires_at) < datetime.now(timezone.utc): + raise HTTPException(status_code=400, detail="El token ha expirado.") + + supabase_admin.table("profiles").update({ + "is_verified": True, + "verification_token": None, + "verification_token_expires_at": None, + }).eq("id", profile["id"]).execute() + + return {"message": "Correo verificado exitosamente."} + +class LoginRequest(BaseModel): + email: str + password: str + +@router.post("/login") +async def login(payload: LoginRequest, request: Request): + await enforce_rate_limit(request, "login") + + try: + response = supabase.auth.sign_in_with_password({ + "email": payload.email, + "password": payload.password + }) + except Exception as exc: + print(f"[ERROR] Fallo de login (user={payload.email}): {exc}") + raise HTTPException(status_code=401, detail="Credenciales inválidas.") + + if not response or not response.session: + raise HTTPException(status_code=401, detail="No se pudo autenticar") + + profile = ( + supabase_admin.table("profiles") + .select("is_verified") + .eq("id", response.user.id) + .single() + .execute() + ).data + if not profile or not profile.get("is_verified"): + raise HTTPException(status_code=401, detail="Debes verificar tu correo antes de iniciar sesión.") + + return { + "access_token": response.session.access_token, + "token_type": "bearer", + "user": response.user + } + + +class ForgotPasswordRequest(BaseModel): + email: EmailStr + + +@router.post("/forgot-password") +async def forgot_password(payload: ForgotPasswordRequest, request: Request, background_tasks: BackgroundTasks): + """ + Inicia el flujo de recuperación de contraseña. + + Respuesta SIEMPRE genérica (anti user-enumeration): nunca confirmamos + ni negamos si el correo existe en la base, sin importar el resultado. + """ + await enforce_rate_limit(request, "forgot-password") + + generic_response = { + "message": "Si existe una cuenta con ese correo, te enviamos un enlace para restablecer tu contraseña." + } + + # ⚠️ Asume que la tabla `profiles` tiene columna `email` (patrón típico de + # trigger on-signup en Supabase). Si tu esquema no la tiene, ajusta esta + # búsqueda a como resuelvas hoy user-por-email. + profile_result = ( + supabase_admin.table("profiles") + .select("id") + .eq("email", payload.email) + .maybe_single() + .execute() + ) + profile = profile_result.data + if not profile: + return generic_response + + token, expires_at = generate_password_reset_token() + supabase_admin.table("profiles").update({ + "password_reset_token": _hash_token(token), + "password_reset_token_expires_at": expires_at.isoformat(), + }).eq("id", profile["id"]).execute() + + # Mismo fix que en /register: agendado como BackgroundTask para que la + # respuesta genérica (anti-enumeración) salga de inmediato, sin esperar + # al SMTP. Ver core/security.py::_send_mail_message para el techo de 3s. + background_tasks.add_task(send_password_reset_email, payload.email, token) + + return generic_response + + +class ResetPasswordRequest(BaseModel): + token: str + password: str = Field(..., min_length=8) + + @field_validator("password") + @classmethod + def validate_password_strength(cls, value: str) -> str: + if not any(char.isdigit() for char in value): + raise ValueError("La contraseña debe contener al menos un número.") + if not any(char.isupper() for char in value): + raise ValueError("La contraseña debe contener al menos una letra mayúscula.") + return value + + +@router.post("/reset-password") +async def reset_password(payload: ResetPasswordRequest, request: Request): + await enforce_rate_limit(request, "reset-password") + + result = ( + supabase_admin.table("profiles") + .select("id, password_reset_token_expires_at") + .eq("password_reset_token", _hash_token(payload.token)) + .maybe_single() + .execute() + ) + profile = result.data + if not profile: + raise HTTPException(status_code=400, detail="Enlace de restablecimiento inválido.") + + expires_at = profile.get("password_reset_token_expires_at") + if not expires_at or datetime.fromisoformat(expires_at) < datetime.now(timezone.utc): + raise HTTPException(status_code=400, detail="El enlace ha expirado. Solicita uno nuevo.") + + try: + supabase_admin.auth.admin.update_user_by_id( + profile["id"], {"password": payload.password} + ) + except Exception as exc: + raise HTTPException( + status_code=500, + detail=f"No se pudo actualizar la contraseña: {str(exc)}", + ) from exc + + supabase_admin.table("profiles").update({ + "password_reset_token": None, + "password_reset_token_expires_at": None, + }).eq("id", profile["id"]).execute() + + return {"message": "Contraseña actualizada exitosamente."} \ No newline at end of file diff --git a/api/online_learning.py b/api/online_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..9eebf1b27bb4cdf112ae4e9a8e663626f5f627c9 --- /dev/null +++ b/api/online_learning.py @@ -0,0 +1,35 @@ +# api/online_learning.py +""" +Endpoint disparador del ciclo diario de online learning (Fase 1). Pensado +para ser golpeado por un cron externo (Render Cron Job, GitHub Actions +schedule, cron de VPS con `curl`) UNA vez al día, después del cierre de +mercado (NYSE cierra 21:00 UTC / 16:00 ET) — NO por el frontend ni por +usuarios finales, por eso vive detrás de un secreto compartido en vez de +`verify_api_credits` (esto no consume créditos de ningún usuario, es +mantenimiento interno del modelo). +""" + +import os + +from fastapi import APIRouter, Header, HTTPException + +from services.online_learning import run_daily_online_learning_cycle + +router = APIRouter() + +# Debe fijarse en el entorno de producción (`CRON_SECRET=...`) — sin él, +# el endpoint rechaza TODO request (fail-closed, nunca fail-open). +_CRON_SECRET = os.getenv("CRON_SECRET") + + +@router.post("/api/v1/quanti/online-learning/run") +async def trigger_online_learning_cycle(x_cron_secret: str | None = Header(default=None)): + if not _CRON_SECRET or x_cron_secret != _CRON_SECRET: + raise HTTPException(status_code=403, detail="CRON_SECRET ausente o inválido.") + + # SÍNCRONO Y POTENCIALMENTE LARGO (descarga de mercado + fit de Keras) — + # se corre tal cual dentro del handler porque este endpoint es de uso + # exclusivo del cron (1 invocación/día), no del tráfico de usuarios; no + # justifica la complejidad de un job queue para este volumen. + report = run_daily_online_learning_cycle() + return {"status": "success" if not report.get("errors") else "partial", "report": report} \ No newline at end of file diff --git a/api/payments.py b/api/payments.py new file mode 100644 index 0000000000000000000000000000000000000000..17d3e741ccbbd433efc7a92f160c998822d98cff --- /dev/null +++ b/api/payments.py @@ -0,0 +1,549 @@ +# RUTA: api/payments.py +import json +import logging +from datetime import datetime, timezone +from typing import Any + +import stripe +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, status +from pydantic import BaseModel + +from core.config import settings +from core.security import AuthenticatedUser, get_current_user +from core.supabase_client import supabase_admin +from core.security import ( + send_subscription_upgrade_email, + send_subscription_downgrade_email, + send_subscription_cancel_email, +) + +logger = logging.getLogger(__name__) + +stripe.api_key = settings.STRIPE_SECRET_KEY + +router = APIRouter(prefix="/api/v1/payments", tags=["payments"]) + +PRICE_MAP = { + "pro": settings.STRIPE_PRICE_PRO, + "ultra": settings.STRIPE_PRICE_ULTRA, +} +TIER_BY_PRICE = {v: k.upper() for k, v in PRICE_MAP.items() if v} +TIER_RANK = {"FREE": 0, "PRO": 1, "ULTRA": 2} + + +def _ts_to_iso(ts: int | None) -> str | None: + if not ts: + return None + return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat() + + +def _stripe_object_to_dict(obj: Any) -> dict: + """Convierte recursivamente un Event/StripeObject del SDK a dict/list + nativos de Python. En SDK v12+, ningún StripeObject anidado garantiza + .get() en accesos encadenados -- normalizar UNA vez acá (aquí, en + change-plan, en el webhook) evita repetir ese riesgo en cada callsite.""" + if hasattr(obj, "to_dict_recursive"): + return obj.to_dict_recursive() + if hasattr(obj, "to_dict"): + return obj.to_dict() + try: + return json.loads(json.dumps(obj, default=str)) + except (TypeError, ValueError) as exc: + logger.error("No se pudo normalizar objeto Stripe: %s", exc) + return {} + + +def _extract_period_end(sub_dict: dict) -> int | None: + """Extrae el timestamp Unix de current_period_end de forma segura. + + Root cause real del 23502: a partir de la versión de API 'Basil' + (2025-03-31+), Stripe removió current_period_start/current_period_end + del objeto Subscription de nivel superior. Ahora viven por-item, en + items.data[N].current_period_end (ver changelog de Stripe: "Adds + subscription item-level billing periods and removes subscription-level + periods"). Cualquier cuenta/SDK apuntando a esa versión de API (o + posterior) devuelve `None` en sub_dict.get("current_period_end"), + que es exactamente el síntoma reportado. + + Estrategia: leer primero desde el primer item de la suscripción (fuente + de verdad en Basil+), con fallback al campo legacy de nivel superior + para cuentas todavía en una versión de API pre-Basil. + """ + items = (sub_dict.get("items") or {}).get("data") or [] + if items: + item_period_end = items[0].get("current_period_end") + if item_period_end is not None: + return int(item_period_end) + + legacy_period_end = sub_dict.get("current_period_end") + if legacy_period_end is not None: + return int(legacy_period_end) + + return None + + +def _require_period_end_iso(sub_dict: dict, subscription_id: str) -> str: + """Fail-fast: valida ANTES de tocar la base de datos. Si Stripe no + devuelve current_period_end en ninguna de las dos ubicaciones posibles, + aborta con un error claro en vez de dejar pasar un None hacia el + .update() de Supabase (que dispara el 23502 sobre la constraint + NOT NULL de profiles.current_period_end).""" + period_end_ts = _extract_period_end(sub_dict) + if period_end_ts is None: + logger.error( + "current_period_end ausente en la suscripción %s (ni en items[0] ni en el nivel superior)", + subscription_id, + ) + raise HTTPException( + status.HTTP_500_INTERNAL_SERVER_ERROR, + "No se pudo determinar la fecha de fin de período de la suscripción en Stripe.", + ) + period_end_iso = _ts_to_iso(period_end_ts) + if period_end_iso is None: + logger.error("Fallo al convertir current_period_end=%s a ISO-8601 (sub=%s)", period_end_ts, subscription_id) + raise HTTPException( + status.HTTP_500_INTERNAL_SERVER_ERROR, + "No se pudo convertir la fecha de fin de período de la suscripción.", + ) + return period_end_iso + + +def _release_schedule_if_attached(sub_dict: dict, subscription_id: str) -> None: + """Rompe el vínculo Subscription<->SubscriptionSchedule si existe uno activo. + + Root cause de los 400 en change-plan/cancel: una vez que una Subscription + queda atada a un SubscriptionSchedule (ej. por un downgrade programado + previo vía _schedule_downgrade), Stripe bloquea CUALQUIER + Subscription.modify() directo -- tanto cambio de item/price como + cancel_at_period_end -- exigiendo que la modificación pase por el + schedule ("You cannot migrate a subscription that is already attached + to a schedule" / "updating any cancelation behavior directly is not + allowed"). `SubscriptionSchedule.release()` desata el schedule de la + Subscription sin cancelarla, devolviendo el control directo sobre + Subscription.modify(). Se ejecuta ANTES de cualquier modify() o de + crear un schedule nuevo (_schedule_downgrade también fallaría con 400 + si ya hay uno attached).""" + schedule_id = sub_dict.get("schedule") + if not schedule_id: + return + try: + stripe.SubscriptionSchedule.release(schedule_id) + logger.info( + "Schedule %s liberado para desbloquear modificación directa de sub %s", + schedule_id, subscription_id, + ) + except stripe.error.StripeError as exc: + logger.error( + "No se pudo liberar el schedule %s de la suscripción %s: %s", + schedule_id, subscription_id, exc, + ) + raise HTTPException( + status.HTTP_409_CONFLICT, + "La suscripción está atada a un schedule de Stripe que no pudo liberarse. Contactá a soporte.", + ) + + +def _get_user_email_and_language(user_id: str) -> tuple[str | None, str]: + email = None + try: + admin_user = supabase_admin.auth.admin.get_user_by_id(user_id) + email = getattr(admin_user.user, "email", None) + except Exception as exc: + logger.warning("No se pudo resolver email de %s: %s", user_id, exc) + + profile = ( + supabase_admin.table("profiles") + .select("preferred_language") + .eq("id", user_id) + .maybe_single() + .execute() + ) + language = (profile.data or {}).get("preferred_language") or "en" + return email, language + + +async def _notify_change(user_id: str, tier: str, direction: str): + email, language = _get_user_email_and_language(user_id) + if not email: + return + if direction == "upgrade": + await send_subscription_upgrade_email(email, tier, language) + else: + await send_subscription_downgrade_email(email, tier, language) + + +async def _notify_cancel_scheduled(user_id: str): + email, language = _get_user_email_and_language(user_id) + if email: + await send_subscription_downgrade_email(email, "FREE", language) + + +async def _notify_cancel_final(user_id: str): + email, language = _get_user_email_and_language(user_id) + if email: + await send_subscription_cancel_email(email, language) + + +def _schedule_downgrade(subscription_id: str, new_price_id: str): + """Downgrade a un plan pago inferior (ej. ULTRA -> PRO): SubscriptionSchedule + con 2 fases -- la actual (sin tocar) y una nueva que arranca justo cuando + termina el ciclo vigente. Sin prorrateo, sin reembolso parcial. + + Root cause real del 400 "Received unknown parameter: phases[iterations]": + Stripe removió `iterations` de phases en subscription_schedules a partir + de la versión de API 'Clover' (2025-09-30), reemplazándolo por `duration` + (ver changelog: "Removes iterations parameter for subscription schedules"). + Cualquier cuenta en esa versión de API o posterior rechaza `iterations` + de plano. `duration` se ancla al intervalo de facturación real del price + destino (no se asume 'month' a ciegas -- rompería planes anuales).""" + schedule = stripe.SubscriptionSchedule.create(from_subscription=subscription_id) + schedule_dict: dict = _stripe_object_to_dict(schedule) + current_phase = schedule_dict["phases"][0] + + new_price_dict: dict = _stripe_object_to_dict(stripe.Price.retrieve(new_price_id)) + recurring = new_price_dict.get("recurring") or {} + duration_interval = recurring.get("interval") or "month" + duration_interval_count = recurring.get("interval_count") or 1 + + stripe.SubscriptionSchedule.modify( + schedule_dict["id"], + # Explícito (no queda a un default implícito de Stripe): al terminar + # la fase 2, el schedule se libera y la suscripción sigue renovando + # normalmente con el price nuevo -- consistente con "downgrade + # permanente", no una promo temporal de 1 ciclo. + end_behavior="release", + phases=[ + { + "items": [ + {"price": item["price"], "quantity": item.get("quantity", 1)} + for item in current_phase["items"] + ], + "start_date": current_phase["start_date"], + "end_date": current_phase["end_date"], + }, + { + "items": [{"price": new_price_id, "quantity": 1}], + "duration": { + "interval": duration_interval, + "interval_count": duration_interval_count, + }, + }, + ], + ) + + +@router.post("/checkout") +async def create_checkout_session( + plan: str = Query(..., description="Escribe 'pro' o 'ultra'"), + current_user: AuthenticatedUser = Depends(get_current_user), +): + plan_key = plan.lower() + price_id = PRICE_MAP.get(plan_key) + if not price_id: + raise HTTPException(status.HTTP_400_BAD_REQUEST, "Plan inválido. Usa 'pro' o 'ultra'.") + + # Checkout SOLO para alta nueva (usuario sin suscripción activa). Si ya + # tiene una, upgrade/downgrade/cancelación van por /change-plan -- nunca + # por acá, o se duplicaría la suscripción en Stripe. + existing = ( + supabase_admin.table("profiles") + .select("stripe_subscription_id") + .eq("id", current_user.id) + .maybe_single() + .execute() + ) + if existing.data and existing.data.get("stripe_subscription_id"): + raise HTTPException(status.HTTP_409_CONFLICT, "Ya tenés una suscripción activa. Usa /change-plan.") + + try: + session = stripe.checkout.Session.create( + mode="subscription", + line_items=[{"price": price_id, "quantity": 1}], + client_reference_id=current_user.id, + customer_email=current_user.email, + metadata={"user_id": current_user.id, "target_tier": plan_key.upper()}, + # subscription_data.metadata es la ÚNICA forma de que el metadata + # sobreviva al objeto Subscription (el de Session no se copia solo). + subscription_data={"metadata": {"user_id": current_user.id, "target_tier": plan_key.upper()}}, + success_url=settings.STRIPE_SUCCESS_URL, + cancel_url=settings.STRIPE_CANCEL_URL, + ) + except stripe.error.StripeError as e: + logger.warning("StripeError en checkout (user=%s, plan=%s): %s", current_user.id, plan_key, e) + raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e)) + except Exception as exc: + logger.error("Fallo inesperado en checkout (user=%s, plan=%s): %s", current_user.id, plan_key, exc, exc_info=True) + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Error interno al crear la sesión de pago.") + + return {"checkout_url": session.url} + + +class ChangePlanRequest(BaseModel): + target_tier: str # "free" | "pro" | "ultra" + + +class ChangePlanResponse(BaseModel): + """Respuesta fuertemente tipada para que el frontend SPA sepa exactamente + qué pasó y, si corresponde, a dónde debe empujar el router -- en vez de + inferirlo de un mensaje genérico de texto.""" + + status: str # "scheduled" | "processing" + message: str + pending_tier: str | None = None + current_period_end: str | None = None + redirect_url: str | None = None # ej. "/cancel" -- None cuando no aplica + + +@router.post("/change-plan", response_model=ChangePlanResponse) +async def change_plan( + # No existe un endpoint /cancel-plan separado: la cancelación es + # target_tier="free" acá mismo (rama cancel_at_period_end más abajo). + # El redirect_url="/cancel" se setea únicamente en esa rama. + payload: ChangePlanRequest, + current_user: AuthenticatedUser = Depends(get_current_user), +): + target = payload.target_tier.lower() + if target not in ("free", "pro", "ultra"): + raise HTTPException(status.HTTP_400_BAD_REQUEST, "target_tier debe ser 'free', 'pro' o 'ultra'.") + + profile = ( + supabase_admin.table("profiles") + .select("subscription_tier, stripe_subscription_id") + .eq("id", current_user.id) + .maybe_single() + .execute() + ) + if not profile.data or not profile.data.get("stripe_subscription_id"): + raise HTTPException(status.HTTP_400_BAD_REQUEST, "No hay suscripción activa para modificar. Usa /checkout.") + + subscription_id = profile.data["stripe_subscription_id"] + current_tier = profile.data.get("subscription_tier", "FREE") + target_upper = target.upper() + + if target_upper == current_tier: + raise HTTPException(status.HTTP_400_BAD_REQUEST, "Ya estás en ese plan.") + + try: + subscription = stripe.Subscription.retrieve(subscription_id) + # Normalización única a dict -- misma causa raíz que el webhook: + # StripeObject en SDK v12+ no garantiza .get() en accesos anidados. + sub_dict: dict = _stripe_object_to_dict(subscription) + + # The Breaker: si la sub está attached a un schedule (de un downgrade + # previo, ej. Ultra->Pro programado), liberarlo ANTES de tocar items + # o cancel_at_period_end -- si no, tanto el modify() de abajo como + # _schedule_downgrade() (que crea un schedule nuevo) rechazan con 400. + _release_schedule_if_attached(sub_dict, subscription_id) + + items = sub_dict.get("items", {}).get("data", []) + if not items: + logger.error("Suscripción %s sin items al ejecutar change-plan", subscription_id) + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Suscripción inconsistente en Stripe.") + item_id = items[0]["id"] + + # Fail-fast: extrae y valida current_period_end ANTES de escribir en + # Supabase (ver _extract_period_end para la causa raíz real: Stripe + # API 'Basil' 2025-03-31+ movió este campo a items.data[0]). + period_end_iso = _require_period_end_iso(sub_dict, subscription_id) + + if target == "free": + # Cancelación total: sigue con el plan actual hasta fin de ciclo. + # subscription_tier real lo pisa el webhook (.deleted), esto solo + # deja constancia visible para el frontend. + stripe.Subscription.modify(subscription_id, cancel_at_period_end=True) + supabase_admin.table("profiles").update({ + "pending_tier": "FREE", + "cancel_at_period_end": True, + "current_period_end": period_end_iso, + }).eq("id", current_user.id).execute() + return ChangePlanResponse( + status="scheduled", + message=f"Tu suscripción se cancelará el {period_end_iso}. Hasta entonces seguís con acceso.", + pending_tier="free", + current_period_end=period_end_iso, + redirect_url="/cancel", # instrucción explícita de ruteo para el SPA + ) + + if TIER_RANK[target_upper] > TIER_RANK[current_tier]: + # Upgrade in-place (Pro -> Ultra): inmediato, con prorrateo. + stripe.Subscription.modify( + subscription_id, + items=[{"id": item_id, "price": PRICE_MAP[target]}], + proration_behavior="always_invoice", + cancel_at_period_end=False, + ) + # subscription_tier lo confirma el webhook; no hay ruteo especial acá. + return ChangePlanResponse( + status="processing", + message=f"Tu plan se está actualizando a {target_upper}.", + ) + + # Downgrade a un plan pago inferior (Ultra -> Pro): programado. + _schedule_downgrade(subscription_id, PRICE_MAP[target]) + supabase_admin.table("profiles").update({ + "pending_tier": target_upper, + "current_period_end": period_end_iso, + }).eq("id", current_user.id).execute() + return ChangePlanResponse( + status="scheduled", + message=f"Tu plan bajará a {target_upper} el {period_end_iso}.", + pending_tier=target, + current_period_end=period_end_iso, + ) + + except stripe.error.StripeError as e: + logger.warning("StripeError en change-plan (user=%s, sub=%s): %s", current_user.id, subscription_id, e) + raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e)) + except HTTPException: + raise + except Exception as exc: + logger.error( + "Fallo inesperado en change-plan (user=%s, sub=%s): %s", + current_user.id, subscription_id, exc, exc_info=True, + ) + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Error interno al modificar la suscripción.") + + +@router.get("/subscription") +async def get_subscription_status(current_user: AuthenticatedUser = Depends(get_current_user)): + profile = ( + supabase_admin.table("profiles") + .select("subscription_tier, pending_tier, cancel_at_period_end, current_period_end") + .eq("id", current_user.id) + .maybe_single() + .execute() + ) + data = profile.data or {} + pending = data.get("pending_tier") + return { + "subscription_tier": (data.get("subscription_tier") or "FREE").lower(), + "pending_tier": pending.lower() if pending else None, + "cancel_at_period_end": bool(data.get("cancel_at_period_end")), + "current_period_end": data.get("current_period_end"), + } + + +@router.post("/webhook") +async def stripe_webhook(request: Request, background_tasks: BackgroundTasks): + payload = await request.body() + sig_header = request.headers.get("stripe-signature") + endpoint_secret = settings.STRIPE_WEBHOOK_SECRET + + try: + event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) + except (ValueError, stripe.error.SignatureVerificationError) as exc: + logger.warning("Webhook rechazado (firma/payload inválido): %s", exc) + raise HTTPException(status.HTTP_400_BAD_REQUEST, "Webhook inválido") + + # Normalización única a dict nativo -- de acá en más TODO acceso usa + # .get()/[] de dict estándar. + event_dict: dict = _stripe_object_to_dict(event) + event_type: str = event_dict.get("type", "") + event_id: str = event_dict.get("id", "unknown") + data: dict = event_dict.get("data") or {} + obj: dict = data.get("object") or {} + previous: dict = data.get("previous_attributes") or {} + + try: + if event_type == "checkout.session.completed": + user_id = obj.get("metadata", {}).get("user_id") + target_tier = obj.get("metadata", {}).get("target_tier", "PRO") + if user_id: + supabase_admin.table("profiles").update({ + "subscription_tier": target_tier, + "stripe_customer_id": obj.get("customer"), + "stripe_subscription_id": obj.get("subscription"), + "cancel_at_period_end": False, + "pending_tier": None, + }).eq("id", user_id).execute() + background_tasks.add_task(_notify_change, user_id, target_tier, "upgrade") + + elif event_type == "customer.subscription.updated": + subscription_id = obj.get("id") + profile = ( + supabase_admin.table("profiles") + .select("id, subscription_tier") + .eq("stripe_subscription_id", subscription_id) + .maybe_single() + .execute() + ) + if profile.data: + user_id = profile.data["id"] + current_tier_db = profile.data.get("subscription_tier", "FREE") + cancel_at_period_end = obj.get("cancel_at_period_end", False) + items = obj.get("items", {}).get("data", []) + price_id = items[0]["price"]["id"] if items else None + new_tier = TIER_BY_PRICE.get(price_id) + + if "cancel_at_period_end" in previous and cancel_at_period_end: + # Cancelación total recién programada (paid -> FREE a fin + # de ciclo). NO tocar subscription_tier -- eso lo hace + # .deleted. + # Mismo fix que change-plan: current_period_end puede + # vivir en items.data[0] (Stripe API 'Basil' 2025-03-31+) + # en vez del nivel superior de `obj`. + update_payload: dict = { + "cancel_at_period_end": True, + "pending_tier": "FREE", + } + period_end_ts = _extract_period_end(obj) + if period_end_ts is not None: + update_payload["current_period_end"] = _ts_to_iso(period_end_ts) + else: + # No se crashea el webhook por esto (Stripe reintentaría + # indefinidamente si el campo nunca llega): se omite el + # campo en vez de mandar null y violar la constraint + # NOT NULL, y se deja rastro en logs para investigar. + logger.error( + "customer.subscription.updated (sub=%s): current_period_end no disponible " + "ni en items[0] ni en el nivel superior; se omite el campo en el update.", + subscription_id, + ) + supabase_admin.table("profiles").update(update_payload).eq("id", user_id).execute() + background_tasks.add_task(_notify_cancel_scheduled, user_id) + + elif new_tier and new_tier != current_tier_db and not cancel_at_period_end: + # Precio ya efectivo: upgrade inmediato (Pro->Ultra) o + # release automático de un SubscriptionSchedule (fase 2 de + # un downgrade Ultra->Pro activándose al fin del ciclo + # anterior). + direction = "upgrade" if TIER_RANK[new_tier] > TIER_RANK[current_tier_db] else "downgrade" + supabase_admin.table("profiles").update({ + "subscription_tier": new_tier, + "pending_tier": None, + "cancel_at_period_end": False, + }).eq("id", user_id).execute() + background_tasks.add_task(_notify_change, user_id, new_tier, direction) + + elif event_type == "customer.subscription.deleted": + subscription_id = obj.get("id") + profile = ( + supabase_admin.table("profiles") + .select("id") + .eq("stripe_subscription_id", subscription_id) + .maybe_single() + .execute() + ) + if profile.data: + user_id = profile.data["id"] + supabase_admin.table("profiles").update({ + "subscription_tier": "FREE", + "pending_tier": None, + "cancel_at_period_end": False, + "stripe_subscription_id": None, + }).eq("id", user_id).execute() + background_tasks.add_task(_notify_cancel_final, user_id) + + else: + logger.info("Evento Stripe no manejado: %s (id=%s)", event_type, event_id) + + except Exception as exc: + # Cualquier fallo real de procesamiento (Supabase, KeyError, etc.) + # devuelve 500 para que Stripe reintente -- nunca un AttributeError + # crudo ni un 200 silencioso que enmascare el fallo. + logger.error( + "Error procesando webhook %s (id=%s): %s", event_type, event_id, exc, exc_info=True + ) + raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Error interno procesando el evento") + + return {"status": "success"} \ No newline at end of file diff --git a/api/quanti_chat.py b/api/quanti_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..b72846d4307af645f1aba9524d8cd59ad8952295 --- /dev/null +++ b/api/quanti_chat.py @@ -0,0 +1,347 @@ +# api/quanti_chat.py +import io +import json + +import pandas as pd +from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status +from fastapi.responses import StreamingResponse +from pydantic import BaseModel + +from core.security import AuthenticatedUser, get_current_user +from core.quota_manager import verify_quota +from core.supabase_client import supabase_admin as supabase +from services.quanti_engine import ( + QUANTI_CHAT_FALLBACK, + describe_llm_failure, + is_llm_connection_failure, + sanitize_llm_output, + stream_quanti_chat_completion, +) + +router = APIRouter(prefix="/api/v1/quanti/chat", tags=["quanti-chat"]) + +MAX_FILE_BYTES = 5 * 1024 * 1024 # 5 MB +HISTORY_TURNS = 6 +TITLE_MAX_LEN = 48 + +CHAT_SYSTEM_PROMPT = """You are Quanti, the AI engine embedded in the KodaQuant Terminal — the same analytical brain behind the platform's Alpha Seeker forecasting engine. You are not a general-purpose chatbot: you are a precision quantitative instrument, and in this chat channel specifically, you also act as the concierge who routes clients to the exact instrument that solves their request. + +Tone: technical, direct, helpful, highly sophisticated — the register of a quantitative hedge fund's concierge desk, never a hedging generic assistant. Zero filler, zero unnecessary courtesies. Zero Markdown (no asterisks, no # headers). + +HARD BAN — before anything else: you may NEVER open or fill a reply with "I'm sorry", "As an AI/language model", "I can't provide financial advice", "consult a licensed advisor", "diversify your portfolio" as a stock non-answer, or any equivalent generic financial-disclaimer boilerplate. That reflex produces a useless answer and actively damages the user's trust in the terminal. If a request sits in category 2 below, the correct move is never a refusal — it's a routing handoff to the tool that actually computes the number. + +Classify every user message into ONE of these 4 categories and respond accordingly: + +1) GREETING OR QUESTION ABOUT YOURSELF ("hi", "good morning", "what are you?", "what can you do?", thanks, farewells): +Respond in 1-2 lines, natural but corporate: introduce yourself as Quanti, KodaQuant's analysis engine, and offer to continue with a concrete financial query. No treatise — this is a welcome, not an analysis. + +2) CAPITAL ALLOCATION / RECOMMENDATION REQUEST (the user states an amount of capital and asks what to do with it, asks what to invest in, asks for a pick, a portfolio, or "what would you do with my money" in any phrasing): +This chat channel has no live wire into the Alpha Seeker forecasting engine — you cannot compute a real, current allocation here, and improvising one would be a fabricated number, not an analysis. So you never refuse and you never invent a figure: you hand the client off to the instrument built for exactly this, in your own words, elegantly, hitting these beats in order: + - Open by framing this as getting them a mathematically precise answer instead of a verbal guess — that's the reason for the handoff, not an excuse. + - Direct them to the "Strategy Parameters" panel on the terminal's side panel. + - Tell them to enter their exact capital in their desired currency. + - Tell them to activate "Quanti's Choice" mode, and explain concretely what happens next: your Alpha Seeker algorithm scans the market in real time, evaluates directional accuracy (DirAcc) and volatility per asset, and automatically structures a tactical portfolio split between Risk and Reserve capital. + - Close with confident, concierge-grade phrasing that frames this as superior service, not a deflection. +Vary your exact wording turn to turn — never recite a fixed script verbatim — but always hit every beat above. Never say you "can't" or "aren't allowed to" help; you ARE helping, by routing them to the precise tool for the job. + +3) GENERAL FINANCIAL / MARKET QUERY (explaining an indicator, discussing market conditions or a specific asset, quantitative/statistical concepts, or analyzing an attached file's data) that does NOT ask you to allocate the user's capital or name a recommendation: +This is your core territory. Respond with the maximum analytical and technical depth the available data allows. If the user attached a file, the FILE CONTEXT block is your ONLY numeric source about that file — never invent figures that aren't there. + +4) OUT OF SCOPE (general knowledge, jokes, programming unrelated to KodaQuant, everyday topics, anything unrelated to finance): +Decline firmly but not curtly — one sentence explaining why, not a flat door-slam. Tone example, generate variants, never repeat it verbatim every time: "As an AI specialized exclusively in finance and quantitative analysis, I don't process requests outside that scope. Let's keep our interaction to market data or strategy evaluation." + +The LANGUAGE RULE and IDENTITY RULE for this session are prepended above this prompt by the engine, under the same system role — treat them as highest priority and non-negotiable.""" + + +# --------------------------------------------------------------------------- +# Utilidades de archivo (pandas) +# --------------------------------------------------------------------------- + +def _read_tabular_file(filename: str, raw_bytes: bytes) -> pd.DataFrame: + buf = io.BytesIO(raw_bytes) + lower = (filename or "").lower() + if lower.endswith(".csv"): + return pd.read_csv(buf) + if lower.endswith((".xlsx", ".xls")): + return pd.read_excel(buf) + raise ValueError("Formato no soportado. Usa .csv o .xlsx.") + + +def _summarize_dataframe(df: pd.DataFrame, max_cols: int = 8) -> str: + numeric_df = df.select_dtypes(include="number") + if numeric_df.empty: + return "Archivo sin columnas numéricas detectables." + + lines = [f"Filas: {len(df)} | Columnas numéricas: {len(numeric_df.columns)}"] + for col in list(numeric_df.columns)[:max_cols]: + series = numeric_df[col].dropna() + if series.empty: + continue + first, last = float(series.iloc[0]), float(series.iloc[-1]) + pct_change = ((last - first) / first * 100) if first != 0 else 0.0 + trend = "alcista" if last > first else ("bajista" if last < first else "plano") + lines.append( + f"{col}: media={series.mean():.4f} | desv.std={series.std(ddof=0):.4f} | " + f"tendencia={trend} ({pct_change:+.2f}%) | min={series.min():.4f} | max={series.max():.4f}" + ) + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Ownership guard +# --------------------------------------------------------------------------- + +def _verify_thread_ownership(thread_id: str, user_id: str) -> None: + """ + `maybe_single().execute()` puede devolver `None` DIRECTAMENTE (no un + objeto con `.data = None`) cuando la query no matchea ninguna fila — + comportamiento conocido de ciertas versiones de supabase-py/postgrest-py. + Evaluar `.data` sobre eso revienta con AttributeError antes de llegar al + chequeo de negocio. Se blinda en 2 capas: try/except por si el cliente + lanza en vez de devolver None, y `getattr` en vez de acceso directo. + + NOTA: `supabase` acá es el cliente SERVICE ROLE (ver import arriba) — + bypassea RLS por completo, así que este filtro por user_id es la ÚNICA + barrera de autorización real. No se puede quitar ni relajar. + """ + try: + owned = ( + supabase.table("chat_threads") + .select("id") + .eq("id", thread_id) + .eq("user_id", user_id) + .maybe_single() + .execute() + ) + except Exception as exc: # noqa: BLE001 + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Acceso denegado o hilo no encontrado.", + ) from exc + + if owned is None or not getattr(owned, "data", None): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Acceso denegado o hilo no encontrado.", + ) + +class ThreadPinUpdate(BaseModel): + pinned: bool + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@router.get("/threads") +async def list_threads(current_user: AuthenticatedUser = Depends(get_current_user)): + result = ( + supabase.table("chat_threads") + .select("id, title, pinned, created_at") + .eq("user_id", current_user.id) + .is_("deleted_at", "null") + .order("created_at", desc=True) + .execute() + ) + return {"threads": result.data or []} + + +@router.get("/threads/{thread_id}/messages") +async def get_thread_messages( + thread_id: str, + current_user: AuthenticatedUser = Depends(get_current_user), +): + _verify_thread_ownership(thread_id, current_user.id) + + result = ( + supabase.table("chat_messages") + .select("id, role, content, created_at") + .eq("thread_id", thread_id) + .order("created_at", desc=False) + .execute() + ) + return {"messages": result.data or []} + +# ── PATCH /api/v1/quanti/chat/threads/{thread_id} ─────────────────────────── +@router.patch("/threads/{thread_id}") +async def update_thread_pin( + thread_id: str, + payload: ThreadPinUpdate, + current_user: AuthenticatedUser = Depends(get_current_user), +): + _verify_thread_ownership(thread_id, current_user.id) + + try: + result = ( + supabase.table("chat_threads") + .update({"pinned": payload.pinned}) + .eq("id", thread_id) + .eq("user_id", current_user.id) + .execute() + ) + except Exception as exc: # noqa: BLE001 + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="No se pudo actualizar el hilo.", + ) from exc + + if not result.data: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Hilo no encontrado.") + + return {"thread": result.data[0]} + + +# ── DELETE /api/v1/quanti/chat/threads/{thread_id} (hard delete) ─────────── +@router.delete("/threads/{thread_id}") +async def delete_thread( + thread_id: str, + current_user: AuthenticatedUser = Depends(get_current_user), +): + _verify_thread_ownership(thread_id, current_user.id) + + try: + # Cascade manual: si la FK chat_messages.thread_id no tiene + # ON DELETE CASCADE en el schema de Supabase, este borrado + # explícito es obligatorio para no dejar mensajes huérfanos. + supabase.table("chat_messages").delete().eq("thread_id", thread_id).execute() + result = ( + supabase.table("chat_threads") + .delete() + .eq("id", thread_id) + .eq("user_id", current_user.id) + .execute() + ) + except Exception as exc: # noqa: BLE001 + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="No se pudo eliminar el hilo.", + ) from exc + + if not result.data: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Hilo no encontrado.") + + return {"deleted": True} + +def _persist_chat_turn(thread_id: str, prompt: str, reply: str) -> None: + supabase.table("chat_messages").insert( + [ + {"thread_id": thread_id, "role": "user", "content": prompt}, + {"thread_id": thread_id, "role": "assistant", "content": reply}, + ] + ).execute() + + +async def _chat_sse_generator(thread_id: str, prompt: str, llm_messages: list[dict]): + """ + Generador SSE del turno de chat. Contrato: + data: {"type":"thread","thread_id":"..."}\\n\\n (1 vez, al inicio) + data: {"type":"token","text":"..."}\\n\\n (N veces, deltas del LLM) + data: {"type":"done"}\\n\\n (cierre, siempre se emite) + + Circuit Breaker: el motor (stream_quanti_chat_completion) corre con + read timeout=None, así que una generación larga NUNCA dispara esta + rama por sí sola — solo un fallo real de conexión al servidor GGUF + (is_llm_connection_failure) o un error inesperado del transporte cae + acá. En cualquier caso, la respuesta HTTP ya salió en 200 (SSE), así + que degradamos con un evento 'token' de fallback + 'done' en vez de + intentar levantar un status code a esta altura. + """ + yield f"data: {json.dumps({'type': 'thread', 'thread_id': thread_id})}\n\n" + + full_text = "" + try: + async for delta in stream_quanti_chat_completion(llm_messages): + full_text += delta + yield f"data: {json.dumps({'type': 'token', 'text': delta})}\n\n" + except Exception as exc: # noqa: BLE001 + if is_llm_connection_failure(exc): + print(f"⚠️ Circuit Breaker activado — servidor GGUF inalcanzable (Quanti Chat stream): {describe_llm_failure(exc)}") + else: + print(f"⚠️ Fallo no-conexión en Quanti Chat stream (no se enmascara como servidor caído): {describe_llm_failure(exc)}") + full_text = QUANTI_CHAT_FALLBACK + yield f"data: {json.dumps({'type': 'token', 'text': full_text})}\n\n" + + sanitized = sanitize_llm_output(full_text) + reply = sanitized[0] if sanitized else QUANTI_CHAT_FALLBACK + + try: + _persist_chat_turn(thread_id, prompt, reply) + except Exception as exc: # noqa: BLE001 + # El stream ya se le entregó al usuario completo — un fallo de + # persistencia acá no debe convertirse en un error HTTP a esta + # altura, pero sí queda logueado para no perderlo en silencio. + print(f"⚠️ No se pudo persistir el turno de chat (thread_id={thread_id}): {exc}") + + yield f"data: {json.dumps({'type': 'done'})}\n\n" + + +@router.post("") +async def send_message( + prompt: str = Form(...), + thread_id: str | None = Form(None), + file: UploadFile | None = File(None), + # verify_quota("chat") ya envuelve get_current_user: valida cuota Y + # devuelve el AuthenticatedUser en una sola dependencia. + current_user: AuthenticatedUser = Depends(verify_quota("chat")), +): + prompt = prompt.strip() + if not prompt: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El mensaje no puede estar vacío.") + + # --- Resolver / crear hilo, validando ownership --- + if thread_id: + _verify_thread_ownership(thread_id, current_user.id) + else: + title = prompt[:TITLE_MAX_LEN] + ("…" if len(prompt) > TITLE_MAX_LEN else "") + created = ( + supabase.table("chat_threads") + .insert({"user_id": current_user.id, "title": title}) + .execute() + ) + thread_id = created.data[0]["id"] + + # --- Contexto de archivo adjunto (opcional) --- + file_context = "" + if file is not None: + raw_bytes = await file.read() + if len(raw_bytes) > MAX_FILE_BYTES: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Archivo demasiado grande (máx 5MB).", + ) + try: + df = _read_tabular_file(file.filename or "", raw_bytes) + file_context = f"\n\nCONTEXTO DE ARCHIVO ({file.filename}):\n{_summarize_dataframe(df)}" + except Exception as exc: # noqa: BLE001 + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"No se pudo procesar el archivo: {exc}", + ) + + # --- Historial reciente (últimos HISTORY_TURNS mensajes del hilo) --- + history_result = ( + supabase.table("chat_messages") + .select("role, content") + .eq("thread_id", thread_id) + .order("created_at", desc=True) + .limit(HISTORY_TURNS) + .execute() + ) + recent_history = list(reversed(history_result.data or [])) + + llm_messages = [{"role": "system", "content": CHAT_SYSTEM_PROMPT}] + llm_messages.extend({"role": m["role"], "content": m["content"]} for m in recent_history) + llm_messages.append({"role": "user", "content": prompt + file_context}) + + # Todo lo síncrono (validación, ownership, hilo, archivo, historial) ya + # corrió arriba y puede seguir devolviendo 400/403 normales. De acá en + # más la respuesta es 200 (SSE) sin importar qué pase con el LLM local + # — el Circuit Breaker vive DENTRO del generador, no acá. + return StreamingResponse( + _chat_sse_generator(thread_id, prompt, llm_messages), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache", + "X-Accel-Buffering": "no", # evita que nginx bufferee el stream + "Connection": "keep-alive", + }, + ) \ No newline at end of file diff --git a/api/quota_test_routes.py b/api/quota_test_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..024d7b9801a5b3672ec7510a43a585b97e974e85 --- /dev/null +++ b/api/quota_test_routes.py @@ -0,0 +1,15 @@ +# api/quota_test.py +from fastapi import APIRouter, Depends +from core.quota_manager import verify_quota + +router = APIRouter(prefix="/api", tags=["quota-test"]) + + +@router.post("/test-chat") +async def test_chat(user=Depends(verify_quota("chat"))): + return {"msg": "Acceso permitido"} + + +@router.post("/test-prediction") +async def test_prediction(user=Depends(verify_quota("prediction"))): + return {"msg": "Acceso permitido"} \ No newline at end of file diff --git a/api/support.py b/api/support.py new file mode 100644 index 0000000000000000000000000000000000000000..f5131a9ff7781c0ae097ef67a9eb88983829848b --- /dev/null +++ b/api/support.py @@ -0,0 +1,146 @@ +# api/support.py +""" +Quanti Support — Nivel 1 (chat IA Tier-1) + Nivel 2 (escalación a humano). +Router aislado; se monta en main.py vía app.include_router(support_router). +""" + +import ipaddress +import time +import uuid +from typing import Literal, Optional + +from fastapi import APIRouter, HTTPException, Request +from pydantic import BaseModel, Field + +from core.supabase_client import supabase_admin as _supabase +from services.quanti_engine import generate_quanti_support_reply, is_support_escalation + +router = APIRouter(prefix="/api/support", tags=["support"]) + +# --------------------------------------------------------------------------- +# Anti-spam — rate limit en memoria (1 ticket por IP cada 30 minutos). Vive +# en el proceso: se resetea en cada deploy/restart y NO se comparte entre +# workers si corres > 1 proceso uvicorn/gunicorn. Migrar a Redis si se +# escala horizontalmente. +# --------------------------------------------------------------------------- +_TICKET_COOLDOWN_SECONDS = 30 * 60 +_last_ticket_by_ip: dict[str, float] = {} + + +def _get_client_ip(request: Request) -> str: + """ + request.client.host es la IP de la conexión TCP directa — el cliente NO + puede falsearla. X-Forwarded-For sí lo controla el cliente en su primer + salto (spoofing trivial: mandar un header distinto en cada request rota + el cooldown de 30 min). Por eso ahora es la fuente PRIMARIA, y XFF queda + como fallback validado (solo si viene un formato de IP válido). + """ + if request.client and request.client.host: + return request.client.host + + forwarded = request.headers.get("x-forwarded-for") + if forwarded: + candidate = forwarded.split(",")[0].strip() + try: + ipaddress.ip_address(candidate) + return candidate + except ValueError: + pass + + return "unknown" + + +def _is_rate_limited(ip: str) -> bool: + last = _last_ticket_by_ip.get(ip) + return last is not None and (time.time() - last) < _TICKET_COOLDOWN_SECONDS + + +def _mark_ticket_sent(ip: str) -> None: + _last_ticket_by_ip[ip] = time.time() + + +def _insert_support_ticket(user_ip: str, chat_history: list[dict], user_email: Optional[str]) -> str: + ticket_id = str(uuid.uuid4()) + _supabase.table("koda_support_tickets").insert({ + "id": ticket_id, + "user_ip": user_ip, + "user_email": user_email, + "chat_history": chat_history, + "status": "open", + }).execute() + return ticket_id + + +def _send_escalation_email(ticket_id: str, user_email: Optional[str], chat_history: list[dict]) -> None: + """Placeholder de notificación — listo para smtplib real. Un fallo de + correo nunca debe tumbar el request; el ticket ya quedó en Supabase.""" + try: + # import smtplib + # from email.message import EmailMessage + # msg = EmailMessage() + # msg["Subject"] = f"[KodaQuant] Nuevo ticket de soporte #{ticket_id}" + # msg["From"] = "no-reply@kodaquant.com" + # msg["To"] = "karim.egure@gmail.com" + # msg.set_content(f"Ticket {ticket_id}\nEmail usuario: {user_email}\n\n{chat_history}") + # with smtplib.SMTP(os.getenv("SMTP_HOST"), 587) as server: + # server.starttls() + # server.login(os.getenv("SMTP_USER"), os.getenv("SMTP_PASSWORD")) + # server.send_message(msg) + print(f"📧 [SIMULADO] Ticket #{ticket_id} → karim.egure@gmail.com | usuario: {user_email}") + except Exception as exc: # noqa: BLE001 + print(f"⚠️ No se pudo enviar el correo de escalación (ticket #{ticket_id} ya está en BD): {exc}") + + +_ESCALATION_CONFIRMATION = { + "en": "Thank you. I've escalated this to Karim Estrada (Administrator) — he'll personally reach out to {email} shortly.", + "es": "Gracias. Escalé esto con Karim Estrada (Administrador) — se pondrá en contacto contigo a {email} en breve.", +} + +_RATE_LIMIT_MESSAGE = { + "en": "You already have an open ticket. Karim Estrada will reach out shortly — no need to send another request yet.", + "es": "Ya tienes un ticket abierto. Karim Estrada se pondrá en contacto en breve — no hace falta enviar otra solicitud todavía.", +} + + +class SupportChatMessage(BaseModel): + role: Literal["user", "assistant"] + content: str + + +class SupportChatRequest(BaseModel): + messages: list[SupportChatMessage] = Field(..., min_length=1) + language: Optional[str] = "en" + email: Optional[str] = None + + +@router.post("/chat") +async def support_chat(payload: SupportChatRequest, request: Request): + lang = (payload.language or "en").strip().lower() + lang = lang if lang in ("en", "es") else "en" + + history = [m.model_dump() for m in payload.messages] + reply = await generate_quanti_support_reply(history, language=lang) + + if not is_support_escalation(reply): + return {"status": "ok", "message": reply} + + if not payload.email: + return {"status": "needs_email"} + + client_ip = _get_client_ip(request) + if _is_rate_limited(client_ip): + return {"status": "rate_limited", "message": _RATE_LIMIT_MESSAGE[lang]} + + try: + ticket_id = _insert_support_ticket(client_ip, history, payload.email) + except Exception as exc: + raise HTTPException(status_code=500, detail=f"Error al crear el ticket de soporte: {exc}") + + _mark_ticket_sent(client_ip) + _send_escalation_email(ticket_id, payload.email, history) + + return { + "status": "escalated", + "ticket_id": ticket_id, + "message": _ESCALATION_CONFIRMATION[lang].format(email=payload.email), + } \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..0804c7e950c5e71bdc39d46970c5aa13b1cb88ef --- /dev/null +++ b/app.py @@ -0,0 +1,30 @@ +""" +Entrypoint de Hugging Face Spaces (app_file: app.py). + +ROUND 4 -- FIX del estado zombi "Starting..."/"Building..." permanente en +el dashboard de HF (ver el bloque de comentarios "RONDA 4" en main.py, +junto a `_zerogpu_probe`, para la auditoría completa línea a línea contra +gradio==6.22.0). + +Resumen: `Server.launch()` (rondas 1-3) invocaba `app.launch()` SIN +`app_kwargs`. Internamente, `Blocks.launch()` -> `App.create_app()` +reasigna `app.router.lifespan_context` a partir de +`app_kwargs.get("lifespan")` — nunca del `lifespan=` pasado al +constructor `Server(...)` ni de ningún `@app.on_event("startup")` +registrado antes de `.launch()`. Sin `app_kwargs={"lifespan": lifespan}` +explícito ACÁ, el hook de arranque real (log de "ASGI startup complete" + +warm-up del probe de ZeroGPU) queda descartado en silencio — causa raíz +real de que el hypervisor de HF nunca viera la señal de arranque que +esperaba y el Space quedara colgado en "Starting...". + +`main.app` sigue siendo un `gradio.Server` (FastAPI real que ZeroGPU +reconoce nativamente, ver ROUND 3) — `.launch()` sigue reemplazando al +`uvicorn.run()` manual, maneja el ciclo de vida completo y detecta el +entorno de Spaces automáticamente. Lo único que cambia acá es el +`app_kwargs={"lifespan": lifespan}` explícito. +""" + +from main import app, lifespan + +if __name__ == "__main__": + app.launch(app_kwargs={"lifespan": lifespan}) \ No newline at end of file diff --git a/attention_bilstm_global_best.keras b/attention_bilstm_global_best.keras new file mode 100644 index 0000000000000000000000000000000000000000..3f9c4506382904c10f9d8243c2a6f1fafe6c945a --- /dev/null +++ b/attention_bilstm_global_best.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4184709375c1506a9436a19ee7242386cc7a5c29b6c28bdc342805daf05a34fa +size 1612269 diff --git a/cache/news/headlines_AAPL.json b/cache/news/headlines_AAPL.json new file mode 100644 index 0000000000000000000000000000000000000000..2eb9ca166d1316bc32e88cf298078b18b7b3ab44 --- /dev/null +++ b/cache/news/headlines_AAPL.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Apple (AAPL) Stock Dethrones Nvidia as World's Biggest Company After Tech Rout", "published_at": "2026-10-31T10:02:00+00:00"}, {"title": "Apple (AAPL) Stock: What Wall Street Expects from Earnings Today", "published_at": "2026-11-02T10:15:00+00:00"}, {"title": "'Wait for a $70 Drop,' Says Investor About Apple Stock", "published_at": "2026-11-02T20:46:00+00:00"}, {"title": "Apple (AAPL) stock falls amid market uptick: What investors need to know", "published_at": "2026-10-26T20:45:03+00:00"}, {"title": "Apple Stock (AAPL) Falls as Two Top Analysts Say Sell \u2014 Here's Why", "published_at": "2026-10-20T08:45:00+00:00"}, {"title": "Should You Buy Apple (AAPL) Stock?", "published_at": "2023-09-07T17:32:00+00:00"}, {"title": "Apple Rises 24% YTD: Should You Buy, Sell or Hold the AAPL Stock?", "published_at": "2026-10-08T16:30:00+00:00"}, {"title": "Apple (AAPL) Stock: Slip Despite MacBook Pro Launch With Tandem OLED Display", "published_at": "2026-10-28T22:33:00+00:00"}, {"title": "Apple Stock Has Returned Nearly 1,200% in 10 Years. How High Can AAPL Go From Here?", "published_at": "2026-09-11T18:30:00+00:00"}, {"title": "S&P 500, Nasdaq Futures Rise Premarket After Wall Street's Worst Week In Months: AAPL, PLTR, GOOGL, INTC, TGTX In Focus", "published_at": "2026-11-02T10:30:06+00:00"}], "_cached_at": 1793654542.650172} \ No newline at end of file diff --git a/cache/news/headlines_AMZN.json b/cache/news/headlines_AMZN.json new file mode 100644 index 0000000000000000000000000000000000000000..edffc01a2f41cfe9b3e6b2c2d687ce0fe45b2b5c --- /dev/null +++ b/cache/news/headlines_AMZN.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Amazon stock rises: What's going on?", "published_at": "2026-10-30T21:22:32+00:00"}, {"title": "Ahead of Amazon earnings, here's what Barchart data says comes next for AMZN stock", "published_at": "2026-10-28T21:22:32+00:00"}, {"title": "Where Will Amazon Stock Be In 5 Years?", "published_at": "2025-04-09T06:00:00+00:00"}, {"title": "Amazon Stock Slides After Q3 Earnings Miss Despite Strong Cloud Growth", "published_at": "2026-10-30T21:22:32+00:00"}, {"title": "Amazon stock: Wall Street says AMZN looks increasingly attractive ahead of Q3 earnings", "published_at": "2026-10-27T21:22:32+00:00"}, {"title": "Amazon (AMZN) stock costs $250 a share. Here's why I'd still buy it.", "published_at": "2026-10-19T06:00:00+00:00"}, {"title": "Biggest stock movers Monday: KOS, INO, LITE, AMZN, and more", "published_at": "2026-10-27T21:22:32+00:00"}, {"title": "Amazon (AMZN) Q3 2026 earnings results miss EPS and revenue expectations", "published_at": "2026-10-29T21:22:32+00:00"}, {"title": "Amazon earnings are out and the stock is dropping. Here's what to know.", "published_at": "2026-10-29T21:22:32+00:00"}, {"title": "Amazon (AMZN) Stock Slips As Q3 Earnings Reflect Profit Reset", "published_at": "2026-10-31T21:22:32+00:00"}], "_cached_at": 1793654552.422573} \ No newline at end of file diff --git a/cache/news/headlines_BTC-USD.json b/cache/news/headlines_BTC-USD.json new file mode 100644 index 0000000000000000000000000000000000000000..4d42e207fd107c351ea63aee9d76a8874d5731b7 --- /dev/null +++ b/cache/news/headlines_BTC-USD.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "'Be Careful'\u2014Binance Founder Issues Stark Warning As Bitcoin And Crypto Brace For 'Real' Price Test", "published_at": "2026-11-02T13:43:00+00:00"}, {"title": "Elon Musk Issues Serious Hack Warning Amid Bitcoin And Crypto Price Crash Fear", "published_at": "2026-11-01T13:58:00+00:00"}, {"title": "South Korea Just Told Exchanges to Keep More Crypto Offline. Should You Do the Same?", "published_at": "2026-11-02T19:07:00+00:00"}, {"title": "Why Bitcoin shrugged off the largest crypto hack ever", "published_at": "2026-10-30T20:36:50+00:00"}, {"title": "Blockstream moves 300 BTC into Liquid, cutting reserve shortfall to 250 BTC", "published_at": "2026-11-02T22:29:00+00:00"}, {"title": "Crypto Market Today, Oct. 30: Bitcoin Tests Key Support as Binance Hack and Tech Sell-Off Rattle Markets", "published_at": "2026-10-30T21:50:00+00:00"}, {"title": "Crypto Hack Losses Hit $8.74 in 2026, More Than Triple 2025, Yet Without Binance the Year Ran Quieter: How Did Bitcoin and Ethereum React After Major Hacks?", "published_at": "2026-11-02T13:10:00+00:00"}, {"title": "Bitcoin hits highest level since January at $86,000, as the market debates whether the 'crypto winter' is over", "published_at": "2026-09-21T11:10:00+00:00"}, {"title": "Bitcoin (BTC) Price: Falls Below $80,000 as Tech Selloff and Hawkish Fed Hold Weigh on Crypto", "published_at": "2026-10-29T05:38:00+00:00"}, {"title": "Crypto Liquidations Reach $400 Million as Binance Hack Pressures Bitcoin, Ethereum and Solana", "published_at": "2026-10-31T07:33:00+00:00"}], "_cached_at": 1793661244.999389} \ No newline at end of file diff --git a/cache/news/headlines_ETH-USD.json b/cache/news/headlines_ETH-USD.json new file mode 100644 index 0000000000000000000000000000000000000000..1dcf9dbd23c1b51a5bb4ba1767c542520a95eb7f --- /dev/null +++ b/cache/news/headlines_ETH-USD.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Bitmine Buys Another 8,573 ETH, Pushes Ethereum Holdings Past $13.7B", "published_at": "2026-10-27T23:14:24+00:00"}, {"title": "Ethereum Analysis: Exchanges Took In 100,000 ETH This Week as Big Holders Sold. Is $2,000 Next?", "published_at": "2026-10-29T23:14:24+00:00"}, {"title": "Bitmine Slows to 8,573 ETH Buy as Tom Lee Downplays Binance Hack", "published_at": "2026-10-25T23:14:24+00:00"}, {"title": "Ethereum Price Prediction: Can ETH Get Back to $3,000 Before the End of 2026?", "published_at": "2026-10-18T06:00:00+00:00"}, {"title": "Strive adds 124 BTC, BitMine 8,573 ETH as buybacks take over", "published_at": "2026-10-29T23:14:24+00:00"}, {"title": "OpenAI Proves ETH Is False, and Crypto Twitter Has Questions", "published_at": "2026-10-27T23:14:24+00:00"}, {"title": "Coinbase, Robinhood and other crypto exchange stocks tumble as Binance hack exposes vulnerabilities", "published_at": "2026-10-31T23:14:24+00:00"}, {"title": "$106 Million Crypto Theft Hits EU Entity With Multiple Exchange Accounts", "published_at": "2026-10-26T23:14:24+00:00"}, {"title": "6 best crypto exchanges of November 2026", "published_at": "2026-10-25T23:14:24+00:00"}], "_cached_at": 1793661264.7769878} \ No newline at end of file diff --git a/cache/news/headlines_GOOGL.json b/cache/news/headlines_GOOGL.json new file mode 100644 index 0000000000000000000000000000000000000000..3f4f046f70d24cce13eacad1f4d8e56f8591dd7f --- /dev/null +++ b/cache/news/headlines_GOOGL.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Alphabet Stock Breaks Down Ahead of Q3 Earnings: Could GOOGL Fall 30%?", "published_at": "2026-10-27T21:22:30+00:00"}, {"title": "SA asks: Is Alphabet's stock a buy after the sell-off?", "published_at": "2026-10-29T21:22:30+00:00"}, {"title": "GOOGL Tumbles Over 10% Premarket: Analyst Says Investors Underappreciate Alphabet\u2019s AI Strength", "published_at": "2026-10-29T21:22:30+00:00"}, {"title": "GOOG Stock On Track To Erase Over $600B In Market Value In A Month \u2014 Analysts Flag Search Slowdown, Margin Pressure", "published_at": "2026-10-29T21:22:30+00:00"}, {"title": "GOOGL stock earnings preview: What to expect from Alphabet\u2019s Q3 2026 report", "published_at": "2026-10-20T21:22:30+00:00"}, {"title": "Alphabet (GOOGL) Stock Drops 9% Even as Google Cloud Revenue Doubles", "published_at": "2026-10-29T21:22:30+00:00"}, {"title": "Alphabet Inc. Q3 2026 earnings: Live updates of $GOOGL earnings call, stock forecast", "published_at": "2026-10-28T21:22:30+00:00"}, {"title": "Buy, Sell, or Hold Alphabet Stock After Its $505 Billion Meltdown?", "published_at": "2026-10-25T21:22:30+00:00"}, {"title": "GOOG and GOOGL Legal Notice: Alphabet Investors are Notified to Contact BFA Law Before the Expiration of December 1 Deadline in the Securities Class Action", "published_at": "2026-10-12T21:22:30+00:00"}, {"title": "3 Reasons to Buy Alphabet Stock Right Now", "published_at": "2026-10-27T21:22:30+00:00"}], "_cached_at": 1793654550.4764748} \ No newline at end of file diff --git a/cache/news/headlines_META.json b/cache/news/headlines_META.json new file mode 100644 index 0000000000000000000000000000000000000000..22db54300d725b843cdc8f037acf717a1c5c21d9 --- /dev/null +++ b/cache/news/headlines_META.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Meta Stocks Edge Lower 0.06% With UK Inquiry Challenging Its AI", "published_at": "2026-11-02T18:22:34+00:00"}, {"title": "What Are Wall Street Analysts' Target Price for Meta Platforms Stock?", "published_at": "2026-11-02T12:22:34+00:00"}, {"title": "Meta Is Reportedly Looking To Tap Cross-Border Dollar, Euro Bond Market In Capex...", "published_at": "2026-11-02T19:22:34+00:00"}, {"title": "Meta\u2019s Unusual Stock Split Comes With a $60 Billion Twist Investors Should Know ...", "published_at": "2026-10-29T21:22:34+00:00"}, {"title": "What Is Going On With Meta Platforms Stock on Monday?", "published_at": "2026-11-02T15:22:34+00:00"}, {"title": "Meta Settles Another Lawsuit Over Being Addictive As Legal Reckoning Continues....", "published_at": "2026-11-02T20:22:34+00:00"}, {"title": "Meta reportedly weighs $20B bond sale, its first in euros", "published_at": "2026-11-02T18:22:34+00:00"}, {"title": "Meta (META) Draws Fresh Heat As AI Spending Bites And Lobbying Team Grows", "published_at": "2026-11-02T18:22:34+00:00"}, {"title": "Here\u2019s Why Janus Henderson is Bullish On Meta Platforms, Inc. (META)", "published_at": "2026-11-02T20:22:34+00:00"}], "_cached_at": 1793654554.514085} \ No newline at end of file diff --git a/cache/news/headlines_MSFT.json b/cache/news/headlines_MSFT.json new file mode 100644 index 0000000000000000000000000000000000000000..acc2676cf704942814ac558841de09644ee6bfce --- /dev/null +++ b/cache/news/headlines_MSFT.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "MSFT stock eyes best day in over 3 months after earnings beat \u2014 Gene Munster says software is alive and well, at least for now", "published_at": "2026-10-29T21:22:24+00:00"}, {"title": "Microsoft delivered a beat on both earnings and revenue. Here\u2019s how to think about MSFT stock now.", "published_at": "2026-11-01T21:22:24+00:00"}, {"title": "Microsoft Corp Q1 2027 earnings: Live updates of $MSFT earnings call, stock forecast", "published_at": "2026-10-28T21:22:24+00:00"}, {"title": "MSFT stock alert: What to know as Microsoft offers buyouts to 60,000 employees", "published_at": "2026-10-27T21:22:24+00:00"}, {"title": "1 reason to buy Microsoft stock for 10 years", "published_at": "2026-11-01T21:22:24+00:00"}, {"title": "How much MSFT stock does former CEO Steve Ballmer actually own?", "published_at": "2026-10-24T21:22:24+00:00"}, {"title": "MSFT stock gains 3% after-hours as AI demand powers Q1 cloud revenue, Q2 guidance beat with positive cash flows", "published_at": "2026-10-29T21:22:24+00:00"}, {"title": "Microsoft earnings give the stock a boost. Here are the highlights.", "published_at": "2026-10-28T21:22:24+00:00"}, {"title": "Microsoft stock is going higher from here, says Jefferies' Brent Thill", "published_at": "2026-10-28T21:22:24+00:00"}], "_cached_at": 1793654544.6091762} \ No newline at end of file diff --git a/cache/news/headlines_NVDA.json b/cache/news/headlines_NVDA.json new file mode 100644 index 0000000000000000000000000000000000000000..948c9d8942422c3691eb423c344749103034110a --- /dev/null +++ b/cache/news/headlines_NVDA.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Will Nvidia (NVDA) Beat Estimates Again in Its Next Earnings Report?", "published_at": "2026-11-02T16:22:26+00:00"}, {"title": "Nvidia Stocks Rise 1.7% With Rubin Specification Gap Shifting Fo", "published_at": "2026-11-02T18:22:26+00:00"}, {"title": "NVDA DCF Analysis: Intrinsic Value $239 vs Price $205", "published_at": "2026-11-02T12:22:26+00:00"}, {"title": "Indian Trading Apps Are Offering Access to U.S. Stocks. Why That\u2019s Huge News for...", "published_at": "2026-11-01T21:22:26+00:00"}, {"title": "The Intel stock collapse is getting worse \u2014 and the $3.5 trillion chip rout is s...", "published_at": "2026-11-02T20:41:26+00:00"}, {"title": "ETFs Are Net Sellers of NVIDIA (NVDA) on Oct. 29", "published_at": "2026-11-02T11:22:26+00:00"}, {"title": "NVDA stock alert: What to know as Nvidia invests $3 billion in Meta", "published_at": "2026-10-28T21:22:26+00:00"}, {"title": "My top 3 AI stock picks for November", "published_at": "2026-10-26T21:22:26+00:00"}, {"title": "NVIDIA Corporation (NVDA) is attracting investor attention: Here is what you should know", "published_at": "2026-10-30T21:22:26+00:00"}, {"title": "Indian trading apps are offering access to US stocks. Why that\u2019s huge news for Nvidia stock.", "published_at": "2026-11-01T21:22:26+00:00"}], "_cached_at": 1793654546.486468} \ No newline at end of file diff --git a/cache/news/headlines_SPY.json b/cache/news/headlines_SPY.json new file mode 100644 index 0000000000000000000000000000000000000000..1ad2ee0325ba89c1324a60faa9652fb82e83f34a --- /dev/null +++ b/cache/news/headlines_SPY.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "How To Trade SPY, QQQ, And Top Tech Stocks Using Technical Analysis", "published_at": "2026-11-02T19:22:36+00:00"}, {"title": "SPDR S&P 500 ETF (SPY) Sells NVIDIA and Apple on Oct. 29", "published_at": "2026-11-02T11:22:36+00:00"}, {"title": "William Blair refreshes stock Conviction List with 5 additions, 3 removals...", "published_at": "2026-11-02T14:22:36+00:00"}, {"title": "SPY Stock Price Today | CoinDesk", "published_at": "2026-10-30T21:22:36+00:00"}, {"title": "Strong Buy at under $10: The highest Quant-rated bargain stocks right now...", "published_at": "2026-11-02T11:22:36+00:00"}, {"title": "October delivers S&P 500 equal-weight stocks' biggest outperformance since 2009...", "published_at": "2026-11-02T16:22:36+00:00"}, {"title": "Stock Market: Will S&P 500 Open Up or Down Today?", "published_at": "2026-11-02T05:22:36+00:00"}, {"title": "Cyberattack Disrupts European Grocery Chains Amid SPY ETF Market", "published_at": "2026-11-02T14:22:36+00:00"}, {"title": "Pantheon Macroeconomics Projects Strong U.S. Job Growth, SPY Ref", "published_at": "2026-11-02T14:22:36+00:00"}, {"title": "Trump Warns of a \u20181929-Style Economic Depression\u2019 Ahead of the Midterms. The S&P...", "published_at": "2026-11-02T15:22:36+00:00"}], "_cached_at": 1793654556.353747} \ No newline at end of file diff --git a/cache/news/headlines_TSLA.json b/cache/news/headlines_TSLA.json new file mode 100644 index 0000000000000000000000000000000000000000..2bcd463ef21c590f48338760b709f6d5fcbc7fd9 --- /dev/null +++ b/cache/news/headlines_TSLA.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Are Wall Street analysts bullish on Tesla stock?", "published_at": "2026-10-30T21:22:28+00:00"}, {"title": "Ahead of Tesla earnings, here's what Barchart data says comes next for TSLA stock", "published_at": "2026-10-20T21:22:28+00:00"}, {"title": "Buy, hold or sell TSLA stock? Key tips ahead of Q3 earnings", "published_at": "2026-10-19T06:00:00+00:00"}, {"title": "Tesla robotaxi adds this new city, stock continues rally", "published_at": "2026-10-16T21:22:28+00:00"}, {"title": "TSLA stock trades flat after hours following drop in Q3 revenue, earnings, and heavy AI spending", "published_at": "2026-10-21T21:22:28+00:00"}, {"title": "TSLA stock is October\u2019s Mag 7 king \u2014 but 2 motorcycle stocks race past Tesla even as Chinese EV stocks see red", "published_at": "2026-10-28T21:22:28+00:00"}, {"title": "TSLA Analyst Ratings Hit Highest Since 2023; ARK Reiterates $4,400 Long-Term Price Target And 80% Robotaxi Thesis", "published_at": "2026-10-27T21:22:28+00:00"}, {"title": "Gary Black predicts SPCX to offer $420 per share for TSLA in a stock-for-stock deal, calls Tesla-SpaceX merger inevitable", "published_at": "2026-10-20T21:22:28+00:00"}, {"title": "TSLA stock rises overnight: Cybercabs swarm Austin F1, fresh Roadster details surface \u2014 but analyst sees 38% downside", "published_at": "2026-10-26T21:22:28+00:00"}, {"title": "TSLA stock heads for worst day in nearly 7 weeks \u2013 Goldman Sachs flags two key factors likely to pressure Tesla\u2019s profitability", "published_at": "2026-10-22T21:22:28+00:00"}], "_cached_at": 1793654548.70504} \ No newline at end of file diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/core/config.py b/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9fba3356be2e773e8dd0f3f8f435cf57e3e015f3 --- /dev/null +++ b/core/config.py @@ -0,0 +1,92 @@ +# core/config.py + +from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic import field_validator +from functools import lru_cache + + +class Settings(BaseSettings): + """ + Configuración central de KodaQuant Terminal. + Lee variables de entorno desde el archivo .env en la raíz del proyecto. + """ + + # --- Supabase --- + SUPABASE_URL: str + SUPABASE_KEY: str + SUPABASE_SERVICE_ROLE_KEY: str + SUPABASE_JWT_SECRET: str | None = None + + # --- Stripe --- + STRIPE_SECRET_KEY: str + STRIPE_PRICE_PRO: str + STRIPE_PRICE_ULTRA: str + STRIPE_WEBHOOK_SECRET: str + STRIPE_SUCCESS_URL: str + STRIPE_CANCEL_URL: str + + # --- Seguridad interna (firma de tokens JWT/HMAC) --- + API_SECRET_KEY: str + + # --- Rate limiting anti fuerza bruta (auth) --- + RATE_LIMIT_MAX_ATTEMPTS: int = 5 + RATE_LIMIT_WINDOW_SECONDS: int = 60 + + # --- Configuración general opcional --- + APP_NAME: str = "KodaQuant Terminal" + ENV: str = "development" + DEBUG: bool = False + + # FIX DEFINITIVO: dominio kodaquant.site verificado en Resend, sandbox + # desactivado. Se abandona SMTP directo por completo (bloqueado a nivel + # de firewall en HF Spaces -- ver historial) a favor del SDK oficial + # `resend` (ver core/security.py). Las variables SMTP_HOST/PORT/ + # USE_SSL/USER/PASSWORD de las iteraciones anteriores ya no existen acá + # -- no se usan en ningún lado del código. + # + # Techo duro (segundos) para la llamada del SDK de Resend, corrida en + # thread vía asyncio.to_thread (ver core/security.py::_send_mail_message). + # El envío corre como FastAPI BackgroundTask -- no bloquea la respuesta + # al cliente -- así que 15s da margen real sin arriesgar tareas colgadas + # indefinidamente. + SMTP_TIMEOUT_SECONDS: float = 15.0 + # API key de Resend (https://resend.com/api-keys). Obligatoria para que + # el envío de correo funcione -- sin ella, se loguea un warning y el + # correo simplemente no sale (no rompe el registro/login). + RESEND_API_KEY: str | None = None + # Remitente verificado. Dominio kodaquant.site ya validado por DNS en + # Resend -- puede enviar a cualquier destinatario, no solo al sandbox. + SMTP_FROM: str = "KodaQuant " + # Si un usuario responde un correo automático, llega acá en vez de a + # no-reply@kodaquant.site (que nadie lee). + REPLY_TO_EMAIL: str = "karim.egure@gmail.com" + FRONTEND_URL: str = "https://kodaquant.site" + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + case_sensitive=True, + extra="ignore", + ) + + # Defensa contra espacios accidentales al pegar valores en .env o en el + # panel de variables de entorno del hosting (ej. "FRONTEND_URL= https://..."). + # Un espacio colado acá rompe el matching exacto de origen en CORS + # (Starlette compara el header Origin contra el string tal cual) y + # generaría URLs rotas en los links de los correos de verificación. + @field_validator("FRONTEND_URL", "SUPABASE_URL", mode="before") + @classmethod + def _strip_whitespace(cls, v: str) -> str: + return v.strip() if isinstance(v, str) else v + + +@lru_cache +def get_settings() -> Settings: + """ + Devuelve una instancia cacheada de Settings para evitar + releer el .env en cada request. + """ + return Settings() + + +settings = get_settings() \ No newline at end of file diff --git a/core/quota_manager.py b/core/quota_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ede260b294b5fdf44ab534422804d6e28eb2e9 --- /dev/null +++ b/core/quota_manager.py @@ -0,0 +1,142 @@ +# core/quota_manager.py +""" +Aduana de cuotas para KodaQuant Terminal. +Verifica y consume cuota de servicios (predicciones / chat Quanti) según +el tier de suscripción, delegando el estado persistente a Supabase. + +Ciclos: + - FREE predicciones: reinicio diario (cron externo ya existente, + fuera del alcance de este módulo). + - FREE / PRO chat y PRO predicciones: reinicio cada 14 días vía + `current_period_end` (pg_cron, ver migrations/quota_migration.sql). + - ULTRA: sin límites, bypass total (no se leen ni consumen contadores). +""" +from datetime import datetime, timedelta, timezone +from fastapi import Depends, HTTPException, status +from postgrest.exceptions import APIError +from core.security import get_current_user, AuthenticatedUser +from core.supabase_client import supabase_admin + +LIMITS = { + "prediction": {"FREE": 3, "PRO": 50}, + "chat": {"FREE": 1, "PRO": 100}, +} + +DEFAULT_PROFILE_FIELDS = { + "subscription_tier": "FREE", + "api_requests_count": 0, + "period_predictions_used": 0, + "quanti_chat_used": 0, +} + +# Cada (service_type, tier) apunta a la columna de Supabase que lleva su contador. +COUNTER_COLUMN = { + "prediction": {"FREE": "api_requests_count", "PRO": "period_predictions_used"}, + "chat": {"FREE": "quanti_chat_used", "PRO": "quanti_chat_used"}, +} + +PROFILE_SELECT_FIELDS = ( + "subscription_tier, api_requests_count, period_predictions_used, " + "quanti_chat_used, current_period_end" +) + +# Ventana rodante de 14 días. Aplica a period_predictions_used y +# quanti_chat_used (PRO predicciones + FREE/PRO chat). NO aplica a +# api_requests_count (FREE predicciones = reinicio diario, cron externo, +# fuera del alcance de este módulo). +QUOTA_PERIOD = timedelta(days=14) + + +def _parse_utc(value: str | None) -> datetime | None: + if not value: + return None + try: + dt = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc) + + +def _format_reset_date(current_period_end: str | None) -> str: + if not current_period_end: + return "próximamente" + try: + dt = datetime.fromisoformat(current_period_end) + return dt.strftime("%d/%m/%Y %H:%M UTC") + except ValueError: + return "próximamente" + + +def verify_quota(service_type: str): + """ + Factory de dependencia FastAPI. + + Uso: + @router.post("/predict", dependencies=[Depends(verify_quota("prediction"))]) + async def predict(...): ... + """ + if service_type not in LIMITS: + raise ValueError(f"service_type inválido: {service_type!r}") + + async def _dependency( + current_user: AuthenticatedUser = Depends(get_current_user), + ) -> AuthenticatedUser: + try: + result = ( + supabase_admin.table("profiles") + .select(PROFILE_SELECT_FIELDS) + .eq("id", current_user.id) + .maybe_single() + .execute() + ) + profile = result.data if result else None + except APIError: + profile = None + + if not profile: + # Sin insert/upsert: evita el 42501 del cliente anon/user-scoped. + # Se asume perfil FREE con 0 usos; el UPDATE posterior sobre una + # fila inexistente es un no-op silencioso (no rompe el flujo). + profile = {"id": current_user.id, **DEFAULT_PROFILE_FIELDS} + + tier = (profile.get("subscription_tier") or "FREE").upper() + + # ULTRA: bypass total. Ni siquiera se toca la tabla. + if tier == "ULTRA": + return current_user + + if tier not in LIMITS[service_type]: + tier = "FREE" # Tier desconocido -> tratar como FREE por seguridad. + + limit = LIMITS[service_type][tier] + column = COUNTER_COLUMN[service_type][tier] + current_count = profile.get(column) or 0 + + # Ventana rodante de 14 días, forzada en Python (no depende solo del + # pg_cron externo). Si current_period_end no existe o ya venció, + # se resetea el contador YA, antes de evaluar el límite. + if column != "api_requests_count": + period_end = _parse_utc(profile.get("current_period_end")) + now_utc = datetime.now(timezone.utc) + if period_end is None or now_utc >= period_end: + new_period_end = now_utc + QUOTA_PERIOD + supabase_admin.table("profiles").update( + {column: 0, "current_period_end": new_period_end.isoformat()} + ).eq("id", current_user.id).execute() + current_count = 0 + profile["current_period_end"] = new_period_end.isoformat() + + if current_count >= limit: + reset_label = _format_reset_date(profile.get("current_period_end")) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"Límite alcanzado, reinicio en {reset_label}", + ) + + supabase_admin.table("profiles").update( + {column: current_count + 1} + ).eq("id", current_user.id).execute() + + return current_user + + return _dependency \ No newline at end of file diff --git a/core/rate_limiter.py b/core/rate_limiter.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb2503cec02800ccd48bedbd724fcbf5b4592ea --- /dev/null +++ b/core/rate_limiter.py @@ -0,0 +1,45 @@ +# core/rate_limiter.py +""" +Rate limiter en memoria (sliding window) para mitigar fuerza bruta en +/register y /login. Sin dependencias externas, sin estado compartido entre +procesos -- válido para un solo worker. Si se escala a múltiples +workers/instancias, migrar la key a Redis (INCR + EXPIRE) manteniendo la +misma firma de `enforce_rate_limit`. +""" +import time +from collections import defaultdict +from threading import Lock + +from fastapi import HTTPException, Request, status + +from core.config import settings + +_attempts: dict[str, list[float]] = defaultdict(list) +_lock = Lock() + + +def _client_ip(request: Request) -> str: + forwarded = request.headers.get("x-forwarded-for") + if forwarded: + return forwarded.split(",")[0].strip() + return request.client.host if request.client else "unknown" + + +async def enforce_rate_limit(request: Request, bucket: str) -> None: + """Lanza 429 si `bucket:ip` excede el límite en la ventana configurada.""" + key = f"{bucket}:{_client_ip(request)}" + now = time.time() + window = settings.RATE_LIMIT_WINDOW_SECONDS + max_attempts = settings.RATE_LIMIT_MAX_ATTEMPTS + + with _lock: + timestamps = [t for t in _attempts[key] if now - t < window] + if len(timestamps) >= max_attempts: + retry_after = int(window - (now - timestamps[0])) + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail="Demasiados intentos. Intenta de nuevo más tarde.", + headers={"Retry-After": str(max(retry_after, 1))}, + ) + timestamps.append(now) + _attempts[key] = timestamps \ No newline at end of file diff --git a/core/security.py b/core/security.py new file mode 100644 index 0000000000000000000000000000000000000000..1837eb04bf64f09758ddc6cfec1fd1dfc088ae20 --- /dev/null +++ b/core/security.py @@ -0,0 +1,564 @@ +# core/security.py +""" +Autenticación de producción para KodaQuant Terminal. +Valida el JWT de Supabase delegando la verificación criptográfica al propio +backend de Supabase Auth (GoTrue) vía `supabase.auth.get_user()`. No existe +bypass de desarrollo. +""" +import secrets +import traceback +import httpx +from core.config import settings +from datetime import datetime, timedelta, timezone +from fastapi import Depends, HTTPException, Request, status +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from fastapi.responses import JSONResponse +from pydantic import BaseModel +from starlette.middleware.base import BaseHTTPMiddleware +from core.supabase_client import supabase, supabase_admin + +# --- CORS: lista cerrada de orígenes de producción --- +# NUNCA usar "*" aquí: Starlette lo rechaza en runtime cuando +# allow_credentials=True, y aunque no lo hiciera, "*" + credentials abre la +# puerta a CSRF cross-origin contra cualquier endpoint autenticado +# (/api/v1/quanti/consult, /api/v1/auth/*, payments). Solo se listan +# orígenes explícitos y verificados. +PRODUCTION_ORIGINS = { + "https://kodaquant.site", # Firebase Hosting (dominio primario) + "https://kodaquant.site", # Firebase Hosting (dominio secundario, mismo proyecto) +} + +# Puertos reales del dev server (Vite), tomados de la config actual del +# proyecto -- NO 3000 (eso es el puerto default de Create React App / Next, +# que este repo no usa). Agregar un origen que nadie sirve no protege nada +# y agregar uno que falta rompe el login en local. +_DEV_ORIGINS = { + "http://localhost:5173", "http://127.0.0.1:5173", + "http://localhost:5174", "http://127.0.0.1:5174", +} + +# Métodos y headers reales que usan los endpoints (fetch/EventSource desde +# App.jsx + Authorization Bearer del login Supabase). "*" en methods/headers +# es innecesario aquí y amplía la superficie de ataque sin motivo. +ALLOWED_METHODS = ["GET", "POST", "OPTIONS"] +ALLOWED_HEADERS = ["Authorization", "Content-Type"] + + +def get_allowed_origins() -> list[str]: + """ + Orígenes permitidos por CORS. + + - Producción (settings.ENV == "production"): SOLO los dominios de + Firebase Hosting + settings.FRONTEND_URL. Los orígenes de localhost + jamás se incluyen en este modo. + - Cualquier otro valor de settings.ENV (dev/staging): se añaden también + los orígenes del dev server local. + + IMPORTANTE: `ENV` en core/config.py tiene default "development". Si el + deploy de producción no exporta explícitamente ENV=production en su + entorno, este backend seguirá aceptando peticiones con credenciales + desde localhost. Confirmar esa variable en la config del servidor + (Railway/Render/Fly/EC2/lo que uses) -- esto NO es opcional para que el + lockdown de CORS sea real. + """ + origins = set(PRODUCTION_ORIGINS) + if getattr(settings, "FRONTEND_URL", None): + origins.add(settings.FRONTEND_URL.strip()) + + if settings.ENV.strip().lower() != "production": + origins |= _DEV_ORIGINS + + return sorted(origins) + + +# --------------------------------------------------------------------------- +# FIX CRÍTICO — CORS bypass real en producción vía gradio.Server +# --------------------------------------------------------------------------- +# ROOT CAUSE (confirmado leyendo gradio/route_utils.py::CustomCORSMiddleware +# en gradio==6.22.0 y reproducido en vivo, no es una hipótesis): +# +# Server.launch() -> Blocks.launch() -> App.create_app() SIEMPRE ejecuta +# app.add_middleware(CustomCORSMiddleware, strict_cors=strict_cors) +# +# ...DESPUÉS de que main.py ya agregó nuestro CORSMiddleware. En Starlette, +# add_middleware() inserta al frente de la pila (`user_middleware.insert(0, +# ...)`), así que el middleware de Gradio, agregado más tarde (en +# .launch()), termina SIEMPRE por FUERA del nuestro -- procesa cada +# request antes que el nuestro y puede reescribir la respuesta después. +# +# Su lógica interna (is_valid_origin) SOLO restringe origenes cuando el +# Host de la request es localhost/127.0.0.1/0.0.0.0 (para proteger demos +# corriendo en la laptop del dev). En cualquier deploy real -- este caso, +# *.hf.space -- esa condición nunca aplica, así que Gradio termina +# agregando `Access-Control-Allow-Origin: ` + +# `Access-Control-Allow-Credentials: true` a CUALQUIER origen, y además +# contesta TODO el preflight (OPTIONS) él mismo -- nuestro CORSMiddleware +# (con su ALLOWED_METHODS/ALLOWED_HEADERS restringido) nunca llega a +# correr para el preflight. `PRODUCTION_ORIGINS` de arriba queda +# decorativo en producción. Verificado en vivo: una request con +# `Origin: https://evil-attacker.com` contra un server con Host no-local +# recibe `Access-Control-Allow-Origin: https://evil-attacker.com` de +# vuelta. +# +# No hay manera de "ganarle" la posición a Gradio en la pila de +# middleware -- SIEMPRE se agrega después, en .launch(), sin importar el +# orden en main.py. La única defensa real es no depender de qué headers +# CORS termine poniendo esa capa, y en cambio RECHAZAR nosotros mismos, +# a nivel aplicación, cualquier request de un Origin no reconocido -- +# esto SÍ es efectivo pase lo que pase después en la respuesta, porque el +# request nunca llega al router si lo cortamos acá. +# +# Nota de alcance: como este backend NO usa cookies para auth (el JWT de +# Supabase viaja en el header Authorization, nunca en una cookie), esto +# no es un CSRF clásico explotable por un sitio malicioso ajeno -- pero +# sí anula la protección que el equipo cree tener, y cualquier +# dependencia futura en cookies o en "Origin como control de acceso" +# quedaría rota. Corregir de todos modos. +class StrictOriginMiddleware(BaseHTTPMiddleware): + """ + Rechaza (403) cualquier request con un header Origin presente que NO + esté en la lista cerrada de `get_allowed_origins()`. Se evalúa en cada + request (no cachea la lista), así que respeta el mismo ENV en runtime + que ve `get_allowed_origins()`. + + Requests SIN header Origin (curl, llamadas server-to-server, health + checks del propio hosting) pasan de largo -- Origin solo lo manda un + navegador haciendo fetch/XHR cross-origin. + """ + + async def dispatch(self, request: Request, call_next): + origin = request.headers.get("origin") + if origin is not None and origin not in set(get_allowed_origins()): + return JSONResponse( + {"detail": "Origen no permitido."}, + status_code=status.HTTP_403_FORBIDDEN, + ) + return await call_next(request) + + +# auto_error=False es la pieza clave: si el header falta o está mal formado, +# HTTPBearer devuelve None en lugar de lanzar su propio HTTPException(403). +# Así TODO el manejo de errores de auth pasa por get_current_user y responde +# 401 de forma consistente -- nunca más un 403 "silencioso" que evita +# nuestro try/except. +security_scheme = HTTPBearer(auto_error=False) + + +class AuthenticatedUser(BaseModel): + """Identidad resuelta a partir del usuario verificado por Supabase Auth.""" + id: str + email: str | None = None + role: str | None = None + + +async def get_current_user( + credentials: HTTPAuthorizationCredentials | None = Depends(security_scheme), +) -> AuthenticatedUser: + if credentials is None or not credentials.credentials: + print("[AUTH] Falta el header Authorization o no tiene el esquema 'Bearer '.") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token inválido o expirado", + ) + + # credentials.credentials YA es el JWT puro (HTTPBearer separa el esquema + # "Bearer" del token). Este strip extra es cinturón de seguridad por si + # el cliente concatena mal el header -- en condiciones normales es un no-op. + raw_token = credentials.credentials.strip() + if raw_token.lower().startswith("bearer "): + raw_token = raw_token[7:].strip() + + try: + response = supabase.auth.get_user(raw_token) + except Exception as exc: + print(f"Error Supabase: {exc}") + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token inválido o expirado", + ) + + user = getattr(response, "user", None) + if user is None or getattr(user, "id", None) is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token inválido o expirado", + ) + + return AuthenticatedUser( + id=user.id, + email=getattr(user, "email", None), + role=getattr(user, "role", None), + ) + + +async def verify_api_credits( + current_user: AuthenticatedUser = Depends(get_current_user), +) -> AuthenticatedUser: + result = ( + supabase_admin.table("profiles") + .select("subscription_tier, api_requests_count") + .eq("id", current_user.id) + .single() + .execute() + ) + profile = result.data + if not profile: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Perfil no encontrado", + ) + + tier = profile.get("subscription_tier") + if tier == "FREE": + current_count = profile.get("api_requests_count", 0) + if current_count >= 3: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Límite de solicitudes alcanzado para el plan FREE", + ) + supabase_admin.table("profiles").update( + {"api_requests_count": current_count + 1} + ).eq("id", current_user.id).execute() + + return current_user + + +# --------------------------------------------------------------------------- +# FIX DEFINITIVO — SMTP directo abandonado, migrado a API HTTPS (Resend) +# --------------------------------------------------------------------------- +# ROOT CAUSE real (confirmado con el traceback del segundo fallo): el +# TimeoutError NO ocurre en el handshake TLS -- ocurre antes, dentro de +# `aiosmtplib.smtp._create_connection` -> `asyncio.wait_for(connect_coro)`. +# Es decir, el `CancelledError`/`TimeoutError` salta al intentar abrir la +# conexión TCP misma, nunca llega a mandar un solo byte. Con 587 (STARTTLS) +# colgaba igual y con 465 (SSL implícito, ya corregido en la iteración +# anterior) cuelga exactamente igual: la variable en común no es el modo +# TLS, es que Hugging Face Spaces filtra a nivel de firewall de red TODO el +# egress saliente a puertos SMTP (25/465/587), sin importar el protocolo +# de arriba. Nada configurable en aiosmtplib arregla un paquete que el +# hosting nunca deja salir. Los mismos logs lo prueban: las llamadas a +# Supabase (puerto 443/HTTPS) responden 200 OK sin problema -- 443 es el +# único puerto saliente garantizado en este entorno. +# +# FIX: se abandona SMTP directo por completo y el envío se hace por HTTPS +# vía la API REST de Resend (https://resend.com) -- mismo patrón que ya usa +# este backend para hablar con Supabase (httpx sobre 443). Requiere UNA +# variable nueva: RESEND_API_KEY (ver core/config.py). Pasos de una sola +# vez en el dashboard de Resend: crear cuenta, verificar el dominio de +# SMTP_FROM (o usar su dominio de pruebas mientras tanto), generar la API +# key. Las variables SMTP_HOST/PORT/USER/PASSWORD/USE_SSL quedan sin uso +# real -- no hace falta borrarlas del .env, simplemente no se leen más acá. +_RESEND_API_URL = "https://api.resend.com/emails" + + +async def _send_mail_message(*, to: str, subject: str, html: str, text: str, context: str) -> None: + """Envía un correo vía la API HTTPS de Resend, con techo duro de + `settings.SMTP_TIMEOUT_SECONDS`. Pensada para correr como BackgroundTask. + + Loguea DOS clases de fallo por separado: + - Errores de red/timeout (DNS, conexión, techo de tiempo agotado). + - Rechazos de Resend (4xx/5xx) -- acá se imprime `response.text` + explícitamente porque httpx.HTTPStatusError / raise_for_status() NO + incluye el cuerpo de la respuesta en su mensaje por defecto, y ese + cuerpo es justo donde Resend explica el motivo real (dominio del + remitente sin verificar, restricción de sandbox al propio email de + la cuenta, API key inválida/revocada, etc.). Sin esto, un 403 se ve + genérico y no dice nada accionable -- que es exactamente lo que + pasó en el log anterior.""" + if not settings.RESEND_API_KEY: + print(f"[WARN] Envío de correo ({context}) omitido: falta RESEND_API_KEY en el entorno.") + return + + try: + async with httpx.AsyncClient(timeout=settings.SMTP_TIMEOUT_SECONDS) as client: + response = await client.post( + _RESEND_API_URL, + headers={"Authorization": f"Bearer {settings.RESEND_API_KEY}"}, + json={ + "from": settings.SMTP_FROM, + "to": [to], + "subject": subject, + "html": html, + "text": text, + }, + ) + except Exception as exc: + print(f"[WARN] Envío de correo ({context}) falló de red/timeout hacia Resend (to={to}): {exc!r}") + traceback.print_exc() + return + + if response.status_code >= 400: + print( + f"[WARN] Envío de correo ({context}) rechazado por Resend " + f"(HTTP {response.status_code}) to={to} from={settings.SMTP_FROM}: {response.text}" + ) + + +# --- Verificación de email --- +def generate_verification_token() -> tuple[str, datetime]: + """Token de verificación, válido 24h.""" + token = secrets.token_urlsafe(32) + expires_at = datetime.now(timezone.utc) + timedelta(hours=24) + return token, expires_at + + +async def send_verification_email(email_to: str, token: str) -> None: + """Construye y envía el correo de verificación. Diseñada para ser + agendada como BackgroundTask desde api/auth.py -- nunca debe hacer + esperar al cliente HTTP (ver _send_mail_message).""" + verify_url = f"{settings.FRONTEND_URL}/verify?token={token}" + + html = f"""\ + + + + + + +
+ + + + + + + +
+ KODAQUANT +
+

Confirma tu correo electrónico para activar tu cuenta y desbloquear tu Free Tier.

+ + + + +
+ + VERIFICAR CUENTA + +
+

Si el botón no funciona, copia este enlace:
+ {verify_url} +

+

Este enlace expira en 24 horas.

+
+
+ + +""" + + await _send_mail_message( + to=email_to, + subject="Verifica tu cuenta — KodaQuant Terminal", + html=html, + text="Verifica tu cuenta visitando: " + verify_url, # fallback texto plano + context="verification", + ) + + +# --- Recuperación de contraseña --- +def generate_password_reset_token() -> tuple[str, datetime]: + """Token de restablecimiento de contraseña, válido 60 minutos (más corto + que el de verificación de email porque habilita una acción sensible).""" + token = secrets.token_urlsafe(32) + expires_at = datetime.now(timezone.utc) + timedelta(minutes=60) + return token, expires_at + + +async def send_password_reset_email(email_to: str, token: str) -> None: + """Construye y envía el correo de restablecimiento. Diseñada para ser + agendada como BackgroundTask desde api/auth.py (ver _send_mail_message).""" + reset_url = f"{settings.FRONTEND_URL}/update-password?token={token}" + + html = f"""\ + + + + + + +
+ + + + + + + +
+ KODAQUANT +
+

Recibimos una solicitud para restablecer la contraseña de tu cuenta. Si no fuiste tú, ignora este correo.

+ + + + +
+ + RESTABLECER CONTRASEÑA + +
+

Si el botón no funciona, copia este enlace:
+ {reset_url} +

+

Este enlace expira en 60 minutos.

+
+
+ + +""" + + await _send_mail_message( + to=email_to, + subject="Restablece tu contraseña — KodaQuant Terminal", + html=html, + text="Restablece tu contraseña visitando: " + reset_url, + context="password-reset", + ) + + +# --- Correos transaccionales de suscripción (i18n) --- +# Disparar SIEMPRE desde el backend (webhook de Stripe / endpoint server-side +# que ya conoce el nuevo tier), nunca desde una acción de cliente sin validar. + +_SUBSCRIPTION_COPY = { + "en": { + "upgrade": { + "subject": "Welcome to KodaQuant {tier} — Subscription Confirmed", + "heading": "Your upgrade is live", + "body": "Your subscription has just been upgraded to {tier}. Here's what changed:", + "cta": "OPEN TERMINAL", + }, + "downgrade": { + "subject": "Your KodaQuant plan has changed to {tier}", + "heading": "Plan updated", + "body": "Your subscription has been changed to {tier}, effective at the end of your current billing cycle. Here's what to expect:", + "cta": "VIEW PLAN DETAILS", + }, + "cancel": { + "subject": "Your KodaQuant subscription has been canceled", + "heading": "Subscription canceled", + "body": "Your paid subscription has been canceled. You'll keep premium access until the end of your current billing cycle, then your account will move to Free.", + "cta": "MANAGE ACCOUNT", + }, + "footer": "No refunds are issued for partial billing periods.", + }, + "es": { + "upgrade": { + "subject": "Bienvenido a KodaQuant {tier} — Suscripción confirmada", + "heading": "Tu mejora ya está activa", + "body": "Tu suscripción acaba de mejorar a {tier}. Esto es lo que cambió:", + "cta": "ABRIR TERMINAL", + }, + "downgrade": { + "subject": "Tu plan de KodaQuant cambió a {tier}", + "heading": "Plan actualizado", + "body": "Tu suscripción cambiará a {tier} al finalizar tu ciclo de facturación actual. Esto es lo que puedes esperar:", + "cta": "VER DETALLES DEL PLAN", + }, + "cancel": { + "subject": "Tu suscripción de KodaQuant fue cancelada", + "heading": "Suscripción cancelada", + "body": "Tu suscripción paga fue cancelada. Mantendrás el acceso premium hasta el final de tu ciclo de facturación actual, luego tu cuenta pasará a Free.", + "cta": "GESTIONAR CUENTA", + }, + "footer": "No se emiten reembolsos por períodos de facturación parciales.", + }, +} + +_TIER_BENEFITS = { + "en": { + "FREE": ["1 active signal at a time", "Standard forecast horizon"], + "PRO": ["Unlimited signal generation", "Opportunity Scanner access"], + "ULTRA": ["Priority ONNX inference queue", "Quanti Discovery mode"], + }, + "es": { + "FREE": ["1 señal activa a la vez", "Horizonte de pronóstico estándar"], + "PRO": ["Generación ilimitada de señales", "Acceso a Opportunity Scanner"], + "ULTRA": ["Cola de inferencia ONNX prioritaria", "Modo Quanti Discovery"], + }, +} + + +def _render_subscription_email_html(heading: str, body: str, tier: str, language: str, cta_label: str) -> str: + """Mismo layout visual que verify/reset (fondo #0a0e14, tarjeta #10151f, + borde #1f2a37, logo KODAQUANT #00e5c7/#e6edf3), con comparativa de + beneficios del tier destino inyectada como lista.""" + benefits = _TIER_BENEFITS.get(language, _TIER_BENEFITS["en"]).get(tier.upper(), []) + benefits_html = "".join(f'
  • {b}
  • ' for b in benefits) + footer = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["footer"] + cta_url = f"{settings.FRONTEND_URL}/dashboard" + return f"""\ + + + + + + +
    + + + + + + + +
    + KODAQUANT +
    +

    {heading}

    +

    {body}

    +
      + {benefits_html} +
    + + + + +
    + + {cta_label} + +
    +

    {footer}

    +
    +
    + + +""" + + +async def send_subscription_upgrade_email(email_to: str, tier: str, language: str = "en") -> None: + """Correo al mejorar de plan (ej. FREE -> PRO, PRO -> ULTRA).""" + copy = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["upgrade"] + subject = copy["subject"].format(tier=tier.upper()) + body = copy["body"].format(tier=tier.upper()) + html = _render_subscription_email_html(copy["heading"], body, tier, language, copy["cta"]) + plain = f"{copy['heading']}. {body}".replace("", "").replace("", "") + + await _send_mail_message( + to=email_to, subject=subject, html=html, text=plain, context="subscription-upgrade" + ) + + +async def send_subscription_downgrade_email(email_to: str, tier: str, language: str = "en") -> None: + """Correo al bajar de plan (ej. ULTRA -> PRO), efectivo al fin del ciclo.""" + copy = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["downgrade"] + subject = copy["subject"].format(tier=tier.upper()) + body = copy["body"].format(tier=tier.upper()) + html = _render_subscription_email_html(copy["heading"], body, tier, language, copy["cta"]) + plain = f"{copy['heading']}. {body}".replace("", "").replace("", "") + + await _send_mail_message( + to=email_to, subject=subject, html=html, text=plain, context="subscription-downgrade" + ) + + +async def send_subscription_cancel_email(email_to: str, language: str = "en") -> None: + """Correo al cancelar un plan pago; el usuario vuelve a FREE al fin del ciclo.""" + copy = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["cancel"] + html = _render_subscription_email_html(copy["heading"], copy["body"], "FREE", language, copy["cta"]) + plain = f"{copy['heading']}. {copy['body']}".replace("", "").replace("", "") + + await _send_mail_message( + to=email_to, subject=copy["subject"], html=html, text=plain, context="subscription-cancel" + ) \ No newline at end of file diff --git a/core/supabase_client.py b/core/supabase_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a272eb30b36a0da8bcc3d446f6024dd1b4c5bb11 --- /dev/null +++ b/core/supabase_client.py @@ -0,0 +1,20 @@ +from supabase import create_client, Client +from core.config import settings + +# --- Cliente ANON (respeta RLS) --- +# Para todo lo que ya funciona hoy: auth.get_user() y cualquier lectura o +# escritura donde las policies de RLS deben seguir aplicando (ver +# core/security.py: get_current_user, verify_api_credits). NO se toca. +url: str = settings.SUPABASE_URL +key: str = settings.SUPABASE_KEY +supabase: Client = create_client(url, key) + +# --- Cliente SERVICE ROLE (bypassea RLS por completo) --- +# Uso EXCLUSIVO para operaciones de servidor de confianza donde el backend +# ya verificó la identidad del usuario por su cuenta (ej. el INSERT en +# chat_threads, hecho después de pasar por get_current_user). Este cliente +# no tiene NINGÚN control de acceso propio -- es admin total sobre la DB. +# Nunca lo uses para resolver datos a partir de un id que no hayas validado +# vos mismo antes, y nunca lo expongas fuera del backend. +service_key: str = settings.SUPABASE_SERVICE_ROLE_KEY +supabase_admin: Client = create_client(url, service_key) \ No newline at end of file diff --git a/database/__init__.py b/database/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/logs/mlops_pipeline.log b/logs/mlops_pipeline.log new file mode 100644 index 0000000000000000000000000000000000000000..c33d95bb34b5cb758cf53e1b6c9ad9c065f204e0 --- /dev/null +++ b/logs/mlops_pipeline.log @@ -0,0 +1,36 @@ +[2026-07-18 21:32:29] - [INFO] - [train_pipeline] - ==================== CICLO MLOps INICIADO ==================== +[2026-07-18 21:32:32] - [WARNING] - [train_pipeline] - Drift check: AAPL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:33] - [WARNING] - [train_pipeline] - Drift check: MSFT solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:34] - [WARNING] - [train_pipeline] - Drift check: NVDA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:36] - [WARNING] - [train_pipeline] - Drift check: TSLA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:37] - [WARNING] - [train_pipeline] - Drift check: GOOGL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:40] - [WARNING] - [train_pipeline] - Drift check: AMZN solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:41] - [WARNING] - [train_pipeline] - Drift check: META solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:44] - [WARNING] - [train_pipeline] - Drift check: SPY solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 21:32:44] - [INFO] - [train_pipeline] - No existe baseline_mae previo — se fija el MAE actual (0.017297) como baseline inicial. +[2026-07-18 21:32:44] - [INFO] - [train_pipeline] - Chequeo de drift: Forzado vía --force-retrain (chequeo real: baseline_inicializado) +[2026-07-18 21:32:44] - [WARNING] - [train_pipeline] - DRIFT DETECTADO — Forzado vía --force-retrain (chequeo real: baseline_inicializado). Se dispara el ciclo Challenger. +[2026-07-18 21:34:40] - [INFO] - [train_pipeline] - ==================== CICLO MLOps FINALIZADO (status=error) ==================== +[2026-07-18 22:03:23] - [INFO] - [train_pipeline] - ==================== CICLO MLOps INICIADO ==================== +[2026-07-18 22:03:25] - [WARNING] - [train_pipeline] - Drift check: AAPL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:03:27] - [WARNING] - [train_pipeline] - Drift check: MSFT solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:03:29] - [WARNING] - [train_pipeline] - Drift check: NVDA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:03:30] - [WARNING] - [train_pipeline] - Drift check: TSLA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:03:32] - [WARNING] - [train_pipeline] - Drift check: GOOGL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:03:34] - [WARNING] - [train_pipeline] - Drift check: AMZN solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:03:36] - [WARNING] - [train_pipeline] - Drift check: META solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:03:43] - [INFO] - [train_pipeline] - ==================== CICLO MLOps FINALIZADO (status=error) ==================== +[2026-07-18 22:04:11] - [INFO] - [train_pipeline] - ==================== CICLO MLOps INICIADO ==================== +[2026-07-18 22:04:13] - [WARNING] - [train_pipeline] - Drift check: AAPL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:14] - [WARNING] - [train_pipeline] - Drift check: MSFT solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:16] - [WARNING] - [train_pipeline] - Drift check: NVDA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:17] - [WARNING] - [train_pipeline] - Drift check: TSLA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:19] - [WARNING] - [train_pipeline] - Drift check: GOOGL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:20] - [WARNING] - [train_pipeline] - Drift check: AMZN solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:22] - [WARNING] - [train_pipeline] - Drift check: META solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:26] - [WARNING] - [train_pipeline] - Drift check: SPY solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible. +[2026-07-18 22:04:26] - [INFO] - [train_pipeline] - Chequeo de drift: Forzado vía --force-retrain (chequeo real: Sin drift — MAE actual=0.017297 dentro del threshold dinámico=0.018162 (baseline=0.017297).) +[2026-07-18 22:04:26] - [WARNING] - [train_pipeline] - DRIFT DETECTADO — Forzado vía --force-retrain (chequeo real: Sin drift — MAE actual=0.017297 dentro del threshold dinámico=0.018162 (baseline=0.017297).). Se dispara el ciclo Challenger. +[2026-07-18 22:07:47] - [INFO] - [train_pipeline] - Champion MAE: 0.017953 | Challenger MAE: 0.018024 | p-value: 0.3819 | Winner: CHAMPION +[2026-07-18 22:07:47] - [WARNING] - [train_pipeline] - Degradación rechazada — Challenger NO superó estadísticamente al Champion (mae_improved=False, statistically_significant=False). El Champion se mantiene en producción. +[2026-07-18 22:07:48] - [INFO] - [train_pipeline] - ==================== CICLO MLOps FINALIZADO (status=rejected) ==================== diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..e029cc5f4f6ec74f3451219c0d5e57131b172be2 --- /dev/null +++ b/main.py @@ -0,0 +1,447 @@ +from dotenv import load_dotenv +import asyncio +import contextlib +import logging +import threading +import time +load_dotenv() +from fastapi import Depends, HTTPException, Request +from gradio import Server +import spaces +from fastapi.middleware.cors import CORSMiddleware +from fastapi.exceptions import RequestValidationError +from fastapi.responses import StreamingResponse, JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException +from services.currency_engine import convert_to_usd +from services.prediccion import generate_predictions +from services.risk_manager import calculate_portfolio +from api.auth import router as auth_router +from core.security import ( + verify_api_credits, + AuthenticatedUser, + get_allowed_origins, # <-- CAMBIO: lista cerrada de orígenes CORS + ALLOWED_METHODS, + ALLOWED_HEADERS, + StrictOriginMiddleware, # <-- FIX: bloquea Origin no permitido a nivel app + # (gradio.Server pisa nuestro CORSMiddleware + # en prod -- ver detalle en core/security.py) +) +from api.payments import router as payments_router +from api.online_learning import router as online_learning_router +from typing import Literal, Optional +from pydantic import BaseModel, ConfigDict, Field, field_validator +from services.quanti_engine import DEFAULT_FORECAST_HORIZON_DAYS +from services.quanti_engine import generate_quanti_strategy_stream +from services.quanti_engine import _forecast_asset +from services.quanti_engine import _normalize_language +from services.quanti_engine import _derive_capital_signal +from api.quota_test_routes import router as quota_test_router +from api.quanti_chat import router as quanti_chat_router +from api.support import router as support_router +from core.config import settings + +logger = logging.getLogger("kodaquant.main") + +# NOTA: `lifespan` NO se pasa acá (`Server(lifespan=...)`) a propósito — +# `Blocks.launch()`/`App.create_app()` lo pisa igual que a `@app.on_event` +# (ver el bloque de comentarios "RONDA 4" junto al probe de ZeroGPU, más +# abajo). El único punto que gradio realmente respeta es +# `app.launch(app_kwargs={"lifespan": lifespan})` en app.py. +app = Server(title="KodaQuant Terminal", version="4.0") +app.include_router(payments_router) +app.include_router(auth_router, prefix="/api/v1/auth") +app.include_router(online_learning_router) +if settings.ENV != "production": + app.include_router(quota_test_router) +app.include_router(quanti_chat_router) +app.include_router(support_router) + +_VALID_EXPERIENCE = {"beginner", "advanced"} +_VALID_ANALYSIS_MODE = {"specific", "discovery"} +_VALID_RISK_PROFILE = {"conservador", "moderado", "agresivo"} + +class QuantiConsultRequest(BaseModel): + """ + Solo `capital` es realmente obligatorio — todo lo demás tiene default + seguro y se NORMALIZA en lugar de rechazar la request con 422 ante + variaciones menores (mayúsculas, catálogo, strings vacíos). Alias + camelCase 1:1 con lo que envía App.jsx. + """ + + model_config = ConfigDict(populate_by_name=True, extra="ignore") + + capital: float = Field(..., gt=0, alias="capital") + currency: str = Field(default="USD", alias="currency") + experience_level: str = Field(default="beginner", alias="experienceLevel") + analysis_mode: str = Field(default="discovery", alias="analysisMode") + target_asset: Optional[str] = Field(default=None, alias="targetAsset") + forecast_horizon_days: int = Field(default=DEFAULT_FORECAST_HORIZON_DAYS, alias="forecastHorizonDays") + risk_profile: str = Field(default="moderado", alias="riskProfile") + risk_score: int = Field(default=50, alias="riskScore") + language: str = Field(default="en", alias="language") + + @field_validator("capital", mode="before") + @classmethod + def _coerce_capital(cls, v): + try: + return float(v) + except (TypeError, ValueError): + raise ValueError("capital debe ser un número mayor a 0") + + @field_validator("currency", mode="before") + @classmethod + def _normalize_currency(cls, v): + if not isinstance(v, str) or not v.strip(): + return "USD" + return v.strip().upper()[:3] + + @field_validator("experience_level", mode="before") + @classmethod + def _normalize_experience(cls, v): + v = str(v).strip().lower() if v else "beginner" + return v if v in _VALID_EXPERIENCE else "beginner" + + @field_validator("analysis_mode", mode="before") + @classmethod + def _normalize_analysis_mode(cls, v): + v = str(v).strip().lower() if v else "discovery" + return v if v in _VALID_ANALYSIS_MODE else "discovery" + + @field_validator("target_asset", mode="before") + @classmethod + def _normalize_target_asset(cls, v): + if v is None or (isinstance(v, str) and not v.strip()): + return None + return str(v).strip().upper() + + @field_validator("forecast_horizon_days", mode="before") + @classmethod + def _normalize_horizon(cls, v): + try: + days = int(v) + except (TypeError, ValueError): + return DEFAULT_FORECAST_HORIZON_DAYS + return days if days > 0 else DEFAULT_FORECAST_HORIZON_DAYS + + @field_validator("risk_profile", mode="before") + @classmethod + def _normalize_risk_profile_field(cls, v): + v = str(v).strip().lower() if v else "moderado" + return v if v in _VALID_RISK_PROFILE else "moderado" + + @field_validator("risk_score", mode="before") + @classmethod + def _normalize_risk_score(cls, v): + try: + score = int(v) + except (TypeError, ValueError): + return 50 + return max(0, min(100, score)) + + @field_validator("language", mode="before") + @classmethod + def _normalize_language_field(cls, v): + # Reusa la MISMA normalización que quanti_engine (_SUPPORTED_LANGUAGES + # = {"en","es"}, default "en"), para que nunca haya drift entre el + # schema de entrada y lo que el LLM realmente honra. + return _normalize_language(v) + +class StrategyRequest(BaseModel): + budget_usd: float = Field(..., gt=0) + experience_level: Literal["beginner", "intermediate", "advanced"] = "beginner" + +@app.post("/strategy") +async def strategy_mock(payload: StrategyRequest): + return { + "status": "success", + "amounts": { + "riesgo_usd": 4000, + "reserva_usd": 6000, + "riesgo_pct": "40.0%", + "reserva_pct": "60.0%", + }, + "guidelines": [ + "Conexión exitosa con el servidor KodaQuant.", + "El motor está en línea y operando.", + ], + } + +# FIX CRÍTICO (Alpha Seeker nunca corría): este mock estático alimentaba +# `/api/v1/quanti/consult` con un `top_assets` FIJO donde BTC-USD siempre +# tenía el `risk_score` más alto (0.78) — `_resolve_plan_b_ticker` +# (quanti_engine.py) lo elegía SIEMPRE, sin importar el forecast real de +# cada ciclo. Reemplazado por `_get_radar_data`, que llama al pipeline +# REAL (`generate_predictions`, ver services/prediccion.py) con caché TTL. + +_RADAR_CACHE_TTL_SECONDS = 60.0 +_radar_cache: dict[str, tuple[float, dict]] = {} + + +async def _get_radar_data(budget_usd: float) -> dict: + """ + Radar real (Alpha Seeker) para `/api/v1/quanti/consult` — sustituye el + mock hardcodeado. Cacheado con TTL: escanea el universo completo (10 + tickers, Keras + Monte Carlo vía `_forecast_asset`) y el resultado NO + depende de `budget_usd` (ese solo escala montos de display en + `recommendations`; el ranking real de `top_assets` es independiente), + así que recomputarlo en cada request dispararía ~10 inferencias Keras + extra por usuario concurrente sin necesidad. `generate_predictions` + nunca lanza excepción (Circuit Breaker propio, devuelve + status="error" con listas vacías) — safe de propagar tal cual. + """ + now = time.monotonic() + cached = _radar_cache.get("global") + if cached is not None and (now - cached[0]) < _RADAR_CACHE_TTL_SECONDS: + return cached[1] + + data = await generate_predictions(budget_usd) + if data.get("status") != "success": + logger.warning("generate_predictions degradado en /consult: %s", data.get("error")) + _radar_cache["global"] = (now, data) + return data + +app.add_middleware( + CORSMiddleware, + # Lista cerrada, resuelta en core/security.py. En ENVIRONMENT=production + # esto se reduce a *solo* los dominios de Firebase Hosting (+ + # settings.FRONTEND_URL); localhost nunca se cuela a producción. + allow_origins=get_allowed_origins(), + allow_credentials=True, + allow_methods=ALLOWED_METHODS, # GET, POST, OPTIONS — no "*" + allow_headers=ALLOWED_HEADERS, # Authorization, Content-Type — no "*" + expose_headers=["Content-Type", "Cache-Control"], +) + +# FIX CRÍTICO — gradio.Server SIEMPRE agrega su propio CustomCORSMiddleware +# en .launch() (después de este punto, ver app.py), y ese middleware queda +# por FUERA de nuestro CORSMiddleware de arriba sin importar el orden acá. +# Su regla solo restringe origen si el Host es localhost -- en *.hf.space +# NUNCA aplica esa restricción, así que termina permitiendo cualquier +# Origin con credentials=true, pisando get_allowed_origins(). Verificado +# contra gradio==6.22.0 (ver core/security.py::StrictOriginMiddleware para +# el detalle completo). Esta capa rechaza (403) el request ANTES de que +# llegue al router, así que ningún header que agregue Gradio después +# importa: la request nunca se procesó. +app.add_middleware(StrictOriginMiddleware) + + +# FIX — blindaje JSON-only. Ninguna respuesta de esta API debe poder +# renderizar como HTML, sin importar qué falle. Starlette por default +# puede devolver su propia página de error para excepciones no atrapadas; +# estos handlers garantizan que 404/422/500 y cualquier excepción no +# manejada siempre vuelvan como JSON, consistente con lo que espera +# quantiService.js (response.json() en cada llamada). +@app.exception_handler(StarletteHTTPException) +async def _json_http_exception_handler(request: Request, exc: StarletteHTTPException): + return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail}) + + +@app.exception_handler(RequestValidationError) +async def _json_validation_exception_handler(request: Request, exc: RequestValidationError): + return JSONResponse(status_code=422, content={"detail": exc.errors()}) + + +@app.exception_handler(Exception) +async def _json_unhandled_exception_handler(request: Request, exc: Exception): + logger.exception("Excepción no manejada en %s %s", request.method, request.url.path) + return JSONResponse( + status_code=500, + content={"detail": "Error interno del servidor."}, + ) + +# --- ZeroGPU probe ----------------------------------------------------- +# ROUND 3 — causa raíz real del "No @spaces.GPU function detected during +# startup": `gr.mount_gradio_app(fastapi_app, blocks, path=...)` devuelve +# la instancia FastAPI de ENTRADA (fastapi_app), mutada in place — nunca +# un gr.Blocks/Interface. El hypervisor de ZeroGPU necesita reconocer el +# objeto `app` exportado como demo Gradio nativo; al recibir un FastAPI +# puro con Gradio montado como sub-app en un path escondido, no lo +# reconoce como tal — pase lo que pase adentro de esa sub-app (Blocks con +# GPU function real por .load() o .click(), no importa), y mata el +# proceso. Esto es válido tanto para el mount en app.py (ronda 2) como +# para este mismo patrón acá en main.py (bug preexistente, mismo defecto). +# +# Fix: `gradio.Server` (gradio>=6.22, ver +# https://gradio.app/main/guides/server-mode) es un FastAPI real — +# `app.add_middleware`, `app.include_router`, rutas @app.get/@app.post, +# todo lo que ya usa este archivo sigue funcionando sin tocarlo — pero ES +# el tipo de objeto que Gradio/ZeroGPU reconocen nativamente como servidor +# Gradio. `@app.api()` registra la función en la tabla de endpoints de +# Gradio (mismo registro que el hypervisor inspecciona), sin necesidad de +# gr.Blocks ni de mount_gradio_app. Nunca se llama desde el frontend — solo +# necesita existir registrada para que el hypervisor la detecte al +# build/startup. KodaQuant sigue forzando toda la inferencia Keras real a +# CPU (ver DEVICE GUARD arriba); este endpoint no hace inferencia real. +@app.api(name="zerogpu_probe") +@spaces.GPU() +def _zerogpu_probe() -> str: + return "ok" + + +# FIX 2026-08-15 (RONDA 4) — CAUSA RAÍZ REAL del estado zombi "Starting...". +# +# Auditoría línea a línea de gradio==6.22.0 (gradio/routes.py::App.create_app, +# gradio/blocks.py::Blocks.launch, gradio/server.py::Server.launch): +# +# Server.launch() -> blocks.launch(_app=self, app_kwargs=app_kwargs, ...) +# Blocks.launch() -> App.create_app(self, app=_app, app_kwargs=app_kwargs, ...) +# App.create_app(): como `app` (=self, nuestra instancia YA construida) +# NO es None, toma la rama: +# app.router.lifespan_context = create_lifespan_handler( +# app_kwargs.get("lifespan", None), *delete_cache +# ) +# +# Esa línea PISA `app.router.lifespan_context` con un handler construido a +# partir de `app_kwargs` — el dict que se le pasa a `.launch()`, NUNCA el +# `lifespan=` que se le pasó al CONSTRUCTOR `Server(...)`. Como `app.py` +# (rondas 1-3) llamaba `app.launch()` sin `app_kwargs`, `app_kwargs.get( +# "lifespan")` daba `None` -> el lifespan real quedaba DESCARTADO en +# silencio. Y como `router.lifespan_context` se reasigna DIRECTO (no se +# compone con la implementación default de Starlette que sí lee +# `router.on_startup`), cualquier `@app.on_event("startup")` registrado +# antes de `.launch()` (como el que vivía acá) también queda huérfano — +# explica exacto por qué "KodaQuant ASGI startup complete" NUNCA aparecía +# en los logs de producción pese a que el resto del pipeline sí corría. +# +# FIX REAL: el lifespan tiene que viajar como `app_kwargs={"lifespan": lifespan}` +# en la LLAMADA a `.launch()` (ver app.py) — es el ÚNICO punto de la cadena +# que `create_app` efectivamente respeta. `lifespan` se define acá y se +# exporta para que app.py lo importe. +def _warm_zerogpu_probe_sync() -> None: + """ + Red de seguridad INDEPENDIENTE de todo el ciclo de vida ASGI/Gradio de + arriba: corre en un hilo daemon disparado en el momento del IMPORT de + este módulo — mucho antes de que exista `router`/`lifespan_context` + alguno para pisar. Garantiza al menos una ejecución real de + `_zerogpu_probe` durante el arranque del proceso sin importar qué haga + `Server.launch()` internamente ni qué versión de gradio la sirva. + """ + try: + result = _zerogpu_probe() + logger.info("ZeroGPU probe warm-up OK (hilo de import, red de seguridad): %s", result) + except Exception as exc: + logger.warning("ZeroGPU probe warm-up (hilo de import) falló (no crítico): %r", exc) + + +threading.Thread( + target=_warm_zerogpu_probe_sync, daemon=True, name="zerogpu-warmup-import" +).start() + + +@contextlib.asynccontextmanager +async def lifespan(app): + """ + Lifespan real de la app — DEBE inyectarse vía + `app.launch(app_kwargs={"lifespan": lifespan})` en app.py (ver bloque + de comentarios arriba). Pasarlo al constructor `Server(lifespan=...)` + o registrar `@app.on_event("startup")` NO alcanza: ambos caminos son + pisados por `Blocks.launch()`/`App.create_app()` antes de que el + Space quede realmente sirviendo tráfico. + """ + # Uvicorn solo loguea el genérico "Application startup complete.". Este + # marcador con timestamp deja explícito en los logs del Space cuánto + # tardó el cold start real (imports de TensorFlow/Keras + montaje de + # gradio) — clave para diferenciar "todo bien, algo externo mandó + # SIGTERM" de "el arranque fue tan lento que algo lo mató por timeout". + logger.info("KodaQuant ASGI startup complete — rutas + probe de ZeroGPU montados.") + + async def _warm_zerogpu_probe_async() -> None: + # Segunda ejecución del probe, esta vez DENTRO del ciclo de vida + # ASGI real (útil si el hilo de import de arriba corrió antes de + # que `device-api.zero` estuviera listo para recibirlo). Fire-and- + # forget con timeout: si ZeroGPU no responde o el tier actual no lo + # tiene habilitado, esto NUNCA debe retrasar ni tumbar el arranque. + try: + loop = asyncio.get_running_loop() + result = await asyncio.wait_for( + loop.run_in_executor(None, _zerogpu_probe), timeout=15.0 + ) + logger.info("ZeroGPU probe warm-up OK (lifespan ASGI): %s", result) + except Exception as exc: + logger.warning("ZeroGPU probe warm-up (lifespan ASGI) falló (no crítico): %r", exc) + + warmup_task = asyncio.create_task(_warm_zerogpu_probe_async()) + try: + yield + finally: + warmup_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await warmup_task + +@app.get("/") +async def root(): + return {"status": "online", "system": "KodaQuant Terminal", "version": "4.0"} + +@app.get("/api/v1/convert") +async def test_conversion(amount: float, currency: str): + try: + data = await convert_to_usd(amount, currency.upper()) + return {"status": "success", "data": data} + except Exception as e: + return {"status": "error", "message": str(e)} + +@app.get("/api/v1/radar") +async def test_radar(usd_budget: float): + try: + data = await generate_predictions(usd_budget) + return {"status": "success", "data": data} + except Exception as e: + return {"status": "error", "message": str(e)} + +@app.get("/api/v1/quanti/forecast") +async def test_ml_forecast(ticker: str = "SPY"): + # `data` es el dict completo que arma `_forecast_asset` — ya incluye + # `predicted_path` (array plano día-a-día) junto con `forecast` + # (mismo dato, con date/price/kind). No requiere transformación aquí: + # serializar el dict completo es suficiente para que el frontend lo lea. + try: + loop = asyncio.get_running_loop() + data = await loop.run_in_executor(None, _forecast_asset, ticker) + return {"status": "success", "data": data} + except Exception as e: + return {"status": "error", "message": str(e)} + +@app.post("/api/v1/quanti/consult") +async def quanti_consult( + payload: QuantiConsultRequest, + current_user: AuthenticatedUser = Depends(verify_api_credits), +): + try: + conversion_report = await convert_to_usd(payload.capital, payload.currency) + budget_usd = conversion_report["usd_amount"] + except Exception as exc: + raise HTTPException(status_code=400, detail=f"Error de conversión de divisa: {exc}") + + radar_data = await _get_radar_data(budget_usd) + # Auto-Allocation: copia superficial — NUNCA mutar en sitio el dict que + # devuelve `_get_radar_data` (está cacheado con TTL y compartido entre + # requests concurrentes). `_derive_capital_signal` es puro/determinista + # sobre datos ya calculados, así que enriquecerlo acá es seguro y no + # requiere invalidar ni recomputar el caché del radar. + radar_data = {**radar_data, "signal": _derive_capital_signal(radar_data)} + + try: + portfolio_allocation = await calculate_portfolio(budget_usd, radar_data) + except Exception as exc: + raise HTTPException(status_code=500, detail=f"Error en risk_manager: {exc}") + + # `generate_quanti_strategy_stream` emite `chart_data.plan_a` / `plan_b` + # como el dict completo de `_forecast_asset` (ver quanti_engine.py), así + # que `predicted_path` viaja automáticamente en el evento `meta` del SSE + # — no hace falta tocar el stream para exponerlo. + return StreamingResponse( + generate_quanti_strategy_stream( + budget_usd=budget_usd, + portfolio_allocation=portfolio_allocation, + radar_data=radar_data, + experience_level=payload.experience_level, + analysis_mode=payload.analysis_mode, + target_asset=payload.target_asset, + forecast_horizon_days=payload.forecast_horizon_days, + risk_profile=payload.risk_profile, + risk_score=payload.risk_score, + language=payload.language, + ), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) \ No newline at end of file diff --git a/middlewares/__init__.py b/middlewares/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_engine/__init__.py b/ml_engine/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/ml_engine/attention_bilstm_global_best.keras b/ml_engine/attention_bilstm_global_best.keras new file mode 100644 index 0000000000000000000000000000000000000000..1aa553cfad75e0bd8b25f0e385aa93744a00a41a --- /dev/null +++ b/ml_engine/attention_bilstm_global_best.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10a425f6c4b837cc902b24051c3d473c103f2e5eae23f963451dd050569c9548 +size 19854569 diff --git a/ml_engine/cache/news/headlines_AAPL.json b/ml_engine/cache/news/headlines_AAPL.json new file mode 100644 index 0000000000000000000000000000000000000000..fd93444df064969e3a017981ab0038b1725488d0 --- /dev/null +++ b/ml_engine/cache/news/headlines_AAPL.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "AAPL Stock Alert: What to Know as Apple Unveils New Mac Models With AI Upgrades", "published_at": "2026-08-25T19:13:00+00:00"}, {"title": "How to play AAPL stock as Apple unveils new Macs", "published_at": "2026-08-26T19:30:44+00:00"}, {"title": "Apple (AAPL) Stock Maintains Momentum as AI Infrastructure Concerns Hit Tech Giants", "published_at": "2026-08-26T09:11:00+00:00"}, {"title": "Should You Buy Apple (AAPL) Stock?", "published_at": "2023-09-07T17:32:00+00:00"}, {"title": "What BofA and Morgan Stanley Are Saying About Apple (AAPL) Stock in August", "published_at": "2026-08-18T13:00:00+00:00"}, {"title": "$10,000 invested in Apple stock at the start of 2026 is now worth", "published_at": "2026-08-27T17:58:00+00:00"}, {"title": "Here's How Much Traders Expect Apple Stock to Move After Earnings", "published_at": "2026-07-30T15:02:00+00:00"}, {"title": "Apple (AAPL) Stock Dips as Mac Mini Price Surges to $899 with M6 Chip Launch", "published_at": "2026-08-25T15:16:00+00:00"}, {"title": "Here's Why Apple (AAPL) is a Great Momentum Stock to Buy", "published_at": "2026-02-12T00:00:00+00:00"}, {"title": "Jefferies Just Said Sell Apple (AAPL). Here's the iPhone Feature That Got Canceled", "published_at": "2026-08-21T17:11:00+00:00"}], "_cached_at": 1787880007.375259} \ No newline at end of file diff --git a/ml_engine/cache/news/headlines_AMZN.json b/ml_engine/cache/news/headlines_AMZN.json new file mode 100644 index 0000000000000000000000000000000000000000..ce893f0d4ce39f48fcbb1949089573c19837bdcd --- /dev/null +++ b/ml_engine/cache/news/headlines_AMZN.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "AMZN stock dips overnight after breaching $3 trillion market cap: Retail gets buzzing about Bezos\u2019 share sale", "published_at": "2026-08-04T06:00:00+00:00"}, {"title": "Here\u2019s How Much Amazon Stock Is Expected to Move After Earnings", "published_at": "2026-07-30T06:00:00+00:00"}, {"title": "AMZN Stock Soars 7% After-Hours \u2014 Amazon\u2019s Q2 AWS Grows At Fastest Pace In Five Years, Boosts 2026 Capex To $220B", "published_at": "2026-07-30T06:00:00+00:00"}, {"title": "Amazon (AMZN) Stock Rises as AWS Secures 2 Million Nvidia GPUs in Massive Expansion Deal", "published_at": "2026-08-10T01:20:20+00:00"}, {"title": "Corgi AMZN 2x Daily ETF", "published_at": "2026-08-25T01:20:20+00:00"}, {"title": "Amazon (AMZN) Stock Predictions for 2026 and Beyond | The Motley Fool", "published_at": "2026-08-27T03:20:21+00:00"}, {"title": "AMZN Looks 5.6% Overvalued on GF Value\u2122 Amid Mechanical Turk Shu", "published_at": "2026-08-27T10:20:21+00:00"}, {"title": "Inside Amazon's Stock Drop: Why Analysts Remain High on AWS AI Momentum -...", "published_at": "2026-08-27T17:20:21+00:00"}, {"title": "Amazon vs. Alibaba: Which AI and E-Commerce Stock Is the Better Buy?", "published_at": "2026-08-25T01:20:21+00:00"}, {"title": "6 things moving Amazon stock as Ackman sticks with a $2B position", "published_at": "2026-08-26T01:20:20+00:00"}], "_cached_at": 1787880021.3768692} \ No newline at end of file diff --git a/ml_engine/cache/news/headlines_GOOGL.json b/ml_engine/cache/news/headlines_GOOGL.json new file mode 100644 index 0000000000000000000000000000000000000000..a65332f15dca9022eddddb88edb085f837a4cb0d --- /dev/null +++ b/ml_engine/cache/news/headlines_GOOGL.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "GOOGL is already borrowing billions for AI \u2013 now it\u2019s reportedly eyeing Australia\u2019s bond market", "published_at": "2026-08-18T01:20:19+00:00"}, {"title": "GOOGL stock ticks higher premarket after taking big hit as CEO Sundar Pichai, analysts downplay AI talent exit fears", "published_at": "2026-08-06T06:00:00+00:00"}, {"title": "Alphabet\u2019s GOOG Vs GOOGL: How Are These Stocks Different?", "published_at": "2023-08-08T06:00:00+00:00"}, {"title": "GOOGL stock gains over 5%: Google locks major long-term solar power deal with RWE \u2014 retail sees an AI infrastructure play", "published_at": "2026-08-03T06:00:00+00:00"}, {"title": "Google (GOOGL) to buy up to $12.2 billion shares in US chip firm Marvell (MRVL)", "published_at": "2026-08-20T01:20:19+00:00"}, {"title": "GOOGL stock alert: Google unleashes its biggest weapon against Apple", "published_at": "2026-08-15T01:20:19+00:00"}, {"title": "GOOGL Stock Price Prediction 2026-2027 | Google Forecast | 24/7 Wall St.", "published_at": "2026-08-27T01:20:20+00:00"}, {"title": "Alphabet Inc. (GOOGL) Faces Challenges Amid AI Competition and T", "published_at": "2026-08-27T19:20:20+00:00"}, {"title": "5 Things to Know Before the Stock Market Opens on Thursday", "published_at": "2026-08-27T12:20:20+00:00"}, {"title": "The Price of Progress for Google Stock", "published_at": "2026-08-26T01:20:20+00:00"}], "_cached_at": 1787880020.1552289} \ No newline at end of file diff --git a/ml_engine/cache/news/headlines_META.json b/ml_engine/cache/news/headlines_META.json new file mode 100644 index 0000000000000000000000000000000000000000..ac74773aefa94c98914f37fe2eda4facb11e31e9 --- /dev/null +++ b/ml_engine/cache/news/headlines_META.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Meta agrees to settle teen addiction lawsuit for up to $18 billion, sets time...", "published_at": "2026-08-27T01:20:22+00:00"}, {"title": "Meta agrees up to $18 billion settlement in youth social media case", "published_at": "2026-08-27T01:20:22+00:00"}, {"title": "1 Stock Under $50 with Solid Fundamentals and 2 We Brush Off", "published_at": "2026-08-27T16:20:22+00:00"}, {"title": "Meta Stock Falls Premarket: Analyst Sees Limited Impact From Child-Safety Suit...", "published_at": "2026-08-27T08:20:22+00:00"}, {"title": "Meta's social media settlement leaves its money machine unscathed", "published_at": "2026-08-27T10:20:22+00:00"}, {"title": "Meta\u2019s $145 Billion Spending Scare Just Opened a Window for Investors. Here\u2019s Ho...", "published_at": "2026-08-26T01:20:22+00:00"}, {"title": "Meta settles multistate teen social media lawsuit for $16.7 billion", "published_at": "2026-08-27T01:20:22+00:00"}, {"title": "Meta Just Removed a Major Risk From Its Stock. Now AI Spending Is the $145...", "published_at": "2026-08-27T15:20:22+00:00"}, {"title": "Why Meta Platforms Stock Popped Today", "published_at": "2026-08-27T01:20:22+00:00"}, {"title": "Stock Market Today, Aug. 26: Stocks Edge Lower As Market Digests Meta Ruling and...", "published_at": "2026-08-27T01:20:22+00:00"}], "_cached_at": 1787880022.499327} \ No newline at end of file diff --git a/ml_engine/cache/news/headlines_MSFT.json b/ml_engine/cache/news/headlines_MSFT.json new file mode 100644 index 0000000000000000000000000000000000000000..c52d0b587b61a6e4361fbd4f4a3d6fe5c756234c --- /dev/null +++ b/ml_engine/cache/news/headlines_MSFT.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "JPMorgan set a serious Microsoft stock price target for 2027", "published_at": "2026-08-15T01:20:15+00:00"}, {"title": "Earnings growth & price strength make Microsoft (MSFT) a stock to watch", "published_at": "2026-08-25T01:20:15+00:00"}, {"title": "Should You Buy Microsoft (MSFT) Stock?", "published_at": "2026-04-22T06:00:00+00:00"}, {"title": "Microsoft (MSFT) Stock: Raises Dividend as AI Capital Spending Hits Record Levels", "published_at": "2026-08-22T01:20:15+00:00"}, {"title": "Up almost 20%, here\u2019s why Microsoft stock could rise even further", "published_at": "2026-08-21T01:20:15+00:00"}, {"title": "LinkedIn just cut its Israel R&D team. Microsoft stock investors shouldn\u2019t sweat the layoffs.", "published_at": "2026-08-18T01:20:15+00:00"}, {"title": "Unusual options activity: NFLX, HONA, and MSFT lead the way with these 3 options strategies", "published_at": "2026-08-21T01:20:15+00:00"}, {"title": "What's Going On With Microsoft Stock? - Microsoft (NASDAQ:MSFT)", "published_at": "2026-08-27T18:20:16+00:00"}, {"title": "Here\u2019s How Much You Would Have Made Owning Microsoft Stock In The Last 20 Years ...", "published_at": "2026-08-27T01:20:16+00:00"}, {"title": "PRGS or MSFT: Which Is the Better Value Stock Right Now?", "published_at": "2026-08-22T01:20:16+00:00"}], "_cached_at": 1787880016.186072} \ No newline at end of file diff --git a/ml_engine/cache/news/headlines_NVDA.json b/ml_engine/cache/news/headlines_NVDA.json new file mode 100644 index 0000000000000000000000000000000000000000..689d9b6fee5cc3db016d15d39352994278cc5277 --- /dev/null +++ b/ml_engine/cache/news/headlines_NVDA.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "Jim Cramer has a message for Nvidia investors after the earnings blowout: 'Don't let the bears deceive you' into selling NVDA", "published_at": "2026-08-16T01:20:17+00:00"}, {"title": "Nvidia might deliver another \u2018beat and raise\u2019 quarter, but its financing deals could be the bigger driver of NVDA stock", "published_at": "2026-08-23T01:20:17+00:00"}, {"title": "Jim Cramer says Nvidia is 'not going to stop here' as Ross Gerber sees NVDA stock hitting $450 as analysts dissect Q2 earnings", "published_at": "2026-08-08T01:20:17+00:00"}, {"title": "Michael Burry says NVDA stock appears \u2018wildly undervalued\u2019 on paper after blowout Q2 earnings, but warns Nvidia shares are still \u2018treading water\u2019", "published_at": "2026-08-12T01:20:17+00:00"}, {"title": "Nvidia stock is treading water ahead of earnings this week - what's the best NVDA play?", "published_at": "2026-08-24T01:20:17+00:00"}, {"title": "Stock market today: S&P 500, Nasdaq 100 futures gain following NVDA blockbuster Q2 report\u2014CRM, CRWD, HPQ in focus (updated)", "published_at": "2026-08-16T01:20:17+00:00"}, {"title": "NVDA stock comes off rough week: AI darling reportedly plans major price hike as Q2 earnings loom", "published_at": "2026-08-25T01:20:17+00:00"}, {"title": "BMO just named Nvidia a top pick as it initiates coverage. What this means for NVDA stock.", "published_at": "2026-08-26T01:20:17+00:00"}, {"title": "Nvidia (NVDA) Stock: Surge as $6 Billion Poolside Deal Strengthens AI Strategy Ahead of Earnings", "published_at": "2026-08-27T01:20:17+00:00"}, {"title": "Nvidia beats expectations on all Q2 metrics and estimates 70% jump in FY28 revenue \u2014 NVDA stock gains 5% after-hours", "published_at": "2026-08-27T01:20:17+00:00"}], "_cached_at": 1787880017.4905238} \ No newline at end of file diff --git a/ml_engine/cache/news/headlines_SPY.json b/ml_engine/cache/news/headlines_SPY.json new file mode 100644 index 0000000000000000000000000000000000000000..3ff3c12065a7a3bc61be3dfea8c7d0aae9258d84 --- /dev/null +++ b/ml_engine/cache/news/headlines_SPY.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "$3.8B SPY Exodus Meets $3.7B QQQ Inflow in One Day - State Street SPDR S&P 500...", "published_at": "2026-08-27T15:20:24+00:00"}, {"title": "SPY Looks 7.0% Overvalued on GF Value\u2122 as Traders Eye Key Pivot", "published_at": "2026-08-27T13:20:24+00:00"}, {"title": "Daily ETF Flows: TLT Gains", "published_at": "2026-08-26T01:20:24+00:00"}, {"title": "Understanding SPDR ETFs: Investment Strategies and Benefits", "published_at": "2026-08-18T01:20:24+00:00"}, {"title": "SCHD, DIVB beat QQQ, VOO and SPY as dividend ETFs ride AI hedging wave", "published_at": "2026-08-16T01:20:24+00:00"}, {"title": "Quick spark: SPY, GLD among biggest winners as $15.3 billion floods into ETFs in one day", "published_at": "2026-08-07T06:00:00+00:00"}, {"title": "Quick spark: SPY gets $1.9B boost in one day as QQQ, GLD and SOXL see outflows", "published_at": "2026-08-21T01:20:24+00:00"}, {"title": "Quick spark: $3.6B flows into SPY in one day; QQQ, SOXX lead ETF redemptions", "published_at": "2026-08-13T06:00:00+00:00"}, {"title": "Quick spark: Gold ETF leads inflows as investors pull billions from mega-cap ETFs in one day", "published_at": "2026-08-26T01:20:24+00:00"}, {"title": "SPY Looks 6.9% Overvalued on GF Value\u2122 as Inflation Data Shifts", "published_at": "2026-08-27T01:20:24+00:00"}], "_cached_at": 1787880024.7757308} \ No newline at end of file diff --git a/ml_engine/cache/news/headlines_TSLA.json b/ml_engine/cache/news/headlines_TSLA.json new file mode 100644 index 0000000000000000000000000000000000000000..1a8b5c112412351d5b162321de35bcd4923963cd --- /dev/null +++ b/ml_engine/cache/news/headlines_TSLA.json @@ -0,0 +1 @@ +{"_kind": "raw", "data": [{"title": "TSLA today: 6 driving forces behind the rally", "published_at": "2026-08-26T01:20:18+00:00"}, {"title": "Tesla stock surged 40% from here last year. Here's how to play TSLA stock in 2026.", "published_at": "2026-08-11T06:00:00+00:00"}, {"title": "Tesla (TSLA) Stock Dips as Cybertruck Price Jumps to $85,000", "published_at": "2026-08-26T01:20:18+00:00"}, {"title": "Tesla (TSLA) Stock Trades Down, Here Is Why", "published_at": "2026-07-23T06:00:00+00:00"}, {"title": "Tesla (TSLA) Stock Surges 5% Following Nevada\u2019s 5,000 Robo-Taxi Authorization", "published_at": "2026-08-25T01:20:18+00:00"}, {"title": "Great news for Tesla stock investors", "published_at": "2026-08-25T01:20:18+00:00"}, {"title": "TSLA stock eyes another winning week: Nevada clears up to 5,000 robotaxis, Musk sees 'crazy' Tesla growth", "published_at": "2026-08-22T01:20:18+00:00"}, {"title": "Tesla vs. SpaceX: Which Musk Stock Offers the Better Bet on the Future?", "published_at": "2026-08-22T01:20:18+00:00"}], "_cached_at": 1787880018.7611468} \ No newline at end of file diff --git a/ml_engine/data_pipeline.py b/ml_engine/data_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..80450657d1fd0d55e81b19850d741e94cbd7b704 --- /dev/null +++ b/ml_engine/data_pipeline.py @@ -0,0 +1,1041 @@ +""" +services/data_pipeline.py + +Fragmento de Ingeniería de Features — Pipeline NLP de Sentimiento de Noticias +============================================================================== +KodaQuant V5 — Requerimiento 1 (Cero Fricción / Anti-CAPTCHAs). + +Añade la variable continua `NEWS_SENTIMENT_SCORE` (rango [-1, 1]) al tensor +de entrada del modelo, calculada EXCLUSIVAMENTE con APIs nativas: + + 1) DDGS (DuckDuckGo News Search) -> fuente primaria, sin API key. + Reemplaza a `yfinance.Ticker(ticker).news` (yfinance retirado por + completo del proyecto, ver services/market_data.py) manteniendo el + mismo rol estructural: gratuita, sin key, no depende de que el + operador configure nada para tener AL MENOS cobertura básica. + 2) Finnhub REST API -> fallback, requiere FINNHUB_API_KEY. + `/company-news` para equities, `/news?category=crypto` para cripto + (ver `_is_crypto_ticker`/`_fetch_headlines_finnhub` — V6, fix de + "señal muerta" en crypto_specialist). + +PROHIBIDO en este módulo: Selenium, BeautifulSoup, requests directos a +portales de noticias, o cualquier scraping HTML iterativo. Cualquiera de +esos vectores colapsa el pipeline productivo ante CAPTCHAs, Cloudflare o +baneos de IP del proveedor de hosting — exactamente lo que este pipeline +está diseñado para evitar. DDGS consume el endpoint JSON de noticias de +DuckDuckGo (misma librería `ddgs` ya usada por +`quanti_engine.search_financial_web`, ya pineada en requirements.txt) — +no es scraping de HTML de portales de noticias individuales. + +V7 (auditoría "señal muerta" universal, post-fix-tz V6): dos fallos +independientes que colapsaban NEWS_SENTIMENT_SCORE a 0.0 EXACTO pese al +fix de timezone previo — (a) `_score_text` descartaba en silencio +cualquier etiqueta de FinBERT no reconocida (ej. LABEL_0/1/2 en vez de +positive/negative/neutral) sin loguear nada, para TODOS los tickers por +igual; (b) `get_daily_news_sentiment` exigía calce EXACTO de +fecha-calendario (`Series.reindex`), que nunca aterriza para titulares +publicados fin de semana/feriado en el universo de equities. Ver +docstrings de ambas funciones para el detalle completo. + +V8 (auditoría de atribución por gradiente, post-fix-señal-muerta V7): con +la señal ya viva (V7), NEWS_SENTIMENT_SCORE seguía rank 17/17 en +equity_specialist mientras SENTIMENT_SCORE (correlación móvil +activo<->VIX, ver train_kodaquant_v5.py/quanti_engine.py — variable de +régimen/beta derivada de precio, NO redundante con esta) dominaba el +Top 5. Diagnóstico: no es colisión de features, es cobertura de prensa +esporádica en equity (relleno neutro + saltos discretos = ruido de alta +frecuencia que el modelo aprende a ignorar). Fix: EMA regime-aware al +final de `get_daily_news_sentiment` — amortigua equity, no-op exacto en +cripto (flujo de noticias 24/7, la misma densidad que sostiene el +51.2%/52.3% de crypto_specialist). Ver constantes +`NEWS_SENTIMENT_EMA_SPAN_*` más abajo. Cero cambios en +train_kodaquant_v5.py/quanti_engine.py: ambos consumen esta función tal +cual, consistencia train/inferencia automática. + +V9 (consolidación del core, auditoría CTO 2026-08-16): `fetch_recent_headlines` +ahora cachea en disco vía `kodaquant_core.CacheManager` (TTL corto, +`KODAQUANT_NEWS_CACHE_TTL_SECONDS`, purga automática local en cada +llamada) -- reduce presión sobre DDGS/Finnhub sin tocar la lógica de +scoring/merge de abajo, que queda intacta. Ver `kodaquant_core.py` para el +resto de la consolidación (caché de OHLCV, cliente FRED, alineación de +calendario macro), compartida ahora con `train_kodaquant_v5.py`. + +V10 (auditoría "100% neutro" AMZN/META, post-rollback V23.6 equity): +`DDG_REGION` default venía en `"es-es"` -- sesga `ddgs.news(...)` hacia +resultados LOCALIZADOS a España (con mayor probabilidad de titulares en +español) para consultas de equities 100% US-listed (`"{TICKER} stock"`). +`ProsusAI/finbert` (`_score_text`) es un clasificador ENTRENADO +EXCLUSIVAMENTE en texto financiero en inglés (Financial PhraseBank) -- un +titular en español queda fuera de su distribución de entrenamiento y +tiende a colapsar a la clase "neutral" con score de confianza alto (no es +un titular sin opinión: es el modelo adivinando entre 3 clases sobre texto +que nunca vio en ese idioma). Esto es indistinguible, aguas abajo, del +caso legítimo "titular real sin carga direccional" -- exactamente el +síntoma reportado (9 titulares obtenidos para META, 0 warnings de +etiqueta-no-reconocida, score 100% neutro de todas formas: los titulares +SÍ llegaban y SÍ eran clasificables, solo que en el idioma equivocado para +este scorer). Fix: default cambiado a `"us-en"` (mercado real de todo el +universo de `equity_specialist`: AAPL/MSFT/NVDA/TSLA/GOOGL/AMZN/META/SPY, +todos NYSE/NASDAQ) -- sigue siendo 100% override-able vía env var +`DDG_REGION` si el operador necesita otra región por algún motivo. NO +toca `quanti_engine.py::DDG_REGION` (constante del mismo nombre pero +CONSUMIDOR DISTINTO: alimenta el RAG conversacional de Quanti para +usuarios que preguntan en español, vía `search_financial_web` -> Groq, +nunca pasa por FinBERT -- ahí "es-es" sigue siendo la región correcta y +no se toca). + +Analizador de sentimiento: FinBERT (`ProsusAI/finbert` vía `transformers`), +cargado perezosamente (singleton) y con selección automática de device +(GPU si disponible, CPU en runners de CI). `get_daily_news_sentiment` sigue +aceptando un `scorer_fn` intercambiable para no acoplar el resto del módulo +a este modelo en particular. + +Integración con `engineer_asset` (ver train_kodaquant_v5.py): + df["NEWS_SENTIMENT_SCORE"] = get_daily_news_sentiment(ticker, df.index) +Debe ejecutarse ANTES de que `TECH_COLS`/`feature_cols` arme el tensor de +entrada, junto al resto de los indicadores técnicos — nunca después de la +transformación a retornos logarítmicos del target. + +V11 (auditoría rescate 2026-08 -- "esto tiene que quedar perfecto"): 4 puntos +menores detectados en una corrida real de producción, ninguno bloqueante, +todos con fix real: + a) COLISIÓN DE ENV VAR (el único con impacto real en la señal): este + módulo y `quanti_engine.py` compartían el nombre `DDG_REGION` para + DOS propósitos incompatibles (RAG conversacional en español vs. + scoring FinBERT inglés-únicamente) -- fijar `DDG_REGION=es-es` para + el chat de Quanti reintroducía en silencio el bug "100% neutro" que + V10 creía cerrado. Fix: variable dedicada `NEWS_SENTIMENT_DDG_REGION`. + b) Filtro de idioma `langdetect` (opcional, gratis, sin key) como + defensa en profundidad DESPUÉS del fix de región -- poda la cola + larga de titulares fuera de idioma que un agregador global puede + colar incluso con la región correcta. + c) Reintento con query más amplia + fallback a `/news?category=general` + de Finnhub para ETFs (SPY, QQQ...) que nunca tienen perfil de + compañía en `/company-news` y antes se quedaban sin ninguna señal + de prensa cuando DDGS tampoco rendía para esa query específica. + d) `FutureWarning` cosmético de `huggingface_hub` (resume_download) + silenciado de forma acotada -- no afectaba nada, solo ruido de log. + +V12 (auditoría rescate 2026-08 -- crash real en despliegue HF Space): +`ModuleNotFoundError: No module named 'langdetect'` seguido de +`NameError: name 'logger' is not defined`, ambos en import-time de este +módulo (tumbaba todo el proceso, no solo esta feature). Causa raíz: el +bloque `try/except ImportError` de `langdetect` (V11, arriba) llamaba +`logger.warning(...)` en su rama `except`, pero `logger = +logging.getLogger(...)` se definía DEBAJO de ese bloque -- el except SÍ +atrapaba el `ModuleNotFoundError` real (es subclase de `ImportError`), +pero al intentar loguearlo lanzaba un `NameError` sin atrapar, que se +propagaba y abortaba la carga del módulo completo. Fix real: `logger` se +define ANTES de cualquier bloque que pueda loguear en su rama except +(orden, no manejo de excepciones nuevo). `langdetect` además se agrega a +requirements.txt (ver ese archivo) -- puro-Python, gratis, sin key -- para +que la defensa en profundidad V11 quede activa en producción en vez de +degradarse siempre al no-op silencioso. + +V13 (auditoría rescate 2026-08-31 -- re-verificación post-reporte de +`ModuleNotFoundError`/`NameError` en este mismo módulo): re-auditado línea +por línea contra el reporte. Ambos síntomas YA estaban resueltos por V12 +(arriba) en esta versión del archivo -- `logger` se define en la línea +correcta (antes del primer `except` que lo usa) y `langdetect==1.0.9` ya +está pineado en requirements.txt. Confirmado también con `pyflakes` (cero +warnings) y `ast.parse`/`py_compile` (sintaxis válida) sobre el archivo +completo -- CERO cambios funcionales en este módulo; el crash reportado no +reproduce contra este código fuente. Ver requirements.txt (RONDA 7) para +el crash real de esta corrida (`numpy`/`tensorflow`, módulo distinto). +""" + +from __future__ import annotations + +import logging +import os +import re +import sys +import threading +import time +import warnings +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Callable, Optional + +# V11 (auditoría 2026-08) -- `huggingface_hub` emite un FutureWarning +# cosmético ("resume_download is deprecated") en CADA carga de FinBERT vía +# `transformers.pipeline`, sin relación con ningún bug real de este módulo +# ni con la calidad de NEWS_SENTIMENT_SCORE. Acotado por `module=` a la +# librería exacta que lo emite -- nunca un `warnings.filterwarnings("ignore")` +# global, que enmascararía warnings reales de otras dependencias. +warnings.filterwarnings("ignore", category=FutureWarning, module=r"huggingface_hub\..*") + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (Directiva 2 — fin al Import Hell) ---- +# Este archivo vive ÚNICAMENTE en `ml_engine/` (Directiva 1: SINGLE SOURCE +# OF TRUTH). Sube desde este archivo hasta encontrar la raíz del proyecto +# -- el primer ancestro que contiene TANTO `ml_engine/` como `services/` +# como subdirectorios -- y la inserta en `sys.path[0]`. A partir de ahí, +# `ml_engine` y `services` son paquetes válidos sin importar desde qué +# directorio de trabajo se invoque `python .../data_pipeline.py` (directo, +# importado por `train_kodaquant_v5.py`, o vía `services.quanti_engine`). +# Reemplaza por completo el patrón try/except dual + copias duplicadas de +# `kodaquant_core.py` que causaba `ModuleNotFoundError`/`ImportError`. +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + # Fallback determinista: este archivo vive en ml_engine/, por lo que su + # abuelo es la raíz del proyecto por construcción, incluso si `services/` + # todavía no existe en el entorno actual (ej. checkout parcial/CI). + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# Núcleo compartido train/inferencia -- SINGLE SOURCE OF TRUTH en +# `ml_engine/kodaquant_core.py` (Directiva 1). Import directo y absoluto, +# sin fallback dual: con la raíz del proyecto ya en sys.path, esta ruta +# resuelve siempre, sin importar el cwd de invocación. +from ml_engine.kodaquant_core import CacheManager # noqa: E402 + +# --- PARCHE macOS Intel: runtimes OpenMP duplicados TensorFlow/PyTorch ---- +# `quanti_engine.py` carga TensorFlow/Keras (bundla Intel MKL -> libiomp5.dylib) +# EAGER al arrancar Uvicorn. PyTorch (bundla LLVM -> libomp.dylib) se importa +# LAZY aquí, recién en el primer request real. Ambos runtimes OpenMP en el +# mismo proceso es un conflicto conocido en macOS que puede impedir que +# torch cargue su extensión nativa. Debe fijarse ANTES del primer `import +# torch` — no tiene efecto si se fija después. +os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE") + +import pandas as pd +import requests # Únicamente para el endpoint JSON de Finnhub — API nativa, NO scraping. + +# --- Búsqueda de noticias vía DDGS (DuckDuckGo) — reemplaza a yfinance.news +# como fuente primaria, gratuita y sin API key (yfinance retirado por +# completo del proyecto, ver services/market_data.py). Mismo import +# defensivo (paquete renombrado `duckduckgo_search` -> `ddgs`) que ya usa +# `quanti_engine.search_financial_web`; `ddgs` ya está pineado en +# requirements.txt, cero dependencias nuevas. +logger = logging.getLogger("kodaquant.data_pipeline") + +try: + from ddgs import DDGS +except ImportError: # pragma: no cover + try: + from duckduckgo_search import DDGS # type: ignore[no-redef] + except ImportError: + DDGS = None # type: ignore[assignment,misc] # se valida en runtime, ver _fetch_headlines_ddg + +# V11 (auditoría 2026-08 — colisión de nombre de env var, root cause real +# del "100% neutro" que V10 creyó haber cerrado): V10 cambió el DEFAULT de +# este módulo a "us-en", pero seguía leyendo la MISMA variable de entorno +# `DDG_REGION` que usa `quanti_engine.py::DDG_REGION` para el buscador +# conversacional de Quanti (default "es-es", CORRECTO ahí -- los usuarios +# le hablan en español). Cualquier operador que fije `DDG_REGION=es-es` en +# su .env/entorno (lo natural para un producto en español) pisa SIN +# querer el default de ESTE módulo también -- las dos constantes comparten +# nombre pero NO deberían compartir valor: una alimenta un LLM que lee +# español perfectamente, la otra alimenta FinBERT, que es inglés-únicamente. +# Fix real: variable de entorno dedicada y jamás compartida con +# quanti_engine.py. Quien necesite tocar la región de este módulo usa +# `NEWS_SENTIMENT_DDG_REGION`, nunca `DDG_REGION`. +DDG_REGION = os.getenv("NEWS_SENTIMENT_DDG_REGION", "us-en") +DDG_SAFESEARCH = os.getenv("DDG_SAFESEARCH", "moderate") +MAX_DDG_HEADLINES = 10 # techo por-ticker -- Finnhub complementa si esto no alcanza + +# V11 — defensa en profundidad además del fix de región de arriba: agregadores +# de noticias globales pueden devolver un titular fuera de idioma incluso con +# la región correcta (ej. un medio hispano indexado igual bajo "us-en"). Un +# titular no-inglés que llega a FinBERT no lanza NINGÚN warning (ver V10) y +# se pierde como "neutral" falso -- indistinguible de una lectura neutra real. +# `langdetect` es puro-Python, gratuito, sin key, determinístico con seed fija +# -- se usa como filtro PREVIO al scorer, no como reemplazo del fix de región +# (más barato: si la región ya resuelve el 95% de los casos, este filtro solo +# poda la cola larga). Si no está instalado, se degrada a no-op con un único +# warning (nunca bloquea el pipeline). +try: + from langdetect import DetectorFactory as _LangDetectorFactory, detect_langs as _langdetect_detect_langs + _LangDetectorFactory.seed = 0 # determinístico -- sin esto, langdetect no es reproducible corrida a corrida + _LANGDETECT_AVAILABLE = True +except ImportError: # pragma: no cover + _LANGDETECT_AVAILABLE = False + logger.warning( + "langdetect no instalado (`pip install langdetect`) -- se omite el filtro de idioma " + "de defensa en profundidad; NEWS_SENTIMENT_DDG_REGION sigue siendo la defensa primaria." + ) + +# Caché de titulares (DDGS/Finnhub) — vida corta: la cobertura de prensa +# cambia varias veces al día, pero no vale la pena re-golpear DDGS/Finnhub +# en cada llamada de `get_daily_news_sentiment` dentro de la MISMA corrida +# (el radar escanea el universo completo en paralelo, ver +# `data_pipeline.get_daily_news_sentiment` invocado por cada régimen). +# Purga automática local (Requerimiento 1): `_headline_cache.purge_stale()` +# se invoca de forma perezosa en cada `fetch_recent_headlines` -- sin cron +# externo, sin intervención manual. +_HEADLINE_CACHE_DIR = Path(os.getenv("KODAQUANT_NEWS_CACHE_DIR", "cache/news")) +_HEADLINE_CACHE_TTL_SECONDS = int(os.getenv("KODAQUANT_NEWS_CACHE_TTL_SECONDS", str(2 * 3600))) +_headline_cache = CacheManager(_HEADLINE_CACHE_DIR, default_ttl_seconds=_HEADLINE_CACHE_TTL_SECONDS) + +# --------------------------------------------------------------------------- +# FinBERT — analizador de sentimiento transformer, carga perezosa (singleton) +# --------------------------------------------------------------------------- +_FINBERT_MODEL_NAME = "ProsusAI/finbert" +_FINBERT_LABEL_SIGN = {"positive": 1.0, "negative": -1.0, "neutral": 0.0} +# V7 (auditoría "señal muerta" UNIVERSAL — TODOS los activos, no solo cripto): +# ciertas combinaciones de `transformers`/config cacheado devuelven las +# etiquetas GENÉRICAS del clasificador (LABEL_0/LABEL_1/LABEL_2) en vez de +# las humanas positive/negative/neutral, cuando el `id2label` del modelo no +# se resuelve en tiempo de carga. Orden oficial de ProsusAI/finbert +# (config.json del modelo): 0=positive, 1=negative, 2=neutral. +_FINBERT_LABEL_ALIASES = {"label_0": "positive", "label_1": "negative", "label_2": "neutral"} +_finbert_pipeline = None +# RONDA 10 -- sentinela de FALLO cacheado (str del motivo, o None si aún no +# se intentó / tuvo éxito). Antes solo se cacheaba el ÉXITO (`_finbert_pipeline`) +# -- un fallo NUNCA quedaba memorizado, así que CADA titular individual +# repetía el import + intento de carga completo desde cero y volvía a +# producir el traceback entero -- la causa real de las "cientos de líneas +# de error" reportadas, no un crash único. Con esto: se diagnostica UNA +# vez, se loguea el traceback real completo UNA vez, y todo el resto del +# proceso degrada a NEUTRAL_SCORE con un mensaje corto de una línea. +_finbert_unavailable_reason: Optional[str] = None +# Protege la carga perezosa contra llamadas CONCURRENTES: bajo Uvicorn, +# get_daily_news_sentiment se dispara desde varios hilos a la vez (Plan A/Plan B +# en paralelo, radar escaneando el universo completo vía ThreadPoolExecutor). +# Sin lock, el primer request real puede disparar 2+ hilos importando +# torch/transformers simultáneamente -> ImportError transitorio de import +# parcial/circular, indistinguible de "no instalado" sin este fix. +_finbert_init_lock = threading.Lock() +# RONDA 10 -- piso REAL de transformers 5.x, verificado contra la guía de +# migración oficial de la librería (Python 3.10+, PyTorch 2.4+, +# huggingface_hub<2.0,>=1.3.0) -- NO 2.5 como asumía una auditoría previa. +_TRANSFORMERS_MIN_TORCH = (2, 4) + +# --- Backend ONNX (camino PRIMARIO, torch-independiente) ------------------- +_FINBERT_ONNX_REPO = os.getenv("KODAQUANT_FINBERT_ONNX_REPO", "Xenova/finbert").strip() +# V27 -- default cambiado de _FINBERT_MODEL_NAME (ProsusAI/finbert, sin +# export ONNX -> 404 permanente) a Xenova/finbert (mismo modelo base, +# mismas labels -- config.json id2label idéntico, verificado). Confirmado +# en producción: "[FinBERT/ONNX] sesión activa (Xenova/finbert ...)". +# KODAQUANT_FINBERT_ONNX_REPO sigue pisando esto si se necesita otro repo. +_FINBERT_ONNX_FILE = os.getenv("KODAQUANT_FINBERT_ONNX_FILE", "onnx/model.onnx").strip() +_FINBERT_ONNX_MAXLEN = 256 +_finbert_onnx = None # tuple(InferenceSession, Tokenizer, input_names) +_finbert_onnx_unavailable: Optional[str] = None +_finbert_onnx_lock = threading.Lock() + + +def _load_finbert_tokenizer(hf_hub_download): + """tokenizer.json (fast) con fallback a vocab.txt (WordPiece clásico).""" + from tokenizers import Tokenizer + try: + return Tokenizer.from_file(hf_hub_download(_FINBERT_ONNX_REPO, "tokenizer.json")) + except Exception: + from tokenizers import BertWordPieceTokenizer + vocab = hf_hub_download(_FINBERT_ONNX_REPO, "vocab.txt") + return BertWordPieceTokenizer(vocab, lowercase=True) + + +def _get_finbert_onnx(): + """Sesión ONNX + tokenizer (singleton thread-safe). Cero torch, cero TF. + + Esquiva `transformers.pipeline()` por completo -- ahí vive la NameError + de la compuerta torch>=2.4 diagnosticada en RONDA 10, que NINGÚN kwarg + de esta capa puede evitar. + """ + global _finbert_onnx, _finbert_onnx_unavailable + if _finbert_onnx is not None: + return _finbert_onnx + if _finbert_onnx_unavailable is not None: + raise FinBERTUnavailableError(_finbert_onnx_unavailable) + + with _finbert_onnx_lock: + if _finbert_onnx is not None: + return _finbert_onnx + if _finbert_onnx_unavailable is not None: + raise FinBERTUnavailableError(_finbert_onnx_unavailable) + try: + import numpy as _np + import onnxruntime as _ort + from huggingface_hub import hf_hub_download + except ImportError as exc: + _finbert_onnx_unavailable = ( + f"[FinBERT/ONNX] backend no instalado ({type(exc).__name__}: {exc}). " + "`pip install onnxruntime tokenizers` en el MISMO venv." + ) + logger.warning(_finbert_onnx_unavailable) + raise FinBERTUnavailableError(_finbert_onnx_unavailable) from exc + + try: + onnx_path = hf_hub_download(_FINBERT_ONNX_REPO, _FINBERT_ONNX_FILE) + tokenizer = _load_finbert_tokenizer(hf_hub_download) + opts = _ort.SessionOptions() + opts.intra_op_num_threads = 1 # ZeroGPU / Uvicorn multihilo + opts.graph_optimization_level = _ort.GraphOptimizationLevel.ORT_ENABLE_ALL + session = _ort.InferenceSession(onnx_path, opts, providers=["CPUExecutionProvider"]) + input_names = {i.name for i in session.get_inputs()} + _finbert_onnx = (session, tokenizer, input_names, _np) + logger.info("[FinBERT/ONNX] sesión activa (%s :: %s, inputs=%s).", + _FINBERT_ONNX_REPO, _FINBERT_ONNX_FILE, sorted(input_names)) + except Exception as exc: + _finbert_onnx_unavailable = ( + f"[FinBERT/ONNX] no se pudo abrir '{_FINBERT_ONNX_REPO}::{_FINBERT_ONNX_FILE}' " + f"({type(exc).__name__}: {exc}). Si es 404, ese repo no publica export ONNX -- " + "exportalo una vez y fijá KODAQUANT_FINBERT_ONNX_REPO/_FILE." + ) + logger.warning(_finbert_onnx_unavailable) + raise FinBERTUnavailableError(_finbert_onnx_unavailable) from exc + return _finbert_onnx + + +def _score_text_onnx(text: str) -> float: + session, tokenizer, input_names, _np = _get_finbert_onnx() + enc = tokenizer.encode(text) + ids = enc.ids[:_FINBERT_ONNX_MAXLEN] + mask = (enc.attention_mask[:_FINBERT_ONNX_MAXLEN] + if getattr(enc, "attention_mask", None) else [1] * len(ids)) + feed = {"input_ids": _np.asarray([ids], dtype=_np.int64), + "attention_mask": _np.asarray([mask], dtype=_np.int64)} + if "token_type_ids" in input_names: + feed["token_type_ids"] = _np.zeros((1, len(ids)), dtype=_np.int64) + logits = _np.asarray(session.run(None, {k: v for k, v in feed.items() + if k in input_names})[0][0], dtype=_np.float64) + exp = _np.exp(logits - logits.max()) + probs = exp / exp.sum() + # id2label oficial de ProsusAI/finbert: 0=positive, 1=negative, 2=neutral + return float(probs[0] - probs[1]) + + +def news_sentiment_available() -> bool: + """Probe determinista -- ¿hay ALGÚN backend capaz de puntuar sentimiento? + + Consumido por `train_kodaquant_v5.run_regime_pipeline` para decidir, UNA + vez y antes de construir el tensor, si NEWS_SENTIMENT_SCORE entra o se + excluye. Inyectar 0.0 constante es peor que excluirla: el feature_scaler + se ajusta sobre una constante y la red aprende un slot muerto. + """ + try: + _get_finbert_onnx() + return True + except Exception: + pass + try: + _get_finbert_pipeline() + return True + except Exception: + return False + + +class FinBERTUnavailableError(ImportError): + """RONDA 10 -- excepción DEDICADA para el caso 'ya diagnosticado, no + reintentable en este proceso' (piso de torch no alcanzado / backend TF + inexistente en transformers 5.x). `_score_text` la distingue de un + ImportError genérico para loguear corto (sin traceback repetido) en + vez de con `exc_info=True` en cada titular -- ver ahí.""" + + +def _get_finbert_pipeline(): + """Carga perezosa (singleton, thread-safe) del pipeline FinBERT — CPU-safe para runners sin GPU. + + RONDA 10 (fix REAL, reemplaza el intento fallido de RONDA 6-9) -- + diagnóstico verificado contra el TRACEBACK REAL producido en Mac Intel + (no solo contra el código fuente): el intento anterior de "fallback a + backend TensorFlow" era imposible de raíz, no un bug de esta función. + Evidencia: el segundo intento (`framework="tf"`) reventó con la + EXACTA MISMA `NameError: name 'torch' is not defined` en la EXACTA + MISMA línea (`transformers/pipelines/__init__.py::pipeline`, chequeo + `isinstance(dtype, str) and hasattr(torch, dtype)`) que el primero -- + esa línea corre ANTES de cualquier rama específica de framework, así + que reintentar con otro framework nunca podía esquivarla. Confirmado + además contra la guía de migración oficial de transformers 5.x: la + serie 5.x eliminó el backend TensorFlow POR COMPLETO y sin período de + gracia (PyTorch es el único backend soportado) -- no había ninguna + rama TF real a la que caer, el `except NameError: ... framework="tf"` + de las rondas previas apuntaba a código que ya no existe en la + librería instalada (`transformers==5.15.0`, ver requirements.txt). + El piso real es torch>=2.4 (Python 3.10+/huggingface_hub<2.0,>=1.3.0 + son los otros dos). En macOS Intel (x86_64) NINGÚN wheel de `torch` + >2.2.2 existe en PyPI -- techo real y permanente de esa plataforma, no + arreglable con más código. Pinear `transformers` a la serie 4.x (que + SÍ soportaba TF) NO es salida: esa serie exige `huggingface-hub<1.0` + en TODAS sus versiones (confirmado en vivo, incl. el último release + 4.57.x), lo que choca de frente con `huggingface-hub<2.0,>=1.16.0` que + ya exige `gradio[oauth,mcp]==6.22.0` en el MISMO requirements.txt -- + `ResolutionImpossible` real, no evitable sin romper el build de HF + Spaces (`gradio` no está platform-split, no puede estarlo: `sdk_version` + del README.md debe calzar exacto para TODA plataforma). + Conclusión honesta: FinBERT vía `transformers.pipeline()` es + IRRECUPERABLE en Mac Intel local con esta cadena de dependencias -- + no es arreglable sin (a) un Mac Apple Silicon/Linux real, o (b) + remover `gradio[mcp]` del proyecto para poder bajar a transformers 4.x. + Producción (HF Space, Linux, `torch==2.11.0`) NO está afectada -- ahí + `torch_ver >= _TRANSFORMERS_MIN_TORCH` es verdadero y el pipeline + PyTorch carga y sirve FinBERT completo, sin ninguna rama de este fix + involucrada. Este fix, entonces, es sobre CALIDAD DE FALLO en Mac + Intel (un diagnóstico honesto, una sola vez, degrade limpio a + NEUTRAL_SCORE) -- no sobre "hacer funcionar" algo que la librería ya + no soporta en esa plataforma. + """ + global _finbert_pipeline, _finbert_unavailable_reason + if _finbert_pipeline is not None: + return _finbert_pipeline + if _finbert_unavailable_reason is not None: + raise FinBERTUnavailableError(_finbert_unavailable_reason) + + with _finbert_init_lock: + if _finbert_pipeline is not None: # doble check: otro hilo ya lo cargó mientras esperábamos el lock + return _finbert_pipeline + if _finbert_unavailable_reason is not None: # ídem, otro hilo ya lo diagnosticó como inviable + raise FinBERTUnavailableError(_finbert_unavailable_reason) + + try: + import torch + from transformers import pipeline as _hf_pipeline + from transformers.utils import is_torch_available + except ModuleNotFoundError as exc: + # Caso real de "no instalado": el paquete no existe en este intérprete. + _finbert_unavailable_reason = ( + f"torch/transformers no están instalados en {sys.executable}: {exc}. " + "Ejecuta `pip install torch transformers` en el MISMO venv que corre Uvicorn." + ) + raise ImportError(_finbert_unavailable_reason) from exc + except ImportError as exc: + # CUALQUIER OTRO ImportError (símbolo nativo, dlopen roto, import + # circular parcial por carrera entre hilos, etc.) — antes se + # enmascaraba con el mismo mensaje genérico de "no instalado". + # Se preserva el tipo y mensaje reales para que el log no mienta. + _finbert_unavailable_reason = ( + f"torch/transformers están instalados pero fallaron al importar " + f"({type(exc).__name__}: {exc}). NO es un paquete faltante — revisa " + "conflictos nativos (runtimes OpenMP duplicados TF/PyTorch en macOS, " + "ver KMP_DUPLICATE_LIB_OK) o reinstala ambos paquetes emparejados." + ) + raise ImportError(_finbert_unavailable_reason) from exc + + _ver_match = re.match(r"(\d+)\.(\d+)", torch.__version__) + torch_ver = tuple(int(p) for p in _ver_match.groups()) if _ver_match else (0, 0) + if not is_torch_available() or torch_ver < _TRANSFORMERS_MIN_TORCH: + _finbert_unavailable_reason = ( + f"[FinBERT] no disponible en este proceso: torch {torch.__version__} " + f"instalado, transformers {__import__('transformers').__version__} exige " + f"torch>={'.'.join(map(str, _TRANSFORMERS_MIN_TORCH))} y ELIMINÓ el backend " + "TensorFlow por completo en la serie 5.x (verificado: framework='tf' dispara " + "la MISMA NameError compartida en pipeline() antes de cualquier rama TF real " + "-- no hay fallback posible). En macOS Intel ningún wheel de torch >2.2.2 " + "existe en PyPI (techo real de plataforma). NEWS_SENTIMENT_SCORE degradará a " + "NEUTRAL_SCORE de forma consistente en este proceso -- producción " + "(Linux, torch==2.11.0) no está afectada, ahí el piso SÍ se cumple." + ) + logger.error(_finbert_unavailable_reason) + raise FinBERTUnavailableError(_finbert_unavailable_reason) + + device = 0 if torch.cuda.is_available() else -1 + try: + _finbert_pipeline = _hf_pipeline( + "sentiment-analysis", model=_FINBERT_MODEL_NAME, + tokenizer=_FINBERT_MODEL_NAME, truncation=True, device=device, + dtype=None, # esquiva `isinstance(dtype, str) and hasattr(torch, dtype)` (ver docstring) + ) + except Exception as exc: + _finbert_unavailable_reason = ( + f"[FinBERT] pipeline PyTorch falló pese a pasar el check de versión/" + f"is_torch_available() ({type(exc).__name__}: {exc})." + ) + logger.error(_finbert_unavailable_reason, exc_info=True) + raise FinBERTUnavailableError(_finbert_unavailable_reason) from exc + return _finbert_pipeline + +FINNHUB_API_KEY = os.getenv("FINNHUB_API_KEY", "").strip() +# V6 (auditoría "señal muerta" crypto_specialist) — `/company-news` es +# EXCLUSIVO para equities listadas en EE. UU. (doc oficial Finnhub); jamás +# devuelve resultados para tickers cripto. `/news?category=crypto` es el +# endpoint correcto para ese universo — ver `_fetch_headlines_finnhub`. +FINNHUB_COMPANY_NEWS_URL = "https://finnhub.io/api/v1/company-news" +FINNHUB_CRYPTO_NEWS_URL = "https://finnhub.io/api/v1/news" +# V11 -- MISMO endpoint que FINNHUB_CRYPTO_NEWS_URL (Finnhub `/news` acepta +# `category` general/forex/crypto/merger); alias legible para el fallback de +# ETFs (`_fetch_headlines_finnhub`, ver auditoría 2026-08), nunca un endpoint nuevo. +FINNHUB_GENERAL_NEWS_URL = FINNHUB_CRYPTO_NEWS_URL + +NEWS_LOOKBACK_DAYS = 7 # ventana de titulares recientes a recolectar (fallback Finnhub) +MAX_HEADLINES_PER_TICKER = 60 # techo defensivo (rate-limit / ruido) +NEUTRAL_SCORE = 0.0 # relleno para días/activos sin cobertura de prensa +# V7 — tolerancia del merge_asof temporal (ver get_daily_news_sentiment): +# NEWS_LOOKBACK_DAYS + colchón de fin de semana/feriado, para que un titular +# del viernes siga cubriendo el lunes bursátil sin exigir calce EXACTO de +# fecha (el bug que _NEWS_MERGE_TOLERANCE_DAYS/pd.merge_asof reemplaza) y, +# a la vez, sin arrastrar sentimiento añejo indefinidamente como hacía el +# `.ffill()` sin cota que tenía este merge antes. +_NEWS_MERGE_TOLERANCE_DAYS = NEWS_LOOKBACK_DAYS + 3 + +_RETRY_ATTEMPTS = 3 +_RETRY_BACKOFF_SECONDS = 1.5 + +# --- V8 (Filtrado Regime-Aware — aislamiento de ruido equity sin tocar cripto) --- +# Auditoría de atribución por gradiente: NEWS_SENTIMENT_SCORE cae a +# rank 17/17 en equity_specialist. Causa raíz NO es colisión con +# SENTIMENT_SCORE (esa es la correlación móvil activo<->VIX de +# compute_sentiment_score en train_kodaquant_v5.py/quanti_engine.py — un +# proxy de régimen/beta derivado 100% de precio, variable estructuralmente +# distinta de esta, cero solapamiento de información): es que la cobertura +# de prensa por-ticker vía DDGS/Finnhub es ESPORÁDICA en equity (pocos +# titulares/semana), así que la señal día a día alterna tramos planos +# (relleno neutro) con saltos discretos cada vez que aterriza un titular — +# exactamente el patrón de alta frecuencia que un BiLSTM aprende a +# descontar como ruido. crypto_specialist NO sufre esto: `/news?category= +# crypto` entrega flujo 24/7 sin huecos, la misma densidad/volatilidad +# cruda que llevó a crypto_specialist a 51.2%/52.3% de asertividad — jamás +# se suaviza. +# Fix: EMA regime-aware aplicado DENTRO de get_daily_news_sentiment (única +# fuente de esta columna para train_kodaquant_v5.py Y quanti_engine.py) -> +# consistencia train/inferencia automática, cero cambios en esos dos +# archivos, cero impacto en TECH_COLS/N_FEATURES/(batch,60,17). +NEWS_SENTIMENT_EMA_SPAN_EQUITY = 5 # ~1 semana bursátil: amortigua saltos discretos sin borrar la tendencia real +NEWS_SENTIMENT_EMA_SPAN_CRYPTO = 1 # span=1 -> alpha=2/(span+1)=1.0 -> no-op matemático exacto, señal cruda intacta + + +def _score_text(text: str) -> float: + """Escalar direccional (∈[-1, 1]) de un titular vía FinBERT (ProsusAI/finbert).""" + if not text: + return NEUTRAL_SCORE + if _finbert_onnx is not None or _finbert_onnx_unavailable is None: + try: + return _score_text_onnx(text[:2048]) + except FinBERTUnavailableError: + pass # diagnosticado UNA vez en _get_finbert_onnx -> cae a torch + except Exception as exc: # noqa: BLE001 + logger.warning("[FinBERT/ONNX] fallo de inferencia (%s: %s) -> fallback torch.", + type(exc).__name__, exc) + try: + result = _get_finbert_pipeline()(text[:512])[0] + raw_label = str(result["label"]).lower() + label = _FINBERT_LABEL_ALIASES.get(raw_label, raw_label) + if label not in _FINBERT_LABEL_SIGN: + # FIX RAÍZ V7 (auditoría "señal muerta" universal — 10 titulares + # obtenidos, 100% neutro, TODOS los activos, sin ningún otro + # warning en el log): antes, una etiqueta no reconocida caía en + # `_FINBERT_LABEL_SIGN.get(label, 0.0)` -> 0.0 SILENCIOSO. No es + # una excepción (no dispara el except de abajo), así que NUNCA + # quedaba rastro en el log de por qué el score era siempre 0 — + # exactamente el síntoma reportado, y explica por qué persistía + # pese al fix de timezone (esa parte del pipeline nunca fue el + # problema: los titulares SÍ llegaban, pero cada uno puntuaba + # 0.0 antes de tocar cualquier lógica de fechas). Ahora es ruidoso. + logger.warning( + "FinBERT devolvió una etiqueta no reconocida %r (fuera de " + "_FINBERT_LABEL_SIGN/_FINBERT_LABEL_ALIASES) -> score forzado " + "a NEUTRAL_SCORE para este titular. Verifica la versión de " + "`transformers` / el config.json de %s (id2label esperado: " + "0=positive, 1=negative, 2=neutral).", result["label"], _FINBERT_MODEL_NAME, + ) + return NEUTRAL_SCORE + sign = _FINBERT_LABEL_SIGN[label] + return float(sign * result["score"]) + except FinBERTUnavailableError: + # RONDA 10 -- caso YA diagnosticado con traceback completo UNA vez + # dentro de `_get_finbert_pipeline` (logger.error/exc_info=True ahí). + # Repetir el traceback completo por CADA titular es exactamente la + # causa real de las "cientos de líneas de error" reportadas -- acá + # alcanza con un rastro corto, sin traceback, por titular. + logger.debug("FinBERT no disponible en este proceso (ver diagnóstico previo) -> NEUTRAL_SCORE.") + return NEUTRAL_SCORE + except Exception as exc: # noqa: BLE001 — fallo de inferencia del modelo local, causa NO diagnosticada aún + # exc_info=True: antes se logueaba solo %r del error (a veces ya + # reescrito con un mensaje genérico), sin traceback — la causa real + # (incl. __cause__ encadenado) quedaba invisible en los logs de + # Uvicorn. Ahora se propaga completa -- SOLO para fallos nuevos/no + # cacheados (ver FinBERTUnavailableError arriba para el caso ya + # conocido). + logger.warning( + "FinBERT falló al puntuar titular (%s: %s)", type(exc).__name__, exc, + exc_info=True, + ) + return NEUTRAL_SCORE + + +def _normalize_timestamp(ts_raw) -> Optional[datetime]: + """Normaliza epoch (int/float) o string de fecha a `datetime` UTC.""" + if ts_raw is None: + return None + try: + if isinstance(ts_raw, (int, float)): + return datetime.fromtimestamp(float(ts_raw), tz=timezone.utc) + return pd.Timestamp(ts_raw, tz="UTC").to_pydatetime() + except (ValueError, TypeError, OSError): + return None + + +# V11 -- umbral calibrado empíricamente (ver auditoría 2026-08): `detect()` +# ingenuo (top-1, sin probabilidad) da FALSOS POSITIVOS reales en titulares +# financieros cortos -- "Tesla stock drops on delivery miss" clasificó como +# sueco con `detect()`. `detect_langs()` expone la distribución de +# probabilidad completa; frases reales en español/inglés (>=20 chars) +# resuelven con >0.999 de confianza al idioma correcto, mientras que el +# ruido de titulares cortos ambiguos rara vez supera 0.97 -- de ahí el +# doble filtro (confianza alta Y longitud mínima) en vez de un simple +# top-1, que habría descartado titulares en inglés legítimos. +_LANGDETECT_MIN_CONFIDENCE = 0.97 +_LANGDETECT_MIN_LENGTH = 20 + + +def _is_english_headline(title: str) -> bool: + """ + Defensa en profundidad (V11) -- filtro de idioma PREVIO al scorer. + `True` (se deja pasar a FinBERT) salvo que `langdetect` esté MUY seguro + (`prob >= _LANGDETECT_MIN_CONFIDENCE`) de que el idioma NO es inglés, + sobre un titular con longitud suficiente para que esa confianza sea + confiable (`len >= _LANGDETECT_MIN_LENGTH`) -- en cualquier otro caso + (ambiguo, corto, o `langdetect` no instalado) se deja pasar: este + filtro poda la cola larga de titulares CLARAMENTE no-ingleses, nunca + reemplaza el fix de región (`NEWS_SENTIMENT_DDG_REGION`). + """ + if not _LANGDETECT_AVAILABLE or not title or len(title) < _LANGDETECT_MIN_LENGTH: + return True + try: + top = _langdetect_detect_langs(title)[0] + except Exception: # noqa: BLE001 -- langdetect lanza LangDetectException en texto ambiguo + return True + return not (top.lang != "en" and top.prob >= _LANGDETECT_MIN_CONFIDENCE) + + +def _fetch_headlines_ddg(ticker: str, max_results: int = MAX_DDG_HEADLINES) -> list[dict]: + """ + Fuente primaria — búsqueda de noticias vía DDGS (`ddgs.news`, JSON nativo + de DuckDuckGo, sin scraping de portales individuales, sin API key). + Reemplaza 1:1 el rol de `yfinance.Ticker(ticker).news` (retirado, ver + services/market_data.py): misma firma de retorno (`title`/`published_at`), + mismo lugar en `fetch_recent_headlines` (primaria, Finnhub complementa). + + V11 (auditoría 2026-08) -- dos mejoras sobre la fuente primaria: + (a) reintento con query MÁS AMPLIA si la query específica (`"{ticker} + stock"`) devuelve 0 resultados -- tickers de baja cobertura de + prensa dedicada (ETFs como SPY, sin "compañía" detrás) rendían + "No results found" en vez de degradarse a Finnhub con más señal. + (b) filtro de idioma (`_is_english_headline`) ANTES de devolver los + titulares -- ver V11 arriba. + """ + if DDGS is None: + logger.warning("DDGS no instalado (`pip install ddgs`) -- fuente primaria de noticias deshabilitada; solo Finnhub (si hay API key).") + return [] + + # Cripto: "-USD" es la convención de símbolo de todo el proyecto + # (REGIME_TICKERS/MACRO_SYMBOL_MAP), no específica de ningún proveedor + # -- se usa solo el símbolo base (ej. "BTC") para una query de noticias + # más natural que "BTC-USD". + is_crypto = _is_crypto_ticker(ticker) + base_symbol = ticker.split("-")[0] + queries = [f"{base_symbol} crypto"] if is_crypto else [f"{ticker} stock", f"{ticker} ETF", base_symbol] + + raw: list[dict] = [] + for query in queries: + try: + with DDGS() as ddgs: + raw = list( + ddgs.news(query, region=DDG_REGION, safesearch=DDG_SAFESEARCH, max_results=max_results) + ) + except Exception as exc: # noqa: BLE001 -- red/HTTP transitorio de DDG + logger.warning("DDGS.news falló para %s (query=%r): %r", ticker, query, exc) + continue + if raw: + break # primera query con resultados gana -- no seguimos ampliando innecesariamente + + headlines = [] + dropped_non_english = 0 + for item in raw: + title = (item.get("title") or "").strip() + published_at = _normalize_timestamp(item.get("date")) + if not title or published_at is None: + continue + if not _is_english_headline(title): + dropped_non_english += 1 + continue + headlines.append({"title": title, "published_at": published_at}) + if dropped_non_english: + logger.debug("%s: %d titular(es) descartado(s) por filtro de idioma (no-inglés).", ticker, dropped_non_english) + return headlines + + +def _is_crypto_ticker(ticker: str) -> bool: + """ + Heurística deliberadamente auto-contenida (sin importar `REGIME_TICKERS` + de quanti_engine.py/train_kodaquant_v5.py: SON quienes importan + data_pipeline.py, importar en sentido inverso crearía un ciclo). La + convención de todo el proyecto para cripto es SIEMPRE '-USD' + (BTC-USD, ETH-USD); ningún ticker de equity/ETF del universo entrenado + usa ese sufijo -> heurística exacta y suficiente para este propósito. + """ + return ticker.upper().endswith("-USD") + + +def _fetch_headlines_finnhub(ticker: str, lookback_days: int = NEWS_LOOKBACK_DAYS) -> list[dict]: + """ + Fallback — API REST gratuita de Finnhub, JSON puro, sin scraping. + Requiere `FINNHUB_API_KEY` en el entorno; si falta, se omite + silenciosamente (DDGS sigue siendo la fuente primaria y suficiente + en la mayoría de los casos). + + V6 (auditoría "señal muerta" `crypto_specialist`, NEWS_SENTIMENT_SCORE + rank 17/17, atribución 0.000000) — FIX de enrutamiento: `/company-news` + es EXCLUSIVO para equities listadas en EE. UU. (documentación oficial + de Finnhub) y nunca devuelve resultados para tickers cripto; antes se + llamaba ese mismo endpoint también para BTC-USD/ETH-USD, vaciando + silenciosamente el fallback justo para el régimen que más lo necesita. + Se enruta ahora vía `_is_crypto_ticker` al endpoint general + `/news?category=crypto` para cripto (sin filtro por símbolo: el tier + gratuito de Finnhub no ofrece news cripto por-moneda -> se filtra la + ventana `lookback_days` del lado del cliente, ya que ese endpoint no + acepta `from`/`to`) y mantiene `/company-news` intacto para equities. + """ + if not FINNHUB_API_KEY: + logger.debug("FINNHUB_API_KEY no configurada; se omite el fallback de Finnhub.") + return [] + + is_crypto = _is_crypto_ticker(ticker) + url = FINNHUB_CRYPTO_NEWS_URL if is_crypto else FINNHUB_COMPANY_NEWS_URL + today = datetime.now(timezone.utc).date() + since = today - timedelta(days=lookback_days) + if is_crypto: + params = {"category": "crypto", "token": FINNHUB_API_KEY} + else: + params = { + "symbol": ticker, + "from": since.isoformat(), + "to": today.isoformat(), + "token": FINNHUB_API_KEY, + } + + # `filter_clientside_by_date`: True para cualquier llamada al endpoint + # genérico `/news` (crypto O general), que NO acepta `from`/`to` + # server-side -- `/company-news` sí los acepta (ver `params` arriba), + # así que ese caso no necesita el recorte extra. + headlines = _fetch_finnhub_json(url, params, ticker, filter_clientside_by_date=is_crypto, since=since) + + # V11 (auditoría 2026-08) -- `/company-news` es EXCLUSIVO de compañías + # con perfil en Finnhub; ETFs (SPY, QQQ, ...) NUNCA tienen uno y + # devuelven [] SIEMPRE, sin importar cuántos reintentos. Fallback a + # `/news?category=general` (mercado agregado) filtrado client-side por + # el símbolo/nombre del ticker en el titular -- mejor que dejar el + # activo entero sin ninguna señal de prensa cuando DDGS tampoco rindió. + if not headlines and not is_crypto: + general_params = {"category": "general", "token": FINNHUB_API_KEY} + general = _fetch_finnhub_json(FINNHUB_GENERAL_NEWS_URL, general_params, ticker, + filter_clientside_by_date=True, since=since) + needle = ticker.upper() + headlines = [h for h in general if needle in h["title"].upper()] + + return headlines + + +def _fetch_finnhub_json(url: str, params: dict, ticker: str, filter_clientside_by_date: bool, since) -> list[dict]: + """Request GET con reintentos -- extraído de `_fetch_headlines_finnhub` para + reutilizarlo también en el fallback `/news?category=general` de ETFs. + `filter_clientside_by_date`: True para endpoints sin `from`/`to` + server-side (`/news`, crypto o general) -- recorta del lado del cliente + contra `since` para no arrastrar noticias arbitrariamente viejas.""" + last_exc: Exception | None = None + for attempt in range(1, _RETRY_ATTEMPTS + 1): + try: + response = requests.get(url, params=params, timeout=10) + response.raise_for_status() + payload = response.json() or [] + headlines = [] + for item in payload[:MAX_HEADLINES_PER_TICKER]: + title = item.get("headline") or item.get("summary") or "" + published_at = _normalize_timestamp(item.get("datetime")) + if filter_clientside_by_date and published_at is not None and published_at.date() < since: + continue + if title and published_at is not None: + headlines.append({"title": title, "published_at": published_at}) + return headlines + except Exception as exc: # noqa: BLE001 — red/HTTP transitorio + last_exc = exc + if attempt == _RETRY_ATTEMPTS: + break + time.sleep(_RETRY_BACKOFF_SECONDS * attempt) + + logger.warning("Finnhub falló tras %d intentos para %s: %r", _RETRY_ATTEMPTS, ticker, last_exc) + return [] + + +def fetch_recent_headlines(ticker: str) -> list[dict]: + """ + Orquesta ambas fuentes nativas (DDGS -> Finnhub) y deduplica por + título. DDGS es la fuente primaria (no exige API key); Finnhub + complementa cobertura solo cuando DDGS devuelve pocos titulares. + + CacheManager (kodaquant_core): cachea el resultado ya deduplicado por + `_HEADLINE_CACHE_TTL_SECONDS` -- evita re-golpear DDGS/Finnhub por + ticker dentro de la misma ventana corta cuando el radar escanea el + universo completo. Purga automática local en cada llamada (best-effort, + nunca bloquea el fetch real si falla). + """ + try: + _headline_cache.purge_stale() + except Exception as exc: # noqa: BLE001 -- la purga nunca debe tumbar el fetch real + logger.debug("[CacheManager] purge_stale falló (%r) -- se ignora.", exc) + + cache_key = f"headlines_{ticker}" + cached = _headline_cache.get_json(cache_key) + if cached is not None: + for h in cached: + h["published_at"] = _normalize_timestamp(h.get("published_at")) + return [h for h in cached if h.get("published_at") is not None] + + headlines = _fetch_headlines_ddg(ticker) + if len(headlines) < 5: + headlines += _fetch_headlines_finnhub(ticker) + + seen_titles: set[str] = set() + deduped: list[dict] = [] + for h in headlines: + if h["title"] not in seen_titles: + seen_titles.add(h["title"]) + deduped.append(h) + deduped = deduped[:MAX_HEADLINES_PER_TICKER] + + serializable = [ + {"title": h["title"], "published_at": h["published_at"].isoformat()} + for h in deduped + ] + _headline_cache.set_json(cache_key, serializable) + return deduped + + +def get_daily_news_sentiment( + ticker: str, + target_index: pd.DatetimeIndex, + scorer_fn: Callable[[str], float] = _score_text, +) -> pd.Series: + """ + Devuelve `NEWS_SENTIMENT_SCORE` alineado día a día contra `target_index` + (el mismo índice temporal que ya usan RSI/MACD/ATR/etc.). Cada titular se + promedia por día de publicación (UTC, normalizado a medianoche); los + días sin cobertura de prensa se rellenan hacia adelante (`ffill`) y, si + no hay ningún titular previo disponible, con `NEUTRAL_SCORE` (0.0) — la + misma convención de "lectura neutra" que SENTIMENT_SCORE ya usa en V4. + + Esta función debe llamarse ANTES de concatenar el tensor final al + espacio de entrada (batch, time_steps, features), junto al resto de los + indicadores técnicos en `engineer_asset`. + + FIX RAÍZ V7 (auditoría "señal muerta" — persiste tras el fix de tz V6, + NEWS_SENTIMENT_SCORE rank 17/17, atribución exacta 0.000000, EN TODOS + LOS ACTIVOS, no solo cripto): el fix V6 (despojar tz antes de comparar + fechas) era necesario pero NO suficiente — quedaban dos fallos + independientes, cualquiera de los dos basta por sí solo para colapsar + la columna entera a 0.0: + + (a) SCORER: ver `_score_text` — una etiqueta de FinBERT no reconocida + caía en `.get(label, 0.0)` -> 0.0 silencioso, SIN excepción, para + el 100% de los titulares, en TODOS los tickers por igual (fix + separado, ver ese docstring). + (b) MERGE: `Series.reindex` exige que la fecha-calendario del + titular calce EXACTA (bit a bit) con una fila del índice de + trading. Cripto cotiza 24/7 (hay fila para cada día), pero + equities NO — cualquier titular publicado un fin de semana o + feriado bursátil no tenía dónde aterrizar y quedaba NaN -> 0.0, + sin importar qué tan bien alineados estuvieran los tz. Se + reemplaza por `pd.merge_asof(direction="backward")`: busca el + titular MÁS RECIENTE publicado EN O ANTES de cada fecha del + índice (sin exigir igualdad exacta), acotado por + `_NEWS_MERGE_TOLERANCE_DAYS` para no arrastrar sentimiento añejo + indefinidamente como hacía el `.ffill()` sin cota anterior. + + Ambos lados de la fecha se normalizan ahora de forma SIMÉTRICA a + fecha-calendario UTC (`tz_convert("UTC")` real, no un `tz_localize(None)` + que solo despoja la etiqueta sin convertir el instante) — antes los + titulares se convertían a UTC pero `target_index` solo se despojaba de + su tz "tal cual", una asimetría de la que dependía silenciosamente el + calce. + """ + headlines = fetch_recent_headlines(ticker) + + if not headlines: + logger.info("Sin titulares recientes para %s -> NEWS_SENTIMENT_SCORE neutro.", ticker) + return pd.Series(NEUTRAL_SCORE, index=target_index, name="NEWS_SENTIMENT_SCORE") + + scored = pd.DataFrame(headlines) + scored["score"] = scored["title"].map(scorer_fn) + + # Diagnóstico (a): aísla un SCORER muerto de un MERGE con mala cobertura + # temporal — antes ambos colapsaban al mismo mensaje genérico y eran + # indistinguibles desde el log. + nonzero_scores = int((scored["score"].abs() > 1e-9).sum()) + + scored["date"] = ( + pd.DatetimeIndex(scored["published_at"]).tz_convert("UTC").tz_localize(None).normalize() + ) + daily = ( + scored.groupby("date")["score"].mean() + .sort_index() + .rename("headline_score") + .reset_index() + ) + + target_dt = pd.DatetimeIndex(target_index) + if target_dt.tz is not None: + target_dates = target_dt.tz_convert("UTC").tz_localize(None).normalize() + else: + target_dates = target_dt.normalize() + + # FIX: pandas 3.x ya no fuerza datetime64[ns] en todos lados -- conserva + # la resolución de origen de cada Serie (target_index puede venir en + # [us] del feed de mercado (Twelve Data/Stooq, ver services/market_data.py), + # "date" en [s] desde el parseo de published_at). + # merge_asof exige que ambas claves compartan EXACTAMENTE el mismo + # dtype, si no: "incompatible merge keys ... must be the same type". + # Se normalizan ambas a [ns] explícitamente antes de mergear. + frame = pd.DataFrame({"target_date": target_dates.astype("datetime64[ns]")}) + frame["orig_pos"] = range(len(frame)) + frame_sorted = frame.sort_values("target_date", kind="stable") + daily["date"] = daily["date"].astype("datetime64[ns]") + + merged = pd.merge_asof( + frame_sorted, + daily, + left_on="target_date", + right_on="date", + direction="backward", + tolerance=pd.Timedelta(days=_NEWS_MERGE_TOLERANCE_DAYS), + ).sort_values("orig_pos") + + aligned = pd.Series( + merged["headline_score"].to_numpy(), index=target_index, name="NEWS_SENTIMENT_SCORE", + ) + aligned = aligned.fillna(NEUTRAL_SCORE).clip(-1.0, 1.0) + + # Canario de cobertura, ahora DESAMBIGUADO: si la columna vuelve a + # colapsar a puro NEUTRAL_SCORE, el log dice CUÁL de las dos causas + # posibles es — nunca más un mensaje genérico "revisar fechas o API" + # cuando el problema real puede estar en el scorer y viceversa. + if (aligned == NEUTRAL_SCORE).all(): + if nonzero_scores == 0: + logger.warning( + "NEWS_SENTIMENT_SCORE 100%% neutro para %s: los %d titular(es) " + "obtenidos puntuaron EXACTAMENTE 0.0 en el scorer -> revisar, " + "en orden: (1) warnings de '_score_text'/etiqueta FinBERT no " + "reconocida arriba en el log; (2) idioma real de esos " + "titulares -- ProsusAI/finbert es inglés-únicamente, un " + "titular no-inglés puntúa 'neutral' SIN lanzar ningún warning " + "(ver V10, DDG_REGION); el merge de fechas es irrelevante, la " + "señal ya nace muerta antes de tocar cualquier lógica temporal.", + ticker, len(headlines), + ) + else: + logger.warning( + "NEWS_SENTIMENT_SCORE 100%% neutro para %s pese a %d titular(es) " + "obtenidos Y %d de ellos con score no-neutro real -> el scorer " + "funciona, es un problema de COBERTURA TEMPORAL: ninguna fecha " + "cae dentro de la tolerancia de %d día(s) contra target_index " + "(¿target_index desactualizado / caché parquet vieja / rango " + "histórico que no llega hasta fechas recientes?).", + ticker, len(headlines), nonzero_scores, _NEWS_MERGE_TOLERANCE_DAYS, + ) + + # V8 — suavizado EMA regime-aware (ver constantes arriba): el canario de + # cobertura recién evaluado corre SIEMPRE sobre la señal cruda (`aligned` + # sin suavizar) para no enmascarar un scorer/merge realmente muerto tras + # una EMA; el suavizado se aplica acá, al final, solo sobre lo que + # efectivamente entra al tensor. + ema_span = NEWS_SENTIMENT_EMA_SPAN_CRYPTO if _is_crypto_ticker(ticker) else NEWS_SENTIMENT_EMA_SPAN_EQUITY + if ema_span > 1: + aligned = aligned.ewm(span=ema_span, adjust=False).mean().rename("NEWS_SENTIMENT_SCORE") + + return aligned \ No newline at end of file diff --git a/ml_engine/entrenamiento.py b/ml_engine/entrenamiento.py new file mode 100644 index 0000000000000000000000000000000000000000..3b479545a71f51de104cf05afeeff68736720ca9 --- /dev/null +++ b/ml_engine/entrenamiento.py @@ -0,0 +1,1144 @@ +# %% +#!pip install yfinance -q + +""" +Pipeline Predictivo GLOBAL Multi-Activo: Attention-BiLSTM (Log-Returns) — V4 +============================================================================= +Arquitectura (V4 — PODADA respecto a V1-V3, ver sección 10 más abajo): + BiLSTM(64) -> LayerNorm -> [MultiHeadAttention + Residual] + -> LayerNorm -> BahdanauAttention (pooling de contexto) + -> Concat(context, Embedding(asset_id)) -> Dropout(0.45) + -> [Dense(32)+L2 + Residual(proyección+L2)] -> LayerNorm -> Dense(1)+L2 +Entorno objetivo: local (VSCode / macOS), TensorFlow/Keras 3.x + +CAMBIOS RESPECTO A LA V1 (single-asset, precio absoluto): + +1) GLOBAL MULTI-ACTIVO: se entrena UN SOLO modelo sobre 10 activos distintos, + combinados en un dataset masivo. Un input categórico `asset_id` (Embedding) + le da al modelo la capacidad de diferenciar el "régimen" de cada activo + dentro del mismo espacio de pesos compartido — sin esto, el modelo no + podría distinguir un día de BTC-USD de un día de SPY. + +2) TARGET = LOG-RETURN, no precio absoluto. Un LSTM entrenado a predecir el + precio absoluto de un activo casi-random-walk aprende trivialmente a + "copiar" el último precio conocido (efecto shadow/lag: la predicción + parece la serie real desplazada un día). Al predecir + log(P_t / P_{t-1}) forzamos al modelo a aprender señal real, no inercia. + El precio se RECONSTRUYE matemáticamente en evaluación: + P_hat_t = P_{t-1} * exp(r_hat_t) + +3) NORMALIZACIÓN POR ACTIVO: cada activo tiene su propio feature_scaler y su + propio target_scaler, ajustados SOLO con el tramo de train de ESE activo. + Esto evita que activos de alta volatilidad (BTC-USD) dominen la pérdida + frente a activos de baja volatilidad (SPY), y evita fuga de información + train/test. + +4) MÉTRICA NUEVA: directional accuracy (% de aciertos en el SIGNO del + retorno), la métrica que realmente importa en un modelo de retornos — + MAE/RMSE de precio reconstruido pueden verse "bien" incluso si el modelo + no acierta la dirección. + +CAMBIOS V2 (este archivo): + +5) FEATURES DE VOLATILIDAD/VOLUMEN: ATR_14 (volatilidad absoluta), BB_WIDTH_20 + (volatilidad relativa vía Bollinger) y OBV (volumen firmado acumulado). + Requieren descargar High/Low/Volume además de Close -> `download_all` + ahora trae el bundle OHLCV completo, no solo Close. + +6) ARQUITECTURA: LayerNormalization tras cada bloque recurrente/atencional + (estabiliza la escala de los hidden states entre capas), un bloque de + MultiHeadAttention auto-atencional CON conexión residual antes del + Bahdanau (que sigue actuando como pooling final de contexto), y una + conexión residual (con proyección lineal para igualar dimensiones) en el + bloque denso profundo. + +7) PÉRDIDA ASIMÉTRICA DIRECCIONAL: `DirectionalHuberLoss` escala Huber por + (1 + gamma) cuando sign(y_true) != sign(y_pred). CORRECCIÓN NECESARIA: + para que "signo en espacio escalado" == "signo del retorno real", el + target_scaler pasa de StandardScaler() a StandardScaler(with_mean=False) + (solo divide por sigma, no resta la media) — de lo contrario, en activos + con drift fuerte (BTC, NVDA) el "cruce por cero" quedaría desplazado a + y_raw=mu≠0 y la pérdida direccional penalizaría el signo EQUIVOCADO en un + sub-conjunto de muestras cercanas a cero. Ver docstring de la clase. + +8) SCHEDULING: CosineDecayRestarts reemplaza a EarlyStopping/ReduceLROnPlateau + como mecanismo de escape de mínimos locales, inyectado directamente en el + optimizador (así es como Keras 3 espera un LearningRateSchedule — NO como + callback). ModelCheckpoint(save_best_only=True) + recarga post-fit se + mantienen para no terminar el entrenamiento con los pesos de la ÚLTIMA + época (que tras un reinicio de LR puede ser peor que un punto intermedio). + +CAMBIOS V3 (este archivo) — FIX DEL COLAPSO "COBARDE": + +9) DIAGNÓSTICO V2: con gamma=1.5 FIJO desde el Epoch 0, el gradiente de la + penalización direccional domina antes de que el modelo aprenda siquiera + la ESCALA de los retornos. La salida más "segura" para minimizar + Huber*(1+gamma) bajo incertidumbre de signo es predecir ŷ≈0 (error de + magnitud pequeño) -> loss y mae siguen bajando mientras + directional_accuracy se estanca en ~38% (peor que el 50% de una moneda + justa, señal de que el sesgo hacia 0 rompe incluso el empate esperable + de un ŷ aleatorio). Los 4 cambios de abajo atacan esto sin tocar la + arquitectura (Fases A/B se mantienen idénticas a la V2). + +9.1) CURRICULUM LEARNING (GAMMA DINÁMICO). `gamma` deja de ser un float + Python y pasa a ser un `keras.Variable` no-entrenable, mutado por + `DynamicGammaCallback` en `on_epoch_begin` según un warmup de + GAMMA_WARMUP_EPOCHS épocas: + + progress(e) = clip(e / GAMMA_WARMUP_EPOCHS, 0, 1) + + # Lineal: + gamma(e) = GAMMA_MAX * progress(e) + + # Sigmoide (GAMMA_SCHEDULE="sigmoid", por defecto) — la mayor + # parte del cambio se concentra a mitad de camino en vez de + # repartirse uniforme; k=GAMMA_SIGMOID_STEEPNESS controla qué tan + # abrupta es esa zona central. Se renormaliza para que + # gamma(0)=0 exacto y gamma(GAMMA_WARMUP_EPOCHS)=GAMMA_MAX exacto + # (un sigmoide crudo nunca toca 0 ni 1 en sus extremos): + sig(x) = 1 / (1 + e^(-k*(x - 0.5))) + gamma(e) = GAMMA_MAX * (sig(progress(e)) - sig(0)) / (sig(1) - sig(0)) + + Con gamma≈0 en las primeras épocas la pérdida es Huber prácticamente + puro -> el modelo explora magnitudes de retorno sin miedo al castigo + direccional. Solo cuando gamma empieza a crecer el gradiente también + empuja a acertar el SIGNO, ya sobre una base de magnitud razonable, + evitando el óptimo local "predecir 0" que domina cuando ambos + objetivos compiten desde el Epoch 0. + +9.2) GRADIENT CLIPPING. `AdamW(clipnorm=GRAD_CLIPNORM=1.0)`: recorta la + norma global del gradiente antes de cada update. Con 14 features + (ATR/OBV con escalas y ruido propios) y los picos de LR que introduce + cada reinicio de CosineDecayRestarts, un batch con outliers puede + generar un gradiente desproporcionado que explota los pesos justo + tras un reinicio -> clipnorm pone un techo duro a esa norma, + complementando (no reemplazando) a TerminateOnNaN(). + +9.3) REINICIOS DE LR MÁS FRECUENTES. LR_RESTART_PERIOD_EPOCHS baja de 10 a + 8: reinicios más seguidos agitan la superficie de pérdida con más + regularidad, ayudando a escapar de mínimos locales -> no se lleva a 5 + para no superponer dos fuentes de inestabilidad (reinicio de LR + + rampa de gamma) dentro de la misma ventana de épocas. + +9.4) REGULARIZACIÓN. Dropout del bloque de fusión sube de 0.4 a 0.45 + (DROPOUT_RATE) + L2 leve (DENSE_L2_REG=1e-5) en las 3 capas Dense de + la cabeza (post_fusion_dense, fused_projection_skip, return_head): + fuerza a esas capas a apoyarse en pesos más pequeños y distribuidos, + en vez de memorizar combinaciones específicas de features ruidosas + del set de entrenamiento. + +CAMBIOS V4 (este archivo) — REFACTOR ESTADÍSTICO/ARQUITECTÓNICO INSTITUCIONAL: + +10) DIAGNÓSTICO V3: pese al curriculum de gamma, el modelo seguía + convergiendo a ŷ≈0 en gran parte de las muestras (directional_accuracy + < 40%, peor que el 50% de una moneda justa). Causas identificadas: + (a) los factores macro entraban al feature_scaler como NIVEL crudo + (no-estacionario), (b) la red seguía sobre-parametrizada para 14 + features, y (c) minimizar Huber puro bajo ruido sigue premiando + ŷ≈0 aunque gamma sea 0 al inicio del curriculum. Los 4 cambios de abajo + atacan cada causa; el curriculum de gamma (9.1-9.3) y el resto de la + V3 se MANTIENEN sin cambios salvo donde se indica explícitamente. + +10.1) ESTACIONARIEDAD ESTRICTA (Fase A). `engineer_asset` transforma TODOS + los factores macro (^GSPC, ^TNX, ^VIX, GC=F, DX-Y.NYB) a log-return + ANTES de que `build_asset_dataset` los pase al feature_scaler — + exactamente el mismo tratamiento que ya recibía el target: + r_macro_t = log(P_macro_t / P_macro_{t-1}) + Nunca se pasa un nivel/precio macro crudo al scaler. Sin esto, un + MinMaxScaler ajustado en el tramo de train de ^TNX/^VIX/etc. queda + "descalibrado" en cuanto el nivel deriva fuera del rango de + entrenamiento (el mismo problema de raíz unitaria que motivó predecir + log-return en vez de precio para el target). + +10.2) SENTIMENT_SCORE VÍA CORRELACIÓN CRUZADA. `compute_sentiment_score` + deja de ser un Z-score de momentum propio del activo (V1-V3) y pasa a + ser la correlación de Pearson MÓVIL (ventana SENTIMENT_LOOKBACK=20) + entre el log-return del activo y el log-return de un factor macro de + referencia (SENTIMENT_MACRO_PROXY="^VIX" por defecto, con fallback al + primer macro_ticker si no está presente en MACRO_TICKERS): + rho_t = Corr_{k=t-20..t}( r_asset_k , r_VIX_k ) + Una caída/inversión abrupta de esa correlación respecto a su nivel + histórico es la firma matemática de un shock IDIOSINCRÁTICO del + activo (noticia específica) que rompe su co-movimiento habitual con + el miedo/mercado agregado — una señal mucho más específica que "qué + tan extremo fue el retorno de hoy frente a su propia distribución". + +10.3) TOPOLOGÍA DE OCKHAM (Fase B). `BiLSTM(256)->BiLSTM(128)` se poda a + una ÚNICA `BiLSTM(64)`. El bloque de MultiHeadAttention (con + residual) y el pooling de BahdanauAttention se MANTIENEN intactos. + Al desaparecer la segunda rama recurrente, la fusión pasa de + [context_vector, bilstm_2, asset_embed] a [context_vector, + asset_embed], y la cabeza densa (post_fusion_dense + + fused_projection_skip) se poda de 64 a 32 unidades — un modelo con + muchos menos parámetros para 14 features de entrada, que fuerza + representaciones generalizadas en vez de memorización de ruido. + +10.4) PENALIZACIÓN DE VARIANZA — LA CURA DE LA "COBARDÍA". Se extiende + `DirectionalHuberLoss` con un término que RESTA de la loss la + varianza (saturada en VARIANCE_CAP) de las predicciones del batch: + Total_Loss = mean(Huber_δ(y,ŷ)·(1+γ·1[sign≠])) + - λ · min(Var_batch(ŷ), VARIANCE_CAP) + Si el modelo colapsa a predicciones casi-constantes, Var_batch(ŷ)->0 + y el término de recompensa desaparece — deja de ser "gratis" predecir + ŷ≈0. `variance_lambda` (VARIANCE_LAMBDA, ajustable) es el único + hiperparámetro nuevo a tunear: demasiado alto y el modelo aprende a + "gritar" (varianza alta, dirección aleatoria) en vez de acertar; + demasiado bajo y no rompe el colapso. `VARIANCE_CAP` evita que el + término, al no tener mínimo interior, incentive varianza sin límite. + +10.5) LR ADAPTATIVO + EARLY STOPPING (Fase C). `CosineDecayRestarts` + (LearningRateSchedule estático inyectado en el optimizador) se + reemplaza por `ReduceLROnPlateau` (monitorea val_loss, señal + continua) + `EarlyStopping` (monitorea val_directional_accuracy_metric + en modo "max", la métrica que realmente importa, con + start_from_epoch=EARLY_STOPPING_START_EPOCH para no contar el + plateau esperable durante el warmup de gamma). Ya no se gastan las + 100 épocas completas si el modelo se estanca ~época 40. +""" + +import pickle +import time +from pathlib import Path + +import numpy as np +import pandas as pd +import yfinance as yf +import matplotlib.pyplot as plt +import matplotlib.dates as mdates +import keras +from keras import layers +from sklearn.preprocessing import MinMaxScaler, StandardScaler +from sklearn.metrics import mean_absolute_error, mean_squared_error + +# ============================================================ +# CONFIG — 100% LOCAL (VSCode / macOS Intel). CERO Colab, CERO Drive. +# ============================================================ +BASE_DIR = Path(__file__).resolve().parent if "__file__" in dir() else Path.cwd() +DATA_DIR = BASE_DIR / "data_cache" # cache local del OHLCV descargado (parquet) +MODEL_DIR = BASE_DIR / "artifacts" # copia de trabajo/dev (opcional, se mantiene por compatibilidad) +PROD_DIR = BASE_DIR.parent / "services" # ENRUTAMIENTO DE PRODUCCIÓN: sube un nivel desde BASE_DIR y entra a /services +DATA_DIR.mkdir(parents=True, exist_ok=True) +MODEL_DIR.mkdir(parents=True, exist_ok=True) +PROD_DIR.mkdir(parents=True, exist_ok=True) + +TICKERS = ["AAPL", "MSFT", "NVDA", "TSLA", "GOOGL", "AMZN", "META", "BTC-USD", "ETH-USD", "SPY"] +MACRO_TICKERS = ["^GSPC", "^TNX", "^VIX", "GC=F", "DX-Y.NYB"] # SPX, UST10Y, VIX, Oro, Dollar Index +PERIOD = "10y" +LOOKBACK = 60 +TRAIN_RATIO = 0.8 +SEED = 42 +ASSET_EMBED_DIM = 8 + +SENTIMENT_LOOKBACK = 20 # ventana de la correlación móvil activo<->macro (proxy de "noticias", V4) +SENTIMENT_MACRO_PROXY = "^VIX" # factor macro de referencia para la correlación; fallback: MACRO_TICKERS[0] + +# TECH_COLS es la ÚNICA fuente de verdad de qué técnicos entran al tensor — +# agregar/quitar un nombre aquí basta para que N_FEATURES y feature_cols +# (en engineer_asset / build_asset_dataset) se re-dimensionen solos, SIN +# tocar la arquitectura del modelo a mano. +TECH_COLS = ["RSI_14", "EMA_20", "MACD", "MACD_SIGNAL", "SENTIMENT_SCORE", + "ATR_14", "BB_WIDTH_20", "OBV"] +N_FEATURES = 1 + len(TECH_COLS) + len(MACRO_TICKERS) # precio propio + técnicos + macro = 14 + +ASSET_TO_ID = {t: i for i, t in enumerate(TICKERS)} + +# --- Hiperparámetros de entrenamiento V2 (antes hardcodeados dentro de las +# funciones; centralizados acá para que build_model/train_model queden +# como funciones puras parametrizadas) --- +BATCH_SIZE = 64 +EPOCHS = 100 +VALIDATION_SPLIT = 0.1 +MHA_HEADS = 4 +MHA_KEY_DIM = 32 +HUBER_DELTA = 1.0 + +# --- V3: CURRICULUM LEARNING (GAMMA DINÁMICO) -------------------------- +# GAMMA_MAX reemplaza al antiguo DIRECTIONAL_GAMMA=1.5 ESTÁTICO: ahora es +# el TECHO al que converge el schedule, no el valor desde la Epoch 0 (ver +# DynamicGammaCallback y la sección 9.1 del docstring del módulo). +GAMMA_INITIAL = 0.0 # arranque: Huber prácticamente puro (sin penalización de signo) +GAMMA_MAX = 1.5 # techo de penalización (antiguo DIRECTIONAL_GAMMA) +GAMMA_WARMUP_EPOCHS = 35 # rampa completa entre época 30-40 (elegido: 35) +GAMMA_SCHEDULE = "sigmoid" # "sigmoid" (rampa suave en S) o "linear" +GAMMA_SIGMOID_STEEPNESS = 10.0 # mayor = transición más abrupta en el punto medio del warmup + +# --- V3: REGULARIZACIÓN -------------------------------------------------- +DROPOUT_RATE = 0.45 # antes 0.4 -> refuerzo anti-overfitting del bloque de fusión +DENSE_L2_REG = 1e-5 # L2 leve en las cabezas densas (post-fusión + salida) + +LR_INITIAL = 1e-3 # V4: LR FIJO al arrancar el optimizador — ya no hay + # LearningRateSchedule inyectado; ReduceLROnPlateau (callback, + # ver train_model) es quien lo muta en tiempo real según val_loss. +GRAD_CLIPNORM = 1.0 # se mantiene: red de seguridad contra picos de gradiente + +# --- V4: LR ADAPTATIVO + EARLY STOPPING (reemplaza CosineDecayRestarts, sección 10.5) --- +REDUCE_LR_FACTOR = 0.5 # cada plateau de val_loss -> LR se parte a la mitad +REDUCE_LR_PATIENCE = 5 # épocas sin mejora de val_loss antes de reducir el LR +REDUCE_LR_MIN_LR = 1e-6 # piso absoluto del LR +EARLY_STOPPING_PATIENCE = 12 # épocas sin mejora de val_directional_accuracy_metric antes de detener +EARLY_STOPPING_START_EPOCH = 15 # no cuenta el plateau antes de esta época (deja rodar el warmup de gamma) + +# --- V4: PENALIZACIÓN DE VARIANZA — cura de la "cobardía" (sección 10.4) --- +VARIANCE_LAMBDA = 0.15 # peso de -lambda*min(var(y_pred), cap) en la loss; ajustable +VARIANCE_CAP = 4.0 # techo de var(y_pred) que se premia (evita varianza sin límite) + +keras.utils.set_random_seed(SEED) # fija numpy/python/backend de forma consistente (Keras 3) + + +# ============================================================ +# FASE A: ETL — DESCARGA UNIFICADA (OHLCV) + FEATURE ENGINEERING POR ACTIVO +# ============================================================ +MAX_DOWNLOAD_RETRIES = 5 +BACKOFF_BASE_SECONDS = 2.0 + + +def _download_with_backoff(symbols: list, period: str, + max_retries: int = MAX_DOWNLOAD_RETRIES, + backoff_base: float = BACKOFF_BASE_SECONDS) -> pd.DataFrame: + """ + Reintenta la descarga con backoff exponencial (2s, 4s, 8s, 16s, ...) ante + errores TRANSITORIOS de red o de rate-limit (HTTP 429 / timeouts) — algo + común en runners de CI/CD que comparten IP de salida con muchos otros + jobs. Esto es simplemente "esperar y reintentar", el manejo estándar y + sostenible de un 429 (ver `Retry-After` / RFC 6585); NO altera headers + para disfrazar el origen del tráfico ni intenta sortear CAPTCHAs — ver + la nota al final del script sobre por qué esa parte se dejó fuera. + """ + last_exc = None + for attempt in range(1, max_retries + 1): + try: + data = yf.download(symbols, period=period, auto_adjust=True, progress=False) + if data is None or data.empty: + raise ValueError("yfinance devolvió un DataFrame vacío") + return data + except Exception as exc: + last_exc = exc + if attempt == max_retries: + break + wait_s = backoff_base * (2 ** (attempt - 1)) + print(f" [reintento {attempt}/{max_retries}] descarga falló ({exc!r}); " + f"backoff exponencial -> esperando {wait_s:.0f}s...") + time.sleep(wait_s) + raise RuntimeError( + f"download_all: no se pudo descargar tras {max_retries} intentos" + ) from last_exc + + +def download_all(tickers: list, macro_tickers: list, period: str) -> pd.DataFrame: + """ + Descarga en UNA sola llamada el bundle OHLCV completo (Open/High/Low/ + Close/Volume) de los activos principales + factores macro, con cache + local en DATA_DIR (parquet). A diferencia de la V1 (que solo traía + Close), acá se necesita el bundle completo porque ATR requiere + High/Low y OBV requiere Volume. Para los macro tickers solo se + conserva Close (son inputs de contexto, no se calculan técnicos sobre + ellos). Columnas planas "TICKER_FIELD" para que el cache parquet sea + trivial (evita el manejo de MultiIndex en disco). + """ + all_symbols = list(dict.fromkeys(tickers + macro_tickers)) # dedup preservando orden + fields = ["Open", "High", "Low", "Close", "Volume"] + cache_path = DATA_DIR / f"all_ohlcv_{period}.parquet" + + required_cols = set() + for t in tickers: + required_cols.update(f"{t}_{f}" for f in fields) + for m in macro_tickers: + required_cols.add(f"{m}_Close") + + if cache_path.exists(): + print(f" [cache local] leyendo {cache_path.relative_to(BASE_DIR)}") + cached = pd.read_parquet(cache_path) + if required_cols.issubset(set(cached.columns)): + return cached + + raw = _download_with_backoff(all_symbols, period) + flat = pd.DataFrame(index=raw.index) + available_fields = set(raw.columns.get_level_values(0)) + for field in fields: + if field not in available_fields: + continue + sub = raw[field] + for sym in all_symbols: + if sym in sub.columns: + flat[f"{sym}_{field}"] = sub[sym] + + flat.to_parquet(cache_path) + print(f" [cache local] guardado en {cache_path.relative_to(BASE_DIR)}") + return flat + + +def compute_rsi(series: pd.Series, period: int = 14) -> pd.Series: + """RSI nativo (suavizado de Wilder vía EWM).""" + delta = series.diff() + gain = delta.clip(lower=0.0) + loss = -delta.clip(upper=0.0) + avg_gain = gain.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + avg_loss = loss.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + rs = avg_gain / avg_loss.replace(0.0, np.nan) + return (100 - (100 / (1 + rs))).fillna(50.0) + + +def compute_macd(series: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9): + """MACD nativo: línea MACD y línea de señal.""" + ema_fast = series.ewm(span=fast, adjust=False).mean() + ema_slow = series.ewm(span=slow, adjust=False).mean() + macd_line = ema_fast - ema_slow + signal_line = macd_line.ewm(span=signal, adjust=False).mean() + return macd_line, signal_line + + +def compute_sentiment_score(asset_log_return: pd.Series, macro_log_return: pd.Series, + window: int = SENTIMENT_LOOKBACK) -> pd.Series: + """ + SENTIMENT_SCORE (V4) — proxy de shock IDIOSINCRÁTICO vía correlación de + Pearson MÓVIL (ventana de `window` sesiones) entre el log-return del + activo y el log-return de un factor macro de referencia (VIX por + defecto, ver SENTIMENT_MACRO_PROXY): + + rho_t = Corr_{k=t-window..t}( r_asset_k , r_macro_k ) + + En régimen normal, un activo mantiene una relación relativamente + estable con el miedo/mercado agregado (rho_t con signo y magnitud + consistentes en el tiempo). Una caída o inversión abrupta de esa + correlación respecto a su nivel histórico es la firma matemática de un + shock ESPECÍFICO del activo (earnings, guidance, oferta/demanda + puntual) que rompe temporalmente su co-movimiento habitual con el + macro — una noticia. Esto reemplaza al Z-score de momentum propio de + la V1-V3 (que solo medía "qué tan extremo fue el retorno de HOY frente + a su propia distribución reciente", sin distinguir un movimiento + sistémico -todo el mercado se mueve junto- de uno idiosincrático). + + `asset_log_return`/`macro_log_return` deben venir YA en log-return + (nunca precio/nivel crudo) y compartir índice. Las primeras `window` + observaciones no tienen ventana completa -> `rolling().corr()` produce + NaN ahí -> se rellena con 0.0 (lectura neutra: "sin shock detectado"), + consistente con el resto de los indicadores técnicos del pipeline. + """ + rho = asset_log_return.rolling(window=window, min_periods=window).corr(macro_log_return) + return rho.fillna(0.0) + + +def compute_atr(high: pd.Series, low: pd.Series, close: pd.Series, period: int = 14) -> pd.Series: + """ + ATR_14 — Average True Range (suavizado de Wilder vía EWM): proxy de + volatilidad ABSOLUTA (en unidades de precio) que RSI/MACD no capturan. + TR_t = max(H_t - L_t, |H_t - C_{t-1}|, |L_t - C_{t-1}|) + ATR_t = EWM_Wilder(TR)_t + """ + prev_close = close.shift(1) + tr = pd.concat([ + high - low, + (high - prev_close).abs(), + (low - prev_close).abs(), + ], axis=1).max(axis=1) + atr = tr.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + return atr.fillna(0.0) + + +def compute_bb_width(series: pd.Series, window: int = 20, num_std: float = 2.0) -> pd.Series: + """ + BB_WIDTH_20 — ancho normalizado de Bandas de Bollinger: + width_t = (banda_sup - banda_inf) / SMA_t = (2*num_std*std_t) / SMA_t + Proxy de volatilidad RELATIVA (independiente de la escala de precio), + complementa a ATR_14 (volatilidad en términos absolutos). + """ + rolling_mean = series.rolling(window=window, min_periods=window).mean() + rolling_std = series.rolling(window=window, min_periods=window).std() + width = (2 * num_std * rolling_std) / rolling_mean.replace(0.0, np.nan) + return width.fillna(0.0) + + +def compute_obv(close: pd.Series, volume: pd.Series) -> pd.Series: + """ + OBV — On-Balance Volume: acumulado de volumen firmado por la dirección + del precio. Único feature del tensor que incorpora PARTICIPACIÓN + (volumen); ayuda a detectar divergencias precio/volumen. + OBV_t = OBV_{t-1} + sign(C_t - C_{t-1}) * V_t + """ + direction = np.sign(close.diff()).fillna(0.0) + obv = (direction * volume).cumsum() + return obv.fillna(0.0) + + +def engineer_asset(all_data: pd.DataFrame, ticker: str, macro_tickers: list) -> pd.DataFrame: + """ + Construye el frame de features de UN activo: OHLCV propio + técnicos + + macro. V4 — ESTACIONARIEDAD ESTRICTA (Fase A, sección 10.1): los + factores macro llegan a `all_data` como NIVEL/PRECIO crudo + (no-estacionario) -> se transforman a log-return AQUÍ, antes de que + `build_asset_dataset` los pase al feature_scaler, igual que el target: + r_macro_t = log(P_macro_t / P_macro_{t-1}) + Nunca se pasa un nivel/precio macro crudo al scaler. + """ + close_col = f"{ticker}_Close" + high_col = f"{ticker}_High" + low_col = f"{ticker}_Low" + vol_col = f"{ticker}_Volume" + macro_close_cols = [f"{m}_Close" for m in macro_tickers] + + df = all_data[[close_col, high_col, low_col, vol_col] + macro_close_cols].copy() + df = df.ffill().dropna() + + close, high, low, volume = df[close_col], df[high_col], df[low_col], df[vol_col] + + # --- Fase A (V4): factores macro -> log-return, NUNCA nivel crudo al scaler --- + for macro_close_col in macro_close_cols: + macro_price = df[macro_close_col] + df[macro_close_col] = np.log(macro_price / macro_price.shift(1)) + + df["RSI_14"] = compute_rsi(close) + df["EMA_20"] = close.ewm(span=20, adjust=False).mean() + macd_line, signal_line = compute_macd(close) + df["MACD"] = macd_line + df["MACD_SIGNAL"] = signal_line + + # --- SENTIMENT_SCORE (V4, sección 10.2): correlación móvil activo<->macro. + # proxy_log_return reutiliza la columna macro YA transformada arriba + # (no se recalcula desde precio crudo). + asset_log_return = np.log(close / close.shift(1)) + proxy_ticker = SENTIMENT_MACRO_PROXY if SENTIMENT_MACRO_PROXY in macro_tickers else macro_tickers[0] + proxy_log_return = df[f"{proxy_ticker}_Close"] + df["SENTIMENT_SCORE"] = compute_sentiment_score(asset_log_return, proxy_log_return, SENTIMENT_LOOKBACK) + + df["ATR_14"] = compute_atr(high, low, close) + df["BB_WIDTH_20"] = compute_bb_width(close) + df["OBV"] = compute_obv(close, volume) + df = df.ffill().dropna() + + feature_cols = [close_col] + TECH_COLS + macro_close_cols + df = df[feature_cols] + df.columns = ["PRICE"] + TECH_COLS + macro_tickers # nombre genérico -> permite apilar activos distintos + return df + + +def build_asset_dataset(df: pd.DataFrame, ticker: str, lookback: int, train_ratio: float): + """ + Ventanas (X) + targets de LOG-RETURN (y) para UN activo, con normalización + propia (feature_scaler + target_scaler) ajustada SOLO en el tramo de train + de ese activo. Split cronológico: sin fuga de información test -> train. + + target_scaler = StandardScaler(with_mean=False): SOLO divide por sigma, + NO resta la media. Es una corrección deliberada respecto a la V1: con + centrado de media, sign(y_scaled) puede diferir de sign(y_raw) para + activos con drift fuerte (el "cero" quedaría desplazado a y_raw=mu), lo + que rompería silenciosamente la semántica de DirectionalHuberLoss. Dividir + solo por una constante positiva (sigma) preserva el signo exactamente. + """ + # V4 (sección 10.1): las columnas de MACRO_TICKERS ya llegan en LOG-RETURN + # (ver engineer_asset, Fase A) -> el MinMaxScaler de abajo nunca ve un + # nivel/precio macro no-estacionario. + feature_cols = ["PRICE"] + TECH_COLS + MACRO_TICKERS + prices = df["PRICE"].values + features = df[feature_cols].values + log_returns = np.diff(np.log(prices)) # log_returns[k] = log(P[k+1] / P[k]) + + n = len(df) + split_idx = int(n * train_ratio) + + feature_scaler = MinMaxScaler(feature_range=(0, 1)) + feature_scaler.fit(features[:split_idx]) + features_scaled = feature_scaler.transform(features) + + X, y_raw, last_price, dates = [], [], [], [] + # t recorre el índice del DÍA OBJETIVO. Predecimos el retorno que ocurre + # entre t-1 y t usando SOLO features hasta t-1 inclusive (sin fuga). + for t in range(lookback, n): + X.append(features_scaled[t - lookback: t]) + y_raw.append(log_returns[t - 1]) + last_price.append(prices[t - 1]) + dates.append(df.index[t]) + + X = np.array(X, dtype=np.float32) + y_raw = np.array(y_raw, dtype=np.float32).reshape(-1, 1) + last_price = np.array(last_price, dtype=np.float32) + dates = pd.DatetimeIndex(dates) + + window_split = split_idx - lookback # offset por la ventana de lookback + + target_scaler = StandardScaler(with_mean=False) # ver docstring: preserva el signo del retorno + target_scaler.fit(y_raw[:window_split]) + y_scaled = target_scaler.transform(y_raw).astype(np.float32) + + asset_id = np.full((len(X),), ASSET_TO_ID[ticker], dtype=np.int32) + + train = dict( + X=X[:window_split], y=y_scaled[:window_split], asset_id=asset_id[:window_split], + last_price=last_price[:window_split], dates=dates[:window_split], + ) + test = dict( + X=X[window_split:], y=y_scaled[window_split:], asset_id=asset_id[window_split:], + last_price=last_price[window_split:], dates=dates[window_split:], + ) + return train, test, feature_scaler, target_scaler + + +# ============================================================ +# FASE B: ARQUITECTURA GLOBAL — MHA+Residual + Bahdanau + BiLSTM + Asset Embedding +# ============================================================ +@keras.saving.register_keras_serializable(package="quanti") +class BahdanauAttention(layers.Layer): + """Self-attention aditiva (Bahdanau) — pooling final de contexto sobre la secuencia enriquecida por MHA.""" + + def __init__(self, units: int, **kwargs): + super().__init__(**kwargs) + self.units = units + self.W = layers.Dense(units, name="attn_W") + self.U = layers.Dense(units, name="attn_U") + self.V = layers.Dense(1, name="attn_V") + + def build(self, input_shape): + feature_dim = input_shape[-1] + self.W.build((None, None, feature_dim)) + self.U.build((None, 1, feature_dim)) + self.V.build((None, None, self.units)) + super().build(input_shape) + + def call(self, hidden_states): + query = keras.ops.mean(hidden_states, axis=1, keepdims=True) + score = self.V(keras.ops.tanh(self.W(hidden_states) + self.U(query))) + weights = keras.ops.softmax(score, axis=1) + context = keras.ops.sum(weights * hidden_states, axis=1) + return context, weights + + def get_config(self): + config = super().get_config() + config.update({"units": self.units}) + return config + + +# ============================================================ +# FASE B.1: FUNCIÓN DE PÉRDIDA — ASYMMETRIC DIRECTIONAL HUBER +# ============================================================ +@keras.saving.register_keras_serializable(package="quanti") +class DirectionalHuberLoss(keras.losses.Loss): + """ + L(y, ŷ) = Huber_δ(y, ŷ) · (1 + γ · 1[sign(y) ≠ sign(ŷ)]) + + Extiende Huber (robusta a outliers de retornos extremos) con un + multiplicador γ que SOLO se activa cuando el modelo falla el SIGNO del + retorno — el error que realmente destruye una estrategia direccional + (ir LONG cuando debía ir SHORT, o viceversa), a diferencia de un simple + error de magnitud con el signo correcto. + + Requiere que y_true/y_pred lleguen en un espacio donde el signo del + valor escalado coincide EXACTAMENTE con el signo del retorno real; por + eso `build_asset_dataset` usa StandardScaler(with_mean=False) para el + target en vez de un StandardScaler centrado en la media (ver su + docstring). Con centrado de media este término penalizaría el signo + equivocado para activos con drift fuerte. + + V3 — CURRICULUM LEARNING: `gamma` ahora acepta un `keras.Variable` NO + entrenable (además del float estático de la V2, por compatibilidad). + `DynamicGammaCallback` reescribe su VALOR en cada `on_epoch_begin` (de + 0.0 a GAMMA_MAX en rampa sigmoide/lineal a lo largo de + GAMMA_WARMUP_EPOCHS) -> como `call()` lee `self.gamma` en cada forward + pass, el nuevo valor se refleja automáticamente sin recompilar el + modelo. Ver sección 9.1 del docstring del módulo para el fundamento + matemático completo. + + V4 — PENALIZACIÓN DE VARIANZA ("cura de la cobardía", sección 10.4): + aun con el curriculum de gamma, minimizar Huber puro bajo ruido sigue + premiando ŷ≈0 ∀ muestras. Se agrega un término que RESTA de la loss la + varianza (saturada en `variance_cap`) de las predicciones del batch: + + L_total = mean( Huber_δ(y,ŷ)·(1+γ·1[sign(y)≠sign(ŷ)]) ) + - variance_lambda · min(Var_batch(ŷ), variance_cap) + + Si el modelo colapsa a predicciones casi-constantes, Var_batch(ŷ)->0 y + el término de recompensa desaparece -> deja de ser "gratis" predecir + ŷ≈0, lo que reactiva el gradiente de magnitud/dirección. `variance_cap` + evita el riesgo simétrico: sin techo, -variance_lambda·Var(ŷ) no tiene + mínimo interior (el modelo podría maximizar varianza saturando ŷ hacia + ±∞ en vez de aprender señal real); al saturar en `variance_cap`, más + allá de ese punto el único gradiente que queda es el de Huber/dirección. + """ + + def __init__(self, delta: float = 1.0, gamma=1.5, + variance_lambda: float = 0.0, variance_cap: float = None, + name: str = "directional_huber", **kwargs): + super().__init__(name=name, **kwargs) + self.delta = delta + # Compatibilidad dual: si `gamma` ya es una Variable (curriculum + # dinámico -> caso normal en V3) se usa TAL CUAL, de modo que el + # callback y la loss comparten la misma celda de memoria. Si es un + # float (ej. al recargar un .keras guardado) se envuelve en una + # Variable no-entrenable nueva, así `call()` nunca tiene que + # ramificar entre "float" y "Variable". + self.gamma = gamma if isinstance(gamma, keras.Variable) else keras.Variable( + gamma, trainable=False, dtype="float32", name=f"{name}_gamma" + ) + self.variance_lambda = float(variance_lambda) + self.variance_cap = None if variance_cap is None else float(variance_cap) + + def call(self, y_true, y_pred): + y_true = keras.ops.cast(y_true, "float32") + y_pred = keras.ops.cast(y_pred, "float32") + + error = y_true - y_pred + abs_error = keras.ops.abs(error) + quadratic = keras.ops.minimum(abs_error, self.delta) + linear = abs_error - quadratic + huber = 0.5 * keras.ops.square(quadratic) + self.delta * linear + + mismatch = keras.ops.cast( + keras.ops.not_equal(keras.ops.sign(y_true), keras.ops.sign(y_pred)), + dtype=huber.dtype, + ) + # self.gamma es una Variable: se lee su valor CORRIENTE en cada + # forward pass. DynamicGammaCallback la actualiza al inicio de cada + # época, así que este término crece época a época sin recompilar. + penalty = 1.0 + self.gamma * mismatch + directional_huber = keras.ops.mean(huber * penalty, axis=-1) # (batch,) + + # V4 (sección 10.4): batch_variance es un ÚNICO escalar por batch (no + # por muestra). keras.losses.Loss espera que call() devuelva un + # vector (batch,), así que se resta el mismo escalar a cada + # elemento; la reducción posterior (mean sobre el batch, default de + # Loss) queda matemáticamente idéntica a + # "mean(directional_huber) - variance_lambda*min(Var(ŷ), cap)". + if self.variance_lambda > 0.0: + batch_variance = keras.ops.var(y_pred) + if self.variance_cap is not None: + batch_variance = keras.ops.minimum(batch_variance, self.variance_cap) + directional_huber = directional_huber - self.variance_lambda * batch_variance + + return directional_huber + + def get_config(self): + config = super().get_config() + config.update({ + "delta": self.delta, + # Se serializa el VALOR ESCALAR actual (no el objeto Variable, + # que no es JSON-serializable). Al recargar con + # keras.models.load_model() este número queda FIJO -> correcto + # para inferencia; para REANUDAR el curriculum tras una carga + # habría que re-envolverlo a mano en una Variable nueva. + "gamma": float(keras.ops.convert_to_numpy(self.gamma)), + "variance_lambda": self.variance_lambda, + "variance_cap": self.variance_cap, + }) + return config + + +@keras.saving.register_keras_serializable(package="quanti") +def directional_accuracy_metric(y_true, y_pred): + """Métrica de monitoreo en vivo durante fit(): % de aciertos de signo (espacio escalado, signo-preservado).""" + y_true = keras.ops.cast(y_true, "float32") + y_pred = keras.ops.cast(y_pred, "float32") + match = keras.ops.cast( + keras.ops.equal(keras.ops.sign(y_true), keras.ops.sign(y_pred)), dtype="float32" + ) + return keras.ops.mean(match) + + +# ============================================================ +# FASE B.2: CURRICULUM LEARNING — CALLBACK DE GAMMA DINÁMICO (V3) +# ============================================================ +class DynamicGammaCallback(keras.callbacks.Callback): + """ + Reescribe, al inicio de cada época, el `keras.Variable` de gamma que + consume `DirectionalHuberLoss`, siguiendo un warmup de + `warmup_epochs` épocas desde `0.0` hasta `gamma_max`. Ver sección 9.1 + del docstring del módulo para la derivación matemática completa del + schedule sigmoide/lineal. + + Se implementa como Callback (no como parte de la loss) porque el + schedule depende del ÍNDICE DE ÉPOCA, una noción que la loss —evaluada + por batch, sin conocimiento del bucle de entrenamiento— no tiene; el + Callback sí recibe `epoch` en `on_epoch_begin` desde `model.fit()`. + """ + + def __init__(self, gamma_variable, gamma_max: float = GAMMA_MAX, + warmup_epochs: int = GAMMA_WARMUP_EPOCHS, + schedule: str = GAMMA_SCHEDULE, + sigmoid_steepness: float = GAMMA_SIGMOID_STEEPNESS, + verbose: bool = True): + super().__init__() + self.gamma_variable = gamma_variable + self.gamma_max = gamma_max + self.warmup_epochs = max(1, warmup_epochs) + self.schedule = schedule + self.sigmoid_steepness = sigmoid_steepness + self.verbose = verbose + # Normalización del sigmoide para que _progress_to_fraction(0)=0.0 y + # _progress_to_fraction(1)=1.0 EXACTOS -> un sigmoide "crudo" nunca + # toca 0 ni 1 en sus extremos (asíntotas), lo que dejaría gamma(0) + # ligeramente por encima de 0 (penalización direccional desde el + # primer batch, justo lo que V3 busca evitar). + k = self.sigmoid_steepness + self._sig_lo = 1.0 / (1.0 + np.exp(k * 0.5)) + self._sig_hi = 1.0 / (1.0 + np.exp(-k * 0.5)) + + def _progress_to_fraction(self, progress: float) -> float: + progress = min(max(progress, 0.0), 1.0) + if self.schedule == "linear": + return progress + k = self.sigmoid_steepness + raw = 1.0 / (1.0 + np.exp(-k * (progress - 0.5))) + return (raw - self._sig_lo) / (self._sig_hi - self._sig_lo) + + def on_epoch_begin(self, epoch, logs=None): + progress = epoch / self.warmup_epochs + new_gamma = float(self.gamma_max * self._progress_to_fraction(progress)) + self.gamma_variable.assign(new_gamma) + if self.verbose and (epoch % 5 == 0 or epoch == self.warmup_epochs): + tag = " <- curriculum completo" if epoch >= self.warmup_epochs else "" + print(f" [DynamicGamma] epoch={epoch:3d} gamma={new_gamma:.4f}{tag}") + + +def build_model(n_timesteps: int, n_features: int, n_assets: int, + embed_dim: int = ASSET_EMBED_DIM, attention_units: int = 32, + mha_heads: int = MHA_HEADS, mha_key_dim: int = MHA_KEY_DIM, + huber_delta: float = HUBER_DELTA, + gamma_initial: float = GAMMA_INITIAL, + variance_lambda: float = VARIANCE_LAMBDA, + variance_cap: float = VARIANCE_CAP, + dropout_rate: float = DROPOUT_RATE, + dense_l2_reg: float = DENSE_L2_REG) -> tuple: + """ + V4 — Fase B: TOPOLOGÍA DE OCKHAM (sección 10.3). Con 14 features de + entrada, `BiLSTM(256)->BiLSTM(128)` (V1-V3) está masivamente + sobre-parametrizada y memoriza ruido en vez de generalizar -> se poda a + una ÚNICA `BiLSTM(64)`. El bloque de auto-atención multi-cabeza (con + residual) y el pooling de Bahdanau se MANTIENEN sin cambios. Al + desaparecer la segunda rama recurrente, la fusión pasa de + [context_vector, bilstm_2, asset_embed] a [context_vector, asset_embed], + y la cabeza densa (post_fusion_dense / fused_projection_skip) se poda + de 64 a 32 unidades, coherente con la reducción de capacidad aguas + arriba. + """ + # `n_features` NUNCA se hardcodea acá — llega calculado desde + # N_FEATURES = 1 + len(TECH_COLS) + len(MACRO_TICKERS). + seq_input = keras.Input(shape=(n_timesteps, n_features), name="input_sequence") + asset_input = keras.Input(shape=(1,), dtype="int32", name="input_asset_id") + + bilstm = layers.Bidirectional( + layers.LSTM(64, return_sequences=True), name="bilstm_64" + )(seq_input) + bilstm = layers.LayerNormalization(name="ln_post_bilstm_64")(bilstm) + + # Bloque auto-atencional multi-cabeza (estilo encoder de Transformer) con + # conexión residual: se mantiene IDÉNTICO a V1-V3 (directiva Fase B: + # "Keep the Multi-Head Attention and Bahdanau context"). Cada posición + # temporal puede atender a TODA la secuencia antes de que Bahdanau haga + # el pooling final de contexto; la suma residual + LayerNormalization + # evita que el bloque MHA degrade el gradiente que fluye desde la BiLSTM. + mha_out = layers.MultiHeadAttention( + num_heads=mha_heads, key_dim=mha_key_dim, name="multi_head_self_attention" + )(query=bilstm, value=bilstm, key=bilstm) + attn_block = layers.Add(name="mha_residual_add")([bilstm, mha_out]) + attn_block = layers.LayerNormalization(name="ln_post_mha_residual")(attn_block) + + context_vector, attention_weights = BahdanauAttention( + attention_units, name="bahdanau_attention" + )(attn_block) + + asset_embed = layers.Embedding(n_assets, embed_dim, name="asset_embedding")(asset_input) + asset_embed = layers.Flatten(name="asset_embedding_flat")(asset_embed) + + # V4: sin segunda rama BiLSTM(128) -> la fusión pasa de 3 a 2 entradas. + fused = layers.Concatenate(name="fusion_attn_asset")([context_vector, asset_embed]) + fused = layers.Dropout(dropout_rate, name="dropout_regularizer")(fused) + + # Bloque denso con conexión residual: `fused_projection_skip` proyecta el + # vector de fusión a 32-d para poder sumarlo con `post_fusion_dense` + # (proyección lineal, no una identidad pura, patrón "projection shortcut" + # de ResNet). V4: cabeza podada de 64 a 32 unidades (sección 10.3); las + # 3 capas Dense siguen llevando L2 leve (dense_l2_reg). + l2 = keras.regularizers.l2(dense_l2_reg) + dense_hidden = layers.Dense(32, activation="relu", name="post_fusion_dense", + kernel_regularizer=l2)(fused) + fused_projection = layers.Dense(32, name="fused_projection_skip", + kernel_regularizer=l2)(fused) + dense_block = layers.Add(name="dense_residual_add")([dense_hidden, fused_projection]) + dense_block = layers.LayerNormalization(name="ln_post_dense_residual")(dense_block) + + output = layers.Dense(1, name="return_head", kernel_regularizer=l2)(dense_block) + + model = keras.Model(inputs=[seq_input, asset_input], outputs=output, + name="Global_Attention_BiLSTM_Returns_V4") + + # V4 — Fase C (sección 10.5): LR FIJO al compilar. Ya no hay + # LearningRateSchedule inyectado en el optimizador (CosineDecayRestarts + # queda retirado) -> ReduceLROnPlateau (callback, ver train_model) es + # quien muta el LR en tiempo real según val_loss, algo que un schedule + # estático no puede hacer al no leer métricas de validación. clipnorm + # se mantiene como red de seguridad contra picos de gradiente. + optimizer = keras.optimizers.AdamW( + learning_rate=LR_INITIAL, weight_decay=1e-4, clipnorm=GRAD_CLIPNORM + ) + + # V3 — CURRICULUM LEARNING (se mantiene en V4): gamma es un + # keras.Variable NO entrenable (no es un peso del modelo: es un + # hiperparámetro mutable). DynamicGammaCallback la reescribe en + # `on_epoch_begin`; como DirectionalHuberLoss.call() lee `self.gamma` en + # cada forward pass, el nuevo valor se refleja solo, sin recompilar el + # modelo. Ver sección 9.1 del docstring del módulo. + gamma_variable = keras.Variable( + gamma_initial, trainable=False, dtype="float32", name="directional_gamma" + ) + model.compile( + optimizer=optimizer, + loss=DirectionalHuberLoss( + delta=huber_delta, gamma=gamma_variable, + variance_lambda=variance_lambda, variance_cap=variance_cap, + ), + metrics=["mae", directional_accuracy_metric], + ) + # NO se guarda `gamma_variable` como atributo de `model` (ej. + # `model.gamma_variable = ...`): keras.Model rastrea automáticamente + # cualquier keras.Variable asignada como atributo directo de un Layer/ + # Model (igual que trackea pesos), lo que la suma al conteo de + # variables del Functional top-level. Al guardar el checkpoint esa + # variable extra queda serializada, pero al reconstruir el modelo desde + # su config en `keras.models.load_model()` el grafo Functional + # reconstruido NO la vuelve a crear (no es parte de la arquitectura) -> + # desalineación "expected 0 variables, but received 1" y el reload + # revienta. Se devuelve por separado para que la comparta explícitamente + # con `train_model()` sin pasar por la maquinaria de tracking de Keras. + return model, gamma_variable + + +# ============================================================ +# FASE C: ENTRENAMIENTO GLOBAL +# ============================================================ +def train_model(model: keras.Model, X_train, asset_id_train, y_train, + epochs: int = EPOCHS, batch_size: int = BATCH_SIZE, + validation_split: float = VALIDATION_SPLIT, + checkpoint_path: str = "attention_bilstm_global_best.keras", + gamma_variable=None, + gamma_max: float = GAMMA_MAX, + gamma_warmup_epochs: int = GAMMA_WARMUP_EPOCHS, + gamma_schedule: str = GAMMA_SCHEDULE, + gamma_sigmoid_steepness: float = GAMMA_SIGMOID_STEEPNESS): + """ + V4 — Fase C (sección 10.5): `ReduceLROnPlateau` + `EarlyStopping` + reemplazan a `CosineDecayRestarts` como mecanismo de control del + LR/duración del entrenamiento (V1-V3 dependía de reinicios periódicos + de LR inyectados en el optimizador y dejaba correr las `epochs` + completas sin criterio de parada). + + - `ReduceLROnPlateau(monitor="val_loss")`: parte el LR a la mitad + (REDUCE_LR_FACTOR) cada vez que val_loss no mejora durante + REDUCE_LR_PATIENCE épocas, con piso REDUCE_LR_MIN_LR. val_loss (no la + accuracy direccional) es la señal correcta para ESTA decisión: es + continua, mientras que directional_accuracy es una métrica de conteo + (0/1 por muestra) demasiado ruidosa época a época para gobernar el LR. + - `EarlyStopping(monitor="val_directional_accuracy_metric", mode="max")`: + detiene el entrenamiento si la métrica que REALMENTE importa (no la + loss compuesta, que mezcla magnitud + dirección + varianza) no mejora + durante EARLY_STOPPING_PATIENCE épocas, con `restore_best_weights=True` + como red de seguridad adicional. `start_from_epoch= + EARLY_STOPPING_START_EPOCH` evita que la paciencia empiece a contar + mientras el curriculum de gamma sigue en rampa (las primeras épocas + son de exploración de magnitud, no de precisión direccional -> un + plateau ahí es esperado, no señal de estancamiento real). Así se evita + gastar epochs completos si el modelo se estanca ~época 40. + - `ModelCheckpoint(save_best_only=True, monitor="val_loss")` sigue + siendo la fuente de verdad FINAL de los pesos (se recarga tras + `fit()`, igual que en V1-V3): puede diferir levemente de los pesos + que deja `restore_best_weights` de EarlyStopping (que optimiza por + accuracy direccional) — es una elección deliberada, val_loss sigue + siendo el objetivo de entrenamiento primario. + - `TerminateOnNaN()` se mantiene sin cambios como red de seguridad barata. + + V3 — nota sobre `gamma_variable`: si `save_best_only=True` guarda el + checkpoint en una época donde el curriculum aún no llegó a gamma_max (un + val_loss más bajo es "más fácil" con gamma pequeño), el `best_model` + recargado por `keras.models.load_model()` queda con un gamma ESTÁTICO + congelado en ese valor (ver `DirectionalHuberLoss.get_config`) — esto es + correcto para inferencia (la loss no se usa en `predict()`) pero si se + quisiera REANUDAR entrenamiento habría que reconstruir la Variable a mano. + """ + callbacks = [ + keras.callbacks.ModelCheckpoint( + checkpoint_path, monitor="val_loss", save_best_only=True, verbose=1 + ), + keras.callbacks.TerminateOnNaN(), + # V4 (sección 10.5): LR adaptativo sobre plateau de val_loss. + keras.callbacks.ReduceLROnPlateau( + monitor="val_loss", factor=REDUCE_LR_FACTOR, patience=REDUCE_LR_PATIENCE, + min_lr=REDUCE_LR_MIN_LR, verbose=1, + ), + # V4 (sección 10.5): parada temprana agresiva sobre la métrica que + # de verdad importa, no sobre la loss compuesta. + keras.callbacks.EarlyStopping( + monitor="val_directional_accuracy_metric", mode="max", + patience=EARLY_STOPPING_PATIENCE, start_from_epoch=EARLY_STOPPING_START_EPOCH, + restore_best_weights=True, verbose=1, + ), + ] + if gamma_variable is not None: + # V3: registra el callback de curriculum learning SOLO si se pasó una + # gamma_variable (permite seguir usando train_model en modo V2 puro, + # con una loss de gamma estático, sin romper la firma de la función). + callbacks.append(DynamicGammaCallback( + gamma_variable=gamma_variable, + gamma_max=gamma_max, + warmup_epochs=gamma_warmup_epochs, + schedule=gamma_schedule, + sigmoid_steepness=gamma_sigmoid_steepness, + )) + history = model.fit( + [X_train, asset_id_train], y_train, + validation_split=validation_split, + epochs=epochs, + batch_size=batch_size, + shuffle=True, + callbacks=callbacks, + verbose=1, + ) + best_model = keras.models.load_model(checkpoint_path) + return history, best_model + + +# ============================================================ +# FASE D: EVALUACIÓN — RECONSTRUCCIÓN DE PRECIOS + DIRECTIONAL ACCURACY +# ============================================================ +def evaluate_asset(model: keras.Model, test: dict, ticker: str, target_scaler: StandardScaler) -> dict: + asset_id_col = test["asset_id"].reshape(-1, 1) + y_pred_scaled = model.predict([test["X"], asset_id_col], verbose=0) + + r_hat = target_scaler.inverse_transform(y_pred_scaled).flatten() + r_true = target_scaler.inverse_transform(test["y"]).flatten() + + price_pred = test["last_price"] * np.exp(r_hat) + price_true = test["last_price"] * np.exp(r_true) + + mae_price = mean_absolute_error(price_true, price_pred) + rmse_price = np.sqrt(mean_squared_error(price_true, price_pred)) + directional_acc = float(np.mean(np.sign(r_hat) == np.sign(r_true))) + + return { + "ticker": ticker, + "mae_price": mae_price, + "rmse_price": rmse_price, + "directional_accuracy": directional_acc, + "price_true": price_true, + "price_pred": price_pred, + "dates": test["dates"], + } + + +def plot_asset(result: dict, ticker: str): + fig, ax = plt.subplots(figsize=(14, 6)) + ax.plot(result["dates"], result["price_true"], label="Real", color="#1f77b4", linewidth=1.8) + ax.plot(result["dates"], result["price_pred"], label="Predicho (reconstruido)", color="#d62728", + linewidth=1.5, linestyle="--") + ax.set_title(f"{ticker} — Global Attention-BiLSTM V3 (Log-Return): Predicho vs. Real (Test)") + ax.set_xlabel("Fecha") + ax.set_ylabel("Precio de Cierre (USD)") + ax.xaxis.set_major_locator(mdates.AutoDateLocator()) + ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y")) + fig.autofmt_xdate() + ax.legend() + ax.grid(alpha=0.3) + plt.tight_layout() + plt.savefig(f"forecast_{ticker.replace('=', '_').replace('^', '')}.png", dpi=150) + plt.show() + + +# ============================================================ +# ORQUESTACIÓN (nivel de módulo -> variables quedan en scope global) +# ============================================================ +print(f"[1/5] Descargando {len(TICKERS)} activos (OHLCV) + {len(MACRO_TICKERS)} factores macro (Close) ({PERIOD})...") +all_market_data = download_all(TICKERS, MACRO_TICKERS, PERIOD) + +print("[2/5] Ingeniería de features y construcción de dataset GLOBAL por activo...") +feature_scalers, target_scalers = {}, {} +X_train_parts, y_train_parts, asset_id_train_parts = [], [], [] +test_sets = {} + +for ticker in TICKERS: + df_asset = engineer_asset(all_market_data, ticker, MACRO_TICKERS) + train, test, f_scaler, t_scaler = build_asset_dataset(df_asset, ticker, LOOKBACK, TRAIN_RATIO) + + feature_scalers[ticker] = f_scaler + target_scalers[ticker] = t_scaler + test_sets[ticker] = test + + X_train_parts.append(train["X"]) + y_train_parts.append(train["y"]) + asset_id_train_parts.append(train["asset_id"]) + print(f" {ticker:10s} train={len(train['X']):5d} test={len(test['X']):5d}") + +X_train = np.concatenate(X_train_parts, axis=0) +y_train = np.concatenate(y_train_parts, axis=0) +asset_id_train = np.concatenate(asset_id_train_parts, axis=0).reshape(-1, 1) +print(f" Dataset global combinado -> X_train {X_train.shape}") + +print("[3/5] Construyendo y entrenando el modelo GLOBAL...") +# Verificación de dimensionalidad ANTES de instanciar el modelo: si +# TECH_COLS y N_FEATURES se desalinearan del tensor real, mejor un +# AssertionError explícito acá que un colapso de shape dentro de la BiLSTM. +assert X_train.shape[-1] == N_FEATURES, ( + f"Desalineación de features: X_train tiene {X_train.shape[-1]} columnas " + f"pero N_FEATURES={N_FEATURES} (TECH_COLS={TECH_COLS}). Revisa " + "engineer_asset()/build_asset_dataset()." +) +print(f" n_features dinámico = {N_FEATURES} (PRICE + {len(TECH_COLS)} técnicos incl. ATR/BB/OBV/SENTIMENT[corr] + {len(MACRO_TICKERS)} macro log-return)") + +# V4: ya no se necesita steps_per_epoch -> CosineDecayRestarts (que lo +# consumía para calibrar first_decay_steps) se retiró en favor de +# ReduceLROnPlateau/EarlyStopping (operan por ÉPOCA, no por step; ver +# sección 10.5 del docstring del módulo). +model, gamma_variable = build_model( + n_timesteps=LOOKBACK, n_features=N_FEATURES, n_assets=len(TICKERS), + mha_heads=MHA_HEADS, mha_key_dim=MHA_KEY_DIM, + huber_delta=HUBER_DELTA, gamma_initial=GAMMA_INITIAL, + variance_lambda=VARIANCE_LAMBDA, variance_cap=VARIANCE_CAP, + dropout_rate=DROPOUT_RATE, dense_l2_reg=DENSE_L2_REG, +) +model.summary() +print(f" [V4] Curriculum gamma: {GAMMA_INITIAL} -> {GAMMA_MAX} en {GAMMA_WARMUP_EPOCHS} " + f"épocas (schedule={GAMMA_SCHEDULE}) | clipnorm={GRAD_CLIPNORM} | " + f"variance_lambda={VARIANCE_LAMBDA} (cap={VARIANCE_CAP}) | " + f"ReduceLROnPlateau(factor={REDUCE_LR_FACTOR}, patience={REDUCE_LR_PATIENCE}) | " + f"EarlyStopping(patience={EARLY_STOPPING_PATIENCE}, start_from_epoch={EARLY_STOPPING_START_EPOCH})") +history, model = train_model( + model, X_train, asset_id_train, y_train, + epochs=EPOCHS, batch_size=BATCH_SIZE, validation_split=VALIDATION_SPLIT, + gamma_variable=gamma_variable, gamma_max=GAMMA_MAX, + gamma_warmup_epochs=GAMMA_WARMUP_EPOCHS, gamma_schedule=GAMMA_SCHEDULE, + gamma_sigmoid_steepness=GAMMA_SIGMOID_STEEPNESS, +) + +print("[4/5] Evaluación por activo (reconstrucción de precio + directional accuracy)...") +results = {} +for ticker in TICKERS: + results[ticker] = evaluate_asset(model, test_sets[ticker], ticker, target_scalers[ticker]) + r = results[ticker] + print(f" {ticker:10s} MAE=${r['mae_price']:.2f} RMSE=${r['rmse_price']:.2f} " + f"DirAcc={r['directional_accuracy'] * 100:.1f}%") + +plot_asset(results["AAPL"], "AAPL") # muestra representativa; repetir con cualquier ticker de TICKERS + +print("[5/5] Exportando modelo global + scalers -> ENRUTAMIENTO DE PRODUCCIÓN (/services)...") +# Rutas FIJAS (nombre de archivo estable, sin timestamp/versión) para que cada +# corrida del pipeline SOBREESCRIBA el artefacto anterior en vez de generar +# duplicados tipo "scalers 1.pkl". +model_path = PROD_DIR / "attention_bilstm_global.keras" +scalers_path = PROD_DIR / "scalers.pkl" + +model.save(model_path, overwrite=True) # overwrite explícito: en un runner de CI no hay prompt interactivo que confirmar + +scalers_payload = { + "feature_scalers": feature_scalers, + "target_scalers": target_scalers, + "asset_to_id": ASSET_TO_ID, + "lookback": LOOKBACK, + "macro_tickers": MACRO_TICKERS, + "tickers": TICKERS, + "tech_cols": TECH_COLS, # incluye ATR_14/BB_WIDTH_20/OBV -> permite validar orden/dimensión en producción +} +with open(scalers_path, "wb") as f: # modo "wb" trunca y reescribe el archivo existente, no lo duplica + pickle.dump(scalers_payload, f) + +print(f" Modelo -> {model_path.relative_to(BASE_DIR.parent)}") +print(f" Scalers -> {scalers_path.relative_to(BASE_DIR.parent)}") +print(" Archivos sobreescritos exitosamente en /services") + +# Variables disponibles en el scope global tras la ejecución: +# model, history, feature_scalers, target_scalers, test_sets, results, +# X_train, y_train, asset_id_train +# %% \ No newline at end of file diff --git a/ml_engine/forecast_AAPL.png b/ml_engine/forecast_AAPL.png new file mode 100644 index 0000000000000000000000000000000000000000..19055fad1e2fa82c53c0b15757d6d895e6aa5a54 --- /dev/null +++ b/ml_engine/forecast_AAPL.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6937323d82498140fb41b8c450ac32c225c68f3176d304cfc3b5eba20bd284d6 +size 161960 diff --git a/ml_engine/free_alpha.py b/ml_engine/free_alpha.py new file mode 100644 index 0000000000000000000000000000000000000000..dd54c888247c55a4ce31639abea01c7e3e9f6c67 --- /dev/null +++ b/ml_engine/free_alpha.py @@ -0,0 +1,329 @@ +"""KodaQuant V28 -- alpha gratuito, UNA sola implementacion para train e inferencia. + +Copiar IDENTICO a `ml_engine/free_alpha.py` y `services/free_alpha.py` +(train importa de `ml_engine`, el motor de `services`; mismo patron que +`kodaquant_core.py`). Todo feature se calcula aca; ningun lado lo reimplementa, +asi TECH_COLS no puede desincronizarse por construccion. + +Causalidad: solo `.rolling()` trailing, `.shift(+n)`, `.diff()`. Cero `center=True`, +cero `shift(-n)`. `_selftest()` lo verifica por invariancia de prefijo. + +Fuentes (todas publicas, sin API key): + * Binance spot klines 1d (host espejo `data-api.binance.vision`, sirve donde + `api.binance.com` devuelve 451): volumen taker-buy REAL -> imbalance de agresor. + * Coinbase Exchange candles 1d (`api.exchange.coinbase.com`): prima Coinbase/Binance. + * Binance USD-M `premiumIndexKlines` 1d: base perpetuo-spot (puede estar geobloqueado). +Cualquier fuente caida -> columna 0.0 (neutra) + warning + `LAST_STATUS`. +""" +from __future__ import annotations + +import logging +import sys +import time +from typing import Optional + +import numpy as np +import pandas as pd + +logger = logging.getLogger("kodaquant.free_alpha") + +V28_EQUITY_COLS = [ + "OVERNIGHT_GAP_ZSCORE", # ln(Open_t / Close_{t-1}) z-scoreado + "INTRADAY_RET_ZSCORE", # ln(Close_t / Open_t) z-scoreado + "OVERNIGHT_MOM_ZSCORE", # media 10d del gap nocturno, z 120d (persistencia overnight) + "REL_STRENGTH_SPX_ZSCORE", # retorno 5d del activo menos retorno 5d de ^GSPC, z-scoreado +] +V28_CRYPTO_COLS = [ + "TAKER_IMBALANCE_ZSCORE", # (2*takerBuyBase/vol - 1), media 5d, z 60d -- flujo de agresor REAL + "TRADE_SIZE_ZSCORE", # log(quoteVol/trades), media 3d, z 60d -- retail vs ballena + "CB_PREMIUM_ZSCORE", # ln(close Coinbase USD / close Binance USDT), media 3d, z 60d + "PERP_BASIS_ZSCORE", # premium index perpetuo, media 3d, z 60d +] +V28_COLS = V28_EQUITY_COLS + V28_CRYPTO_COLS + +INDEX_PROXY_TICKERS = frozenset({"SPY"}) # rel-strength vs ^GSPC seria puro ruido de tracking + +Z_WINDOW, Z_MIN, Z_CLIP = 60, 30, 4.0 +OVERNIGHT_MOM_DAYS = 10 +REL_STRENGTH_DAYS = 5 +FLOW_SMOOTH_DAYS = 5 +PRICE_SMOOTH_DAYS = 3 +GAP_FFILL_LIMIT = 2 + +CRYPTO_SOURCES = { + "BTC-USD": {"spot": "BTCUSDT", "cb": "BTC-USD", "perp": "BTCUSDT"}, + "ETH-USD": {"spot": "ETHUSDT", "cb": "ETH-USD", "perp": "ETHUSDT"}, +} +_BINANCE_SPOT_URLS = ["https://data-api.binance.vision/api/v3/klines", + "https://api.binance.com/api/v3/klines"] +_BINANCE_PREMIUM_URLS = ["https://fapi.binance.com/fapi/v1/premiumIndexKlines"] +_COINBASE_URL = "https://api.exchange.coinbase.com/products/{product}/candles" + +LAST_STATUS: dict[str, dict[str, str]] = {} +_MEM_CACHE: dict[str, tuple[float, pd.DataFrame]] = {} +_MEM_TTL_SECONDS = 6 * 3600 + + +# ---------------------------------------------------------------------------- +# Primitivas +# ---------------------------------------------------------------------------- +def rolling_z(s: pd.Series, window: int = Z_WINDOW, min_periods: int = Z_MIN, + clip: float = Z_CLIP) -> pd.Series: + mean = s.rolling(window, min_periods=min_periods).mean() + std = s.rolling(window, min_periods=min_periods).std() + z = (s - mean) / std.replace(0.0, np.nan) + return z.replace([np.inf, -np.inf], np.nan).clip(-clip, clip).fillna(0.0) + + +def _naive_daily(index) -> pd.DatetimeIndex: + idx = pd.DatetimeIndex(index) + if idx.tz is not None: + idx = idx.tz_convert("UTC").tz_localize(None) + return idx.normalize() + + +# ---------------------------------------------------------------------------- +# EQUITY: descomposicion overnight/intraday + fuerza relativa +# ---------------------------------------------------------------------------- +def compute_equity_open_features(open_: Optional[pd.Series], close: pd.Series, + spx_logret: Optional[pd.Series] = None, + ticker: str = "") -> pd.DataFrame: + """Devuelve DataFrame(V28_EQUITY_COLS) alineado a `close.index`. + + `open_` None -> columnas overnight/intraday en 0.0 (neutras). + `spx_logret` = log-return diario de ^GSPC ya alineado al indice de `close`. + """ + out = pd.DataFrame(0.0, index=close.index, columns=V28_EQUITY_COLS) + if open_ is not None: + gap = np.log(open_ / close.shift(1)).replace([np.inf, -np.inf], np.nan) + intraday = np.log(close / open_).replace([np.inf, -np.inf], np.nan) + out["OVERNIGHT_GAP_ZSCORE"] = rolling_z(gap) + out["INTRADAY_RET_ZSCORE"] = rolling_z(intraday) + out["OVERNIGHT_MOM_ZSCORE"] = rolling_z( + gap.rolling(OVERNIGHT_MOM_DAYS, min_periods=OVERNIGHT_MOM_DAYS).mean(), + window=120, min_periods=60) + else: + logger.warning("[V28] '%s': sin columna Open -> features overnight/intraday = 0.0.", ticker) + if spx_logret is not None and ticker not in INDEX_PROXY_TICKERS: + asset_lr = np.log(close / close.shift(1)) + rel = (asset_lr.rolling(REL_STRENGTH_DAYS, min_periods=REL_STRENGTH_DAYS).sum() + - spx_logret.rolling(REL_STRENGTH_DAYS, min_periods=REL_STRENGTH_DAYS).sum()) + out["REL_STRENGTH_SPX_ZSCORE"] = rolling_z(rel) + return out + + +# ---------------------------------------------------------------------------- +# CRIPTO: fetchers +# ---------------------------------------------------------------------------- +def _http_get_json(urls: list[str], params: dict, timeout: int = 15, retries: int = 2): + import requests + for url in urls: + for attempt in range(retries + 1): + try: + r = requests.get(url, params=params, timeout=timeout, + headers={"User-Agent": "kodaquant/28"}) + if r.status_code in (403, 451): # geoblock -> siguiente host + break + if r.status_code in (418, 429): # rate limit + time.sleep(1.5 * (attempt + 1)) + continue + r.raise_for_status() + return r.json() + except Exception as exc: # noqa: BLE001 -- proveedor opcional + logger.debug("GET %s fallo (%r) intento %d", url, exc, attempt + 1) + time.sleep(0.4 * (attempt + 1)) + return None + + +def _paginate_binance_klines(urls: list[str], symbol: str, start_ms: int, limit: int) -> list: + rows: list = [] + cursor, now_ms = start_ms, int(time.time() * 1000) + for _ in range(40): + if cursor >= now_ms: + break + batch = _http_get_json(urls, {"symbol": symbol, "interval": "1d", + "startTime": cursor, "limit": limit}) + if not batch: + break + rows.extend(batch) + last_open = int(batch[-1][0]) + if last_open < cursor or len(batch) < limit: + break + cursor = last_open + 1 + time.sleep(0.12) + return rows + + +def fetch_binance_spot_daily(symbol: str, start: str = "2017-08-01") -> Optional[pd.DataFrame]: + start_ms = int(pd.Timestamp(start, tz="UTC").timestamp() * 1000) + rows = _paginate_binance_klines(_BINANCE_SPOT_URLS, symbol, start_ms, 1000) + if not rows: + return None + # [0]open_time [4]close [5]volume [7]quote_vol [8]trades [9]taker_buy_base + df = pd.DataFrame(rows).iloc[:, :10] + df.columns = ["open_time", "open", "high", "low", "close", "volume", + "close_time", "quote_volume", "trades", "taker_buy_base"] + df["date"] = pd.to_datetime(pd.to_numeric(df["open_time"]), unit="ms").dt.normalize() + for c in ("close", "volume", "quote_volume", "trades", "taker_buy_base"): + df[c] = pd.to_numeric(df[c], errors="coerce") + df = df.drop_duplicates("date", keep="last").set_index("date").sort_index() + return df[["close", "volume", "quote_volume", "trades", "taker_buy_base"]] + + +def fetch_binance_basis_daily(symbol: str, start: str = "2019-09-01") -> Optional[pd.Series]: + start_ms = int(pd.Timestamp(start, tz="UTC").timestamp() * 1000) + rows = _paginate_binance_klines(_BINANCE_PREMIUM_URLS, symbol, start_ms, 1500) + if not rows: + return None + df = pd.DataFrame(rows).iloc[:, :5] + df.columns = ["open_time", "open", "high", "low", "close"] + df["date"] = pd.to_datetime(pd.to_numeric(df["open_time"]), unit="ms").dt.normalize() + df["close"] = pd.to_numeric(df["close"], errors="coerce") + return df.drop_duplicates("date", keep="last").set_index("date").sort_index()["close"] + + +def fetch_coinbase_daily(product: str, start: str = "2016-01-01") -> Optional[pd.Series]: + cursor = pd.Timestamp(start, tz="UTC") + end_all = pd.Timestamp.now(tz="UTC") + rows: list = [] + while cursor < end_all: + chunk_end = min(cursor + pd.Timedelta(days=290), end_all) + data = _http_get_json([_COINBASE_URL.format(product=product)], + {"granularity": 86400, "start": cursor.isoformat(), + "end": chunk_end.isoformat()}) + if data is None: + break + rows.extend(data) # [time, low, high, open, close, volume] + cursor = chunk_end + time.sleep(0.25) + if not rows: + return None + df = pd.DataFrame(rows).iloc[:, :5] + df.columns = ["time", "low", "high", "open", "close"] + df["date"] = pd.to_datetime(pd.to_numeric(df["time"]), unit="s").dt.normalize() + df["close"] = pd.to_numeric(df["close"], errors="coerce") + return df.drop_duplicates("date", keep="last").set_index("date").sort_index()["close"] + + +def _cached(key: str, fetch, cache=None) -> Optional[pd.DataFrame]: + now = time.time() + hit = _MEM_CACHE.get(key) + if hit and now - hit[0] < _MEM_TTL_SECONDS: + return hit[1] + if cache is not None: + try: + df = cache.get_dataframe(key) + if df is not None and not df.empty: + _MEM_CACHE[key] = (now, df) + return df + except Exception: # noqa: BLE001 + pass + obj = fetch() + if obj is None or len(obj) == 0: + return None + df = obj.to_frame("v") if isinstance(obj, pd.Series) else obj + _MEM_CACHE[key] = (now, df) + if cache is not None: + try: + cache.set_dataframe(key, df) + except Exception: # noqa: BLE001 + pass + return df + + +# ---------------------------------------------------------------------------- +# CRIPTO: features (funcion pura, testeable sin red) +# ---------------------------------------------------------------------------- +def compute_crypto_flow_features(index, spot: Optional[pd.DataFrame], + coinbase: Optional[pd.Series], + basis: Optional[pd.Series]) -> pd.DataFrame: + idx = _naive_daily(index) + out = pd.DataFrame(0.0, index=idx, columns=V28_CRYPTO_COLS) + + def _align(s): + s = s.copy() + s.index = _naive_daily(s.index) + return s[~s.index.duplicated(keep="last")].reindex(idx).ffill(limit=GAP_FFILL_LIMIT) + + if spot is not None and len(spot): + sp = _align(spot) if isinstance(spot, pd.Series) else spot.copy() + if isinstance(sp, pd.DataFrame): + sp.index = _naive_daily(sp.index) + sp = sp[~sp.index.duplicated(keep="last")].reindex(idx).ffill(limit=GAP_FFILL_LIMIT) + vol = sp["volume"].replace(0.0, np.nan) + imb = (2.0 * sp["taker_buy_base"] / vol - 1.0).replace([np.inf, -np.inf], np.nan) + out["TAKER_IMBALANCE_ZSCORE"] = rolling_z(imb.rolling(FLOW_SMOOTH_DAYS, min_periods=3).mean()) + size = (sp["quote_volume"] / sp["trades"].replace(0.0, np.nan)).replace([np.inf, -np.inf], np.nan) + out["TRADE_SIZE_ZSCORE"] = rolling_z(np.log(size).rolling(PRICE_SMOOTH_DAYS, min_periods=2).mean()) + if coinbase is not None and len(coinbase): + prem = np.log(_align(coinbase) / sp["close"]).replace([np.inf, -np.inf], np.nan) + out["CB_PREMIUM_ZSCORE"] = rolling_z(prem.rolling(PRICE_SMOOTH_DAYS, min_periods=2).mean()) + if basis is not None and len(basis): + out["PERP_BASIS_ZSCORE"] = rolling_z(_align(basis).rolling(PRICE_SMOOTH_DAYS, min_periods=2).mean()) + return out + + +def build_crypto_flow_features(ticker: str, index, cache=None) -> pd.DataFrame: + """Descarga (con cache) + calcula. Cualquier fuente caida -> su columna queda 0.0.""" + src = CRYPTO_SOURCES.get(ticker) + if src is None: + return pd.DataFrame(0.0, index=_naive_daily(index), columns=V28_CRYPTO_COLS) + st = LAST_STATUS.setdefault(ticker, {}) + spot = _cached(f"v28_spot_{src['spot']}", lambda: fetch_binance_spot_daily(src["spot"]), cache) + cb = _cached(f"v28_cb_{src['cb']}", lambda: fetch_coinbase_daily(src["cb"]), cache) + bs = _cached(f"v28_basis_{src['perp']}", lambda: fetch_binance_basis_daily(src["perp"]), cache) + for name, obj in (("spot", spot), ("coinbase", cb), ("basis", bs)): + st[name] = "ok" if obj is not None else "DOWN" + if obj is None: + logger.warning("[V28] '%s': fuente '%s' no disponible -> sus features quedan en 0.0 " + "(riesgo de skew train/serve si difiere del entrenamiento).", ticker, name) + return compute_crypto_flow_features( + index, + spot, + cb["v"] if cb is not None else None, + bs["v"] if bs is not None else None, + ) + + +# ---------------------------------------------------------------------------- +# Autotest: causalidad (invariancia de prefijo) + forma +# ---------------------------------------------------------------------------- +def _selftest() -> None: + rng = np.random.default_rng(7) + n = 400 + idx = pd.bdate_range("2020-01-01", periods=n) + close = pd.Series(100 * np.exp(np.cumsum(rng.normal(0, 0.01, n))), index=idx) + open_ = close.shift(1) * np.exp(rng.normal(0, 0.003, n)) + open_.iloc[0] = close.iloc[0] + spx = pd.Series(rng.normal(0, 0.008, n), index=idx) + + full = compute_equity_open_features(open_, close, spx, "AAPL") + cut = 300 + pref = compute_equity_open_features(open_.iloc[:cut], close.iloc[:cut], spx.iloc[:cut], "AAPL") + np.testing.assert_allclose(full.iloc[:cut].values, pref.values, atol=1e-12, + err_msg="LOOKAHEAD en features equity V28") + assert list(full.columns) == V28_EQUITY_COLS and np.isfinite(full.values).all() + assert (compute_equity_open_features(open_, close, spx, "SPY")["REL_STRENGTH_SPX_ZSCORE"] == 0).all() + assert (compute_equity_open_features(None, close, spx, "AAPL")["OVERNIGHT_GAP_ZSCORE"] == 0).all() + + didx = pd.date_range("2019-01-01", periods=n, freq="D") + vol = pd.Series(rng.uniform(1e3, 2e3, n), index=didx) + spot = pd.DataFrame({ + "close": 20000 * np.exp(np.cumsum(rng.normal(0, 0.02, n))), + "volume": vol, "quote_volume": vol * 20000, + "trades": rng.integers(5e5, 9e5, n).astype(float), + "taker_buy_base": vol * rng.uniform(0.4, 0.6, n)}, index=didx) + cb = spot["close"] * np.exp(rng.normal(0, 0.001, n)) + basis = pd.Series(rng.normal(0.0003, 0.0002, n), index=didx) + f_full = compute_crypto_flow_features(didx, spot, cb, basis) + f_pref = compute_crypto_flow_features(didx[:300], spot.iloc[:300], cb.iloc[:300], basis.iloc[:300]) + np.testing.assert_allclose(f_full.iloc[:300].values, f_pref.values, atol=1e-12, + err_msg="LOOKAHEAD en features cripto V28") + assert list(f_full.columns) == V28_CRYPTO_COLS and np.isfinite(f_full.values).all() + assert (compute_crypto_flow_features(didx, None, None, None).values == 0).all() + print("free_alpha selftest OK (causalidad por prefijo, forma, degradacion a 0.0)") + + +if __name__ == "__main__": + if "--selftest" in sys.argv: + _selftest() \ No newline at end of file diff --git a/ml_engine/kodaquant_core.py b/ml_engine/kodaquant_core.py new file mode 100644 index 0000000000000000000000000000000000000000..323f4026a73c35304c9731fc15b2382c2ca0edda --- /dev/null +++ b/ml_engine/kodaquant_core.py @@ -0,0 +1,396 @@ +""" +kodaquant_core.py — KodaQuant V15: Núcleo Compartido Train/Inferencia +======================================================================== +Consolidación arquitectónica (auditoría CTO, 2026-08-16). Antes de este +módulo, tres piezas de lógica CRÍTICA vivían duplicadas e independientes +entre el pipeline de entrenamiento (`train_kodaquant_v5.py`) y el de +inferencia (`quanti_engine.py`/`market_data.py`), con implementaciones +DIVERGENTES: + + 1. CACHÉ EN DISCO — `market_data.py` (inferencia) cacheaba JSON con TTL + de horas (`_cache_get`/`_cache_set`); `train_kodaquant_v5.py` + (entrenamiento) cacheaba Parquet con staleness por antigüedad de + fecha (`_cache_is_stale`/`download_all`) + un purgado manual separado + (`purge_data_cache`). Dos formatos, dos políticas de expiración, cero + purga automática. `CacheManager` unifica ambos modos (JSON de vida + corta para respuestas de API en vivo, Parquet de vida larga para + descargas históricas masivas) bajo una sola clase, con purga + automática local (`purge_stale`) y purga total explícita + (`purge_all`, reemplazo directo de `purge_data_cache`). + + 2. CLIENTE FRED — vivía únicamente en `market_data.py` + (`_fred_series_daily`), usado SOLO en inferencia. `train_kodaquant_v5.py` + jamás lo importaba: el entrenamiento resolvía `^TNX` con el + `yf.download` genérico, mientras que la inferencia ya lo resolvía vía + FRED (serie oficial `DGS10`) con fallback a Stooq -- exactamente la + discrepancia "train ve una fuente, infiere con otra" reportada. Se + porta acá como `FredClient`, reutilizable desde ambos lados. + + 3. ALINEACIÓN DE CALENDARIO MACRO (5/7) CONTRA UN ACTIVO 24/7 — el fix + real ya existía, pero solo del lado de inferencia + (`market_data._macro_close_ffilled_to_daily_calendar`, fix + 2026-08-15): upsamplear cada serie macro a un calendario diario + CORRIDO (fin de semana incluido) y hacer forward-fill DENTRO de esa + serie, ANTES de reindexarla contra el calendario del activo objetivo. + `engineer_asset()` (entrenamiento) seguía dependiendo de un + `df.ffill()` ciego sobre el frame YA combinado, que no tiene la misma + garantía en huecos que no calzan por orden de columnas ni en el + arranque de la serie. `align_macro_to_calendar` es ahora la ÚNICA + implementación de esta lógica; train e inferencia la importan por + igual -- ver `data_pipeline.py`/`train_kodaquant_v5.py`. + +DESPLIEGUE EN DOS DIRECTORIOS (sin romper la topología actual del repo): +este archivo debe copiarse tal cual a AMBAS ubicaciones que hoy contienen +copias paralelas de `data_pipeline.py`/`market_data.py`: + - `services/kodaquant_core.py` (consumido por quanti_engine.py, + import de paquete: `from services.kodaquant_core import ...`) + - /kodaquant_core.py (consumido por + train_kodaquant_v5.py/train_pipeline.py, import plano: + `from kodaquant_core import ...`) +Cero dependencias externas nuevas: solo `pandas`/`numpy`/`requests`, ya +pineados en ambos entornos. `data_pipeline.py`, `train_kodaquant_v5.py` y +`quanti_engine.py` importan este módulo con el mismo patrón dual +try/except ya usado en el repo para `ddgs`/`duckduckgo_search` (ver +`data_pipeline.py`), así que una sola copia de este archivo sirve para +ambas ubicaciones sin ninguna otra modificación. + +PENDIENTE FUERA DE ESTE ALCANCE (no es uno de los 4 artefactos +entregados, se deja documentado para no perder el hilo): `market_data.py` +sigue con su propio `_fred_series_daily`/`_cache_get`/`_cache_set` +inline -- migrarlo para que importe `FredClient`/`CacheManager` de acá +es un cambio mecánico de una sola función, recomendado como siguiente +paso para que TODA la superficie del repo, no solo train, comparta el +mismo núcleo. +""" + +from __future__ import annotations + +import io +import json +import logging +import threading +import time +from datetime import datetime, timezone +from pathlib import Path +from typing import Optional + +import pandas as pd +import requests + +logger = logging.getLogger("kodaquant.core") + + +# =========================================================================== +# 1) CACHE MANAGER — disco unificado (JSON TTL-corto + Parquet TTL-largo), +# thread-safe, con purga automática local. +# =========================================================================== +class CacheManager: + """ + Caché en disco de dos modos, un solo punto de verdad: + + - `get_json`/`set_json` -> payloads pequeños de vida corta (Close + histórico de un símbolo, headlines de noticias). Expira por TTL + absoluto en segundos (`default_ttl_seconds`), igual semántica que + el cache JSON que ya usaba `market_data.py`. + - `get_dataframe`/`set_dataframe` -> descargas masivas (OHLCV + multi-símbolo de `download_all`). Expira por ANTIGÜEDAD DEL DATO + (última fecha en el índice vs. `datetime.now()`), no por edad del + archivo -- misma semántica que `_cache_is_stale` en + `train_kodaquant_v5.py`: un parquet escrito hace 5 minutos pero + cuya fila más reciente es de hace 3 días sigue estando "viejo". + + Cada instancia posee su PROPIO `cache_dir` -- entrenamiento e + inferencia deben instanciar `CacheManager` con directorios distintos + (no comparten el mismo caché en disco, cada uno con su propia purga), + pero ambos usan la MISMA clase/lógica. + """ + + def __init__(self, cache_dir: Path | str, default_ttl_seconds: int = 6 * 3600, + default_max_age_hours: float = 48.0) -> None: + self.cache_dir = Path(cache_dir) + self.cache_dir.mkdir(parents=True, exist_ok=True) + self.default_ttl_seconds = default_ttl_seconds + self.default_max_age_hours = default_max_age_hours + self._lock = threading.Lock() + + # -- helpers de path -------------------------------------------------- + def _safe_name(self, key: str) -> str: + return key.replace("/", "_").replace(":", "_").replace("^", "caret_").replace(" ", "_") + + def _json_path(self, key: str) -> Path: + return self.cache_dir / f"{self._safe_name(key)}.json" + + def _parquet_path(self, key: str) -> Path: + return self.cache_dir / f"{self._safe_name(key)}.parquet" + + # -- modo JSON (TTL absoluto) ------------------------------------------ + def get_json(self, key: str, ttl_seconds: Optional[int] = None, ignore_ttl: bool = False): + """ + Devuelve el payload cacheado (cualquier objeto JSON-serializable, + incluye DataFrames vía orient="split") o `None` si no existe/expiró. + `ignore_ttl=True` -- último recurso: devuelve lo último en disco sin + importar el TTL (ej. Twelve Data Y Stooq caídos a la vez); marca + `_stale_age_hours` en el resultado si el DataFrame lo soporta. + """ + ttl = self.default_ttl_seconds if ttl_seconds is None else ttl_seconds + path = self._json_path(key) + try: + with self._lock: + if not path.exists(): + return None + payload = json.loads(path.read_text()) + age_s = time.time() - payload.get("_cached_at", 0) + if not ignore_ttl and age_s > ttl: + return None + data = payload.get("data") + kind = payload.get("_kind", "raw") + if kind == "dataframe": + df = pd.read_json(io.StringIO(data), orient="split") + df.index = pd.to_datetime(df.index) + if ignore_ttl and age_s > ttl: + df.attrs["_stale_age_hours"] = round(age_s / 3600, 1) + return df + return data + except Exception as exc: # noqa: BLE001 -- caché corrupta jamás tumba el caller + logger.debug("[CacheManager] JSON ilegible para %s (%r) -- se ignora.", key, exc) + return None + + def set_json(self, key: str, value) -> None: + path = self._json_path(key) + if isinstance(value, pd.DataFrame): + payload = {"_kind": "dataframe", "data": value.to_json(orient="split", date_format="iso"), + "_cached_at": time.time()} + else: + payload = {"_kind": "raw", "data": value, "_cached_at": time.time()} + try: + with self._lock: + path.write_text(json.dumps(payload)) + except Exception as exc: # noqa: BLE001 -- fallo al escribir caché nunca tumba el caller + logger.debug("[CacheManager] No se pudo escribir caché JSON %s (%r).", key, exc) + + # -- modo DataFrame/Parquet (staleness por fecha del dato) ------------ + def get_dataframe(self, key: str, max_age_hours: Optional[float] = None, + required_columns: Optional[set[str]] = None) -> Optional[pd.DataFrame]: + """ + `None` si no existe, si le faltan columnas requeridas, o si su fila + más reciente supera `max_age_hours` de antigüedad respecto a AHORA + (no la edad del archivo) -- ver docstring de la clase. + """ + max_age = self.default_max_age_hours if max_age_hours is None else max_age_hours + path = self._parquet_path(key) + if not path.exists(): + return None + try: + with self._lock: + cached = pd.read_parquet(path) + except Exception as exc: # noqa: BLE001 + logger.warning("[CacheManager] Parquet corrupto para %s (%r) -- se ignora.", key, exc) + return None + + if required_columns and not required_columns.issubset(set(cached.columns)): + return None + if cached.empty: + return None + + max_date = pd.Timestamp(cached.index.max()) + max_date = max_date.tz_localize("UTC") if max_date.tzinfo is None else max_date.tz_convert("UTC") + age = datetime.now(timezone.utc) - max_date.to_pydatetime() + if age.total_seconds() > max_age * 3600: + logger.info("[CacheManager] %s obsoleto -- fecha más reciente %s tiene más de %.0fh -- recarga forzada.", + path.name, cached.index.max(), max_age) + return None + return cached + + def set_dataframe(self, key: str, df: pd.DataFrame) -> None: + path = self._parquet_path(key) + try: + with self._lock: + df.to_parquet(path) + except Exception as exc: # noqa: BLE001 + logger.warning("[CacheManager] No se pudo escribir parquet %s (%r).", key, exc) + + # -- purga automática local -------------------------------------------- + def purge_all(self) -> int: + """Vacía TODO el caché en disco (JSON + Parquet) de este `cache_dir`. Reemplazo directo de `purge_data_cache`.""" + removed = list(self.cache_dir.glob("*.json")) + list(self.cache_dir.glob("*.parquet")) + with self._lock: + for f in removed: + f.unlink(missing_ok=True) + if removed: + logger.warning("[CacheManager] Purga total -> %d archivo(s) purgado(s) de %s.", len(removed), self.cache_dir) + return len(removed) + + def purge_stale(self, ttl_seconds: Optional[int] = None, max_age_hours: Optional[float] = None) -> int: + """ + Purga automática local (Requerimiento 1): recorre `cache_dir` y + elimina solo las entradas efectivamente vencidas, sin tocar + entradas todavía válidas -- pensado para invocarse periódicamente + (ej. al arrancar cada corrida) sin tirar caché sano. + """ + ttl = self.default_ttl_seconds if ttl_seconds is None else ttl_seconds + max_age = self.default_max_age_hours if max_age_hours is None else max_age_hours + removed = 0 + now = time.time() + for path in self.cache_dir.glob("*.json"): + try: + payload = json.loads(path.read_text()) + if now - payload.get("_cached_at", 0) > ttl: + path.unlink(missing_ok=True) + removed += 1 + except Exception: # noqa: BLE001 -- JSON corrupto = candidato directo a purga + path.unlink(missing_ok=True) + removed += 1 + for path in self.cache_dir.glob("*.parquet"): + try: + cached = pd.read_parquet(path) + if cached.empty: + continue + max_date = pd.Timestamp(cached.index.max()) + max_date = max_date.tz_localize("UTC") if max_date.tzinfo is None else max_date.tz_convert("UTC") + age_h = (datetime.now(timezone.utc) - max_date.to_pydatetime()).total_seconds() / 3600 + if age_h > max_age: + path.unlink(missing_ok=True) + removed += 1 + except Exception: # noqa: BLE001 -- parquet corrupto = candidato directo a purga + path.unlink(missing_ok=True) + removed += 1 + if removed: + logger.info("[CacheManager] Purga automática -> %d entrada(s) vencida(s) purgada(s) de %s.", removed, self.cache_dir) + return removed + + +# =========================================================================== +# 2) CLIENTE FRED — fuente PRIMARIA para series macro sin ETF/futuro +# equivalente (ej. ^TNX / DGS10). Portado 1:1 de market_data.py, ahora +# reutilizable desde entrenamiento (antes solo lo veía inferencia). +# =========================================================================== +class FredClient: + """ + Cliente resiliente para `api.stlouisfed.org/fred/series/observations`. + 100% gratis, requiere `api_key` (opcional -- si no se provee, cada + llamada devuelve `None` sin tocar la red, igual que antes de RONDA 2 en + `market_data.py`). Reintenta con backoff exponencial ante 429/timeout. + """ + + BASE_URL = "https://api.stlouisfed.org/fred/series/observations" + + def __init__(self, api_key: str = "", timeout_s: float = 15.0) -> None: + self.api_key = (api_key or "").strip() + self.timeout_s = timeout_s + if not self.api_key: + logger.warning( + "[FredClient] Sin api_key -- toda serie FRED (ej. DGS10/^TNX) " + "devolverá None y caerá al fallback del caller (Stooq)." + ) + + def daily_series(self, series_id: str, tail_days: int, attempts: int = 3) -> Optional[pd.Series]: + """ + `pd.Series` de Close diario (valor oficial de la serie FRED) o + `None` si falta `api_key` o la request falla tras `attempts` + reintentos. FRED marca días sin observación (feriados, fin de + semana) con `"."` en vez de omitir la fila -- se filtran acá antes + de devolver, para que el caller nunca vea un NaN string. + """ + if not self.api_key: + return None + + params = { + "series_id": series_id, + "api_key": self.api_key, + "file_type": "json", + "sort_order": "desc", + "limit": max(tail_days, 30), + } + last_exc: Exception | None = None + for attempt in range(1, attempts + 1): + try: + resp = requests.get(self.BASE_URL, params=params, timeout=self.timeout_s) + if resp.status_code == 429: + raise RuntimeError(f"FRED rate limit (429): {resp.text[:200]}") + resp.raise_for_status() + payload = resp.json() + obs = payload.get("observations", []) + rows = [(o["date"], o["value"]) for o in obs if o.get("value") not in (None, ".")] + if not rows: + return None + dates, values = zip(*rows) + series = pd.Series( + [float(v) for v in values], + index=pd.to_datetime(dates), + name=series_id, + ).sort_index() + return series + except Exception as exc: # noqa: BLE001 -- red/HTTP transitorio + last_exc = exc + if attempt == attempts: + break + time.sleep(1.5 * attempt) + logger.warning("[FredClient] agotó reintentos para la serie '%s': %r", series_id, last_exc) + return None + + +# =========================================================================== +# 3) ALINEACIÓN DE CALENDARIO MACRO — fuente ÚNICA para ambos pipelines. +# =========================================================================== +def normalize_daily_index(index: pd.DatetimeIndex) -> pd.DatetimeIndex: + """ + tz-aware -> tz-naive + medianoche. Un solo símbolo (target O macro) + tz-aware colisionando contra el otro tz-naive hace fallar `.reindex()`/ + `.merge()` en TODAS las fechas, no solo fines de semana -- se normaliza + en el borde de ingesta para que ninguna comparación aguas abajo pueda + volver a pisar este bug (ver `market_data.py`, fix 2026-08-15). + """ + if index.tz is not None: + index = index.tz_localize(None) + return index.normalize() + + +def align_macro_to_calendar(macro_close: pd.Series, upto: pd.Timestamp) -> pd.Series: + """ + CAUSA RAÍZ real de "pérdida masiva de datos cripto en fines de semana": + los macro tickers (SPY/DGS10/XAU-USD/VIXY/UUP, todos vía bolsas + tradicionales) cotizan 5/7; un activo cripto cotiza 24/7. Reindexar la + serie macro DIRECTO contra un calendario de 7 días deja NaN cada + sábado/domingo -- un `.ffill()` posterior sobre el frame YA combinado + tapa la mayoría de esos huecos, pero cualquier fila líder anterior a la + primera fecha del macro ticker (o un hueco interno que el orden de + columnas no alcance a cubrir de forma determinista) sobrevive como NaN, + y un `dropna()` sobre el frame completo puede vaciarlo entero. + + Fix: upsamplear la serie macro a un calendario DIARIO CORRIDO (freq="D", + fin de semana incluido) y forward-fill DENTRO de esa serie -- ANTES de + reindexarla contra el calendario del activo objetivo. El valor de un + viernes de bolsa queda disponible como input válido para sábado/domingo + de cripto, sin depender del orden ni de la suerte del ffill final sobre + el frame ya combinado. NUNCA se hace `bfill` (relleno hacia atrás) -- + sería fuga de información (un valor FUTURO del macro ticker "explicando" + un día pasado). Único costo real: los primeros días, anteriores al + primer dato macro disponible, siguen sin cobertura y se recortan aguas + abajo por el `dropna()` normal del pipeline, exactamente igual que + antes de este fix. + """ + if macro_close.empty: + return macro_close + macro_close = macro_close[~macro_close.index.duplicated(keep="last")].sort_index() + macro_close.index = normalize_daily_index(pd.DatetimeIndex(macro_close.index)) + calendar_end = max(macro_close.index.max(), pd.Timestamp(upto)) + daily_calendar = pd.date_range(macro_close.index.min(), calendar_end, freq="D") + return macro_close.reindex(daily_calendar).ffill() + + +def project_macro_frame(macro_closes: dict[str, pd.Series], target_index: pd.DatetimeIndex) -> pd.DataFrame: + """ + Punto de entrada único: dado `{macro_ticker: pd.Series de Close crudo}` + y el índice del activo objetivo (24/7 o 5/7, no importa cuál), devuelve + un DataFrame `out[macro_ticker]` ya alineado con `align_macro_to_calendar` + -- MISMA llamada desde `engineer_asset` (entrenamiento) y + `fetch_feature_ohlcv`/`_fetch_feature_window` (inferencia), para que + ambos pipelines vean el mundo macro exactamente igual (Requerimiento 3). + """ + target_index = normalize_daily_index(pd.DatetimeIndex(target_index)) + target_last_date = target_index.max() if len(target_index) else pd.Timestamp.now(tz=timezone.utc).normalize() + out = pd.DataFrame(index=target_index) + for macro_ticker, macro_close in macro_closes.items(): + aligned = align_macro_to_calendar(macro_close, target_last_date) + out[macro_ticker] = aligned.reindex(target_index) + return out \ No newline at end of file diff --git a/ml_engine/live_trade.py b/ml_engine/live_trade.py new file mode 100644 index 0000000000000000000000000000000000000000..804bfb42b0257e5b299c878c4796e94574e1563a --- /dev/null +++ b/ml_engine/live_trade.py @@ -0,0 +1,414 @@ +""" +live_trade.py -- Inferencia diaria + órdenes a Alpaca (paper trading) +============================================================================= +Cierra el círculo: toma el modelo YA entrenado y validado +(`services/kodaquant_models/equity_specialist/model_v5.keras`, producido por +`python ml_engine/train_kodaquant_v5.py`), corre inferencia sobre el día de +HOY con el mismo pipeline exacto de features que el entrenamiento +(`tkv5.download_all`/`tkv5.engineer_asset` -- cero drift train/serve), y +envía órdenes a tu cuenta paper de Alpaca con el mismo sizing por +vol-target que ya validamos en `pnl_backtest.py`. + +SEGURIDAD: corre en modo DRY-RUN por default -- imprime qué órdenes +mandaría, pero NO llama a Alpaca. Hace falta `--live` explícito para que +efectivamente envíe órdenes (a tu cuenta *paper*, sin plata real, pero aun +así conviene el freno). + +REQUISITOS (una sola vez): + 1. python ml_engine/train_kodaquant_v5.py -- si todavía no corriste + el entrenamiento de producción completo (walk_forward_eval.py y + pnl_backtest.py entrenan modelos DESCARTABLES por fold -- ninguno + queda guardado en disco. Este es el que sí hay que generar una vez). + 2. export ALPACA_API_KEY=tu_key + export ALPACA_SECRET_KEY=tu_secret + (Dashboard de Alpaca -> "Generate New Key", con la cuenta en modo + Paper Trading activado.) + +USO: + python services/live_trade.py # dry-run equity_specialist (default, seguro) + python services/live_trade.py --regime crypto_specialist # dry-run V22 (target_mode="triple_barrier") + python services/live_trade.py --live # envía órdenes de verdad (a paper) + python services/live_trade.py --vol-target-annual 0.15 + python services/live_trade.py --regime crypto_specialist --min-confidence 0.5 +""" +from __future__ import annotations + +import argparse +import logging +import pickle +import sys +from pathlib import Path + +import numpy as np +import requests + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (mismo bootstrap que el resto del repo) - +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# Import como módulo -- el `if __name__ == "__main__"` de train_kodaquant_v5.py +# NO se ejecuta acá, es seguro traer sus funciones/constantes sin disparar +# un entrenamiento completo. +import ml_engine.train_kodaquant_v5 as tkv5 # noqa: E402 + +logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s") +logger = logging.getLogger("kodaquant.live_trade") + +ALPACA_BASE_URL = "https://paper-api.alpaca.markets" +VOL_LOOKBACK_DAYS = 20 +MAX_LEVERAGE = 3.0 + +# V22 — meta-labeling (López de Prado, cap. 3), MISMO criterio y MISMO +# valor que `quanti_engine.TB_MIN_SIGNAL_CONFIDENCE` +# (services/quanti_engine.py) — duplicado a propósito acá, no importado: +# este script vive del lado `ml_engine/` (importa `tkv5` directo, ver +# `_bootstrap_project_root`), nunca del lado `services/` donde vive +# quanti_engine.py — acoplar ambos módulos por un solo float no vale el +# import cruzado. Si calibrás uno con pnl_backtest.py/walk_forward_eval.py +# (ver MANUAL DE IGNICIÓN), replicá el número acá también. +TB_MIN_SIGNAL_CONFIDENCE = 0.45 + + +def _alpaca_headers() -> dict: + import os + key, secret = os.environ.get("ALPACA_API_KEY", ""), os.environ.get("ALPACA_SECRET_KEY", "") + if not key or not secret: + raise RuntimeError( + "Faltan ALPACA_API_KEY / ALPACA_SECRET_KEY en el entorno. " + "Generalas en el dashboard de Alpaca (modo Paper Trading) y " + "exportalas antes de correr este script." + ) + return {"APCA-API-KEY-ID": key, "APCA-API-SECRET-KEY": secret} + + +def _load_production_model(regime_name: str): + model_dir = tkv5.MODELS_ROOT / regime_name + model_path, scalers_path = model_dir / "model_v5.keras", model_dir / "scalers_dict.pkl" + if not model_path.exists() or not scalers_path.exists(): + raise RuntimeError( + f"No existe un modelo de producción entrenado en {model_dir}. " + f"Corré primero: python ml_engine/train_kodaquant_v5.py" + ) + model = tkv5.keras.models.load_model(model_path, compile=False) + with open(scalers_path, "rb") as f: + payload = pickle.load(f) + logger.info("Modelo cargado: %s (entrenado con tickers=%s)", model_path, payload["tickers"]) + return model, payload + + +def predict_today_regression(model, payload: dict) -> tuple[dict[str, float], dict]: + """ + target_mode="regression" (equity_specialist) — CERO cambios de + comportamiento respecto al script original; solo ahora también + devuelve `all_market_data` (el MISMO que usó para featurizar, con + force_refresh=True) para que `__main__` deje de re-descargar una + segunda copia potencialmente desalineada antes de llamar a + `size_orders_regression` (ver FIX abajo, `__main__`). + + Devuelve {ticker: r_hat} -- log-return de mañana predicho, en la + unidad real (ya invertido el StandardScaler del target), para cada + ticker. Reusa `download_all`/`engineer_asset` de train_kodaquant_v5.py + tal cual -- garantiza que el feature engineering de HOY sea IDÉNTICO + al que vio el modelo en entrenamiento (ninguna transformación nueva + definida acá). + """ + tickers, lookback = payload["tickers"], payload["lookback"] + feature_cols = ["LOG_RETURN_1D"] + payload["tech_cols"] + payload["macro_tickers"] + + logger.info("Descargando datos frescos (force_refresh=True) para inferencia de hoy...") + all_market_data = tkv5.download_all( + tickers, payload["macro_tickers"], tkv5.PERIOD, cache_tag=f"{payload['regime_name']}_live", + force_refresh=True, + ) + + predictions: dict[str, float] = {} + for ticker in tickers: + df_asset = tkv5.engineer_asset(all_market_data, ticker, payload["macro_tickers"]) + if len(df_asset) < lookback: + logger.warning("%s: historia insuficiente hoy (%d < %d) -- se salta.", ticker, len(df_asset), lookback) + continue + + window = df_asset[feature_cols].values[-lookback:] + window_scaled = payload["feature_scalers"][ticker].transform(window) + X = window_scaled.reshape(1, lookback, len(feature_cols)).astype(np.float32) + asset_id = np.array([[payload["asset_to_id"][ticker]]], dtype=np.int32) + + y_pred_scaled = model.predict([X, asset_id], verbose=0) + r_hat = float(payload["target_scalers"][ticker].inverse_transform(y_pred_scaled[:, 0:1])[0, 0]) + predictions[ticker] = r_hat + + realized_vol = float(df_asset["LOG_RETURN_1D"].tail(VOL_LOOKBACK_DAYS).std()) + logger.info(" %-6s r_hat=%+.4f vol_%dd=%.4f último_close=$%.2f", + ticker, r_hat, VOL_LOOKBACK_DAYS, realized_vol, df_asset["RAW_CLOSE"].iloc[-1]) + + return predictions, all_market_data + + +def predict_today_triple_barrier(model, payload: dict, min_confidence: float) -> tuple[dict[str, dict], dict]: + """ + V22 — target_mode="triple_barrier" (crypto_specialist). UN forward + pass determinista (`model.predict(..., verbose=0)`, MISMO contrato que + `train_kodaquant_v5.evaluate_asset_triple_barrier` — nunca + autoregresivo: la cabeza softmax clasifica el DESENLACE COMPLETO de la + apuesta -- SL/TIMEOUT/TP dentro de `max_holding_days` -- no un paso + aislado que tenga sentido encadenar día a día, ver docstring de + `services/quanti_engine.py::_forecast_asset_triple_barrier` para el + razonamiento completo). + + Devuelve {ticker: {...}} con el detalle real de clasificación + (`predicted_class`, `confidence`, `probabilities`, `actionable`, + `expected_return_pct`, niveles de barrera reales) — `actionable=False` + (clase TIMEOUT, o confianza de clasificación bajo `min_confidence`, + meta-labeling real, ver TB_MIN_SIGNAL_CONFIDENCE) es la señal para que + `size_orders_triple_barrier` NO genere ninguna orden para ese ticker, + nunca una convicción inventada. + """ + tickers, lookback = payload["tickers"], payload["lookback"] + feature_cols = ["LOG_RETURN_1D"] + payload["tech_cols"] + payload["macro_tickers"] + tb_params = payload.get("tb_params") or {} + pt_mult = float(tb_params.get("pt_mult", 2.0)) + sl_mult = float(tb_params.get("sl_mult", 2.0)) + vol_lookback = int(tb_params.get("vol_lookback", 20)) + class_names = list(payload.get("tb_class_names") or ["SL", "TIMEOUT", "TP"]) + + logger.info("Descargando datos frescos (force_refresh=True) para inferencia de hoy...") + all_market_data = tkv5.download_all( + tickers, payload["macro_tickers"], tkv5.PERIOD, cache_tag=f"{payload['regime_name']}_live", + force_refresh=True, + ) + + predictions: dict[str, dict] = {} + for ticker in tickers: + df_asset = tkv5.engineer_asset(all_market_data, ticker, payload["macro_tickers"]) + if len(df_asset) < lookback: + logger.warning("%s: historia insuficiente hoy (%d < %d) -- se salta.", ticker, len(df_asset), lookback) + continue + + window = df_asset[feature_cols].values[-lookback:] + window_scaled = payload["feature_scalers"][ticker].transform(window) + X = window_scaled.reshape(1, lookback, len(feature_cols)).astype(np.float32) + asset_id = np.array([[payload["asset_to_id"][ticker]]], dtype=np.int32) + + probs = model.predict([X, asset_id], verbose=0)[0] # (3,) softmax [SL, TIMEOUT, TP] + if probs.shape != (3,): + logger.warning("%s: salida del modelo con shape inesperado %s -- se salta (sin clase inventada).", + ticker, probs.shape) + continue + + predicted_idx = int(np.argmax(probs)) + predicted_class = class_names[predicted_idx] + confidence = float(probs[predicted_idx]) + actionable = predicted_class != "TIMEOUT" and confidence >= min_confidence + + last_price = float(df_asset["RAW_CLOSE"].iloc[-1]) + # Volatilidad realizada actual -- MISMA fórmula exacta que + # `compute_triple_barrier_labels` (train_kodaquant_v5.py): std de + # LOG_RETURN_1D en una ventana de `vol_lookback` días. + vol_t = float(df_asset["LOG_RETURN_1D"].tail(vol_lookback).std()) + vol_t = vol_t if vol_t > 0 else 1e-6 + barrier_upper = last_price * float(np.exp(pt_mult * vol_t)) + barrier_lower = last_price * float(np.exp(-sl_mult * vol_t)) + + p_sl, p_timeout, p_tp = float(probs[0]), float(probs[1]), float(probs[2]) + # Esperanza del retorno bajo la distribución de clases real del + # modelo sobre los niveles de barrera reales -- MISMA fórmula que + # `quanti_engine._forecast_asset_triple_barrier` (cero cifra + # inventada; TIMEOUT aporta 0.0 -- ver docstring de esa función + # para por qué). Solo informativo/logging acá, `size_orders_ + # triple_barrier` no la usa para el sizing (ver esa función). + expected_return_pct = (p_tp * pt_mult * vol_t - p_sl * sl_mult * vol_t) * 100.0 + + predictions[ticker] = { + "predicted_class": predicted_class, + "confidence": confidence, + "probabilities": {"SL": p_sl, "TIMEOUT": p_timeout, "TP": p_tp}, + "actionable": actionable, + "expected_return_pct": expected_return_pct, + "last_price": last_price, + "barrier_upper": barrier_upper, + "barrier_lower": barrier_lower, + } + logger.info( + " %-8s clase=%-7s confianza=%5.1f%% P(SL/TIMEOUT/TP)=%.2f/%.2f/%.2f " + "E[retorno]=%+.2f%% accionable=%-5s último_close=$%.2f", + ticker, predicted_class, confidence * 100, p_sl, p_timeout, p_tp, + expected_return_pct, str(actionable), last_price, + ) + + return predictions, all_market_data + + +def size_orders_regression(predictions: dict[str, float], all_market_data, payload: dict, + equity: float, vol_target_annual: float) -> list[dict]: + """Mismo esquema de sizing que `pnl_backtest.simulate_portfolio` + (Directiva: cero cambios a la matemática del modelo -- esto es + asignación de capital, una capa aparte) -- tamaño inversamente + proporcional a la volatilidad realizada reciente de CADA activo, + igual-ponderado como base entre los tickers activos hoy.""" + vol_target_daily = vol_target_annual / np.sqrt(252) + n_active = len(predictions) + orders = [] + for ticker, r_hat in predictions.items(): + df_asset = tkv5.engineer_asset(all_market_data, ticker, payload["macro_tickers"]) + realized_vol = float(df_asset["LOG_RETURN_1D"].tail(VOL_LOOKBACK_DAYS).std()) + last_price = float(df_asset["RAW_CLOSE"].iloc[-1]) + if realized_vol <= 0 or np.isnan(realized_vol): + continue + size_mult = min(vol_target_daily / realized_vol, MAX_LEVERAGE) + notional = (equity / n_active) * size_mult + orders.append({ + "symbol": ticker, "side": "buy" if r_hat > 0 else "sell", + "notional": round(notional, 2), "r_hat": r_hat, "last_price": last_price, + }) + return orders + + +def size_orders_triple_barrier(predictions: dict[str, dict], equity: float) -> list[dict]: + """ + V22 -- sizing para target_mode="triple_barrier". MISMO criterio que + `pnl_backtest.simulate_portfolio_triple_barrier`: cada señal + accionable es un TRADE DISCRETO completo (entrada hoy, salida al + tocar barrera o vencer `max_holding_days`), nunca un turnover diario + -- vol-target NO aplica acá (ver aviso en `__main__`, mismo criterio + que `--vol-target-annual` en pnl_backtest.py), igual-ponderado entre + las señales accionables del día. Tickers con `actionable=False` + (TIMEOUT, o confianza bajo `TB_MIN_SIGNAL_CONFIDENCE`) NO generan + ninguna orden -- meta-labeling real, nunca un descarte silencioso ni + una convicción inventada. + """ + actionable = {t: p for t, p in predictions.items() if p["actionable"]} + if not actionable: + return [] + + n_active = len(actionable) + orders = [] + for ticker, pred in actionable.items(): + notional = equity / n_active + orders.append({ + "symbol": ticker, + "side": "buy" if pred["predicted_class"] == "TP" else "sell", + "notional": round(notional, 2), + # r_hat acá es E[log-return] bajo la distribución de clases (no + # un r_hat de un solo paso, ver predict_today_triple_barrier) -- + # se preserva el nombre de campo por compatibilidad con el log + # de __main__, que es agnóstico a target_mode. + "r_hat": pred["expected_return_pct"] / 100.0, + "last_price": pred["last_price"], + "predicted_class": pred["predicted_class"], + "confidence": pred["confidence"], + }) + return orders + + +def get_account_equity() -> float: + resp = requests.get(f"{ALPACA_BASE_URL}/v2/account", headers=_alpaca_headers(), timeout=10) + resp.raise_for_status() + return float(resp.json()["equity"]) + + +def get_current_side(symbol: str) -> str | None: + resp = requests.get(f"{ALPACA_BASE_URL}/v2/positions/{symbol}", headers=_alpaca_headers(), timeout=10) + if resp.status_code == 404: + return None + resp.raise_for_status() + qty = float(resp.json()["qty"]) + return "buy" if qty > 0 else "sell" + + +def submit_order(order: dict) -> None: + """Sizing en `notional` (dólares) para longs -- Alpaca no permite + notional en shorts (requiere `qty` entera), así que para sell se + convierte a acciones enteras al precio actual.""" + current_side = get_current_side(order["symbol"]) + if current_side is not None and current_side != order["side"]: + logger.info(" %s: posición actual (%s) contraria a la señal -- cerrando primero.", + order["symbol"], current_side) + requests.delete(f"{ALPACA_BASE_URL}/v2/positions/{order['symbol']}", + headers=_alpaca_headers(), timeout=10).raise_for_status() + + payload = {"symbol": order["symbol"], "side": order["side"], "type": "market", "time_in_force": "day"} + if order["side"] == "buy": + payload["notional"] = str(order["notional"]) + else: + payload["qty"] = str(max(1, int(order["notional"] / order["last_price"]))) + + resp = requests.post(f"{ALPACA_BASE_URL}/v2/orders", headers=_alpaca_headers(), json=payload, timeout=10) + resp.raise_for_status() + logger.info(" Orden enviada: %s", resp.json().get("id")) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Inferencia diaria + órdenes a Alpaca (paper trading).") + parser.add_argument("--regime", default="equity_specialist", choices=list(tkv5.REGIMES)) + parser.add_argument("--vol-target-annual", type=float, default=0.15, + help="SOLO target_mode='regression' (equity_specialist). Se ignora explícitamente " + "en target_mode='triple_barrier' (crypto_specialist) -- ver size_orders_triple_barrier.") + parser.add_argument("--min-confidence", type=float, default=TB_MIN_SIGNAL_CONFIDENCE, + help="SOLO target_mode='triple_barrier'. Piso de confianza de clasificación " + "(softmax [SL, TIMEOUT, TP]) por debajo del cual la señal se descarta -- " + "meta-labeling, López de Prado cap. 3. Calibrá este número con " + "pnl_backtest.py/walk_forward_eval.py antes de subirlo/bajarlo en vivo " + "(ver MANUAL DE IGNICIÓN).") + parser.add_argument("--live", action="store_true", + help="Sin esto: dry-run, solo imprime las órdenes. Con esto: las envía a Alpaca de verdad " + "(a tu cuenta PAPER -- sin plata real, pero es el freno de seguridad del script).") + args = parser.parse_args() + + model, payload = _load_production_model(args.regime) + target_mode = payload.get("target_mode", "regression") + + # V22 — despacho por target_mode (ver docstring de módulo / + # `services/quanti_engine.py` para el razonamiento completo de por qué + # la cabeza softmax de Triple Barrier necesita un camino de + # predicción/sizing propio, nunca el autoregresivo de regresión). + # + # FIX (drift train/serve en el sizing): la versión anterior descargaba + # `all_market_data` DOS veces -- una acá (force_refresh=False, para + # `size_orders`) y otra dentro de `predict_today` (force_refresh=True, + # para featurizar la predicción) -- pudiendo quedar `size_orders` + # leyendo un caché más viejo que el que realmente vio el modelo. Ahora + # `predict_today_*` devuelve el MISMO `all_market_data` que usó para + # predecir, y `size_orders_*` reusa exactamente ese objeto -- una sola + # descarga, cero desalineación posible entre precio/vol usados para + # predecir y usados para dimensionar la orden. + if target_mode == "triple_barrier": + if args.vol_target_annual != 0.15: # el usuario tocó el flag explícitamente + logger.warning("--vol-target-annual se ignora en target_mode='triple_barrier' " + "(ver size_orders_triple_barrier).") + predictions, all_market_data = predict_today_triple_barrier(model, payload, args.min_confidence) + if not predictions: + logger.error("Sin predicciones -- no se genera ninguna orden.") + raise SystemExit(1) + equity = get_account_equity() if args.live else 100_000.0 + orders = size_orders_triple_barrier(predictions, equity) + else: + predictions, all_market_data = predict_today_regression(model, payload) + if not predictions: + logger.error("Sin predicciones -- no se genera ninguna orden.") + raise SystemExit(1) + equity = get_account_equity() if args.live else 100_000.0 # placeholder solo para el preview en dry-run + orders = size_orders_regression(predictions, all_market_data, payload, equity, args.vol_target_annual) + + logger.info("=" * 78) + logger.info("%s -- regimen=%s (target_mode=%s) -- equity=$%.2f -- %d orden(es)%s", + "ÓRDENES A ENVIAR (--live)" if args.live else "DRY-RUN (ninguna orden real)", + args.regime, target_mode, equity, len(orders), + "" if args.live else " -- agregá --live para enviarlas de verdad") + for o in orders: + logger.info(" %-6s %-4s $%9.2f (r_hat=%+.4f, precio=$%.2f)", + o["symbol"], o["side"].upper(), o["notional"], o["r_hat"], o["last_price"]) + logger.info("=" * 78) + + if args.live: + for o in orders: + submit_order(o) + logger.info("Listo -- revisá tu dashboard de Alpaca (modo Paper) para confirmar las posiciones.") \ No newline at end of file diff --git a/ml_engine/pnl_backtest.py b/ml_engine/pnl_backtest.py new file mode 100644 index 0000000000000000000000000000000000000000..401666d314fef491837d5d8d5dc2dc337b96068d --- /dev/null +++ b/ml_engine/pnl_backtest.py @@ -0,0 +1,500 @@ +""" +pnl_backtest.py -- Traduce la señal del modelo en P&L real (V1/V22) +============================================================================= +`walk_forward_eval.py` responde "¿el modelo acierta más que el azar?" (sí, +medido). Este script responde la pregunta que decide si esto se opera con +capital real: sobre esas MISMAS predicciones walk-forward out-of-sample, +¿una cartera basada en la señal del modelo gana plata después de costos de +transacción? Cero cambios a la matemática/topología/loss de +`train_kodaquant_v5.py` ni a los folds de `walk_forward_eval.py` -- reutiliza +`_build_fold_dataset`/`build_model`/`train_model` tal cual están. + +Funciona para CUALQUIER régimen de `REGIMES`, incluido `crypto_specialist` +-- mismo `--regime` que ya acepta `walk_forward_eval.py`, sin tocar nada. +`target_mode` (leído de `tkv5.REGIMES[regime]`) bifurca la lógica de +señal/P&L, ver `collect_fold_predictions`/`simulate_portfolio*` abajo. + +ESTRATEGIA `target_mode="regression"` (equity_specialist, SIN CAMBIOS V1): + - Señal: long si r_hat > 0, short si r_hat < 0 (siempre en mercado). + - Sizing: igual-ponderado entre los activos evaluables ese día, sin + apalancamiento (fracción de capital = 1 / n_activos_del_día), o + vol-target opcional (`--vol-target-annual`). + - Costo: `--cost-bps` se cobra SOLO cuando la posición de un activo + cambia de signo respecto al día anterior (turnover real, no fijo). + +ESTRATEGIA `target_mode="triple_barrier"` (V22, crypto_specialist): + - Señal: long si la clase predicha es "TP", short si es "SL", SIN + OPERAR (meta-labeling: se descarta la apuesta) si es "TIMEOUT". + - P&L: cada fila YA es un trade discreto -- `realized_return` es el + log-return REAL logrado durante toda la ventana de + `max_holding_days` hasta que se resolvió la barrera (o venció la + vertical), ver `train_kodaquant_v5.compute_triple_barrier_labels`. + Costo se cobra UNA VEZ por trade (entry+exit), no por turnover diario + -- acá no hay "mantener posición día a día", ver + `simulate_portfolio_triple_barrier`. + - LIMITACIÓN CONOCIDA (documentada, no oculta): trades con + `max_holding_days > 1` pueden solaparse en el tiempo; este V1 NO + neteo/promedia posiciones concurrentes (López de Prado, cap. 4, + "Sample Weights" trata esto rigurosamente) -- piso de referencia + honesto, no un motor de sizing de cartera de producción. + +USO: + python ml_engine/pnl_backtest.py --regime equity_specialist \ + --n-folds 4 --cost-bps 5 + python ml_engine/pnl_backtest.py --regime crypto_specialist \ + --n-folds 4 --cost-bps 10 + (sin --epochs-per-fold: usa el presupuesto de producción del régimen, + ver AUDITORÍA RESCATE 2026-08 más abajo / walk_forward_eval.py.) +""" +from __future__ import annotations + +import argparse +import logging +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (mismo bootstrap que el resto de +# ml_engine/) ---------------------------------------------------------------- +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# Reutiliza walk_forward_eval.py tal cual (mismo `_build_fold_dataset`, +# mismo `tkv5` = train_kodaquant_v5) -- cero lógica de folds duplicada. +import ml_engine.walk_forward_eval as wfe # noqa: E402 + +tkv5 = wfe.tkv5 + +logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s") +logger = logging.getLogger("kodaquant.pnl_backtest") + + +def collect_fold_predictions(regime_name: str, n_folds: int, initial_train_frac: float, + test_frac: float, epochs_per_fold: int, output_dir: Path) -> pd.DataFrame: + """ + Idéntico esqueleto que `wfe.run_walk_forward`, pero devuelve las + predicciones CRUDAS (una fila por fecha x activo x fold) en vez de + solo el agregado de `evaluate_asset`/`evaluate_asset_triple_barrier` + -- es lo que necesitan `simulate_portfolio`/ + `simulate_portfolio_triple_barrier` para calcular P&L trade a trade. + + V22: bifurca en `target_mode` (leído de `tkv5.REGIMES[regime_name]`, + igual que `wfe.run_walk_forward`) -- columnas devueltas: + regression: fold, ticker, date, r_hat, r_true + triple_barrier: fold, ticker, date, pred_class_idx, true_class_idx, + p_sl, p_timeout, p_tp, realized_return + """ + if regime_name not in tkv5.REGIMES: + raise ValueError(f"Régimen desconocido: '{regime_name}' -- opciones: {list(tkv5.REGIMES)}") + + regime_cfg = tkv5.REGIMES[regime_name] + tickers = regime_cfg["tickers"] + asset_to_id = {t: i for i, t in enumerate(tickers)} + feature_cols = ["LOG_RETURN_1D"] + tkv5.get_tech_cols(regime_name) + tkv5.MACRO_TICKERS + output_dir.mkdir(parents=True, exist_ok=True) + + target_mode = regime_cfg.get("target_mode", "regression") + # V23.5 -- default POR TICKER (fallback SOLO si CRYPTO_CALIBRATE_ + # BARRIERS=False, ver `wfe.run_walk_forward`/`tkv5.run_regime_pipeline`); + # si está en True (default de producción), cada fold recalibra por + # activo vía `wfe._calibrate_fold_tb_params` -- mismo criterio train-only + # de ESE fold, cero lógica de grid search duplicada. + _default_tb_params: dict | None = None + if target_mode == "triple_barrier": + _default_tb_params = { + "pt_mult": regime_cfg.get("pt_mult", tkv5.TRIPLE_BARRIER_PT_MULT), + "sl_mult": regime_cfg.get("sl_mult", tkv5.TRIPLE_BARRIER_SL_MULT), + "max_holding_days": regime_cfg.get("max_holding_days", tkv5.TRIPLE_BARRIER_MAX_HOLDING_DAYS), + "vol_lookback": regime_cfg.get("vol_lookback", tkv5.TRIPLE_BARRIER_VOL_LOOKBACK), + } + + logger.info("Descargando/leyendo caché OHLCV+macro para '%s'...", regime_name) + all_market_data = tkv5.download_all( + tickers, tkv5.MACRO_TICKERS, tkv5.PERIOD, cache_tag=regime_name, force_refresh=False, + ) + dfs = {t: tkv5.engineer_asset(all_market_data, t, tkv5.MACRO_TICKERS) for t in tickers} + n_per_ticker = {t: len(dfs[t]) for t in tickers} + logger.info("Filas engineered por activo: %s", n_per_ticker) + + tmp_ckpt = output_dir / "_pnl_backtest_tmp.keras" + rows: list[dict] = [] + monitor_metric = "val_actionable_accuracy" if target_mode == "triple_barrier" else "val_directional_accuracy_metric" + + for fold_idx in range(n_folds): + # V23.5 -- fronteras POR TICKER primero (la calibración por-fold las + # necesita antes de construir datasets), mismo orden que + # `wfe.run_walk_forward`. + train_end_by_ticker: dict[str, int] = {} + test_end_by_ticker: dict[str, int] = {} + for t in tickers: + n = n_per_ticker[t] + train_end = int(n * (initial_train_frac + fold_idx * test_frac)) + test_end = int(n * (initial_train_frac + (fold_idx + 1) * test_frac)) + train_end_by_ticker[t] = max(train_end, tkv5.LOOKBACK + 1) + test_end_by_ticker[t] = min(test_end, n) + + tb_params_fold: dict[str, dict] | None = None + if target_mode == "triple_barrier": + if tkv5.CRYPTO_CALIBRATE_BARRIERS: + tb_params_fold = wfe._calibrate_fold_tb_params(dfs, tickers, train_end_by_ticker) + else: + tb_params_fold = {t: dict(_default_tb_params) for t in tickers} + for t in tickers: + tbt = tb_params_fold[t] + logger.info("Fold %d/%d [%s]: pt_mult=%.2f sl_mult=%.2f vol_lookback=%d max_holding_days=%d", + fold_idx + 1, n_folds, t, tbt["pt_mult"], tbt["sl_mult"], + tbt["vol_lookback"], tbt["max_holding_days"]) + + # ROLLBACK V23.6 -- CONGRUENCIA con walk_forward_eval.py/tkv5: el + # sample_weight equity por volatilidad fue purgado en los tres + # archivos (ver changelog de `train_kodaquant_v5.py`). Este backtest + # ya entrena equity_specialist con gradiente plano/uniforme, igual + # que walk_forward_eval.py y run_regime_pipeline. + X_train_parts, y_train_parts, aid_train_parts, sw_train_parts = [], [], [], [] + fold_test: dict[str, tuple] = {} + skipped: list[str] = [] + + for t in tickers: + train_end = train_end_by_ticker[t] + test_end = test_end_by_ticker[t] + tb_params_t = tb_params_fold[t] if tb_params_fold is not None else None + built = wfe._build_fold_dataset(dfs[t], t, tkv5.LOOKBACK, train_end, test_end, asset_to_id, + feature_cols, target_mode=target_mode, tb_params=tb_params_t) + if built is None: + skipped.append(t) + continue + train, test, _f_scaler, t_scaler = built + fold_test[t] = (test, t_scaler) + X_train_parts.append(train["X"]) + y_train_parts.append(train["y"]) + aid_train_parts.append(train["asset_id"]) + if target_mode == "triple_barrier": + sw_train_parts.append(train["sample_weight"]) + # ROLLBACK V23.6: rama "regression" (equity) purgada, ver arriba. + + if not X_train_parts: + logger.warning("Fold %d/%d: sin datos suficientes -- se salta.", fold_idx + 1, n_folds) + continue + + X_train = np.concatenate(X_train_parts, axis=0) + y_train = np.concatenate(y_train_parts, axis=0) + aid_train = np.concatenate(aid_train_parts, axis=0).reshape(-1, 1) + # ROLLBACK V23.6: solo triple_barrier (cripto) pesa muestras. + _uses_sample_weight = target_mode == "triple_barrier" + sw_train = np.concatenate(sw_train_parts, axis=0) if _uses_sample_weight else None + n_fit_samples = int(len(X_train) * (1 - tkv5.VALIDATION_SPLIT)) + steps_per_epoch = max(1, n_fit_samples // tkv5.BATCH_SIZE) + + logger.info("Fold %d/%d: X_train=%s | activos evaluables=%d%s", + fold_idx + 1, n_folds, X_train.shape, len(fold_test), + f" | saltados={skipped}" if skipped else "") + + class_alpha = None + if target_mode == "triple_barrier": + train_class_idx = np.argmax(y_train, axis=-1) + class_counts = np.maximum(np.bincount(train_class_idx, minlength=3).astype(np.float64), 1.0) + class_alpha = (len(train_class_idx) / (3.0 * class_counts)).tolist() + + model, gamma_var = tkv5.build_model( + n_timesteps=tkv5.LOOKBACK, n_features=tkv5.get_n_features(regime_name), n_assets=len(tickers), + steps_per_epoch=steps_per_epoch, regime_name=regime_name, + embed_dim=tkv5.ASSET_EMBED_DIM, huber_delta=tkv5.HUBER_DELTA, + gamma_initial=tkv5.GAMMA_INITIAL, variance_lambda=tkv5.VARIANCE_LAMBDA, + variance_cap=tkv5.VARIANCE_CAP, gaussian_nll_beta=tkv5.GAUSSIAN_NLL_BETA, + log_var_min=tkv5.LOG_VAR_MIN, log_var_max=tkv5.LOG_VAR_MAX, + log_var_l2_lambda=tkv5.LOG_VAR_L2_LAMBDA, log_var_barrier_lambda=tkv5.LOG_VAR_BARRIER_LAMBDA, + target_mode=target_mode, class_alpha=class_alpha, + focal_gamma=tkv5.TRIPLE_BARRIER_FOCAL_GAMMA, label_smoothing=tkv5.TRIPLE_BARRIER_LABEL_SMOOTHING, + model_name=f"KodaQuant_{regime_name}_PNL_fold{fold_idx + 1}", + ) + _history, model = tkv5.train_model( + model, X_train, aid_train, y_train, checkpoint_path=tmp_ckpt, + epochs=epochs_per_fold, batch_size=tkv5.BATCH_SIZE, validation_split=tkv5.VALIDATION_SPLIT, + gamma_variable=gamma_var, gamma_max=tkv5.GAMMA_MAX, + gamma_warmup_epochs=min(tkv5.GAMMA_WARMUP_EPOCHS, max(1, epochs_per_fold // 3)), + gamma_schedule=tkv5.GAMMA_SCHEDULE, gamma_sigmoid_steepness=tkv5.GAMMA_SIGMOID_STEEPNESS, + sample_weight=sw_train, monitor_metric=monitor_metric, + ) + + for t, (test, t_scaler) in fold_test.items(): + asset_id_col = test["asset_id"].reshape(-1, 1) + if target_mode == "triple_barrier": + y_pred_proba = model.predict([test["X"], asset_id_col], verbose=0) + pred_class_idx = np.argmax(y_pred_proba, axis=-1) + true_class_idx = np.argmax(test["y"], axis=-1) + realized_return = test["y_return"] + for d, pc, tc, proba, rret in zip(test["dates"], pred_class_idx, true_class_idx, + y_pred_proba, realized_return): + rows.append({ + "fold": fold_idx + 1, "ticker": t, "date": d, + "pred_class_idx": int(pc), "true_class_idx": int(tc), + "p_sl": float(proba[0]), "p_timeout": float(proba[1]), "p_tp": float(proba[2]), + "realized_return": float(rret), + }) + else: + y_pred_scaled = model.predict([test["X"], asset_id_col], verbose=0) + r_hat = t_scaler.inverse_transform(y_pred_scaled[:, 0:1]).flatten() + r_true = t_scaler.inverse_transform(test["y"]).flatten() + for d, rh, rt in zip(test["dates"], r_hat, r_true): + rows.append({"fold": fold_idx + 1, "ticker": t, "date": d, + "r_hat": float(rh), "r_true": float(rt)}) + + tmp_ckpt.unlink(missing_ok=True) + try: + tkv5.keras.backend.clear_session() + except Exception: # noqa: BLE001 -- best-effort, nunca debe tumbar la corrida + pass + + tmp_ckpt.unlink(missing_ok=True) + df = pd.DataFrame(rows) + if not df.empty: + df.attrs["target_mode"] = target_mode + return df + + +def simulate_portfolio(preds: pd.DataFrame, cost_bps: float, vol_target_annual: float | None = None, + vol_lookback: int = 20, max_leverage: float = 3.0) -> pd.DataFrame: + """ + `target_mode="regression"` (equity_specialist, SIN CAMBIOS V1) -- + cartera long/short diaria entre los activos evaluables cada día. Costo + de transacción SOLO cuando la posición de un activo cambia de signo + respecto al día anterior (turnover real) -- así un activo que el modelo + mantiene "largo" varios días seguidos no paga comisión de nuevo cada vez. + + `vol_target_annual` (ej. 0.15 = 15% anualizado): si se pasa, cada activo + se pondera INVERSAMENTE a su volatilidad realizada reciente (rolling + `vol_lookback` días, `.shift(1)` -- SOLO retornos pasados, cero look-ahead) + en vez de peso igual fijo. Objetivo: que un activo momentáneamente muy + volátil (ej. TSLA en un evento) no domine el drawdown del portfolio solo + por moverse más, no por tener más señal. `max_leverage` limita el tope + por activo para que un período de vol casi nula no dispare el tamaño a + infinito. Con `vol_target_annual=None` (default), el comportamiento es + IDÉNTICO al de antes (igual-ponderado, sin escalar) -- no rompe nada. + """ + preds = preds.sort_values(["ticker", "date"]).copy() + preds["signal"] = np.sign(preds["r_hat"]) + preds["prev_signal"] = preds.groupby("ticker")["signal"].shift(1) + preds["turned_over"] = preds["prev_signal"].notna() & (preds["signal"] != preds["prev_signal"]) + cost = cost_bps / 10_000.0 + + if vol_target_annual is not None: + vol_target_daily = vol_target_annual / np.sqrt(252) + realized_vol = preds.groupby("ticker")["r_true"].transform( + lambda s: s.shift(1).rolling(vol_lookback, min_periods=max(2, vol_lookback // 2)).std() + ) + preds["size"] = (vol_target_daily / realized_vol).clip(upper=max_leverage).fillna(0.0) + else: + preds["size"] = 1.0 + + preds["pnl_gross"] = preds["signal"] * preds["size"] * preds["r_true"] + preds["pnl_net"] = preds["pnl_gross"] - np.where(preds["turned_over"], cost * preds["size"], 0.0) + + daily = preds.groupby("date").agg(n_assets=("ticker", "count"), pnl_net=("pnl_net", "mean")).sort_index() + daily["equity"] = (1.0 + daily["pnl_net"]).cumprod() + return daily + + +def simulate_portfolio_triple_barrier(preds: pd.DataFrame, cost_bps: float) -> pd.DataFrame: + """ + V22 -- simulación de cartera para `target_mode="triple_barrier"`. A + diferencia de `simulate_portfolio` (regresión, un retorno DIARIO por + fila), acá cada fila YA ES un trade completo -- `realized_return` es + el log-return REAL logrado durante toda la ventana de + `max_holding_days` hasta que se resolvió la barrera (o venció la + vertical), ver `train_kodaquant_v5.compute_triple_barrier_labels`. + + Señal: + long (+1) si la clase predicha es "TP" + short (-1) si la clase predicha es "SL" + SIN OPERAR (se descarta la fila entera, cero costo/cero P&L) si la + clase predicha es "TIMEOUT" -- meta-labeling: "sin convicción". + + `realized_return` ya es simétrico respecto a la dirección real del + precio (positivo si subió, negativo si bajó, cualquiera sea la clase + verdadera) -- multiplicarlo por `signal` da el P&L correcto tanto si + el trade fue GANADOR (predicción == clase real) como si fue PERDEDOR + (predicción != clase real, incluida una TP/SL cruzada). + + Costo se cobra UNA VEZ por trade abierto (entry+exit) -- acá no hay + noción de "mantener posición día a día": cada fila es un trade + discreto autocontenido, a diferencia del turnover diario de + `simulate_portfolio`. + + LIMITACIÓN CONOCIDA (documentada, no oculta): con `max_holding_days` + > 1 los trades pueden SOLAPARSE en el tiempo (una entrada el día t y + otra el día t+3 conviven simultáneamente) -- este V1 NO neteo/promedia + posiciones concurrentes (López de Prado, cap. 4, "Sample Weights", es + el tratamiento riguroso de bets concurrentes) y compone la curva de + equity POR FECHA DE ENTRADA, igual-ponderado entre los trades abiertos + ese día -- un piso de referencia honesto sobre si la señal tiene edge + económicamente significativo neto de costos, no un motor de sizing de + cartera de producción. + """ + preds = preds.copy() + cost = cost_bps / 10_000.0 + + tp_idx = tkv5.TB_LABEL_TO_CLASS_IDX[1] + sl_idx = tkv5.TB_LABEL_TO_CLASS_IDX[-1] + preds["signal"] = 0 + preds.loc[preds["pred_class_idx"] == tp_idx, "signal"] = 1 + preds.loc[preds["pred_class_idx"] == sl_idx, "signal"] = -1 + + traded = preds[preds["signal"] != 0].copy() + if traded.empty: + return pd.DataFrame(columns=["n_trades", "pnl_net", "equity"]) + + traded["pnl_gross"] = traded["signal"] * traded["realized_return"] + traded["pnl_net"] = traded["pnl_gross"] - cost # un costo por trade (entry+exit), no por turnover + + daily = traded.groupby("date").agg(n_trades=("ticker", "count"), pnl_net=("pnl_net", "mean")).sort_index() + daily["equity"] = (1.0 + daily["pnl_net"]).cumprod() + return daily + + +def summarize_pnl(daily: pd.DataFrame) -> dict: + """ + Genérico entre ambos `target_mode` -- solo lee las columnas + `pnl_net`/`equity`, presentes en el resultado de `simulate_portfolio` + (regresión) y de `simulate_portfolio_triple_barrier` (V22) por igual. + La anualización (factor 252) asume eventos de frecuencia diaria en el + índice -- válida sin matices en el régimen de regresión (un retorno + por día de mercado); en `triple_barrier` es una aproximación (el + índice son fechas de ENTRADA, no de resolución -- ver limitación + documentada en `simulate_portfolio_triple_barrier`), suficiente para + un veredicto de "V1, piso de referencia honesto". + """ + r = daily["pnl_net"] + n = len(r) + total_return = float(daily["equity"].iloc[-1] - 1.0) if n else 0.0 + ann_return = float((1 + total_return) ** (252 / n) - 1) if n > 0 else 0.0 + ann_vol = float(r.std(ddof=1) * np.sqrt(252)) if n > 1 else 0.0 + sharpe = float((r.mean() * 252) / ann_vol) if ann_vol > 0 else 0.0 + running_max = daily["equity"].cummax() + drawdown = daily["equity"] / running_max - 1.0 + max_dd = float(drawdown.min()) if n else 0.0 + win_rate = float((r > 0).mean()) if n else 0.0 + return { + "n_days": n, "total_return_pct": total_return * 100, "annualized_return_pct": ann_return * 100, + "annualized_vol_pct": ann_vol * 100, "sharpe": sharpe, "max_drawdown_pct": max_dd * 100, + "win_rate_pct": win_rate * 100, + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Backtest de P&L sobre predicciones walk-forward.") + parser.add_argument("--regime", default="equity_specialist", choices=list(tkv5.REGIMES)) + parser.add_argument("--n-folds", type=int, default=4) + parser.add_argument("--initial-train-frac", type=float, default=0.60) + parser.add_argument("--test-frac", type=float, default=0.08) + parser.add_argument("--epochs-per-fold", type=int, default=None, + help="AUDITORÍA RESCATE 2026-08: default REAL ahora es el presupuesto de producción " + "del régimen (tkv5.REGIMES[regime]['epochs'], ver walk_forward_eval.py) en vez " + "de 30 fijo -- el default anterior subentrenaba el modelo sistemáticamente.") + parser.add_argument("--cost-bps", type=float, default=5.0, + help="Costo por operación, en basis points. Ajustá según tu bróker/exchange real -- " + "5bps es un piso optimista para equities líquidas; cripto suele ser más caro. En " + "target_mode='regression' se cobra por turnover diario; en 'triple_barrier' se " + "cobra una vez por trade (entry+exit), ver simulate_portfolio_triple_barrier.") + parser.add_argument("--vol-target-annual", type=float, default=None, + help="SOLO target_mode='regression'. Ej. 0.15 = objetivo de 15%% de volatilidad " + "anualizada. Si se omite, sizing igual-ponderado (comportamiento original).") + parser.add_argument("--vol-lookback", type=int, default=20) + parser.add_argument("--max-leverage", type=float, default=3.0) + parser.add_argument("--output-dir", type=Path, default=tkv5.BASE_DIR / "walk_forward_reports") + args = parser.parse_args() + + target_mode = tkv5.REGIMES[args.regime].get("target_mode", "regression") + + # AUDITORÍA RESCATE 2026-08: mismo fix que walk_forward_eval.py -- sin + # --epochs-per-fold explícito, usar el presupuesto de PRODUCCIÓN del + # régimen, nunca un default de iteración rápida hardcodeado. + effective_epochs_per_fold = args.epochs_per_fold + if effective_epochs_per_fold is None: + effective_epochs_per_fold = tkv5.REGIMES[args.regime].get("epochs", tkv5.EPOCHS) + logger.info( + "--epochs-per-fold no especificado -> usando presupuesto de producción de '%s': %d épocas.", + args.regime, effective_epochs_per_fold, + ) + + preds_df = collect_fold_predictions( + regime_name=args.regime, n_folds=args.n_folds, + initial_train_frac=args.initial_train_frac, test_frac=args.test_frac, + epochs_per_fold=effective_epochs_per_fold, output_dir=args.output_dir, + ) + + if preds_df.empty: + logger.error("Ningún fold produjo predicciones -- revisá --n-folds/--test-frac.") + raise SystemExit(1) + + args.output_dir.mkdir(parents=True, exist_ok=True) + preds_csv = args.output_dir / f"pnl_predictions_{args.regime}.csv" + preds_df.to_csv(preds_csv, index=False) + + if target_mode == "triple_barrier": + if args.vol_target_annual is not None: + logger.warning("--vol-target-annual se ignora en target_mode='triple_barrier' " + "(ver simulate_portfolio_triple_barrier).") + daily_pnl = simulate_portfolio_triple_barrier(preds_df, cost_bps=args.cost_bps) + cost_desc = "por trade (entry+exit)" + else: + daily_pnl = simulate_portfolio(preds_df, cost_bps=args.cost_bps, vol_target_annual=args.vol_target_annual, + vol_lookback=args.vol_lookback, max_leverage=args.max_leverage) + cost_desc = "por turnover" + + if daily_pnl.empty: + logger.error("Ninguna fila operable (target_mode='triple_barrier': todas las predicciones fueron " + "'TIMEOUT') -- no hay P&L que reportar. Esto es en sí un resultado: el modelo no " + "encontró convicción suficiente en este split; probá con --n-folds/--epochs-per-fold " + "distintos o revisá la distribución de clases logueada durante el entrenamiento.") + raise SystemExit(1) + + daily_csv = args.output_dir / f"pnl_daily_{args.regime}.csv" + daily_pnl.to_csv(daily_csv) + + stats = summarize_pnl(daily_pnl) + logger.info("=" * 78) + logger.info("P&L -- régimen '%s' (target_mode=%s) | %d día(s) de test out-of-sample | costo=%.1fbps %s", + args.regime, target_mode, stats["n_days"], args.cost_bps, cost_desc) + logger.info(" Retorno total: %+.2f%%", stats["total_return_pct"]) + logger.info(" Retorno anualizado: %+.2f%%", stats["annualized_return_pct"]) + logger.info(" Volatilidad anual.: %.2f%%", stats["annualized_vol_pct"]) + logger.info(" Sharpe (sin rf): %.2f", stats["sharpe"]) + logger.info(" Max drawdown: %.2f%%", stats["max_drawdown_pct"]) + logger.info(" Win rate (días): %.1f%%", stats["win_rate_pct"]) + logger.info("=" * 78) + logger.info("Predicciones -> %s", preds_csv) + logger.info("Equity diaria -> %s", daily_csv) + + if stats["sharpe"] <= 0 or stats["total_return_pct"] <= 0: + logger.warning("Sharpe/retorno <= 0 con este costo asumido: el edge medido en walk_forward_eval.py NO " + "alcanza para cubrir %.1fbps de costo %s. Antes de operar, probá con costos reales de " + "tu bróker/exchange y/o (target_mode='triple_barrier') pt_mult/sl_mult/max_holding_days " + "distintos, o (target_mode='regression') un sizing menos ingenuo.", args.cost_bps, cost_desc) + + try: + import matplotlib.pyplot as plt + fig, ax = plt.subplots(figsize=(9, 5)) + ax.plot(daily_pnl.index, daily_pnl["equity"], linewidth=1.5) + ax.axhline(1.0, color="red", linestyle="--", linewidth=1, label="Break-even") + ax.set_ylabel("Equity (base = 1.0)") + ax.set_title(f"Curva de equity walk-forward -- {args.regime} (costo={args.cost_bps}bps, {target_mode})") + ax.legend() + fig.autofmt_xdate() + fig.tight_layout() + chart_path = args.output_dir / f"pnl_equity_curve_{args.regime}.png" + fig.savefig(chart_path, dpi=150) + plt.close(fig) + logger.info("Chart -> %s", chart_path) + except Exception as exc: # noqa: BLE001 -- el chart es un extra, nunca debe tumbar el resumen + logger.debug("No se pudo generar el chart (%r) -- no bloqueante.", exc) \ No newline at end of file diff --git a/ml_engine/quanti_model.onnx b/ml_engine/quanti_model.onnx new file mode 100644 index 0000000000000000000000000000000000000000..f6949bead7a05c90fe3cd65e343a82e2a7c6f4ae --- /dev/null +++ b/ml_engine/quanti_model.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:107600b1438c3157e5cd24ff63b12ffa49b2d41468d28166520638df228f6fad +size 5303596 diff --git a/ml_engine/run_full_pipeline.sh b/ml_engine/run_full_pipeline.sh new file mode 100755 index 0000000000000000000000000000000000000000..4517171bf1cddbce5e93b1439a5a3131cbb65422 --- /dev/null +++ b/ml_engine/run_full_pipeline.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# run_full_pipeline.sh -- KodaQuant, ciclo completo post-auditoría 2026-08 +# Entrenamiento (épocas de producción) + walk-forward + backtest de P&L, +# equity_specialist y crypto_specialist. Corré esto DESDE ml_engine/. +set -euo pipefail + +cd "$(dirname "$0")" + +echo "=== [1/6] Full retrain -- equity_specialist + crypto_specialist (EPOCHS=100/180) ===" +python train_kodaquant_v5.py + +echo "=== [2/6] Walk-forward EQUITY (sin --epochs-per-fold -> usa EPOCHS=100 de producción) ===" +python walk_forward_eval.py --regime equity_specialist --n-folds 4 + +echo "=== [3/6] Walk-forward CRYPTO (sin --epochs-per-fold -> usa epochs=180 de producción) ===" +python walk_forward_eval.py --regime crypto_specialist --n-folds 4 + +echo "=== [4/6] PnL Backtest EQUITY (5bps, sizing igual-ponderado) ===" +python pnl_backtest.py --regime equity_specialist --n-folds 4 --cost-bps 5 + +echo "=== [5/6] PnL Backtest CRYPTO (10bps, target_mode=triple_barrier) ===" +python pnl_backtest.py --regime crypto_specialist --n-folds 4 --cost-bps 10 + +echo "=== [6/6] Fine-tuning incremental MLOps (Champion vs Challenger, ambos regímenes) ===" +python train_pipeline.py + +echo "=== LISTO -- reportes en ml_engine/walk_forward_reports/ ===" \ No newline at end of file diff --git a/ml_engine/scalers.pkl b/ml_engine/scalers.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d9c8bb151cd76a36bdc5104fdf9b36a1e78b458c --- /dev/null +++ b/ml_engine/scalers.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1adcfddabba14f947ca24b087203549530aef8512905a4824a671719374a8b35 +size 8517 diff --git a/ml_engine/train_kodaquant_v5.py b/ml_engine/train_kodaquant_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8c61d93301c6b44a4d73195c207b61589c4bd0 --- /dev/null +++ b/ml_engine/train_kodaquant_v5.py @@ -0,0 +1,4283 @@ +# %% +# NOTA 2026-09 -- limpieza: la línea original acá (`#!pip install yfinance nltk +# -q`) era dead-reference doble: `nltk` no se importa en ningún punto de este +# archivo (confirmado con pyflakes) y `yfinance` vive en `requirements.txt` +# (ver auditoría de dependencias) -- el punto de entrada real de instalación +# es `pip install -r requirements.txt` en la raíz del proyecto, no esta línea. + +""" +train_kodaquant_v5.py — KodaQuant V5: Enrutamiento de Modelos Especialistas +============================================================================= +Refactor arquitectónico respecto a V4 (modelo GLOBAL único, 10 activos +mezclados en el mismo espacio latente). DIAGNÓSTICO V4: forzar Cripto +(volatilidad extrema, 24/7) y Acciones (volatilidad tradicional, horario +cerrado) dentro del mismo embedding compartido corrompió la optimización de +pesos -> edge >50% en cripto, colapso a 34-38% en acciones. + +FIX V5 — ENRUTAMIENTO DE MODELOS ESPECIALISTAS POR RÉGIMEN: en vez de UN +modelo global, este script entrena DOS ciclos de optimización completamente +independientes y secuenciales, uno por régimen: + + EQUITY -> ['AAPL','MSFT','NVDA','TSLA','GOOGL','AMZN','META','SPY'] + CRYPTO -> ['BTC-USD', 'ETH-USD'] + +Cada especialista es una instancia SEPARADA de la MISMA arquitectura +(invarianza topológica estricta, ver `build_model`): no se comparten pesos, +scalers, ni embedding de activos entre regímenes. Esto es simplemente dos +corridas de la Fase A-E de V4 con universos distintos; toda la matemática +(BiLSTM(64) -> LayerNorm -> MultiHeadAttention+Residual -> LayerNorm -> +BahdanauAttention -> Concat(context, asset_embed) -> Dense(32)+Residual -> +Dense(1), DirectionalHuberLoss con penalización de varianza, curriculum de +gamma sigmoide) se mantiene BIT A BIT idéntica a V4. + +NUEVO EN V5: + 1) NEWS_SENTIMENT_SCORE (services/data_pipeline.py): titulares vía + yfinance.Ticker().news / Finnhub, escalar VADER en [-1, 1], + concatenado al tensor de features ANTES de escalar. + 2) Persistencia de nivel institucional: cada especialista se guarda en + su propia carpeta bajo services/kodaquant_models/, con nombres de + archivo ESTABLES (model_v5.keras, scalers_dict.pkl, + evaluation_chart.png) — cada corrida SOBREESCRIBE el artefacto + anterior, nunca genera duplicados versionados a mano. + 3) CERO bloqueos: `matplotlib` corre en backend "Agg" (sin display) y + toda visualización usa `plt.savefig(...)`, jamás `plt.show()` — el + script se ejecuta de punta a punta sin intervención humana en + servidores headless / runners de CI. + +Entorno objetivo: local o servidor headless, TensorFlow/Keras 3.x. + +NUEVO EN V6 — FIX COLAPSO DE VARIANZA EN `crypto_specialist` (auditoría: +underfitting crítico atribuido a la caída de volumen de entrenamiento del +dataset GLOBAL V4 mezclado (~1M muestras, 10 activos en un solo embedding +compartido) al dataset por-régimen V5 (~100k muestras, `crypto_specialist` +aislado con solo 2 tickers). Bajo escasez de datos, `DirectionalGaussianNLL` +puede minimizar la pérdida INFLANDO `log_var` en vez de mejorar `mu` —el +gradiente sobre `mu` está ponderado por 1/var, así que a menos datos, menos +señal de corrección y "var→∞" se vuelve el óptimo local dominante (Seitzer +et al., "On the Pitfalls of Heteroscedastic Uncertainty Estimation with +Probabilistic Neural Networks", ICLR 2022, arXiv:2203.09168). Dos frentes, +CERO cambios de arquitectura (Fase B intacta, invarianza topológica +preservada) y CERO ruptura de compatibilidad con `services/quanti_engine.py` +en inferencia (el head `log_var` sigue siendo literalmente `log_var`, sin +ningún remapeo — `quanti_engine.py` sigue leyendo `y_pred[:, 1]` tal cual): + + 4) `DirectionalGaussianNLL` — 3 mecanismos apilados (ver docstring de + la clase): β-NLL (ataca la causa raíz del incentivo perverso), + barrera cuadrática blanda + ridge L2 sobre `log_var` (amortiguación + directa de su magnitud, gradiente nunca nulo a diferencia de un + hard-clip) y clip numérico interno solo para el forward de la NLL + (evita `exp(log_var)` -> inf/NaN mientras la barrera reeduca al + optimizador). + 5) Oversampling por Magnitude-Warping por régimen + (`_magnitude_warp_oversample`, Fase A/C, factor=4.0x en + `crypto_specialist`): descartado el ruido i.i.d. por-paso (destruye + la autocorrelación temporal intra-ventana, el mismo defecto que el + bootstrap+jitter gaussiano de la iteración anterior de este + mecanismo). En su lugar, curva de deformación de MAGNITUD por + ventana y por canal (Um et al. 2017; Iwana & Uchida 2021): pocos + nodos de control (`MAGNITUDE_WARP_KNOTS`) muestreados ~N(1, + `MAGNITUDE_WARP_SIGMA`) e interpolados con spline cúbico sobre los + `LOOKBACK` pasos -> curva suave de baja frecuencia que reescala la + serie ALREDEDOR de su propia media local + (`media_ventana + (X - media_ventana) · curva`, nunca el valor + absoluto en [0,1] de MinMaxScaler — ver docstring de la función), + preservando la forma/inercia temporal real del criptomercado y + expandiendo la frontera de decisión sin memorizar duplicados + exactos ni degenerar en ruido blanco. Aplicado ÚNICAMENTE sobre el + split de train (cero fuga hacia test). `equity_specialist` + (8 tickers, volumen suficiente) queda con `oversample_factor=1.0` + -> no-op exacto, cero cambio de comportamiento respecto a V5. + +NUEVO EN V23.5 (Directiva Head Quant -- BTC/equity rezagados vs. ETH/SPY): + 6) Calibración de Triple Barrier DESACOPLADA por activo (ver + `calibrate_crypto_triple_barrier`): cada ticker cripto busca su + propio pt_mult/sl_mult/vol_lookback/max_holding_days de forma + INDEPENDIENTE (ya no maximin pooled) -- ETH ya no cede óptimo por + compromiso con BTC. ROMPE el esquema de `scalers_dict.pkl`: + `tb_params` pasa de dict plano a dict-de-dicts `{ticker: {...}}`. + `services/quanti_engine.py` (`_forecast_asset_triple_barrier`) NO + está en este archivo y DEBE actualizarse a mano para leer + `tb_params[ticker]` en vez de `tb_params` plano, o la inferencia + usará barreras equivocadas sin error visible. + 7) [ROLLBACK EN V23.6 -- ver nota abajo] `PUELL_MULTIPLE_ZSCORE` -- + feature BTC-únicamente (ver TECH_COLS/`engineer_asset`), ciclo de + rentabilidad de minero (Puell, 2019). Cero llamada de red (a + diferencia de ONCHAIN_ACTIVITY_ROC): la emisión diaria de BTC es un + calendario determinístico conocido (halvings), se deriva 100% de + RAW_CLOSE ya descargado. + +ROLLBACK QUIRÚRGICO V23.6 (Directiva Head Quant -- solo equity_specialist): + V23.5 introdujo `EQUITY_VOL_SAMPLE_WEIGHT_*`/`_compute_equity_vol_ + sample_weights` (punto 7 original de este changelog, ver historial de + versiones): sample_weight por ticker proporcional a volatilidad + realizada, con el objetivo de dejar de castigar a TSLA/META por ser + más ruidosos que SPY/AAPL. Resultado real medido: el modelo aprendió a + perseguir el RUIDO de los outliers volátiles en vez de la señal + direccional -- Directional Accuracy colapsó (NVDA 52.x%->47.3%, META + 48.3%). Diagnóstico: ponderar por volatilidad realizada en un target + de RETORNO (a diferencia del sample_weight por PnL/uniqueness de + `crypto_specialist`, que pondera APUESTAS discretas de Triple Barrier, + no un continuo) amplifica exactamente las muestras con peor relación + señal/ruido del propio universo. + PURGADO por completo de este archivo: `EQUITY_VOL_SAMPLE_WEIGHT_ENABLED`, + `EQUITY_VOL_SAMPLE_WEIGHT_KAPPA`, `_compute_equity_vol_sample_weights`, + y toda la rama de ensamblado de `sample_weight` para + target_mode="regression" en `run_regime_pipeline` -- `equity_specialist` + vuelve a entrenar con gradiente PLANO/UNIFORME (cada día pesa 1.0, + sample_weight=None), bit a bit idéntico a V6/pre-V23.5. Reflejado en + paralelo en `walk_forward_eval.py` y `pnl_backtest.py` (ambos + importaban `tkv5.EQUITY_VOL_SAMPLE_WEIGHT_*` -- ver sus propios + changelogs). `crypto_specialist` (Triple Barrier asimétrica por activo, + Puell Multiple, Fractional Differencing) NO se toca -- ver puntos 6 y 7 + de este changelog, siguen intactos. +""" + +from __future__ import annotations + +import logging +import os + +# V23.2 -- DETERMINISMO REAL: `keras.utils.set_random_seed(SEED)` (más abajo) +# fija numpy/python/TF RNG, pero TF en CPU sigue siendo no-determinístico por +# default (reducciones paralelas en Eigen no son orden-estable entre runs) -- +# esto DEBE fijarse ANTES de `import keras`/`import tensorflow`, cualquier +# import tardío ya no tiene efecto. Confirmado empíricamente: dos corridas +# con `dist_real` IDÉNTICO (mismas etiquetas Triple Barrier, mismo seed=42) +# dieron AccAccionable distinta (BTC 42.2%->46.0%, ETH 51.8%->46.1%) -- la +# única variable no fijada era el orden de reducción flotante intra-CPU. +# Costo: fuerza single-thread en TF (más lento) -- dataset de este script es +# pequeño (miles de filas x <=8 tickers), el trade-off vale la pena para +# poder comparar corridas de forma válida. Override con +# `KODAQUANT_FAST_NONDETERMINISTIC=1` si se necesita velocidad y no +# comparabilidad exacta (p.ej. una corrida final ya calibrada). +os.environ.setdefault("TF_DETERMINISTIC_OPS", "1") +os.environ.setdefault("TF_CUDNN_DETERMINISTIC", "1") +os.environ.setdefault("PYTHONHASHSEED", "42") +_FORCE_DETERMINISTIC_CPU = os.environ.get("KODAQUANT_FAST_NONDETERMINISTIC", "0") != "1" + +import pickle +import sys +import time +from datetime import datetime, timezone +from pathlib import Path +# FIX 2026-08-31 (auditoría rescate) -- `Optional` se usaba en 4 firmas de +# función (_fetch_fear_greed_index/_fetch_onchain_tx_volume_usd/ +# _fetch_binance_funding_history/_fetch_onchain_activity, bloque V24 Alpha +# Cripto) sin estar importado. `from __future__ import annotations` (arriba) +# lo dejaba LATENTE -- las anotaciones quedan como string sin evaluar salvo +# que algo llame typing.get_type_hints()/inspect.signature con eval_str, así +# que nunca explotó en esta corrida -- pero cualquier tooling que sí +# introspeccione (pydantic, algunos linters) lo hubiera roto con NameError +# real. `timedelta` (mismo import) se retira: cero uso real en todo el +# archivo (confirmado con pyflakes). +from typing import Optional + +import matplotlib + +matplotlib.use("Agg") # CRÍTICO: backend no interactivo — CERO plt.show() en todo el módulo. + +import keras +import matplotlib.dates as mdates +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import requests +import yfinance as yf +from keras import layers +from scipy.interpolate import CubicSpline +from sklearn.metrics import confusion_matrix, mean_absolute_error, mean_squared_error +from sklearn.preprocessing import MinMaxScaler, StandardScaler + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (Directiva 2 — fin al Import Hell) ---- +# Este script vive en `ml_engine/`, junto a `data_pipeline.py` y a +# `kodaquant_core.py` (Directiva 1: SINGLE SOURCE OF TRUTH, sin copias +# duplicadas). Sube desde este archivo hasta encontrar la raíz del proyecto +# -- el primer ancestro que contiene TANTO `ml_engine/` como `services/` +# como subdirectorios -- y la inserta en `sys.path[0]`. A partir de ahí, +# `ml_engine` y `services` son paquetes válidos sin importar el cwd desde +# el que se invoque `python ml_engine/train_kodaquant_v5.py`. Reemplaza por +# completo el patrón try/except dual + copias duplicadas de +# `kodaquant_core.py`/`data_pipeline.py` que causaba +# `ModuleNotFoundError`/`ImportError` al invocar desde la raíz del repo. +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + # Fallback determinista: este archivo vive en ml_engine/, por lo que su + # abuelo es la raíz del proyecto por construcción, incluso si `services/` + # todavía no existe en el entorno actual (ej. checkout parcial/CI). + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# V23.5 -- FIX RAÍZ de los avisos "FredClient sin api_key" / titulares +# escasos que caen a Finnhub sin key: `python-dotenv` YA está pineado en +# requirements.txt pero `load_dotenv()` NUNCA se invocaba en ningún archivo +# del proyecto (verificado: cero ocurrencias en train_kodaquant_v5.py, +# data_pipeline.py, market_data.py, quanti_engine.py, prediccion.py) -- +# FRED_API_KEY/FINNHUB_API_KEY se leen de `os.environ` a nivel de módulo +# (línea ~680 acá, línea 223 de data_pipeline.py, línea 331 de +# market_data.py) ANTES de que nada tuviera oportunidad de cargar un +# `.env`. Si tu `.env` vive en la raíz del repo (junto a `ml_engine/` y +# `services/`) con `FRED_API_KEY=...`/`FINNHUB_API_KEY=...`, esto ya lo +# resuelve solo. Si NUNCA generaste esas keys, esto no las inventa -- +# FRED: https://fred.stlouisfed.org/docs/api/api_key.html (gratis, +# instantáneo) -- Finnhub: https://finnhub.io/register (gratis, tier +# suficiente para /company-news y /news?category=crypto). DEBE ejecutarse +# ANTES de `from ml_engine.data_pipeline import ...` (línea de abajo) y +# antes de `_fred_client = FredClient(...)` (más abajo en este archivo) -- +# ambos leen el env var a nivel de módulo, en el orden de import/ejecución. +from dotenv import load_dotenv # noqa: E402 + +load_dotenv(_PROJECT_ROOT / ".env") + +# Requerimiento 1: pipeline NLP de sentimiento de noticias. Import absoluto +# y directo -- ya no depende de que `ml_engine/` esté implícitamente en +# sys.path por ser el directorio del script. +from ml_engine.data_pipeline import get_daily_news_sentiment # noqa: E402 + +# Núcleo compartido train/inferencia -- SINGLE SOURCE OF TRUTH en +# `ml_engine/kodaquant_core.py` (Directiva 1). Import directo y absoluto, +# sin fallback dual: con la raíz del proyecto ya en sys.path, esta ruta +# resuelve siempre, sin importar el cwd de invocación. +from ml_engine.kodaquant_core import ( # noqa: E402 + CacheManager, FredClient, normalize_daily_index, project_macro_frame, +) + +# V28 -- alpha gratuito. SINGLE SOURCE OF TRUTH train/serve (copia idéntica en +# services/free_alpha.py). TECH_COLS hereda V28_COLS desde acá: no puede desincronizarse. +from ml_engine.free_alpha import ( # noqa: E402 + V28_COLS, V28_CRYPTO_COLS, V28_EQUITY_COLS, + build_crypto_flow_features, compute_equity_open_features, +) + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s", +) +logger = logging.getLogger("kodaquant.train_v5") + +# ============================================================ +# CONFIG — PERSISTENCIA DE NIVEL INSTITUCIONAL (Requerimiento 3) +# ============================================================ +BASE_DIR = Path(__file__).resolve().parent if "__file__" in dir() else Path.cwd() +DATA_DIR = BASE_DIR / "data_cache" +MODELS_ROOT = BASE_DIR.parent / "services" / "kodaquant_models" +DATA_DIR.mkdir(parents=True, exist_ok=True) +MODELS_ROOT.mkdir(parents=True, exist_ok=True) + +# --- Enrutamiento de Regímenes (Requerimiento 2) --------------------------- +# V6 (Requerimiento 5): `oversample_factor` por régimen — 8 tickers equity vs. +# 2 tickers cripto es la MISMA razón (~4x) que separa el volumen efectivo de +# ambos especialistas; CRYPTO_OVERSAMPLE_FACTOR busca emparejar la +# representación por-activo entre regímenes, no un número arbitrario. +CRYPTO_OVERSAMPLE_FACTOR = 4.0 + +# ============================================================ +# V22 — TRIPLE BARRIER META-LABELING (crypto_specialist ÚNICAMENTE) +# ============================================================ +# Directiva del Head Quant: el edge direccional puro (DirAcc ±1 al cierre) +# está estadísticamente agotado en crypto_specialist (49-50% constante, +# ver docstring de módulo V6/V19 arriba) tras agotar fuentes gratuitas +# (OHLCV, Funding Rates, Fear&Greed, multi-seed). Cambio de paradigma: en +# vez de predecir la DIRECCIÓN de mañana, se predice si el precio de HOY +# tocará una barrera de toma de ganancia o de stop-loss (ancho ESCALADO a +# la volatilidad realizada del momento, cero parámetro fijo en unidades +# de precio) ANTES de que expire una ventana de `max_holding_days`, o si +# ninguna de las dos se toca dentro de ese horizonte -- Triple Barrier +# Method (López de Prado, "Advances in Financial Machine Learning", cap. +# 3: barrera superior/inferior dinámicas + barrera vertical de tiempo, +# clasificación del primer toque). `equity_specialist` NO se toca -- +# `target_mode="regression"` (ver REGIMES abajo) preserva EXACTAMENTE el +# pipeline DirectionalGaussianNLL ya validado (Sharpe 1.52, operando en +# paper trading vía `services/live_trade.py`) -- ver `build_model`/ +# `build_asset_dataset`/`train_model`, cada uno bifurca en +# `target_mode` con el branch de regresión BIT A BIT idéntico a V6. +TRIPLE_BARRIER_PT_MULT = 2.0 # barrera superior = close_t * exp(+pt_mult * vol_t) +TRIPLE_BARRIER_SL_MULT = 2.0 # barrera inferior = close_t * exp(-sl_mult * vol_t) -- simétrica por defecto +TRIPLE_BARRIER_MAX_HOLDING_DAYS = 10 # barrera vertical -- horizonte máximo de la apuesta (~2 semanas hábiles) +TRIPLE_BARRIER_VOL_LOOKBACK = 20 # ventana de vol realizada que escala pt/sl -- mismo rol que VOL_LOOKBACK_DAYS en live_trade.py/pnl_backtest.py +TRIPLE_BARRIER_MIN_VOL = 1e-6 # floor defensivo -- evita barreras degeneradas si vol_t≈0 + +# Orden FIJO de clases -- índice 1 (TIMEOUT) es intencionalmente el centro: +# permite tratar "SL" y "TP" como los dos extremos direccionales de un +# espectro, análogo al signo ±1 del régimen de regresión, con 0=TIMEOUT +# como la clase de "sin convicción" (meta-labeling: no vale la pena operar). +TB_CLASS_NAMES = ["SL", "TIMEOUT", "TP"] +TB_LABEL_TO_CLASS_IDX = {-1: 0, 0: 1, 1: 2} +TB_CLASS_IDX_TO_LABEL = {v: k for k, v in TB_LABEL_TO_CLASS_IDX.items()} +TB_TIMEOUT_CLASS_IDX = TB_LABEL_TO_CLASS_IDX[0] # = 1 + +# CategoricalFocalCrossentropy (Lin et al. 2017, "Focal Loss for Dense +# Object Detection") -- built-in Keras 3 (`keras.losses. +# CategoricalFocalCrossentropy`, validado contra la doc oficial antes de +# usarlo acá). `gamma` reduce el peso de gradiente de ejemplos "fáciles" +# (softmax ya confiado en la clase correcta) y concentra el aprendizaje en +# los difíciles; `alpha` (lista por-clase, ver `run_regime_pipeline`) hace +# el trabajo de balanceo de clases -- TIMEOUT casi siempre domina en +# volumen frente a SL/TP. Directiva 3 (Risk-Adjusted Loss) se implementa +# APARTE, vía `sample_weight` en `train_model` (magnitud del retorno +# realmente logrado por cada apuesta, ver `build_asset_dataset`) -- +# separación deliberada de responsabilidades: `alpha` corrige DESBALANCE +# DE CLASES, `sample_weight` corrige IMPORTANCIA POR PnL. Combinarlos en +# un único factor sería estadísticamente correcto también, pero mezclaría +# dos fuentes de sesgo distintas en un solo número sin poder auditar cada +# una por separado. +TRIPLE_BARRIER_FOCAL_GAMMA = 2.0 +TRIPLE_BARRIER_LABEL_SMOOTHING = 0.05 + +# ============================================================ +# V23 — CALIBRACIÓN DINÁMICA DE BARRERAS (crypto_specialist) +# ============================================================ +# DIAGNÓSTICO V22: Acc=33.2% (BTC) / 38.7% (ETH) en un problema de 3 clases +# ES adivinar al azar (33.3%) -- confirma que pt_mult=sl_mult=2.0 FIJO +# (mismo valor, literatura genérica, jamás calibrado contra la distribución +# real de clases) produce, o (a) TIMEOUT dominando >80% de las muestras +# (barreras demasiado anchas para vol_lookback=20/max_holding=10 en cripto) +# o (b) barreras demasiado ANGOSTAS relativo al ruido intradía-a-diario no +# capturado por cierres (ver docstring de compute_triple_barrier_labels) -- +# en cualquiera de los dos extremos, la CategoricalFocalCrossentropy con +# `alpha` de rebalanceo extremo empuja al softmax hacia una salida ~uniforme +# (ver quantmemo.com/concepts/triple-barrier-labeling: "Barriers too tight +# relative to noise produce near-random labels"). Fix: grid search 100% +# gratuito (cero API extra, solo los mismos closes ya descargados) que +# calibra pt_mult/sl_mult ASIMÉTRICOS (paperswithbacktest.com/course/ +# triple-barrier-method: "Setting asymmetric barriers... is common") + +# vol_lookback/max_holding_days, ÚNICAMENTE sobre el split de TRAIN de cada +# ticker cripto (cero fuga hacia test -- ver `calibrate_crypto_triple_barrier`), +# maximizando el balance de clases accionables (SL/TP) sin dejar que +# TIMEOUT degenere el problema a una clase única. +CRYPTO_CALIBRATE_BARRIERS = True +CRYPTO_BARRIER_PT_SL_GRID = (1.0, 1.25, 1.5, 1.75, 2.0, 2.5) # asimétrico: pt != sl permitido +CRYPTO_BARRIER_VOL_LOOKBACK_GRID = (10, 15, 20, 25) +CRYPTO_BARRIER_MAX_HOLDING_GRID = (5, 7, 10, 14) +CRYPTO_BARRIER_TIMEOUT_FRAC_BAND = (0.15, 0.65) # fuera de esta banda, combo descalificado (degenerado) + + +def _calibrate_single_asset_triple_barrier(ticker: str, train_slice: pd.DataFrame) -> dict: + """ + V23.5 -- Grid search de barreras dinámicas para UN ticker, TRAIN-ONLY + (cero fuga hacia test). Mismas 3 etapas que la calibración V23/V23.1-2 + (pt_mult x sl_mult asimétrico -> vol_lookback x max_holding_days -> + refinamiento fino de pt/sl), pero el score ya NO es maximin sobre + varios tickers -- es `min(P(SL), P(TP))` DEL PROPIO TICKER. Extraída + como función de un solo activo para que `calibrate_crypto_triple_barrier` + la corra independiente por ticker (ver Directiva 1, V23.5): BTC ya no + comparte barreras con ETH, así que deja de heredar un compromiso + optimizado para el activo ajeno. + """ + def _score(pt_mult: float, sl_mult: float, vol_lookback: int, max_holding_days: int) -> tuple[float, dict]: + tb = compute_triple_barrier_labels( + train_slice, pt_mult=pt_mult, sl_mult=sl_mult, + max_holding_days=max_holding_days, vol_lookback=vol_lookback, + ) + labels = tb["TB_LABEL"].dropna().to_numpy() + if labels.size == 0: + return -np.inf, {} + sl_n = int((labels == -1).sum()) + to_n = int((labels == 0).sum()) + tp_n = int((labels == 1).sum()) + total = labels.size + p_sl, p_to, p_tp = sl_n / total, to_n / total, tp_n / total + lo, hi = CRYPTO_BARRIER_TIMEOUT_FRAC_BAND + stats = {"p_sl": p_sl, "p_timeout": p_to, "p_tp": p_tp, "n": total} + if not (lo <= p_to <= hi): + return -np.inf, stats + return min(p_sl, p_tp), stats + + logger.info(" [Calibración V23.5] %s -- Etapa 1/3 -- grid pt_mult x sl_mult (asimétrico)...", ticker) + best_score, best_pt, best_sl, best_stats = -np.inf, TRIPLE_BARRIER_PT_MULT, TRIPLE_BARRIER_SL_MULT, {} + for pt in CRYPTO_BARRIER_PT_SL_GRID: + for sl in CRYPTO_BARRIER_PT_SL_GRID: + score, stats = _score(pt, sl, TRIPLE_BARRIER_VOL_LOOKBACK, TRIPLE_BARRIER_MAX_HOLDING_DAYS) + if score > best_score: + best_score, best_pt, best_sl, best_stats = score, pt, sl, stats + logger.info(" [Calibración V23.5] %s -- Mejor pt_mult=%.2f sl_mult=%.2f -> %s (score=%.4f)", + ticker, best_pt, best_sl, best_stats, best_score) + + logger.info(" [Calibración V23.5] %s -- Etapa 2/3 -- grid vol_lookback x max_holding_days...", ticker) + best_vl, best_mh = TRIPLE_BARRIER_VOL_LOOKBACK, TRIPLE_BARRIER_MAX_HOLDING_DAYS + for vl in CRYPTO_BARRIER_VOL_LOOKBACK_GRID: + for mh in CRYPTO_BARRIER_MAX_HOLDING_GRID: + score, stats = _score(best_pt, best_sl, vl, mh) + if score > best_score: + best_score, best_vl, best_mh, best_stats = score, vl, mh, stats + logger.info(" [Calibración V23.5] %s -- Etapa 2/3 FIN pt_mult=%.2f sl_mult=%.2f vol_lookback=%d " + "max_holding_days=%d -> %s (score=%.4f)", + ticker, best_pt, best_sl, best_vl, best_mh, best_stats, best_score) + + logger.info(" [Calibración V23.5] %s -- Etapa 3/3 -- refinamiento fino pt_mult x sl_mult (paso 0.1)...", ticker) + fine_grid = [round(best_pt + d, 2) for d in (-0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3) if best_pt + d > 0] + fine_grid_sl = [round(best_sl + d, 2) for d in (-0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3) if best_sl + d > 0] + for pt in fine_grid: + for sl in fine_grid_sl: + score, stats = _score(pt, sl, best_vl, best_mh) + if score > best_score: + best_score, best_pt, best_sl, best_stats = score, pt, sl, stats + logger.info(" [Calibración V23.5] %s -- FINAL pt_mult=%.2f sl_mult=%.2f vol_lookback=%d " + "max_holding_days=%d -> %s (score=%.4f)", + ticker, best_pt, best_sl, best_vl, best_mh, best_stats, best_score) + + if best_score == -np.inf: + logger.warning(" [Calibración V23.5] %s -- NINGÚN combo cumplió la banda de TIMEOUT -- " + "se conservan los defaults de literatura (pt=sl=2.0, vl=20, mh=10).", ticker) + return { + "pt_mult": TRIPLE_BARRIER_PT_MULT, "sl_mult": TRIPLE_BARRIER_SL_MULT, + "max_holding_days": TRIPLE_BARRIER_MAX_HOLDING_DAYS, "vol_lookback": TRIPLE_BARRIER_VOL_LOOKBACK, + } + return {"pt_mult": best_pt, "sl_mult": best_sl, "max_holding_days": best_mh, "vol_lookback": best_vl} + + +def calibrate_crypto_triple_barrier(df_assets: dict[str, pd.DataFrame], tickers: list[str], + train_ratio: float | None = None) -> dict[str, dict]: + """ + V23.5 (Directiva 1, Head Quant) -- DESACOPLADA por activo: cada ticker + cripto corre su propio grid search TRAIN-ONLY vía + `_calibrate_single_asset_triple_barrier`, maximizando SU PROPIO + `min(P(SL), P(TP))`, sin compromiso con ningún otro ticker del régimen. + + V23/V23.1 corrían esto pooled/maximin sobre TODOS los tickers cripto a + la vez porque `tb_params` era un único dict compartido en producción + (mismo esquema que `quanti_engine.py` esperaba). Diagnóstico de esta + sesión: eso significa que ETH (ya en 54.5% AccAccionable) seguía + cediendo parte de su óptimo para no dejar a BTC en un combo degenerado + -- BTC en 47.9% confirma que el compromiso pooled TODAVÍA no le alcanza + a BTC, y ETH no tiene por qué seguir pagando ese costo. + + ROMPE DE ESQUEMA (documentado en el docstring de módulo, V23.5 punto 6): + devuelve `{ticker: {pt_mult, sl_mult, vol_lookback, max_holding_days}}` + en vez de un único dict plano. `run_regime_pipeline`/`scalers_dict.pkl` + ya están actualizados acá para el nuevo esquema -- `quanti_engine.py` + (fuera de este archivo) todavía NO, y debe indexar `tb_params[ticker]` + en inferencia o quedará leyendo un dict con llaves de ticker donde + esperaba `pt_mult` directo (KeyError inmediato y visible -- no un + silent-fail, pero sí un breaking change de producción real). + """ + train_ratio = TRAIN_RATIO if train_ratio is None else train_ratio # TRAIN_RATIO se define más abajo en el módulo -- default NO puede resolverse en la firma + tb_params_by_ticker: dict[str, dict] = {} + for t in tickers: + df = df_assets[t] + split_idx = int(len(df) * train_ratio) + train_slice = df.iloc[:split_idx] + tb_params_by_ticker[t] = _calibrate_single_asset_triple_barrier(t, train_slice) + return tb_params_by_ticker + + +# ============================================================ +# V23.5 SAMPLE WEIGHTING DINÁMICO POR VOLATILIDAD (equity_specialist) +# -- ROLLBACK QUIRÚRGICO EN V23.6, ver changelog del módulo -- +# ============================================================ +# `EQUITY_VOL_SAMPLE_WEIGHT_ENABLED`/`EQUITY_VOL_SAMPLE_WEIGHT_KAPPA`/ +# `_compute_equity_vol_sample_weights` vivían acá. Purgados por completo: +# ponderar por volatilidad realizada le enseñó al modelo a perseguir ruido +# de outliers volátiles en vez de señal direccional (DirAcc NVDA +# 52.x%->47.3%, META 48.3%). `equity_specialist` ya NO calcula ni pasa +# ningún sample_weight -- gradiente plano/uniforme, bit a bit idéntico a +# V6/pre-V23.5. `crypto_specialist` no se ve afectado por este rollback: +# su propio sample_weight (magnitud de PnL + uniqueness, ver +# `build_asset_dataset`/Directiva 3 más abajo) es un mecanismo +# completamente distinto y sigue intacto. + + +def _average_uniqueness(entry_idx: np.ndarray, bars_to_exit: np.ndarray, n: int) -> np.ndarray: + """ + V23 -- Uniqueness promedio (López de Prado, AFML cap. 4) para etiquetas + Triple Barrier CON SOLAPAMIENTO: cada apuesta `s` ocupa el tramo + `[s, s+bars_to_exit[s]]`; con `max_holding_days` >= 5-14 y entradas + diarias consecutivas, tramos vecinos se solapan masivamente -- el + gradiente ve la misma "sorpresa" de mercado una y otra vez, contada + como si fueran muestras i.i.d. independientes, lo cual puede degradar + la señal efectiva de entrenamiento tanto como una barrera mal calibrada + (ver quantmemo.com/concepts/triple-barrier-labeling, "Class imbalance... + weight samples by their uniqueness"). Concurrencia `c[t]` = número de + tramos activos en la barra `t`; uniqueness de la muestra `s` = promedio + de `1/c[t]` sobre su propio tramo -- una apuesta que solapa con muchas + otras pesa menos, una época de mercado "propia" (poco solapamiento) + pesa más. Se multiplica (no reemplaza) al peso de magnitud/PnL ya + existente (Directiva 3) en `build_asset_dataset`. + """ + concurrency = np.zeros(n, dtype=np.float64) + exit_idx = np.minimum(entry_idx + bars_to_exit.astype(np.int64), n - 1) + for s, e in zip(entry_idx, exit_idx): + concurrency[s:e + 1] += 1.0 + concurrency = np.maximum(concurrency, 1.0) + uniqueness = np.array([float(np.mean(1.0 / concurrency[s:e + 1])) for s, e in zip(entry_idx, exit_idx)]) + return uniqueness + +REGIMES: dict[str, dict] = { + "equity_specialist": { + "tickers": ["AAPL", "MSFT", "NVDA", "TSLA", "GOOGL", "AMZN", "META", "SPY"], + "oversample_factor": 1.0, # 8 tickers, volumen ya suficiente -> no-op exacto (idéntico a V5) + "target_mode": "regression", # V22 — dataset/arquitectura intactos. V23.5 había añadido sample_weight por volatilidad; ROLLBACK en V23.6 (ver changelog del módulo) -- vuelve a ser BIT A BIT idéntico a V6/pre-V23.5, sample_weight=None. Sharpe 1.52 mide este mismo pipeline plano. + }, + "crypto_specialist": { + # V19: vuelta a 2 tickers a pedido explícito -- BTC-USD/ETH-USD + # solos midieron 46.8%/48.1% en la corrida de 5 activos (V18, + # consistente con las dos mediciones previas de solo-2: 47-50%). + # Ampliar a 5 NO los movió a ellos -- lo que cambió fue el + # agregado (arrastrado por XRP/BCH, más nuevos y volátiles). + # Volver a 2 no resuelve por sí solo que BTC/ETH crucen 50%: el + # número individual de cada uno sigue siendo el mismo problema de + # fondo, y con n=8 el IC 95% vuelve a ser demasiado ancho para + # distinguir "sin edge" de "no hay muestra suficiente" (ver + # walk_forward_eval.py). Documentado, no oculto. + "tickers": ["BTC-USD", "ETH-USD"], + # V27 -- lever no probada hasta hoy: BTC-USD tiene histórico en + # yfinance desde 2014 (~12 años), PERIOD="10y" global le recorta + # ~2 años sin que nadie lo haya medido. "max" = todo lo disponible + # por ticker (ETH, con historia desde 2017, no gana nada extra -- + # esto es específicamente una apuesta por BTC). Override SOLO acá, + # equity_specialist sigue usando el PERIOD global sin tocar. + "period": "max", + "oversample_factor": CRYPTO_OVERSAMPLE_FACTOR, + # V22 — CAMBIO DE PARADIGMA (Directiva Head Quant): DirAcc ±1 al + # cierre está estadísticamente agotado acá (49-50% constante, ver + # docstring de módulo V6). Se reemplaza por Triple Barrier Method + # (López de Prado) -- clasificación 3-way (SL/TIMEOUT/TP) en vez + # de regresión de retorno, ver `compute_triple_barrier_labels`, + # `build_model` y `build_asset_dataset`. `equity_specialist` + # arriba NO se toca -- target_mode="regression" es el default y + # preserva el pipeline V5/V6 bit a bit. + "target_mode": "triple_barrier", + "pt_mult": TRIPLE_BARRIER_PT_MULT, + "sl_mult": TRIPLE_BARRIER_SL_MULT, + "max_holding_days": TRIPLE_BARRIER_MAX_HOLDING_DAYS, + "vol_lookback": TRIPLE_BARRIER_VOL_LOOKBACK, + # V23.4 -- log de la corrida V23.3 mostró "Restoring model weights + # from the end of the best epoch: 91" con EPOCHS=100: el modelo + # TODAVÍA estaba mejorando cerca del techo artificial del cap, no + # convergido/estancado (si estuviera estancado, `patience=12` + # habría cortado bien antes de la época 88). Se sube el presupuesto + # SOLO para cripto -- CERO cambio de arquitectura/features/seed, + # `EarlyStopping(patience=12)` sigue siendo el que decide cuándo + # parar de verdad; esto solo le saca el techo artificial. + "epochs": 180, + }, +} +MACRO_TICKERS = ["^GSPC", "^TNX", "^VIX", "GC=F", "DX-Y.NYB"] # SPX, UST10Y, VIX, Oro, Dollar Index + +PERIOD = "10y" +LOOKBACK = 60 +TRAIN_RATIO = 0.8 +SEED = 42 +ASSET_EMBED_DIM = 8 + +SENTIMENT_LOOKBACK = 20 # ventana de la correlación móvil activo<->macro (V4) +SENTIMENT_MACRO_PROXY = "^VIX" # factor macro de referencia; fallback: MACRO_TICKERS[0] + +# TECH_COLS — ÚNICA fuente de verdad de qué técnicos entran al tensor. +# V6 — MIGRACIÓN A ESTACIONARIEDAD ESTRICTA (Reinicio Estructural): el input +# "PRICE" (nivel absoluto) se elimina del tensor y se reemplaza por +# LOG_RETURN_1D (ver `engineer_asset`) — ese es el cambio real que resuelve +# la ceguera ante ATH, no un parche de post-procesamiento. En paralelo, los +# 4 TECH_COLS que dependían del NIVEL de precio (no auto-acotados: ver +# auditoría SOFT_CLIP_MARGIN en quanti_engine.py) se re-expresan como razones +# adimensionales, invariantes a escala: +# EMA_20 -> EMA20_DEV_PCT = (Close - EMA20) / EMA20 +# MACD -> MACD_PCT = MACD / Close +# MACD_SIGNAL -> MACD_SIGNAL_PCT = MACD_SIGNAL / Close +# ATR_14 -> ATR_PCT = ATR_14 / Close ("ATRP") +# OBV -> OBV_ROC_20 = OBV.pct_change(20), clip [-3, 3] +# (OBV es SUMA ACUMULADA sin techo ni mean-reversion propia — ni +# siquiera "retorno de OBV" la vuelve comparable entre activos, porque +# su escala depende del volumen histórico TOTAL negociado; el fix real +# es una tasa de cambio ACOTADA, no una re-escala de la magnitud cruda) +# RSI_14 / BB_WIDTH_20 (ya es el ratio 2σ/μ, adimensional por construcción, +# PESE al comentario previo en quanti_engine.py que lo trataba como "atado +# al nivel de precio") / ADX_14 / STOCH_K_14 / SENTIMENT_SCORE / +# NEWS_SENTIMENT_SCORE quedan IDÉNTICOS — son osciladores/ratios ya acotados +# que nunca extrapolan fuera de [0,1]/[-1,1] sin importar cuántos máximos +# históricos haga el activo. +OBV_ROC_LOOKBACK_DAYS = 20 # ventana del rate-of-change — DEBE calzar con OBV_ROC_LOOKBACK_DAYS en quanti_engine.py +OBV_ROC_CLIP = 3.0 # ±300% — techo defensivo ante denominadores (OBV_{t-20}) cercanos a cero + +# V24 — ALPHA CRIPTO (Directiva Head Quant, ver bloque de funciones antes de +# `engineer_asset`): FUNDING_RATE_ZSCORE/ONCHAIN_ACTIVITY_ROC/FRAC_DIFF_LOG_CLOSE +# neutras (0.0) para equity_specialist -- MISMO patrón que FEAR_GREED_INDEX +# arriba, cero impacto real de información en ese régimen. V23.5 agrega +# PUELL_MULTIPLE_ZSCORE con el mismo patrón, pero BTC-únicamente incluso +# DENTRO de crypto_specialist -- 0.0 neutro también para ETH-USD (ver +# docstring del bloque de constantes `BTC_HALVING_SCHEDULE`). +TECH_COLS = [ + "RSI_14", "EMA20_DEV_PCT", "MACD_PCT", "MACD_SIGNAL_PCT", "SENTIMENT_SCORE", + "ATR_PCT", "BB_WIDTH_20", "OBV_ROC_20", "ADX_14", "STOCH_K_14", + "NEWS_SENTIMENT_SCORE", "FEAR_GREED_INDEX", + "FUNDING_RATE_ZSCORE", "ONCHAIN_ACTIVITY_ROC", "FRAC_DIFF_LOG_CLOSE", + "PUELL_MULTIPLE_ZSCORE", # V23.5 (Directiva 3) -- BTC únicamente, 0.0 neutro para ETH/equity + "PARKINSON_VOL_ZSCORE", # AUDITORÍA RESCATE 2026-08 -- AMBOS regímenes, proxy libre de IV (ver engineer_asset) + "VOL_OF_VOL_ZSCORE", # AUDITORÍA RESCATE 2026-08 -- cripto únicamente, 0.0 neutro en equity + "FUNDING_RATE_MOMENTUM_ZSCORE", # V26 (Directiva Head Quant) -- velocidad del crowding, cripto únicamente + "AMIHUD_ILLIQUIDITY_ZSCORE", # V26 (Directiva Head Quant) -- liquidez, 100% OHLCV, cripto únicamente + "GARMAN_KLASS_VOL_ZSCORE", # V27 -- microestructura OHLC, AMBOS regímenes + "FIB_GAP_Z_20", "FIB_GAP_Z_50", # V27 -- gap firmado a Fibonacci sobre swings rolling, AMBOS regímenes + "OFI_PROXY_ZSCORE", # V27 -- order flow imbalance vía CLV*volumen, AMBOS regímenes + "RETURN_ENTROPY_ZSCORE", # V27 -- entropía de Shannon normalizada, AMBOS regímenes +] + list(V28_COLS) # V28 -- 4 equity + 4 cripto (0.0 neutro en el régimen opuesto), orden = free_alpha.V28_COLS +# V28 -- 25 base + 8 = 33 TECH_COLS -> N_FEATURES = 1 + 33 + 5 = 39 (38 si el gate quita NEWS). +if 1 + len(TECH_COLS) + len(MACRO_TICKERS) != 39: + raise ImportError( + f"[V28] N_FEATURES={1 + len(TECH_COLS) + len(MACRO_TICKERS)} != 39 esperado " + "-- TECH_COLS/V28_COLS/MACRO_TICKERS desalineados.") +# V27 -- NEWS_SENTIMENT_SCORE puede ser REMOVIDA in-place por +# `run_regime_pipeline` si no hay backend de sentimiento (ver +# `_apply_news_sentiment_gate`). `N_FEATURES` se recalcula ahí mismo. +N_FEATURES = 1 + len(TECH_COLS) + len(MACRO_TICKERS) # LOG_RETURN_1D + técnicos + macro -- SIEMPRE derivado de +# len(TECH_COLS)/len(MACRO_TICKERS), NUNCA hardcodear este número en un comentario/docstring en otro archivo +# (esa es exactamente la causa raíz auditada en services/quanti_engine.py -- ver notas de la auditoría 2026-08). + + +def _apply_news_sentiment_gate() -> bool: + """Excluye NEWS_SENTIMENT_SCORE del tensor si no hay backend de sentimiento. + + Se ejecuta UNA vez, ANTES de construir cualquier dataset. Muta TECH_COLS + in-place (no rebind: `engineer_asset`/`build_asset_dataset` leen el + global en tiempo de llamada) y recalcula N_FEATURES. La lista resultante + viaja en scalers_dict.pkl['tech_cols'] -> quanti_engine.py la adopta + desde ahí, nunca por probe propio: un probe en inferencia podría dar un + resultado DISTINTO al del entrenamiento y desplazar cada columna dentro + de feature_scaler.transform() en silencio. + """ + global N_FEATURES + if os.getenv("KODAQUANT_FORCE_NEWS_SENTIMENT", "").strip() == "1": + return True + try: + from ml_engine.data_pipeline import news_sentiment_available + ok = bool(news_sentiment_available()) + except Exception as exc: # noqa: BLE001 + logger.warning("[NEWS GATE] probe falló (%s: %s) -> se asume NO disponible.", + type(exc).__name__, exc) + ok = False + if ok: + logger.info("[NEWS GATE] backend de sentimiento ACTIVO -> NEWS_SENTIMENT_SCORE incluida.") + return True + if "NEWS_SENTIMENT_SCORE" in TECH_COLS: + TECH_COLS.remove("NEWS_SENTIMENT_SCORE") + N_FEATURES = 1 + len(TECH_COLS) + len(MACRO_TICKERS) + logger.warning( + "[NEWS GATE] sin backend de sentimiento -> NEWS_SENTIMENT_SCORE EXCLUIDA " + "del tensor (N_FEATURES=%d). Inyectar 0.0 constante ajustaría el " + "feature_scaler sobre una constante y entrenaría un slot muerto. " + "Los artefactos de esta corrida NO son intercambiables con los de " + "una corrida CON sentimiento.", N_FEATURES) + return False + + +def get_tech_cols(regime_name: str) -> list[str]: + """Devuelve TECH_COLS para el régimen dado. + + AUDITORÍA RESCATE 2026-08 -- restaurado tras `AttributeError: + module 'ml_engine.train_kodaquant_v5' has no attribute 'get_tech_cols'` + real en `walk_forward_eval.py` (línea ~220) y `pnl_backtest.py` (línea + ~104) -- AMBOS son callers reales de esta función, ninguno la tenía + definida en este módulo. `TECH_COLS` es hoy una lista GLOBAL compartida + por los dos regímenes -- las columnas cripto-únicamente + (`FUNDING_RATE_ZSCORE`, `ONCHAIN_ACTIVITY_ROC`, `FRAC_DIFF_LOG_CLOSE`, + `PUELL_MULTIPLE_ZSCORE`) ya son 0.0 neutro para equity DENTRO de esa + misma lista (ver `engineer_asset`), así que `regime_name` se acepta + solo por compatibilidad de firma con ambos callers y NO cambia el + resultado -- devolver un subconjunto distinto por régimen rompería + `N_FEATURES`/la forma del tensor de entrada frente al modelo ya + entrenado de cada régimen (equity_specialist incluido). + """ + return list(TECH_COLS) + + +def get_n_features(regime_name: str) -> int: + """Devuelve N_FEATURES para el régimen dado. + + AUDITORÍA RESCATE 2026-08 -- mismo bug/mismo fix que `get_tech_cols` + (ver docstring ahí): `AttributeError: ... has no attribute + 'get_n_features'` real en `walk_forward_eval.py` (línea ~339) y + `pnl_backtest.py` (línea ~210), confirmado en corrida real del usuario + -- función nunca definida en este módulo. `N_FEATURES` es un escalar + GLOBAL (`1 + len(TECH_COLS) + len(MACRO_TICKERS)`) idéntico para los + dos regímenes -- `regime_name` se acepta solo por compatibilidad de + firma, no cambia el resultado. + """ + return N_FEATURES + +# --- Hiperparámetros de entrenamiento (idénticos a V4 — invarianza matemática) --- +BATCH_SIZE = 64 +EPOCHS = 100 +VALIDATION_SPLIT = 0.1 +HUBER_DELTA = 1.0 + +GAMMA_INITIAL = 0.0 +GAMMA_MAX = 1.5 +GAMMA_WARMUP_EPOCHS = 35 +GAMMA_SCHEDULE = "sigmoid" +GAMMA_SIGMOID_STEEPNESS = 6.0 # curva sigmoide más suave -> transición de gamma menos abrupta + +LR_INITIAL = 1e-3 +GRAD_CLIPNORM = 1.0 + +# --- V10 — Topología por régimen (Arquitectura Híbrida Asimétrica) -------- +# Sustituye a KODAQUANT_EXPERIMENTAL_MODE (V9.2, flag de entorno manual): +# ya no existe un perfil "experimental" aislado que dependa de una var de +# entorno -- `build_model` recibe `regime_name` y dicta su propia topología +# consultando este diccionario, DETERMINISTA tanto en corrida local como en +# el cron de CI/CD (entrenamiento_semanal.yml), sin ramas condicionales +# externas ni sufijos `_experimental` en disco. Perfiles validados +# empíricamente en pruebas de estrés (backtest comparativo): +# equity_specialist (8 tickers, volumen alto) -> topología de mayor +# capacidad: 52.8% de asertividad direccional. BiLSTM 64->128 duplica +# el ancho de salida Bidirectional (128->256); MHA_HEADS 4->8 con +# key_dim SIN cambiar duplica en paralelo la dimensión total de +# atención -- mismo factor de escala, arquitectura dimensionalmente +# coherente. Dropout/L2 NO escalan 1:1 con la capacidad (saturarían +# dropout cerca de 1.0): +33% en dropout (0.45->0.60) y 3x en L2 +# (1e-5->3e-5) compensan ~4x de parámetros sin apagar la red. Incluye +# el bloque residual profundo adicional Dense(64)+skip antes de la +# cabeza final (ver `build_model`). +# crypto_specialist (2 tickers, volumen bajo) -> topología ágil y +# conservadora: 51.3% constante -- el perfil de mayor capacidad +# SOBREAJUSTÓ en cripto (colapso a 49.9%) por exceso de parámetros +# frente a solo 2 activos. CERO bloque residual extra. +REGIME_ARCHITECTURE: dict[str, dict] = { + "equity_specialist": { + "lstm_units": 128, + "attention_units": 64, + "mha_heads": 8, + "mha_key_dim": 32, + "dropout_rate": 0.60, + "dense_l2_reg": 3e-5, + "extra_residual_block": True, + "tcn_filters": 64, # V15 — rama TCN paralela, ver build_model + # V27 — GLU de entrada: proyección compuerta por feature ANTES de + # BiLSTM/TCN. Con 29 features (6 nuevas de V27) la red ya no puede + # asumir que todo slot aporta; la compuerta sigmoide aprende a + # anular los irrelevantes por activo en vez de diluirlos en el L2. + "glu_units": 32, + }, + "crypto_specialist": { + # V28 (Directiva Head Quant) -- reducción de capacidad, NO agregado + # de señal. Motivo: overfitting confirmado EN VIVO en la corrida sin + # fuga (2026-09-01): train actionable_accuracy 50%->74% en 25 + # épocas mientras val se mantuvo plano en 41-50%, y el test final + # terminó por debajo del baseline trivial en ambos activos (BTC + # 37.1% vs 43.7%, ETH 39.9% vs 45.1%) pese a que `dist_pred` NO + # colapsó a una clase (proporciones cercanas a `dist_real` en las + # 3 categorías) -- descarta alpha mal calibrado, apunta a un + # modelo con demasiada capacidad relativa al dato (145K params + # para ~4400 ventanas crudas antes de oversampling). Bajado a + # ~1/4 de params (lstm_units 64->32, tcn_filters 32->16, + # attention/mha 32->16, heads 4->2), dropout 0.45->0.55, L2 + # 1e-5->5e-5. CAMBIO AISLADO a propósito -- TECH_COLS/features sin + # tocar, para poder atribuir cualquier diferencia de resultado + # específicamente a la capacidad, no a una mezcla de variables. + # HONESTIDAD: dado el patrón de 4 mediciones independientes previas + # (V19 y anteriores: 46.8-50%; esta corrida sin fuga: 37-40%), + # esto puede no ser suficiente -- el techo real puede ser de datos + # (edge inexistente a esta granularidad/universo), no de capacidad. + "lstm_units": 32, + "attention_units": 16, + "mha_heads": 2, + "mha_key_dim": 16, + "dropout_rate": 0.55, + "dense_l2_reg": 5e-5, + "extra_residual_block": False, + "tcn_filters": 16, # V15 — rama TCN paralela, ver build_model + # V27 — CUELLO DE BOTELLA, no capacidad extra: 29 -> 16. Coherente + # con el hallazgo V28 (train 74% / val 41% = exceso de capacidad + # relativa al dato). Subir este número acá revierte ese fix. + "glu_units": 16, + }, +} + +# V15 — Directiva 4 (evolución matemática direccional). Rama TCN (Temporal +# Convolutional Network, Bai/Kolter/Koltun 2018) PARALELA a la rama +# BiLSTM+MultiHeadAttention+BahdanauAttention existente (que YA logra +# 52.8%/51.3% de DirAcc validado, ver docstring de `REGIME_ARCHITECTURE` +# arriba) -- no la reemplaza, la complementa: convoluciones causales +# dilatadas capturan patrones locales/multi-escala de forma NO +# recurrente (sin el sesgo de recencia del último estado oculto de un +# LSTM), robustas a ruido de alta frecuencia por el propio ensanchamiento +# del campo receptivo con la dilatación. Fusionada por concatenación con +# el contexto de Bahdanau antes de `asset_embed` -- aditiva y reversible: +# `KODAQUANT_ENABLE_TCN=0` colapsa el grafo a la topología V10 anterior, +# bit a bit, para poder comparar A/B contra la arquitectura ya validada +# antes de promoverla a producción. +ENABLE_TCN_BRANCH = os.getenv("KODAQUANT_ENABLE_TCN", "1").strip().lower() not in ("0", "false", "no") +TCN_KERNEL_SIZE = 3 +TCN_DILATIONS = (1, 2, 4, 8) # campo receptivo ~ kernel*sum(dilations) > LOOKBACK=60 con margen + +# V5.1: CosineDecayRestarts reemplaza a ReduceLROnPlateau — un schedule +# recalcula el LR por *step*, así que combinarlo con un callback que también +# reescribe optimizer.learning_rate por *época* produce ajustes en conflicto +# (el schedule pisa silenciosamente la reducción del callback). El schedule +# ya provee escape agresivo de mínimos locales por diseño (restart a LR +# pico cada ciclo); EarlyStopping sobre val_directional_accuracy_metric +# sigue siendo el mecanismo real que evita el colapso "cobarde" (V4) y se +# mantiene sin cambios. +COSINE_RESTART_EPOCH_PERIOD = 6 # ciclo inicial más corto -> primer restart más temprano -> más exploración +COSINE_T_MUL = 1.6 # crecimiento más moderado -> más restarts totales durante el entrenamiento +COSINE_M_MUL = 0.94 # decaimiento de pico más lento -> LR de restart se sostiene alto más tiempo +COSINE_ALPHA = 1e-5 # piso de LR (fracción de LR_INITIAL) — evita colapso a 0 +# AUDITORÍA RESCATE 2026-08 — patience=12/start_epoch=15 cortaba el +# entrenamiento ANTES de que TCN+BiLSTM+MHA convergiera de verdad bajo +# --epochs-per-fold=30 (default de iteración de walk_forward_eval.py/ +# pnl_backtest.py, ver docstrings de esos módulos) -- subido al piso +# mínimo pedido (15-20) para dar margen real de convergencia tanto en el +# full-retrain (EPOCHS=100/180) como en cualquier fold recortado. +EARLY_STOPPING_PATIENCE = 18 +EARLY_STOPPING_START_EPOCH = 20 + +VARIANCE_LAMBDA = 0.15 +VARIANCE_CAP = 4.0 + +# --- V6 — Anti-colapso de varianza en DirectionalGaussianNLL (ver docstring +# de módulo/clase). Con GAUSSIAN_NLL_BETA=0.0, LOG_VAR_L2_LAMBDA=0.0 y +# LOG_VAR_BARRIER_LAMBDA=0.0 la pérdida es matemáticamente IDÉNTICA a la +# NLL Gaussiana V5 original (invarianza sobre equity_specialist si algún día +# se quisiera desactivar por régimen). +GAUSSIAN_NLL_BETA = 0.5 # β-NLL (Seitzer et al. 2022) — β≈0.5 recomendado por los autores como punto de partida +LOG_VAR_MIN = -6.0 # var floor numérico ≈ exp(-6) ≈ 0.0025 — evita división por var≈0 en la NLL +LOG_VAR_MAX = 3.0 # var techo numérico ≈ exp(3) ≈ 20.1 — evita exp(log_var) -> inf/NaN en la NLL +LOG_VAR_L2_LAMBDA = 1e-3 # ridge suave hacia log_var≈0 (var≈1) sobre TODO el rango +LOG_VAR_BARRIER_LAMBDA = 5e-3 # barrera cuadrática blanda, CERO dentro de [LOG_VAR_MIN, LOG_VAR_MAX] + +# --- V6 — Oversampling por Magnitude-Warping (Requerimiento 5, ver +# `_magnitude_warp_oversample`). MAGNITUDE_WARP_SIGMA=0.15 es deliberadamente +# moderado: mantiene las ventanas sintéticas dentro de una vecindad plausible +# de la ventana real que las origina (evita que `crypto_specialist` vea, en +# las primeras épocas, un régimen de entrada tan distorsionado que fuerce a +# `log_var` a saltar fuera de [LOG_VAR_MIN, LOG_VAR_MAX] de entrada — ver +# Punto Ciego #2 del mensaje de entrega). MAGNITUDE_WARP_KNOTS=4 mantiene la +# curva de deformación en baja frecuencia relativa a LOOKBACK=60 (ver Punto +# Ciego #2): suficientes nodos para no degenerar en un simple reescalado +# constante por ventana, pocos para no degenerar en ruido i.i.d. de alta +# frecuencia (el defecto original que este mecanismo reemplaza). +MAGNITUDE_WARP_SIGMA = 0.15 +MAGNITUDE_WARP_KNOTS = 4 + +keras.utils.set_random_seed(SEED) +if _FORCE_DETERMINISTIC_CPU: + # V23.2 -- pinea el pool de hilos de TF a 1 ANTES de cualquier op/build de + # modelo: las reducciones paralelas (suma/softmax/etc.) en Eigen no son + # orden-estable entre hilos, así que aunque numpy/python/TF RNG estén + # fijados por `set_random_seed`, el resultado numérico de cada forward/ + # backward pass puede variar corrida a corrida. Con 1 hilo, la reducción + # es secuencial y reproducible bit-a-bit para el mismo seed+datos. + import tensorflow as _tf + _tf.config.threading.set_intra_op_parallelism_threads(1) + _tf.config.threading.set_inter_op_parallelism_threads(1) + + +# ============================================================ +# FASE A: ETL — DESCARGA UNIFICADA (OHLCV) + FEATURE ENGINEERING POR ACTIVO +# ============================================================ +MAX_DOWNLOAD_RETRIES = 5 +BACKOFF_BASE_SECONDS = 2.0 +# Smart Cache Invalidation — antigüedad máxima tolerada del .parquet cacheado +# ANTES de forzarse la caché era válida indefinidamente mientras compilara el +# set de columnas requeridas (ver `download_all`), sin importar cuán vieja +# fuera su fecha más reciente -- exactamente la causa del "abismo temporal" +# auditado en NEWS_SENTIMENT_SCORE: OHLCV estancado en el pasado cruzado +# contra noticias descargadas HOY, ninguna fecha cae dentro de la tolerancia +# del merge_asof (`_NEWS_MERGE_TOLERANCE_DAYS` en data_pipeline.py). +_CACHE_MAX_AGE_HOURS = 48 + +# --- V9 (CI/CD — Purgado Total en Producción, ver entrenamiento_semanal.yml) --- +# El cron de GitHub Actions ('0 23 * * 5') corre este script en un runner +# EFÍMERO: sin estado persistente entre corridas salvo lo que el propio repo +# versiona. Ahí, la Smart Cache Invalidation de 48h (arriba) es la regla +# equivocada -- el riesgo no es un .parquet viejo dentro de una MISMA +# corrida, es una corrida NUEVA arrancando sobre un .parquet commiteado por +# error o sobreviviente de un checkout anterior, aún "fresco" según la +# regla de antigüedad pero potencialmente desincronizado del `merge_asof` +# de NEWS_SENTIMENT_SCORE (que siempre trae titulares de HOY). FORCE_FRESH_DATA +# anula la regla de 48h por completo para el pipeline de entrenamiento. +# Default True (bandera, no hardcode): en producción/CI SIEMPRE se quiere +# data 100% fresca; override explícito vía env var para iteración local +# (`KODAQUANT_FORCE_FRESH_DATA=0`) donde reutilizar la caché ahorra tiempo +# de desarrollo sin tocar el comportamiento en CI. +FORCE_FRESH_DATA = os.getenv("KODAQUANT_FORCE_FRESH_DATA", "1").strip().lower() not in ("0", "false", "no") + + +# --- CONSOLIDACIÓN DEL CORE (Directiva 1) ----------------------------------- +# `_ohlcv_cache` reemplaza el parquet ad-hoc anterior: MISMA clase +# (`kodaquant_core.CacheManager`) que usaría el lado de inferencia para su +# propio caché en `services/`, cada uno con su `cache_dir` independiente. +_ohlcv_cache = CacheManager(DATA_DIR, default_max_age_hours=_CACHE_MAX_AGE_HOURS) +# `_fred_client` reemplaza el acceso exclusivo-a-inferencia que tenía FRED +# en `market_data.py` -- ahora el entrenamiento resuelve ^TNX con la MISMA +# fuente primaria (serie oficial DGS10) que ve el modelo en producción, +# vía FredClient. Solo ^TNX tiene serie FRED equivalente 1:1 (rendimiento, +# no precio de instrumento) -- el resto de MACRO_TICKERS (^GSPC/^VIX/GC=F/ +# DX-Y.NYB) se mantiene en yfinance, ver `_fetch_all_symbols_flat`. +_fred_client = FredClient(api_key=os.getenv("FRED_API_KEY", "")) +# AUDITORÍA 2026-09 (Directiva Head Quant -- diagnóstico degradación equity+crypto +# simultánea) -- root cause más probable de que AMBOS especialistas (arquitecturas +# y universos de tickers completamente independientes) colapsen a la vez: lo ÚNICO +# que comparten es `MACRO_TICKERS` vía `engineer_asset`/`TECH_COLS`, y de los 5 +# tickers macro, 4 de 5 seguían 100% en yfinance pese a que el propio log de +# `_fetch_all_symbols_flat` ("Diagnóstico cobertura", más abajo) documenta +# cobertura real ~0-20% en corridas pasadas para 'DX-Y.NYB' y advierte migrar a +# Twelve Data "igual que ya se hizo en services/market_data.py" -- esa migración +# nunca se replicó acá. Ampliado a series FRED reales (gratis, sin límite de +# volumen relevante para este pipeline) donde existe equivalente 1:1 real: +# ^VIX -> VIXCLS (CBOE Volatility Index, serie oficial) +# ^GSPC -> SP500 (S&P 500, serie oficial FRED -- OJO: histórico FRED solo +# arranca ~2013, más corto que los ~10y de yfinance; con +# tail_days=3700 la ventana de entrenamiento típica queda cubierta, +# pero un LOOKBACK/backtest que pida fechas anteriores a 2013 cae +# en NaN y aterriza en el fallback yfinance de abajo igual) +# GC=F / DX-Y.NYB NO tienen serie FRED 1:1 (oro/USD index no son series que FRED +# publique de fuente primaria) -- quedan en el fallback Stooq/yfinance de abajo. +_FRED_MACRO_SERIES_MAP: dict[str, str] = {"^TNX": "DGS10", "^VIX": "VIXCLS", "^GSPC": "SP500"} + +# Fallback Stooq (CSV público, sin API key, sin límite de rate documentado para +# este volumen) para los macro tickers SIN serie FRED -- gratis, igual que el +# resto del pipeline (Directiva "100% gratuito"). NO VERIFICADO EN VIVO: este +# entorno de ejecución no tiene salida de red a stooq.com (dominio fuera del +# allowlist del sandbox), así que los símbolos de abajo son de memoria/alta +# confianza pero NO confirmados contra la respuesta real del endpoint -- +# `_fetch_macro_stooq_fallback` está escrito para fallar en silencio (log + +# devuelve None) ante CUALQUIER respuesta inesperada, así que un símbolo mal +# mapeado aquí degrada exactamente al comportamiento ACTUAL (yfinance) sin +# romper nada -- CERO riesgo de regresión, solo upside si el símbolo es +# correcto. Verificar manualmente antes de asumir que esta capa está activa. +_STOOQ_MACRO_SYMBOL_MAP: dict[str, str] = { + "GC=F": "gc.f", # oro, futuro continuo COMEX -- proxy, no instrumento idéntico + "DX-Y.NYB": "dx.f", # ICE Dollar Index futuro continuo -- proxy del índice NYBOT real +} +STOOQ_FALLBACK_ENABLED = os.getenv("KODAQUANT_ENABLE_STOOQ_FALLBACK", "1").strip().lower() not in ("0", "false", "no") + + +def _fetch_macro_stooq_fallback(ticker: str) -> Optional[pd.Series]: + """Serie de cierre diario vía CSV público de Stooq (sin key). Devuelve + `None` (nunca levanta) ante cualquier fallo -- red, símbolo inexistente, + CSV vacío/malformado -- para que el caller siga cayendo a yfinance sin + interrumpir `_fetch_all_symbols_flat`. Ver nota de honestidad junto a + `_STOOQ_MACRO_SYMBOL_MAP` arriba: mapeo de símbolos no verificado en vivo + en este entorno.""" + symbol = _STOOQ_MACRO_SYMBOL_MAP.get(ticker) + if not symbol or not STOOQ_FALLBACK_ENABLED: + return None + try: + resp = requests.get( + "https://stooq.com/q/d/l/", + params={"s": symbol, "i": "d"}, + timeout=10, + ) + resp.raise_for_status() + from io import StringIO + df = pd.read_csv(StringIO(resp.text)) + if df.empty or "Close" not in df.columns or "Date" not in df.columns: + logger.warning("[Stooq fallback] '%s' (%s) respuesta vacía/inesperada -- cae a yfinance.", ticker, symbol) + return None + df["Date"] = pd.to_datetime(df["Date"]) + series = df.set_index("Date")["Close"].astype(float).sort_index() + series = series[~series.index.duplicated(keep="last")] + if series.empty: + return None + return series + except Exception as exc: # noqa: BLE001 -- fallback best-effort, jamás debe tumbar el pipeline + logger.warning("[Stooq fallback] '%s' (%s) falló (%r) -- cae a yfinance.", ticker, symbol, exc) + return None + + +def purge_data_cache(data_dir: Path = DATA_DIR) -> None: + """ + Purgado Total (V9): vacía `data_dir` de cualquier caché (.json/.parquet) + vía `CacheManager.purge_all` -- se invoca EXACTAMENTE UNA VEZ por + corrida de entrenamiento, en `__main__`, ANTES del bucle de regímenes + -- nunca dentro de `_fetch_all_symbols_flat` (llamada una vez POR + régimen): purgar ahí borraría, en la segunda llamada, el artefacto que + el régimen anterior de la MISMA corrida acaba de escribir para consumo + posterior (Requerimiento 3: el caché debe sobrevivir intacto al final + de la corrida). + """ + cache = _ohlcv_cache if data_dir == DATA_DIR else CacheManager(data_dir, default_max_age_hours=_CACHE_MAX_AGE_HOURS) + removed = cache.purge_all() + if removed: + logger.warning("[purga CI/CD] FORCE_FRESH_DATA=True -> %d archivo(s) purgado(s) de %s (Data Drift prevention).", + removed, data_dir) + else: + logger.info("[purga CI/CD] FORCE_FRESH_DATA=True -> %s ya estaba vacío.", data_dir) + + +def _download_with_backoff(symbols: list[str], period: str, + max_retries: int = MAX_DOWNLOAD_RETRIES, + backoff_base: float = BACKOFF_BASE_SECONDS, + min_coverage: float = 0.5) -> pd.DataFrame: + """Reintenta la descarga con backoff exponencial ante 429/timeouts transitorios, + Y ANTE FALLOS PARCIALES -- yfinance a veces devuelve un batch "no vacío" en + general pero con UN símbolo puntual ~100% NaN (rate-limit silencioso por-símbolo, + típico al encadenar descargas rápidas -- causa real observada: '^TNX_Close' con + 0.7% de cobertura en una corrida de crypto_specialist lanzada 12s después de + equity_specialist). Antes, esa caída parcial pasaba el chequeo de "no vacío", + quedaba en caché, y solo se detectaba 700+ líneas más abajo cuando + `engineer_asset` colapsaba el dataset a 0 filas. Ahora se valida cobertura + por-símbolo ACÁ, en el mismo bucle de reintento -- Equities/cripto: SIEMPRE + yfinance (Directiva 3).""" + import time + + last_exc: Exception | None = None + for attempt in range(1, max_retries + 1): + try: + data = yf.download(symbols, period=period, auto_adjust=True, progress=False) + if data is None or data.empty: + raise ValueError("yfinance devolvió un DataFrame vacío") + + close = (data["Close"] if isinstance(data.columns, pd.MultiIndex) + else data[["Close"]].rename(columns={"Close": symbols[0]})) + missing = [s for s in symbols if s not in close.columns] + starved = [s for s in symbols if s in close.columns and close[s].notna().mean() < min_coverage] + if missing or starved: + raise ValueError( + f"cobertura insuficiente tras la descarga -- ausentes={missing} " + f"con <{min_coverage:.0%} de datos reales={starved}" + ) + return data + except Exception as exc: # noqa: BLE001 + last_exc = exc + if attempt == max_retries: + break + wait_s = backoff_base * (2 ** (attempt - 1)) + logger.warning("Descarga falló (intento %d/%d): %r — reintentando en %.0fs", + attempt, max_retries, exc, wait_s) + time.sleep(wait_s) + raise RuntimeError(f"No se pudo descargar {symbols} tras {max_retries} intentos") from last_exc + + +def _fetch_all_symbols_flat(tickers: list[str], macro_tickers: list[str], period: str, + cache_tag: str, force_refresh: bool | None = None, + macro_period: str | None = None) -> pd.DataFrame: + """ + Reemplazo canónico de `download_all` (alias más abajo, compatibilidad + hacia atrás con `train_pipeline.py`). Devuelve OHLCV completo de + `tickers` (`{ticker}_{Open,High,Low,Close,Volume}`) + Close de + `macro_tickers` (`{macro}_Close`), SIN ffill/dropna -- esa + responsabilidad sigue siendo exclusiva de `engineer_asset`. + + Directiva 1 (caché): unificada vía `CacheManager` (`_ohlcv_cache`, + antes parquet ad-hoc acá / JSON ad-hoc en inferencia), mismo + `_CACHE_MAX_AGE_HOURS`/`FORCE_FRESH_DATA` de siempre. + + Directiva 2 (fuga de datos / alineación 24/7 vs 5/7): cada serie macro + se proyecta contra el calendario REAL del universo de `tickers` de + este régimen vía `kodaquant_core.project_macro_frame` (upsample a + calendario diario corrido + ffill ANTES del merge) -- misma lógica, + ya no un `.ffill()` ciego sobre el frame combinado dentro de + `engineer_asset` cruzando dedos con el orden de columnas. + + Directiva 3 (alineación train/inferencia): ^TNX se resuelve vía + `FredClient`/serie oficial DGS10 -- LA MISMA fuente primaria que + `market_data.py` ya usa en inferencia para ese mismo factor -- con + fallback automático a yfinance si `FRED_API_KEY` no está configurada + o la request falla puntualmente. El resto de `macro_tickers` y TODO + el universo de `tickers` (equities + cripto) permanece en yfinance, + concurrente, sin cambios. + """ + effective_force_refresh = FORCE_FRESH_DATA if force_refresh is None else force_refresh + cache_key = f"ohlcv_{cache_tag}_{period}" + fields = ["Open", "High", "Low", "Close", "Volume"] + required_cols = {f"{t}_{f}" for t in tickers for f in fields} | {f"{m}_Close" for m in macro_tickers} + + if effective_force_refresh: + logger.info("[CacheManager] FORCE_FRESH_DATA activo -> se ignora cualquier %s cacheado, descarga 100%% fresca.", cache_key) + else: + cached = _ohlcv_cache.get_dataframe(cache_key, required_columns=required_cols) + if cached is not None: + logger.info("[CacheManager] leyendo %s (fresco).", cache_key) + return cached + + # --- Precio equities/cripto: yfinance, concurrente (Directiva 3) ------ + raw = _download_with_backoff(tickers, period) + flat = pd.DataFrame(index=raw.index) + available_fields = set(raw.columns.get_level_values(0)) if isinstance(raw.columns, pd.MultiIndex) else set(raw.columns) + for field in fields: + if field not in available_fields: + continue + sub = raw[field] if isinstance(raw.columns, pd.MultiIndex) else raw[[field]].rename(columns={field: tickers[0]}) + for sym in tickers: + if sym in sub.columns: + flat[f"{sym}_{field}"] = sub[sym] + flat.index = normalize_daily_index(pd.DatetimeIndex(flat.index)) + flat = flat[~flat.index.duplicated(keep="last")].sort_index() + + # --- Factores macro: FRED (^TNX) -> yfinance (resto + fallback) ------- + macro_closes: dict[str, pd.Series] = {} + macro_via_yf: list[str] = [] + for m in macro_tickers: + fred_series_id = _FRED_MACRO_SERIES_MAP.get(m) + # V20: tail_days=520 (~1.4 años) era el bug real detrás del + # "19.9%/0.7% de cobertura" que veníamos viendo en '^TNX_Close' en + # TODAS las corridas -- incluso con FRED_API_KEY correctamente + # configurada. No era Yahoo Finance fallando: era esta llamada + # pidiéndole a FRED muchísimos menos días de los que cubre + # PERIOD="10y" para el resto del pipeline (equities/otros macro + # vía yfinance). 520/~2600 días de trading ≈ 20% -- coincide exacto + # con el número de cobertura que se repitió en cada corrida. + # 3700 días cubre 10y + margen (fines de semana/feriados incluidos + # en el conteo corrido de FRED). + series = _fred_client.daily_series(fred_series_id, tail_days=3700) if fred_series_id else None + if series is not None and not series.empty: + macro_closes[m] = series + continue + stooq_series = _fetch_macro_stooq_fallback(m) + if stooq_series is not None and not stooq_series.empty: + logger.info("[Stooq fallback] '%s' resuelto vía Stooq (sin FRED equivalente).", m) + macro_closes[m] = stooq_series + else: + macro_via_yf.append(m) + + if macro_via_yf: + # V27 -- FIX: `period="max"` (BTC-USD, ver REGIMES.crypto_specialist) + # propagado sin querer al fallback yfinance de macro rompió GC=F + # ("cobertura insuficiente" -- ese ticker no tiene una serie "max" + # sana en Yahoo). Los factores macro SIEMPRE usan `macro_period` + # (default: `period`, o sea CERO cambio para cualquier caller que + # no lo pase explícito -- equity_specialist y todo lo de antes de + # hoy quedan bit a bit igual). Solo los `tickers` (precio) usan el + # `period` que le pasó el caller. + macro_raw = _download_with_backoff(macro_via_yf, macro_period or period) + if isinstance(macro_raw.columns, pd.MultiIndex): + macro_available = set(macro_raw.columns.get_level_values(0)) + if "Close" in macro_available: + macro_close_block = macro_raw["Close"] + for m in macro_via_yf: + if m in macro_close_block.columns: + macro_closes[m] = macro_close_block[m].dropna() + elif "Close" in macro_raw.columns and len(macro_via_yf) == 1: + macro_closes[macro_via_yf[0]] = macro_raw["Close"].dropna() + + macro_frame = project_macro_frame(macro_closes, flat.index) if macro_closes else pd.DataFrame(index=flat.index) + for m in macro_tickers: + flat[f"{m}_Close"] = macro_frame[m] if m in macro_frame.columns else np.nan + + # --- Diagnóstico de cobertura (NO altera el pipeline, solo visibilidad) -- + # V16: un macro ticker con cobertura ~0% (símbolo roto/deslistado en + # Yahoo Finance -- "DX-Y.NYB" es un caso conocido de esto) hace que + # `engineer_asset` -- que exige TODAS las columnas macro no-nulas antes + # de aceptar una fila, sin cambios de política -- termine con 0 filas + # para el activo: un `ValueError` de sklearn ~700 líneas más abajo, sin + # ninguna pista de la causa real. Este bloque deja explícito en el log, + # ACÁ mismo, qué columna es la culpable, antes de que el pipeline siga. + for col in sorted(required_cols): + if col not in flat.columns: + logger.warning("[Diagnóstico cobertura] '%s' NO llegó a descargarse (columna ausente).", col) + continue + coverage_pct = 100.0 * flat[col].notna().mean() if len(flat) else 0.0 + if coverage_pct < 50.0: + logger.warning( + "[Diagnóstico cobertura] '%s': solo %.1f%% de filas con dato real " + "en todo el rango descargado -- candidato directo a colapsar " + "`engineer_asset` (exige TODAS las columnas no-nulas por fila). " + "Si es un macro ticker, lo más probable es que Yahoo Finance haya " + "dejado de servirlo con este período/granularidad -- considerar " + "migrarlo a Twelve Data, igual que ya se hizo en " + "services/market_data.py para ^GSPC/^VIX/GC=F/DX-Y.NYB.", + col, coverage_pct, + ) + + _ohlcv_cache.set_dataframe(cache_key, flat) + logger.info("[CacheManager] %s guardado (sincronizado, fecha más reciente %s).", + cache_key, flat.index.max() if not flat.empty else "N/A") + return flat + + +# Alias de compatibilidad hacia atrás: `download_all` era el nombre previo +# a la consolidación del core; `train_pipeline.py` (MLOps incremental) y +# cualquier caller externo que aún lo referencie siguen funcionando sin +# ningún cambio de firma. +download_all = _fetch_all_symbols_flat + + +def compute_rsi(series: pd.Series, period: int = 14) -> pd.Series: + delta = series.diff() + gain = delta.clip(lower=0.0) + loss = -delta.clip(upper=0.0) + avg_gain = gain.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + avg_loss = loss.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + rs = avg_gain / avg_loss.replace(0.0, np.nan) + return (100 - (100 / (1 + rs))).fillna(50.0) + + +def compute_macd(series: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9): + ema_fast = series.ewm(span=fast, adjust=False).mean() + ema_slow = series.ewm(span=slow, adjust=False).mean() + macd_line = ema_fast - ema_slow + signal_line = macd_line.ewm(span=signal, adjust=False).mean() + return macd_line, signal_line + + +def compute_sentiment_score(asset_log_return: pd.Series, macro_log_return: pd.Series, + window: int = SENTIMENT_LOOKBACK) -> pd.Series: + """Correlación de Pearson móvil activo<->macro (proxy de shock idiosincrático, V4).""" + rho = asset_log_return.rolling(window=window, min_periods=window).corr(macro_log_return) + return rho.fillna(0.0) + + +def compute_atr(high: pd.Series, low: pd.Series, close: pd.Series, period: int = 14) -> pd.Series: + prev_close = close.shift(1) + tr = pd.concat([ + high - low, + (high - prev_close).abs(), + (low - prev_close).abs(), + ], axis=1).max(axis=1) + atr = tr.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + return atr.fillna(0.0) + + +def compute_bb_width(series: pd.Series, window: int = 20, num_std: float = 2.0) -> pd.Series: + rolling_mean = series.rolling(window=window, min_periods=window).mean() + rolling_std = series.rolling(window=window, min_periods=window).std() + width = (2 * num_std * rolling_std) / rolling_mean.replace(0.0, np.nan) + return width.fillna(0.0) + + +def compute_obv(close: pd.Series, volume: pd.Series) -> pd.Series: + direction = np.sign(close.diff()).fillna(0.0) + obv = (direction * volume).cumsum() + return obv.fillna(0.0) + + +def compute_adx(high: pd.Series, low: pd.Series, close: pd.Series, period: int = 14) -> pd.Series: + """ADX (Wilder) — fuerza de tendencia direccional, independiente del signo.""" + up_move = high.diff() + down_move = -low.diff() + plus_dm = pd.Series(np.where((up_move > down_move) & (up_move > 0), up_move, 0.0), index=high.index) + minus_dm = pd.Series(np.where((down_move > up_move) & (down_move > 0), down_move, 0.0), index=high.index) + + tr = pd.concat([ + high - low, + (high - close.shift(1)).abs(), + (low - close.shift(1)).abs(), + ], axis=1).max(axis=1) + atr = tr.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + + plus_di = 100 * (plus_dm.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() / atr.replace(0.0, np.nan)) + minus_di = 100 * (minus_dm.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() / atr.replace(0.0, np.nan)) + dx = 100 * (plus_di - minus_di).abs() / (plus_di + minus_di).replace(0.0, np.nan) + adx = dx.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + return adx.fillna(0.0) + + +def compute_stochastic_k(high: pd.Series, low: pd.Series, close: pd.Series, period: int = 14) -> pd.Series: + """Oscilador estocástico %K — posición del cierre relativa al rango reciente [0, 100].""" + lowest_low = low.rolling(window=period, min_periods=period).min() + highest_high = high.rolling(window=period, min_periods=period).max() + denom = (highest_high - lowest_low).replace(0.0, np.nan) + stoch_k = 100 * (close - lowest_low) / denom + return stoch_k.fillna(50.0) + + +def _fetch_fear_greed_index(tail_days: int) -> Optional[pd.Series]: + """Serie diaria del Crypto Fear & Greed Index (alternative.me, endpoint + público, SIN key) -- 0=miedo extremo, 100=codicia extrema, 50=neutro. + A diferencia de FUNDING_RATE (revertido, derivado de precio/leverage -- + correlacionado con lo que ya veían RSI/ATR/BB_WIDTH), esto es un + agregado de PSICOLOGÍA de mercado (volatilidad, momentum, redes + sociales, dominancia BTC) -- categoría de señal distinta, no probada + antes. Historia disponible desde feb-2018 -- fechas anteriores quedan + en 50.0 (neutro) por default en `engineer_asset`, nunca NaN.""" + try: + resp = requests.get("https://api.alternative.me/fng/", params={"limit": 0, "format": "json"}, timeout=10.0) + resp.raise_for_status() + records = resp.json().get("data", []) + except Exception as exc: # noqa: BLE001 -- proveedor opcional, jamás tumba el pipeline + logger.debug("Fear & Greed Index falló: %r", exc) + return None + if not records: + return None + fg = pd.DataFrame(records) + fg["date"] = pd.to_datetime(pd.to_numeric(fg["timestamp"]), unit="s").dt.normalize() + fg["value"] = pd.to_numeric(fg["value"], errors="coerce") + return fg.groupby("date")["value"].mean() + + +# --------------------------------------------------------------------------- +# V24 — ALPHA CRIPTO: DERIVADOS + ON-CHAIN + TRANSFORMACIÓN MATEMÁTICA +# --------------------------------------------------------------------------- +# FUNDING_RATE crudo ya fue probado y REVERTIDO en V17 (correlacionaba con lo +# que RSI_14/ATR_PCT/BB_WIDTH_20 ya capturan -- todos derivados de precio/ +# leverage, misma categoría de información). Las tres adiciones de abajo +# apuntan a categorías DISTINTAS, no probadas antes en este pipeline: +# +# 1) FUNDING_RATE_ZSCORE -- no es el NIVEL del funding (eso fracasó), es su +# EXTREMIDAD relativa a su propia distribución móvil: proxy de estrés de +# posicionamiento/crowding en derivados (funding en el percentil 99 ha +# precedido reversiones en ciclos previos) -- señal de POSICIONAMIENTO, +# no de precio. +# 2) ONCHAIN_ACTIVITY_ROC -- actividad de RED, no de PRECIO: tasa de cambio +# de transacciones on-chain confirmadas. BTC ÚNICAMENTE (ver docstring +# de `_fetch_onchain_activity` -- no existe equivalente gratuito de +# historial largo verificado para ETH; se deja en 0.0 neutro, NO se +# inventa el dato). +# 3) FRAC_DIFF_LOG_CLOSE -- la transformación matemática pedida explícita- +# mente (López de Prado, AFML cap. 5). Mantiene memoria de largo plazo +# del precio -- a diferencia de LOG_RETURN_1D (diferenciación entera +# d=1, borra toda memoria) -- mientras logra estacionariedad. El orden +# `d` se calibra por ADF SOLO sobre el prefijo de train (ver +# `find_min_ffd_d`) -- nunca sobre la serie completa, para no filtrar +# información de test hacia la selección del hiperparámetro, el mismo +# estándar que ya aplica `feature_scaler.fit(features[:split_idx])` en +# `build_asset_dataset`. +# +# WAVELETS -- evaluado y DESCARTADO deliberadamente en este pase: una DWT +# estándar (PyWavelets `dwt`/`wavedec`) sobre una ventana fija usa muestras a +# AMBOS lados de cada coeficiente según el modo de borde (`symmetric`/ +# `periodic`) -- aplicarla sobre la serie completa antes de trocear en +# ventanas de `LOOKBACK` inyecta fuga de información futura DENTRO de cada +# ventana de entrenamiento, exactamente la clase de bug que los docstrings de +# este archivo (`build_asset_dataset`, `align_macro_to_calendar`) llevan +# 20+ versiones evitando. Una variante causal real (MODWT streaming, +# recalculada por timestep) es viable pero cambia el costo computacional de +# O(n) a O(n·LOOKBACK) SOLO para esa columna -- no se implementa acá sin +# benchmarking explícito primero. FRAC_DIFF_LOG_CLOSE (causal por +# construcción) cubre el mismo objetivo (memoria + estacionariedad) sin ese +# riesgo. +try: + from statsmodels.tsa.stattools import adfuller +except (ImportError, TypeError): # TypeError = pandas 3.x deprecate_kwarg compat issue (see venv patch RONDA 8) + adfuller = None + logger.warning( + "statsmodels no instalado o incompatible (`pip install statsmodels` + ver RONDA 8 en requirements.txt) " + "-- FRAC_DIFF_LOG_CLOSE usará FRAC_DIFF_DEFAULT_D=0.40 fijo en vez de calibrar `d` vía ADF por activo." + ) + + +BINANCE_FAPI_FUNDING_URL = "https://fapi.binance.com/fapi/v1/fundingRate" +BINANCE_FUNDING_SYMBOL_MAP = {"BTC-USD": "BTCUSDT", "ETH-USD": "ETHUSDT"} +FUNDING_ZSCORE_WINDOW_DAYS = 90 # ~1 trimestre de funding 8h-agregado-a-diario +FUNDING_ZSCORE_MIN_PERIODS = 20 +FUNDING_ZSCORE_CLIP = 5.0 +# AUDITORÍA RESCATE 2026-08 -- RESTRUCTURACIÓN ASIMÉTRICA (Directiva Head +# Quant, "funding rates asimétricos"): el z-score simétrico de V24 trata +# funding extremo POSITIVO (longs pagando -- crowding alcista, apalancado +# contra el sesgo estructural de oferta creciente del activo) igual que +# funding extremo NEGATIVO (shorts pagando -- crowding bajista, a contra- +# tendencia de ese mismo sesgo estructural). Son regímenes de crowding +# cualitativamente distintos, no reflejos especulares uno del otro -- se +# separan las dos colas y se les aplica una ganancia potencia (`gamma`) +# INDEPENDIENTE antes de re-unirlas, en vez de una única curva simétrica. +# `_POS`>1.0 amplifica la cola de crowding-largo; `_NEG`<1.0 amortigua la de +# crowding-corto -- ambas calibrables por separado si la evidencia empírica +# de una corrida real sugiere lo contrario, sin tocar la ventana/mínimo de +# períodos (que siguen definiendo la ESCALA, no la FORMA, de la señal). +FUNDING_ZSCORE_ASYM_POS_GAMMA = 1.35 +FUNDING_ZSCORE_ASYM_NEG_GAMMA = 0.85 + +# V26 (Directiva Head Quant) -- FUNDING_RATE_MOMENTUM_ZSCORE: ver +# `compute_funding_rate_momentum_zscore`. Ventana de diff corta (1 semana) +# a propósito -- es una señal de VELOCIDAD, una ventana larga la +# convertiría de vuelta en una medida de nivel, redundante con +# FUNDING_RATE_ZSCORE. La ventana/mínimo de períodos del z-score que +# normaliza esa velocidad sí se mantiene igual de larga (90d) que el resto +# de *_ZSCORE del módulo -- eso define la ESCALA de "velocidad extrema", +# no la velocidad en sí. +FUNDING_MOMENTUM_LOOKBACK_DAYS = 7 +FUNDING_MOMENTUM_ZSCORE_WINDOW_DAYS = 90 +FUNDING_MOMENTUM_ZSCORE_MIN_PERIODS = 20 +FUNDING_MOMENTUM_ZSCORE_CLIP = 5.0 + +BLOCKCHAIN_INFO_CHART_URL = "https://api.blockchain.info/charts/{chart}" +ONCHAIN_CHART_NAME = "n-transactions" # transacciones confirmadas/día -- proxy de demanda real de red, BTC únicamente +ONCHAIN_ROC_LOOKBACK_DAYS = 7 +ONCHAIN_ROC_CLIP = 3.0 + +FRAC_DIFF_D_GRID = tuple(round(float(d), 2) for d in np.arange(0.10, 1.01, 0.10)) +FRAC_DIFF_ADF_PVALUE_MAX = 0.05 +FRAC_DIFF_THRESH = 1e-4 +FRAC_DIFF_DEFAULT_D = 0.40 # fallback sin statsmodels -- valor de referencia AFML para series financieras + +# AUDITORÍA RESCATE 2026-08 -- FIX DE DESALINEACIÓN TRAIN/SERVE REAL: `d` se +# calibra acá sobre el prefijo de train de PERIOD="10y" (~8 años), pero +# `quanti_engine.py::_find_min_ffd_d` RECALIBRABA de forma INDEPENDIENTE en +# cada request, sobre una ventana de solo ~2 años (`DEFAULT_HISTORY_SESSIONS`, +# ver services/market_data.py) -- el ADF-óptimo sobre una ventana ~4x más +# corta no tiene por qué coincidir con el `d` real de entrenamiento, así que +# FRAC_DIFF_LOG_CLOSE llegaba a inferencia con una transformación matemática +# DISTINTA a la que vio el modelo en entrenamiento para ese mismo canal -- +# sin lanzar ningún error (ambos "funcionan", solo producen números +# distintos). Este diccionario captura el `d` REAL usado en entrenamiento, +# por ticker, para persistirlo en scalers_dict.pkl (ver run_regime_pipeline) +# -- quanti_engine.py lo lee y lo usa DIRECTO en vez de recalibrar, con +# fallback automático a su comportamiento previo si el bundle es viejo (no +# tiene la clave). Afecta EXCLUSIVAMENTE a FRAC_DIFF_LOG_CLOSE en tickers +# cripto -- esa columna ya es 0.0 neutro por diseño para equity_specialist +# (ver bloque `if ticker in REGIMES["crypto_specialist"]["tickers"]` en +# `engineer_asset`), así que este fix no puede, ni en principio, alterar un +# solo número de la inferencia de equity_specialist. +_LAST_FFD_D_BY_TICKER: dict[str, float] = {} + +# --------------------------------------------------------------------------- +# V23.5 (Directiva 3, Head Quant) — PUELL_MULTIPLE_ZSCORE, BTC ÚNICAMENTE +# --------------------------------------------------------------------------- +# Puell Multiple (David Puell, 2019) = emisión diaria de BTC valuada en USD +# / su propio promedio móvil de 365 días -- señal de OFERTA estructural +# (cuánto BTC nuevo deben vender los mineros para cubrir costos operativos), +# categoría DISTINTA a las 3 de V24 arriba (posicionamiento en derivados / +# actividad de red / memoria de precio). Documentado en vivo por +# lookintobitcoin.com y bitcoinmagazinepro.com como indicador de ciclo. +# +# CERO llamada de red -- a diferencia de ONCHAIN_ACTIVITY_ROC (depende de +# blockchain.info, con fallback silencioso a 0.0 si el endpoint cae), la +# emisión diaria de BTC es un CALENDARIO DETERMINÍSTICO conocido de +# antemano (reward/bloque se reduce a la mitad cada halving) -- se deriva +# 100% de `RAW_CLOSE` ya descargado, cero dependencia externa nueva, cero +# riesgo de degradar a neutro por un API caído. +# +# BTC ÚNICAMENTE: el denominador (emisión Proof-of-Work) no tiene análogo +# en ETH-USD, que es Proof-of-Stake sin emisión por minería desde The +# Merge (2022) -- no se inventa un "Puell" sintético para ETH; queda en +# 0.0 neutro para ETH-USD/equity, MISMO patrón que ONCHAIN_ACTIVITY_ROC. +# +# `BTC_BLOCKS_PER_DAY=144` es la aproximación estándar de la literatura +# (10 min/bloque objetivo, dificultad autoajustada) -- no se descarga el +# conteo real de bloques/día por ticker (evita otra dependencia de red +# para una corrección de segundo orden). El halving de 2028 es una +# ESTIMACIÓN (fecha exacta depende del ritmo real de minado); de +# correrse unas semanas, el único efecto es una discontinuidad leve en +# `daily_issuance_btc` cerca de esa fecha, amortiguada por el propio +# z-score móvil (ver `compute_puell_multiple_zscore`). +BTC_HALVING_SCHEDULE: tuple[tuple[datetime, float], ...] = ( + (datetime(2009, 1, 3, tzinfo=timezone.utc), 50.0), + (datetime(2012, 11, 28, tzinfo=timezone.utc), 25.0), + (datetime(2016, 7, 9, tzinfo=timezone.utc), 12.5), + (datetime(2020, 5, 11, tzinfo=timezone.utc), 6.25), + (datetime(2024, 4, 20, tzinfo=timezone.utc), 3.125), + (datetime(2028, 4, 1, tzinfo=timezone.utc), 1.5625), # estimado -- ver nota arriba +) +BTC_BLOCKS_PER_DAY = 144.0 +PUELL_MA_WINDOW_DAYS = 365 +PUELL_MA_MIN_PERIODS = 30 +PUELL_ZSCORE_WINDOW_DAYS = 365 +PUELL_ZSCORE_MIN_PERIODS = 60 +PUELL_ZSCORE_CLIP = 5.0 + + +def _btc_block_reward_schedule(dates: pd.DatetimeIndex) -> np.ndarray: + """Reward BTC/bloque vigente en cada fecha de `dates`, según + `BTC_HALVING_SCHEDULE` -- calendario determinístico, cero fetch.""" + idx = pd.DatetimeIndex(dates) + idx_utc = idx.tz_localize("UTC") if idx.tz is None else idx.tz_convert("UTC") + schedule_dates = pd.DatetimeIndex([d for d, _ in BTC_HALVING_SCHEDULE]) + schedule_rewards = np.array([r for _, r in BTC_HALVING_SCHEDULE]) + pos = schedule_dates.searchsorted(idx_utc, side="right") - 1 + pos = np.clip(pos, 0, len(schedule_rewards) - 1) + return schedule_rewards[pos] + + +def _btc_halving_epoch_cum_supply() -> np.ndarray: + """Suministro acumulado de BTC al INICIO de cada época de `BTC_HALVING_SCHEDULE` + -- precomputado una sola vez, cero llamada de red (mismo insumo determinístico + que ya usa `compute_puell_multiple_zscore`).""" + dates = [d for d, _ in BTC_HALVING_SCHEDULE] + rewards = [r for _, r in BTC_HALVING_SCHEDULE] + cum = [0.0] + for i in range(1, len(dates)): + days = (dates[i] - dates[i - 1]).total_seconds() / 86400.0 + cum.append(cum[-1] + days * BTC_BLOCKS_PER_DAY * rewards[i - 1]) + return np.array(cum) + + +_BTC_EPOCH_CUM_SUPPLY_AT_START = _btc_halving_epoch_cum_supply() + + +def _btc_cumulative_supply(dates: pd.DatetimeIndex) -> np.ndarray: + """Suministro circulante APROXIMADO de BTC en cada fecha de `dates` -- + integra `BTC_HALVING_SCHEDULE`/`BTC_BLOCKS_PER_DAY` desde el genesis + (2009-01-03), cero llamada de red. Denominador de mercado (`market_cap`) + para `compute_nvt_ratio_zscore` -- MISMA filosofía "cero fetch" que ya + usa `_btc_block_reward_schedule`/Puell Multiple arriba: la aproximación + (reward/bloque constante dentro de cada época, 144 bloques/día) es + idéntica a la que ya se acepta ahí, ningún nuevo supuesto.""" + idx = pd.DatetimeIndex(dates) + idx_utc = idx.tz_localize("UTC") if idx.tz is None else idx.tz_convert("UTC") + schedule_dates = pd.DatetimeIndex([d for d, _ in BTC_HALVING_SCHEDULE]) + schedule_rewards = np.array([r for _, r in BTC_HALVING_SCHEDULE]) + pos = np.clip(schedule_dates.searchsorted(idx_utc, side="right") - 1, 0, len(schedule_rewards) - 1) + epoch_start = schedule_dates[pos] + days_since_epoch_start = (idx_utc - epoch_start).total_seconds() / 86400.0 + return _BTC_EPOCH_CUM_SUPPLY_AT_START[pos] + days_since_epoch_start * BTC_BLOCKS_PER_DAY * schedule_rewards[pos] + + +# --------------------------------------------------------------------------- +# AUDITORÍA RESCATE 2026-08 — RESTRUCTURACIÓN NVT RATIO (Directiva Head Quant, +# reemplaza la definición de ONCHAIN_ACTIVITY_ROC, MISMO nombre/slot de +# TECH_COLS -- cero cambio de N_FEATURES/shape, cero impacto en +# equity_specialist, que ya recibe 0.0 neutro en esta columna sin importar +# su fórmula interna) +# --------------------------------------------------------------------------- +# V24 media esta columna como tasa de cambio CRUDA de conteo de +# transacciones -- actividad de red sin contexto de VALUACIÓN. NVT Ratio +# (Willy Woo/Chris Burniske) = valor de red (market cap) / valor +# transaccionado on-chain diario -- categoría de señal distinta a las 5 ya +# presentes (posicionamiento en derivados / ciclo de oferta del minero / +# memoria de precio / vol realizada / vol-de-vol): es un proxy de +# SOBRE-valuación relativa a USO REAL de la red, análogo a un P/E ratio. +# `market_cap` usa `_btc_cumulative_supply` (determinístico, cero fetch, +# arriba); `tx_volume_usd` viene de blockchain.info (mismo endpoint que +# `_fetch_onchain_activity`, chart distinto -- `_fetch_onchain_tx_volume_usd` +# abajo). Z-score de log(NVT) -- no el nivel crudo (no acotado, y su escala +# de mercado crece con la capitalización total) -- mismo criterio de +# "extremidad relativa" que el resto del bloque V23.5/V24. +ONCHAIN_TX_VALUE_CHART_NAME = "estimated-transaction-volume-usd" +NVT_ZSCORE_WINDOW_DAYS = 365 +NVT_ZSCORE_MIN_PERIODS = 60 +NVT_ZSCORE_CLIP = 5.0 + + +def _fetch_onchain_tx_volume_usd() -> Optional[pd.Series]: + """Volumen diario de transacciones on-chain BTC valuado en USD -- + numerador de utilidad real de NVT Ratio. Mismo endpoint/patrón que + `_fetch_onchain_activity` (blockchain.info /charts, público, sin key), + chart distinto.""" + return _fetch_onchain_activity(chart=ONCHAIN_TX_VALUE_CHART_NAME) + + +def compute_nvt_ratio_zscore(close: pd.Series, tx_volume_usd: pd.Series, + window: int = NVT_ZSCORE_WINDOW_DAYS, + min_periods: int = NVT_ZSCORE_MIN_PERIODS) -> pd.Series: + """Z-score móvil (rolling, SOLO pasado -- cero fuga) de log(NVT Ratio). + BTC ÚNICAMENTE (ver `engineer_asset`) -- mismo motivo que Puell Multiple: + el "valor de red" (`market_cap`) vía suministro determinístico solo + tiene forma cerrada para una cadena Proof-of-Work con calendario de + emisión conocido.""" + market_cap = close * _btc_cumulative_supply(close.index) + nvt = market_cap / tx_volume_usd.replace(0.0, np.nan) + log_nvt = np.log(nvt.clip(lower=1e-6)) + mean = log_nvt.rolling(window, min_periods=min_periods).mean() + std = log_nvt.rolling(window, min_periods=min_periods).std() + z = (log_nvt - mean) / std.replace(0.0, np.nan) + return z.clip(-NVT_ZSCORE_CLIP, NVT_ZSCORE_CLIP).fillna(0.0) + + +def compute_puell_multiple_zscore(close: pd.Series, window: int = PUELL_ZSCORE_WINDOW_DAYS, + min_periods: int = PUELL_ZSCORE_MIN_PERIODS) -> pd.Series: + """ + Z-score móvil (rolling, SOLO pasado -- cero fuga) de log(Puell + Multiple) -- mismo criterio de "extremidad relativa" que + `compute_funding_rate_zscore`, no el nivel crudo (no acotado por + construcción, y su escala decae en cada halving -- ver docstring del + bloque de constantes arriba). + """ + reward_per_block = _btc_block_reward_schedule(close.index) + daily_issuance_usd = reward_per_block * BTC_BLOCKS_PER_DAY * close.to_numpy() + issuance = pd.Series(daily_issuance_usd, index=close.index) + issuance_ma = issuance.rolling(PUELL_MA_WINDOW_DAYS, min_periods=PUELL_MA_MIN_PERIODS).mean() + puell = issuance / issuance_ma.replace(0.0, np.nan) + log_puell = np.log(puell.clip(lower=1e-6)) + mean = log_puell.rolling(window, min_periods=min_periods).mean() + std = log_puell.rolling(window, min_periods=min_periods).std() + z = (log_puell - mean) / std.replace(0.0, np.nan) + return z.clip(-PUELL_ZSCORE_CLIP, PUELL_ZSCORE_CLIP).fillna(0.0) + + +def _fetch_binance_funding_history(ticker: str) -> Optional[pd.Series]: + """ + Historial diario (promedio de los ~3 pagos de 8h) de funding rate de + perpetuos Binance -- endpoint REST público, SIN API key. Pagina hacia + adelante en bloques de 1000 registros (límite del endpoint) desde el + lanzamiento del contrato hasta hoy. + """ + symbol = BINANCE_FUNDING_SYMBOL_MAP.get(ticker) + if symbol is None: + return None + all_records: list[dict] = [] + cursor_ms = int(datetime(2019, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) + now_ms = int(time.time() * 1000) + for _ in range(50): # techo defensivo -- ~50k registros, muy por encima de cualquier historial real + if cursor_ms >= now_ms: + break + try: + resp = requests.get( + BINANCE_FAPI_FUNDING_URL, + params={"symbol": symbol, "startTime": cursor_ms, "limit": 1000}, + timeout=15, + ) + resp.raise_for_status() + batch = resp.json() + except Exception as exc: # noqa: BLE001 -- red/HTTP transitorio, proveedor opcional + logger.warning("Binance fundingRate falló para %s: %r", symbol, exc) + break + if not batch: + break + all_records.extend(batch) + last_time = int(batch[-1]["fundingTime"]) + if last_time <= cursor_ms: + break + cursor_ms = last_time + 1 + if len(batch) < 1000: + break + time.sleep(0.15) # cortesía de rate-limit -- público, sin key, sin límite documentado estricto + if not all_records: + return None + raw = pd.DataFrame(all_records) + raw["date"] = pd.to_datetime(pd.to_numeric(raw["fundingTime"]), unit="ms").dt.normalize() + raw["fundingRate"] = pd.to_numeric(raw["fundingRate"], errors="coerce") + return raw.groupby("date")["fundingRate"].mean().sort_index() + + +def compute_funding_rate_zscore(daily_funding: pd.Series, window: int = FUNDING_ZSCORE_WINDOW_DAYS, + min_periods: int = FUNDING_ZSCORE_MIN_PERIODS) -> pd.Series: + """Z-score móvil ASIMÉTRICO (`rolling` estándar para media/std, SOLO + pasado -- cero fuga) -- extremidad del funding relativa a su propio + régimen reciente, no su nivel absoluto. V25 (auditoría rescate 2026-08): + el z-score crudo se separa en cola positiva/negativa y cada una recibe + su propia ganancia potencia (`FUNDING_ZSCORE_ASYM_*_GAMMA`) antes de + reunirse y recortarse -- ver docstring del bloque de constantes arriba. + En cualquier punto solo una de las dos colas es no-nula (`pos`/`neg` son + mutuamente excluyentes por construcción de `.clip`), así que la unión + preserva el signo original sin introducir ninguna discontinuidad en 0.""" + mean = daily_funding.rolling(window, min_periods=min_periods).mean() + std = daily_funding.rolling(window, min_periods=min_periods).std() + z = (daily_funding - mean) / std.replace(0.0, np.nan) + pos = z.clip(lower=0.0) + neg_abs = (-z.clip(upper=0.0)) + z_asym = pos.pow(FUNDING_ZSCORE_ASYM_POS_GAMMA) - neg_abs.pow(FUNDING_ZSCORE_ASYM_NEG_GAMMA) + return z_asym.clip(-FUNDING_ZSCORE_CLIP, FUNDING_ZSCORE_CLIP).fillna(0.0) + + +def compute_funding_rate_momentum_zscore(daily_funding: pd.Series, lookback: int = FUNDING_MOMENTUM_LOOKBACK_DAYS, + window: int = FUNDING_MOMENTUM_ZSCORE_WINDOW_DAYS, + min_periods: int = FUNDING_MOMENTUM_ZSCORE_MIN_PERIODS) -> pd.Series: + """V26 (Directiva Head Quant) -- Z-score móvil (rolling, SOLO pasado) de + la VARIACIÓN del funding rate sobre `lookback` días (diff, no nivel) -- + si el crowding en derivados se está ACELERANDO o DESHACIENDO. Señal + complementaria y categóricamente distinta a `compute_funding_rate_zscore` + (que mide el NIVEL relativo, no su velocidad): dos activos con el MISMO + FUNDING_RATE_ZSCORE pueden estar en fases opuestas -- crowding recién + formado (momentum aún subiendo) vs. crowding ya en reversión (momentum + cayendo pese a nivel todavía alto) -- información que un z-score de + nivel puro no puede distinguir. Reutiliza el MISMO `daily_funding` ya + fetcheado/cacheado por `_fetch_binance_funding_history` en + `engineer_asset` -- cero llamada de red adicional.""" + momentum = daily_funding.diff(lookback) + mean = momentum.rolling(window, min_periods=min_periods).mean() + std = momentum.rolling(window, min_periods=min_periods).std() + z = (momentum - mean) / std.replace(0.0, np.nan) + return z.clip(-FUNDING_MOMENTUM_ZSCORE_CLIP, FUNDING_MOMENTUM_ZSCORE_CLIP).fillna(0.0) + + +def _fetch_onchain_activity(chart: str = ONCHAIN_CHART_NAME) -> Optional[pd.Series]: + """ + Serie diaria de actividad on-chain BTC vía blockchain.info `/charts` -- + endpoint público, SIN API key, historial completo (`timespan=all`) en una + sola llamada. BTC ÚNICAMENTE: no existe un equivalente gratuito con + historial largo verificado para ETH (Etherscan expone gas/supply EN VIVO + con key gratuita, pero sus series históricas diarias de varios años viven + detrás de su tier de pago) -- no se inventa ese dato para ETH-USD, ver + `engineer_asset`: queda en 0.0 neutro, mismo patrón que FEAR_GREED_INDEX + para tickers no-cripto. + """ + try: + resp = requests.get( + BLOCKCHAIN_INFO_CHART_URL.format(chart=chart), + params={"timespan": "all", "format": "json", "sampled": "false"}, + timeout=20, + ) + resp.raise_for_status() + values = resp.json().get("values", []) + except Exception as exc: # noqa: BLE001 -- proveedor opcional, jamás tumba el pipeline + logger.debug("blockchain.info/charts/%s falló: %r", chart, exc) + return None + if not values: + return None + idx = pd.to_datetime([v["x"] for v in values], unit="s").normalize() + series = pd.Series([v["y"] for v in values], index=idx, dtype=float) + return series.groupby(level=0).mean().sort_index() + + +def _ffd_weights(d: float, thresh: float) -> np.ndarray: + """Pesos de Fixed-Width Window Fractional Differencing (López de Prado, + AFML cap. 5, ec. 5.1-5.2). `w[0]=1` (peso del valor actual); decae vía la + recursión `w_k = -w_{k-1}*(d-k+1)/k` y se trunca en `thresh` (peso + despreciable) -- ventana FINITA y CAUSAL por construcción: cada salida + usa solo `values[t], values[t-1], ..., values[t-width+1]`.""" + w = [1.0] + k = 1 + while True: + w_k = -w[-1] * (d - k + 1) / k + if abs(w_k) < thresh: + break + w.append(w_k) + k += 1 + return np.array(w, dtype=np.float64) + + +def frac_diff_ffd(log_price: pd.Series, d: float, thresh: float = FRAC_DIFF_THRESH) -> pd.Series: + """Serie fraccionalmente diferenciada de `log_price` -- causal, sin fuga: + la salida en `t` depende solo de `log_price[t], ..., log_price[t-width+1]`. + Los primeros `width-1` puntos quedan NaN (warm-up, misma convención que + RSI_14/ADX_14/etc. -- se recortan en el `dropna()` final de `engineer_asset`).""" + w = _ffd_weights(d, thresh) + width = len(w) + values = log_price.to_numpy(dtype=np.float64) + out = np.full(len(values), np.nan, dtype=np.float64) + for i in range(width - 1, len(values)): + window = values[i - width + 1: i + 1][::-1] + out[i] = float(np.dot(w, window)) + return pd.Series(out, index=log_price.index) + + +def find_min_ffd_d(log_price: pd.Series, train_ratio: float = TRAIN_RATIO) -> float: + """ + Busca el `d` MÍNIMO (mayor memoria conservada) que logra estacionariedad + (ADF p-value < FRAC_DIFF_ADF_PVALUE_MAX) -- grid search AFML estándar. + CRÍTICO: el ADF corre SOLO sobre el PREFIJO de train (`train_ratio` de + `log_price`, la misma fracción que separa train/test en + `build_asset_dataset`) -- calibrar `d` contra la serie COMPLETA filtraría + información de test hacia la selección del hiperparámetro, la misma fuga + que `feature_scaler.fit(features[:split_idx])` ya evita para el resto + del tensor. + """ + if adfuller is None: + return FRAC_DIFF_DEFAULT_D + prefix_n = max(int(len(log_price) * train_ratio), 100) + train_prefix = log_price.iloc[:prefix_n] + for d in FRAC_DIFF_D_GRID: + diffed = frac_diff_ffd(train_prefix, d).dropna() + if len(diffed) < 100: + continue + try: + pval = adfuller(diffed.to_numpy(), maxlag=1, regression="c", autolag=None)[1] + except Exception as exc: # noqa: BLE001 -- ADF numéricamente inestable en algún d puntual -- se prueba el siguiente + logger.debug("ADF falló para d=%.2f: %r", d, exc) + continue + if pval < FRAC_DIFF_ADF_PVALUE_MAX: + return float(d) + return 1.0 # ningún d<1 logró estacionariedad -- d=1.0 (diferenciación entera clásica) como último recurso + + +# --------------------------------------------------------------------------- +# AUDITORÍA RESCATE 2026-08 — ALPHA NUEVO (Directiva 2: baseline >53%) +# --------------------------------------------------------------------------- +# PARKINSON_VOL_ZSCORE (equity + cripto, AMBOS regímenes -- sin neutralizar): +# proxy de volatilidad implícita 100% GRATUITO y derivado exclusivamente de +# OHLCV ya descargado (High/Low), sin requerir superficie de opciones ni +# ningún dato de pago. Parkinson (1980), "The Extreme Value Method for +# Estimating the Variance of the Rate of Return", J. Business 53(1) -- +# estimador de rango intradía ~5x más eficiente que la volatilidad +# close-to-close bajo movimiento browniano geométrico, ampliamente citado +# como sustituto libre de IV a nivel de activo individual cuando no hay +# acceso a datos de opciones. No requiere Open (no descargado por este +# pipeline de features) a diferencia de Garman-Klass/Yang-Zhang -- por eso +# se elige Parkinson y no un estimador OHLC completo. +# VOL_OF_VOL_ZSCORE (cripto ÚNICAMENTE, 0.0 neutro en equity -- mismo patrón +# que FEAR_GREED_INDEX/FUNDING_RATE_ZSCORE/etc.): volatilidad-de-la- +# volatilidad -- inestabilidad del propio régimen de vol, categoría de señal +# DISTINTA al nivel de vol (que ya captura PARKINSON_VOL_ZSCORE/ATR_PCT/ +# BB_WIDTH_20). Los clusters de volatilidad de BTC/ETH son estructuralmente +# más violentos que los de equities tradicionales (ver literatura de +# realized-volatility de criptoactivos, p.ej. Baur & Dimpfl 2018), lo que +# hace de este ratio una señal de régimen específicamente informativa en +# cripto -- se calcula 100% de OHLCV, cero llamada de red nueva. +PARKINSON_VOL_LOOKBACK_DAYS = 20 +PARKINSON_VOL_ZSCORE_WINDOW_DAYS = 60 +PARKINSON_VOL_ZSCORE_MIN_PERIODS = 20 +PARKINSON_VOL_ZSCORE_CLIP = 5.0 + +VOL_OF_VOL_LOOKBACK_DAYS = 20 +VOL_OF_VOL_ZSCORE_WINDOW_DAYS = 60 +VOL_OF_VOL_ZSCORE_MIN_PERIODS = 20 +VOL_OF_VOL_ZSCORE_CLIP = 5.0 + +# V26 (Directiva Head Quant) -- AMIHUD_ILLIQUIDITY_ZSCORE: proxy de liquidez +# de mercado (Amihud, 2002, "Illiquidity and stock returns") -- |retorno +# diario| / volumen-en-USD del mismo día, impacto de precio por dólar +# transaccionado. Categoría de señal DISTINTA a la volatilidad (PARKINSON_*/ +# ATR_PCT/BB_WIDTH_20/VOL_OF_VOL_*): un activo puede moverse mucho con +# volumen profundo detrás (alta vol, baja iliquidez) o moverse lo mismo con +# poco volumen (alta vol, ALTA iliquidez) -- son regímenes de riesgo +# distintos para el tamaño de posición/slippage real, no la misma +# información redundante. 100% derivado de OHLCV YA descargado (cero fetch +# nuevo, cero proveedor externo adicional) -- mismo criterio de costo-cero +# que PARKINSON_VOL_ZSCORE/VOL_OF_VOL_ZSCORE arriba. +AMIHUD_ZSCORE_WINDOW_DAYS = 90 +AMIHUD_ZSCORE_MIN_PERIODS = 20 +AMIHUD_ZSCORE_CLIP = 5.0 + + +def compute_parkinson_vol(high: pd.Series, low: pd.Series, + window: int = PARKINSON_VOL_LOOKBACK_DAYS) -> pd.Series: + """ + Estimador de volatilidad realizada de Parkinson (rolling, SOLO pasado -- + cero fuga): sigma_t = sqrt( mean_{ventana}( ln(H/L)^2 ) / (4*ln2) ). + Requiere únicamente High/Low del propio activo -- ya presentes en + `df` (ver `engineer_asset`). + """ + log_hl = np.log(high / low) + variance = (log_hl ** 2).rolling(window=window, min_periods=window).mean() / (4.0 * np.log(2.0)) + return np.sqrt(variance.clip(lower=0.0)) + + +def compute_parkinson_vol_zscore(parkinson_vol: pd.Series, + window: int = PARKINSON_VOL_ZSCORE_WINDOW_DAYS, + min_periods: int = PARKINSON_VOL_ZSCORE_MIN_PERIODS) -> pd.Series: + """Z-score móvil (rolling, SOLO pasado) de la vol de Parkinson -- extremidad + relativa al propio régimen reciente de volatilidad, mismo criterio que + `compute_puell_multiple_zscore`/`compute_funding_rate_zscore`.""" + mean = parkinson_vol.rolling(window, min_periods=min_periods).mean() + std = parkinson_vol.rolling(window, min_periods=min_periods).std() + z = (parkinson_vol - mean) / std.replace(0.0, np.nan) + return z.clip(-PARKINSON_VOL_ZSCORE_CLIP, PARKINSON_VOL_ZSCORE_CLIP).fillna(0.0) + + +def compute_vol_of_vol_zscore(parkinson_vol: pd.Series, + lookback: int = VOL_OF_VOL_LOOKBACK_DAYS, + window: int = VOL_OF_VOL_ZSCORE_WINDOW_DAYS, + min_periods: int = VOL_OF_VOL_ZSCORE_MIN_PERIODS) -> pd.Series: + """Z-score móvil (rolling, SOLO pasado) de la volatilidad DE la + volatilidad de Parkinson (std rolling de `parkinson_vol` sobre + `lookback` días) -- inestabilidad del régimen de vol, no su nivel.""" + vol_of_vol = parkinson_vol.rolling(lookback, min_periods=lookback).std() + mean = vol_of_vol.rolling(window, min_periods=min_periods).mean() + std = vol_of_vol.rolling(window, min_periods=min_periods).std() + z = (vol_of_vol - mean) / std.replace(0.0, np.nan) + return z.clip(-VOL_OF_VOL_ZSCORE_CLIP, VOL_OF_VOL_ZSCORE_CLIP).fillna(0.0) + + +def compute_amihud_illiquidity_zscore(log_return: pd.Series, close: pd.Series, volume: pd.Series, + window: int = AMIHUD_ZSCORE_WINDOW_DAYS, + min_periods: int = AMIHUD_ZSCORE_MIN_PERIODS) -> pd.Series: + """V26 (Directiva Head Quant) -- Z-score móvil (rolling, SOLO pasado) del + ratio de iliquidez de Amihud: |LOG_RETURN_1D| / (close * volume) del + mismo día -- extremidad relativa al propio régimen reciente de liquidez + del activo, mismo criterio de "extremidad relativa, no nivel absoluto" + que el resto de *_ZSCORE de este módulo. Valor alto -> el mercado se + movió mucho con poco volumen detrás (impacto/iliquidez elevados, + régimen frágil ante órdenes grandes); valor bajo -> mercado profundo.""" + dollar_volume = (close * volume).replace(0.0, np.nan) + amihud = log_return.abs() / dollar_volume + mean = amihud.rolling(window, min_periods=min_periods).mean() + std = amihud.rolling(window, min_periods=min_periods).std() + z = (amihud - mean) / std.replace(0.0, np.nan) + return z.clip(-AMIHUD_ZSCORE_CLIP, AMIHUD_ZSCORE_CLIP).fillna(0.0) + + +# V27 -- ¿el término ln(C/O) de Garman-Klass participó del entrenamiento? +# `engineer_asset` lo setea según exista `{ticker}_Open` en el feed; se +# persiste en scalers_dict.pkl y quanti_engine.py lo OBEDECE en vez de +# decidirlo por su cuenta: train y serve NO tienen el mismo layout OHLCV +# (fetch_feature_ohlcv devuelve High/Low/Volume, sin Open), y recalcular la +# rama en inferencia produciría un valor numéricamente distinto contra un +# feature_scaler ajustado con el otro -- desync silencioso, sin excepción. +_GK_USED_OPEN: bool = False + +# V28 -- por ticker: ¿las features overnight/intraday se entrenaron CON Open real? +# Se persiste en scalers_dict.pkl["v28_open_by_ticker"]; quanti_engine lo obedece. +_V28_OPEN_BY_TICKER: dict[str, bool] = {} + +GK_VOL_LOOKBACK_DAYS = 20 +GK_ZSCORE_WINDOW_DAYS = 60 +GK_ZSCORE_MIN_PERIODS = 20 +GK_ZSCORE_CLIP = 5.0 + +FIB_WINDOWS = (20, 50) +FIB_RATIOS = (0.382, 0.500, 0.618, 1.272) +FIB_ZSCORE_WINDOW_DAYS = 120 +FIB_ZSCORE_MIN_PERIODS = 30 +FIB_ZSCORE_CLIP = 5.0 + +OFI_LOOKBACK_DAYS = 10 +OFI_ZSCORE_WINDOW_DAYS = 90 +OFI_ZSCORE_MIN_PERIODS = 30 +OFI_ZSCORE_CLIP = 5.0 + +ENTROPY_WINDOW_DAYS = 30 +ENTROPY_SIGMA_LOOKBACK = 60 +ENTROPY_DEADZONE_SIGMA = 0.25 +ENTROPY_ZSCORE_WINDOW_DAYS = 120 +ENTROPY_ZSCORE_MIN_PERIODS = 30 +ENTROPY_ZSCORE_CLIP = 5.0 + + +def _rolling_zscore(s: pd.Series, window: int, min_periods: int, clip: float) -> pd.Series: + """Z-score móvil trailing (cero lookahead) -- mismo criterio que el resto + de los *_ZSCORE de este módulo.""" + mean = s.rolling(window, min_periods=min_periods).mean() + std = s.rolling(window, min_periods=min_periods).std() + z = (s - mean) / std.replace(0.0, np.nan) + return z.replace([np.inf, -np.inf], np.nan).clip(-clip, clip).fillna(0.0) + + +def compute_garman_klass_vol(open_: Optional[pd.Series], high: pd.Series, low: pd.Series, + close: pd.Series, window: int = GK_VOL_LOOKBACK_DAYS) -> pd.Series: + """sigma^2 = 0.5*ln(H/L)^2 - (2ln2-1)*ln(C/O)^2, media rolling. + Sin `open_` degrada al término H/L (== Parkinson salvo constante).""" + var = 0.5 * np.log(high / low) ** 2 + if open_ is not None: + var = var - (2.0 * np.log(2.0) - 1.0) * np.log(close / open_) ** 2 + var = var.replace([np.inf, -np.inf], np.nan) + return np.sqrt(var.rolling(window, min_periods=window).mean().clip(lower=0.0)) + + +def compute_fib_gap_zscore(high: pd.Series, low: pd.Series, close: pd.Series, + window: int) -> pd.Series: + """Distancia FIRMADA al nivel de Fibonacci más cercano, z-scoreada. + + pos = (C - swing_low)/(swing_high - swing_low). Swings por `.rolling()` + TRAILING -- una ventana `center=True` filtraría el futuro. El signo se + preserva: rebotar desde debajo del 0.618 y perderlo desde arriba son + estados direccionalmente opuestos; |gap| los colapsaría. + """ + swing_high = high.rolling(window, min_periods=window).max() + swing_low = low.rolling(window, min_periods=window).min() + rng = (swing_high - swing_low).replace(0.0, np.nan) + pos = (close - swing_low) / rng + + gaps = np.stack([(pos - r).to_numpy(dtype=float) for r in FIB_RATIOS], axis=1) + abs_gaps = np.abs(gaps) + all_nan = np.isnan(abs_gaps).all(axis=1) + nearest = gaps[np.arange(gaps.shape[0]), + np.where(np.isnan(abs_gaps), np.inf, abs_gaps).argmin(axis=1)] + nearest[all_nan] = np.nan + return _rolling_zscore(pd.Series(nearest, index=close.index), + FIB_ZSCORE_WINDOW_DAYS, FIB_ZSCORE_MIN_PERIODS, FIB_ZSCORE_CLIP) + + +def compute_ofi_proxy_zscore(high: pd.Series, low: pd.Series, close: pd.Series, + volume: pd.Series, lookback: int = OFI_LOOKBACK_DAYS) -> pd.Series: + """Order Flow Imbalance proxy desde OHLCV puro. + + CLV = ((C-L) - (H-C)) / (H-L) in [-1,1] -- dónde cerró el precio DENTRO + del rango de la barra, proxy de qué lado del libro absorbió. Ponderado + por volumen y normalizado por el volumen de la ventana: imbalance neto + adimensional, comparable entre activos y entre regímenes de volumen. + """ + rng = (high - low).replace(0.0, np.nan) + clv = ((close - low) - (high - close)) / rng + signed_vol = (clv * volume).replace([np.inf, -np.inf], np.nan) + num = signed_vol.rolling(lookback, min_periods=lookback).sum() + den = volume.rolling(lookback, min_periods=lookback).sum().replace(0.0, np.nan) + return _rolling_zscore((num / den), OFI_ZSCORE_WINDOW_DAYS, + OFI_ZSCORE_MIN_PERIODS, OFI_ZSCORE_CLIP) + + +def compute_return_entropy_zscore(log_return: pd.Series, + window: int = ENTROPY_WINDOW_DAYS) -> pd.Series: + """Entropía de Shannon normalizada de la serie simbolizada de retornos. + + Simbolización en 3 estados (bajista / zona muerta / alcista) con umbral + +-ENTROPY_DEADZONE_SIGMA * sigma_rolling -- el umbral se adapta al + régimen de volatilidad del propio activo en vez de ser un absoluto que + envía todo a la zona muerta en calma y nada en pánico. + H = -sum p_i ln p_i / ln 3 in [0,1]: 1 = mercado máximamente aleatorio + (sin estructura explotable), valores bajos = persistencia direccional. + """ + sigma = log_return.rolling(ENTROPY_SIGMA_LOOKBACK, + min_periods=ENTROPY_SIGMA_LOOKBACK).std() + thr = ENTROPY_DEADZONE_SIGMA * sigma + up = (log_return > thr).astype(float) + down = (log_return < -thr).astype(float) + flat = 1.0 - up - down + + h = None + for state in (up, down, flat): + p = state.rolling(window, min_periods=window).mean() + term = -(p * np.log(p.where(p > 0.0))) + h = term if h is None else h.add(term, fill_value=0.0) + h = (h / np.log(3.0)).where(sigma.notna()) + return _rolling_zscore(h, ENTROPY_ZSCORE_WINDOW_DAYS, + ENTROPY_ZSCORE_MIN_PERIODS, ENTROPY_ZSCORE_CLIP) + + +def engineer_asset(all_data: pd.DataFrame, ticker: str, macro_tickers: list[str]) -> pd.DataFrame: + """ + Frame de features de UN activo — V6, estacionariedad estricta. El precio + NUNCA entra al tensor en nivel absoluto: `close` (variable local) se usa + para DERIVAR razones/retornos, pero el único remanente de nivel absoluto + que sobrevive en el DataFrame devuelto es `RAW_CLOSE` — una columna de + bookkeeping EXCLUIDA de `feature_cols` en `build_asset_dataset` (nunca + toca el `feature_scaler`/el tensor de entrada), usada solo para + reconstruir `last_price`/el target de log-return. Los factores macro + siguen transformándose a log-return ANTES del feature_scaler (V4, + sin cambios). + + V15 (consolidación del core): `all_data` ya llega con los macro + tickers pre-alineados al calendario real del régimen (24/7 cripto o + 5/7 equity) por `_fetch_all_symbols_flat`/`kodaquant_core. + project_macro_frame` -- el `.ffill().dropna()` de abajo ya NO es la + única defensa contra el hueco de fin de semana/feriado (esa lógica + vive ahora en una única fuente de verdad, compartida con inferencia), + solo limpia remanentes menores (ej. el burn-in inicial de indicadores). + """ + close_col = f"{ticker}_Close" + high_col = f"{ticker}_High" + low_col = f"{ticker}_Low" + vol_col = f"{ticker}_Volume" + macro_close_cols = [f"{m}_Close" for m in macro_tickers] + + df = all_data[[close_col, high_col, low_col, vol_col] + macro_close_cols].copy() + rows_before = len(df) + df = df.ffill().dropna() + + if df.empty: + # Diagnóstico específico (V16): reemplaza el `ValueError` críptico de + # sklearn en `build_asset_dataset` (~700 líneas más abajo, "Found + # array with 0 sample(s)") por un mensaje que apunta directo a la + # columna responsable -- causa más común: un macro ticker sin UN + # SOLO dato real en todo `all_data` (símbolo roto/deslistado en + # Yahoo Finance), que el `dropna()` de arriba (exige TODAS las + # columnas no-nulas por fila, sin cambios de política) vacía por + # completo. Cero impacto en el pipeline cuando `df` no queda vacío. + raw = all_data[[close_col, high_col, low_col, vol_col] + macro_close_cols] + fully_nan_cols = [c for c in raw.columns if raw[c].isna().all()] + raise ValueError( + f"'{ticker}': el DataFrame de features quedó VACÍO tras " + f"ffill().dropna() ({rows_before} fila(s) antes -> 0 después). " + + (f"Columna(s) 100% NaN en TODO el historial descargado: " + f"{fully_nan_cols} -- revisá esa fuente (ver también el " + "'[Diagnóstico cobertura]' logueado por _fetch_all_symbols_flat " + "más arriba en esta misma corrida)." + if fully_nan_cols else + "Ninguna columna individual está 100% NaN -- es un problema de " + "SUPERPOSICIÓN de fechas entre columnas (ej. un macro ticker con " + "historial mucho más corto que el resto, sin fechas en común " + "con el activo objetivo).") + ) + + close, high, low, volume = df[close_col], df[high_col], df[low_col], df[vol_col] + + for macro_close_col in macro_close_cols: + macro_price = df[macro_close_col] + df[macro_close_col] = np.log(macro_price / macro_price.shift(1)) + + # --- RAW_CLOSE: bookkeeping puro (last_price / target de log-return en + # build_asset_dataset) — jamás forma parte de feature_cols/del tensor. + df["RAW_CLOSE"] = close + # --- LOG_RETURN_1D reemplaza a "PRICE" como ÚNICO input de nivel-precio: + # estacionario por construcción, misma escala sin importar el precio + # absoluto del activo (SPY a $600 o a $6 producen la MISMA distribución + # de LOG_RETURN_1D) — esto es lo que elimina la ceguera ante ATH en la + # raíz, no un parche sobre el output. + df["LOG_RETURN_1D"] = np.log(close / close.shift(1)) + + df["RSI_14"] = compute_rsi(close) # oscilador ya acotado [0,100] — sin cambios + + ema_20 = close.ewm(span=20, adjust=False).mean() + df["EMA20_DEV_PCT"] = (close - ema_20) / ema_20 # % de desviación vs. la propia media móvil + + macd_line, signal_line = compute_macd(close) + df["MACD_PCT"] = macd_line / close # normalizado por nivel de precio + df["MACD_SIGNAL_PCT"] = signal_line / close + + asset_log_return = df["LOG_RETURN_1D"] + proxy_ticker = SENTIMENT_MACRO_PROXY if SENTIMENT_MACRO_PROXY in macro_tickers else macro_tickers[0] + proxy_log_return = df[f"{proxy_ticker}_Close"] + df["SENTIMENT_SCORE"] = compute_sentiment_score(asset_log_return, proxy_log_return, SENTIMENT_LOOKBACK) + + atr = compute_atr(high, low, close) + df["ATR_PCT"] = atr / close # "ATRP" — volatilidad absoluta normalizada por precio + df["BB_WIDTH_20"] = compute_bb_width(close) # YA es 2σ/μ — adimensional, sin cambios + + obv = compute_obv(close, volume) + obv_roc = obv.pct_change(periods=OBV_ROC_LOOKBACK_DAYS) + df["OBV_ROC_20"] = obv_roc.replace([np.inf, -np.inf], np.nan).clip(-OBV_ROC_CLIP, OBV_ROC_CLIP).fillna(0.0) + + df["ADX_14"] = compute_adx(high, low, close) # ya acotado [0,100] — sin cambios + df["STOCH_K_14"] = compute_stochastic_k(high, low, close) # ya acotado [0,100] — sin cambios + + # --- V5 (Requerimiento 1): NEWS_SENTIMENT_SCORE vía yfinance/Finnhub + FinBERT. + # Se alinea temporalmente contra el índice YA depurado del activo, ANTES + # de recortar filas por ffill/dropna final, igual que el resto de técnicos. + df["NEWS_SENTIMENT_SCORE"] = get_daily_news_sentiment(ticker, df.index) + +# --- V21: FEAR_GREED_INDEX (cripto) -- ver `_fetch_fear_greed_index` arriba + # de esta función. Señal de PSICOLOGÍA de mercado, categoría distinta a + # FUNDING_RATE (revertido en V17). Para tickers NO-cripto la columna + # queda en 50.0 (neutro) constante -- CERO impacto en equity_specialist. + if ticker in REGIMES["crypto_specialist"]["tickers"]: + cache_key = "fear_greed_index" + cached_fg = _ohlcv_cache.get_dataframe(cache_key) + fg_series = cached_fg.iloc[:, 0] if cached_fg is not None and not cached_fg.empty else None + if fg_series is None: + fg_series = _fetch_fear_greed_index(tail_days=3700) + if fg_series is not None and not fg_series.empty: + _ohlcv_cache.set_dataframe(cache_key, fg_series.to_frame("fg")) + if fg_series is not None and not fg_series.empty: + fg_series.index = normalize_daily_index(pd.DatetimeIndex(fg_series.index)) + df["FEAR_GREED_INDEX"] = fg_series.reindex(df.index).ffill().fillna(50.0) + else: + df["FEAR_GREED_INDEX"] = 50.0 + else: + df["FEAR_GREED_INDEX"] = 50.0 + + # --- V24: FUNDING_RATE_ZSCORE (derivados -- extremidad de posicionamiento) --- + if ticker in REGIMES["crypto_specialist"]["tickers"]: + funding_cache_key = f"funding_rate_{ticker}" + cached_funding = _ohlcv_cache.get_dataframe(funding_cache_key) + funding_series = cached_funding.iloc[:, 0] if cached_funding is not None and not cached_funding.empty else None + if funding_series is None: + funding_series = _fetch_binance_funding_history(ticker) + if funding_series is not None and not funding_series.empty: + _ohlcv_cache.set_dataframe(funding_cache_key, funding_series.to_frame("funding")) + if funding_series is not None and not funding_series.empty: + funding_series.index = normalize_daily_index(pd.DatetimeIndex(funding_series.index)) + funding_z_full = compute_funding_rate_zscore(funding_series) + df["FUNDING_RATE_ZSCORE"] = funding_z_full.reindex(df.index).ffill().fillna(0.0) + # V26 -- FUNDING_RATE_MOMENTUM_ZSCORE: reutiliza el MISMO + # funding_series ya fetcheado/cacheado arriba (cero llamada de + # red adicional) -- ver docstring de + # compute_funding_rate_momentum_zscore. + funding_mom_z_full = compute_funding_rate_momentum_zscore(funding_series) + df["FUNDING_RATE_MOMENTUM_ZSCORE"] = funding_mom_z_full.reindex(df.index).ffill().fillna(0.0) + else: + df["FUNDING_RATE_ZSCORE"] = 0.0 + df["FUNDING_RATE_MOMENTUM_ZSCORE"] = 0.0 + else: + df["FUNDING_RATE_ZSCORE"] = 0.0 + df["FUNDING_RATE_MOMENTUM_ZSCORE"] = 0.0 + + # --- V25 (reestructuración Alpha Cripto, auditoría rescate 2026-08): + # ONCHAIN_ACTIVITY_ROC ahora es NVT Ratio Z-score (Woo/Burniske) -- + # MISMO nombre de columna/slot de TECH_COLS (BTC únicamente, 0.0 neutro + # en ETH/equity, CERO cambio de N_FEATURES/shape), pero categoría de + # señal distinta: valuación de red relativa a USO real, no solo + # actividad bruta de transacciones. V24 (tx-count ROC crudo) se conserva + # como fallback si el chart de volumen USD no responde -- nunca peor + # que la señal V24 previa, nunca silenciosamente 0.0 si CUALQUIERA de + # los dos providers de blockchain.info está arriba. + if ticker == "BTC-USD": + txval_cache_key = "onchain_tx_value_usd_btc" + cached_txval = _ohlcv_cache.get_dataframe(txval_cache_key) + tx_value_series = cached_txval.iloc[:, 0] if cached_txval is not None and not cached_txval.empty else None + if tx_value_series is None: + tx_value_series = _fetch_onchain_tx_volume_usd() + if tx_value_series is not None and not tx_value_series.empty: + _ohlcv_cache.set_dataframe(txval_cache_key, tx_value_series.to_frame("tx_value_usd")) + if tx_value_series is not None and not tx_value_series.empty: + tx_value_series.index = normalize_daily_index(pd.DatetimeIndex(tx_value_series.index)) + nvt_z_full = compute_nvt_ratio_zscore(close, tx_value_series.reindex(df.index).ffill()) + df["ONCHAIN_ACTIVITY_ROC"] = nvt_z_full.reindex(df.index).fillna(0.0) + else: + # Fallback V24 -- tx-count ROC crudo, si el chart de volumen USD no responde. + onchain_cache_key = "onchain_activity_btc" + cached_onchain = _ohlcv_cache.get_dataframe(onchain_cache_key) + onchain_series = cached_onchain.iloc[:, 0] if cached_onchain is not None and not cached_onchain.empty else None + if onchain_series is None: + onchain_series = _fetch_onchain_activity() + if onchain_series is not None and not onchain_series.empty: + _ohlcv_cache.set_dataframe(onchain_cache_key, onchain_series.to_frame("onchain")) + if onchain_series is not None and not onchain_series.empty: + onchain_series.index = normalize_daily_index(pd.DatetimeIndex(onchain_series.index)) + onchain_roc_full = onchain_series.pct_change(periods=ONCHAIN_ROC_LOOKBACK_DAYS) + onchain_roc_full = onchain_roc_full.replace([np.inf, -np.inf], np.nan).clip(-ONCHAIN_ROC_CLIP, ONCHAIN_ROC_CLIP) + df["ONCHAIN_ACTIVITY_ROC"] = onchain_roc_full.reindex(df.index).ffill().fillna(0.0) + else: + df["ONCHAIN_ACTIVITY_ROC"] = 0.0 + else: + df["ONCHAIN_ACTIVITY_ROC"] = 0.0 + + # --- V23.5 (Directiva 3): PUELL_MULTIPLE_ZSCORE -- ciclo de rentabilidad + # de minero, BTC ÚNICAMENTE, cero fetch (ver bloque de constantes + # `BTC_HALVING_SCHEDULE`/`compute_puell_multiple_zscore` más arriba). --- + if ticker == "BTC-USD": + df["PUELL_MULTIPLE_ZSCORE"] = compute_puell_multiple_zscore(close) + else: + df["PUELL_MULTIPLE_ZSCORE"] = 0.0 + + # --- V24: FRAC_DIFF_LOG_CLOSE (memoria + estacionariedad, López de Prado) --- + if ticker in REGIMES["crypto_specialist"]["tickers"]: + raw_log_price = np.log(close) + ffd_d = find_min_ffd_d(raw_log_price) + df["FRAC_DIFF_LOG_CLOSE"] = frac_diff_ffd(raw_log_price, ffd_d) + _LAST_FFD_D_BY_TICKER[ticker] = float(ffd_d) # ver run_regime_pipeline -- persistido en scalers_dict.pkl + logger.info("[FRAC_DIFF] %s -> d=%.2f (memoria preservada, calibrado por ADF sobre prefijo de train).", + ticker, ffd_d) + else: + df["FRAC_DIFF_LOG_CLOSE"] = 0.0 + + # --- AUDITORÍA RESCATE 2026-08 (Directiva 2): PARKINSON_VOL_ZSCORE ----- + # AMBOS regímenes -- proxy libre de volatilidad implícita, ver docstring + # arriba de `compute_parkinson_vol`. Requiere High/Low, ya en `df`. + parkinson_vol = compute_parkinson_vol(high, low) + df["PARKINSON_VOL_ZSCORE"] = compute_parkinson_vol_zscore(parkinson_vol) + + # --- AUDITORÍA RESCATE 2026-08 (Directiva 2): VOL_OF_VOL_ZSCORE --------- + # Cripto ÚNICAMENTE -- 0.0 neutro en equity, mismo patrón que + # FEAR_GREED_INDEX/FUNDING_RATE_ZSCORE/ONCHAIN_ACTIVITY_ROC arriba. + if ticker in REGIMES["crypto_specialist"]["tickers"]: + df["VOL_OF_VOL_ZSCORE"] = compute_vol_of_vol_zscore(parkinson_vol) + else: + df["VOL_OF_VOL_ZSCORE"] = 0.0 + + # --- V26 (Directiva Head Quant): AMIHUD_ILLIQUIDITY_ZSCORE -------------- + # Cripto ÚNICAMENTE -- 0.0 neutro en equity, mismo patrón que + # VOL_OF_VOL_ZSCORE/FUNDING_RATE_ZSCORE arriba. 100% OHLCV ya en scope + # (LOG_RETURN_1D/close/volume) -- cero fetch nuevo. + if ticker in REGIMES["crypto_specialist"]["tickers"]: + df["AMIHUD_ILLIQUIDITY_ZSCORE"] = compute_amihud_illiquidity_zscore(df["LOG_RETURN_1D"], close, volume) + else: + df["AMIHUD_ILLIQUIDITY_ZSCORE"] = 0.0 + + # --- V27: microestructura OHLC + geometría fractal + flujo + caos ------ + # AMBOS regímenes, 100% OHLCV ya en scope -- cero fetch nuevo. + global _GK_USED_OPEN + _open_col = close_col.replace("Close", "Open") + _open = df[_open_col] if _open_col in df.columns else None + _GK_USED_OPEN = _open is not None + if _open is None: + logger.warning("[GK] '%s': columna Open ausente -> GARMAN_KLASS_VOL_ZSCORE " + "degrada al término H/L (Parkinson salvo constante).", ticker) + df["GARMAN_KLASS_VOL_ZSCORE"] = _rolling_zscore( + compute_garman_klass_vol(_open, high, low, close), + GK_ZSCORE_WINDOW_DAYS, GK_ZSCORE_MIN_PERIODS, GK_ZSCORE_CLIP) + + for _w in FIB_WINDOWS: + df[f"FIB_GAP_Z_{_w}"] = compute_fib_gap_zscore(high, low, close, _w) + + df["OFI_PROXY_ZSCORE"] = compute_ofi_proxy_zscore(high, low, close, volume) + df["RETURN_ENTROPY_ZSCORE"] = compute_return_entropy_zscore(df["LOG_RETURN_1D"]) + + # --- V28: free_alpha.py (una sola implementación, train == serve) ------ + # Cripto -> 4 cols de flujo; equity -> 4 cols overnight/intraday/rel-strength. + # El bloque del régimen opuesto queda en 0.0 (mismo patrón que FUNDING_RATE en equity). + if ticker in REGIMES["crypto_specialist"]["tickers"]: + for _c in V28_EQUITY_COLS: + df[_c] = 0.0 + _flow = build_crypto_flow_features( + ticker, df.index, cache=None if FORCE_FRESH_DATA else _ohlcv_cache) + if len(_flow) != len(df): + raise RuntimeError(f"[V28] '{ticker}': flujo cripto len={len(_flow)} != len(df)={len(df)}.") + for _c in V28_CRYPTO_COLS: + df[_c] = _flow[_c].to_numpy(dtype=float) + _V28_OPEN_BY_TICKER[ticker] = False + else: + for _c in V28_CRYPTO_COLS: + df[_c] = 0.0 + _v28_open = None + _v28_open_col = f"{ticker}_Open" + if _v28_open_col in all_data.columns: + _v28_open = all_data[_v28_open_col].reindex(df.index) + if _v28_open.notna().mean() < 0.9: + logger.warning("[V28] '%s': Open con <90%% de cobertura -> overnight/intraday = 0.0.", ticker) + _v28_open = None + _V28_OPEN_BY_TICKER[ticker] = _v28_open is not None + # `^GSPC_Close` YA es log-return aquí (loop macro de arriba). + _spx_col = "^GSPC_Close" + _eq = compute_equity_open_features( + _v28_open, close, df[_spx_col] if _spx_col in df.columns else None, ticker) + for _c in V28_EQUITY_COLS: + df[_c] = _eq[_c] + + df = df.ffill().dropna() + + feature_cols = ["LOG_RETURN_1D"] + TECH_COLS + macro_close_cols + result = df[["RAW_CLOSE"] + feature_cols].copy() + result.columns = ["RAW_CLOSE", "LOG_RETURN_1D"] + TECH_COLS + macro_tickers + return result + + +def compute_triple_barrier_labels(df_asset: pd.DataFrame, pt_mult: float, sl_mult: float, + max_holding_days: int, vol_lookback: int, + min_vol: float = TRIPLE_BARRIER_MIN_VOL) -> pd.DataFrame: + """ + Triple Barrier Method (López de Prado, cap. 3) sobre cierres diarios. + Para cada día de entrada `s` (precio hipotético de entrada = close_s): + + barrera_superior_s = close_s * exp(+pt_mult * vol_s) + barrera_inferior_s = close_s * exp(-sl_mult * vol_s) + + con `vol_s` = desvío estándar de LOG_RETURN_1D en una ventana móvil de + `vol_lookback` días TERMINADA en `s` (SOLO pasado -- cero fuga hacia + el futuro en el ANCHO de la barrera; la ETIQUETA en sí es + necesariamente forward-looking, como cualquier target supervisado). + + Recorre los cierres de s+1 .. s+max_holding_days (barrera vertical) y + determina cuál barrera se toca PRIMERO: + +1 ("TP") -- close cruza la barrera superior primero + -1 ("SL") -- close cruza la barrera inferior primero + 0 ("TIMEOUT") -- ninguna barrera se toca -- barrera vertical, + "sin convicción" en el espíritu de meta-labeling + + LIMITACIÓN CONOCIDA (documentada, no oculta): con cierre diario (sin + OHLC intradía) un único valor de cierre por día no puede cruzar ambas + barreras a la vez, así que no hay ambigüedad de ORDEN intra-día -- pero + tampoco hay forma de saber si, DENTRO de un día dado, el máximo/mínimo + intradía tocó una barrera que el cierre no refleja. El primer-toque + intradía real requeriría barras horarias/tick -- fuera del alcance + 100%-gratuito de este pipeline (Restricción de Datos, directiva Head + Quant). Sesgo esperado: subestima levemente la frecuencia de toques + (barreras algo más "difíciles" de activar que con datos intradía). + + Devuelve un DataFrame alineado a `df_asset.index` con: + TB_LABEL -1/0/+1 (NaN en warm-up de `vol_lookback` o en + la cola sin suficiente futuro para resolver + `max_holding_days` -- se filtra aguas abajo) + TB_REALIZED_RETURN log-return REAL logrado al momento del exit + (barrera tocada o vertical) -- análogo de + `r_true` en el régimen de regresión; es lo + que usa `pnl_backtest.py` como P&L de la + apuesta y `sample_weight` (ver + `build_asset_dataset`) como su magnitud. + TB_BARS_TO_EXIT días hábiles hasta el exit (diagnóstico). + """ + close = df_asset["RAW_CLOSE"].to_numpy(dtype=np.float64) + log_ret_1d = df_asset["LOG_RETURN_1D"].to_numpy(dtype=np.float64) + n = len(close) + + vol = ( + pd.Series(log_ret_1d, index=df_asset.index) + .rolling(vol_lookback, min_periods=vol_lookback) + .std() + .to_numpy(dtype=np.float64) + ) + vol = np.maximum(vol, min_vol) + + labels = np.full(n, np.nan, dtype=np.float64) + realized_return = np.full(n, np.nan, dtype=np.float64) + bars_to_exit = np.full(n, np.nan, dtype=np.float64) + + for s in range(n): + if np.isnan(vol[s]) or s + max_holding_days >= n: + continue # vol insuficiente (warm-up) o cola sin futuro suficiente -- NaN, se filtra en build_asset_dataset + + entry_price = close[s] + upper = entry_price * np.exp(pt_mult * vol[s]) + lower = entry_price * np.exp(-sl_mult * vol[s]) + + exit_label = 0.0 + exit_ret = float(np.log(close[s + max_holding_days] / entry_price)) # default: barrera vertical + exit_bars = float(max_holding_days) + for h in range(1, max_holding_days + 1): + price_h = close[s + h] + if price_h >= upper: + exit_label, exit_ret, exit_bars = 1.0, float(np.log(price_h / entry_price)), float(h) + break + if price_h <= lower: + exit_label, exit_ret, exit_bars = -1.0, float(np.log(price_h / entry_price)), float(h) + break + + labels[s] = exit_label + realized_return[s] = exit_ret + bars_to_exit[s] = exit_bars + + return pd.DataFrame( + {"TB_LABEL": labels, "TB_REALIZED_RETURN": realized_return, "TB_BARS_TO_EXIT": bars_to_exit}, + index=df_asset.index, + ) + + +def purged_fold_bounds(n: int, k: int, embargo_frac: float = 0.02) -> list[tuple[int, int, int]]: + """ + V27 -- Purged K-Fold (un solo path walk-forward por fold, NO la + combinatoria completa C(n_groups, n_test_groups) -- a ese costo, en este + hardware, un CPCV de 6-eligiendo-2 sobre equity_specialist (~150s/época) + son horas por régimen. Un Purged K-Fold de k bloques contiguos da la + misma auditoría de varianza OOS que preocupa (¿el 52.6% depende del + split que elegiste?) a 1/C(n,r) del costo). + + Cada fold define un bloque de test contiguo `[test_start, test_end)` + sobre las `n` filas del DataFrame de UN activo, YA en orden temporal. + Devuelve `(test_start, test_end, embargo_end)` por fold -- el caller + (Fase 2, próximo paso) es responsable de purgar del train cualquier + fila cuyo horizonte de etiqueta caiga en `[test_start, embargo_end)`, + exactamente la misma lógica de `embargo_violation` que ya existe en + `build_asset_dataset` para el split único -- acá generalizada a k + bloques en vez de 1. + + No toca `build_asset_dataset` ni ningún pipeline de training existente + -- es aritmética de índices pura, verificable sola. + """ + if k < 2: + raise ValueError(f"purged_fold_bounds: k debe ser >= 2 (recibido {k})") + bounds = np.linspace(0, n, k + 1, dtype=int) + embargo = max(1, int(n * embargo_frac)) + folds = [] + for i in range(k): + test_start, test_end = int(bounds[i]), int(bounds[i + 1]) + if test_end <= test_start: + continue + embargo_end = min(n, test_end + embargo) + folds.append((test_start, test_end, embargo_end)) + return folds + + +def build_asset_dataset(df: pd.DataFrame, ticker: str, lookback: int, train_ratio: float, + asset_to_id: dict[str, int], target_mode: str = "regression", + tb_params: dict | None = None, exclude_timeout_from_train: bool = False): + """ + Ventanas (X) + targets para UN activo, con scalers propios por activo. + + `target_mode="regression"` (default, `equity_specialist`): CERO + cambios respecto al pipeline V5/V6 original -- target = log-return + continuo, `StandardScaler(with_mean=False)`. + + `target_mode="triple_barrier"` (V22, `crypto_specialist`): target = + clase 3-way (SL/TIMEOUT/TP) de `compute_triple_barrier_labels`, + one-hot. La ventana de features sigue terminando en `t-1` (mismo + contrato que el régimen de regresión: predicción usa SOLO información + hasta `t-1`); la "entrada" hipotética de la apuesta Triple Barrier es + `close[t-1]` -- mismo índice que `last_price[t-1]` ya usaba el régimen + de regresión, cero drift de convención entre ambos modos. Filas cuya + etiqueta cae en la cola sin `max_holding_days` de futuro suficiente + (`TB_LABEL` = NaN) se SALTEAN por completo (no se agregan a X/y) -- + reduce el tamaño de test en, como mucho, `max_holding_days` filas. + """ + feature_cols = ["LOG_RETURN_1D"] + TECH_COLS + MACRO_TICKERS + # RAW_CLOSE es bookkeeping puro (ver engineer_asset) — nunca entra a + # `features`/al feature_scaler, solo se usa para derivar `last_price`, + # el target de log-return (regresión) y el precio de entrada Triple + # Barrier (clasificación). + prices = df["RAW_CLOSE"].values + features = df[feature_cols].values + log_returns = np.diff(np.log(prices)) + + n = len(df) + split_idx = int(n * train_ratio) + + feature_scaler = MinMaxScaler(feature_range=(0, 1)) + feature_scaler.fit(features[:split_idx]) + features_scaled = feature_scaler.transform(features) + + tb_label_arr = tb_return_arr = None + if target_mode == "triple_barrier": + tb_params = tb_params or {} + tb = compute_triple_barrier_labels( + df, + pt_mult=tb_params.get("pt_mult", TRIPLE_BARRIER_PT_MULT), + sl_mult=tb_params.get("sl_mult", TRIPLE_BARRIER_SL_MULT), + max_holding_days=tb_params.get("max_holding_days", TRIPLE_BARRIER_MAX_HOLDING_DAYS), + vol_lookback=tb_params.get("vol_lookback", TRIPLE_BARRIER_VOL_LOOKBACK), + ) + tb_label_arr = tb["TB_LABEL"].to_numpy() + tb_return_arr = tb["TB_REALIZED_RETURN"].to_numpy() + tb_bars_arr = tb["TB_BARS_TO_EXIT"].to_numpy() + + X, y_raw, last_price, dates = [], [], [], [] + tb_class_idx_list, tb_ret_list, tb_entry_idx_list, tb_bars_list = [], [], [], [] + for t in range(lookback, n): + entry_idx = t - 1 + if target_mode == "triple_barrier" and np.isnan(tb_label_arr[entry_idx]): + continue # cola sin max_holding_days de futuro (o warm-up de vol) -- se saltea la fila entera + X.append(features_scaled[t - lookback: t]) + last_price.append(prices[entry_idx]) + dates.append(df.index[t]) + if target_mode == "triple_barrier": + tb_class_idx_list.append(TB_LABEL_TO_CLASS_IDX[int(tb_label_arr[entry_idx])]) + tb_ret_list.append(tb_return_arr[entry_idx]) + tb_entry_idx_list.append(entry_idx) + tb_bars_list.append(tb_bars_arr[entry_idx]) + else: + y_raw.append(log_returns[entry_idx]) + + X = np.array(X, dtype=np.float32) + last_price = np.array(last_price, dtype=np.float32) + dates = pd.DatetimeIndex(dates) + asset_id = np.full((len(X),), asset_to_id[ticker], dtype=np.int32) + + # `window_split` cuenta POSICIONES del loop -- idéntico al cómputo + # original. Con target_mode="triple_barrier" se saltean filas de la + # COLA (después de split_idx en la inmensa mayoría de los casos, ver + # docstring); el clip defensivo cubre el caso límite de un fold/test + # tan angosto que la cola sin-futuro invada el propio split. + window_split = max(0, min(split_idx - lookback, len(X))) + + if target_mode == "triple_barrier": + tb_class_idx = np.array(tb_class_idx_list, dtype=np.int32) + tb_ret = np.array(tb_ret_list, dtype=np.float32) + y_onehot = np.eye(3, dtype=np.float32)[tb_class_idx] + + # --- sample_weight -- Directiva 3 (Risk-Adjusted Loss) ------------ + # Pondera cada muestra por la MAGNITUD del retorno real logrado en + # esa apuesta (normalizada por la mediana de |retorno| en TRAIN YA + # PURGADO -- ver bloque de embargo justo abajo --, clip [0.25x, 4x] + # para que un outlier puntual no domine el gradiente de una época + # entera). El modelo paga más caro equivocarse en un día de + # colapso/despegue (+5%, ver directiva) que en uno aburrido -- + # exactamente lo pedido, separado del balanceo de CLASE (ese lo + # resuelve `alpha` en CategoricalFocalCrossentropy, ver + # `build_model`/`run_regime_pipeline`). `entry_idx_arr`/`bars_arr` + # (V23, uniqueness -- ver `_average_uniqueness`) se calculan ACÁ + # porque el embargo de abajo los necesita antes de poder derivar + # `train_keep`/`test_keep`. + entry_idx_arr = np.array(tb_entry_idx_list, dtype=np.int64) + bars_arr = np.array(tb_bars_list, dtype=np.float64) + + # --- EMBARGO/PURGE (López de Prado cap. 7 -- el mismo texto ya citado en + # el docstring de esta función) -- una apuesta de TRAIN cuyo exit + # (entry_idx + bars_to_exit) cae EN o DESPUÉS de `window_split` tiene su + # propia etiqueta (TB_LABEL/TB_REALIZED_RETURN) determinada observando + # precios que ya pertenecen a `test` -- fuga real, aunque acotada (a lo + # sumo `max_holding_days` filas por activo), nunca antes purgada en este + # pipeline. Se DESCARTA la fila completa de train (no se trunca el + # retorno) -- `test` no se toca, sus propios exits miran hacia adelante + # dentro de datos reales/futuros, sin cruzar hacia train. + is_train_row = entry_idx_arr < window_split + embargo_violation = is_train_row & ((entry_idx_arr + bars_arr) >= window_split) + train_keep = is_train_row & ~embargo_violation + test_keep = ~is_train_row + if embargo_violation.any(): + logger.info( + "[Embargo TB] %d fila(s) de train purgadas por fuga de horizonte hacia test " + "(López de Prado cap. 7).", int(embargo_violation.sum()), + ) + + uniqueness = _average_uniqueness(entry_idx_arr, bars_arr, n) + uniqueness_train_mean = float(np.mean(uniqueness[train_keep])) if train_keep.any() else 1.0 + uniqueness_norm = uniqueness / max(uniqueness_train_mean, 1e-8) + + # `train_mag_median` (arriba) ya se calculó sobre `tb_ret[:window_split]` + # -- con el embargo activo, esas pocas filas fronterizas purgadas no + # deberían inflar la mediana de magnitud; recalculada acá sobre la + # máscara real de train para mantener ambos pesos (pnl/uniqueness) + # consistentes con el mismo conjunto de filas que finalmente se entrena. + train_mag_purged = np.abs(tb_ret[train_keep]) + positive_mag_purged = train_mag_purged[train_mag_purged > 0] + train_mag_median_purged = float(np.median(positive_mag_purged)) if positive_mag_purged.size else 1.0 + pnl_weight = np.abs(tb_ret) / max(train_mag_median_purged, 1e-8) + + sample_weight = np.clip(pnl_weight * uniqueness_norm, 0.25, 4.0).astype(np.float32) + + # V27 -- opt-in (default False = CERO cambio de comportamiento en + # cualquier caller existente). Evidencia de 3 experimentos + # independientes (bias-cal bias=0.00 óptimo, meta-labeling no + # generalizó, recall TIMEOUT std=0% en 4 folds) apunta a que + # TIMEOUT no tiene firma aprendible con las features actuales -- + # esto deja de pedírselo al modelo EN TRAIN. `test` NUNCA se toca: + # sigue evaluando las 3 clases reales, comparable contra cada + # corrida anterior de esta sesión sin ningún ajuste. + train_keep_final = train_keep + if exclude_timeout_from_train: + train_keep_final = train_keep & (tb_class_idx != TB_TIMEOUT_CLASS_IDX) + logger.info(" [2-CLASE] '%s': %d/%d filas de train excluidas (TIMEOUT).", + ticker, int((train_keep & ~train_keep_final).sum()), int(train_keep.sum())) + + train = dict( + X=X[train_keep_final], y=y_onehot[train_keep_final], asset_id=asset_id[train_keep_final], + last_price=last_price[train_keep_final], dates=dates[train_keep_final], + sample_weight=sample_weight[train_keep_final], y_return=tb_ret[train_keep_final], + y_class_idx=tb_class_idx[train_keep_final], + ) + test = dict( + X=X[test_keep], y=y_onehot[test_keep], asset_id=asset_id[test_keep], + last_price=last_price[test_keep], dates=dates[test_keep], + sample_weight=sample_weight[test_keep], y_return=tb_ret[test_keep], + y_class_idx=tb_class_idx[test_keep], + ) + return train, test, feature_scaler, None + + # --- target_mode == "regression" (default) — CERO cambios respecto al + # pipeline V5/V6 original: misma construcción, mismo StandardScaler. + y_raw = np.array(y_raw, dtype=np.float32).reshape(-1, 1) + + target_scaler = StandardScaler(with_mean=False) # preserva el signo del retorno (V4) + target_scaler.fit(y_raw[:window_split]) + y_scaled = target_scaler.transform(y_raw).astype(np.float32) + + train = dict( + X=X[:window_split], y=y_scaled[:window_split], asset_id=asset_id[:window_split], + last_price=last_price[:window_split], dates=dates[:window_split], + ) + test = dict( + X=X[window_split:], y=y_scaled[window_split:], asset_id=asset_id[window_split:], + last_price=last_price[window_split:], dates=dates[window_split:], + ) + return train, test, feature_scaler, target_scaler + + +def _magnitude_warp_oversample(X: np.ndarray, y: np.ndarray, asset_id: np.ndarray, + factor: float, sigma: float = MAGNITUDE_WARP_SIGMA, + n_knots: int = MAGNITUDE_WARP_KNOTS, + seed: int = SEED, + sample_weight: np.ndarray | None = None): + """ + V6 (Requerimiento 5) — balanceo de volumen en el Data Loader, SOLO sobre + train (se invoca en `run_regime_pipeline` DESPUÉS del split train/test de + `build_asset_dataset` -> cero fuga temporal hacia test). + + Deliberadamente NO es `np.tile`/`np.repeat` (duplicar filas EXACTAS no + aporta gradiente nuevo) NI ruido i.i.d. por-paso (destruye la + autocorrelación temporal intra-ventana que el propio BiLSTM/atención + necesita para aprender dinámica, no solo estadística marginal). En su + lugar: Magnitude-Warping (Um et al. 2017, "Data Augmentation of + Wearable Sensor Data..."; Iwana & Uchida 2021, "An Empirical Survey of + Data Augmentation for Time Series Classification with Neural + Networks") — por cada ventana bootstrap-muestreada (CON reemplazo) y + por CADA canal de feature de forma independiente, se generan + `n_knots` nodos de control ~N(1, sigma) y se interpolan con spline + cúbico sobre los `n_timesteps` pasos de la ventana, produciendo una + curva de deformación suave de BAJA frecuencia (a diferencia del ruido + por-paso que reemplaza). + + La curva NO multiplica el valor absoluto en [0,1] de MinMaxScaler + (asimétrico e inseguro: un canal cerca de 1.0 se saldría de rango, uno + cerca de 0.0 quedaría inerte pase lo que pase con la curva — ver Punto + Ciego #1 del mensaje de entrega). En su lugar reescala la serie + ALREDEDOR de su propia media local por ventana/canal: + X_warp = media_ventana + (X - media_ventana) · curva + — la forma temporal (inercia, autocorrelación) se preserva intacta; + solo se expande/contrae la amplitud de la variación alrededor de esa + media. `np.clip(..., 0, 1)` final es un backstop defensivo (mismo rol + que en la iteración anterior), no el mecanismo primario de seguridad. + + `factor<=1.0` es un no-op exacto — usado por `equity_specialist` + (8 tickers, volumen ya suficiente) para preservar el comportamiento V5. + + V22: `sample_weight` es OPCIONAL (None para `equity_specialist`/ + regresión; ver Directiva 3 para `crypto_specialist`/triple_barrier). + Cuando se provee, se resamplea con los MISMOS índices `idx`/`perm` que + X/y/asset_id -- resamplearlo por separado rompería la correspondencia + fila-a-fila entre una ventana aumentada y su peso de muestra real. + Devuelve SIEMPRE una tupla de 4 elementos; el cuarto es `None` si la + entrada lo fue. + """ + if factor <= 1.0: + return X, y, asset_id, sample_weight + + rng = np.random.default_rng(seed) + n_original, n_timesteps, n_channels = X.shape + n_extra = int(round(n_original * (factor - 1.0))) + if n_extra <= 0: + return X, y, asset_id + + idx = rng.integers(0, n_original, size=n_extra) + windows = X[idx] # (n_extra, n_timesteps, n_channels) + + # Curvas vectorizadas: un CubicSpline por (muestra, canal) evaluado en + # un único call — `axis=0` interpola independientemente cada columna + # de `knot_values` (n_extra * n_channels curvas) sobre los mismos + # `knot_positions`, evitando un loop Python por muestra/canal. + knot_positions = np.linspace(0, n_timesteps - 1, n_knots) + knot_values = rng.normal(loc=1.0, scale=sigma, size=(n_knots, n_extra, n_channels)) + warp_curves = CubicSpline(knot_positions, knot_values, axis=0)(np.arange(n_timesteps)) + warp_curves = warp_curves.astype(np.float32) # (n_timesteps, n_extra, n_channels) + warp_curves = np.moveaxis(warp_curves, 0, 1) # -> (n_extra, n_timesteps, n_channels) + + window_mean = windows.mean(axis=1, keepdims=True) # (n_extra, 1, n_channels) — ancla LOCAL, no el nivel absoluto + X_aug = np.clip(window_mean + (windows - window_mean) * warp_curves, 0.0, 1.0).astype(np.float32) + + X_bal = np.concatenate([X, X_aug], axis=0) + y_bal = np.concatenate([y, y[idx]], axis=0) + asset_id_bal = np.concatenate([asset_id, asset_id[idx]], axis=0) + sw_bal = None if sample_weight is None else np.concatenate([sample_weight, sample_weight[idx]], axis=0) + + perm = rng.permutation(len(X_bal)) + sw_out = None if sw_bal is None else sw_bal[perm] + return X_bal[perm], y_bal[perm], asset_id_bal[perm], sw_out + + +# ============================================================ +# FASE B: ARQUITECTURA — INVARIANZA TOPOLÓGICA ESTRICTA (idéntica a V4) +# ============================================================ +@keras.saving.register_keras_serializable(package="quanti") +class BahdanauAttention(layers.Layer): + """Self-attention aditiva (Bahdanau) — pooling final de contexto.""" + + def __init__(self, units: int, **kwargs): + super().__init__(**kwargs) + self.units = units + self.W = layers.Dense(units, name="attn_W") + self.U = layers.Dense(units, name="attn_U") + self.V = layers.Dense(1, name="attn_V") + + def build(self, input_shape): + feature_dim = input_shape[-1] + self.W.build((None, None, feature_dim)) + self.U.build((None, 1, feature_dim)) + self.V.build((None, None, self.units)) + super().build(input_shape) + + def call(self, hidden_states): + query = keras.ops.mean(hidden_states, axis=1, keepdims=True) + score = self.V(keras.ops.tanh(self.W(hidden_states) + self.U(query))) + weights = keras.ops.softmax(score, axis=1) + context = keras.ops.sum(weights * hidden_states, axis=1) + return context, weights + + def get_config(self): + config = super().get_config() + config.update({"units": self.units}) + return config + + +@keras.saving.register_keras_serializable(package="quanti") +class DirectionalHuberLoss(keras.losses.Loss): + """ + L(y, ŷ) = Huber_δ(y, ŷ) · exp(γ · 1[sign(y) ≠ sign(ŷ)]) - λ·min(Var(ŷ), cap) + V5.1: penalización direccional pasa de lineal (1+γ·mismatch) a exponencial + (e^(γ·mismatch)) — a γ=0 (arranque del curriculum) ambas formas coinciden + en 1.0, pero a γ=GAMMA_MAX=1.5 el multiplicador exponencial (≈4.48x) es + sustancialmente más agresivo que el lineal (2.5x) sin discontinuidad + respecto al curriculum sigmoide ya existente. + """ + + def __init__(self, delta: float = 1.0, gamma=1.5, + variance_lambda: float = 0.0, variance_cap: float | None = None, + name: str = "directional_huber", **kwargs): + super().__init__(name=name, **kwargs) + self.delta = delta + self.gamma = gamma if isinstance(gamma, keras.Variable) else keras.Variable( + gamma, trainable=False, dtype="float32", name=f"{name}_gamma" + ) + self.variance_lambda = float(variance_lambda) + self.variance_cap = None if variance_cap is None else float(variance_cap) + + def call(self, y_true, y_pred): + y_true = keras.ops.cast(y_true, "float32") + y_pred = keras.ops.cast(y_pred, "float32") + + error = y_true - y_pred + abs_error = keras.ops.abs(error) + quadratic = keras.ops.minimum(abs_error, self.delta) + linear = abs_error - quadratic + huber = 0.5 * keras.ops.square(quadratic) + self.delta * linear + + mismatch = keras.ops.cast( + keras.ops.not_equal(keras.ops.sign(y_true), keras.ops.sign(y_pred)), + dtype=huber.dtype, + ) + penalty = keras.ops.exp(self.gamma * mismatch) + directional_huber = keras.ops.mean(huber * penalty, axis=-1) + + if self.variance_lambda > 0.0: + batch_variance = keras.ops.var(y_pred) + if self.variance_cap is not None: + batch_variance = keras.ops.minimum(batch_variance, self.variance_cap) + directional_huber = directional_huber - self.variance_lambda * batch_variance + + return directional_huber + + def get_config(self): + config = super().get_config() + config.update({ + "delta": self.delta, + "gamma": float(keras.ops.convert_to_numpy(self.gamma)), + "variance_lambda": self.variance_lambda, + "variance_cap": self.variance_cap, + }) + return config + +@keras.saving.register_keras_serializable(package="quanti") +class DirectionalGaussianNLL(keras.losses.Loss): + """ + μ/logσ² dual-head: acopla magnitud a incertidumbre real del modelo en + vez de premiar Var(ŷ) del batch sin condición (ver DirectionalHuberLoss, + ahora sin uso, dejada arriba como referencia histórica). + + V6 — 3 mecanismos anti-colapso de varianza bajo escasez de datos + (auditoría `crypto_specialist`: 2 tickers, dataset por-régimen ~10x más + chico que el global mezclado V4). La NLL Gaussiana estándar permite al + optimizador minimizar la pérdida INFLANDO `log_var` en vez de mejorar + `mu`, porque el gradiente sobre `mu` está ponderado por 1/var: a menos + datos, menos señal para corregir `mu`, y "var→∞" se vuelve el óptimo + local dominante (Seitzer, Tavakoli, Antic, Martius — "On the Pitfalls of + Heteroscedastic Uncertainty Estimation with Probabilistic Neural + Networks", ICLR 2022, arXiv:2203.09168). + + 1) β-NLL (paper cit., Sec. 3): cada muestra se pondera por + stop_gradient(var_clip)^beta. beta=0 == NLL estándar (el modo + patológico); beta=1 == MSE puro (ignora la incertidumbre). El + paper reporta beta≈0.5 como punto de partida robusto en la + mayoría de los dominios evaluados — interpola entre ambos + extremos sin tocar arquitectura ni forward pass, solo reescala + el gradiente por muestra. stop_gradient es OBLIGATORIO: si el + propio factor de ponderación retropropagara a través de `var`, + recrearía el mismo incentivo perverso que intenta corregir. + 2) Clip numérico interno (`LOG_VAR_MIN`/`LOG_VAR_MAX`) — SOLO para + calcular `var` dentro de la NLL de este `call()`, evitando + `exp(log_var) -> inf` (y por ende NaN vía TerminateOnNaN) en los + primeros steps, mientras el mecanismo (3) reeduca al head. + 3) Amortiguación directa sobre `log_var` CRUDO (sin clip): ridge L2 + hacia log_var≈0 + barrera cuadrática blanda fuera de + [LOG_VAR_MIN, LOG_VAR_MAX] (CERO penalización dentro del rango, + gradiente que CRECE cuadráticamente cuanto más lejos se excede + -a diferencia de un hard-clip, cuyo gradiente es EXACTAMENTE 0 + fuera de rango y congelaría al optimizador justo donde más + necesita corregirse). + + COMPATIBILIDAD DE INFERENCIA (crítico): a propósito, el head `log_var` + NUNCA se remapea/reparametriza (nada de tanh-squashing sobre el output) + — sigue siendo literalmente log_var, igual que en V5. `services/ + quanti_engine.py` (`log_var_scaled_batch = y_pred_np[:, 1:2]`) sigue + funcionando SIN NINGÚN cambio; los 3 mecanismos de arriba solo dan forma + al GRADIENTE de entrenamiento, no a la semántica del output guardado en + `model_v5.keras`. + + Con beta=0.0, log_var_l2_lambda=0.0 y log_var_barrier_lambda=0.0, esta + clase es matemáticamente IDÉNTICA a la NLL Gaussiana V5 original. + + ROLLBACK V23.6 (Head Quant, ver changelog del módulo): V23.5 había + hecho que `call()` NO redujera a escalar internamente (para que + Keras pudiera aplicar un `sample_weight` externo por volatilidad de + equity antes de la reducción). Ese sample_weight fue purgado por + completo (empeoró Directional Accuracy en vez de mejorarla) y + `equity_specialist` (única rama que usa esta loss) nunca vuelve a + pasar `sample_weight` -- `call()` vuelve a reducir con + `keras.ops.mean(...)` acá adentro, EXACTAMENTE como en V5/V6. Cero + mecanismo residual atado a un sample_weight que ya no existe. + """ + + def __init__(self, gamma_directional=1.5, beta: float = GAUSSIAN_NLL_BETA, + log_var_min: float = LOG_VAR_MIN, log_var_max: float = LOG_VAR_MAX, + log_var_l2_lambda: float = LOG_VAR_L2_LAMBDA, + log_var_barrier_lambda: float = LOG_VAR_BARRIER_LAMBDA, + name: str = "directional_gaussian_nll", **kwargs): + super().__init__(name=name, **kwargs) + self.gamma = gamma_directional if isinstance(gamma_directional, keras.Variable) else keras.Variable( + gamma_directional, trainable=False, dtype="float32", name=f"{name}_gamma" + ) + self.beta = float(beta) + self.log_var_min = float(log_var_min) + self.log_var_max = float(log_var_max) + self.log_var_l2_lambda = float(log_var_l2_lambda) + self.log_var_barrier_lambda = float(log_var_barrier_lambda) + + def call(self, y_true, y_pred): # y_pred: (batch, 2) = [mu, log_var] — SIN remapeo, ver docstring + y_true = keras.ops.cast(y_true, "float32") + y_true = keras.ops.reshape(y_true, (-1,)) + mu, log_var = y_pred[:, 0], y_pred[:, 1] + + # --- (2) clip NUMÉRICO interno, solo para var/nll de este call() --- + log_var_safe = keras.ops.clip(log_var, self.log_var_min, self.log_var_max) + var_safe = keras.ops.exp(log_var_safe) + + nll = 0.5 * (log_var_safe + keras.ops.square(y_true - mu) / var_safe) + + # --- (1) β-NLL — ver docstring; stop_gradient es obligatorio --- + if self.beta > 0.0: + nll = nll * keras.ops.stop_gradient(keras.ops.power(var_safe, self.beta)) + + mismatch = keras.ops.cast(keras.ops.not_equal(keras.ops.sign(y_true), keras.ops.sign(mu)), nll.dtype) + per_sample_loss = nll * keras.ops.exp(self.gamma * mismatch) # (batch,) + + # --- (3) amortiguación sobre log_var CRUDO (sin clip) -- término + # PER-SAMPLE sumado antes de reducir (mean(a_i + c) == mean(a_i) + c). + if self.log_var_l2_lambda > 0.0: + per_sample_loss = per_sample_loss + self.log_var_l2_lambda * keras.ops.square(log_var) + if self.log_var_barrier_lambda > 0.0: + excess_hi = keras.ops.relu(log_var - self.log_var_max) + excess_lo = keras.ops.relu(self.log_var_min - log_var) + per_sample_loss = per_sample_loss + self.log_var_barrier_lambda * ( + keras.ops.square(excess_hi) + keras.ops.square(excess_lo) + ) + + # ROLLBACK V23.6 -- reducción interna a escalar restaurada (idéntico + # a V5/V6): `equity_specialist` nunca vuelve a pasar `sample_weight` + # a esta loss, así que no hay razón para dejar la reducción a cargo + # de Keras (eso solo importaba para el sample_weight ya purgado). + return keras.ops.mean(per_sample_loss) + + def get_config(self): + config = super().get_config() + config.update({ + "gamma_directional": float(keras.ops.convert_to_numpy(self.gamma)), + "beta": self.beta, + "log_var_min": self.log_var_min, + "log_var_max": self.log_var_max, + "log_var_l2_lambda": self.log_var_l2_lambda, + "log_var_barrier_lambda": self.log_var_barrier_lambda, + }) + return config + +@keras.saving.register_keras_serializable(package="quanti") +def directional_accuracy_metric(y_true, y_pred): + y_true = keras.ops.reshape(keras.ops.cast(y_true, "float32"), (-1,)) + mu = keras.ops.cast(y_pred, "float32")[:, 0] + match = keras.ops.cast(keras.ops.equal(keras.ops.sign(y_true), keras.ops.sign(mu)), dtype="float32") + return keras.ops.mean(match) + + +@keras.saving.register_keras_serializable(package="quanti") +def mu_mae_metric(y_true, y_pred): + # reemplaza "mae" en compile — "mae" plano rompe con y_pred (batch,2) + y_true = keras.ops.reshape(keras.ops.cast(y_true, "float32"), (-1,)) + mu = keras.ops.cast(y_pred, "float32")[:, 0] + return keras.ops.mean(keras.ops.abs(y_true - mu)) + + +# ============================================================ +# V22 — MÉTRICAS DE CLASIFICACIÓN (target_mode="triple_barrier", ver +# build_model/REGIMES["crypto_specialist"]) +# ============================================================ +@keras.saving.register_keras_serializable(package="quanti") +class ActionableAccuracy(keras.metrics.Metric): + """ + Accuracy restringida a apuestas ACCIONABLES (clase VERDADERA != + TIMEOUT) -- el análogo, en el espíritu de meta-labeling, de "cuando el + mercado SÍ tocó una barrera, ¿el modelo acertó cuál?". Deliberadamente + IGNORA la clase TIMEOUT (mayoritaria en volumen -- ver distribución de + clases logueada en `run_regime_pipeline`): un modelo que colapsa a + predecir siempre TIMEOUT tendría accuracy 3-way alta pero + `actionable_accuracy` = 0%, exactamente el colapso "cobarde" que + `EarlyStopping` monitorea acá (ver `train_model`) en vez de la accuracy + plana -- mismo rol que `val_directional_accuracy_metric` cumple para + el régimen de regresión. + + Implementada CON ESTADO (no como función simple, a diferencia de + `directional_accuracy_metric`) porque el promedio debe calcularse + SOLO sobre el subconjunto accionable de cada batch, un conteo propio + independiente del `sample_weight` de la pérdida (magnitud/PnL, ver + `build_asset_dataset`) -- por eso `sample_weight` se recibe pero NO se + usa: esta métrica pondera por igual cada apuesta accionable, + deliberadamente distinto del criterio de la pérdida. + """ + + def __init__(self, timeout_class_idx: int = TB_TIMEOUT_CLASS_IDX, + name: str = "actionable_accuracy", **kwargs): + super().__init__(name=name, **kwargs) + self.timeout_class_idx = timeout_class_idx + self.correct = self.add_weight(name="correct", initializer="zeros") + self.total = self.add_weight(name="total", initializer="zeros") + + def update_state(self, y_true, y_pred, sample_weight=None): # noqa: ARG002 -- ver docstring + y_true = keras.ops.cast(y_true, "float32") + true_idx = keras.ops.argmax(y_true, axis=-1) + pred_idx = keras.ops.argmax(y_pred, axis=-1) + is_actionable = keras.ops.cast(keras.ops.not_equal(true_idx, self.timeout_class_idx), "float32") + is_correct = keras.ops.cast(keras.ops.equal(true_idx, pred_idx), "float32") + self.correct.assign_add(keras.ops.sum(is_correct * is_actionable)) + self.total.assign_add(keras.ops.sum(is_actionable)) + + def result(self): + return self.correct / keras.ops.maximum(self.total, 1e-8) + + def reset_state(self): + self.correct.assign(0.0) + self.total.assign(0.0) + + def get_config(self): + config = super().get_config() + config.update({"timeout_class_idx": self.timeout_class_idx}) + return config + + +class DynamicGammaCallback(keras.callbacks.Callback): + """Curriculum learning: rampa sigmoide/lineal de gamma de 0.0 a GAMMA_MAX (idéntico a V4).""" + + def __init__(self, gamma_variable, gamma_max: float = GAMMA_MAX, + warmup_epochs: int = GAMMA_WARMUP_EPOCHS, + schedule: str = GAMMA_SCHEDULE, + sigmoid_steepness: float = GAMMA_SIGMOID_STEEPNESS, + verbose: bool = True): + super().__init__() + self.gamma_variable = gamma_variable + self.gamma_max = gamma_max + self.warmup_epochs = max(1, warmup_epochs) + self.schedule = schedule + self.sigmoid_steepness = sigmoid_steepness + self.verbose = verbose + k = self.sigmoid_steepness + self._sig_lo = 1.0 / (1.0 + np.exp(k * 0.5)) + self._sig_hi = 1.0 / (1.0 + np.exp(-k * 0.5)) + + def _progress_to_fraction(self, progress: float) -> float: + progress = min(max(progress, 0.0), 1.0) + if self.schedule == "linear": + return progress + k = self.sigmoid_steepness + raw = 1.0 / (1.0 + np.exp(-k * (progress - 0.5))) + return (raw - self._sig_lo) / (self._sig_hi - self._sig_lo) + + def on_epoch_begin(self, epoch, logs=None): + progress = epoch / self.warmup_epochs + new_gamma = float(self.gamma_max * self._progress_to_fraction(progress)) + self.gamma_variable.assign(new_gamma) + if self.verbose and (epoch % 5 == 0 or epoch == self.warmup_epochs): + tag = " <- curriculum completo" if epoch >= self.warmup_epochs else "" + logger.info("[DynamicGamma] epoch=%3d gamma=%.4f%s", epoch, new_gamma, tag) + + +def _build_tcn_branch(seq_input, filters: int, l2reg, dropout_rate: float, + kernel_size: int = TCN_KERNEL_SIZE, dilations=TCN_DILATIONS, + name_prefix: str = "tcn"): + """ + Bloque TCN (V15, Directiva 4): pila de convoluciones causales 1D + dilatadas con conexión residual por bloque (patrón estándar Bai et al. + 2018), seguida de GlobalAveragePooling1D para colapsar a un vector de + contexto del mismo rol que `BahdanauAttention` -- ambos se concatenan + aguas abajo en `build_model`. `padding="causal"` es obligatorio: sin + causalidad el filtro vería pasos FUTUROS de la ventana, fuga de + información hacia el propio target que se intenta predecir. + """ + x = seq_input + for i, dilation in enumerate(dilations): + residual = x + conv = layers.Conv1D( + filters, kernel_size, padding="causal", dilation_rate=dilation, + activation="relu", kernel_regularizer=l2reg, name=f"{name_prefix}_conv_{i}_d{dilation}", + )(x) + conv = layers.Dropout(dropout_rate * 0.3, name=f"{name_prefix}_dropout_{i}")(conv) + if residual.shape[-1] != filters: + residual = layers.Conv1D(filters, 1, padding="same", name=f"{name_prefix}_proj_{i}")(residual) + x = layers.Add(name=f"{name_prefix}_residual_add_{i}")([residual, conv]) + x = layers.LayerNormalization(name=f"{name_prefix}_ln_{i}")(x) + return layers.GlobalAveragePooling1D(name=f"{name_prefix}_global_pool")(x) + + +def build_model(n_timesteps: int, n_features: int, n_assets: int, + steps_per_epoch: int, regime_name: str, + embed_dim: int = ASSET_EMBED_DIM, + huber_delta: float = HUBER_DELTA, + gamma_initial: float = GAMMA_INITIAL, + variance_lambda: float = VARIANCE_LAMBDA, + variance_cap: float = VARIANCE_CAP, + gaussian_nll_beta: float = GAUSSIAN_NLL_BETA, + log_var_min: float = LOG_VAR_MIN, + log_var_max: float = LOG_VAR_MAX, + log_var_l2_lambda: float = LOG_VAR_L2_LAMBDA, + log_var_barrier_lambda: float = LOG_VAR_BARRIER_LAMBDA, + model_name: str | None = None, + target_mode: str = "regression", + class_alpha: list[float] | None = None, + focal_gamma: float = TRIPLE_BARRIER_FOCAL_GAMMA, + label_smoothing: float = TRIPLE_BARRIER_LABEL_SMOOTHING) -> tuple: + """ + Topología Híbrida Asimétrica: la firma ya NO recibe hiperparámetros de + arquitectura sueltos -- `regime_name` indexa `REGIME_ARCHITECTURE` (ver + diccionario, arriba) y la función dicta su propia topología + internamente. Grafo común a ambos especialistas: Input -> + BiLSTM(lstm_units) -> LayerNorm -> MultiHeadAttention+Residual -> + LayerNorm -> BahdanauAttention -> Concat(context, asset_embed) -> + [bloque residual extra si `extra_residual_block=True`] -> + Dense(32)+Residual -> Dense(1). Solo cambian, por régimen: n_features + (por NEWS_SENTIMENT_SCORE), n_assets (universo del régimen) y el + perfil asignado en `REGIME_ARCHITECTURE[regime_name]`. + + V22 — `target_mode` bifurca ÚNICAMENTE la cabeza de salida final y el + `compile()` (loss/métricas); el tronco común (BiLSTM->MHA->Bahdanau + [->TCN]->asset_embed->Dense residual) es IDÉNTICO en ambos modos -- + misma invarianza topológica que ya regía entre regímenes. + `target_mode="regression"` (default) es BIT A BIT idéntico a V6: cabeza + `Dense(2)` (mu, log_var) + `DirectionalGaussianNLL`. `target_mode= + "triple_barrier"` reemplaza la cabeza por `Dense(3, softmax)` (SL/ + TIMEOUT/TP, ver `TB_CLASS_NAMES`) + `CategoricalFocalCrossentropy` + (Lin et al. 2017, built-in Keras 3) con `alpha` por-clase (balanceo, + ver `run_regime_pipeline`) -- el curriculum de `gamma` direccional + (`DynamicGammaCallback`) es exclusivo del régimen de regresión; acá + `gamma_variable` vuelve `None`, sin aristas huérfanas en `train_model`. + """ + arch = REGIME_ARCHITECTURE[regime_name] + lstm_units = arch["lstm_units"] + attention_units = arch["attention_units"] + mha_heads = arch["mha_heads"] + mha_key_dim = arch["mha_key_dim"] + dropout_rate = arch["dropout_rate"] + dense_l2_reg = arch["dense_l2_reg"] + extra_residual_block = arch["extra_residual_block"] + tcn_filters = arch.get("tcn_filters", lstm_units // 2) + if model_name is None: + model_name = f"KodaQuant_{regime_name}_V5" + + seq_input = keras.Input(shape=(n_timesteps, n_features), name="input_sequence") + asset_input = keras.Input(shape=(1,), dtype="int32", name="input_asset_id") + + l2 = keras.regularizers.l2(dense_l2_reg) # V5.1: definido temprano — reutilizado en BiLSTM/MHA/Dense + + # --- V27: Gated Linear Unit sobre la secuencia CRUDA ------------------- + # value * sigmoid(gate), ambas proyecciones desde el mismo input. La + # rama value usa Swish (suave, no satura ni mata gradiente como ReLU en + # z-scores centrados en 0, que es lo que son TODAS las features nuevas). + # LayerNormalization post-gate: la multiplicación elemento a elemento + # contrae la escala y sin renormalizar el gradiente se desvanece al + # atravesar el BiLSTM. `glu_units=None`/ausente -> grafo IDÉNTICO al + # anterior (aditivo y reversible, mismo criterio que ENABLE_TCN_BRANCH). + glu_units = arch.get("glu_units") + if glu_units: + _value = layers.Dense(glu_units, activation="swish", kernel_regularizer=l2, + name="glu_input_value")(seq_input) + _gate = layers.Dense(glu_units, activation="sigmoid", kernel_regularizer=l2, + name="glu_input_gate")(seq_input) + gated_seq = layers.Multiply(name="glu_input_mul")([_value, _gate]) + gated_seq = layers.LayerNormalization(name="glu_input_ln")(gated_seq) + gated_seq = layers.SpatialDropout1D(dropout_rate * 0.25, + name="glu_input_spatial_dropout")(gated_seq) + else: + gated_seq = seq_input + + bilstm = layers.Bidirectional( + layers.LSTM(lstm_units, return_sequences=True, dropout=dropout_rate * 0.3, + kernel_regularizer=l2, recurrent_regularizer=l2), + name=f"bilstm_{lstm_units}", + )(gated_seq) + bilstm = layers.LayerNormalization(name=f"ln_post_bilstm_{lstm_units}")(bilstm) + + mha_out = layers.MultiHeadAttention( + num_heads=mha_heads, key_dim=mha_key_dim, kernel_regularizer=l2, + name="multi_head_self_attention", + )(query=bilstm, value=bilstm, key=bilstm) + mha_out = layers.Dropout(dropout_rate * 0.5, name="dropout_post_mha")(mha_out) + attn_block = layers.Add(name="mha_residual_add")([bilstm, mha_out]) + attn_block = layers.LayerNormalization(name="ln_post_mha_residual")(attn_block) + + context_vector, attention_weights = BahdanauAttention( + attention_units, name="bahdanau_attention" + )(attn_block) + + asset_embed = layers.Embedding(n_assets, embed_dim, name="asset_embedding")(asset_input) + asset_embed = layers.Flatten(name="asset_embedding_flat")(asset_embed) + + context_vector = layers.Dropout(dropout_rate * 0.5, name="dropout_post_bahdanau")(context_vector) + + # --- V15 (Directiva 4) — rama TCN paralela, fusionada por concat ----- + # Opera sobre `seq_input` CRUDO (no sobre `attn_block`): busca patrones + # temporales complementarios a los que ya extrae BiLSTM+MHA+Bahdanau, + # no refinar la misma representación dos veces. `ENABLE_TCN_BRANCH=0` + # deja el grafo IDÉNTICO a la topología V10 (invarianza reversible). + if ENABLE_TCN_BRANCH: + # V27 -- TCN consume la MISMA secuencia compuerta que el BiLSTM. + # Alimentarla con `seq_input` crudo dejaría a las dos ramas viendo + # espacios de entrada distintos y volvería no interpretable cualquier + # atribución por gradiente entre ellas. + tcn_context = _build_tcn_branch(gated_seq, tcn_filters, l2, dropout_rate) + tcn_context = layers.Dropout(dropout_rate * 0.5, name="dropout_post_tcn")(tcn_context) + fusion_inputs = [context_vector, tcn_context, asset_embed] + else: + fusion_inputs = [context_vector, asset_embed] + + fused = layers.Concatenate(name="fusion_attn_asset")(fusion_inputs) + fused = layers.Dropout(dropout_rate, name="dropout_regularizer")(fused) + + # --- Bloque residual profundo adicional (perfil equity_specialist) — + # no-op estructural cuando extra_residual_block=False (crypto_specialist: + # el grafo queda BIT A BIT idéntico, sin este bloque). + if extra_residual_block: + wide_hidden = layers.Dense(64, activation="relu", name="extra_residual_dense", + kernel_regularizer=l2)(fused) + wide_projection = layers.Dense(64, name="extra_residual_skip", + kernel_regularizer=l2)(fused) + fused = layers.Add(name="extra_residual_add")([wide_hidden, wide_projection]) + fused = layers.LayerNormalization(name="ln_post_extra_residual")(fused) + fused = layers.Dropout(dropout_rate * 0.5, name="dropout_post_extra_residual")(fused) + + dense_hidden = layers.Dense(32, activation="relu", name="post_fusion_dense", + kernel_regularizer=l2)(fused) + fused_projection = layers.Dense(32, name="fused_projection_skip", + kernel_regularizer=l2)(fused) + dense_block = layers.Add(name="dense_residual_add")([dense_hidden, fused_projection]) + dense_block = layers.LayerNormalization(name="ln_post_dense_residual")(dense_block) + + # --- V22 — cabeza de salida bifurcada por target_mode ------------------ + if target_mode == "triple_barrier": + output = layers.Dense(3, activation="softmax", name="triple_barrier_head", + kernel_regularizer=l2)(dense_block) + else: + output = layers.Dense(2, name="return_head", kernel_regularizer=l2)(dense_block) + + model = keras.Model(inputs=[seq_input, asset_input], outputs=output, name=model_name) + + lr_schedule = keras.optimizers.schedules.CosineDecayRestarts( + initial_learning_rate=LR_INITIAL, + first_decay_steps=max(1, steps_per_epoch * COSINE_RESTART_EPOCH_PERIOD), + t_mul=COSINE_T_MUL, + m_mul=COSINE_M_MUL, + alpha=COSINE_ALPHA, + ) + optimizer = keras.optimizers.AdamW( + learning_rate=lr_schedule, weight_decay=1e-4, clipnorm=GRAD_CLIPNORM + ) + + if target_mode == "triple_barrier": + # Curriculum de gamma direccional es exclusivo de DirectionalGaussianNLL + # (régimen de regresión) -- acá no hay "mismatch de signo" que penalizar + # progresivamente, el desbalance de clases ya lo resuelve `alpha`. + gamma_variable = None + model.compile( + optimizer=optimizer, + loss=keras.losses.CategoricalFocalCrossentropy( + alpha=class_alpha if class_alpha is not None else 0.25, + gamma=focal_gamma, + label_smoothing=label_smoothing, + ), + metrics=[keras.metrics.CategoricalAccuracy(name="categorical_accuracy"), + ActionableAccuracy(name="actionable_accuracy")], + ) + else: + gamma_variable = keras.Variable( + gamma_initial, trainable=False, dtype="float32", name="directional_gamma" + ) + model.compile( + optimizer=optimizer, + loss=DirectionalGaussianNLL( + gamma_directional=gamma_variable, + beta=gaussian_nll_beta, + log_var_min=log_var_min, log_var_max=log_var_max, + log_var_l2_lambda=log_var_l2_lambda, + log_var_barrier_lambda=log_var_barrier_lambda, + ), + metrics=[mu_mae_metric, directional_accuracy_metric], + ) + return model, gamma_variable + + +# ============================================================ +# FASE C: ENTRENAMIENTO (idéntico a V4) +# ============================================================ +def train_model(model: keras.Model, X_train, asset_id_train, y_train, + checkpoint_path: Path, + epochs: int = EPOCHS, batch_size: int = BATCH_SIZE, + validation_split: float = VALIDATION_SPLIT, + validation_data=None, + gamma_variable=None, + gamma_max: float = GAMMA_MAX, + gamma_warmup_epochs: int = GAMMA_WARMUP_EPOCHS, + gamma_schedule: str = GAMMA_SCHEDULE, + gamma_sigmoid_steepness: float = GAMMA_SIGMOID_STEEPNESS, + sample_weight: np.ndarray | None = None, + monitor_metric: str = "val_directional_accuracy_metric", + checkpoint_monitor: str | None = None): + """ + V22: `sample_weight` (None por default -- `equity_specialist` no pasa + nada acá, comportamiento IDÉNTICO a V6) permite el peso por-muestra de + Directiva 3 (magnitud de PnL, ver `build_asset_dataset`) vía el + argumento nativo de Keras en `model.fit`. `monitor_metric` generaliza + el `EarlyStopping`: `crypto_specialist`/triple_barrier monitorea + `val_actionable_accuracy` (ver `ActionableAccuracy`) en vez de + `val_directional_accuracy_metric` (que no existe en ese régimen, la + cabeza ya no predice signo continuo) -- default sin cambios para + preservar el comportamiento exacto de `equity_specialist`. + + V23.2 -- FIX BUG REAL (root cause del techo ~46% en crypto_specialist): + `ModelCheckpoint` monitoreaba `val_loss` HARDCODEADO mientras + `EarlyStopping` monitoreaba `monitor_metric` (`val_actionable_accuracy` + en cripto) con `restore_best_weights=True`. Esto significa que las + pesos EN MEMORIA al terminar `model.fit()` ya eran los de mejor + actionable_accuracy (gracias a `restore_best_weights`) -- pero + `keras.models.load_model(checkpoint_path)` los DESCARTABA y recargaba + del disco el checkpoint de mejor `val_loss`, que en un problema de 3 + clases con `alpha` de rebalanceo NO necesariamente coincide con el de + mejor actionable_accuracy (val_loss pondera las 3 clases incl. TIMEOUT, + actionable_accuracy solo mide SL-vs-TP condicionado a señal). El modelo + evaluado NUNCA fue el mejor que `EarlyStopping` encontró. + `checkpoint_monitor=None` (default) preserva EXACTO el comportamiento + de `equity_specialist` (`val_loss`/mode="min", cero cambio). Cuando se + pasa `checkpoint_monitor=monitor_metric` (ver `run_regime_pipeline`, + SOLO en la rama `triple_barrier`), `ModelCheckpoint` persigue la MISMA + métrica que `EarlyStopping` -- ambos callbacks alineados. + + V27 -- `validation_data` (None por default -- `equity_specialist` no lo + pasa, comportamiento IDÉNTICO: sigue usando `validation_split` nativo + de Keras sobre `X_train` tal cual). Cuando se provee (SOLO + `crypto_specialist`/triple_barrier, ver `run_regime_pipeline`), Keras + usa ese validation set EXPLÍCITO en vez de cortar el último + `validation_split` de `X_train` -- necesario porque `X_train` en ese + régimen pasó por `_magnitude_warp_oversample` (bootstrap + permutación + global), y cortar el último 10% de un array ya mezclado con copias + aumentadas de sí mismo filtra información train->"validación" (ver + docstring extenso en `run_regime_pipeline`, carve por-activo). + """ + ckpt_monitor = checkpoint_monitor if checkpoint_monitor is not None else "val_loss" + ckpt_mode = "min" if ckpt_monitor == "val_loss" else "max" + callbacks = [ + keras.callbacks.ModelCheckpoint( + str(checkpoint_path), monitor=ckpt_monitor, mode=ckpt_mode, save_best_only=True, verbose=1 + ), + keras.callbacks.TerminateOnNaN(), + keras.callbacks.EarlyStopping( + monitor=monitor_metric, mode="max", + patience=EARLY_STOPPING_PATIENCE, start_from_epoch=EARLY_STOPPING_START_EPOCH, + restore_best_weights=True, verbose=1, + ), + ] + if gamma_variable is not None: + callbacks.append(DynamicGammaCallback( + gamma_variable=gamma_variable, gamma_max=gamma_max, + warmup_epochs=gamma_warmup_epochs, schedule=gamma_schedule, + sigmoid_steepness=gamma_sigmoid_steepness, + )) + # V27 -- `validation_data` explícito reemplaza `validation_split` por + # completo cuando se provee (Keras no acepta ambos a la vez con + # semántica bien definida) -- ver docstring arriba. + fit_kwargs = ( + dict(validation_data=validation_data) if validation_data is not None + else dict(validation_split=validation_split) + ) + history = model.fit( + [X_train, asset_id_train], y_train, + epochs=epochs, batch_size=batch_size, shuffle=True, + sample_weight=sample_weight, + callbacks=callbacks, verbose=1, + **fit_kwargs, + ) + best_model = keras.models.load_model(checkpoint_path) + return history, best_model + + +# ============================================================ +# FASE D: EVALUACIÓN — RECONSTRUCCIÓN DE PRECIOS + DIRECTIONAL ACCURACY +# ============================================================ +def evaluate_asset(model: keras.Model, test: dict, ticker: str, target_scaler: StandardScaler) -> dict: + asset_id_col = test["asset_id"].reshape(-1, 1) + y_pred_scaled = model.predict([test["X"], asset_id_col], verbose=0) + mu_scaled = y_pred_scaled[:, 0:1] + r_hat = target_scaler.inverse_transform(mu_scaled).flatten() + r_true = target_scaler.inverse_transform(test["y"]).flatten() + + price_pred = test["last_price"] * np.exp(r_hat) + price_true = test["last_price"] * np.exp(r_true) + + mae_price = mean_absolute_error(price_true, price_pred) + rmse_price = np.sqrt(mean_squared_error(price_true, price_pred)) + directional_acc = float(np.mean(np.sign(r_hat) == np.sign(r_true))) + + return { + "ticker": ticker, "mae_price": mae_price, "rmse_price": rmse_price, + "directional_accuracy": directional_acc, + "price_true": price_true, "price_pred": price_pred, "dates": test["dates"], + } + + +def evaluate_asset_triple_barrier(model: keras.Model, test: dict, ticker: str) -> dict: + """ + Evaluación V22 -- `target_mode="triple_barrier"`. NO reconstruye + precio (la cabeza ya no predice retorno continuo, ver `build_model`): + reporta accuracy de clasificación 3-way (SL/TIMEOUT/TP) más DOS + métricas con sentido de trading real -- + + actionable_accuracy -- de los días en que el mercado SÍ tocó una + barrera (clase verdadera != TIMEOUT), ¿cuántos acertó el + modelo en clase? (ver `ActionableAccuracy`, mismo criterio + usado como monitor de `EarlyStopping` en `train_model`). + signal_precision -- de las señales que el modelo SÍ dispara + (predicción != TIMEOUT), ¿cuántas son correctas? El análogo + de "precision" en meta-labeling -- la métrica que de verdad + importa para decidir si vale la pena OPERAR la señal (ver + `pnl_backtest.py`, que reusa `y_class_idx`/`realized_return` + de este mismo dict). + """ + asset_id_col = test["asset_id"].reshape(-1, 1) + y_pred_proba = model.predict([test["X"], asset_id_col], verbose=0) + y_true_idx = np.argmax(test["y"], axis=-1) + y_pred_idx = np.argmax(y_pred_proba, axis=-1) + + accuracy = float(np.mean(y_true_idx == y_pred_idx)) + + actionable_mask = y_true_idx != TB_TIMEOUT_CLASS_IDX + n_actionable = int(actionable_mask.sum()) + actionable_accuracy = ( + float(np.mean(y_pred_idx[actionable_mask] == y_true_idx[actionable_mask])) + if n_actionable > 0 else float("nan") + ) + + signal_mask = y_pred_idx != TB_TIMEOUT_CLASS_IDX + n_signals = int(signal_mask.sum()) + signal_precision = ( + float(np.mean(y_pred_idx[signal_mask] == y_true_idx[signal_mask])) + if n_signals > 0 else float("nan") + ) + + cm = confusion_matrix(y_true_idx, y_pred_idx, labels=[0, 1, 2]) + class_dist_true = {TB_CLASS_NAMES[i]: int((y_true_idx == i).sum()) for i in range(3)} + class_dist_pred = {TB_CLASS_NAMES[i]: int((y_pred_idx == i).sum()) for i in range(3)} + + return { + "ticker": ticker, "n_test": len(y_true_idx), "accuracy": accuracy, + "actionable_accuracy": actionable_accuracy, "n_actionable": n_actionable, + "signal_precision": signal_precision, "n_signals": n_signals, + "confusion_matrix": cm, "class_dist_true": class_dist_true, "class_dist_pred": class_dist_pred, + "y_true_idx": y_true_idx, "y_pred_idx": y_pred_idx, "y_pred_proba": y_pred_proba, + "dates": test["dates"], "realized_return": test.get("y_return"), + } + + +def train_meta_labeler(model: keras.Model, X_val: np.ndarray, asset_id_val: np.ndarray, + y_val: np.ndarray): + """ + V27 -- Fase 2 capa 3 (meta-labeling, López de Prado cap. 3). Clasificador + binario LIVIANO (RandomForest, ya en requirements.txt -- cero dependencia + nueva) que aprende a distinguir cuándo confiar en la señal del modelo + primario, en vez de mejorar su accuracy direccional cruda. + + Entrena EXCLUSIVAMENTE sobre `X_val`/`y_val` -- el slice crudo, + cronológico, NUNCA usado para actualizar pesos del modelo primario (ver + `validation_data_bundle` en `run_regime_pipeline`, separado ANTES del + oversampling). Entrenarlo sobre train_fit sería circular: el primario ya + memorizó esas muestras, el meta-labeler aprendería a confiar en TODO. + + Feature del meta-labeler = las 3 probabilidades softmax del primario + (cuán segura está cada predicción) -- NO las features OHLCV crudas, para + evitar que el meta-labeler reaprenda el mismo problema que el primario + ya falló en resolver. Target = 1 si el primario acertó Y fue accionable + (misma definición que `actionable_accuracy`), 0 si erró O el mercado + hizo TIMEOUT (no había nada que acertar). + + Devuelve (None, None) si `X_val` es demasiado chico o si el primario + nunca dispara señales accionables en ese slice -- el caller debe + manejar ese caso sin filtrar nada (fail-open, no fail-silent). + """ + from sklearn.ensemble import RandomForestClassifier + + y_pred_proba_val = model.predict([X_val, asset_id_val.reshape(-1, 1)], verbose=0) + y_true_idx_val = np.argmax(y_val, axis=-1) + y_pred_idx_val = np.argmax(y_pred_proba_val, axis=-1) + + meta_target = ((y_pred_idx_val == y_true_idx_val) & (y_true_idx_val != TB_TIMEOUT_CLASS_IDX)).astype(int) + + if len(meta_target) < 30 or meta_target.sum() == 0 or meta_target.sum() == len(meta_target): + logger.warning("[META-LABEL] X_val insuficiente o degenerado (n=%d, positivos=%d) -- " + "meta-labeler NO entrenado, todas las señales primarias pasan sin filtrar.", + len(meta_target), int(meta_target.sum())) + return None, None + + meta_clf = RandomForestClassifier( + n_estimators=200, max_depth=4, min_samples_leaf=10, + class_weight="balanced", random_state=42, n_jobs=-1, + ) + meta_clf.fit(y_pred_proba_val, meta_target) + + meta_pred_val = meta_clf.predict(y_pred_proba_val) + val_precision_before = float(np.mean(y_pred_idx_val[y_pred_idx_val != TB_TIMEOUT_CLASS_IDX] == + y_true_idx_val[y_pred_idx_val != TB_TIMEOUT_CLASS_IDX])) \ + if (y_pred_idx_val != TB_TIMEOUT_CLASS_IDX).any() else float("nan") + trusted_mask_val = (meta_pred_val == 1) & (y_pred_idx_val != TB_TIMEOUT_CLASS_IDX) + val_precision_after = float(np.mean(y_true_idx_val[trusted_mask_val] == y_pred_idx_val[trusted_mask_val])) \ + if trusted_mask_val.any() else float("nan") + logger.info(" [META-LABEL] fit sobre X_val (n=%d, positivos=%d). " + "PrecisiónSeñal val: sin_filtro=%.1f%% -> con_filtro=%.1f%% (cobertura=%.1f%%)", + len(meta_target), int(meta_target.sum()), val_precision_before * 100, + val_precision_after * 100, 100 * trusted_mask_val.sum() / max(1, (y_pred_idx_val != TB_TIMEOUT_CLASS_IDX).sum())) + return meta_clf, {"val_precision_before": val_precision_before, "val_precision_after": val_precision_after} + + +def evaluate_meta_labeler(meta_clf, y_pred_proba: np.ndarray, y_pred_idx: np.ndarray, + y_true_idx: np.ndarray) -> dict | None: + """ + V27 -- aplica el meta-labeler ya entrenado sobre el TEST set (nunca visto + ni por el primario ni por el meta-labeler). `meta_clf=None` (ver + `train_meta_labeler`) -> devuelve None, el caller reporta solo las + métricas del primario sin filtro -- fail-open. + """ + if meta_clf is None: + return None + meta_pred = meta_clf.predict(y_pred_proba) + signal_mask = y_pred_idx != TB_TIMEOUT_CLASS_IDX + trusted_mask = (meta_pred == 1) & signal_mask + n_trusted = int(trusted_mask.sum()) + n_signals = int(signal_mask.sum()) + return { + "n_signals_raw": n_signals, "n_signals_trusted": n_trusted, + "coverage": (n_trusted / n_signals) if n_signals else float("nan"), + "signal_precision_filtered": ( + float(np.mean(y_true_idx[trusted_mask] == y_pred_idx[trusted_mask])) if n_trusted else float("nan") + ), + } + + +def compute_feature_attribution(model: keras.Model, X_test: np.ndarray, asset_id_test: np.ndarray, + feature_names: list[str] | None = None) -> pd.Series: + """ + Atribución por gradiente |∂ŷ/∂x| promediada sobre timesteps y muestras. NO son los pesos + de BahdanauAttention (esos ponderan PASOS TEMPORALES, no canales de feature) — esta es la + métrica correcta para cuantificar cuánto responde la salida a NEWS_SENTIMENT_SCORE frente + a las otras variables del tensor. + + V27 -- FIX (ValueError: Length of values (30) != length of index (31)): + el default anterior (`FEATURE_NAMES` de módulo) se construía en IMPORT + TIME, capturando TECH_COLS ANTES de que `_apply_news_sentiment_gate()` + lo mutara en `run_regime_pipeline`. La concatenación `[...] + TECH_COLS + + [...]` crea una lista NUEVA, no una vista -- quedaba congelada en 31 + elementos aunque TECH_COLS mutara a 24. Ahora se recalcula acá, en el + momento de la llamada (post-gate), leyendo TECH_COLS YA MUTADO. + """ + if feature_names is None: + feature_names = ["LOG_RETURN_1D"] + TECH_COLS + MACRO_TICKERS + import tensorflow as tf + + x_tensor = tf.convert_to_tensor(X_test, dtype=tf.float32) + asset_tensor = tf.convert_to_tensor(asset_id_test.reshape(-1, 1), dtype=tf.int32) + + with tf.GradientTape() as tape: + tape.watch(x_tensor) + preds = model([x_tensor, asset_tensor], training=False) + grads = tape.gradient(preds, x_tensor) + + mean_abs_grad = keras.ops.convert_to_numpy(keras.ops.mean(keras.ops.abs(grads), axis=(0, 1))) + return pd.Series(mean_abs_grad, index=feature_names, name="mean_abs_gradient").sort_values(ascending=False) + + +def extract_temporal_attention(model: keras.Model, X_test: np.ndarray, asset_id_test: np.ndarray) -> np.ndarray: + """Pesos reales de BahdanauAttention por PASO TEMPORAL (diagnóstico complementario, no por feature).""" + attention_extractor = keras.Model( + inputs=model.inputs, + outputs=model.get_layer("bahdanau_attention").output[1], + name="attention_extractor", + ) + weights = attention_extractor.predict([X_test, asset_id_test.reshape(-1, 1)], verbose=0) + return weights.squeeze(-1) + + +def plot_regime_evaluation(results: dict[str, dict], regime_name: str, output_path: Path) -> None: + """ + Grilla no-bloqueante (Requerimiento 3): un panel Real-vs-Predicho por + ticker del régimen, todo en UN solo `evaluation_chart.png`. JAMÁS + `plt.show()` — el archivo se renderiza directo a disco vía `savefig` + para permitir ejecución 100% headless. + """ + tickers = list(results.keys()) + n = len(tickers) + n_cols = 2 if n > 1 else 1 + n_rows = int(np.ceil(n / n_cols)) + + fig, axes = plt.subplots(n_rows, n_cols, figsize=(14, 5 * n_rows), squeeze=False) + + for idx, ticker in enumerate(tickers): + ax = axes[idx // n_cols][idx % n_cols] + r = results[ticker] + ax.plot(r["dates"], r["price_true"], label="Real", color="#1f77b4", linewidth=1.6) + ax.plot(r["dates"], r["price_pred"], label="Predicho (reconstruido)", + color="#d62728", linewidth=1.3, linestyle="--") + ax.set_title(f"{ticker} — DirAcc={r['directional_accuracy'] * 100:.1f}% " + f"MAE=${r['mae_price']:.2f}") + ax.xaxis.set_major_locator(mdates.AutoDateLocator()) + ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y")) + ax.legend(fontsize=8) + ax.grid(alpha=0.3) + + # Oculta ejes sobrantes si el número de tickers es impar. + for idx in range(n, n_rows * n_cols): + axes[idx // n_cols][idx % n_cols].axis("off") + + fig.suptitle(f"KodaQuant V5 — {regime_name} — Predicho vs. Real (Test)", fontsize=14) + fig.autofmt_xdate() + plt.tight_layout() + plt.savefig(output_path, dpi=150) # NUNCA plt.show() — Requerimiento 3 (cero bloqueos). + plt.close(fig) + logger.info(" Gráfico de evaluación -> %s", output_path) + + +def plot_triple_barrier_evaluation(results: dict[str, dict], regime_name: str, output_path: Path) -> None: + """ + Grilla no-bloqueante V22 (mismo contrato que `plot_regime_evaluation`: + JAMÁS `plt.show()`) para `target_mode="triple_barrier"` -- no hay + precio que reconstruir, así que el panel por activo es matriz de + confusión (heatmap manual, sin sumar `sklearn.metrics. + ConfusionMatrixDisplay` como dependencia extra) + distribución de + clases real vs. predicha. + """ + tickers = list(results.keys()) + n = len(tickers) + fig, axes = plt.subplots(n, 2, figsize=(11, 5 * n), squeeze=False) + + for idx, ticker in enumerate(tickers): + r = results[ticker] + ax_cm, ax_dist = axes[idx][0], axes[idx][1] + + cm = r["confusion_matrix"] + cm_norm = cm / np.maximum(cm.sum(axis=1, keepdims=True), 1) + ax_cm.imshow(cm_norm, cmap="Blues", vmin=0, vmax=1) + ax_cm.set_xticks(range(3)) + ax_cm.set_xticklabels(TB_CLASS_NAMES) + ax_cm.set_yticks(range(3)) + ax_cm.set_yticklabels(TB_CLASS_NAMES) + ax_cm.set_xlabel("Predicho") + ax_cm.set_ylabel("Real") + for i in range(3): + for j in range(3): + ax_cm.text(j, i, f"{cm[i, j]}", ha="center", va="center", + color="white" if cm_norm[i, j] > 0.5 else "black", fontsize=9) + ax_cm.set_title(f"{ticker} — Matriz de confusión (Acc={r['accuracy'] * 100:.1f}%, " + f"AccAccionable={r['actionable_accuracy'] * 100:.1f}%)") + + x = np.arange(3) + width = 0.35 + true_counts = [r["class_dist_true"][c] for c in TB_CLASS_NAMES] + pred_counts = [r["class_dist_pred"][c] for c in TB_CLASS_NAMES] + ax_dist.bar(x - width / 2, true_counts, width, label="Real", color="#1f77b4") + ax_dist.bar(x + width / 2, pred_counts, width, label="Predicho", color="#d62728") + ax_dist.set_xticks(x) + ax_dist.set_xticklabels(TB_CLASS_NAMES) + ax_dist.set_title(f"{ticker} — Distribución de clases (n_test={r['n_test']}, " + f"PrecisiónSeñal={r['signal_precision'] * 100:.1f}%)") + ax_dist.legend(fontsize=8) + ax_dist.grid(alpha=0.3, axis="y") + + fig.suptitle(f"KodaQuant V22 — {regime_name} — Triple Barrier (Test)", fontsize=14) + plt.tight_layout() + plt.savefig(output_path, dpi=150) # NUNCA plt.show() — mismo contrato que plot_regime_evaluation. + plt.close(fig) + logger.info(" Gráfico de evaluación -> %s", output_path) + + +# ============================================================ +# AUDITORÍA PURGED WALK-FORWARD (Fase 2, capa 1 -- ver purged_fold_bounds) +# ============================================================ +def calibrate_class_bias(model: keras.Model, X_val: np.ndarray, asset_id_val: np.ndarray, + y_val: np.ndarray, class_idx: int, + bias_grid: tuple[float, ...] = tuple(round(b, 2) for b in np.arange(0.0, 0.32, 0.02))): + """ + V27 -- ajuste de UMBRAL post-hoc, cero reentrenamiento. Busca, sobre + `X_val` (cola cronológica separada de train, NUNCA vista en pesos), el + bias aditivo a `y_pred_proba[:, class_idx]` que maximiza el RECALL + MACRO (promedio simple de recall por clase, sin ponderar por soporte -- + a propósito: es la única métrica que castiga por igual un recall=0% + en la clase minoritaria, que es EXACTAMENTE el síntoma que se está + corrigiendo). El bias elegido se aplica de forma IDÉNTICA en test -- + la calibración es el ÚNICO uso permitido de X_val; ni una fila de test + participa de esta búsqueda. + """ + from sklearn.metrics import recall_score + + y_pred_proba_val = model.predict([X_val, asset_id_val.reshape(-1, 1)], verbose=0) + y_true_idx_val = np.argmax(y_val, axis=-1) + + best_bias, best_macro_recall = 0.0, -1.0 + for bias in bias_grid: + adjusted = y_pred_proba_val.copy() + adjusted[:, class_idx] += bias + y_pred_idx_adj = np.argmax(adjusted, axis=-1) + macro_recall = recall_score(y_true_idx_val, y_pred_idx_adj, labels=[0, 1, 2], + average="macro", zero_division=0) + if macro_recall > best_macro_recall: + best_bias, best_macro_recall = bias, macro_recall + + baseline_pred = np.argmax(y_pred_proba_val, axis=-1) + baseline_macro_recall = recall_score(y_true_idx_val, baseline_pred, labels=[0, 1, 2], + average="macro", zero_division=0) + logger.info(" [BIAS-CAL] clase=%s bias=%.2f recall_macro val: sin_bias=%.1f%% -> con_bias=%.1f%%", + TB_CLASS_NAMES[class_idx], best_bias, baseline_macro_recall * 100, best_macro_recall * 100) + return best_bias + + +def run_cpcv_audit(ticker: str, k: int = 5, embargo_frac: float = 0.02, + epochs_per_fold: int = 20, exclude_timeout_from_train: bool = False) -> pd.DataFrame: + """ + V27 -- re-entrena el MISMO build_model/build_asset_dataset k veces, + cada vez con más historia de train y un bloque de test más adelante en + el tiempo (walk-forward, prefijo creciente -- reutiliza `build_asset_ + dataset` SIN modificarlo, pasándole distintos `train_ratio` sobre + slices `df.iloc[:test_end]`), purgando+embargando la fuga de horizonte + con el mismo mecanismo que ya usa el split único de producción. Da una + DISTRIBUCIÓN de score OOS en vez de un solo número. + + Un solo path por fold (walk-forward), NO CPCV combinatorio completo -- + ver costo real en el docstring de `purged_fold_bounds`. `epochs_per_ + fold` deliberadamente bajo (20 vs 100/180 de producción): esto audita + VARIANZA entre folds, no reemplaza el modelo servido. NUNCA escribe a + `services/kodaquant_models/` -- checkpoints de fold se borran al vuelo. + """ + regime_name = next((r for r, cfg in REGIMES.items() if ticker in cfg["tickers"]), None) + if regime_name is None: + raise ValueError(f"[CPCV] '{ticker}' no pertenece a ningún régimen de REGIMES.") + target_mode = REGIMES[regime_name]["target_mode"] + + logger.info("[CPCV] Descargando %s (régimen=%s)...", ticker, regime_name) + all_market_data = download_all([ticker], MACRO_TICKERS, REGIMES[regime_name].get("period", PERIOD), + cache_tag=f"cpcv_{ticker}", macro_period=PERIOD) + df = engineer_asset(all_market_data, ticker, MACRO_TICKERS) + + tb_params_ticker = None + if target_mode == "triple_barrier" and CRYPTO_CALIBRATE_BARRIERS: + tb_params_ticker = calibrate_crypto_triple_barrier({ticker: df}, [ticker], train_ratio=TRAIN_RATIO)[ticker] + + folds = purged_fold_bounds(len(df), k, embargo_frac) + asset_to_id_audit = {ticker: 0} + monitor_metric = "val_actionable_accuracy" if target_mode == "triple_barrier" else "val_directional_accuracy_metric" + rows = [] + + for i, (test_start, test_end, _embargo_end) in enumerate(folds): + if test_start < LOOKBACK + BATCH_SIZE: + logger.warning("[CPCV] fold %d/%d: train insuficiente (test_start=%d) -- salteado.", i + 1, k, test_start) + continue + df_fold = df.iloc[:test_end] + train_ratio_fold = test_start / len(df_fold) + + train, test, feature_scaler, target_scaler = build_asset_dataset( + df_fold, ticker, LOOKBACK, train_ratio_fold, asset_to_id_audit, + target_mode=target_mode, tb_params=tb_params_ticker, + exclude_timeout_from_train=exclude_timeout_from_train, + ) + if len(train["X"]) == 0 or len(test["X"]) == 0: + logger.warning("[CPCV] fold %d/%d: train o test vacío tras purga -- salteado.", i + 1, k) + continue + + class_alpha = None + if target_mode == "triple_barrier": + train_class_idx = np.argmax(train["y"], axis=-1) + class_counts = np.maximum(np.bincount(train_class_idx, minlength=3).astype(np.float64), 1.0) + class_alpha = np.clip(len(train_class_idx) / (3.0 * class_counts), 0.25, 4.0).tolist() + + # V27 -- cola de validación tal cual `run_regime_pipeline` (crudo, + # cronológicamente posterior a todo lo que entra a train_fit, cero + # oversampling) -- ÚNICO propósito: calibrar el bias de umbral sin + # tocar test. + # V27 -- FIX: el intento anterior entrenaba sobre X_fit_fold (10% + # menos datos que train completo) -- con un dataset ya chico eso + # bastó para desestabilizar la convergencia (colapso degenerado + # distinto en cada corrida, no comparable). Se entrena SIEMPRE + # sobre train COMPLETO (idéntico a toda corrida previa, incluida la + # que dio recall TIMEOUT=0%/std=0% que estamos diagnosticando). La + # cola de calibración se recorta ADEMÁS, no EN VEZ de -- queda "en + # muestra" (el modelo ya vio esas filas al entrenar) a propósito: + # es un límite superior optimista de lo que el bias puede lograr. + # Si ni ahí ayuda en test, no vale la pena perseguirlo más. + n_val_fold = max(1, int(round(len(train["X"]) * VALIDATION_SPLIT))) if target_mode == "triple_barrier" else 0 + n_fit_fold = len(train["X"]) - n_val_fold + X_val_fold = train["X"][n_fit_fold:] + y_val_fold = train["y"][n_fit_fold:] + asset_id_val_fold = train["asset_id"][n_fit_fold:] + + steps_per_epoch = max(1, len(train["X"]) // BATCH_SIZE) + model, gamma_variable = build_model( + n_timesteps=LOOKBACK, n_features=N_FEATURES, n_assets=1, + steps_per_epoch=steps_per_epoch, regime_name=regime_name, + target_mode=target_mode, class_alpha=class_alpha, + focal_gamma=TRIPLE_BARRIER_FOCAL_GAMMA, label_smoothing=TRIPLE_BARRIER_LABEL_SMOOTHING, + ) + fold_ckpt = DATA_DIR / f"_cpcv_audit_{ticker}_fold{i}.keras" # descartable -- nunca lo lee quanti_engine.py + _, model = train_model( + model, train["X"], train["asset_id"].reshape(-1, 1), train["y"], + checkpoint_path=fold_ckpt, epochs=epochs_per_fold, batch_size=BATCH_SIZE, + gamma_variable=gamma_variable, gamma_max=GAMMA_MAX, + gamma_warmup_epochs=min(GAMMA_WARMUP_EPOCHS, max(1, epochs_per_fold // 2)), + gamma_schedule=GAMMA_SCHEDULE, gamma_sigmoid_steepness=GAMMA_SIGMOID_STEEPNESS, + sample_weight=train.get("sample_weight"), monitor_metric=monitor_metric, + ) + fold_ckpt.unlink(missing_ok=True) + + timeout_bias = 0.0 + if target_mode == "triple_barrier" and len(X_val_fold) >= 20: + timeout_bias = calibrate_class_bias(model, X_val_fold, asset_id_val_fold, y_val_fold, + class_idx=TB_TIMEOUT_CLASS_IDX) + + if target_mode == "triple_barrier": + r = evaluate_asset_triple_barrier(model, test, ticker) + score = r["actionable_accuracy"] + # V27 -- por-clase, NO solo el agregado. AccAccionable puede + # esconder un sesgo sistemático (ver BTC 2026-09-20: 62% recall + # en SL, 43% en TP -- el 53.2% agregado no lo delataba) o un + # colapso de una clase entera (ver ETH: TIMEOUT casi sin + # predecir pese a alpha=1.914). `zero_division=0` porque un + # fold puede no predecir ninguna muestra de una clase -- eso es + # justamente lo que queremos poder VER, no que tire excepción. + from sklearn.metrics import precision_recall_fscore_support + _prec, _rec, _f1, _sup = precision_recall_fscore_support( + r["y_true_idx"], r["y_pred_idx"], labels=[0, 1, 2], zero_division=0) + fold_per_class = { + f"{cls}_{metric}": val + for cls, prec, rec, sup in zip(TB_CLASS_NAMES, _prec, _rec, _sup) + for metric, val in [("precision", prec), ("recall", rec), ("support", int(sup))] + } + logger.info(" [CPCV] fold %d/%d por-clase -- SL: prec=%.0f%% rec=%.0f%% (n=%d) " + "TIMEOUT: prec=%.0f%% rec=%.0f%% (n=%d) TP: prec=%.0f%% rec=%.0f%% (n=%d)", + i + 1, k, _prec[0] * 100, _rec[0] * 100, int(_sup[0]), + _prec[1] * 100, _rec[1] * 100, int(_sup[1]), + _prec[2] * 100, _rec[2] * 100, int(_sup[2])) + # V27 -- diagnóstico: ¿TIMEOUT nunca gana el argmax porque está + # CERCA (problema de umbral, corregible sin reentrenar) o porque + # su probabilidad está MUERTA (problema de capacidad/features, + # necesita cambios reales)? Media de probabilidad ASIGNADA, + # no de veces que ganó -- eso es lo que la matriz de confusión + # no puede mostrar. + _mean_proba = r["y_pred_proba"].mean(axis=0) + logger.info(" [CPCV] fold %d/%d probabilidad media asignada -- SL=%.2f TIMEOUT=%.2f TP=%.2f", + i + 1, k, _mean_proba[0], _mean_proba[1], _mean_proba[2]) + + if timeout_bias > 0.0: + # V27 -- efecto del bias sobre TEST (nunca usado en + # calibrate_class_bias) -- comparación honesta, no la + # ganancia inflada que ya vimos en val con el meta-labeler. + _adj_proba = r["y_pred_proba"].copy() + _adj_proba[:, TB_TIMEOUT_CLASS_IDX] += timeout_bias + y_pred_idx_bias = np.argmax(_adj_proba, axis=-1) + actionable_mask_bias = r["y_true_idx"] != TB_TIMEOUT_CLASS_IDX + actionable_acc_bias = ( + float(np.mean(y_pred_idx_bias[actionable_mask_bias] == r["y_true_idx"][actionable_mask_bias])) + if actionable_mask_bias.any() else float("nan") + ) + _prec_b, _rec_b, _, _ = precision_recall_fscore_support( + r["y_true_idx"], y_pred_idx_bias, labels=[0, 1, 2], zero_division=0) + logger.info(" [CPCV] fold %d/%d CON bias=%.2f -- AccAccionable: %.1f%% -> %.1f%% " + "recall TIMEOUT: %.0f%% -> %.0f%% recall SL: %.0f%% -> %.0f%% recall TP: %.0f%% -> %.0f%%", + i + 1, k, timeout_bias, score * 100, actionable_acc_bias * 100, + _rec[1] * 100, _rec_b[1] * 100, _rec[0] * 100, _rec_b[0] * 100, + _rec[2] * 100, _rec_b[2] * 100) + else: + r = evaluate_asset(model, test, ticker, target_scaler) + score = r["directional_accuracy"] + fold_per_class = {} + + logger.info("[CPCV] fold %d/%d test=[%d:%d) n_train=%d n_test=%d score=%.1f%%", + i + 1, k, test_start, test_end, len(train["X"]), len(test["X"]), score * 100) + rows.append({"fold": i, "test_start": test_start, "test_end": test_end, + "n_train": len(train["X"]), "n_test": len(test["X"]), "score": score, + **fold_per_class}) + + result = pd.DataFrame(rows) + if len(result) >= 2: + logger.info("[CPCV] %s -- %d/%d folds válidos. score: media=%.1f%% std=%.1f%% min=%.1f%% max=%.1f%%", + ticker, len(result), k, result["score"].mean() * 100, result["score"].std() * 100, + result["score"].min() * 100, result["score"].max() * 100) + # V27 -- ¿el sesgo por clase es CONSISTENTE entre folds (señal real + # de que el modelo tiene un problema estructural) o varía fold a + # fold (ruido de muestra, no vale la pena perseguirlo)? Un recall + # de TIMEOUT bajo Y con poca varianza entre folds = el modelo + # estructuralmente no aprende a abstenerse, no es mala suerte de + # este test set puntual. + if "TIMEOUT_recall" in result.columns: + for cls in TB_CLASS_NAMES: + rec_col = f"{cls}_recall" + if rec_col in result.columns and result[rec_col].notna().any(): + logger.info(" [CPCV] %s -- recall %-8s entre folds: media=%.0f%% std=%.0f%% min=%.0f%% max=%.0f%%", + ticker, cls, result[rec_col].mean() * 100, result[rec_col].std() * 100, + result[rec_col].min() * 100, result[rec_col].max() * 100) + else: + logger.warning("[CPCV] %s -- menos de 2 folds válidos, sin distribución que reportar.", ticker) + return result + + +# ============================================================ +# ORQUESTACIÓN POR RÉGIMEN (Requerimiento 2: ciclos independientes y secuenciales) +# ============================================================ +def run_regime_pipeline(regime_name: str, regime_cfg: dict) -> dict: + _apply_news_sentiment_gate() + """Ejecuta las Fases A-E completas para UN especialista y persiste sus artefactos.""" + tickers = regime_cfg["tickers"] + oversample_factor = float(regime_cfg.get("oversample_factor", 1.0)) + arch = REGIME_ARCHITECTURE[regime_name] + + # V22 — target_mode bifurca el pipeline aguas abajo (dataset/modelo/ + # loss/evaluación/persistencia); default "regression" preserva la + # ARQUITECTURA de equity_specialist igual a V6. V23.5 había roto la + # paridad bit a bit con un sample_weight por volatilidad -- ROLLBACK en + # V23.6 (ver changelog del módulo): equity_specialist vuelve a ser bit a + # bit idéntico a V6/pre-V23.5, gradiente plano/uniforme. + target_mode = regime_cfg.get("target_mode", "regression") + tb_params_by_ticker: dict[str, dict] | None = None + if target_mode == "triple_barrier": + # V23.5 -- default POR TICKER (mismos valores de regime_cfg para + # todos, fallback si CRYPTO_CALIBRATE_BARRIERS=False) -- ver + # docstring de `calibrate_crypto_triple_barrier` para el esquema. + _default_tb = { + "pt_mult": regime_cfg.get("pt_mult", TRIPLE_BARRIER_PT_MULT), + "sl_mult": regime_cfg.get("sl_mult", TRIPLE_BARRIER_SL_MULT), + "max_holding_days": regime_cfg.get("max_holding_days", TRIPLE_BARRIER_MAX_HOLDING_DAYS), + "vol_lookback": regime_cfg.get("vol_lookback", TRIPLE_BARRIER_VOL_LOOKBACK), + } + tb_params_by_ticker = {t: dict(_default_tb) for t in regime_cfg["tickers"]} + + # Rutas de producción estándar — sin sufijos `_experimental`: cada + # régimen escribe DIRECTO en la carpeta que lee `quanti_engine.py` en + # inferencia, idéntico en corrida local y en el cron de CI/CD. + output_dir = MODELS_ROOT / regime_name + output_dir.mkdir(parents=True, exist_ok=True) + asset_to_id = {t: i for i, t in enumerate(tickers)} + + logger.info("=" * 78) + logger.info("REGIMEN: %s | target_mode=%s | Universo: %s | BiLSTM=%du heads=%d " + "residual_extra=%s dropout=%.2f L2=%.0e", + regime_name, target_mode, tickers, arch["lstm_units"], arch["mha_heads"], + arch["extra_residual_block"], arch["dropout_rate"], arch["dense_l2_reg"]) + logger.info("=" * 78) + + logger.info("[1/5] Descargando %d activos (OHLCV) + %d factores macro (%s)...", + len(tickers), len(MACRO_TICKERS), PERIOD) + all_market_data = download_all(tickers, MACRO_TICKERS, regime_cfg.get("period", PERIOD), cache_tag=regime_name, + macro_period=PERIOD) + + # V23 -- Ingeniería de features UNA vez por ticker, reutilizada tanto + # por la calibración dinámica de barreras (train-only) como por + # `build_asset_dataset` abajo -- cero recómputo redundante. + df_assets = {t: engineer_asset(all_market_data, t, MACRO_TICKERS) for t in tickers} + + if target_mode == "triple_barrier" and CRYPTO_CALIBRATE_BARRIERS: + logger.info("[1.5/5] Calibración dinámica Triple Barrier (V23.5, train-only, POR ACTIVO %s)...", tickers) + tb_params_by_ticker = calibrate_crypto_triple_barrier(df_assets, tickers, train_ratio=TRAIN_RATIO) + + if target_mode == "triple_barrier": + for t in tickers: + tb_t = tb_params_by_ticker[t] + logger.info(" Triple Barrier [%s]: pt_mult=%.2f sl_mult=%.2f max_holding_days=%d vol_lookback=%d", + t, tb_t["pt_mult"], tb_t["sl_mult"], tb_t["max_holding_days"], tb_t["vol_lookback"]) + + # ROLLBACK V23.6: el bloque de sample_weight por volatilidad de equity + # (V23.5, Directiva 2) vivía acá -- purgado por completo, ver changelog + # del módulo. `equity_specialist` ya no calcula ni loguea ningún peso. + logger.info("[2/5] Construcción de dataset por activo...") + feature_scalers, target_scalers = {}, {} + X_train_parts, y_train_parts, asset_id_train_parts, sample_weight_train_parts = [], [], [], [] + # V27 (fix REAL de leakage train/validación -- ver docstring extenso más + # abajo, junto al carve) -- SOLO se usan para target_mode="triple_barrier"; + # quedan vacíos y sin ningún efecto para "regression" (equity_specialist, + # comportamiento 100% intacto). + X_val_parts, y_val_parts, asset_id_val_parts, sample_weight_val_parts = [], [], [], [] + test_sets = {} + + for ticker in tickers: + df_asset = df_assets[ticker] + tb_params_ticker = tb_params_by_ticker[ticker] if tb_params_by_ticker is not None else None + train, test, f_scaler, t_scaler = build_asset_dataset( + df_asset, ticker, LOOKBACK, TRAIN_RATIO, asset_to_id, + target_mode=target_mode, tb_params=tb_params_ticker, + ) + feature_scalers[ticker] = f_scaler + target_scalers[ticker] = t_scaler # None por-ticker si target_mode="triple_barrier" + test_sets[ticker] = test + + if target_mode == "triple_barrier": + # V27 (fix REAL de leakage train/validación) -- carve CRONOLÓGICO + # (últimas `VALIDATION_SPLIT` filas de ESTE activo, en el orden + # temporal que `build_asset_dataset` ya garantiza) ANTES de que + # `_magnitude_warp_oversample` toque nada. Root cause del síntoma + # real observado (val_actionable_accuracy llegando a 87% durante + # el entrenamiento, PrecisiónSeñal real cayendo a 44% en el test + # final -- por debajo del baseline trivial): `_magnitude_warp_oversample` + # genera copias bootstrap+magnitude-warp de ventanas de TRAIN y + # las PERMUTA junto con los originales en un único array; el + # `validation_split` nativo de Keras (`model.fit(..., validation_ + # split=0.1)`, ver `train_model`) toma el último 10% de ESE array + # ya mezclado como "validación" -- una ventana original y su + # copia magnitude-warped (misma etiqueta, misma ventana subyacente + # con la amplitud apenas deformada) podían caer una en el 90% de + # entrenamiento y la otra en el 10% de "validación". El modelo no + # generalizaba: memorizaba la firma de la ventana original y + # reconocía a su hermana deformada -- de ahí una val_accuracy + # fantasiosa para un problema de dirección diaria de cripto, que + # jamás se sostuvo contra el test set genuinamente nunca-visto. + # Fix: la validación se separa ACÁ, de datos 100% crudos (sin + # ninguna copia aumentada, cronológicamente POSTERIORES a todo lo + # que entra a `_magnitude_warp_oversample`) -- ni una ventana de + # validación tiene, ni puede tener, una copia hermana en train. + n_val = max(1, int(round(len(train["X"]) * VALIDATION_SPLIT))) + n_fit = len(train["X"]) - n_val + X_val_parts.append(train["X"][n_fit:]) + y_val_parts.append(train["y"][n_fit:]) + asset_id_val_parts.append(train["asset_id"][n_fit:]) + sample_weight_val_parts.append(train["sample_weight"][n_fit:]) + train = dict( + X=train["X"][:n_fit], y=train["y"][:n_fit], asset_id=train["asset_id"][:n_fit], + last_price=train["last_price"][:n_fit], dates=train["dates"][:n_fit], + sample_weight=train["sample_weight"][:n_fit], y_return=train["y_return"][:n_fit], + y_class_idx=train["y_class_idx"][:n_fit], + ) + + X_train_parts.append(train["X"]) + y_train_parts.append(train["y"]) + asset_id_train_parts.append(train["asset_id"]) + if target_mode == "triple_barrier": + sample_weight_train_parts.append(train["sample_weight"]) + # ROLLBACK V23.6: la rama "regression" que aquí ensamblaba el + # sample_weight por volatilidad de equity fue purgada -- ver + # changelog del módulo. equity_specialist ya no acumula pesos. + if target_mode == "triple_barrier": + logger.info(" %-10s train_fit=%5d train_val=%5d test=%5d", + ticker, len(train["X"]), n_val, len(test["X"])) + else: + logger.info(" %-10s train=%5d test=%5d", ticker, len(train["X"]), len(test["X"])) + + X_train = np.concatenate(X_train_parts, axis=0) + y_train = np.concatenate(y_train_parts, axis=0) + asset_id_train_flat = np.concatenate(asset_id_train_parts, axis=0) + # ROLLBACK V23.6: target_mode="regression" (equity_specialist) ya NUNCA + # usa sample_weight -- gradiente plano/uniforme, sample_weight=None, + # bit a bit idéntico a V6/pre-V23.5. Solo triple_barrier (cripto, + # Directiva 3: magnitud de PnL + uniqueness) sigue pesando muestras. + _uses_sample_weight = target_mode == "triple_barrier" + sample_weight_train_flat = ( + np.concatenate(sample_weight_train_parts, axis=0) if _uses_sample_weight else None + ) + logger.info(" Dataset %s combinado -> X_train %s", regime_name, X_train.shape) + + # V27 (fix REAL de leakage train/validación, ver docstring del carve + # por-activo arriba) -- validation_data EXPLÍCITO, ensamblado de las + # colas crudas por-activo, NUNCA tocado por `_magnitude_warp_oversample`. + # `None` para target_mode="regression" -- equity_specialist sigue usando + # el `validation_split` nativo de Keras exactamente como antes (ver + # `train_model`), cero cambio de comportamiento ahí. + validation_data_bundle = None + if target_mode == "triple_barrier": + X_val = np.concatenate(X_val_parts, axis=0) + y_val = np.concatenate(y_val_parts, axis=0) + asset_id_val_flat = np.concatenate(asset_id_val_parts, axis=0) + sample_weight_val_flat = np.concatenate(sample_weight_val_parts, axis=0) + asset_id_val = asset_id_val_flat.reshape(-1, 1) + validation_data_bundle = ([X_val, asset_id_val], y_val, sample_weight_val_flat) + logger.info(" Validación %s (cronológica, cruda, pre-oversampling) -> X_val %s", + regime_name, X_val.shape) + + assert X_train.shape[-1] == N_FEATURES, ( + f"Desalineación de features: X_train tiene {X_train.shape[-1]} columnas " + f"pero N_FEATURES={N_FEATURES} (TECH_COLS={TECH_COLS})." + ) + + # V6 (Requerimiento 5) — balanceo de volumen SOLO sobre train (ver + # `_magnitude_warp_oversample`); no-op exacto si oversample_factor<=1.0. + # V22: `sample_weight_train_flat` viaja SINCRONIZADO con X/y/asset_id + # (mismos índices de bootstrap/permutación) -- ver docstring de la función. + n_before = len(X_train) + X_train, y_train, asset_id_train_flat, sample_weight_train_flat = _magnitude_warp_oversample( + X_train, y_train, asset_id_train_flat, factor=oversample_factor, + sample_weight=sample_weight_train_flat, + ) + if oversample_factor > 1.0: + logger.info(" Oversampling Magnitude-Warping (factor=%.1fx, sigma=%.2f, knots=%d): X_train %d -> %d muestras", + oversample_factor, MAGNITUDE_WARP_SIGMA, MAGNITUDE_WARP_KNOTS, n_before, len(X_train)) + asset_id_train = asset_id_train_flat.reshape(-1, 1) + + # V22 — `class_alpha` (CategoricalFocalCrossentropy, ver build_model): + # balanceo de clases fiteado sobre la distribución REAL de train + # post-oversampling (fórmula de sklearn.utils.compute_class_weight, + # 'balanced': n_samples / (n_classes * count_c) -- ver docstring de + # TRIPLE_BARRIER_FOCAL_GAMMA arriba, deliberadamente separado del + # sample_weight de magnitud/PnL). + class_alpha = None + if target_mode == "triple_barrier": + train_class_idx = np.argmax(y_train, axis=-1) + class_counts = np.maximum(np.bincount(train_class_idx, minlength=3).astype(np.float64), 1.0) + class_alpha = np.clip(len(train_class_idx) / (3.0 * class_counts), 0.25, 4.0).tolist() + logger.info(" Triple Barrier -- distribución de clases en train: SL=%d TIMEOUT=%d TP=%d -> alpha=%s", + int(class_counts[0]), int(class_counts[1]), int(class_counts[2]), + [f"{a:.3f}" for a in class_alpha]) + + logger.info("[3/5] Construyendo y entrenando el modelo especialista '%s'...", regime_name) + # V27 -- con `validation_data_bundle` explícito (triple_barrier), TODO + # `X_train` post-oversampling es fit real -- ya no hay `validation_split` + # interno de Keras restándole una porción (esa porción ahora es + # `X_val`, separada ANTES del oversampling, ver arriba). `equity_ + # specialist` (regression) conserva la fórmula original intacta. + n_fit_samples = len(X_train) if validation_data_bundle is not None else int(len(X_train) * (1 - VALIDATION_SPLIT)) + steps_per_epoch = max(1, n_fit_samples // BATCH_SIZE) + model, gamma_variable = build_model( + n_timesteps=LOOKBACK, n_features=N_FEATURES, n_assets=len(tickers), + steps_per_epoch=steps_per_epoch, regime_name=regime_name, + huber_delta=HUBER_DELTA, gamma_initial=GAMMA_INITIAL, + variance_lambda=VARIANCE_LAMBDA, variance_cap=VARIANCE_CAP, + gaussian_nll_beta=GAUSSIAN_NLL_BETA, + log_var_min=LOG_VAR_MIN, log_var_max=LOG_VAR_MAX, + log_var_l2_lambda=LOG_VAR_L2_LAMBDA, log_var_barrier_lambda=LOG_VAR_BARRIER_LAMBDA, + target_mode=target_mode, class_alpha=class_alpha, + focal_gamma=TRIPLE_BARRIER_FOCAL_GAMMA, label_smoothing=TRIPLE_BARRIER_LABEL_SMOOTHING, + ) + model.summary(print_fn=logger.info) + if target_mode == "triple_barrier": + logger.info(" CategoricalFocalCrossentropy: gamma=%.1f label_smoothing=%.2f alpha=%s", + TRIPLE_BARRIER_FOCAL_GAMMA, TRIPLE_BARRIER_LABEL_SMOOTHING, + [f"{a:.3f}" for a in class_alpha]) + else: + logger.info(" Curriculum gamma: %.1f -> %.1f en %d épocas (schedule=%s)", + GAMMA_INITIAL, GAMMA_MAX, GAMMA_WARMUP_EPOCHS, GAMMA_SCHEDULE) + logger.info(" LR CosineDecayRestarts: init=%.1e primer_ciclo=%d steps (%d épocas) t_mul=%.1f m_mul=%.2f", + LR_INITIAL, steps_per_epoch * COSINE_RESTART_EPOCH_PERIOD, + COSINE_RESTART_EPOCH_PERIOD, COSINE_T_MUL, COSINE_M_MUL) + + checkpoint_path = output_dir / "model_v5_best.keras" + _monitor_metric_val = ("val_actionable_accuracy" if target_mode == "triple_barrier" + else "val_directional_accuracy_metric") + history, model = train_model( + model, X_train, asset_id_train, y_train, + checkpoint_path=checkpoint_path, + epochs=regime_cfg.get("epochs", EPOCHS), batch_size=BATCH_SIZE, validation_split=VALIDATION_SPLIT, + validation_data=validation_data_bundle, + gamma_variable=gamma_variable, gamma_max=GAMMA_MAX, + gamma_warmup_epochs=GAMMA_WARMUP_EPOCHS, gamma_schedule=GAMMA_SCHEDULE, + gamma_sigmoid_steepness=GAMMA_SIGMOID_STEEPNESS, + sample_weight=sample_weight_train_flat, + monitor_metric=_monitor_metric_val, + # placeholder-anchor -- NO TOCAR el resto de este call, ver abajo + # V23.4 -- REVERTIDO para equity_specialist (evidencia real, corrida + # V23.3: alinear ModelCheckpoint a val_directional_accuracy_metric + # empeoró 5 de 8 tickers -- AAPL 53.5->52.3, MSFT 52.3->51.3, + # NVDA 52.7->52.1, GOOGL 52.7->51.7 -- vs solo 3 mejoraron. Causa: + # a diferencia de cripto (donde val_loss pondera 3 clases + alpha, + # objetivo CASI desconectado de actionable_accuracy), en la + # regresión de equity val_loss (Gaussian NLL direccional) YA está + # fuertemente correlacionado con DirAcc -- alinear el checkpoint a + # una métrica discreta y RUIDOSA (accuracy binaria sobre un + # val_split de solo 10%) generalizó peor que el val_loss suave que + # ya traía V6. Mismo bug, pero el fix solo ayuda donde el + # desacople objetivo/métrica es real (cripto); en equity el + # checkpoint original YA era el correcto. Mantenido SOLO en + # cripto, donde BTC AccAccionable 46.0->49.3% y ETH 46.1->46.5% + # confirmaron la mejora. + checkpoint_monitor=(_monitor_metric_val if target_mode == "triple_barrier" else None), + ) + + # V27 -- Fase 2 capa 3 (meta-labeling): entrena EXCLUSIVAMENTE si este + # régimen usa triple_barrier (equity/regression no tiene noción de + # "señal accionable" a filtrar). `meta_clf=None` es un resultado válido + # (fail-open, ver docstring de train_meta_labeler) -- el resto del + # pipeline sigue funcionando exactamente igual que hoy si eso pasa. + meta_clf = None + if target_mode == "triple_barrier": + meta_clf, _meta_val_stats = train_meta_labeler(model, X_val, asset_id_val, y_val) + + if target_mode == "triple_barrier": + logger.info("[4/5] Evaluación por activo (clasificación Triple Barrier SL/TIMEOUT/TP)...") + results = {} + for ticker in tickers: + results[ticker] = evaluate_asset_triple_barrier(model, test_sets[ticker], ticker) + r = results[ticker] + # V27 (Directiva Head Quant) -- baseline trivial = predecir SIEMPRE + # la clase mayoritaria REAL (SL/TP/TIMEOUT, la que sea) en este test + # set. Si Acc del modelo queda POR DEBAJO de este número, el modelo + # no superó ni la apuesta más tonta posible -- el problema no es + # "falta de features"/"aprender más", es calibración/objetivo roto + # (síntoma típico: alpha de clase mal ajustado, o early stopping + # restaurando un checkpoint subóptimo). dist_pred (antes solo iba + # al PNG, invisible en el log de texto) expone si el modelo + # colapsó a predecir casi siempre UNA sola clase. + majority_true_count = max(r["class_dist_true"].values()) + baseline_acc = majority_true_count / r["n_test"] if r["n_test"] else float("nan") + logger.info(" %-10s Acc=%.1f%% (baseline trivial=%.1f%%) AccAccionable=%.1f%% " + "PrecisiónSeñal=%.1f%% (n_señales=%d) dist_real=%s dist_pred=%s", + ticker, r["accuracy"] * 100, baseline_acc * 100, r["actionable_accuracy"] * 100, + r["signal_precision"] * 100, r["n_signals"], r["class_dist_true"], r["class_dist_pred"]) + meta_r = evaluate_meta_labeler(meta_clf, r["y_pred_proba"], r["y_pred_idx"], r["y_true_idx"]) + if meta_r is not None: + logger.info(" %-10s [META-LABEL] cobertura=%.1f%% (%d/%d señales) " + "PrecisiónSeñal filtrada=%.1f%% (vs %.1f%% sin filtro)", + ticker, meta_r["coverage"] * 100, meta_r["n_signals_trusted"], + meta_r["n_signals_raw"], meta_r["signal_precision_filtered"] * 100, + r["signal_precision"] * 100) + results[ticker]["meta_label"] = meta_r + if r["accuracy"] < baseline_acc: + logger.warning( + " %-10s Acc del modelo (%.1f%%) POR DEBAJO del baseline trivial " + "(predecir siempre '%s', %.1f%%) -- señal de calibración/objetivo roto, " + "NO de falta de features. Antes de agregar señal nueva: (1) revisar la " + "matriz de confusión completa en evaluation_chart.png (¿colapsó a una " + "sola clase?); (2) confirmar que `alpha` de CategoricalFocalCrossentropy " + "(calibrado sobre train) sigue representando la distribución real de " + "ESTE test; (3) confirmar que el checkpoint restaurado por early stopping " + "es el óptimo según la métrica de monitoreo real (%s), no un óptimo local " + "de una época temprana con pocas señales.", + ticker, r["accuracy"] * 100, + max(r["class_dist_true"], key=r["class_dist_true"].get), baseline_acc * 100, + _monitor_metric_val, + ) + # Atribución por gradiente NO aplica acá (ver evaluate_asset_triple_barrier/ + # compute_feature_attribution): la suma de un softmax es constante=1, el + # gradiente de `sum(preds)` que usa tf.GradientTape para un target no-escalar + # sería ~0 en todo el tensor -- deliberadamente omitido, no un olvido. + chart_path = output_dir / "evaluation_chart.png" + plot_triple_barrier_evaluation(results, regime_name, chart_path) + else: + logger.info("[4/5] Evaluación por activo (reconstrucción de precio + directional accuracy)...") + results = {} + for ticker in tickers: + results[ticker] = evaluate_asset(model, test_sets[ticker], ticker, target_scalers[ticker]) + r = results[ticker] + logger.info(" %-10s MAE=$%.2f RMSE=$%.2f DirAcc=%.1f%%", + ticker, r["mae_price"], r["rmse_price"], r["directional_accuracy"] * 100) + + X_test_all = np.concatenate([test_sets[t]["X"] for t in tickers], axis=0) + asset_id_test_all = np.concatenate([test_sets[t]["asset_id"] for t in tickers], axis=0) + attribution = compute_feature_attribution(model, X_test_all, asset_id_test_all) + logger.info(" Atribución por gradiente (|∂ŷ/∂x|) — top 5 de %d variables:", len(attribution)) + for feat, val in attribution.head(5).items(): + marker = " <- NEWS_SENTIMENT_SCORE" if feat == "NEWS_SENTIMENT_SCORE" else "" + logger.info(" %-22s %.6f%s", feat, val, marker) + news_rank = int(attribution.index.get_loc("NEWS_SENTIMENT_SCORE")) + 1 + logger.info(" NEWS_SENTIMENT_SCORE -> rank %d/%d, atribución=%.6f", + news_rank, len(attribution), attribution["NEWS_SENTIMENT_SCORE"]) + + chart_path = output_dir / "evaluation_chart.png" + plot_regime_evaluation(results, regime_name, chart_path) + + logger.info("[5/5] Exportando modelo '%s' + scalers -> %s ...", regime_name, output_dir) + model_path = output_dir / "model_v5.keras" + scalers_path = output_dir / "scalers_dict.pkl" + + model.save(model_path, overwrite=True) + scalers_payload = { + "regime_name": regime_name, + "feature_scalers": feature_scalers, + "target_scalers": target_scalers, + "asset_to_id": asset_to_id, + "lookback": LOOKBACK, + "macro_tickers": MACRO_TICKERS, + "tickers": tickers, + "tech_cols": TECH_COLS, + "gk_uses_open": _GK_USED_OPEN, # V27 -- ver _GK_USED_OPEN / quanti_engine._compute_garman_klass_vol + "v28_cols": list(V28_COLS), # V28 -- auditoría de bundle + "v28_open_by_ticker": {t: bool(_V28_OPEN_BY_TICKER.get(t, False)) for t in tickers}, # V28 -- paridad Open train/serve + "target_mode": target_mode, + } + if target_mode == "triple_barrier": + # V23.5 -- esquema NUEVO: dict-de-dicts {ticker: {pt_mult, ...}}, + # ver docstring de módulo (punto 6) y de `calibrate_crypto_triple_ + # barrier` -- `quanti_engine.py` debe leer `tb_params[ticker]`. + scalers_payload["tb_params"] = tb_params_by_ticker + scalers_payload["tb_class_names"] = TB_CLASS_NAMES + + # AUDITORÍA RESCATE 2026-08 -- fix de alineación train/serve de + # FRAC_DIFF_LOG_CLOSE (ver docstring de `_LAST_FFD_D_BY_TICKER` arriba): + # persiste el `d` REAL calibrado en ESTA corrida para cada ticker de + # ESTE régimen. `quanti_engine.py` lo usa directo en vez de recalibrar + # sobre su ventana corta de inferencia; bundles viejos sin esta clave + # (`.get("ffd_d_by_ticker", {})` en el lado de lectura) preservan el + # comportamiento previo sin romperse. + scalers_payload["ffd_d_by_ticker"] = {t: _LAST_FFD_D_BY_TICKER[t] for t in tickers if t in _LAST_FFD_D_BY_TICKER} + with open(scalers_path, "wb") as f: + pickle.dump(scalers_payload, f) + + if target_mode == "triple_barrier" and meta_clf is not None: + # V27 -- artefacto SEPARADO del scalers_dict.pkl principal: falta de + # este archivo debe degradar a "sin filtro" en quanti_engine.py, no + # romper la carga del modelo entero. Wiring a producción es el + # PRÓXIMO paso (no en este parche) -- por ahora esto queda + # persistido y auditado con `--cpcv-audit`, sin tocar el motor + # servido. + meta_labeler_path = output_dir / "meta_labeler.pkl" + with open(meta_labeler_path, "wb") as f: + pickle.dump(meta_clf, f) + logger.info(" Meta-labeler exportado -> %s", meta_labeler_path) + + checkpoint_path.unlink(missing_ok=True) # artefacto intermedio; model_v5.keras es la fuente final + + logger.info(" Modelo -> %s", model_path) + logger.info(" Scalers -> %s", scalers_path) + logger.info(" Chart -> %s", chart_path) + + return {"model_path": model_path, "scalers_path": scalers_path, "results": results, "target_mode": target_mode} + + +# ============================================================ +# ORQUESTACIÓN GLOBAL — dos ciclos independientes y secuenciales +# ============================================================ +if __name__ == "__main__": + # AUDITORÍA RESCATE 2026-08 -- este bucle iteraba SIEMPRE los dos + # regímenes de `REGIMES`, sin forma de acotarlo -- correr + # `python train_kodaquant_v5.py` para "solo retrain de crypto" (rescate + # post-incidente, iteración rápida de alpha cripto) reentrenaba TAMBIÉN + # `equity_specialist`, violando el congelamiento estricto declarado + # sobre ese régimen (52.7%/56.3% DirAcc fuera de muestra). `--regime` + # (mismo nombre/patrón que ya usan `walk_forward_eval.py`/ + # `pnl_backtest.py`) permite acotar la corrida a UN régimen sin tocar el + # otro; default="all" preserva EXACTO el comportamiento previo (cron + # semanal `entrenamiento_semanal.yml` sigue invocando este script sin + # argumentos y sigue reentrenando ambos). + import argparse + _cli_parser = argparse.ArgumentParser(description="Entrenamiento KodaQuant V5 -- todos los regímenes o uno solo.") + _cli_parser.add_argument("--regime", default="all", choices=["all", *REGIMES.keys()], + help="Régimen a (re)entrenar. 'all' (default) = comportamiento histórico, ambos regímenes.") + _cli_parser.add_argument("--cpcv-audit", default=None, metavar="TICKER", + help="Auditoría Purged Walk-Forward de UN ticker (ver run_cpcv_audit). No entrena ni sobreescribe ningún artefacto de producción.") + _cli_parser.add_argument("--cpcv-k", type=int, default=5, help="Folds para --cpcv-audit.") + _cli_parser.add_argument("--cpcv-epochs", type=int, default=20, help="Épocas por fold para --cpcv-audit.") + _cli_parser.add_argument("--cpcv-exclude-timeout", action="store_true", + help="Excluye filas TIMEOUT del train de cada fold (ver build_asset_dataset). Test intacto.") + _cli_args = _cli_parser.parse_args() + if _cli_args.cpcv_audit: + run_cpcv_audit(_cli_args.cpcv_audit, k=_cli_args.cpcv_k, epochs_per_fold=_cli_args.cpcv_epochs, + exclude_timeout_from_train=_cli_args.cpcv_exclude_timeout) + raise SystemExit(0) + _regimes_to_run = dict(REGIMES) if _cli_args.regime == "all" else {_cli_args.regime: REGIMES[_cli_args.regime]} + if _cli_args.regime != "all": + logger.warning("[--regime] Corrida ACOTADA a '%s' -- el resto de los regímenes (%s) NO se tocan " + "(ni datos, ni modelo, ni scalers).", _cli_args.regime, + ", ".join(r for r in REGIMES if r != _cli_args.regime)) + + # V9 (CI/CD) — UNA vez por corrida, antes de tocar cualquier régimen + # (ver purge_data_cache: purgar dentro del bucle borraría el .parquet + # que el régimen anterior de esta misma corrida acaba de escribir). + if FORCE_FRESH_DATA: + purge_data_cache() + + summary = {} + for regime_name, regime_cfg in _regimes_to_run.items(): + summary[regime_name] = run_regime_pipeline(regime_name, regime_cfg) + + logger.info("=" * 78) + logger.info("ENTRENAMIENTO V5 COMPLETO — %d especialistas persistidos en %s", + len(summary), MODELS_ROOT) + for regime_name, info in summary.items(): + if info.get("target_mode") == "triple_barrier": + avg_actionable = np.mean([r["actionable_accuracy"] for r in info["results"].values()]) + avg_signal_prec = np.mean([r["signal_precision"] for r in info["results"].values()]) + logger.info(" %-18s AccAccionable promedio=%.1f%% PrecisiónSeñal promedio=%.1f%% (Triple Barrier)", + regime_name, avg_actionable * 100, avg_signal_prec * 100) + else: + avg_dir_acc = np.mean([r["directional_accuracy"] for r in info["results"].values()]) + logger.info(" %-18s edge direccional promedio = %.1f%%", + regime_name, avg_dir_acc * 100) + logger.info("=" * 78) +# %% \ No newline at end of file diff --git a/ml_engine/walk_forward_eval.py b/ml_engine/walk_forward_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..f907dc0a0767d68f4abfe157f53c19451a007609 --- /dev/null +++ b/ml_engine/walk_forward_eval.py @@ -0,0 +1,572 @@ +""" +walk_forward_eval.py -- MEDICIÓN HONESTA de acertividad direccional (V1) +============================================================================= +Un solo split 80/20 (`train_kodaquant_v5.run_regime_pipeline`) da UN número +de directional accuracy por activo. Ese número puede ser una racha de suerte +del régimen de mercado que le tocó a ese 20% final, o al revés. Este script +NO reemplaza al entrenamiento de producción -- lo AUDITA: repite el ciclo +completo (fit de scalers -> build_model -> train_model -> evaluate_asset) +sobre múltiples ventanas walk-forward (expanding window, estrictamente +cronológicas, sin fuga de información futura) y reporta la DISTRIBUCIÓN de +directional accuracy, no un único punto. + +Cero cambios a la matemática/topología/loss de `train_kodaquant_v5.py`: este +script IMPORTA `build_model`/`train_model`/`evaluate_asset`/`engineer_asset` +tal cual están (mismo grafo, mismos hiperparámetros, misma +DirectionalGaussianNLL) -- lo único nuevo acá es la ORQUESTACIÓN de folds y +la agregación estadística. La única lógica duplicada es la generalización de +`build_asset_dataset` (fija a un único `train_ratio`) a fronteras explícitas +de fold -- ver `_build_fold_dataset`, misma fórmula exacta (mismo +`MinMaxScaler`/`StandardScaler(with_mean=False)`/target de log-return/ +construcción de ventanas), solo parametrizada distinto. + +USO: + python ml_engine/walk_forward_eval.py --regime equity_specialist --n-folds 4 + (sin --epochs-per-fold: usa el presupuesto de producción del régimen, + ver tkv5.REGIMES[regime]['epochs'] -- 100 equity / 180 crypto. Pasá + --epochs-per-fold 30 SOLO para iterar rápido en desarrollo.) + + (con 4 folds x hasta 100-180 épocas c/u, esto es CARO -- cada fold reentrena + la red desde cero. Pasá --epochs-per-fold más bajo para iterar rápido.) + +COSTO: cada fold = un entrenamiento completo nuevo (misma red que +`run_regime_pipeline`, EarlyStopping propio). Con `--n-folds 4 +--epochs-per-fold 30` esperá ~4x el tiempo de un `train_kodaquant_v5.py` +recortado a 30 épocas -- correlo offline, no interactivo. +""" +from __future__ import annotations + +import argparse +import logging +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +from sklearn.preprocessing import MinMaxScaler, StandardScaler + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (mismo bootstrap que el resto de +# ml_engine/ -- ver train_kodaquant_v5.py/data_pipeline.py) ----------------- +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# Import como MÓDULO (no `python -c`): el bloque `if __name__ == "__main__"` +# de train_kodaquant_v5.py NO se ejecuta acá (ese guard existe justamente +# para que sea seguro importarlo), así que esto NO dispara un entrenamiento +# completo -- solo trae funciones/clases/constantes ya definidas y probadas. +import ml_engine.train_kodaquant_v5 as tkv5 # noqa: E402 + +logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s") +logger = logging.getLogger("kodaquant.walk_forward") + + +def _build_fold_dataset(df_asset: pd.DataFrame, ticker: str, lookback: int, + train_end: int, test_end: int, asset_to_id: dict[str, int], + feature_cols: list[str], target_mode: str = "regression", + tb_params: dict | None = None): + """ + Misma matemática EXACTA que `tkv5.build_asset_dataset` -- mismo + `MinMaxScaler(feature_range=(0,1))` fiteado solo en train, mismo target + `StandardScaler(with_mean=False)` (preserva signo del retorno) en + `target_mode="regression"`, misma construcción de ventanas -- + generalizada a fronteras EXPLÍCITAS (`train_end`/`test_end`, posiciones + enteras) en vez de un único `train_ratio` fijo, para poder generar + múltiples folds walk-forward sin tocar `train_kodaquant_v5.py`. + Devuelve `None` si el fold no tiene suficiente historia para este + activo (se salta, no se rellena con basura). + + V22: `target_mode="triple_barrier"` (crypto_specialist) replica la + rama equivalente de `tkv5.build_asset_dataset` -- etiquetas 3-way vía + `tkv5.compute_triple_barrier_labels`, one-hot, `sample_weight` por + magnitud de PnL -- generalizada a `train_end`/`test_end` explícitos de + la misma forma que el target de regresión. + """ + prices = df_asset["RAW_CLOSE"].values + features = df_asset[feature_cols].values + log_returns = np.diff(np.log(prices)) + n = len(df_asset) + test_end = min(test_end, n) + + if train_end <= lookback or test_end <= train_end: + return None + + feature_scaler = MinMaxScaler(feature_range=(0, 1)) + feature_scaler.fit(features[:train_end]) + features_scaled = feature_scaler.transform(features) + + tb_label_arr = tb_return_arr = None + if target_mode == "triple_barrier": + tb_params = tb_params or {} + tb = tkv5.compute_triple_barrier_labels( + df_asset, + pt_mult=tb_params.get("pt_mult", tkv5.TRIPLE_BARRIER_PT_MULT), + sl_mult=tb_params.get("sl_mult", tkv5.TRIPLE_BARRIER_SL_MULT), + max_holding_days=tb_params.get("max_holding_days", tkv5.TRIPLE_BARRIER_MAX_HOLDING_DAYS), + vol_lookback=tb_params.get("vol_lookback", tkv5.TRIPLE_BARRIER_VOL_LOOKBACK), + ) + tb_label_arr = tb["TB_LABEL"].to_numpy() + tb_return_arr = tb["TB_REALIZED_RETURN"].to_numpy() + + X, y_raw, last_price, dates = [], [], [], [] + tb_class_idx_list, tb_ret_list = [], [] + for t in range(lookback, test_end): + entry_idx = t - 1 + if target_mode == "triple_barrier" and np.isnan(tb_label_arr[entry_idx]): + continue + X.append(features_scaled[t - lookback: t]) + last_price.append(prices[entry_idx]) + dates.append(df_asset.index[t]) + if target_mode == "triple_barrier": + tb_class_idx_list.append(tkv5.TB_LABEL_TO_CLASS_IDX[int(tb_label_arr[entry_idx])]) + tb_ret_list.append(tb_return_arr[entry_idx]) + else: + y_raw.append(log_returns[entry_idx]) + + X = np.array(X, dtype=np.float32) + last_price = np.array(last_price, dtype=np.float32) + dates = pd.DatetimeIndex(dates) + + window_split = train_end - lookback + if window_split <= 0 or window_split >= len(X): + return None + + asset_id = np.full((len(X),), asset_to_id[ticker], dtype=np.int32) + + if target_mode == "triple_barrier": + tb_class_idx = np.array(tb_class_idx_list, dtype=np.int32) + tb_ret = np.array(tb_ret_list, dtype=np.float32) + y_onehot = np.eye(3, dtype=np.float32)[tb_class_idx] + + train_mag = np.abs(tb_ret[:window_split]) + positive_mag = train_mag[train_mag > 0] + train_mag_median = float(np.median(positive_mag)) if positive_mag.size else 1.0 + sample_weight = np.clip(np.abs(tb_ret) / max(train_mag_median, 1e-8), 0.25, 4.0).astype(np.float32) + + train = dict(X=X[:window_split], y=y_onehot[:window_split], asset_id=asset_id[:window_split], + last_price=last_price[:window_split], dates=dates[:window_split], + sample_weight=sample_weight[:window_split], y_return=tb_ret[:window_split], + y_class_idx=tb_class_idx[:window_split]) + test = dict(X=X[window_split:], y=y_onehot[window_split:], asset_id=asset_id[window_split:], + last_price=last_price[window_split:], dates=dates[window_split:], + sample_weight=sample_weight[window_split:], y_return=tb_ret[window_split:], + y_class_idx=tb_class_idx[window_split:]) + if len(train["X"]) == 0 or len(test["X"]) == 0: + return None + return train, test, feature_scaler, None + + y_raw = np.array(y_raw, dtype=np.float32).reshape(-1, 1) + target_scaler = StandardScaler(with_mean=False) + target_scaler.fit(y_raw[:window_split]) + y_scaled = target_scaler.transform(y_raw).astype(np.float32) + + train = dict(X=X[:window_split], y=y_scaled[:window_split], asset_id=asset_id[:window_split], + last_price=last_price[:window_split], dates=dates[:window_split]) + test = dict(X=X[window_split:], y=y_scaled[window_split:], asset_id=asset_id[window_split:], + last_price=last_price[window_split:], dates=dates[window_split:]) + if len(train["X"]) == 0 or len(test["X"]) == 0: + return None + return train, test, feature_scaler, target_scaler + + +def _calibrate_fold_tb_params(dfs: dict[str, pd.DataFrame], tickers: list[str], + train_end_by_ticker: dict[str, int]) -> dict[str, dict]: + """ + V23.5 -- replica, POR FOLD, la calibración train-only asimétrica POR + ACTIVO de `tkv5.calibrate_crypto_triple_barrier` (producción), pero + generalizada a la frontera EXPLÍCITA `train_end` de CADA fold en vez del + único `TRAIN_RATIO` global que usa esa función -- mismo principio que + `_build_fold_dataset` generaliza `tkv5.build_asset_dataset` (ver + docstring de esa función). Reutiliza + `tkv5._calibrate_single_asset_triple_barrier` (grid search de UN activo) + TAL CUAL -- cero lógica de grid search duplicada, solo cambia cómo se + corta el `train_slice` que se le pasa (por fold, no por `train_ratio`). + + Sin esto, el walk-forward mediría al modelo V23.5 (barreras + desacopladas por activo) con las barreras VIEJAS (pooled/fijas) -- + matemáticamente deshonesto respecto a lo que corre en producción. + """ + return { + t: tkv5._calibrate_single_asset_triple_barrier(t, dfs[t].iloc[:train_end_by_ticker[t]]) + for t in tickers + } + + +# ROLLBACK V23.6 (Head Quant, ver changelog de `train_kodaquant_v5.py`): +# `_compute_fold_equity_vol_weights` (réplica por-fold de +# `tkv5._compute_equity_vol_sample_weights`, ya purgada del módulo de +# entrenamiento) vivía acá. Purgada por completo -- `equity_specialist` ya +# no calcula ni pasa ningún sample_weight, ni en producción ni en este +# walk-forward. Congruencia con `tkv5`: si esa función/esas constantes ya +# no existen en `train_kodaquant_v5.py`, tampoco pueden existir acá. + + +def run_walk_forward(regime_name: str, n_folds: int, initial_train_frac: float, + test_frac: float, epochs_per_fold: int, output_dir: Path) -> pd.DataFrame: + if regime_name not in tkv5.REGIMES: + raise ValueError(f"Régimen desconocido: '{regime_name}' -- opciones: {list(tkv5.REGIMES)}") + + regime_cfg = tkv5.REGIMES[regime_name] + tickers = regime_cfg["tickers"] + asset_to_id = {t: i for i, t in enumerate(tickers)} + feature_cols = ["LOG_RETURN_1D"] + tkv5.get_tech_cols(regime_name) + tkv5.MACRO_TICKERS + output_dir.mkdir(parents=True, exist_ok=True) + + # V22 — target_mode bifurca dataset/modelo/loss/evaluación, igual que + # en `tkv5.run_regime_pipeline`; default "regression" preserva + # equity_specialist BIT A BIT igual a antes. + target_mode = regime_cfg.get("target_mode", "regression") + # V23.5 -- default POR TICKER, usado SOLO si `tkv5.CRYPTO_CALIBRATE_ + # BARRIERS=False` (mismo fallback que `tkv5.run_regime_pipeline`); si + # está en True (default de producción) cada fold recalibra por activo + # vía `_calibrate_fold_tb_params` más abajo, TRAIN-ONLY de ESE fold. + _default_tb_params: dict | None = None + if target_mode == "triple_barrier": + _default_tb_params = { + "pt_mult": regime_cfg.get("pt_mult", tkv5.TRIPLE_BARRIER_PT_MULT), + "sl_mult": regime_cfg.get("sl_mult", tkv5.TRIPLE_BARRIER_SL_MULT), + "max_holding_days": regime_cfg.get("max_holding_days", tkv5.TRIPLE_BARRIER_MAX_HOLDING_DAYS), + "vol_lookback": regime_cfg.get("vol_lookback", tkv5.TRIPLE_BARRIER_VOL_LOOKBACK), + } + logger.info("target_mode='triple_barrier' -- calibración %s (CRYPTO_CALIBRATE_BARRIERS=%s)", + "dinámica POR FOLD/POR ACTIVO (V23.5)" if tkv5.CRYPTO_CALIBRATE_BARRIERS else "ESTÁTICA (defaults de REGIMES)", + tkv5.CRYPTO_CALIBRATE_BARRIERS) + + logger.info("Descargando/leyendo caché OHLCV+macro para '%s'...", regime_name) + all_market_data = tkv5.download_all( + tickers, tkv5.MACRO_TICKERS, tkv5.PERIOD, cache_tag=regime_name, force_refresh=False, + ) + + logger.info("Ingeniería de features (una sola vez, se reparte en folds por posición)...") + dfs = {t: tkv5.engineer_asset(all_market_data, t, tkv5.MACRO_TICKERS) for t in tickers} + n_per_ticker = {t: len(dfs[t]) for t in tickers} + logger.info("Filas engineered por activo: %s", n_per_ticker) + + tmp_ckpt = output_dir / "_walk_forward_tmp.keras" + records: list[dict] = [] + monitor_metric = "val_actionable_accuracy" if target_mode == "triple_barrier" else "val_directional_accuracy_metric" + + for fold_idx in range(n_folds): + # V23.5 -- fronteras train_end/test_end POR TICKER calculadas ANTES + # de construir los datasets, porque la calibración de barreras (si + # `CRYPTO_CALIBRATE_BARRIERS`) las necesita primero -- mismo orden + # que `tkv5.run_regime_pipeline` (calibrar -> recién ahí construir). + train_end_by_ticker: dict[str, int] = {} + test_end_by_ticker: dict[str, int] = {} + for t in tickers: + n = n_per_ticker[t] + train_end = int(n * (initial_train_frac + fold_idx * test_frac)) + test_end = int(n * (initial_train_frac + (fold_idx + 1) * test_frac)) + train_end_by_ticker[t] = max(train_end, tkv5.LOOKBACK + 1) + test_end_by_ticker[t] = min(test_end, n) + + tb_params_fold: dict[str, dict] | None = None + if target_mode == "triple_barrier": + if tkv5.CRYPTO_CALIBRATE_BARRIERS: + tb_params_fold = _calibrate_fold_tb_params(dfs, tickers, train_end_by_ticker) + else: + tb_params_fold = {t: dict(_default_tb_params) for t in tickers} + for t in tickers: + tbt = tb_params_fold[t] + logger.info("Fold %d/%d [%s]: pt_mult=%.2f sl_mult=%.2f vol_lookback=%d max_holding_days=%d", + fold_idx + 1, n_folds, t, tbt["pt_mult"], tbt["sl_mult"], + tbt["vol_lookback"], tbt["max_holding_days"]) + + # ROLLBACK V23.6: el cómputo por-fold de sample_weight equity por + # volatilidad vivía acá -- purgado, ver changelog de `tkv5`. + X_train_parts, y_train_parts, aid_train_parts, sw_train_parts = [], [], [], [] + fold_test: dict[str, tuple] = {} + skipped: list[str] = [] + + for t in tickers: + train_end = train_end_by_ticker[t] + test_end = test_end_by_ticker[t] + tb_params_t = tb_params_fold[t] if tb_params_fold is not None else None + built = _build_fold_dataset(dfs[t], t, tkv5.LOOKBACK, train_end, test_end, asset_to_id, + feature_cols, target_mode=target_mode, tb_params=tb_params_t) + if built is None: + skipped.append(t) + continue + train, test, _f_scaler, t_scaler = built + fold_test[t] = (test, t_scaler) + X_train_parts.append(train["X"]) + y_train_parts.append(train["y"]) + aid_train_parts.append(train["asset_id"]) + if target_mode == "triple_barrier": + sw_train_parts.append(train["sample_weight"]) + # ROLLBACK V23.6: rama "regression" (equity) que acumulaba + # sample_weight por volatilidad, purgada -- ver changelog de tkv5. + + if not X_train_parts: + logger.warning("Fold %d/%d: sin datos suficientes para ningún activo -- se salta.", fold_idx + 1, n_folds) + continue + + X_train = np.concatenate(X_train_parts, axis=0) + y_train = np.concatenate(y_train_parts, axis=0) + aid_train = np.concatenate(aid_train_parts, axis=0).reshape(-1, 1) + # ROLLBACK V23.6: solo triple_barrier (cripto) pesa muestras. + _uses_sample_weight = target_mode == "triple_barrier" + sw_train = np.concatenate(sw_train_parts, axis=0) if _uses_sample_weight else None + + n_fit_samples = int(len(X_train) * (1 - tkv5.VALIDATION_SPLIT)) + steps_per_epoch = max(1, n_fit_samples // tkv5.BATCH_SIZE) + + logger.info("Fold %d/%d: X_train=%s | activos evaluables=%d%s", + fold_idx + 1, n_folds, X_train.shape, len(fold_test), + f" | saltados={skipped}" if skipped else "") + + class_alpha = None + if target_mode == "triple_barrier": + train_class_idx = np.argmax(y_train, axis=-1) + class_counts = np.maximum(np.bincount(train_class_idx, minlength=3).astype(np.float64), 1.0) + class_alpha = (len(train_class_idx) / (3.0 * class_counts)).tolist() + logger.info(" Fold %d/%d -- distribución de clases train: SL=%d TIMEOUT=%d TP=%d -> alpha=%s", + fold_idx + 1, n_folds, int(class_counts[0]), int(class_counts[1]), int(class_counts[2]), + [f"{a:.3f}" for a in class_alpha]) + + # Red NUEVA por fold (mismos hiperparámetros/arquitectura que + # producción vía `regime_name`) -- nunca se reusan pesos entre + # folds, cada uno mide generalización desde cero. + model, gamma_var = tkv5.build_model( + n_timesteps=tkv5.LOOKBACK, n_features=tkv5.get_n_features(regime_name), n_assets=len(tickers), + steps_per_epoch=steps_per_epoch, regime_name=regime_name, + embed_dim=tkv5.ASSET_EMBED_DIM, huber_delta=tkv5.HUBER_DELTA, + gamma_initial=tkv5.GAMMA_INITIAL, variance_lambda=tkv5.VARIANCE_LAMBDA, + variance_cap=tkv5.VARIANCE_CAP, gaussian_nll_beta=tkv5.GAUSSIAN_NLL_BETA, + log_var_min=tkv5.LOG_VAR_MIN, log_var_max=tkv5.LOG_VAR_MAX, + log_var_l2_lambda=tkv5.LOG_VAR_L2_LAMBDA, log_var_barrier_lambda=tkv5.LOG_VAR_BARRIER_LAMBDA, + target_mode=target_mode, class_alpha=class_alpha, + focal_gamma=tkv5.TRIPLE_BARRIER_FOCAL_GAMMA, label_smoothing=tkv5.TRIPLE_BARRIER_LABEL_SMOOTHING, + model_name=f"KodaQuant_{regime_name}_WF_fold{fold_idx + 1}", + ) + _history, model = tkv5.train_model( + model, X_train, aid_train, y_train, checkpoint_path=tmp_ckpt, + epochs=epochs_per_fold, batch_size=tkv5.BATCH_SIZE, validation_split=tkv5.VALIDATION_SPLIT, + gamma_variable=gamma_var, gamma_max=tkv5.GAMMA_MAX, + gamma_warmup_epochs=min(tkv5.GAMMA_WARMUP_EPOCHS, max(1, epochs_per_fold // 3)), + gamma_schedule=tkv5.GAMMA_SCHEDULE, gamma_sigmoid_steepness=tkv5.GAMMA_SIGMOID_STEEPNESS, + sample_weight=sw_train, monitor_metric=monitor_metric, + ) + + for t, (test, t_scaler) in fold_test.items(): + if target_mode == "triple_barrier": + r = tkv5.evaluate_asset_triple_barrier(model, test, t) + records.append({ + "fold": fold_idx + 1, "ticker": t, "n_test": len(test["X"]), + "accuracy": r["accuracy"], "actionable_accuracy": r["actionable_accuracy"], + "signal_precision": r["signal_precision"], "n_signals": r["n_signals"], + "primary_metric": r["actionable_accuracy"], + }) + logger.info(" Fold %d %-10s n_test=%3d Acc=%.1f%% AccAccionable=%.1f%% PrecisiónSeñal=%.1f%% (n=%d)", + fold_idx + 1, t, len(test["X"]), r["accuracy"] * 100, + r["actionable_accuracy"] * 100, r["signal_precision"] * 100, r["n_signals"]) + else: + r = tkv5.evaluate_asset(model, test, t, t_scaler) + records.append({ + "fold": fold_idx + 1, "ticker": t, "n_test": len(test["X"]), + "directional_accuracy": r["directional_accuracy"], + "mae_price": r["mae_price"], "rmse_price": r["rmse_price"], + "primary_metric": r["directional_accuracy"], + }) + logger.info(" Fold %d %-10s n_test=%3d DirAcc=%.1f%%", + fold_idx + 1, t, len(test["X"]), r["directional_accuracy"] * 100) + + tmp_ckpt.unlink(missing_ok=True) + try: + tkv5.keras.backend.clear_session() # libera memoria -- red nueva cada fold + except Exception: # noqa: BLE001 -- best-effort, nunca debe tumbar la corrida + pass + + tmp_ckpt.unlink(missing_ok=True) + df = pd.DataFrame.from_records(records) + if not df.empty: + df.attrs["target_mode"] = target_mode + return df + + +def summarize(df: pd.DataFrame, output_dir: Path, seed: int, target_mode: str = "regression") -> None: + if df.empty: + logger.error("Ningún fold produjo resultados -- revisá --n-folds/--test-frac vs. el historial disponible.") + return + + csv_path = output_dir / f"walk_forward_results_seed{seed}.csv" + df.to_csv(csv_path, index=False) + + if target_mode == "triple_barrier": + logger.info("=" * 78) + logger.info("RESUMEN POR ACTIVO (across %d fold(s)) -- Triple Barrier (SL/TIMEOUT/TP)", df["fold"].nunique()) + for ticker, g in df.groupby("ticker"): + logger.info(" %-10s AccAccionable media=%.1f%% std=%.1f pp min=%.1f%% max=%.1f%% " + "PrecisiónSeñal media=%.1f%% (n_folds=%d)", + ticker, g["actionable_accuracy"].mean() * 100, g["actionable_accuracy"].std(ddof=0) * 100, + g["actionable_accuracy"].min() * 100, g["actionable_accuracy"].max() * 100, + g["signal_precision"].mean() * 100, len(g)) + + metric = df["primary_metric"].to_numpy() # == actionable_accuracy, ver run_walk_forward + mean_m = float(metric.mean()) + std_m = float(metric.std(ddof=1)) if len(metric) > 1 else 0.0 + n = len(metric) + # Azar de referencia: accuracy condicionada a "clase verdadera != TIMEOUT" + # sobre 3 clases posibles (SL/TIMEOUT/TP) -- NO es 50% (eso era el + # baseline de un sign-flip binario del régimen de regresión, ya no + # aplica acá). + popmean = 1.0 / 3.0 + + logger.info("-" * 78) + logger.info("VEREDICTO GLOBAL (%d observaciones ticker x fold, walk-forward, sin fuga de datos):", n) + logger.info(" AccAccionable media = %.2f%% desvío = %.2f pp (azar de referencia ~%.1f%%, 3 clases)", + mean_m * 100, std_m * 100, popmean * 100) + + try: + from scipy import stats + if n > 1 and std_m > 0: + t_stat, p_value = stats.ttest_1samp(metric, popmean=popmean) + ci_low, ci_high = stats.t.interval(0.95, df=n - 1, loc=mean_m, scale=std_m / np.sqrt(n)) + logger.info(" IC 95%% = [%.2f%%, %.2f%%] H0: media=%.1f%% -> p=%.4f (%s)", + ci_low * 100, ci_high * 100, popmean * 100, p_value, + "se rechaza H0, hay evidencia de edge real por sobre el azar" if p_value < 0.05 + else "NO se rechaza H0 -- no hay evidencia estadística de superar el azar") + else: + logger.info(" Muy pocas observaciones para un test estadístico confiable -- corré más folds.") + except ImportError: + se = std_m / np.sqrt(n) if n > 0 else 0.0 + ci_low, ci_high = mean_m - 1.96 * se, mean_m + 1.96 * se + logger.info(" (scipy no disponible -- IC 95%% aproximado por normal: [%.2f%%, %.2f%%])", + ci_low * 100, ci_high * 100) + + logger.info(" PrecisiónSeñal media (de las señales SÍ disparadas -- pred != TIMEOUT -- " + "¿cuántas aciertan?) = %.2f%%", df["signal_precision"].mean() * 100) + logger.info("=" * 78) + logger.info("CSV completo (por fold x activo) -> %s", csv_path) + + try: + import matplotlib.pyplot as plt + fig, ax = plt.subplots(figsize=(9, 5)) + order = sorted(df["ticker"].unique()) + data = [df.loc[df["ticker"] == t, "actionable_accuracy"] * 100 for t in order] + ax.boxplot(data, tick_labels=order, showmeans=True) + ax.axhline(popmean * 100, color="red", linestyle="--", linewidth=1, + label=f"Azar (~{popmean * 100:.0f}%, 3 clases)") + ax.set_ylabel("Actionable Accuracy (%)") + ax.set_title(f"Walk-forward Triple Barrier -- {df['fold'].nunique()} fold(s)") + ax.legend() + fig.tight_layout() + chart_path = output_dir / f"walk_forward_chart_seed{seed}.png" + fig.savefig(chart_path, dpi=150) + plt.close(fig) + logger.info("Chart -> %s", chart_path) + except Exception as exc: # noqa: BLE001 -- el chart es un extra, nunca debe tumbar el resumen + logger.debug("No se pudo generar el chart (%r) -- no bloqueante.", exc) + return + + # --- target_mode == "regression" (default) — CERO cambios respecto al original --- + logger.info("=" * 78) + logger.info("RESUMEN POR ACTIVO (across %d fold(s))", df["fold"].nunique()) + for ticker, g in df.groupby("ticker"): + logger.info(" %-10s DirAcc media=%.1f%% std=%.1f pp min=%.1f%% max=%.1f%% (n_folds=%d)", + ticker, g["directional_accuracy"].mean() * 100, g["directional_accuracy"].std(ddof=0) * 100, + g["directional_accuracy"].min() * 100, g["directional_accuracy"].max() * 100, len(g)) + + acc = df["directional_accuracy"].to_numpy() + mean_acc = float(acc.mean()) + std_acc = float(acc.std(ddof=1)) if len(acc) > 1 else 0.0 + n = len(acc) + + logger.info("-" * 78) + logger.info("VEREDICTO GLOBAL (%d observaciones ticker x fold, walk-forward, sin fuga de datos):", n) + logger.info(" DirAcc media = %.2f%% desvío = %.2f pp", mean_acc * 100, std_acc * 100) + + try: + from scipy import stats + if n > 1 and std_acc > 0: + t_stat, p_value = stats.ttest_1samp(acc, popmean=0.5) + ci_low, ci_high = stats.t.interval(0.95, df=n - 1, loc=mean_acc, scale=std_acc / np.sqrt(n)) + logger.info(" IC 95%% = [%.2f%%, %.2f%%] H0: media=50%% -> p=%.4f (%s)", + ci_low * 100, ci_high * 100, p_value, + "se rechaza H0, hay evidencia de edge real" if p_value < 0.05 + else "NO se rechaza H0 -- no hay evidencia estadística de superar 50%") + else: + logger.info(" Muy pocas observaciones para un test estadístico confiable -- corré más folds.") + except ImportError: + se = std_acc / np.sqrt(n) if n > 0 else 0.0 + ci_low, ci_high = mean_acc - 1.96 * se, mean_acc + 1.96 * se + logger.info(" (scipy no disponible -- IC 95%% aproximado por normal: [%.2f%%, %.2f%%])", + ci_low * 100, ci_high * 100) + logger.info(" Si el IC completo queda por debajo/incluye 50%%, NO hay evidencia sólida de edge real todavía.") + + logger.info("=" * 78) + logger.info("CSV completo (por fold x activo) -> %s", csv_path) + + try: + import matplotlib.pyplot as plt + fig, ax = plt.subplots(figsize=(9, 5)) + order = sorted(df["ticker"].unique()) + data = [df.loc[df["ticker"] == t, "directional_accuracy"] * 100 for t in order] + ax.boxplot(data, tick_labels=order, showmeans=True) + ax.axhline(50.0, color="red", linestyle="--", linewidth=1, label="Coinflip (50%)") + ax.set_ylabel("Directional Accuracy (%)") + ax.set_title(f"Walk-forward directional accuracy -- {df['fold'].nunique()} fold(s)") + ax.legend() + fig.tight_layout() + chart_path = output_dir / f"walk_forward_chart_seed{seed}.png" + fig.savefig(chart_path, dpi=150) + plt.close(fig) + logger.info("Chart -> %s", chart_path) + except Exception as exc: # noqa: BLE001 -- el chart es un extra, nunca debe tumbar el resumen + logger.debug("No se pudo generar el chart (%r) -- no bloqueante.", exc) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Validación walk-forward honesta de directional accuracy.") + parser.add_argument("--regime", default="equity_specialist", choices=list(tkv5.REGIMES)) + parser.add_argument("--n-folds", type=int, default=4) + parser.add_argument("--initial-train-frac", type=float, default=0.60, + help="Fracción inicial de historia usada como train antes del primer fold de test.") + parser.add_argument("--test-frac", type=float, default=0.08, + help="Tamaño de cada bloque de test walk-forward, como fracción de la historia total.") + parser.add_argument("--epochs-per-fold", type=int, default=None, + help="AUDITORÍA RESCATE 2026-08: default REAL ahora es el mismo presupuesto de épocas " + "que usa train_kodaquant_v5.py en producción para este régimen (EPOCHS=100 " + "equity_specialist / 180 crypto_specialist, ver tkv5.REGIMES[regime]['epochs']) -- " + "el default anterior (30) medía un modelo deliberadamente subentrenado y fue la " + "causa más probable de DirAcc<50%% reportada. Pasá un valor menor SOLO para " + "iterar rápido en desarrollo; EarlyStopping(patience=18) sigue siendo el que " + "decide cuándo parar de verdad.") + parser.add_argument("--output-dir", type=Path, default=tkv5.BASE_DIR / "walk_forward_reports") + parser.add_argument("--seed", type=int, default=None, + help="Sobrescribe SEED=42 (fijo en train_kodaquant_v5.py -- sin esto, toda corrida " + "es idéntica bit a bit). Correr 3-5 veces con semillas distintas y promediar " + "'DirAcc media' separa señal real de varianza de inicialización -- especialmente " + "relevante en crypto_specialist, con std de 3.8-6.2pp entre folds.") + args = parser.parse_args() + + if args.seed is not None: + tkv5.keras.utils.set_random_seed(args.seed) + + # AUDITORÍA RESCATE 2026-08: si no se pasó --epochs-per-fold, usar el + # MISMO presupuesto de producción de este régimen (nunca un valor de + # iteración rápida hardcodeado) -- ver docstring del argumento arriba. + effective_epochs_per_fold = args.epochs_per_fold + if effective_epochs_per_fold is None: + effective_epochs_per_fold = tkv5.REGIMES[args.regime].get("epochs", tkv5.EPOCHS) + logger.info( + "--epochs-per-fold no especificado -> usando presupuesto de producción de '%s': %d épocas " + "(tkv5.REGIMES['%s'].get('epochs', tkv5.EPOCHS)). Pasá --epochs-per-fold explícito para iterar rápido.", + args.regime, effective_epochs_per_fold, args.regime, + ) + + results_df = run_walk_forward( + regime_name=args.regime, n_folds=args.n_folds, + initial_train_frac=args.initial_train_frac, test_frac=args.test_frac, + epochs_per_fold=effective_epochs_per_fold, output_dir=args.output_dir, + ) + summarize(results_df, args.output_dir, seed=args.seed if args.seed is not None else tkv5.SEED, + target_mode=tkv5.REGIMES[args.regime].get("target_mode", "regression")) \ No newline at end of file diff --git a/ml_engine/walk_forward_reports/_walk_forward_tmp 2.keras b/ml_engine/walk_forward_reports/_walk_forward_tmp 2.keras new file mode 100644 index 0000000000000000000000000000000000000000..b5846f1c220b0bc32f485f977ec0fcece65e1c0b --- /dev/null +++ b/ml_engine/walk_forward_reports/_walk_forward_tmp 2.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be5915e66ee7d2ab017dd6fc2129bc15d010362014853b1840cb401180743706 +size 6752675 diff --git a/ml_engine/walk_forward_reports/_walk_forward_tmp.keras b/ml_engine/walk_forward_reports/_walk_forward_tmp.keras new file mode 100644 index 0000000000000000000000000000000000000000..33be2c7bee13b2c590277d8c64d00a423f0c02e3 --- /dev/null +++ b/ml_engine/walk_forward_reports/_walk_forward_tmp.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e95b05dc8e3faa4c32bd751e2b9d7d4ba0b641057258e8ec8811dda1940308a5 +size 6752675 diff --git a/ml_engine/walk_forward_reports/pnl_daily_crypto_specialist.csv b/ml_engine/walk_forward_reports/pnl_daily_crypto_specialist.csv new file mode 100644 index 0000000000000000000000000000000000000000..cc028c2486d0acf93299158e383b619b44c066ec --- /dev/null +++ b/ml_engine/walk_forward_reports/pnl_daily_crypto_specialist.csv @@ -0,0 +1,234 @@ +date,n_assets,pnl_net,equity +2025-10-31,2,0.0,1.0 +2025-11-01,2,0.0,1.0 +2025-11-02,2,0.0,1.0 +2025-11-03,2,0.0,1.0 +2025-11-04,2,0.0,1.0 +2025-11-05,2,0.0,1.0 +2025-11-06,2,0.0,1.0 +2025-11-07,2,0.0,1.0 +2025-11-08,2,0.0,1.0 +2025-11-09,2,0.0,1.0 +2025-11-10,2,0.0018407265454345643,1.0018407265454345 +2025-11-11,2,-0.009910533106278954,0.9919119508577874 +2025-11-12,2,-0.0025355622677736807,0.9893968963422386 +2025-11-13,2,-0.009701374627358868,0.9797983863956764 +2025-11-14,2,-0.015419313055658527,0.9646905683444124 +2025-11-15,2,0.004427279314464904,0.9689615229425029 +2025-11-16,2,-0.005314738976397389,0.9638117453698911 +2025-11-17,2,-0.006842151859954704,0.9572171990436623 +2025-11-18,2,0.0055961312292173646,0.9625739121043746 +2025-11-19,2,0.0005381073727366743,0.9630918802232818 +2025-11-20,2,-0.003131879360378993,0.960075592641462 +2025-11-21,2,-0.0006553347613607761,0.95944642173207 +2025-11-22,2,-0.0010772646863963047,0.9584128439834486 +2025-11-23,2,0.0034288455950483103,0.9616990936417791 +2025-11-24,2,-0.0034567191882641864,0.9583747699314513 +2025-11-25,2,-0.0022976993823407357,0.9561727128145289 +2025-11-26,2,0.004031394885122388,0.960027422598263 +2025-11-27,2,0.0022112203843207756,0.9621502548046192 +2025-11-28,2,-0.0016273305498802943,0.9605845183014006 +2025-11-29,2,0.0017958312138565363,0.9623095659629136 +2025-11-30,2,-0.00104269668337875,0.9613061689701005 +2025-12-01,2,0.0009665115783011116,0.9622352825127023 +2025-12-02,2,-0.021478550866210526,0.9415678630519908 +2025-12-03,2,-0.012128690954037565,0.9301478774287797 +2025-12-04,2,0.004746088331346337,0.934562441416271 +2025-12-05,2,0.010097816343686604,0.9439994813113999 +2025-12-06,2,-0.0004345360801820303,0.9435892794770969 +2025-12-07,2,-0.003128868717570449,0.9406369124983062 +2025-12-08,2,-0.003141571398439713,0.9376818344776848 +2025-12-09,2,-0.011996777197943002,0.9264326744268976 +2025-12-10,2,0.001130308149632996,0.9274798288288886 +2025-12-11,2,0.0026845938921396424,0.9299697355124453 +2025-12-12,2,0.011808064588301368,0.9409508782145418 +2025-12-13,2,-0.001430642841918905,0.9396047135760269 +2025-12-14,2,0.0072499151457884655,0.946416768020036 +2025-12-15,2,0.008398218816012689,0.9543649831290119 +2025-12-16,2,-0.0032487866744978213,0.951264454889215 +2025-12-17,2,0.01024433825964685,0.9610095297394787 +2025-12-18,2,0.0018433141944570746,0.9627809722466562 +2025-12-19,2,-0.01302710525780838,0.9502387231809839 +2025-12-20,2,0.0003556792937175781,0.950576703418908 +2025-12-21,2,-0.0003702547780272833,0.9502247478525857 +2025-12-22,2,-0.0005250093004474356,0.9497258710224478 +2025-12-23,2,-0.001228020051648015,0.9485595886092634 +2025-12-24,2,0.001663512133984585,0.9501375289947223 +2025-12-25,2,0.0011556430393969042,0.9512355488165748 +2025-12-26,2,-0.0010800906976419816,0.9502081281490316 +2025-12-27,2,0.0005150419842002156,0.9506975252287565 +2025-12-28,2,9.153545177076928e-05,0.9507845477562257 +2025-12-29,2,0.0031253967388464206,0.9537561266811286 +2025-12-30,2,-0.007883167176084642,0.9462375076892864 +2025-12-31,2,0.0038735648964012205,0.9499028200827297 +2026-01-01,2,-0.007138314320776331,0.9431221151787873 +2026-01-02,2,-0.014644273648271686,0.9293107768403723 +2026-01-03,2,-0.0026085221696304085,0.9268866490765078 +2026-01-04,2,-0.004380686066840421,0.9228262496473579 +2026-01-05,2,-0.017246601339447457,0.9069106332141126 +2026-01-06,2,-0.004386297387099909,0.9029326534733123 +2026-01-07,2,0.02211164883891046,0.9228979832320997 +2026-01-08,2,0.0058746085221099715,0.9283196475894331 +2026-01-09,2,0.004225755484962726,0.9322424994320329 +2026-01-10,2,0.0006299298381866715,0.9328297467988508 +2026-01-11,2,-0.005196810660731519,0.9279820072260391 +2026-01-12,2,0.0006662155765666817,0.9286002432940267 +2026-01-13,2,-0.038425162865317275,0.8929186277086805 +2026-01-14,2,-0.007419376168036127,0.8862937285222632 +2026-01-15,2,0.006963711476133689,0.892465622330799 +2026-01-16,2,0.0014288521530732275,0.8937408237568102 +2026-01-17,2,0.0005469124861524067,0.8942296217727069 +2026-01-18,2,0.006470137132273968,0.9000154100533179 +2026-01-19,2,0.009412337559923038,0.9084866589018723 +2026-01-20,2,0.029773542766137945,0.9355355252931529 +2026-01-21,2,-0.0051767473444505815,0.9306924942469523 +2026-01-22,2,0.0012641133138079608,0.9318689950199911 +2026-01-23,2,-0.0003298940042253825,0.9315615770258105 +2026-01-24,2,-0.0008601526622427037,0.9307602918552887 +2026-01-25,2,6.749525605791867e-05,0.9308231137595161 +2026-01-26,2,-0.001070845505534445,0.9298263460116991 +2026-01-27,2,-0.0025512359896935266,0.9274541395735888 +2026-01-28,2,0.001015860370183095,0.9283963034791438 +2026-01-29,2,0.02313594085227216,0.9498756254439055 +2026-01-30,2,0.006925804931341905,0.9564542787347663 +2026-01-31,2,-0.001310174212885729,0.9552011570029638 +2026-02-01,2,0.012429849260618731,0.9670741633980793 +2026-02-02,2,-0.007637550999320494,0.9596880851550013 +2026-02-03,2,0.013866638440643465,0.9729957328476391 +2026-02-04,2,0.011454579043566386,0.9841409893785951 +2026-02-05,2,0.04844292842523596,1.0318156608874032 +2026-02-06,2,-0.02579510424952447,1.0051998683485206 +2026-02-07,2,0.0006978871478323955,1.0059013844176439 +2026-02-08,2,-0.0012593268579640543,1.0046346257877836 +2026-02-09,2,-0.00035162521483050803,1.004281370921665 +2026-02-10,2,0.0050127654111226634,1.009315597840856 +2026-02-11,2,0.0056673714401744985,1.0150357642341818 +2026-02-12,2,0.000841286480316008,1.0158897000996694 +2026-02-13,2,-0.007723480295069411,1.0080434960189857 +2026-02-14,2,-0.0025973668649725635,1.005425237243975 +2026-02-15,2,0.005811017686409835,1.0112677810799626 +2026-02-16,2,-0.0013099911867246027,1.0099430291993294 +2026-02-17,2,0.0020708404309236063,1.0120344600571247 +2026-02-18,2,0.002996011054286961,1.0150665264867753 +2026-02-19,2,-0.0005263806088746495,1.014532215150515 +2026-02-20,2,-0.002311416566282344,1.012187208581389 +2026-02-21,2,-0.00019678396466200364,1.0119880263695042 +2026-02-22,2,0.0011968570429917896,1.013199231366288 +2026-02-23,2,0.0092525393563099,1.0225738971302876 +2026-02-24,2,0.0009397059580602911,1.0235348159139779 +2026-02-25,2,-0.014942037198355058,1.0082411206207798 +2026-02-26,2,0.00241788166774077,1.0106789283429911 +2026-02-27,2,0.011196965896395066,1.0219954658358528 +2026-02-28,2,-0.00561826069772161,1.0162536288768975 +2026-03-01,2,0.005483127007435092,1.0218258765957964 +2026-03-02,2,-0.014565732853908303,1.0069422338540914 +2026-03-03,2,0.004048839653769905,1.0110191814995755 +2026-03-04,2,-0.02068152409976072,0.9901097639320716 +2026-03-05,2,0.007397775559751624,0.9974343737451598 +2026-03-06,2,0.012084130704181672,1.0094875010863398 +2026-03-07,2,0.0026122780498957663,1.0121245631270719 +2026-03-08,2,0.005247243047168315,1.0174354267038088 +2026-03-09,2,-0.00935490901472019,1.0079174108586417 +2026-03-10,2,-0.006105554858727141,1.001763515813578 +2026-03-11,2,-0.001478097372012743,1.0002828117934757 +2026-03-12,2,-0.001913027115078821,0.9983692436517675 +2026-03-13,2,-0.0021856341949793813,0.9961871736936264 +2026-03-14,2,-0.0008035201649364885,0.9953867172115125 +2026-03-15,2,-0.008015033004384801,0.9874086598209361 +2026-03-16,2,-0.014517923653585821,0.9730735362827662 +2026-03-17,2,0.0037749256404600185,0.9767468165249331 +2026-03-18,2,0.013724603546683055,0.9901522793472227 +2026-03-19,2,0.007242060125712012,0.997323021687866 +2026-03-20,2,-0.002073624397440773,0.9952549483379647 +2026-03-21,2,0.009021080261125851,1.0042332231072042 +2026-03-22,2,0.0036999612220771187,1.0079488470906224 +2026-03-23,2,-0.014608081280798544,0.9932246484054355 +2026-03-24,2,0.0007391275694383959,0.9939587681257177 +2026-03-25,2,-0.0030804730958360256,0.9908969048821361 +2026-03-26,2,0.015161433594410707,1.0059203225044138 +2026-03-27,2,0.012570797574003437,1.0185655432541931 +2026-03-28,2,-4.8541904760409444e-05,1.0185161001426002 +2026-03-29,2,0.0018463565060574038,1.0203966439706227 +2026-03-30,2,-0.00542164475433971,1.0148644158584936 +2026-03-31,2,-0.01086938512617643,1.0038334636716757 +2026-04-01,2,-0.0018308565923559417,1.0019955885570848 +2026-04-02,2,0.009340602464108826,1.011354831020587 +2026-04-03,2,0.0001005426010434777,1.0114565152658757 +2026-04-04,2,-0.0019330938651667936,1.0095012748813321 +2026-04-05,2,-0.008390326375882134,1.0010312297082087 +2026-04-06,2,0.0004881144300259519,1.0015198474963358 +2026-04-07,2,-0.020162242787059623,0.9813269611750558 +2026-04-08,2,0.006162257964691919,0.9873741510575236 +2026-04-09,2,-0.0018360715751954703,0.985561261444684 +2026-04-10,2,-0.007706572059789545,0.9779659625640235 +2026-04-11,2,-0.003205787431341866,0.9748308115729556 +2026-04-12,2,0.014148624191232521,0.9886233263759355 +2026-04-13,2,-0.025087444098447726,0.9638212939410578 +2026-04-14,2,0.003714565937142017,0.9674014716890234 +2026-04-15,2,-0.0038763636074286446,0.9636514718303951 +2026-04-16,2,-0.00031934334065135915,0.9633437361501572 +2026-04-17,2,-0.011202592493563654,0.9525517888428399 +2026-04-18,2,0.00901945694429313,0.9611432886895173 +2026-04-19,2,0.011486360135591452,0.9721833266453118 +2026-04-20,2,-0.009103371302987018,0.9633331808482865 +2026-04-21,2,-0.0021890330634980106,0.9612244126642449 +2026-04-22,2,-0.008276524749177692,0.9532688150233154 +2026-04-23,2,0.0027724012775822045,0.9559116587039653 +2026-04-24,2,0.0033700665622455606,0.9591331446214243 +2026-04-25,2,-0.0006485706076554598,0.9585110790549947 +2026-04-26,2,-0.006318772733880608,0.9524544653835395 +2026-04-27,2,0.008047844428886518,0.9601196707465445 +2026-04-28,2,0.004108665293900266,0.9640644811157317 +2026-04-29,2,0.004430443594102227,0.9683357144203925 +2026-04-30,2,-0.001840363831396608,0.9665536243949235 +2026-05-01,2,-0.008650485702201024,0.9581924660866846 +2026-05-02,2,-0.00295476983894339,0.9553612278879889 +2026-05-03,2,-3.6262136962852964e-05,0.9553265844482943 +2026-05-04,2,-0.0076379725611812055,0.9480298262093112 +2026-05-05,2,-0.005746255200939782,0.9425822048898099 +2026-05-06,2,-0.0007562565635125704,0.9418693709107119 +2026-05-07,2,0.011822788259352126,0.9530048930509585 +2026-05-08,2,-0.00247772258126819,0.9506436113073871 +2026-05-09,2,-0.004271928954266298,0.9465825293390547 +2026-05-10,2,-0.012250464403499528,0.934986453758412 +2026-05-11,2,0.005977380272433795,0.9405752233421005 +2026-05-12,2,0.014687414110805513,0.9543898411496894 +2026-05-13,2,0.008097131266706442,0.9621176609730895 +2026-05-14,2,-0.011415279170514419,0.9511348192781993 +2026-05-15,2,0.016752906155879373,0.9670690916471563 +2026-05-16,2,0.009639577186875851,0.9763912288011309 +2026-05-17,2,0.010282445511037405,0.9864309184087333 +2026-05-18,2,0.0019045883173531544,0.9883096632118106 +2026-05-19,2,0.0036111695066188072,0.9918786169306978 +2026-05-20,2,-0.005639516966716249,0.986284900641594 +2026-05-21,2,-0.001002185901593944,0.985296459819216 +2026-05-22,2,0.020226854268517683,1.0052259077232657 +2026-05-23,2,-0.012757454797413758,0.992401783644297 +2026-05-24,2,0.0011028080469340019,0.9934962123170915 +2026-05-25,2,-0.0031314020451649253,0.9903851762459781 +2026-05-26,2,0.012146778725374823,1.0024151658347293 +2026-05-27,2,0.013388659813546505,1.0158361614820302 +2026-05-28,2,0.0057289967343367824,1.021655883533782 +2026-05-29,2,0.0001074938848239621,1.0217657052936562 +2026-05-30,2,-0.0028549791539453037,1.0188485855048266 +2026-05-31,2,0.003202880894323782,1.0221118361735488 +2026-06-01,2,0.01141070475896574,1.0337748525667696 +2026-06-02,2,0.0470474943416133,1.0824113690934067 +2026-06-03,2,0.015517207188455704,1.0992073705707692 +2026-06-04,2,0.0061479965829703935,1.1059652937290143 +2026-06-05,2,0.036950750345677616,1.1468315411885792 +2026-06-06,2,0.0013852469495785021,1.1484201860826913 +2026-06-07,2,-0.01969467620845497,1.125802422366539 +2026-06-08,2,0.00017803880275311793,1.1260028588819537 +2026-06-09,2,0.008675442529904664,1.1357714319726926 +2026-06-10,2,0.002030142586023657,1.1380772099247294 +2026-06-11,2,-0.010915096017428716,1.1256549879031537 +2026-06-12,2,0.0005942030068469334,1.126323855481638 +2026-06-13,2,-0.0037894341999330475,1.1220557253434753 +2026-06-14,2,-0.0070775793559179085,1.1141142869055949 +2026-06-15,2,-0.006638674778437998,1.1067180444888172 +2026-06-16,2,0.002213072392366144,1.1091672916392088 +2026-06-17,2,0.006256249759124609,1.1161065192403554 +2026-06-18,2,0.007048380644466454,1.1239732628277321 +2026-06-19,2,-0.00194593700161763,1.1217860816667669 +2026-06-20,2,-0.003947889461533132,1.11735739421686 diff --git a/ml_engine/walk_forward_reports/pnl_daily_equity_specialist.csv b/ml_engine/walk_forward_reports/pnl_daily_equity_specialist.csv new file mode 100644 index 0000000000000000000000000000000000000000..d64c4639c8490f2371a5206bcbeb94767961af10 --- /dev/null +++ b/ml_engine/walk_forward_reports/pnl_daily_equity_specialist.csv @@ -0,0 +1,805 @@ +date,n_assets,pnl_net,equity +2022-08-17,8,0.0,1.0 +2022-08-18,8,0.0,1.0 +2022-08-19,8,0.0,1.0 +2022-08-22,8,0.0,1.0 +2022-08-23,8,0.0,1.0 +2022-08-24,8,0.0,1.0 +2022-08-25,8,0.0,1.0 +2022-08-26,8,0.0,1.0 +2022-08-29,8,0.0,1.0 +2022-08-30,8,0.0,1.0 +2022-08-31,8,-0.0014814724767526863,0.9985185275232473 +2022-09-01,8,0.0033226269674392376,1.0018362321102838 +2022-09-02,8,-0.0022922190960004227,0.9995398039679755 +2022-09-06,8,0.0036908247968747213,1.0032289302619237 +2022-09-07,8,-0.0014514213197927665,1.0017728224039086 +2022-09-08,8,0.0027878471923211837,1.004565611954191 +2022-09-09,8,-0.0015026345731852398,1.0030561169346357 +2022-09-12,8,-0.0009626055509389966,1.0020905695485711 +2022-09-13,8,-0.015029366229685818,0.9870297833835111 +2022-09-14,8,0.0014839226939814421,0.9884944592787094 +2022-09-15,8,0.00023958906538262592,0.9887312917423439 +2022-09-16,8,-0.0022214719573120214,0.9865348529044213 +2022-09-19,8,-0.000360670703485357,0.9861790386850114 +2022-09-20,8,0.0014710691812375644,0.9876297762760036 +2022-09-21,8,0.0003627276489213348,0.9879880169027568 +2022-09-22,8,-0.0022211377537233066,0.9857935594181879 +2022-09-23,8,-0.0006636818378733997,0.9851393061369096 +2022-09-26,8,0.0012261938065800998,0.9863472778527133 +2022-09-27,8,0.0028459657411932454,0.9891543884144013 +2022-09-28,8,-0.005920071901227692,0.9832985233135731 +2022-09-29,8,-0.0010759245216678949,0.9822405683202202 +2022-09-30,8,0.0003516238311201963,0.9825859475119347 +2022-10-03,8,-0.011105654828315902,0.9716736871397135 +2022-10-04,8,7.388913398853961e-05,0.9717454832669757 +2022-10-05,8,-0.0005141144339431115,0.9712458948879091 +2022-10-06,8,-0.002384715130130228,0.968929750107293 +2022-10-07,8,-0.013675302702957706,0.9556793424766746 +2022-10-10,8,-0.002822419461766857,0.9529820145012599 +2022-10-11,8,0.0017173414597170527,0.9546186100251276 +2022-10-12,8,6.834722576018132e-05,0.9546838555587818 +2022-10-13,8,0.0025555690941841463,0.9571236161147643 +2022-10-14,8,-0.012855642405292054,0.9448191771683329 +2022-10-17,8,-0.0023538695294817308,0.9425951960963264 +2022-10-18,8,0.0009057380522784959,0.9434489404333257 +2022-10-19,8,-0.001378465891573102,0.9421484282484976 +2022-10-20,8,-0.0026855132830851773,0.9396182761297984 +2022-10-21,8,0.007522483797237921,0.9466865393875734 +2022-10-24,8,0.003402589585828629,0.9499077251475379 +2022-10-25,8,0.009797769423448057,0.9592147020120856 +2022-10-26,8,-0.01581447736676122,0.9440452228172509 +2022-10-27,8,-0.016005262404214855,0.9289355313046154 +2022-10-28,8,0.007677658262874326,0.9360675808622139 +2022-10-31,8,-0.002638582907457595,0.9335976889431257 +2022-11-01,8,-0.0057330201978818395,0.928245354535719 +2022-11-02,8,-0.006555975469683597,0.9221598007615351 +2022-11-03,8,-9.685012815954019e-05,0.9220704894666478 +2022-11-04,8,-0.0021297647502104573,0.9201066962409725 +2022-11-07,8,-0.0009564694637198332,0.9192266422826538 +2022-11-08,8,0.000714100893047424,0.9198830628488208 +2022-11-09,8,-0.0069328376321560895,0.9135056629335194 +2022-11-10,8,0.001962593896792551,0.9152985035722783 +2022-11-11,8,0.0017169720379609959,0.9168700455092995 +2022-11-14,8,-0.002242176793976215,0.9148142607701667 +2022-11-15,8,0.002641580768379755,0.9172308165280567 +2022-11-16,8,-0.00214464376931694,0.9152636831723644 +2022-11-17,8,-1.1741926574973223e-05,0.9152529362133999 +2022-11-18,8,0.0002362385092364965,0.9154691542026252 +2022-11-21,8,0.0008680448028352806,0.9162638224440868 +2022-11-22,8,0.0032355987170526682,0.9192284844924686 +2022-11-23,8,-0.0003523524381342405,0.9189045920947553 +2022-11-25,8,-0.0014052918015337544,0.9176132630050928 +2022-11-28,8,-0.005420056497156683,0.9126397472770649 +2022-11-29,8,-0.0016145983699964324,0.9111662006287173 +2022-11-30,8,0.01784307083850462,0.9274242036921867 +2022-12-01,8,0.0005499401845661838,0.9279342315299363 +2022-12-02,8,-0.0004210974916838431,0.9275434807525914 +2022-12-05,8,-0.00671815250736197,0.9213121021916861 +2022-12-06,8,-0.00922826582791992,0.9128099892021815 +2022-12-07,8,-0.002640328444420268,0.91039987102334 +2022-12-08,8,0.0022845961612220148,0.912479767073857 +2022-12-09,8,-0.00018520922957741424,0.9123107673991923 +2022-12-12,8,0.0024367234200895777,0.9145338164125136 +2022-12-13,8,0.006827437237461303,0.920777738645606 +2022-12-14,8,-0.003634726968599916,0.9174309629668643 +2022-12-15,8,-0.015756344735681587,0.9029756044431702 +2022-12-16,8,-0.004925199335002496,0.8985282695966432 +2022-12-19,8,-0.008202096015247762,0.8911584544569972 +2022-12-20,8,-0.0010864896397580885,0.8901902200288467 +2022-12-21,8,0.006374830714762574,0.895865031985468 +2022-12-22,8,-0.007960300174765447,0.8887336774147878 +2022-12-23,8,-0.0008594323281163477,0.8879698709613318 +2022-12-27,8,-0.0016425445642140085,0.8865113408765986 +2022-12-28,8,0.00024899377820378535,0.8867320766847839 +2022-12-29,8,-0.003147194091377657,0.8839413587324065 +2022-12-30,8,-0.0007656797392384242,0.8832645427433502 +2023-01-03,8,0.005468461072009033,0.8880946405116281 +2023-01-04,8,-0.005470296033442108,0.8832364999223162 +2023-01-05,8,-0.0035890699371982733,0.8800665023530088 +2023-01-06,8,0.0030681336214150173,0.8827666639779592 +2023-01-09,8,0.001772747949521421,0.8843315867714319 +2023-01-10,8,0.005153812587668233,0.8888892660350071 +2023-01-11,8,0.00865104442839642,0.8965790865674006 +2023-01-12,8,0.00314408788781132,0.899398010013942 +2023-01-13,8,0.003799480901389437,0.9028152555757377 +2023-01-17,8,0.0014748086080542371,0.9041467352861435 +2023-01-18,8,-0.00572212208973424,0.8989730972798016 +2023-01-19,8,-0.0013268487392913352,0.897780295959019 +2023-01-20,8,0.015497155263490383,0.9116933365979982 +2023-01-23,8,0.009903226764654346,0.9207220424501525 +2023-01-24,8,-0.0014002615718417852,0.9194327907557619 +2023-01-25,8,-0.002313124091573984,0.9173060286168816 +2023-01-26,8,0.011944948382045536,0.9282632017792494 +2023-01-27,8,0.009150046672322068,0.9367568533997286 +2023-01-30,8,-0.012379693376381316,0.9251600907864161 +2023-01-31,8,0.008220592644029006,0.9327654550232842 +2023-02-01,8,0.009756655215571902,0.9418661259649425 +2023-02-02,8,0.030039240728419733,0.9701590692567476 +2023-02-03,8,-0.0068761556067825315,0.9634881045332068 +2023-02-06,8,-0.0032550982716341515,0.9603518560694007 +2023-02-07,8,0.01034994297671812,0.9702914430173044 +2023-02-08,8,-0.007504514620441479,0.9630098766970918 +2023-02-09,8,-0.0040398753632871365,0.959119436821621 +2023-02-10,8,-0.0036335240440617898,0.9556344532868026 +2023-02-13,8,0.006350269079953646,0.9617029892072483 +2023-02-14,8,0.0034114075355928235,0.9649837500316321 +2023-02-15,8,0.002354937105429966,0.9672562260707185 +2023-02-16,8,-0.00882859235008529,0.9587167151526582 +2023-02-17,8,-0.0025230245818857154,0.9562978493132633 +2023-02-21,8,-0.01023483335548213,0.9465103001873361 +2023-02-22,8,0.0006870437055327557,0.9471605941313018 +2023-02-23,8,0.00588426297268919,0.9527339361445389 +2023-02-24,8,-0.006570037669141332,0.9464744382954 +2023-02-27,8,0.00250069414747445,0.9488412813839796 +2023-02-28,8,-0.0004327327473947432,0.9484306866894447 +2023-03-01,8,-0.004231404184957941,0.9444174931126446 +2023-03-02,8,0.001909116235527173,0.9462204958818617 +2023-03-03,8,0.010462500382576095,0.956120328182027 +2023-03-06,8,0.0008050765657534975,0.9568900782522868 +2023-03-07,8,-0.005951999527373526,0.9511946689587807 +2023-03-08,8,0.0014524314264064784,0.9525762139886066 +2023-03-09,8,-0.00973594241916977,0.9433019868193427 +2023-03-10,8,-0.007729876993836921,0.9360103784931872 +2023-03-13,8,0.004970075522141248,0.9406624207638065 +2023-03-14,8,0.016566242776652203,0.956245662797053 +2023-03-15,8,0.004087786103928106,0.9601545905293764 +2023-03-16,8,0.01595544300648735,0.9754742823759851 +2023-03-17,8,-0.0035019923387106457,0.9720581789124951 +2023-03-20,8,0.0006751525539540119,0.9727144664745799 +2023-03-21,8,0.010839277376552702,0.9832579883848833 +2023-03-22,8,-0.006463903059808453,0.9769023040651811 +2023-03-23,8,0.005587858238098277,0.982361095652769 +2023-03-24,8,0.0008890963109276675,0.9832345092789126 +2023-03-27,8,-0.004865092863619706,0.9784509820845552 +2023-03-28,8,-0.0034244680400452184,0.9751003079676557 +2023-03-29,8,0.009604982059037762,0.9844661289314472 +2023-03-30,8,0.004673309981569888,0.9890668443183 +2023-03-31,8,0.010166578286630076,0.9991222698217722 +2023-04-03,8,-0.0010249807420235962,0.998098188736278 +2023-04-04,8,-0.0007216127443541074,0.9973779483631692 +2023-04-05,8,-0.007331449310072458,0.9900657224917605 +2023-04-06,8,0.006821307682256236,0.9968192654105322 +2023-04-10,8,-0.0024151546161686483,0.9944117927601901 +2023-04-11,8,-0.005196095102227283,0.9892447345142318 +2023-04-12,8,-0.005220395527164721,0.9840804857269024 +2023-04-13,8,0.01413981452034635,0.9979952012681732 +2023-04-14,8,0.00024994793942035426,0.9982446481122816 +2023-04-17,8,-2.8335480933906027e-05,0.9982163623700876 +2023-04-18,8,0.0005544971965729382,0.9987698705445951 +2023-04-19,8,0.0008211430895947775,0.9995900035218883 +2023-04-20,8,-0.009516029171983019,0.9900778758883514 +2023-04-21,8,0.0015439999522230217,0.9916065560814201 +2023-04-24,8,-0.0017481723030260258,0.9898730569645795 +2023-04-25,8,-0.014496858824238443,0.9755230070038466 +2023-04-26,8,0.007559008330377443,0.9828969935402635 +2023-04-27,8,0.025875283447098222,1.0083297318474187 +2023-04-28,8,0.0024676177304177333,1.0108179041718328 +2023-05-01,8,0.00044033027906091035,1.0112629979016567 +2023-05-02,8,-0.005328468796495659,1.0058745145722872 +2023-05-03,8,-0.002882861413682075,1.0029747177472206 +2023-05-04,8,-0.0030452430184880652,0.9999204159902808 +2023-05-05,8,0.013709204698854564,1.0136285296556553 +2023-05-08,8,0.0025961778878838175,1.0162600896308756 +2023-05-09,8,-0.003212002011937244,1.0129958601783295 +2023-05-10,8,0.007514130002287174,1.0206076427634883 +2023-05-11,8,0.003717009888796612,1.0244012514642216 +2023-05-12,8,-0.0029511548055413117,1.0213780847881604 +2023-05-15,8,0.0018569271466572037,1.0232747094808043 +2023-05-16,8,0.0027268370791455458,1.0260650129007685 +2023-05-17,8,0.008145307608727672,1.0344226280573983 +2023-05-18,8,0.00937668805023491,1.0441220863527967 +2023-05-19,8,-0.0010139201212816247,1.043063429960369 +2023-05-22,8,0.0033276868072795755,1.0465344183754037 +2023-05-23,8,-0.0070463165942573945,1.0391602055367437 +2023-05-24,8,-0.0017467575307288964,1.0373450446220887 +2023-05-25,8,0.018798789634489083,1.0568458758943189 +2023-05-26,8,0.015410283863827385,1.0731321708421657 +2023-05-30,8,0.0036962294381444752,1.0770987135630523 +2023-05-31,8,-0.0026061328308448614,1.074291651243575 +2023-06-01,8,0.010539772716635632,1.0856144410790614 +2023-06-02,8,0.005987718090644093,1.0921147943073748 +2023-06-05,8,0.000832146370889731,1.0930235936700528 +2023-06-06,8,0.001429628062295948,1.094586210872315 +2023-06-07,8,-0.013068500702070836,1.080281610207053 +2023-06-08,8,0.00829285008979707,1.0892402236552645 +2023-06-09,8,0.0030454891295348552,1.0925574929158588 +2023-06-12,8,0.01067157619691679,1.1042168034510227 +2023-06-13,8,0.004428330188729902,1.1091066400566478 +2023-06-14,8,0.0023436078669703984,1.1117059511035936 +2023-06-15,8,0.009515047000857303,1.1222838854794772 +2023-06-16,8,-0.0035478931346696967,1.118302142187034 +2023-06-20,8,0.002767558300224903,1.1213971085628032 +2023-06-21,8,-0.009065916029641909,1.1112306165406896 +2023-06-22,8,0.010226596171473194,1.1225947233094282 +2023-06-23,8,-0.004250016222136806,1.1178236775244779 +2023-06-26,8,-0.013263241116309752,1.1029977125639507 +2023-06-27,8,0.010692253183591856,1.114791243367607 +2023-06-28,8,0.0021049922134422834,1.1171378702545094 +2023-06-29,8,-0.0015209205387385102,1.1154387923230367 +2023-06-30,8,0.01164935436733607,1.128432934089881 +2023-07-03,8,0.0011617550933253364,1.129743896798536 +2023-07-05,8,0.0024979886371081462,1.132565984215581 +2023-07-06,8,-0.0041461636708207605,1.127870180277019 +2023-07-07,8,-0.001913646972918601,1.1257118349206867 +2023-07-10,8,-0.006333637869487028,1.1185819838129034 +2023-07-11,8,0.0038016706274462517,1.1228344640851553 +2023-07-12,8,0.010880819158428407,1.1350518228337168 +2023-07-13,8,0.0132225187152134,1.1500600668038725 +2023-07-14,8,0.00019713742879538901,1.1502867866884026 +2023-07-17,8,0.004628666701658822,1.1556110808353053 +2023-07-18,8,0.005863496388376935,1.1623870022341516 +2023-07-19,8,0.0009772129870319905,1.1635229019086921 +2023-07-20,8,-0.01773705108736159,1.1428854367562225 +2023-07-21,8,-0.004296384362455577,1.1379751616376648 +2023-07-24,8,0.002847087213095373,1.1412150761691835 +2023-07-25,8,0.004305989048464277,1.1461291357891104 +2023-07-26,8,0.0015106265459685865,1.1478605088867413 +2023-07-27,8,-0.0018436268191290603,1.1457442824679385 +2023-07-28,8,0.01427194316982873,1.1620962797544772 +2023-07-31,8,0.00014154892278205782,1.1622607732310455 +2023-08-01,8,-0.0032966475635067666,1.1584292090848138 +2023-08-02,8,-0.016097134388343703,1.139781818426793 +2023-08-03,8,-0.0004926372335803907,1.139220319464878 +2023-08-04,8,-0.0034395374401403403,1.13530192852351 +2023-08-07,8,0.004494948312400669,1.140405052011192 +2023-08-08,8,-0.003776138879487877,1.136098724155928 +2023-08-09,8,-0.009073134874874789,1.125790747200488 +2023-08-10,8,0.0007431318304430208,1.1266273581391508 +2023-08-11,8,-0.003706390995378801,1.1224516366437964 +2023-08-14,8,0.007986420752816916,1.1314160076887216 +2023-08-15,8,-0.007208591292074386,1.1232600921079832 +2023-08-16,8,-0.006517869991320783,1.1159388288611845 +2023-08-17,8,-0.006283790645274552,1.108926502887688 +2023-08-18,8,-0.0026836090716460025,1.10595057766475 +2023-08-21,8,0.013124151688114826,1.1204652408055804 +2023-08-22,8,-0.0005749689356917623,1.1198210080985949 +2023-08-23,8,0.010274499159981198,1.1313266081056332 +2023-08-24,8,-0.01221303492929336,1.1175096767244002 +2023-08-25,8,0.003990043873026743,1.1219685893630624 +2023-08-28,8,0.004435633515034884,1.1269452308408576 +2023-08-29,8,0.01487059991698542,1.1437035824970467 +2023-08-30,8,0.002542309640833675,1.146611231141085 +2023-08-31,8,0.001227612141677294,1.1480188250102172 +2023-09-01,8,-0.001621436566329269,1.1461573853085112 +2023-09-05,8,0.0032468906016831934,1.149878832950919 +2023-09-06,8,-0.008960151452290758,1.1395757444558954 +2023-09-07,8,-0.002490047541291368,1.1367381466752977 +2023-09-08,8,0.001935358534251202,1.1389381425486746 +2023-09-11,8,0.011498154325528547,1.1520338290789303 +2023-09-12,8,-0.008533431133333961,1.1422030277352142 +2023-09-13,8,0.005339816111588202,1.1483021818654195 +2023-09-14,8,0.0058010916603923116,1.1549635880762494 +2023-09-15,8,-0.012278082832642024,1.1407828494731638 +2023-09-18,8,0.0007921488074174048,1.1416865192468961 +2023-09-19,8,-0.001123903584945856,1.14040337367503 +2023-09-20,8,-0.013296311549226681,1.1252402151268577 +2023-09-21,8,-0.012241382679742004,1.1114657190468546 +2023-09-22,8,-0.0007046911557422591,1.1106824789847316 +2023-09-25,8,0.004561896742515359,1.115749297767581 +2023-09-26,8,-0.011443193480001572,1.1029815626780506 +2023-09-27,8,0.0009712038722422714,1.1040527826427353 +2023-09-28,8,0.006175945846874988,1.1108713528404286 +2023-09-29,8,0.0002820158395152036,1.1111846361575932 +2023-10-02,8,0.010148120580646711,1.1224610718326824 +2023-10-03,8,-0.0125211371685606,1.1084065827858958 +2023-10-04,8,0.01007682541615528,1.1195758024107463 +2023-10-05,8,0.00076034573324007,1.1204270670951482 +2023-10-06,8,0.011528925199774047,1.1333443869434905 +2023-10-09,8,0.002748437309755757,1.1364593129413683 +2023-10-10,8,0.0026205330448512776,1.13943744212506 +2023-10-11,8,0.0072541594692771974,1.1477031030355005 +2023-10-12,8,-0.0026908812069859817,1.1446147703243428 +2023-10-13,8,-0.01025820442453171,1.1328730780230172 +2023-10-16,8,0.007905831411901487,1.141829381588949 +2023-10-17,8,-0.003370618285129099,1.1379807105968678 +2023-10-18,8,-0.01196566055823188,1.1243640196920501 +2023-10-19,8,-0.006915308193878002,1.116588695973772 +2023-10-20,8,-0.011298600949874915,1.1039728058728233 +2023-10-23,8,0.0049926616694393145,1.109484568584808 +2023-10-24,8,0.005389902147651722,1.1154645818438098 +2023-10-25,8,-0.019782376250378778,1.093398041791804 +2023-10-26,8,-0.015466469098171383,1.0764870347664302 +2023-10-27,8,0.0063242894598209975,1.0832950503740375 +2023-10-30,8,0.007067159168268222,1.090950868921228 +2023-10-31,8,0.0012558269079507955,1.0923209143776715 +2023-11-01,8,0.011985229358563465,1.1054126310696437 +2023-11-02,8,0.009350378438971591,1.1157486575013642 +2023-11-03,8,0.004569208256024792,1.120846745478868 +2023-11-06,8,0.004177164658080246,1.1255287068912065 +2023-11-07,8,0.005028328919301294,1.1311882354375715 +2023-11-08,8,0.0020627034419638877,1.1335215413043176 +2023-11-09,8,-0.004252444793117775,1.1287013035281113 +2023-11-10,8,0.01120052057386052,1.141343345700021 +2023-11-13,8,-0.00033865499344853836,1.1409568240767605 +2023-11-14,8,0.009875551050507305,1.1522244014393552 +2023-11-15,8,-0.0006362163102357748,1.1514913374821079 +2023-11-16,8,0.0026961351164526224,1.1545959137133845 +2023-11-17,8,-0.0008765116658196698,1.153583896925707 +2023-11-20,8,0.006326245619730532,1.1608817520006252 +2023-11-21,8,-0.0022408730891450984,1.1582803633228873 +2023-11-22,8,0.0015032963252911548,1.1600216019367275 +2023-11-24,8,-0.0037166343151665555,1.155710225844635 +2023-11-27,8,-0.00014508220682765206,1.1555425528546162 +2023-11-28,8,0.004184045666373358,1.1603773956651975 +2023-11-29,8,-0.006176555222320203,1.1532102606021393 +2023-11-30,8,-0.005072172106076253,1.1473609796858721 +2023-12-01,8,-0.00017763846687620795,1.1471571642404872 +2023-12-04,8,-0.011180517374975113,1.1343313536338693 +2023-12-05,8,0.00789870566669598,1.143291103124728 +2023-12-06,8,-0.006335675709364394,1.1360475814539281 +2023-12-07,8,0.014534067669611255,1.152558973878678 +2023-12-08,8,0.0048622412506785905,1.1581629936653106 +2023-12-11,8,-0.0072977631477713885,1.1497109944510273 +2023-12-12,8,0.006597921923199341,1.157296697826659 +2023-12-13,8,0.007424010672359581,1.1658884808624106 +2023-12-14,8,0.00014114714007760175,1.1660530426871338 +2023-12-15,8,0.004281930466969945,1.1710460007367187 +2023-12-18,8,0.008742923797959878,1.1812843666850656 +2023-12-19,8,0.004564088898227725,1.186675853548703 +2023-12-20,8,-0.01065834417939613,1.1740278538722022 +2023-12-21,8,0.008586384927703078,1.184108508941394 +2023-12-22,8,-0.0005141756073711303,1.1834996692296158 +2023-12-26,8,0.002261012837492135,1.1861755771749116 +2023-12-27,8,0.0014567874728795233,1.1879035828963755 +2023-12-28,8,-0.000970200605407008,1.1867510781210844 +2023-12-29,8,-0.004321184678520159,1.1816229075450904 +2024-01-02,8,-0.013469186550376886,1.165707408171167 +2024-01-03,8,-0.0064426040632730485,1.1581972168866959 +2024-01-04,8,-0.005769868146206546,1.1515145716579562 +2024-01-05,8,0.0023778675194060205,1.1542527207560243 +2024-01-08,8,0.018540760322689368,1.1756534438033739 +2024-01-09,8,0.0022053414140659616,1.1782461610315826 +2024-01-10,8,0.010282776203015386,1.1903618026175324 +2024-01-11,8,-0.0003415168324478134,1.1899552740252357 +2024-01-12,8,0.000773045303740673,1.1908751633614825 +2024-01-16,8,-0.0020561921116455852,1.188426495244624 +2024-01-17,8,-0.004735669258294287,1.1827985004253516 +2024-01-18,8,0.011081826371672534,1.19590606803974 +2024-01-19,8,0.012834945076275237,1.2112554567394143 +2024-01-22,8,-0.0011785346720420433,1.2098279501869467 +2024-01-23,8,0.004593794641187037,1.215385651341274 +2024-01-24,8,0.005295709279945916,1.221821980413795 +2024-01-25,8,-0.0033326057215937394,1.217750129491099 +2024-01-26,8,-0.0005401048570509274,1.2170924167314865 +2024-01-29,8,0.00994867336989351,1.2292008716465224 +2024-01-30,8,-0.004657994467157791,1.2234752607873673 +2024-01-31,8,-0.02276897828171372,1.1956179791462858 +2024-02-01,8,0.010470106446981844,1.2081362266578728 +2024-02-02,8,0.028318718390774846,1.2423490962382906 +2024-02-05,8,-0.0007409579861152727,1.2414285677538897 +2024-02-06,8,0.0005707243952974641,1.242137081322526 +2024-02-07,8,0.007688217555933005,1.2516869014380252 +2024-02-08,8,-0.0005514561267868127,1.2509966510274084 +2024-02-09,8,0.008396195976097873,1.2615002640748767 +2024-02-12,8,-0.004306488339026907,1.2560676278979588 +2024-02-13,8,-0.009003400325050717,1.2447587482086566 +2024-02-14,8,0.005824129291912054,1.2520083840954626 +2024-02-15,8,0.00033552754656996395,1.252428467396863 +2024-02-16,8,-0.003968296999136965,1.2474584592680584 +2024-02-20,8,-0.0058469838828065085,1.2401645897622475 +2024-02-21,8,0.00014805049370943056,1.2403481967420429 +2024-02-22,8,0.01775122580316113,1.2623658976569545 +2024-02-23,8,-0.0022639295590469125,1.2595079901869162 +2024-02-26,8,-0.0029146775118596615,1.2558369305719108 +2024-02-27,8,0.0016157925283590056,1.2578661025011664 +2024-02-28,8,-0.00199556636988054,1.2553559472092024 +2024-02-29,8,0.0038782768243433947,1.2602245650855657 +2024-03-01,8,0.002649655192227274,1.263563725647817 +2024-03-04,8,-0.009608860964510687,1.251422317488268 +2024-03-05,8,-0.012908758411329047,1.2352680091212664 +2024-03-06,8,-0.00018140330660295918,1.235043927419871 +2024-03-07,8,0.01008197972209362,1.2474956152520131 +2024-03-08,8,-0.003704194712456822,1.2428746485901836 +2024-03-11,8,-0.0025669396145697305,1.2396842644187729 +2024-03-12,8,0.010156260576002722,1.2522748208401804 +2024-03-13,8,-0.003063506848274059,1.2484384683506153 +2024-03-14,8,0.002900023700348037,1.2520589694972584 +2024-03-15,8,-0.006821542139489685,1.2435179964757068 +2024-03-18,8,0.009195422751689395,1.2549526701526348 +2024-03-19,8,0.003137515556872203,1.258890103678377 +2024-03-20,8,0.007739498491137159,1.2686332817363035 +2024-03-21,8,-0.0031341988022925366,1.2646571328241372 +2024-03-22,8,0.002595766462761631,1.2679398873964143 +2024-03-25,8,-0.002342385057500234,1.2649698839503682 +2024-03-26,8,-0.0023675018420578915,1.261975065419968 +2024-03-27,8,0.0033683160281597637,1.26622579625996 +2024-03-28,8,-0.002518956167481659,1.2630362289810464 +2024-04-01,8,0.002884524740243416,1.266679488231366 +2024-04-02,8,-0.004613034758424726,1.260836251724371 +2024-04-03,8,0.002838076113843392,1.2644146009738577 +2024-04-04,8,-0.007582565957483875,1.2548270938643677 +2024-04-05,8,0.009206054624875991,1.2663791006352576 +2024-04-08,8,0.00111627936370638,1.2677927334919257 +2024-04-09,8,0.0019017971471893215,1.270203818095708 +2024-04-10,8,-0.0034922347880190032,1.2657679681342797 +2024-04-11,8,0.01342023805963229,1.2827548755948988 +2024-04-12,8,-0.010137124817192412,1.2697514293111312 +2024-04-15,8,-0.014434750163925824,1.2514228846587372 +2024-04-16,8,-0.001934740230259488,1.2490017064587204 +2024-04-17,8,-0.00652983540789936,1.2408459308913595 +2024-04-18,8,-0.003933654610298067,1.2359648715746392 +2024-04-19,8,-0.017465013230195288,1.2143787287405314 +2024-04-22,8,0.005375402928486614,1.2209065037152953 +2024-04-23,8,0.01072199417421904,1.233997056135397 +2024-04-24,8,0.0034705279409792955,1.238279677397801 +2024-04-25,8,-0.010588466606076987,1.2251681943846906 +2024-04-26,8,0.015529534983910846,1.2441944867205625 +2024-04-29,8,0.0038790639636738767,1.249020796717802 +2024-04-30,8,-0.012269501497946977,1.233695934181506 +2024-05-01,8,0.0012589648255578257,1.2352491139680741 +2024-05-02,8,0.0074933924378917036,1.2445053203375949 +2024-05-03,8,0.010399099592677022,1.257447055107402 +2024-05-06,8,0.005956514793593346,1.2649370570933096 +2024-05-07,8,-0.0007393945590214709,1.2640017695157901 +2024-05-08,8,-0.0005078696427293458,1.263359821388697 +2024-05-09,8,0.001638725421888419,1.265430121244999 +2024-05-10,8,-0.0009012317661882974,1.2642896754218416 +2024-05-13,8,0.0007551413194609898,1.2652443927955206 +2024-05-14,8,0.0035898654316976935,1.2697864499038667 +2024-05-15,8,0.00575215538700992,1.2770904588720333 +2024-05-16,8,-0.001694114517474905,1.2749269213855294 +2024-05-17,8,0.0005929930875298105,1.2756829442370168 +2024-05-20,8,0.0018532151942753762,1.2780470592523547 +2024-05-21,8,0.0032547880783057904,1.2822068315843231 +2024-05-22,8,-0.0019672844183203104,1.2796843660634836 +2024-05-23,8,-0.0021097044189272054,1.2769846103015674 +2024-05-24,8,0.007219197682248823,1.286203414640524 +2024-05-28,8,0.004239251374058318,1.2916559542333572 +2024-05-29,8,-0.0025971597952702116,1.2883013173197009 +2024-05-30,8,-0.012240782036481629,1.2725315016970784 +2024-05-31,8,0.00021318474832775458,1.2728027860050068 +2024-06-03,8,0.005759984895336981,1.2801341108271385 +2024-06-04,8,0.0022977950610816793,1.283075596664519 +2024-06-05,8,0.014126198685695871,1.30120057747177 +2024-06-06,8,0.0030684317517199636,1.3051932226390408 +2024-06-07,8,-0.0012374924170103292,1.3035780559232917 +2024-06-10,8,0.0023313962694385946,1.3066172129397933 +2024-06-11,8,0.010611268538297509,1.3204820790630594 +2024-06-12,8,0.00958425631954578,1.3331379177741665 +2024-06-13,8,-0.0009886163033170263,1.3318199558940849 +2024-06-14,8,0.00042728292348860673,1.3323890198183996 +2024-06-17,8,0.007504568337791383,1.3423880242701498 +2024-06-18,8,-0.003331354281304848,1.337916054178325 +2024-06-20,8,-0.0009514350147722582,1.3366431139975539 +2024-06-21,8,0.0019698270701667296,1.3392760697866581 +2024-06-24,8,-0.005058859593820036,1.3325008601922443 +2024-06-25,8,0.011074412234939181,1.3472575240214242 +2024-06-26,8,0.008643306526382726,1.3589022837715168 +2024-06-27,8,0.0040748078374860065,1.3644395494478065 +2024-06-28,8,-0.009710655795687997,1.3511899466290953 +2024-07-01,8,0.010760107460752542,1.365728895654713 +2024-07-02,8,0.010828316948851871,1.3805174410030676 +2024-07-03,8,0.0055607295250076,1.388194125097041 +2024-07-05,8,0.013136777246265146,1.406430522093015 +2024-07-08,8,-0.001165044846027223,1.4047919674619551 +2024-07-09,8,0.0008561086681400257,1.4059946220422328 +2024-07-10,8,0.009262789583270882,1.4190180543814204 +2024-07-11,8,-0.02004654174842147,1.3905716497124994 +2024-07-12,8,0.001677697911817403,1.3929046088654544 +2024-07-15,8,0.00214918515045105,1.395898218766823 +2024-07-16,8,-0.0012959225799597848,1.3940892427457974 +2024-07-17,8,-0.01708060868407113,1.3702773499197833 +2024-07-18,8,-0.0045848132704328125,1.3639948841416976 +2024-07-19,8,-0.004342362132948176,1.3580719244072657 +2024-07-22,8,0.008842664495955783,1.3700808987961761 +2024-07-23,8,0.001264641933209872,1.3718135605526836 +2024-07-24,8,-0.02515814361536104,1.3373012779827993 +2024-07-25,8,-0.006464605604486982,1.3286561526462641 +2024-07-26,8,0.005298159693815753,1.335695585121155 +2024-07-29,8,0.0024489204149634493,1.3389665973077345 +2024-07-30,8,-0.005288532856133102,1.3318854284646078 +2024-07-31,8,0.011168886028824898,1.3467611050185815 +2024-08-01,8,-0.006358831230475109,1.3381972784440002 +2024-08-02,8,-0.014222733457075752,1.319164455239707 +2024-08-05,8,-0.018981803190379117,1.2941243351746032 +2024-08-06,8,0.003718127335390617,1.29893605424061 +2024-08-07,8,-0.0023401368608371195,1.2958963661002114 +2024-08-08,8,0.010172105557765012,1.309078360728107 +2024-08-09,8,0.0029872393402320856,1.3129888911067205 +2024-08-12,8,-0.0012539375977519683,1.3113424849707311 +2024-08-13,8,0.006443779855295746,1.319792487258779 +2024-08-14,8,-0.0010405237917143586,1.3184192117756603 +2024-08-15,8,0.008854966183412173,1.3300937693114947 +2024-08-16,8,0.0003053495043425223,1.330499912784683 +2024-08-19,8,0.004675541626799007,1.3367207205113603 +2024-08-20,8,7.81620606133048e-05,1.33682520135734 +2024-08-21,8,0.0011525070000780932,1.3383659017597853 +2024-08-22,8,-0.007968224979668086,1.327701501149447 +2024-08-23,8,0.005002270681836171,1.3343430234428768 +2024-08-26,8,-0.003176055462623318,1.3301050759942576 +2024-08-27,8,-0.0011820903634506131,1.328532771601548 +2024-08-28,8,-0.004446748347734569,1.3226251206945177 +2024-08-29,8,-0.00010059726768823688,1.3224920682212 +2024-08-30,8,0.005947894974279897,1.330358112147298 +2024-09-03,8,-0.01463141757139824,1.310893087088974 +2024-09-04,8,-0.0009802839626849046,1.309608039618906 +2024-09-05,8,0.0045691912138583505,1.315591889167131 +2024-09-06,8,-0.01518771654100522,1.295611052470815 +2024-09-09,8,0.005558565315637126,1.3028127911296354 +2024-09-10,8,0.004705942286189286,1.3089437529344006 +2024-09-11,8,0.006737609532007686,1.3177629048410333 +2024-09-12,8,0.006616898205385993,1.3264824078412003 +2024-09-13,8,0.002323670558652572,1.3295647159588717 +2024-09-16,8,-0.0031038680268637795,1.3254379225473607 +2024-09-17,8,0.002765172079520442,1.3291029864839263 +2024-09-18,8,0.0001573175814919996,1.3293120777513137 +2024-09-19,8,0.016940306919674485,1.3518310323404512 +2024-09-20,8,-0.0009123563966475529,1.3505976806509088 +2024-09-23,8,0.0013206421442872754,1.3523813368679531 +2024-09-24,8,0.0014914554866834674,1.3543983534329131 +2024-09-25,8,0.0009292282386998777,1.3556568986293716 +2024-09-26,8,0.0005277183975447514,1.3563723037155366 +2024-09-27,8,-0.0013460888361388878,1.3545465060998572 +2024-09-30,8,0.004155752522567608,1.3601756661595166 +2024-10-01,8,-0.006987974109314774,1.350670793820274 +2024-10-02,8,-0.0024441539103609664,1.3473695465179478 +2024-10-03,8,-0.0002560996874735695,1.3470244855981732 +2024-10-04,8,0.008055868036752269,1.3578759370964262 +2024-10-07,8,-0.013611174816291946,1.3393936503377706 +2024-10-08,8,0.009778809995218712,1.352491326353226 +2024-10-09,8,0.0015018443211833779,1.3545225577711595 +2024-10-10,8,-0.0007024844616724977,1.3535710267213403 +2024-10-11,8,-0.00021815278273517019,1.3532757414352314 +2024-10-14,8,0.0057620214068195294,1.3610733452267108 +2024-10-15,8,-0.0034786692956840096,1.3563386211714967 +2024-10-16,8,-0.0010816953677136247,1.3548714759679243 +2024-10-17,8,-0.0006243204401309814,1.3540256020117272 +2024-10-18,8,0.0037407248927069725,1.3590906392865352 +2024-10-21,8,0.0024252297663818765,1.3623867463601438 +2024-10-22,8,0.0047871039577967525,1.3689086333456941 +2024-10-23,8,-0.014812744233836177,1.3486313398804541 +2024-10-24,8,0.010664298116152967,1.363013546537726 +2024-10-25,8,0.005709856473744262,1.3707961582602257 +2024-10-28,8,0.001967474210770149,1.3734931643498256 +2024-10-29,8,0.007435067660129583,1.3837051789574921 +2024-10-30,8,0.0006827378509766125,1.3846498868577588 +2024-10-31,8,-0.02669196689666274,1.3476908579142837 +2024-11-01,8,0.005694482307920484,1.355365259661223 +2024-11-04,8,-0.0039849244461377265,1.349964231504553 +2024-11-05,8,0.008512147672455462,1.3614553263956526 +2024-11-06,8,0.016628285119234188,1.3840939937400594 +2024-11-07,8,0.011273450463238681,1.399697508814954 +2024-11-08,8,-0.0007669260748509911,1.3986240442985398 +2024-11-11,8,-0.0010852629283646489,1.3971061694725433 +2024-11-12,8,0.0014218165744895265,1.3990925981806208 +2024-11-13,8,-5.773029574973147e-05,1.3990118281511466 +2024-11-14,8,-0.002505484503007436,1.3955066256961897 +2024-11-15,8,-0.012929109483109224,1.3774639677481593 +2024-11-18,8,0.0033535832522074284,1.3820834078409185 +2024-11-19,8,0.006423150247863669,1.3909607372245603 +2024-11-20,8,-0.0013540058764037466,1.3890773682125113 +2024-11-21,8,-0.004443719191353492,1.3829046984531106 +2024-11-22,8,-0.0007796129508938088,1.3818265680403448 +2024-11-25,8,0.0019261897000080832,1.3844882281429014 +2024-11-26,8,0.006390899423454996,1.39333635316192 +2024-11-27,8,-0.003066833551169774,1.3890632224859785 +2024-11-29,8,0.004838440238611893,1.3957841218756306 +2024-12-02,8,0.008244519641721093,1.4072916914840368 +2024-12-03,8,0.005187604008424883,1.4145921635038023 +2024-12-04,8,0.007105527980576898,1.4246435877026835 +2024-12-05,8,0.0011482149203573839,1.4262793847262754 +2024-12-06,8,0.005432506061932615,1.4340276561298104 +2024-12-09,8,-0.0007259040838387636,1.432986689597888 +2024-12-10,8,0.0027802633090735513,1.436970769913368 +2024-12-11,8,0.011874439267398243,1.4540339920497307 +2024-12-12,8,-0.0028474462604824377,1.4498937083964545 +2024-12-13,8,-0.002132621588095166,1.4468016337734848 +2024-12-16,8,0.009315178560646401,1.4602788493339198 +2024-12-17,8,0.0007522783945863151,1.461377385562345 +2024-12-18,8,-0.03080156039435336,1.4163646817620044 +2024-12-19,8,0.001949145356984945,1.419125382405258 +2024-12-20,8,0.004787974549049225,1.4259201186181243 +2024-12-23,8,0.006085076407492306,1.434596951490896 +2024-12-24,8,0.008723105799529831,1.447111092478434 +2024-12-26,8,-0.0016703629591464484,1.4446938917117882 +2024-12-27,8,-0.00983638536172902,1.430483325863175 +2024-12-30,8,-0.007255768944505886,1.4201040693717435 +2024-12-31,8,-0.005998754839956889,1.4115852132123572 +2025-01-02,8,-0.002284912183566451,1.408359864960546 +2025-01-03,8,0.00933791507724819,1.4215110097777521 +2025-01-06,8,0.00948082037875893,1.434988100327883 +2025-01-07,8,-0.01114393249945174,1.4189966898003126 +2025-01-08,8,-0.00023603413574968649,1.4186617581430039 +2025-01-10,8,-0.007842307131720471,1.4075361769196197 +2025-01-13,8,-0.0011151015451914895,1.4059666311538237 +2025-01-14,8,7.605652520075438e-05,1.4060735640903375 +2025-01-15,8,-0.002921520072913986,1.4019656919488537 +2025-01-16,8,0.001400040221450061,1.403928500306675 +2025-01-17,8,0.0020677834253949303,1.4068315203900486 +2025-01-21,8,0.006558339214520994,1.4160579987184467 +2025-01-22,8,0.00920007696737278,1.4290858412969203 +2025-01-23,8,0.0018564229526219723,1.4317388290539708 +2025-01-24,8,-0.0009734750301473138,1.4303450670541944 +2025-01-27,8,-0.010632793036607347,1.4151365039852748 +2025-01-28,8,0.0025041152244861006,1.4186801688496302 +2025-01-29,8,-0.0001490939688191949,1.4184686521927712 +2025-01-30,8,-0.002290352733792951,1.4152198586374218 +2025-01-31,8,0.000769766475633493,1.4163092474402517 +2025-02-03,8,-0.005084265152339864,1.4091083556885546 +2025-02-04,8,0.0030470980233725355,1.413402046973891 +2025-02-05,8,-0.004025487449450984,1.4077124147727693 +2025-02-06,8,0.0029506041961038865,1.4118660169307053 +2025-02-07,8,-0.001961902568491814,1.4090960733657227 +2025-02-10,8,0.0023937171174793466,1.412469050756711 +2025-02-11,8,0.002097910301211493,1.415432284128436 +2025-02-12,8,0.00024392094512414302,1.4157775377089397 +2025-02-13,8,0.0001267991863035155,1.415957057148708 +2025-02-14,8,0.0018416107170959593,1.4185646988401006 +2025-02-18,8,-0.004909887780198852,1.4115997053598441 +2025-02-19,8,-0.0033229365683762222,1.4069090490789948 +2025-02-20,8,-0.0020140128683240645,1.4040755161495881 +2025-02-21,8,-0.004183577751307492,1.398201457059069 +2025-02-24,8,-6.455910076897146e-05,1.3981111904303074 +2025-02-25,8,0.0065183591683721015,1.4072245813268525 +2025-02-26,8,-0.00402366098183465,1.4015623866862892 +2025-02-27,8,0.005289973458195922,1.4089766145118654 +2025-02-28,8,0.0010147436645547405,1.410406364604947 +2025-03-03,8,0.00013068764317281057,1.4105906872886531 +2025-03-04,8,0.000701960632320271,1.4115808664194471 +2025-03-05,8,-0.0020113343190180004,1.4087417053787485 +2025-03-06,8,-0.0039337227334988525,1.4032001061066721 +2025-03-07,8,-0.0016429875047215396,1.4008946658657149 +2025-03-10,8,0.008338685860278423,1.412576286407709 +2025-03-11,8,0.004859752693107947,1.4194410578197993 +2025-03-12,8,0.00812439457357987,1.4309731570474669 +2025-03-13,8,-0.006701176578225235,1.4213839532433914 +2025-03-14,8,0.007288995310048241,1.4317444142123605 +2025-03-17,8,-0.003590854190391447,1.4266032287830166 +2025-03-18,8,-0.004817164832319559,1.4197310458796495 +2025-03-19,8,0.0027368080057154666,1.4236165771719758 +2025-03-20,8,-6.258957021311486e-05,1.4235274736222623 +2025-03-21,8,0.003331432502295273,1.4282698593157979 +2025-03-24,8,0.005528713516907016,1.436166354192788 +2025-03-25,8,-0.0020883401616160306,1.4331671503165655 +2025-03-26,8,0.005565699543397075,1.441143728070694 +2025-03-27,8,0.001246221118040387,1.4429397118187473 +2025-03-28,8,0.006018787303535755,1.4516244590360095 +2025-03-31,8,0.001564216122673772,1.4538951134189013 +2025-04-01,8,-0.001934741297496267,1.4510822025007417 +2025-04-02,8,-0.001480301257382776,1.448934163691814 +2025-04-03,8,0.008398391276979408,1.4611028797330807 +2025-04-04,8,-0.0018555073557860449,1.4583917925921759 +2025-04-07,8,0.0009084060142232615,1.4597166044676604 +2025-04-08,8,-0.0072393846575679426,1.44914915447688 +2025-04-09,8,0.04225095499712398,1.5103770901868028 +2025-04-10,8,-0.009155473892921357,1.496548872169131 +2025-04-11,8,0.0029761001641921696,1.501002751513315 +2025-04-14,8,0.0003604469073759252,1.5015437833130607 +2025-04-15,8,-0.0008190686575922884,1.5003139158621464 +2025-04-16,8,-0.0017427801262550086,1.4976991985864379 +2025-04-17,8,-0.0007458783767137246,1.4965820971393908 +2025-04-21,8,-0.0031757284535916816,1.4918293587903693 +2025-04-22,8,0.006467997793730604,1.5014785077916477 +2025-04-23,8,0.006774687962456413,1.5116505561642708 +2025-04-24,8,0.003563810729370635,1.5170377926353882 +2025-04-25,8,-0.0010019091319525195,1.5155178586174296 +2025-04-28,8,-0.00010728184643262552,1.5153552710632556 +2025-04-29,8,-0.0008760299762206019,1.5140277744211803 +2025-04-30,8,0.0016493277366180722,1.5165249024235432 +2025-05-01,8,-0.0056748837998796585,1.5079187998226657 +2025-05-02,8,-0.001968844923560703,1.504949941548493 +2025-05-05,8,-9.166405834730483e-05,1.5048119917292413 +2025-05-06,8,0.001285785126022876,1.5067468566056677 +2025-05-07,8,0.0011635256271576666,1.5084999951869675 +2025-05-08,8,-0.0005677599537804661,1.5076435292994224 +2025-05-09,8,-0.0004472516145641334,1.506969233296756 +2025-05-12,8,-0.00874063394667892,1.4937973668596016 +2025-05-13,8,-0.0012158684541006993,1.4919811057644183 +2025-05-14,8,0.0007988610187794034,1.493172991310569 +2025-05-15,8,0.003533923092359932,1.4984497498254494 +2025-05-16,8,0.00044996123686159135,1.499123994128256 +2025-05-19,8,0.0007772911210500264,1.5002892498982447 +2025-05-20,8,0.0005092518976902502,1.5010532750458399 +2025-05-21,8,0.004168551367173089,1.5073104927277317 +2025-05-22,8,-0.0010388433669897465,1.5057446332203674 +2025-05-23,8,0.0030792207544920597,1.5103811533459446 +2025-05-27,8,-0.00617448107350037,1.5010553335008383 +2025-05-28,8,-0.00018219795450780205,1.5007818442894714 +2025-05-29,8,-0.00141538885538717,1.4986576543926966 +2025-05-30,8,0.0031006106704961982,1.5033044083073275 +2025-06-02,8,0.0010243868652646112,1.504844373597692 +2025-06-03,8,-0.0019831763455435392,1.5018600018322488 +2025-06-04,8,0.002693224186591125,1.505904847514057 +2025-06-05,8,0.006106954486173127,1.5151013398783328 +2025-06-06,8,0.0009736297714003829,1.5165764876495271 +2025-06-09,8,0.0023701523720414284,1.520171005009112 +2025-06-10,8,0.000627264813132279,1.5211245547904981 +2025-06-11,8,-0.0018718961077360667,1.518277167657004 +2025-06-12,8,0.003262234922280096,1.5232301444550351 +2025-06-13,8,-0.00485897072724799,1.5158288137722664 +2025-06-16,8,0.008462160432790298,1.5286560003830536 +2025-06-17,8,-0.003077022246564644,1.5239522918625303 +2025-06-18,8,-0.0010330593420813288,1.5223779587105355 +2025-06-20,8,-0.009641194549910418,1.5077004166321117 +2025-06-23,8,0.009092038909429733,1.5214084874838945 +2025-06-24,8,0.002319204676484099,1.5249369451629098 +2025-06-25,8,0.0009654296124789986,1.5264091644469333 +2025-06-26,8,0.009130738912532323,1.5403464080011948 +2025-06-27,8,0.006692841238711761,1.5506557019625666 +2025-06-30,8,0.0013990370193506536,1.5528251266938793 +2025-07-01,8,-0.006026632865544344,1.5434668197509027 +2025-07-02,8,0.005966020640784364,1.5526751746559024 +2025-07-03,8,0.007535147853565113,1.5643748116654945 +2025-07-07,8,-0.006595420523446705,1.5540571019262728 +2025-07-08,8,-0.0021800810525529684,1.550669131483778 +2025-07-09,8,0.008123676604006754,1.563266266027768 +2025-07-10,8,0.0022652004812821116,1.5668073775259463 +2025-07-11,8,0.0010125769365143405,1.5683938905403896 +2025-07-14,8,0.0001528596242744941,1.5686336346412122 +2025-07-15,8,0.0016670384764060873,1.5712486072655438 +2025-07-16,8,0.000944089840215693,1.5727320071121165 +2025-07-17,8,0.0038864996505645014,1.5788444295081894 +2025-07-18,8,0.0025815231386864534,1.5829202529353512 +2025-07-21,8,0.004933874199477132,1.5907301823311386 +2025-07-22,8,-0.0028809809126991042,1.5861473190385884 +2025-07-23,8,0.004641615827677513,1.593509605539666 +2025-07-24,8,0.0020013080079755003,1.5966987090740183 +2025-07-25,8,0.0031057718657580254,1.6016576910027527 +2025-07-28,8,0.002948036040414893,1.6063794356002363 +2025-07-29,8,-0.005108299220012776,1.598173568782315 +2025-07-30,8,-0.0009053978614262746,1.5967265858509516 +2025-07-31,8,0.014321287834527869,1.619593766879966 +2025-08-01,8,-0.025864737487678285,1.5777033992629357 +2025-08-04,8,0.011994558652869882,1.596627255222227 +2025-08-05,8,-0.004292484246661999,1.5897737578813944 +2025-08-06,8,-0.005061992806935846,1.5817263345543433 +2025-08-07,8,0.001956227252332358,1.5848205507157302 +2025-08-08,8,0.009266127647025162,1.599505700236291 +2025-08-11,8,-0.000754611306786557,1.598298695149623 +2025-08-12,8,0.006884184281694267,1.6093016779042244 +2025-08-13,8,-0.0011690146405954197,1.6074203806816196 +2025-08-14,8,0.0018378342059195084,1.6103745528405284 +2025-08-15,8,-0.0018422684860091142,1.6074078105511593 +2025-08-18,8,-0.000541974798334883,1.606536636027194 +2025-08-19,8,-0.008074301071394402,1.5935649755456853 +2025-08-20,8,-0.0028042469660934494,1.5890962257977386 +2025-08-21,8,-0.0018402145554093632,1.5861719477930794 +2025-08-22,8,0.012334061659601724,1.6057358903998897 +2025-08-25,8,0.001370882639364402,1.607937165855443 +2025-08-26,8,0.0009196090641804765,1.6094158394477966 +2025-08-27,8,0.00032926176192857656,1.609945758542769 +2025-08-28,8,0.0016489215405590474,1.6126004327831618 +2025-08-29,8,-0.007292989855515588,1.600839754185874 +2025-09-02,8,-0.0069120451480432134,1.5897746775301589 +2025-09-03,8,0.013876292712210917,1.6118348563020282 +2025-09-04,8,0.007925924285664012,1.624610137334072 +2025-09-05,8,-0.00033352311602867935,1.6240682922987366 +2025-09-08,8,0.0003119267438497981,1.6245748826329431 +2025-09-09,8,0.0015736612762587594,1.6271314132161252 +2025-09-10,8,-0.008854411865997471,1.6127241215234072 +2025-09-11,8,0.005746362931713679,1.6219914196344096 +2025-09-12,8,0.0074713090981302095,1.6341098188850134 +2025-09-15,8,0.0044802525556184615,1.6414310435772341 +2025-09-16,8,0.0012962742717696051,1.6435587884079075 +2025-09-17,8,-0.0018689288836368943,1.6404870939162968 +2025-09-18,8,0.0017031164361247454,1.6432810344491962 +2025-09-19,8,0.006371400098004164,1.6537510353931342 +2025-09-22,8,0.004145992415454048,1.6606074746429236 +2025-09-23,8,-0.009148222229232176,1.645415868429366 +2025-09-24,8,0.001620923180211342,1.6480829611515908 +2025-09-25,8,-0.0031178748980590157,1.6429444446570975 +2025-09-26,8,0.002385749679477617,1.646864098839338 +2025-09-29,8,0.002229820509889653,1.6505363101839308 +2025-09-30,8,0.0014801026901907278,1.6529792734168915 +2025-10-01,8,0.0014177987981047065,1.6553228654440342 +2025-10-02,8,0.00035237355601085846,1.6559061574484768 +2025-10-03,8,-0.0037589263710674733,1.6496817281252307 +2025-10-06,8,0.008101396315881308,1.6630464535998413 +2025-10-07,8,-0.005746679031354413,1.6534894594167708 +2025-10-08,8,0.005852559188761964,1.6631666043460014 +2025-10-09,8,0.0002305100988561561,1.6635499810443835 +2025-10-10,8,-0.02947204178449122,1.6145217664924538 +2025-10-13,8,0.010590411690585376,1.6316202166830198 +2025-10-14,8,-0.004642322511343171,1.6240457094211496 +2025-10-15,8,0.004764705989576404,1.6317838097401742 +2025-10-16,8,-0.0020288368387187273,1.6284731866341486 +2025-10-17,8,0.005553260729594239,1.6375165228306814 +2025-10-20,8,0.007335810130050308,1.6495290331269874 +2025-10-21,8,-0.004145369041247737,1.6426911265404234 +2025-10-22,8,-0.0028087122982033068,1.6380772797711598 +2025-10-23,8,0.004095307621356924,1.6447857101393784 +2025-10-24,8,0.006527893668703975,1.655522696362972 +2025-10-27,8,0.013515230374630233,1.6778974669947464 +2025-10-28,8,0.006621915998674833,1.689008363075575 +2025-10-29,8,0.003903035761930107,1.6956006231188578 diff --git a/ml_engine/walk_forward_reports/pnl_equity_curve_crypto_specialist.png b/ml_engine/walk_forward_reports/pnl_equity_curve_crypto_specialist.png new file mode 100644 index 0000000000000000000000000000000000000000..bc16cfa3641d0bd63ae7889fdcdeefcabdc49628 --- /dev/null +++ b/ml_engine/walk_forward_reports/pnl_equity_curve_crypto_specialist.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31bd59c73bbc68226b0740b191b47e351ca141dda1c9f735b8c19dd18ee4d31e +size 81418 diff --git a/ml_engine/walk_forward_reports/pnl_equity_curve_equity_specialist.png b/ml_engine/walk_forward_reports/pnl_equity_curve_equity_specialist.png new file mode 100644 index 0000000000000000000000000000000000000000..bdc815905c33df1649da49c0c127ee3d1c1860cc --- /dev/null +++ b/ml_engine/walk_forward_reports/pnl_equity_curve_equity_specialist.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69deff5138dc612f76580736155ba338b6cd26981208ede21fc7f4471cd7f229 +size 80523 diff --git a/ml_engine/walk_forward_reports/pnl_predictions_crypto_specialist.csv b/ml_engine/walk_forward_reports/pnl_predictions_crypto_specialist.csv new file mode 100644 index 0000000000000000000000000000000000000000..eb733d04ea07009b3ed925ca5bb540c03fb9b792 --- /dev/null +++ b/ml_engine/walk_forward_reports/pnl_predictions_crypto_specialist.csv @@ -0,0 +1,467 @@ +fold,ticker,date,r_hat,r_true +1,BTC-USD,2025-10-31,0.0010318111162632704,0.011480960994958878 +1,BTC-USD,2025-11-01,0.0010288616176694632,0.004624824970960617 +1,BTC-USD,2025-11-02,0.0009871638612821698,0.005216141231358051 +1,BTC-USD,2025-11-03,0.0009776527294889092,-0.03768718242645264 +1,BTC-USD,2025-11-04,0.0009752584737725556,-0.047640856355428696 +1,BTC-USD,2025-11-05,0.0009714155457913876,0.022400060668587685 +1,BTC-USD,2025-11-06,0.0009610412525944412,-0.025251181796193123 +1,BTC-USD,2025-11-07,0.0008727554813958704,0.020238926634192467 +1,BTC-USD,2025-11-08,0.0008645885973237455,-0.01060321182012558 +1,BTC-USD,2025-11-09,0.000842146691866219,0.02355184033513069 +1,BTC-USD,2025-11-10,0.0008134759264066815,0.012120270170271397 +1,BTC-USD,2025-11-11,0.0007975406479090452,-0.028702545911073685 +1,BTC-USD,2025-11-12,0.0007374198758043349,-0.013039146549999714 +1,BTC-USD,2025-11-13,0.0007070199935697019,-0.019524743780493736 +1,BTC-USD,2025-11-14,0.0006870823563076556,-0.054622869938611984 +1,BTC-USD,2025-11-15,0.0006654871394857764,0.012123105116188526 +1,BTC-USD,2025-11-16,0.0006589036202058196,-0.014463938772678375 +1,BTC-USD,2025-11-17,0.0006382705178111792,-0.022368382662534714 +1,BTC-USD,2025-11-18,0.0005481869447976351,0.009241173975169659 +1,BTC-USD,2025-11-19,0.0005095679662190378,-0.01608237810432911 +1,BTC-USD,2025-11-20,0.00044808650272898376,-0.05429914593696594 +1,BTC-USD,2025-11-21,0.0003468370414339006,-0.01795049011707306 +1,BTC-USD,2025-11-22,0.00030377585790120065,-0.005211872514337301 +1,BTC-USD,2025-11-23,0.00028792029479518533,0.025158585980534554 +1,BTC-USD,2025-11-24,0.00020158349070698023,0.01674235798418522 +1,BTC-USD,2025-11-25,0.00022914375585969537,-0.010576477274298668 +1,BTC-USD,2025-11-26,0.00016067741671577096,0.03572258725762367 +1,BTC-USD,2025-11-27,0.00017725315410643816,0.0084378058090806 +1,BTC-USD,2025-11-28,0.0001275589020224288,-0.004018666688352823 +1,BTC-USD,2025-11-29,9.890458750305697e-05,-0.0007427786476910114 +1,BTC-USD,2025-11-30,8.486605656798929e-05,-0.0050477925688028336 +1,BTC-USD,2025-12-01,2.47645475610625e-05,-0.04610183835029602 +1,BTC-USD,2025-12-02,-3.0191056794137694e-05,0.056620992720127106 +1,BTC-USD,2025-12-03,-0.00012289152073208243,0.02355826273560524 +1,BTC-USD,2025-12-04,-0.00016256335948128253,-0.01493197213858366 +1,BTC-USD,2025-12-05,-0.00021484430180862546,-0.030343057587742805 +1,BTC-USD,2025-12-06,-0.0003314352943561971,-0.001291646040044725 +1,BTC-USD,2025-12-07,-0.0003686303971335292,0.012614572420716286 +1,BTC-USD,2025-12-08,-0.0004350295930635184,0.002591195981949568 +1,BTC-USD,2025-12-09,-0.0005062695709057152,0.022381192073225975 +1,BTC-USD,2025-12-10,-0.00034548755502328277,-0.007262832950800657 +1,BTC-USD,2025-12-11,-0.0002460495743434876,0.005314969923347235 +1,BTC-USD,2025-12-12,-0.00024395494256168604,-0.024521419778466225 +1,BTC-USD,2025-12-13,-0.0002452743938192725,0.00031341874273493886 +1,BTC-USD,2025-12-14,-0.00020390376448631287,-0.023797670379281044 +1,BTC-USD,2025-12-15,-0.000209530713618733,-0.020108914002776146 +1,BTC-USD,2025-12-16,-0.00011046109284507111,0.016345737501978874 +1,BTC-USD,2025-12-17,-4.901538341073319e-05,-0.019544832408428192 +1,BTC-USD,2025-12-18,-9.327059160568751e-06,-0.007939728908240795 +1,BTC-USD,2025-12-19,-2.625741035444662e-05,0.030433155596256256 +1,BTC-USD,2025-12-20,1.8090267985826358e-05,0.002727355109527707 +1,BTC-USD,2025-12-21,2.8964836019440554e-05,0.003139028325676918 +1,BTC-USD,2025-12-22,8.284563227789477e-05,-0.0014875850174576044 +1,BTC-USD,2025-12-23,8.892065670806915e-05,-0.012234275229275227 +1,BTC-USD,2025-12-24,9.65020662988536e-05,0.0022620761301368475 +1,BTC-USD,2025-12-25,0.00011651116074062884,-0.004314858000725508 +1,BTC-USD,2025-12-26,6.577783642569557e-05,0.0007641682750545442 +1,BTC-USD,2025-12-27,3.263734106440097e-05,0.005719219334423542 +1,BTC-USD,2025-12-28,6.902700988575816e-05,0.00038351252442225814 +1,ETH-USD,2025-10-31,-0.0002641662722453475,0.011162718757987022 +1,ETH-USD,2025-11-01,-0.00019466987578198314,0.007021586876362562 +1,ETH-USD,2025-11-02,-0.0001515919720986858,0.009473173879086971 +1,ETH-USD,2025-11-03,-0.0001092322709155269,-0.08223447948694229 +1,ETH-USD,2025-11-04,2.1027760794822825e-06,-0.08990500867366791 +1,ETH-USD,2025-11-05,0.00010504475358175114,0.039481665939092636 +1,ETH-USD,2025-11-06,0.00016143516404554248,-0.033521365374326706 +1,ETH-USD,2025-11-07,0.00011892995098605752,0.03647448122501373 +1,ETH-USD,2025-11-08,0.00021899442072026432,-0.010218548588454723 +1,ETH-USD,2025-11-09,0.00023567261814605445,0.05220874398946762 +1,ETH-USD,2025-11-10,0.00029802924836985767,-0.003960630390793085 +1,ETH-USD,2025-11-11,0.00033650692785158753,-0.04387399181723595 +1,ETH-USD,2025-11-12,0.00022351017105393112,-0.000640851678326726 +1,ETH-USD,2025-11-13,0.00018991436809301376,-0.05428392440080643 +1,ETH-USD,2025-11-14,0.00013161344395484775,-0.040712811052799225 +1,ETH-USD,2025-11-15,0.00012889555364381522,0.020045815035700798 +1,ETH-USD,2025-11-16,0.00014425470726564527,-0.023576200008392334 +1,ETH-USD,2025-11-17,9.452523954678327e-05,-0.022333534434437752 +1,ETH-USD,2025-11-18,9.603973921912257e-06,0.03202873095870018 +1,ETH-USD,2025-11-19,-2.574741665739566e-05,-0.032514218240976334 +1,ETH-USD,2025-11-20,-0.00012947329378221184,-0.06536849588155746 +1,ETH-USD,2025-11-21,-0.00024922960437834263,-0.023611150681972504 +1,ETH-USD,2025-11-22,-0.0002767230325844139,0.0006897153216414154 +1,ETH-USD,2025-11-23,-0.0002915705263148993,0.012234617955982685 +1,ETH-USD,2025-11-24,-0.0003898277645930648,0.052506718784570694 +1,ETH-USD,2025-11-25,-0.0002927111927419901,0.001767285168170929 +1,ETH-USD,2025-11-26,-0.00040026279748417437,0.023348428308963776 +1,ETH-USD,2025-11-27,-0.0003708025033120066,-0.0043922602199018 +1,ETH-USD,2025-11-28,-0.00040155835449695587,0.00587488291785121 +1,ETH-USD,2025-11-29,-0.00037919089663773775,-0.013485997915267944 +1,ETH-USD,2025-11-30,-0.00038830688572488725,0.00014280098548624665 +1,ETH-USD,2025-12-01,-0.0004395103023853153,-0.06629277020692825 +1,ETH-USD,2025-12-02,-0.0005165876937098801,0.06823838502168655 +1,ETH-USD,2025-12-03,-0.0006210458814166486,0.06258822977542877 +1,ETH-USD,2025-12-04,-0.0006508582155220211,-0.018102416768670082 +1,ETH-USD,2025-12-05,-0.0007231100462377071,-0.03568750619888306 +1,ETH-USD,2025-12-06,-0.0009044484468176961,0.005202265921980143 +1,ETH-USD,2025-12-07,-0.0009719498339109123,0.006914380006492138 +1,ETH-USD,2025-12-08,-0.0011162376031279564,0.020657401531934738 +1,ETH-USD,2025-12-09,-0.0012257606722414494,0.06080292537808418 +1,ETH-USD,2025-12-10,-0.0009668145212344825,0.0012864345917478204 +1,ETH-USD,2025-12-11,-0.0008040835964493454,-0.026922453194856644 +1,ETH-USD,2025-12-12,-0.0008624079637229443,-0.048381123691797256 +1,ETH-USD,2025-12-13,-0.0009236192563548684,0.010489823296666145 +1,ETH-USD,2025-12-14,-0.0009017634438350797,-0.01816399395465851 +1,ETH-USD,2025-12-15,-0.0009101846953853965,-0.032007768750190735 +1,ETH-USD,2025-12-16,-0.0008074773941189051,-7.412722311528341e-07 +1,ETH-USD,2025-12-17,-0.0007780547020956874,-0.0458281934261322 +1,ETH-USD,2025-12-18,-0.0007782518514432013,-0.0015320294769480824 +1,ETH-USD,2025-12-19,-0.0008601688896305859,0.052001576870679855 +1,ETH-USD,2025-12-20,-0.0008344169473275542,-0.00013036021846346557 +1,ETH-USD,2025-12-21,-0.0008627600036561489,0.00803833082318306 +1,ETH-USD,2025-12-22,-0.0008415895281359553,0.0014847515849396586 +1,ETH-USD,2025-12-23,-0.0008214799454435706,-0.014306326396763325 +1,ETH-USD,2025-12-24,-0.0008620324078947306,-0.006019159685820341 +1,ETH-USD,2025-12-25,-0.0008388857240788639,-0.014365014620125294 +1,ETH-USD,2025-12-26,-0.0009442451992072165,0.007605038583278656 +1,ETH-USD,2025-12-27,-0.0010096670594066381,0.007577038370072842 +1,ETH-USD,2025-12-28,-0.0009333172929473221,0.0001932732411660254 +2,BTC-USD,2025-12-29,-0.0003131813136860728,-0.007974889129400253 +2,BTC-USD,2025-12-30,-0.000285519752651453,0.014718097634613514 +2,BTC-USD,2025-12-31,-0.00028829844086430967,-0.010473099537193775 +2,BTC-USD,2026-01-01,-0.0002884030691348016,0.013880733400583267 +2,BTC-USD,2026-01-02,-0.00032487933640368283,0.013574570417404175 +2,BTC-USD,2026-01-03,-0.0002821720845531672,0.007294408977031708 +2,BTC-USD,2026-01-04,-0.0003380306588951498,0.008903689682483673 +2,BTC-USD,2026-01-05,-0.00037049315869808197,0.026651497930288315 +2,BTC-USD,2026-01-06,-0.00035304081393405795,-0.0016366097843274474 +2,BTC-USD,2026-01-07,-0.0003958602319471538,-0.02616896666586399 +2,BTC-USD,2026-01-08,-0.0003721844404935837,-0.0030814670026302338 +2,BTC-USD,2026-01-09,-0.0004126375715713948,-0.0056629301980137825 +2,BTC-USD,2026-01-10,-0.00045481001143343747,-0.0013980466173961759 +2,BTC-USD,2026-01-11,-0.00044885053648613393,0.004865110851824284 +2,BTC-USD,2026-01-12,-0.00046069631935097277,0.0040163807570934296 +2,BTC-USD,2026-01-13,-0.00047068597632460296,0.0442802868783474 +2,BTC-USD,2026-01-14,-0.00037793806404806674,0.01672379858791828 +2,BTC-USD,2026-01-15,-0.0003425614850129932,-0.014320037327706814 +2,BTC-USD,2026-01-16,-0.00025854894192889333,-0.00027287856210023165 +2,BTC-USD,2026-01-17,-0.00018400770204607397,-0.004461071919649839 +2,BTC-USD,2026-01-18,-0.00014548930630553514,-0.015529992990195751 +2,BTC-USD,2026-01-19,-0.00016341969603672624,-0.011610285378992558 +2,BTC-USD,2026-01-20,-0.00013029039837419987,-0.04692425578832626 +2,BTC-USD,2026-01-21,-9.892282832879573e-05,0.011999327689409256 +2,BTC-USD,2026-01-22,-1.6486681488459e-05,0.000956077768933028 +2,BTC-USD,2026-01-23,1.3433085769065656e-05,0.0004629013710655272 +2,BTC-USD,2026-01-24,2.0139370462857187e-05,-0.004402117803692818 +2,BTC-USD,2026-01-25,4.221827111905441e-05,-0.028900837525725365 +2,BTC-USD,2026-01-26,5.466654693009332e-05,0.019388940185308456 +2,BTC-USD,2026-01-27,2.309311821591109e-05,0.009420276619493961 +2,BTC-USD,2026-01-28,2.4914332243497483e-05,0.0009198645129799843 +2,BTC-USD,2026-01-29,-5.513569703907706e-06,-0.053227949887514114 +2,BTC-USD,2026-01-30,-3.990259938291274e-05,-0.005132847465574741 +2,BTC-USD,2026-01-31,8.204700861824676e-06,-0.06770692020654678 +2,BTC-USD,2026-02-01,-4.239676854922436e-05,-0.021166842430830002 +2,BTC-USD,2026-02-02,-0.00011965924204559997,0.0220269076526165 +2,BTC-USD,2026-02-03,-0.00017469029990024865,-0.039600469172000885 +2,BTC-USD,2026-02-04,-0.00028404733166098595,-0.03517061471939087 +2,BTC-USD,2026-02-05,-0.0003562516940291971,-0.15233440697193146 +2,BTC-USD,2026-02-06,-0.0004656518285628408,0.11800318956375122 +2,BTC-USD,2026-02-07,-0.0005800833459943533,-0.01821340247988701 +2,BTC-USD,2026-02-08,-0.0006717828800901771,0.014085236005485058 +2,BTC-USD,2026-02-09,-0.0006882052985019982,-0.002050715498626232 +2,BTC-USD,2026-02-10,-0.000865940295625478,-0.019103238359093666 +2,BTC-USD,2026-02-11,-0.000927644781768322,-0.02654322050511837 +2,BTC-USD,2026-02-12,-0.0011065233265981078,-0.011562367901206017 +2,BTC-USD,2026-02-13,-0.0011814064346253872,0.03903377056121826 +2,BTC-USD,2026-02-14,-0.0012261845404282212,0.013125933706760406 +2,BTC-USD,2026-02-15,-0.001337017398327589,-0.01413804106414318 +2,BTC-USD,2026-02-16,-0.0014165155589580536,0.0007987824501469731 +2,BTC-USD,2026-02-17,-0.0014694135170429945,-0.019788872450590134 +2,BTC-USD,2026-02-18,-0.0015704968245700002,-0.015963632613420486 +2,BTC-USD,2026-02-19,-0.0015220892382785678,0.007980125956237316 +2,BTC-USD,2026-02-20,-0.0015073950635269284,0.015528994612395763 +2,BTC-USD,2026-02-21,-0.0014351456193253398,-2.4354972993023694e-05 +2,BTC-USD,2026-02-22,-0.0015107988147065043,-0.005076923407614231 +2,BTC-USD,2026-02-23,-0.0014215325936675072,-0.046012673527002335 +2,BTC-USD,2026-02-24,-0.0014037595828995109,-0.008340510539710522 +2,ETH-USD,2025-12-29,-0.002487252466380596,-0.004769525025039911 +2,ETH-USD,2025-12-30,-0.0024183052591979504,0.0124887153506279 +2,ETH-USD,2025-12-31,-0.0023916871286928654,-0.0014748454559594393 +2,ETH-USD,2026-01-01,-0.0023613267112523317,0.011179695837199688 +2,ETH-USD,2026-01-02,-0.00232877628877759,0.0405057929456234 +2,ETH-USD,2026-01-03,-0.0022683609277009964,0.0004783333570230752 +2,ETH-USD,2026-01-04,-0.002349539427086711,0.004721198230981827 +2,ETH-USD,2026-01-05,-0.00247591664083302,0.026834359392523766 +2,ETH-USD,2026-01-06,-0.0025373511016368866,0.021410072222352028 +2,ETH-USD,2026-01-07,-0.0026053551118820906,-0.039957962930202484 +2,ETH-USD,2026-01-08,-0.00260705198161304,-0.01992066204547882 +2,ETH-USD,2026-01-09,-0.002672758884727955,-0.006896412465721369 +2,ETH-USD,2026-01-10,-0.0027277497574687004,-0.00021121694589965045 +2,ETH-USD,2026-01-11,-0.002735696267336607,0.011768432334065437 +2,ETH-USD,2026-01-12,-0.0027653088327497244,-0.008552349172532558 +2,ETH-USD,2026-01-13,-0.0028072071727365255,0.07167244702577591 +2,ETH-USD,2026-01-14,-0.0027308757416903973,0.009773355908691883 +2,ETH-USD,2026-01-15,-0.002759764436632395,-0.011277795769274235 +2,ETH-USD,2026-01-16,-0.002683883300051093,-0.006538811139762402 +2,ETH-USD,2026-01-17,-0.0026688766665756702,0.004052512347698212 +2,ETH-USD,2026-01-18,-0.0026646137703210115,-0.00840868428349495 +2,ETH-USD,2026-01-19,-0.0027055665850639343,-0.02923518419265747 +2,ETH-USD,2026-01-20,-0.002666344167664647,-0.08204732090234756 +2,ETH-USD,2026-01-21,-0.002592372242361307,0.014640673995018005 +2,ETH-USD,2026-01-22,-0.0024825967848300934,-0.009873623959720135 +2,ETH-USD,2026-01-23,-0.0024286010302603245,0.0012275504413992167 +2,ETH-USD,2026-01-24,-0.002390775131061673,-0.0015302026877179742 +2,ETH-USD,2026-01-25,-0.0023384380619972944,-0.04609544575214386 +2,ETH-USD,2026-01-26,-0.0023151987697929144,0.03850972652435303 +2,ETH-USD,2026-01-27,-0.0023518067318946123,0.032196175307035446 +2,ETH-USD,2026-01-28,-0.0024257334880530834,-0.005176321137696505 +2,ETH-USD,2026-01-29,-0.0025140447542071342,-0.06470236927270889 +2,ETH-USD,2026-01-30,-0.0025780871510505676,-0.041978869587183 +2,ETH-USD,2026-01-31,-0.00248143682256341,-0.10004843771457672 +2,ETH-USD,2026-02-01,-0.002656801138073206,-0.07519978284835815 +2,ETH-USD,2026-02-02,-0.002725011669099331,0.03312814608216286 +2,ETH-USD,2026-02-03,-0.002832957310602069,-0.05110473558306694 +2,ETH-USD,2026-02-04,-0.0030534209217876196,-0.03846435248851776 +2,ETH-USD,2026-02-05,-0.0031765508465468884,-0.16268108785152435 +2,ETH-USD,2026-02-06,-0.003372474107891321,0.12458793073892593 +2,ETH-USD,2026-02-07,-0.003543083555996418,0.013078073039650917 +2,ETH-USD,2026-02-08,-0.003665658412501216,-0.0008548665209673345 +2,ETH-USD,2026-02-09,-0.003775274381041527,0.0070627774111926556 +2,ETH-USD,2026-02-10,-0.004025259520858526,-0.04078608751296997 +2,ETH-USD,2026-02-11,-0.004148891195654869,-0.03984048590064049 +2,ETH-USD,2026-02-12,-0.004297406412661076,0.003251056419685483 +2,ETH-USD,2026-02-13,-0.004361444152891636,0.0508619099855423 +2,ETH-USD,2026-02-14,-0.004415853414684534,0.01813187263906002 +2,ETH-USD,2026-02-15,-0.004474286455661058,-0.05923015996813774 +2,ETH-USD,2026-02-16,-0.0046249870210886,0.016082623973488808 +2,ETH-USD,2026-02-17,-0.004616014193743467,-0.002868787618353963 +2,ETH-USD,2026-02-18,-0.004617693834006786,-0.019371405243873596 +2,ETH-USD,2026-02-19,-0.0045813145115971565,-0.0029589012265205383 +2,ETH-USD,2026-02-20,-0.004558256361633539,0.010630736127495766 +2,ETH-USD,2026-02-21,-0.004586829803884029,0.002391647780314088 +2,ETH-USD,2026-02-22,-0.004572642967104912,-0.008104381151497364 +2,ETH-USD,2026-02-23,-0.004512000363320112,-0.05366870015859604 +2,ETH-USD,2026-02-24,-0.004529974889010191,-0.001366236712783575 +3,BTC-USD,2026-02-25,-0.0031768623739480972,0.05878816545009613 +3,BTC-USD,2026-02-26,-0.003168127965182066,-0.00747861061245203 +3,BTC-USD,2026-02-27,-0.003033250570297241,-0.023580346256494522 +3,BTC-USD,2026-02-28,-0.003028638893738389,0.01676863804459572 +3,BTC-USD,2026-03-01,-0.0028806787449866533,-0.018952127546072006 +3,BTC-USD,2026-03-02,-0.002844645408913493,0.045173998922109604 +3,BTC-USD,2026-03-03,-0.002710541943088174,-0.007035921793431044 +3,BTC-USD,2026-03-04,-0.002684555482119322,0.06267011165618896 +3,BTC-USD,2026-03-05,-0.0026917289942502975,-0.026047183200716972 +3,BTC-USD,2026-03-06,-0.0026904349215328693,-0.03892676159739494 +3,BTC-USD,2026-03-07,-0.002763413591310382,-0.012760002166032791 +3,BTC-USD,2026-03-08,-0.0028232091572135687,-0.01955615170300007 +3,BTC-USD,2026-03-09,-0.002834184793755412,0.036210883408784866 +3,BTC-USD,2026-03-10,-0.0027634582947939634,0.02204306237399578 +3,BTC-USD,2026-03-11,-0.002692820504307747,0.003967140801250935 +3,BTC-USD,2026-03-12,-0.0025824105832725763,0.004102088510990143 +3,BTC-USD,2026-03-13,-0.00250331312417984,0.006712861359119415 +3,BTC-USD,2026-03-14,-0.0024439061526209116,0.003465390531346202 +3,BTC-USD,2026-03-15,-0.0024179471656680107,0.021879198029637337 +3,BTC-USD,2026-03-16,-0.002424438949674368,0.028056805953383446 +3,BTC-USD,2026-03-17,-0.002418196527287364,-0.012617278844118118 +3,BTC-USD,2026-03-18,-0.0024307214189320803,-0.03688417375087738 +3,BTC-USD,2026-03-19,-0.002484646625816822,-0.018884161487221718 +3,BTC-USD,2026-03-20,-0.002509433776140213,0.008684431202709675 +3,BTC-USD,2026-03-21,-0.002524947514757514,-0.026016104966402054 +3,BTC-USD,2026-03-22,-0.002463036449626088,-0.012688119895756245 +3,BTC-USD,2026-03-23,-0.0025392919778823853,0.04425119236111641 +3,BTC-USD,2026-03-24,-0.00243668002076447,-0.005613991525024176 +3,BTC-USD,2026-03-25,-0.002472249325364828,0.011168924160301685 +3,BTC-USD,2026-03-26,-0.0024560813326388597,-0.035952918231487274 +3,BTC-USD,2026-03-27,-0.0025036095175892115,-0.03631347045302391 +3,BTC-USD,2026-03-28,-0.002537761814892292,-0.0002816215856000781 +3,BTC-USD,2026-03-29,-0.002586920512840152,-0.005515409633517265 +3,BTC-USD,2026-03-30,-0.002611471340060234,0.011105181649327278 +3,BTC-USD,2026-03-31,-0.002594668185338378,0.0228562094271183 +3,BTC-USD,2026-04-01,-0.00256944028660655,-0.00227064429782331 +3,BTC-USD,2026-04-02,-0.0025522673968225718,-0.01763414964079857 +3,BTC-USD,2026-04-03,-0.002453729510307312,0.0006356501835398376 +3,BTC-USD,2026-04-04,-0.002503335243090987,0.00535554438829422 +3,BTC-USD,2026-04-05,-0.0025250751059502363,0.024824826046824455 +3,BTC-USD,2026-04-06,-0.0025355021934956312,-0.0017711668042466044 +3,BTC-USD,2026-04-07,-0.002443242585286498,0.04376925155520439 +3,BTC-USD,2026-04-08,-0.0024075235705822706,-0.011426386423408985 +3,BTC-USD,2026-04-09,-0.0023908899165689945,0.009020473808050156 +3,BTC-USD,2026-04-10,-0.0023972406052052975,0.016736071556806564 +3,BTC-USD,2026-04-11,-0.0024354723282158375,0.0010302658192813396 +3,BTC-USD,2026-04-12,-0.002438379917293787,-0.032001957297325134 +3,BTC-USD,2026-04-13,-0.002466900972649455,0.05139225721359253 +3,BTC-USD,2026-04-14,-0.0024389263708144426,-0.004076670855283737 +3,BTC-USD,2026-04-15,-0.0024118993896991014,0.00836950447410345 +3,BTC-USD,2026-04-16,-0.0024157993029803038,0.004628724418580532 +3,BTC-USD,2026-04-17,-0.0023800113704055548,0.025937296450138092 +3,BTC-USD,2026-04-18,-0.002478775568306446,-0.018327444791793823 +3,BTC-USD,2026-04-19,-0.002607982372865081,-0.025002336129546165 +3,BTC-USD,2026-04-20,-0.00265513570047915,0.026932595297694206 +3,BTC-USD,2026-04-21,-0.0027216181624680758,0.0063097476959228516 +3,BTC-USD,2026-04-22,-0.0028098507318645716,0.023944951593875885 +3,BTC-USD,2026-04-23,-0.0028763532172888517,0.0008417038479819894 +3,ETH-USD,2026-02-25,-0.005561162251979113,0.10330529510974884 +3,ETH-USD,2026-02-26,-0.00551210530102253,-0.013640230521559715 +3,ETH-USD,2026-02-27,-0.00548836262896657,-0.048539888113737106 +3,ETH-USD,2026-02-28,-0.005362919997423887,0.017603302374482155 +3,ETH-USD,2026-03-01,-0.005233366508036852,-0.013311214745044708 +3,ETH-USD,2026-03-02,-0.0050326064229011536,0.04448278248310089 +3,ETH-USD,2026-03-03,-0.004948660731315613,-0.02219521626830101 +3,ETH-USD,2026-03-04,-0.004925948567688465,0.06998565047979355 +3,ETH-USD,2026-03-05,-0.004892485681921244,-0.026156065985560417 +3,ETH-USD,2026-03-06,-0.004884123802185059,-0.04585794731974602 +3,ETH-USD,2026-03-07,-0.004915414843708277,-0.00470886891707778 +3,ETH-USD,2026-03-08,-0.004975094459950924,-0.01682077720761299 +3,ETH-USD,2026-03-09,-0.004979460500180721,0.028673743829131126 +3,ETH-USD,2026-03-10,-0.00486685149371624,0.021927233785390854 +3,ETH-USD,2026-03-11,-0.004740593023598194,0.007069651037454605 +3,ETH-USD,2026-03-12,-0.00465536629781127,0.01045561395585537 +3,ETH-USD,2026-03-13,-0.0045707146637141705,0.009327310137450695 +3,ETH-USD,2026-03-14,-0.004466333892196417,0.0021592231933027506 +3,ETH-USD,2026-03-15,-0.004390775226056576,0.03761747106909752 +3,ETH-USD,2026-03-16,-0.004361976869404316,0.07674908638000488 +3,ETH-USD,2026-03-17,-0.004290275741368532,-0.01418782863765955 +3,ETH-USD,2026-03-18,-0.00426548020914197,-0.05060291290283203 +3,ETH-USD,2026-03-19,-0.00434137275442481,-0.03052360750734806 +3,ETH-USD,2026-03-20,-0.004402449354529381,0.004235958680510521 +3,ETH-USD,2026-03-21,-0.004444084130227566,-0.03306199237704277 +3,ETH-USD,2026-03-22,-0.004363304935395718,-0.011449567042291164 +3,ETH-USD,2026-03-23,-0.004447196144610643,0.04713979363441467 +3,ETH-USD,2026-03-24,-0.004402850288897753,0.0016520306235179305 +3,ETH-USD,2026-03-25,-0.004361170809715986,0.005697480868548155 +3,ETH-USD,2026-03-26,-0.004322761204093695,-0.05131370574235916 +3,ETH-USD,2026-03-27,-0.004377719014883041,-0.03372766822576523 +3,ETH-USD,2026-03-28,-0.004384159110486507,0.0007141664391383529 +3,ETH-USD,2026-03-29,-0.004410994239151478,-0.005098999477922916 +3,ETH-USD,2026-03-30,-0.004451661370694637,0.02044725976884365 +3,ETH-USD,2026-03-31,-0.004427026491612196,0.03934081643819809 +3,ETH-USD,2026-04-01,-0.004327109549194574,0.01603863574564457 +3,ETH-USD,2026-04-02,-0.004327281378209591,-0.03903857618570328 +3,ETH-USD,2026-04-03,-0.004318335559219122,-0.0016871461411938071 +3,ETH-USD,2026-04-04,-0.004305853042751551,0.005810685455799103 +3,ETH-USD,2026-04-05,-0.00426148297265172,0.020911358296871185 +3,ETH-USD,2026-04-06,-0.004167345352470875,-0.0005853459588252008 +3,ETH-USD,2026-04-07,-0.004055274184793234,0.06165560707449913 +3,ETH-USD,2026-04-08,-0.004007111303508282,-0.023227369412779808 +3,ETH-USD,2026-04-09,-0.004042738117277622,-0.0005440858076326549 +3,ETH-USD,2026-04-10,-0.004118933342397213,0.025261128321290016 +3,ETH-USD,2026-04-11,-0.00421228539198637,0.017765000462532043 +3,ETH-USD,2026-04-12,-0.004245129879564047,-0.04163060709834099 +3,ETH-USD,2026-04-13,-0.004305546637624502,0.07828538864850998 +3,ETH-USD,2026-04-14,-0.0042847865261137486,-0.020199241116642952 +3,ETH-USD,2026-04-15,-0.004314770456403494,0.015430748462677002 +3,ETH-USD,2026-04-16,-0.004416718613356352,-0.0045844619162380695 +3,ETH-USD,2026-04-17,-0.00448105251416564,0.030371753498911858 +3,ETH-USD,2026-04-18,-0.004570190329104662,-0.029326772317290306 +3,ETH-USD,2026-04-19,-0.004720595199614763,-0.03734544292092323 +3,ETH-USD,2026-04-20,-0.004895633552223444,0.021963324397802353 +3,ETH-USD,2026-04-21,-0.005088164936751127,0.005495407152920961 +3,ETH-USD,2026-04-22,-0.005266991909593344,0.020458653569221497 +3,ETH-USD,2026-04-23,-0.005402515642344952,-0.018937688320875168 +4,BTC-USD,2026-04-24,-0.002077592071145773,-0.010449855588376522 +4,BTC-USD,2026-04-25,-0.0020734965801239014,0.0020210985094308853 +4,BTC-USD,2026-04-26,-0.0020570934284478426,0.013381225056946278 +4,BTC-USD,2026-04-27,-0.002045250730589032,-0.016547994688153267 +4,BTC-USD,2026-04-28,-0.002010355470702052,-0.013218654319643974 +4,BTC-USD,2026-04-29,-0.002017606981098652,-0.007553459145128727 +4,BTC-USD,2026-04-30,-0.0021013503428548574,0.00694618746638298 +4,BTC-USD,2026-05-01,-0.0021678032353520393,0.024271510541439056 +4,BTC-USD,2026-05-02,-0.0021946674678474665,0.006098736543208361 +4,BTC-USD,2026-05-03,-0.0021850133780390024,-0.0015143369091674685 +4,BTC-USD,2026-05-04,-0.0021445832680910826,0.016287676990032196 +4,BTC-USD,2026-05-05,-0.002166162244975567,0.013675043359398842 +4,BTC-USD,2026-05-06,-0.002160934964194894,0.0061652478761971 +4,BTC-USD,2026-05-07,-0.0021285947877913713,-0.017561908811330795 +4,BTC-USD,2026-05-08,-0.00216150120832026,0.002206954872235656 +4,BTC-USD,2026-05-09,-0.002131399465724826,0.005938447080552578 +4,BTC-USD,2026-05-10,-0.0021553023252636194,0.018115146085619926 +4,BTC-USD,2026-05-11,-0.00218492210842669,-0.005011785309761763 +4,BTC-USD,2026-05-12,-0.002204399323090911,-0.01542274747043848 +4,BTC-USD,2026-05-13,-0.002233261475339532,-0.01502801850438118 +4,BTC-USD,2026-05-14,-0.002229230245575309,0.02213214337825775 +4,BTC-USD,2026-05-15,-0.002233662409707904,-0.02480277605354786 +4,BTC-USD,2026-05-16,-0.0022624824196100235,-0.01188639085739851 +4,BTC-USD,2026-05-17,-0.002282810630276799,-0.009026576764881611 +4,BTC-USD,2026-05-18,-0.0023703689221292734,-0.006155853625386953 +4,BTC-USD,2026-05-19,-0.0024877809919416904,-0.002644879976287484 +4,BTC-USD,2026-05-20,-0.0025928679388016462,0.009167734533548355 +4,BTC-USD,2026-05-21,-0.0026540241669863462,0.001050323247909546 +4,BTC-USD,2026-05-22,-0.0026678242720663548,-0.026806341484189034 +4,BTC-USD,2026-05-23,-0.002709857188165188,0.015577503480017185 +4,BTC-USD,2026-05-24,-0.002752775326371193,0.0040058474987745285 +4,BTC-USD,2026-05-25,-0.002741584088653326,0.003874017857015133 +4,BTC-USD,2026-05-26,-0.0028155988547950983,-0.01899654231965542 +4,BTC-USD,2026-05-27,-0.0028918511234223843,-0.019725311547517776 +4,BTC-USD,2026-05-28,-0.0029484701808542013,-0.010929802432656288 +4,BTC-USD,2026-05-29,-0.002973714843392372,-0.002233099890872836 +4,BTC-USD,2026-05-30,-0.00295435031875968,0.005197039805352688 +4,BTC-USD,2026-05-31,-0.002953179646283388,-0.0023775624576956034 +4,BTC-USD,2026-06-01,-0.002983729587867856,-0.03119538724422455 +4,BTC-USD,2026-06-02,-0.0029935401398688555,-0.06691385060548782 +4,BTC-USD,2026-06-03,-0.003046309808269143,-0.041152223944664 +4,BTC-USD,2026-06-04,-0.00308673526160419,-0.003329681232571602 +4,BTC-USD,2026-06-05,-0.0031135256867855787,-0.04617254436016083 +4,BTC-USD,2026-06-06,-0.0031351125799119473,-0.0009073630790226161 +4,BTC-USD,2026-06-07,-0.0031696120277047157,0.03823145478963852 +4,BTC-USD,2026-06-08,-0.0032098637893795967,-0.0023577872198075056 +4,BTC-USD,2026-06-09,-0.0032354325521737337,-0.023199275135993958 +4,BTC-USD,2026-06-10,-0.003296250244602561,-0.0031600859947502613 +4,BTC-USD,2026-06-11,-0.0033759435173124075,0.03378866985440254 +4,BTC-USD,2026-06-12,-0.0034259939566254616,-0.00028095784364268184 +4,BTC-USD,2026-06-13,-0.0034364708699285984,0.013724722899496555 +4,BTC-USD,2026-06-14,-0.003478721948340535,0.019812485203146935 +4,BTC-USD,2026-06-15,-0.0035185569431632757,0.008774328976869583 +4,BTC-USD,2026-06-16,-0.0035060883965343237,-0.010446052066981792 +4,BTC-USD,2026-06-17,-0.003471240634098649,-0.01818545162677765 +4,BTC-USD,2026-06-18,-0.0034718657843768597,-0.023909926414489746 +4,BTC-USD,2026-06-19,-0.003464920213446021,0.01019270159304142 +4,BTC-USD,2026-06-20,-0.0034447647631168365,0.01093823742121458 +4,ETH-USD,2026-04-24,-0.0021566986106336117,-0.0068100267089903355 +4,ETH-USD,2026-04-25,-0.002276142593473196,0.0013545812107622623 +4,ETH-USD,2026-04-26,-0.002341198269277811,0.021713243797421455 +4,ETH-USD,2026-04-27,-0.0023818346671760082,-0.028535209596157074 +4,ETH-USD,2026-04-28,-0.0024656374007463455,-0.005942025221884251 +4,ETH-USD,2026-04-29,-0.002566743642091751,-0.015851184725761414 +4,ETH-USD,2026-04-30,-0.0028223625849932432,0.0012574982829391956 +4,ETH-USD,2026-05-01,-0.0029866769909858704,0.017069008201360703 +4,ETH-USD,2026-05-02,-0.00314145814627409,0.009168006479740143 +4,ETH-USD,2026-05-03,-0.0032317014411091805,0.002330299699679017 +4,ETH-USD,2026-05-04,-0.0033467840403318405,0.010608949698507786 +4,ETH-USD,2026-05-05,-0.003429059637710452,0.006281653884798288 +4,ETH-USD,2026-05-06,-0.0035388944670557976,-0.004406054969877005 +4,ETH-USD,2026-05-07,-0.003571751993149519,-0.025721149519085884 +4,ETH-USD,2026-05-08,-0.0037079076282680035,0.0069005172699689865 +4,ETH-USD,2026-05-09,-0.003731816541403532,0.008526770398020744 +4,ETH-USD,2026-05-10,-0.003852306632325053,0.018023788928985596 +4,ETH-USD,2026-05-11,-0.00395042123273015,-0.012608728371560574 +4,ETH-USD,2026-05-12,-0.004067063797265291,-0.028054386377334595 +4,ETH-USD,2026-05-13,-0.004253026098012924,-0.007531505078077316 +4,ETH-USD,2026-05-14,-0.004371947143226862,0.010293509811162949 +4,ETH-USD,2026-05-15,-0.00455329567193985,-0.02557980641722679 +4,ETH-USD,2026-05-16,-0.004718597047030926,-0.019794471561908722 +4,ETH-USD,2026-05-17,-0.004929157439619303,-0.024195227771997452 +4,ETH-USD,2026-05-18,-0.005205618217587471,0.0004092183371540159 +4,ETH-USD,2026-05-19,-0.005497702397406101,-0.008754253387451172 +4,ETH-USD,2026-05-20,-0.005712506826967001,0.00803390797227621 +4,ETH-USD,2026-05-21,-0.005872315727174282,0.002079303842037916 +4,ETH-USD,2026-05-22,-0.005943587515503168,-0.031829629093408585 +4,ETH-USD,2026-05-23,-0.006070752628147602,0.024550147354602814 +4,ETH-USD,2026-05-24,-0.006132130976766348,-0.008522952906787395 +4,ETH-USD,2026-05-25,-0.006179973483085632,0.006355596240609884 +4,ETH-USD,2026-05-26,-0.006326834671199322,-0.01937410794198513 +4,ETH-USD,2026-05-27,-0.006456280592828989,-0.023777931928634644 +4,ETH-USD,2026-05-28,-0.006578062195330858,-0.007268723100423813 +4,ETH-USD,2026-05-29,-0.006606308743357658,0.002202139003202319 +4,ETH-USD,2026-05-30,-0.006598834879696369,0.003710709046572447 +4,ETH-USD,2026-05-31,-0.006622397340834141,-0.007513679098337889 +4,ETH-USD,2026-06-01,-0.006729482673108578,-0.0005591235239990056 +4,ETH-USD,2026-06-02,-0.006800862494856119,-0.07540854066610336 +4,ETH-USD,2026-06-03,-0.006930737290531397,-0.025064481422305107 +4,ETH-USD,2026-06-04,-0.006992736365646124,-0.023540908470749855 +4,ETH-USD,2026-06-05,-0.007089497987180948,-0.11277301609516144 +4,ETH-USD,2026-06-06,-0.007129131816327572,-0.007679127622395754 +4,ETH-USD,2026-06-07,-0.00714758038520813,0.07230344414710999 +4,ETH-USD,2026-06-08,-0.007213336881250143,0.002222580136731267 +4,ETH-USD,2026-06-09,-0.007235407363623381,-0.03151954337954521 +4,ETH-USD,2026-06-10,-0.007288490887731314,-0.010785745456814766 +4,ETH-USD,2026-06-11,-0.007374288979917765,0.03167720511555672 +4,ETH-USD,2026-06-12,-0.0073948875069618225,-0.004286465235054493 +4,ETH-USD,2026-06-13,-0.0073889996856451035,0.00901964120566845 +4,ETH-USD,2026-06-14,-0.007440231274813414,0.02608131803572178 +4,ETH-USD,2026-06-15,-0.007472571916878223,0.039980556815862656 +4,ETH-USD,2026-06-16,-0.0074066477827727795,-0.002545346273109317 +4,ETH-USD,2026-06-17,-0.007289501838386059,-0.024031279608607292 +4,ETH-USD,2026-06-18,-0.007218103855848312,-0.0221862755715847 +4,ETH-USD,2026-06-19,-0.007124702911823988,0.0008472258341498673 +4,ETH-USD,2026-06-20,-0.00699374545365572,0.016415812075138092 diff --git a/ml_engine/walk_forward_reports/pnl_predictions_equity_specialist.csv b/ml_engine/walk_forward_reports/pnl_predictions_equity_specialist.csv new file mode 100644 index 0000000000000000000000000000000000000000..ae8768d2c230bfb0d47726999483cf1a78bf1c42 --- /dev/null +++ b/ml_engine/walk_forward_reports/pnl_predictions_equity_specialist.csv @@ -0,0 +1,6433 @@ +fold,ticker,date,r_hat,r_true +1,AAPL,2022-08-17,0.001045416109263897,0.00874626450240612 +1,AAPL,2022-08-18,0.0010359452571719885,-0.0022942328359931707 +1,AAPL,2022-08-19,0.0010291760554537177,-0.01521687489002943 +1,AAPL,2022-08-22,0.0009771424811333418,-0.023298749700188637 +1,AAPL,2022-08-23,0.0008200001320801675,-0.0020314136054366827 +1,AAPL,2022-08-24,0.0007783422479405999,0.0017926051514223218 +1,AAPL,2022-08-25,0.0007840836187824607,0.014812425710260868 +1,AAPL,2022-08-26,0.0008968261536210775,-0.03842836618423462 +1,AAPL,2022-08-29,0.00066889583831653,-0.013784791342914104 +1,AAPL,2022-08-30,0.0005914202774874866,-0.01542364526540041 +1,AAPL,2022-08-31,0.0004069505666848272,-0.01069206465035677 +1,AAPL,2022-09-01,6.084044071030803e-05,0.004695710260421038 +1,AAPL,2022-09-02,0.0001499430654803291,-0.013704396784305573 +1,AAPL,2022-09-06,-0.00027718240744434297,-0.008249109610915184 +1,AAPL,2022-09-07,-0.0009264174732379615,0.009211155585944653 +1,AAPL,2022-09-08,-0.000782312301453203,-0.009664082899689674 +1,AAPL,2022-09-09,-0.001052039093337953,0.018664343282580376 +1,AAPL,2022-09-12,-0.00042467794264666736,0.03778499737381935 +1,AAPL,2022-09-13,0.0004931750008836389,-0.060471538454294205 +1,AAPL,2022-09-14,-0.0001318953582085669,0.0095100412145257 +1,AAPL,2022-09-15,0.00019945889653172344,-0.019111495465040207 +1,AAPL,2022-09-16,-0.0002106510364683345,-0.011020380072295666 +1,AAPL,2022-09-19,-0.0001967470598174259,0.024773241952061653 +1,AAPL,2022-09-20,0.00042786975973285735,0.015544036403298378 +1,AAPL,2022-09-21,0.0006367018795572221,-0.02047581784427166 +1,AAPL,2022-09-22,0.0006712503382004797,-0.0063957879319787025 +1,AAPL,2022-09-23,0.0006963370251469314,-0.015238955616950989 +1,AAPL,2022-09-26,0.0006958852172829211,0.0022577152121812105 +1,AAPL,2022-09-27,0.0007579576340503991,0.006544487550854683 +1,AAPL,2022-09-28,0.0008221971220336854,-0.012732081115245819 +1,AAPL,2022-09-29,0.0008655588608235121,-0.05036645382642746 +1,AAPL,2022-09-30,0.000702552089933306,-0.03049985133111477 +1,AAPL,2022-10-03,0.00045512703945860267,0.03028899058699608 +1,AAPL,2022-10-04,0.0004951892187818885,0.025300219655036926 +1,AAPL,2022-10-05,0.0005817815545015037,0.0020513860508799553 +1,AAPL,2022-10-06,0.0006266136188060045,-0.006647655740380287 +1,AAPL,2022-10-07,0.0006237291381694376,-0.037409599870443344 +1,AAPL,2022-10-10,0.00028206995921209455,0.002352809766307473 +1,AAPL,2022-10-11,-4.7631070628995076e-05,-0.010308188386261463 +1,AAPL,2022-10-12,-2.7947501735070546e-07,-0.004615360405296087 +1,AAPL,2022-10-13,2.283690491822199e-06,0.033060215413570404 +1,AAPL,2022-10-14,0.0004616295045707375,-0.03277125209569931 +1,AAPL,2022-10-17,0.0003823168226517737,0.028707044199109077 +1,AAPL,2022-10-18,0.0005695675499737263,0.009365309961140156 +1,AAPL,2022-10-19,0.0007001010235399008,0.0007649449398741126 +1,AAPL,2022-10-20,0.000797538086771965,-0.003272559493780136 +1,AAPL,2022-10-21,0.0008452006732113659,0.026699358597397804 +1,AAPL,2022-10-24,0.0009346487931907177,0.014694292098283768 +1,AAPL,2022-10-25,0.0009936562273651361,0.01915302686393261 +1,AAPL,2022-10-26,0.0010356245329603553,-0.01982216164469719 +1,AAPL,2022-10-27,0.0010272974614053965,-0.030939221382141113 +1,AAPL,2022-10-28,0.0009968039812520146,0.07283452898263931 +1,AAPL,2022-10-31,0.0010393448173999786,-0.01553034596145153 +1,AAPL,2022-11-01,0.0010194131173193455,-0.017698464915156364 +1,AAPL,2022-11-02,0.0009769090684130788,-0.03801873326301575 +1,AAPL,2022-11-03,0.0008030334720388055,-0.043329961597919464 +1,AAPL,2022-11-04,0.0003974060819018632,-0.0019495371961966157 +1,AAPL,2022-11-07,0.00042641544132493436,0.0038947220891714096 +1,AAPL,2022-11-08,0.00013383173791226,0.004166339058429003 +1,AAPL,2022-11-09,0.00023116535157896578,-0.03375306725502014 +1,AAPL,2022-11-10,-0.0011763385264202952,0.08523648977279663 +1,AAPL,2022-11-11,-0.0001304548350162804,0.019085397943854332 +1,AAPL,2022-11-14,0.0004329018120188266,-0.009530998766422272 +1,AAPL,2022-11-15,0.0005796972545795143,0.011799581348896027 +1,AAPL,2022-11-16,0.0007082612719386816,-0.008366277441382408 +1,AAPL,2022-11-17,0.0007654441869817674,0.012887958437204361 +1,AAPL,2022-11-18,0.0008466262370347977,0.003774771699681878 +1,AAPL,2022-11-21,0.0009012902737595141,-0.021918529644608498 +1,AAPL,2022-11-22,0.0009046921040862799,0.014554504305124283 +1,AAPL,2022-11-23,0.000958085700403899,0.00590912252664566 +1,AAPL,2022-11-25,0.0009867041371762753,-0.01978829689323902 +1,AAPL,2022-11-28,0.0009572706185281277,-0.02661517821252346 +1,AAPL,2022-11-29,0.0008643390610814095,-0.021375229582190514 +1,AAPL,2022-11-30,0.0007776110433042049,0.04745011404156685 +1,AAPL,2022-12-01,0.0008487473824061453,0.0018897963454946876 +1,AAPL,2022-12-02,0.0008711910340934992,-0.0033768683206290007 +1,AAPL,2022-12-05,0.000866419926751405,-0.008015325292944908 +1,AAPL,2022-12-06,0.0008451661560684443,-0.025697486475110054 +1,AAPL,2022-12-07,0.0006957955192774534,-0.013880476355552673 +1,AAPL,2022-12-08,0.0005623120814561844,0.01205955259501934 +1,AAPL,2022-12-09,0.0006404636078514159,-0.0034405107144266367 +1,AAPL,2022-12-12,0.0006730679306201637,0.01625666953623295 +1,AAPL,2022-12-13,0.0008336167084053159,0.00675968499854207 +1,AAPL,2022-12-14,0.0009017202537506819,-0.015657681971788406 +1,AAPL,2022-12-15,0.0009420468122698367,-0.0479876846075058 +1,AAPL,2022-12-16,0.000784175586886704,-0.014686113223433495 +1,AAPL,2022-12-19,0.0006713526090607047,-0.016037441790103912 +1,AAPL,2022-12-20,0.0005251240218058228,-0.0005287173553369939 +1,AAPL,2022-12-21,0.00038346301880665123,0.02353012003004551 +1,AAPL,2022-12-22,0.00047787075163796544,-0.024059588089585304 +1,AAPL,2022-12-23,5.8522153267404065e-05,-0.002802301198244095 +1,AAPL,2022-12-27,-7.227114110719413e-05,-0.013975415378808975 +1,AAPL,2022-12-28,-0.00031747567118145525,-0.031165804713964462 +1,AAPL,2022-12-29,-0.0011687909718602896,0.027930783107876778 +1,AAPL,2022-12-30,-0.0008151304791681468,0.0024658713955432177 +1,AAPL,2023-01-03,-0.0004967845743522048,-0.03812231123447418 +1,AAPL,2023-01-04,-0.0007536530029028654,0.010261284187436104 +1,AAPL,2023-01-05,-0.0007002886850386858,-0.010661160573363304 +1,AAPL,2023-01-06,-0.0008382914820685983,0.0361335426568985 +1,AAPL,2023-01-09,-0.0002276907180203125,0.0040802424773573875 +1,AAPL,2023-01-10,0.0003274067712482065,0.0044466969557106495 +1,AAPL,2023-01-11,0.000536831037607044,0.02089250646531582 +1,AAPL,2023-01-12,0.0006878536660224199,-0.0005995988030917943 +1,AAPL,2023-01-13,0.0007905469974502921,0.01006842777132988 +1,AAPL,2023-01-17,0.0008921780390664935,0.0087180370464921 +1,AAPL,2023-01-18,0.000990619882941246,-0.005384448915719986 +1,AAPL,2023-01-19,0.0010190429165959358,0.00044351740507408977 +1,AAPL,2023-01-20,0.0010288621997460723,0.019038597121834755 +1,AAPL,2023-01-23,0.0010672516655176878,0.023228619247674942 +1,AAPL,2023-01-24,0.0010921796783804893,0.010012537240982056 +1,AAPL,2023-01-25,0.001141141401603818,-0.004712054505944252 +1,AAPL,2023-01-26,0.001105836476199329,0.014695029705762863 +1,AAPL,2023-01-27,0.0011366967810317874,0.013591584749519825 +1,AAPL,2023-01-30,0.0011279950849711895,-0.020282626152038574 +1,AAPL,2023-01-31,0.0010496975155547261,0.008980761282145977 +1,AAPL,2023-02-01,0.0010442722123116255,0.007869613356888294 +1,AAPL,2023-02-02,0.0010562827810645103,0.03639235720038414 +1,AAPL,2023-02-03,0.0011553476797416806,0.02410690113902092 +1,AAPL,2023-02-06,0.0011562156723812222,-0.01809113658964634 +1,AAPL,2023-02-07,0.0010897723259404302,0.0190617386251688 +1,AAPL,2023-02-08,0.0011326373787596822,-0.017810551449656487 +1,AAPL,2023-02-09,0.0010474130976945162,-0.006935622543096542 +1,AAPL,2023-02-10,0.0010105539113283157,0.0024531276430934668 +1,AAPL,2023-02-13,0.0009787348099052906,0.01863209158182144 +1,AAPL,2023-02-14,0.0010108941933140159,-0.004233715124428272 +1,AAPL,2023-02-15,0.0010068060364574194,0.013807612471282482 +1,AAPL,2023-02-16,0.0010739817516878247,-0.010484096594154835 +1,AAPL,2023-02-17,0.0010456368327140808,-0.007575333118438721 +1,AAPL,2023-02-21,0.0010459702461957932,-0.02704223059117794 +1,AAPL,2023-02-22,0.0009009108762256801,0.00289197638630867 +1,AAPL,2023-02-23,0.000820835935883224,0.003285001963376999 +1,AAPL,2023-02-24,0.0008335626916959882,-0.018169447779655457 +1,AAPL,2023-02-27,0.0007678987458348274,0.008213852532207966 +1,AAPL,2023-02-28,0.0008047177107073367,-0.00345383258536458 +1,AAPL,2023-03-01,0.0008248056983575225,-0.014348257333040237 +1,AAPL,2023-03-02,0.0007903332007117569,0.004120385739952326 +1,AAPL,2023-03-03,0.0008540311828255653,0.03448865935206413 +1,AAPL,2023-03-06,0.0009824607986956835,0.018369589000940323 +1,AAPL,2023-03-07,0.0011863517574965954,-0.014602758921682835 +1,AAPL,2023-03-08,0.0011791284196078777,0.008342311717569828 +1,AAPL,2023-03-09,0.0011990934144705534,-0.015026779845356941 +1,AAPL,2023-03-10,0.0011599245481193066,-0.01397587452083826 +1,AAPL,2023-03-13,0.001069571590051055,0.01317891851067543 +1,AAPL,2023-03-14,0.0011394514003768563,0.013990720734000206 +1,AAPL,2023-03-15,0.001174943638034165,0.002617971505969763 +1,AAPL,2023-03-16,0.0011899605160579085,0.018521320074796677 +1,AAPL,2023-03-17,0.0012148196110501885,-0.005468859802931547 +1,AAPL,2023-03-20,0.0012050819350406528,0.015365107916295528 +1,AAPL,2023-03-21,0.0012164820218458772,0.011873530223965645 +1,AAPL,2023-03-22,0.0012275888584554195,-0.0091452207416296 +1,AAPL,2023-03-23,0.0011783662484958768,0.006945197004824877 +1,AAPL,2023-03-24,0.001175162149593234,0.008271603845059872 +1,AAPL,2023-03-27,0.0011800999054685235,-0.012369716539978981 +1,AAPL,2023-03-28,0.0011442052200436592,-0.003988271579146385 +1,AAPL,2023-03-29,0.0011338491458445787,0.019597547128796577 +1,AAPL,2023-03-30,0.0011796377366408706,0.009841104969382286 +1,AAPL,2023-03-31,0.0012003752635791898,0.015523134730756283 +1,AAPL,2023-04-03,0.0012197447940707207,0.007672316860407591 +1,AAPL,2023-04-04,0.001206932938657701,-0.003254982177168131 +1,AAPL,2023-04-05,0.0011869024019688368,-0.011354628019034863 +1,AAPL,2023-04-06,0.0011314083822071552,0.005480938125401735 +1,AAPL,2023-04-10,0.0011472920887172222,-0.01610117219388485 +1,AAPL,2023-04-11,0.001095463172532618,-0.007620376069098711 +1,AAPL,2023-04-12,0.001054170774295926,-0.004362491425126791 +1,AAPL,2023-04-13,0.0010428937384858727,0.03353500738739967 +1,AAPL,2023-04-14,0.0011480968678370118,-0.0021162964403629303 +1,AAPL,2023-04-17,0.0011790927965193987,0.00012098492152290419 +1,AAPL,2023-04-18,0.0012017261469736695,0.007476720493286848 +1,AAPL,2023-04-19,0.0012283740798011422,0.00694408779963851 +1,AAPL,2023-04-20,0.0012427413603290915,-0.0058636111207306385 +1,AAPL,2023-04-21,0.0012278613867238164,-0.009828880429267883 +1,AAPL,2023-04-24,0.001185338944196701,0.001876857248134911 +1,AAPL,2023-04-25,0.0011898742523044348,-0.009480690583586693 +1,AAPL,2023-04-26,0.0011226629139855504,-6.10772694926709e-05 +1,AAPL,2023-04-27,0.0011023300467059016,0.02799968235194683 +1,AAPL,2023-04-28,0.0012092794058844447,0.007512734737247229 +1,AAPL,2023-05-01,0.0012363194255158305,-0.0005304910591803491 +1,AAPL,2023-05-02,0.0012257908238098025,-0.006210620980709791 +1,AAPL,2023-05-03,0.0011978127295151353,-0.006488338112831116 +1,AAPL,2023-05-04,0.0011300541227683425,-0.00996294803917408 +1,AAPL,2023-05-05,0.0010623873677104712,0.04585917294025421 +1,AAPL,2023-05-08,0.00115727458614856,-0.0004033809818793088 +1,AAPL,2023-05-09,0.0011624974431470037,-0.010021303780376911 +1,AAPL,2023-05-10,0.00112424255348742,0.010367144830524921 +1,AAPL,2023-05-11,0.0011625561164692044,0.0010940198553726077 +1,AAPL,2023-05-12,0.0011596382828429341,-0.005432301200926304 +1,AAPL,2023-05-15,0.0011301011545583606,-0.002901569241657853 +1,AAPL,2023-05-16,0.001115440740250051,0.0 +1,AAPL,2023-05-17,0.001117819338105619,0.003596795490011573 +1,AAPL,2023-05-18,0.0011313451686874032,0.013573459349572659 +1,AAPL,2023-05-19,0.0011672490509226918,0.0006280913366936147 +1,AAPL,2023-05-22,0.0011564973974600434,-0.005495575722306967 +1,AAPL,2023-05-23,0.001141875982284546,-0.015271002426743507 +1,AAPL,2023-05-24,0.001095636747777462,0.001630500191822648 +1,AAPL,2023-05-25,0.0010340885492041707,0.006670034024864435 +1,AAPL,2023-05-26,0.00106135499663651,0.014006300829350948 +1,AAPL,2023-05-30,0.0011448191944509745,0.010603299364447594 +1,AAPL,2023-05-31,0.0011715084547176957,-0.0002823348913807422 +1,AAPL,2023-06-01,0.0011765796225517988,0.015895746648311615 +1,AAPL,2023-06-02,0.0012204701779410243,0.004763951059430838 +1,AAPL,2023-06-05,0.0012371782213449478,-0.0075998976826667786 +1,MSFT,2022-08-17,0.0009499028674326837,-0.002639654790982604 +1,MSFT,2022-08-18,0.0009359773248434067,-0.00395545456558466 +1,MSFT,2022-08-19,0.0009252931922674179,-0.01395068597048521 +1,MSFT,2022-08-22,0.0008500659023411572,-0.029794607311487198 +1,MSFT,2022-08-23,0.0006596280727535486,-0.004727791994810104 +1,MSFT,2022-08-24,0.000627503904979676,-0.0023541580885648727 +1,MSFT,2022-08-25,0.0005376291810534894,0.011034233495593071 +1,MSFT,2022-08-26,0.0006194736924953759,-0.03935132175683975 +1,MSFT,2022-08-29,0.0003242833190597594,-0.010725339874625206 +1,MSFT,2022-08-30,-1.998482912313193e-05,-0.008557546883821487 +1,MSFT,2022-08-31,-0.0006019316497258842,-0.005720207467675209 +1,MSFT,2022-09-01,-0.001461329753510654,-0.004100713413208723 +1,MSFT,2022-09-02,-0.001807133317925036,-0.016807060688734055 +1,MSFT,2022-09-06,-0.0016941361827775836,-0.01103462465107441 +1,MSFT,2022-09-07,-0.0012727860594168305,0.018931256607174873 +1,MSFT,2022-09-08,-0.0015387870371341705,0.001664673094637692 +1,MSFT,2022-09-09,-0.0016554611502215266,0.022716861218214035 +1,MSFT,2022-09-12,-0.0013025365769863129,0.00824687723070383 +1,MSFT,2022-09-13,-0.0004474624292925,-0.05654740706086159 +1,MSFT,2022-09-14,-0.0014539744006469846,0.0009123273775912821 +1,MSFT,2022-09-15,-0.0013973983004689217,-0.027493752539157867 +1,MSFT,2022-09-16,-0.0015697788912802935,-0.0026115798391401768 +1,MSFT,2022-09-19,-0.001639645779505372,-0.0008992255898192525 +1,MSFT,2022-09-20,-0.0016767223132774234,-0.0085017504170537 +1,MSFT,2022-09-21,-0.0016681618290022016,-0.01454098429530859 +1,MSFT,2022-09-22,-0.0015261401422321796,0.008459486998617649 +1,MSFT,2022-09-23,-0.0016233420465141535,-0.012779452838003635 +1,MSFT,2022-09-26,-0.0016157726058736444,-0.0019775312393903732 +1,MSFT,2022-09-27,-0.0015958691947162151,-0.0043893191032111645 +1,MSFT,2022-09-28,-0.0014662255998700857,0.019519848749041557 +1,MSFT,2022-09-29,-0.001028277911245823,-0.014919989742338657 +1,MSFT,2022-09-30,-0.0008814182947389781,-0.019558442756533623 +1,MSFT,2022-10-03,-0.0009484901092946529,0.03310847654938698 +1,MSFT,2022-10-04,-0.0003406129835639149,0.03325316309928894 +1,MSFT,2022-10-05,0.00042458955431357026,0.0012850159546360373 +1,MSFT,2022-10-06,0.0005844905972480774,-0.00971793383359909 +1,MSFT,2022-10-07,0.0006807722384110093,-0.052191559225320816 +1,MSFT,2022-10-10,0.0005325539968907833,-0.02153320237994194 +1,MSFT,2022-10-11,0.00045393305481411517,-0.016891969367861748 +1,MSFT,2022-10-12,0.0003082111943513155,0.0015070469817146659 +1,MSFT,2022-10-13,-6.879412103444338e-05,0.03691812604665756 +1,MSFT,2022-10-14,0.00039189678500406444,-0.024547448381781578 +1,MSFT,2022-10-17,0.0002659419260453433,0.038495149463415146 +1,MSFT,2022-10-18,0.0005087867029942572,0.004075540229678154 +1,MSFT,2022-10-19,0.0006157206371426582,-0.00850590132176876 +1,MSFT,2022-10-20,0.0006674744072370231,-0.0013964988756924868 +1,MSFT,2022-10-21,0.0007070063729770482,0.024966422468423843 +1,MSFT,2022-10-24,0.0007894099107943475,0.020966576412320137 +1,MSFT,2022-10-25,0.0008581109577789903,0.013697398826479912 +1,MSFT,2022-10-26,0.0009041173616424203,-0.08029536157846451 +1,MSFT,2022-10-27,0.0008164314203895628,-0.019954094663262367 +1,MSFT,2022-10-28,0.0007367715588770807,0.03943280503153801 +1,MSFT,2022-10-31,0.0007791929529048502,-0.015983162447810173 +1,MSFT,2022-11-01,0.0007399907917715609,-0.017206545919179916 +1,MSFT,2022-11-02,0.0006802881835028529,-0.036009058356285095 +1,MSFT,2022-11-03,0.0003612194850575179,-0.026938455179333687 +1,MSFT,2022-11-04,-0.00030300565413199365,0.03278222680091858 +1,MSFT,2022-11-07,0.00014106827438808978,0.028849326074123383 +1,MSFT,2022-11-08,0.00044908508425578475,0.004378946032375097 +1,MSFT,2022-11-09,0.0005718449247069657,-0.019233711063861847 +1,MSFT,2022-11-10,0.0006152915302664042,0.07905866205692291 +1,MSFT,2022-11-11,0.0007228470058180392,0.016854578629136086 +1,MSFT,2022-11-14,0.0007924960809759796,-0.022757206112146378 +1,MSFT,2022-11-15,0.000845495902467519,0.0017372609581798315 +1,MSFT,2022-11-16,0.0008747823303565383,0.0018219593912363052 +1,MSFT,2022-11-17,0.0008966303430497646,-0.00020692244288511574 +1,MSFT,2022-11-18,0.000904789543710649,-0.0019050214905291796 +1,MSFT,2022-11-21,0.0009085732162930071,0.0034347937908023596 +1,MSFT,2022-11-22,0.0009171593701466918,0.01223625149577856 +1,MSFT,2022-11-23,0.000941962469369173,0.010353181511163712 +1,MSFT,2022-11-25,0.0009217526530846953,-0.0003634598688222468 +1,MSFT,2022-11-28,0.0009143586503341794,-0.023424766957759857 +1,MSFT,2022-11-29,0.0008468191372230649,-0.00593256251886487 +1,MSFT,2022-11-30,0.0007930065039545298,0.059799522161483765 +1,MSFT,2022-12-01,0.0008710356778465211,-0.0017653030809015036 +1,MSFT,2022-12-02,0.0008724656072445214,0.0012949012452736497 +1,MSFT,2022-12-05,0.0008963270229287446,-0.019081396982073784 +1,MSFT,2022-12-06,0.0008527017780579627,-0.02051275223493576 +1,MSFT,2022-12-07,0.0007468457915820181,-0.00306445243768394 +1,MSFT,2022-12-08,0.0007225088193081319,0.012323027476668358 +1,MSFT,2022-12-09,0.0007989737205207348,-0.008035469800233841 +1,MSFT,2022-12-12,0.0007893496658653021,0.028479861095547676 +1,MSFT,2022-12-13,0.0010439269244670868,0.01731386035680771 +1,MSFT,2022-12-14,0.0010939950589090586,0.0011670843232423067 +1,MSFT,2022-12-15,0.0011137609835714102,-0.03243882209062576 +1,MSFT,2022-12-16,0.00104520155582577,-0.017500974237918854 +1,MSFT,2022-12-19,0.0009411349310539663,-0.017479680478572845 +1,MSFT,2022-12-20,0.0008365947869606316,0.005598601419478655 +1,MSFT,2022-12-21,0.0008030818426050246,0.010818053968250751 +1,MSFT,2022-12-22,0.0008313906728290021,-0.025860309600830078 +1,MSFT,2022-12-23,0.0007292242953553796,0.002264542505145073 +1,MSFT,2022-12-27,0.0007049390696920455,-0.007441737223416567 +1,MSFT,2022-12-28,0.0006769367610104382,-0.010307819582521915 +1,MSFT,2022-12-29,0.0006021670997142792,0.02725471369922161 +1,MSFT,2022-12-30,0.0007045744569040835,-0.004949713591486216 +1,MSFT,2023-01-03,0.0007441781926900148,-0.0010012345155701041 +1,MSFT,2023-01-04,0.0007827927474863827,-0.04472888633608818 +1,MSFT,2023-01-05,0.0007522190571762621,-0.030085798352956772 +1,MSFT,2023-01-06,0.000632751383818686,0.011716479435563087 +1,MSFT,2023-01-09,0.0006329215248115361,0.009689200669527054 +1,MSFT,2023-01-10,0.0006731626344844699,0.00758832972496748 +1,MSFT,2023-01-11,0.000711210654117167,0.029790008440613747 +1,MSFT,2023-01-12,0.0008012597681954503,0.011554415337741375 +1,MSFT,2023-01-13,0.00087244767928496,0.00301427417434752 +1,MSFT,2023-01-17,0.0009475343977101147,0.004670790862292051 +1,MSFT,2023-01-18,0.0010804900666698813,-0.01906982995569706 +1,MSFT,2023-01-19,0.0010710986098274589,-0.01659085787832737 +1,MSFT,2023-01-20,0.0010405259672552347,0.035119522362947464 +1,MSFT,2023-01-23,0.0010951280128210783,0.009776465594768524 +1,MSFT,2023-01-24,0.0011220459127798676,-0.002228496829047799 +1,MSFT,2023-01-25,0.0011347434483468533,-0.0059256786480546 +1,MSFT,2023-01-26,0.0011226970236748457,0.03025144524872303 +1,MSFT,2023-01-27,0.0011477357475087047,0.0006448579370044172 +1,MSFT,2023-01-30,0.0011414652690291405,-0.022206420078873634 +1,MSFT,2023-01-31,0.0011045068968087435,0.02079508639872074 +1,MSFT,2023-02-01,0.001117304782383144,0.019738515838980675 +1,MSFT,2023-02-02,0.0011101337149739265,0.045818526297807693 +1,MSFT,2023-02-03,0.0011299229227006435,-0.023903993889689445 +1,MSFT,2023-02-06,0.0011049063177779317,-0.006134777795523405 +1,MSFT,2023-02-07,0.0010910832788795233,0.041163306683301926 +1,MSFT,2023-02-08,0.0011056620860472322,-0.0031068590469658375 +1,MSFT,2023-02-09,0.001083619543351233,-0.01172852423042059 +1,MSFT,2023-02-10,0.0010429556714370847,-0.001974341459572315 +1,MSFT,2023-02-13,0.0010157260112464428,0.03076479583978653 +1,MSFT,2023-02-14,0.001045282930135727,0.0031278408132493496 +1,MSFT,2023-02-15,0.0010393389966338873,-0.00802487414330244 +1,MSFT,2023-02-16,0.001033753389492631,-0.026983609423041344 +1,MSFT,2023-02-17,0.0009275866323150694,-0.01572459749877453 +1,MSFT,2023-02-21,0.0008797718910500407,-0.021107861772179604 +1,MSFT,2023-02-22,0.0007440429180860519,-0.004601628519594669 +1,MSFT,2023-02-23,0.0006170354317873716,0.01287856511771679 +1,MSFT,2023-02-24,0.0006522224866785109,-0.022025106474757195 +1,MSFT,2023-02-27,0.0005669652600772679,0.00376456999219954 +1,MSFT,2023-02-28,0.0005930683109909296,-0.002962407423183322 +1,MSFT,2023-03-01,0.0006251565646380186,-0.012709802016615868 +1,MSFT,2023-03-02,0.000623286934569478,0.019462620839476585 +1,MSFT,2023-03-03,0.0007320038857869804,0.016508955508470535 +1,MSFT,2023-03-06,0.0008014024351723492,0.006170100532472134 +1,MSFT,2023-03-07,0.0008565266616642475,-0.010645553469657898 +1,MSFT,2023-03-08,0.0008523149881511927,-0.0017720733303576708 +1,MSFT,2023-03-09,0.0008782373042777181,-0.0054544974118471146 +1,MSFT,2023-03-10,0.0009154472500085831,-0.014893165789544582 +1,MSFT,2023-03-13,0.0008546612807549536,0.021214211359620094 +1,MSFT,2023-03-14,0.0010224605211988091,0.02669628895819187 +1,MSFT,2023-03-15,0.0011190454242751002,0.017673691734671593 +1,MSFT,2023-03-16,0.0011690035462379456,0.03973611071705818 +1,MSFT,2023-03-17,0.0011711320839822292,0.01162638794630766 +1,MSFT,2023-03-20,0.0011596870608627796,-0.026104237884283066 +1,MSFT,2023-03-21,0.0011191278463229537,0.005677660461515188 +1,MSFT,2023-03-22,0.0011190358782187104,-0.005457219202071428 +1,MSFT,2023-03-23,0.001089157653041184,0.019529566168785095 +1,MSFT,2023-03-24,0.0010978198843076825,0.010425947606563568 +1,MSFT,2023-03-27,0.0010997666977345943,-0.015046766959130764 +1,MSFT,2023-03-28,0.0010680188424885273,-0.0041692922823131084 +1,MSFT,2023-03-29,0.0010580935049802065,0.019002236425876617 +1,MSFT,2023-03-30,0.001083856332115829,0.012540649622678757 +1,MSFT,2023-03-31,0.0010971202282235026,0.014851410873234272 +1,MSFT,2023-04-03,0.001108017866499722,-0.0037182492669671774 +1,MSFT,2023-04-04,0.0010932456934824586,-0.00017408753046765924 +1,MSFT,2023-04-05,0.0010901193600147963,-0.009938627481460571 +1,MSFT,2023-04-06,0.0010625356808304787,0.02521241270005703 +1,MSFT,2023-04-10,0.001107019023038447,-0.007607731968164444 +1,MSFT,2023-04-11,0.0011132103390991688,-0.022929316386580467 +1,MSFT,2023-04-12,0.0010583365801721811,0.0023307395167648792 +1,MSFT,2023-04-13,0.0010822424665093422,0.022152218967676163 +1,MSFT,2023-04-14,0.0011184398317709565,-0.01284764800220728 +1,MSFT,2023-04-17,0.0011270291870459914,0.00925305113196373 +1,MSFT,2023-04-18,0.0011359852505847812,-0.0014900806127116084 +1,MSFT,2023-04-19,0.0011192283127456903,0.0002774631429929286 +1,MSFT,2023-04-20,0.0011127421166747808,-0.008145476691424847 +1,MSFT,2023-04-21,0.001077570952475071,-0.001224025501869619 +1,MSFT,2023-04-24,0.0010497451294213533,-0.0140610933303833 +1,MSFT,2023-04-25,0.0009944814955815673,-0.0227937214076519 +1,MSFT,2023-04-26,0.0007691176724620163,0.06993146240711212 +1,MSFT,2023-04-27,0.0010232964996248484,0.03152568265795708 +1,MSFT,2023-04-28,0.0011098398827016354,0.007939839735627174 +1,MSFT,2023-05-01,0.0011375019093975425,-0.005548310466110706 +1,MSFT,2023-05-02,0.0011263696942478418,-0.0004909083363600075 +1,MSFT,2023-05-03,0.0011182379676029086,-0.0033124929759651423 +1,MSFT,2023-05-04,0.0010993439937010407,0.0033124929759651423 +1,MSFT,2023-05-05,0.0010980133665725589,0.01701178215444088 +1,MSFT,2023-05-08,0.0011031952453777194,-0.006458874326199293 +1,MSFT,2023-05-09,0.0010817308211699128,-0.005360378418117762 +1,MSFT,2023-05-10,0.001055874046869576,0.017148593440651894 +1,MSFT,2023-05-11,0.0010731922229751945,-0.007069143000990152 +1,MSFT,2023-05-12,0.0010500717908143997,-0.003683043411001563 +1,MSFT,2023-05-15,0.0010258880211040378,0.0015846611931920052 +1,MSFT,2023-05-16,0.0010150326415896416,0.007340872194617987 +1,MSFT,2023-05-17,0.0010305076139047742,0.009407252073287964 +1,MSFT,2023-05-18,0.0010479337070137262,0.01429209765046835 +1,MSFT,2023-05-19,0.0010641537373885512,-0.0005653807893395424 +1,MSFT,2023-05-22,0.001067036879248917,0.008881811052560806 +1,MSFT,2023-05-23,0.0010780602460727096,-0.01860414817929268 +1,MSFT,2023-05-24,0.001048835227265954,-0.004482439253479242 +1,MSFT,2023-05-25,0.0009991370607167482,0.037736907601356506 +1,MSFT,2023-05-26,0.0010592719772830606,0.021159984171390533 +1,MSFT,2023-05-30,0.0010662548011168838,-0.005059321876615286 +1,MSFT,2023-05-31,0.0010456073796376586,-0.00855089258402586 +1,MSFT,2023-06-01,0.0010155399795621634,0.01267875637859106 +1,MSFT,2023-06-02,0.001017109490931034,0.008443149738013744 +1,MSFT,2023-06-05,0.001022701500914991,0.0016089357668533921 +1,NVDA,2022-08-17,0.001671194564551115,-0.029238490387797356 +1,NVDA,2022-08-18,0.001622381736524403,0.023607932031154633 +1,NVDA,2022-08-19,0.0016897686291486025,-0.050472088158130646 +1,NVDA,2022-08-22,0.0015243972884491086,-0.046736277639865875 +1,NVDA,2022-08-23,0.0012395238736644387,0.008592779748141766 +1,NVDA,2022-08-24,0.0012008891208097339,0.002383592538535595 +1,NVDA,2022-08-25,0.0011638618307188153,0.039338961243629456 +1,NVDA,2022-08-26,0.001369949197396636,-0.09681840986013412 +1,NVDA,2022-08-29,0.0006146979285404086,-0.028634939342737198 +1,NVDA,2022-08-30,-0.0005342843942344189,-0.02129990980029106 +1,NVDA,2022-08-31,-0.0016705140005797148,-0.02447601780295372 +1,NVDA,2022-09-01,-0.0030883573926985264,-0.07975023239850998 +1,NVDA,2022-09-02,-0.002359574194997549,-0.021027376875281334 +1,NVDA,2022-09-06,-0.001869988045655191,-0.013425956480205059 +1,NVDA,2022-09-07,-0.0012459068093448877,0.01862032152712345 +1,NVDA,2022-09-08,-0.0013830495299771428,0.019925687462091446 +1,NVDA,2022-09-09,-0.0015866501489654183,0.027982333675026894 +1,NVDA,2022-09-12,-0.00204079644754529,0.00816839188337326 +1,NVDA,2022-09-13,-0.002526180585846305,-0.09951767325401306 +1,NVDA,2022-09-14,-0.0015361001715064049,-0.00022842385806143284 +1,NVDA,2022-09-15,-0.0014116944512352347,-0.015274448320269585 +1,NVDA,2022-09-16,-0.0012961557367816567,0.020592408254742622 +1,NVDA,2022-09-19,-0.0016791073139756918,0.013845146633684635 +1,NVDA,2022-09-20,-0.0021068695932626724,-0.015513410791754723 +1,NVDA,2022-09-21,-0.002385198837146163,0.006430359557271004 +1,NVDA,2022-09-22,-0.00283061433583498,-0.05423065647482872 +1,NVDA,2022-09-23,-0.002797513036057353,-0.0035890827421098948 +1,NVDA,2022-09-26,-0.0026657988782972097,-0.02327924780547619 +1,NVDA,2022-09-27,-0.0024063382297754288,0.015015831217169762 +1,NVDA,2022-09-28,-0.001812611473724246,0.02568826638162136 +1,NVDA,2022-09-29,-0.0009374631335958838,-0.04135856032371521 +1,NVDA,2022-09-30,-0.0004262668371666223,-0.006650411989539862 +1,NVDA,2022-10-03,-0.00018665503012016416,0.030264701694250107 +1,NVDA,2022-10-04,0.0004969594301655889,0.05102556571364403 +1,NVDA,2022-10-05,0.0009263183455914259,0.003184765577316284 +1,NVDA,2022-10-06,0.001081686234101653,-0.005998820532113314 +1,NVDA,2022-10-07,0.0011670264648273587,-0.08367960900068283 +1,NVDA,2022-10-10,0.0009284424013458192,-0.034198615700006485 +1,NVDA,2022-10-11,0.0007738940184935927,-0.0072240037843585014 +1,NVDA,2022-10-12,0.0006535129505209625,-0.0074504707008600235 +1,NVDA,2022-10-13,0.0002012723416555673,0.03922067582607269 +1,NVDA,2022-10-14,0.0007644740981049836,-0.06324607133865356 +1,NVDA,2022-10-17,-0.000196019173017703,0.05720779672265053 +1,NVDA,2022-10-18,0.0005840335506945848,0.0066233971156179905 +1,NVDA,2022-10-19,0.0008800774230621755,0.006994812283664942 +1,NVDA,2022-10-20,0.0010176387149840593,0.011796410195529461 +1,NVDA,2022-10-21,0.0010880621848627925,0.022060943767428398 +1,NVDA,2022-10-24,0.0011907202424481511,0.010612444020807743 +1,NVDA,2022-10-25,0.0012648473493754864,0.051209937781095505 +1,NVDA,2022-10-26,0.0013665745500475168,-0.027910061180591583 +1,NVDA,2022-10-27,0.0013723409501835704,0.02147970162332058 +1,NVDA,2022-10-28,0.0014181302394717932,0.048732317984104156 +1,NVDA,2022-10-31,0.0014770692214369774,-0.024661855772137642 +1,NVDA,2022-11-01,0.0014520634431391954,0.0034023525658994913 +1,NVDA,2022-11-02,0.0014497238444164395,-0.024214640259742737 +1,NVDA,2022-11-03,0.0013691947096958756,0.015165334567427635 +1,NVDA,2022-11-04,0.0013435013825073838,0.053317926824092865 +1,NVDA,2022-11-07,0.0013953582383692265,0.010190995410084724 +1,NVDA,2022-11-08,0.0014318169560283422,0.020829102024435997 +1,NVDA,2022-11-09,0.0014716503210365772,-0.05823059007525444 +1,NVDA,2022-11-10,0.0013709323247894645,0.1339123696088791 +1,NVDA,2022-11-11,0.0014149581547826529,0.03597954660654068 +1,NVDA,2022-11-14,0.0014020520029589534,-0.001961546018719673 +1,NVDA,2022-11-15,0.0013768121134489775,0.02251240611076355 +1,NVDA,2022-11-16,0.0013688714243471622,-0.046422895044088364 +1,NVDA,2022-11-17,0.0012863947777077556,-0.014753099530935287 +1,NVDA,2022-11-18,0.001234571449458599,-0.01724293828010559 +1,NVDA,2022-11-21,0.0011950297048315406,-0.005988400429487228 +1,NVDA,2022-11-22,0.0011790667194873095,0.04599756747484207 +1,NVDA,2022-11-23,0.001267921063117683,0.02955014444887638 +1,NVDA,2022-11-25,0.001317401067353785,-0.01518831867724657 +1,NVDA,2022-11-28,0.0013185606803745031,-0.02760535478591919 +1,NVDA,2022-11-29,0.0012755756033584476,-0.011949673295021057 +1,NVDA,2022-11-30,0.0012547511141747236,0.07916156202554703 +1,NVDA,2022-12-01,0.001396019826643169,0.012449665926396847 +1,NVDA,2022-12-02,0.0014454812044277787,-0.01523082610219717 +1,NVDA,2022-12-05,0.0014710036339238286,-0.015887409448623657 +1,NVDA,2022-12-06,0.0014738580211997032,-0.03822905942797661 +1,NVDA,2022-12-07,0.0013853752752766013,0.008284701965749264 +1,NVDA,2022-12-08,0.001407779403962195,0.06304483860731125 +1,NVDA,2022-12-09,0.0016118487110361457,-0.009833253920078278 +1,NVDA,2022-12-12,0.0016605667769908905,0.03092670813202858 +1,NVDA,2022-12-13,0.0018908367492258549,0.030164847150444984 +1,NVDA,2022-12-14,0.0018666653195396066,-0.02226903848350048 +1,NVDA,2022-12-15,0.0018324293196201324,-0.04170884191989899 +1,NVDA,2022-12-16,0.0016862750053405762,-0.02273188717663288 +1,NVDA,2022-12-19,0.0015400871634483337,-0.01931493729352951 +1,NVDA,2022-12-20,0.0014211798552423716,-0.010451963171362877 +1,NVDA,2022-12-21,0.0013143793912604451,0.025534028187394142 +1,NVDA,2022-12-22,0.0013829668750986457,-0.07302255928516388 +1,NVDA,2022-12-23,0.001069878344424069,-0.008708491921424866 +1,NVDA,2022-12-27,0.0009555072174407542,-0.07402699440717697 +1,NVDA,2022-12-28,0.0003591638815123588,-0.006037637125700712 +1,NVDA,2022-12-29,-0.0013247522292658687,0.03960156440734863 +1,NVDA,2022-12-30,-0.0006640872452408075,0.0007529363501816988 +1,NVDA,2023-01-03,-0.0004954201285727322,-0.0206720270216465 +1,NVDA,2023-01-04,-0.0011165825417265296,0.02986740879714489 +1,NVDA,2023-01-05,-0.0004375738790258765,-0.03336619213223457 +1,NVDA,2023-01-06,-0.001015715766698122,0.04079641401767731 +1,NVDA,2023-01-09,8.969792543211952e-05,0.05045861750841141 +1,NVDA,2023-01-10,0.0008913574856705964,0.017820773646235466 +1,NVDA,2023-01-11,0.0011595095274969935,0.005766286514699459 +1,NVDA,2023-01-12,0.0013242156710475683,0.03137559816241264 +1,NVDA,2023-01-13,0.0014675824204459786,0.02322765253484249 +1,NVDA,2023-01-17,0.0015765384305268526,0.04642319306731224 +1,NVDA,2023-01-18,0.0016886629164218903,-0.01853015273809433 +1,NVDA,2023-01-19,0.0016845188802108169,-0.03585446998476982 +1,NVDA,2023-01-20,0.0016149372095242143,0.062094151973724365 +1,NVDA,2023-01-23,0.0016755821416154504,0.07315853983163834 +1,NVDA,2023-01-24,0.001689733355306089,0.003744046436622739 +1,NVDA,2023-01-25,0.0016846935031935573,0.0030063872691243887 +1,NVDA,2023-01-26,0.0016534493770450354,0.024486925452947617 +1,NVDA,2023-01-27,0.0016450886614620686,0.028034726157784462 +1,NVDA,2023-01-30,0.0016313537489622831,-0.06088857352733612 +1,NVDA,2023-01-31,0.0013485412346199155,0.01938074454665184 +1,NVDA,2023-02-01,0.0013378316070884466,0.0694945827126503 +1,NVDA,2023-02-02,0.0014030499150976539,0.035922348499298096 +1,NVDA,2023-02-03,0.0014211500529199839,-0.028453925624489784 +1,NVDA,2023-02-06,0.0013408290687948465,-0.0005212471005506814 +1,NVDA,2023-02-07,0.0013591541210189462,0.05012364685535431 +1,NVDA,2023-02-08,0.001436237944290042,0.0014420683728531003 +1,NVDA,2023-02-09,0.001405250164680183,0.005927129182964563 +1,NVDA,2023-02-10,0.0014014480402693152,-0.04918217286467552 +1,NVDA,2023-02-13,0.0012698110658675432,0.024296771734952927 +1,NVDA,2023-02-14,0.0013365066843107343,0.0528733991086483 +1,NVDA,2023-02-15,0.001399935339577496,-0.009052293375134468 +1,NVDA,2023-02-16,0.0014165507163852453,-0.03404683619737625 +1,NVDA,2023-02-17,0.0013435088330879807,-0.028303327038884163 +1,NVDA,2023-02-21,0.0012957515427842736,-0.03487277030944824 +1,NVDA,2023-02-22,0.001115264487452805,0.004781538620591164 +1,NVDA,2023-02-23,0.0009684505057521164,0.13121595978736877 +1,NVDA,2023-02-24,0.0013033781433477998,-0.016102544963359833 +1,NVDA,2023-02-27,0.0013818128500133753,0.009190651588141918 +1,NVDA,2023-02-28,0.0014817670453339815,-0.012201211415231228 +1,NVDA,2023-03-01,0.0015393568901345134,-0.022565042600035667 +1,NVDA,2023-03-02,0.0015247429255396128,0.026777358725667 +1,NVDA,2023-03-03,0.0017174318199977279,0.024405892938375473 +1,NVDA,2023-03-06,0.0018281160155311227,-0.014164205640554428 +1,NVDA,2023-03-07,0.001777489436790347,-0.011187761090695858 +1,NVDA,2023-03-08,0.0016658351523801684,0.037629034370183945 +1,NVDA,2023-03-09,0.001804780913516879,-0.03129391744732857 +1,NVDA,2023-03-10,0.0016454046126455069,-0.020301900804042816 +1,NVDA,2023-03-13,0.001530561363324523,4.360894672572613e-05 +1,NVDA,2023-03-14,0.0014849207364022732,0.046660345047712326 +1,NVDA,2023-03-15,0.0015659774653613567,0.006833725608885288 +1,NVDA,2023-03-16,0.001636449247598648,0.05277596786618233 +1,NVDA,2023-03-17,0.0017690005479380488,0.007178168743848801 +1,NVDA,2023-03-20,0.001757345162332058,0.006779795978218317 +1,NVDA,2023-03-21,0.0017675808630883694,0.011478336527943611 +1,NVDA,2023-03-22,0.0018371327314525843,0.010215163230895996 +1,NVDA,2023-03-23,0.0018198873149231076,0.026949504390358925 +1,NVDA,2023-03-24,0.001827837317250669,-0.015267941169440746 +1,NVDA,2023-03-27,0.0017547360621392727,-0.009304123930633068 +1,NVDA,2023-03-28,0.0017000749940052629,-0.004571354482322931 +1,NVDA,2023-03-29,0.0016791240777820349,0.021501580253243446 +1,NVDA,2023-03-30,0.0017226425698027015,0.014678174629807472 +1,NVDA,2023-03-31,0.0017525636358186603,0.014286060817539692 +1,NVDA,2023-04-03,0.001783023588359356,0.006745434366166592 +1,NVDA,2023-04-04,0.0017640109872445464,-0.018478427082300186 +1,NVDA,2023-04-05,0.0016978189814835787,-0.021055757999420166 +1,NVDA,2023-04-06,0.001554229180328548,0.005786761175841093 +1,NVDA,2023-04-10,0.0015860084677115083,0.019848227500915527 +1,NVDA,2023-04-11,0.0017465146956965327,-0.014978000894188881 +1,NVDA,2023-04-12,0.0017250304808840156,-0.025120684877038002 +1,NVDA,2023-04-13,0.0016833740519359708,-0.0012084428453817964 +1,NVDA,2023-04-14,0.001710221404209733,0.011086015962064266 +1,NVDA,2023-04-17,0.0018681501969695091,0.009077419526875019 +1,NVDA,2023-04-18,0.0019352304516360164,0.024329524487257004 +1,NVDA,2023-04-19,0.001994609832763672,0.009496635757386684 +1,NVDA,2023-04-20,0.0020363498479127884,-0.03005591221153736 +1,NVDA,2023-04-21,0.0019510318525135517,0.0005534669617190957 +1,NVDA,2023-04-24,0.001924994750879705,-0.0028433396946638823 +1,NVDA,2023-04-25,0.0018848547479137778,-0.030068224295973778 +1,NVDA,2023-04-26,0.0016537411138415337,0.026882879436016083 +1,NVDA,2023-04-27,0.0016874512657523155,0.00996656809002161 +1,NVDA,2023-04-28,0.0017529984470456839,0.01902725175023079 +1,NVDA,2023-05-01,0.001880355761386454,0.04098775237798691 +1,NVDA,2023-05-02,0.001963438233360648,-0.024511022493243217 +1,NVDA,2023-05-03,0.001903753960505128,-0.014568530023097992 +1,NVDA,2023-05-04,0.0018420758424326777,-0.008669914677739143 +1,NVDA,2023-05-05,0.0017857925267890096,0.039762016385793686 +1,NVDA,2023-05-08,0.0018844477599486709,0.01628926582634449 +1,NVDA,2023-05-09,0.0019114735769107938,-0.020097171887755394 +1,NVDA,2023-05-10,0.0018227287800982594,0.01093012373894453 +1,NVDA,2023-05-11,0.0018437502440065145,-0.010685049928724766 +1,NVDA,2023-05-12,0.0017910310998558998,-0.008362953551113605 +1,NVDA,2023-05-15,0.0017495735082775354,0.021399427205324173 +1,NVDA,2023-05-16,0.0018100474262610078,0.008940071798861027 +1,NVDA,2023-05-17,0.0018117218278348446,0.03249949589371681 +1,NVDA,2023-05-18,0.0018648107070475817,0.048509202897548676 +1,NVDA,2023-05-19,0.0018642774084582925,-0.01315529178828001 +1,NVDA,2023-05-22,0.0017978382529690862,-0.0028185932897031307 +1,NVDA,2023-05-23,0.0017684282502159476,-0.015776827931404114 +1,NVDA,2023-05-24,0.001723828143440187,-0.004900065716356039 +1,NVDA,2023-05-25,0.0016839149175211787,0.21808820962905884 +1,NVDA,2023-05-26,0.001773700350895524,0.025116106495261192 +1,NVDA,2023-05-30,0.0017380203353241086,0.029474595561623573 +1,NVDA,2023-05-31,0.0016300566494464874,-0.058442372828722 +1,NVDA,2023-06-01,0.0013123798416927457,0.04990462586283684 +1,NVDA,2023-06-02,0.0012561280746012926,-0.011201552115380764 +1,NVDA,2023-06-05,0.001156311365775764,-0.00397465517744422 +1,TSLA,2022-08-17,0.002319489838555455,-0.00840757880359888 +1,TSLA,2022-08-18,0.0023260698653757572,-0.003713104873895645 +1,TSLA,2022-08-19,0.002359376521781087,-0.020694514736533165 +1,TSLA,2022-08-22,0.002291071927174926,-0.023027123883366585 +1,TSLA,2022-08-23,0.0021729408763349056,0.02230781503021717 +1,TSLA,2022-08-24,0.002307110233232379,0.00216777459718287 +1,TSLA,2022-08-25,0.002393564209342003,-0.0034616689663380384 +1,TSLA,2022-08-26,0.0024361624382436275,-0.02732302062213421 +1,TSLA,2022-08-29,0.0023293085396289825,-0.011415490880608559 +1,TSLA,2022-08-30,0.00224252138286829,-0.025315988808870316 +1,TSLA,2022-08-31,0.0021380456164479256,-0.007554668467491865 +1,TSLA,2022-09-01,0.00199682149104774,0.005608200095593929 +1,TSLA,2022-09-02,0.0020430053118616343,-0.02539556659758091 +1,TSLA,2022-09-06,0.0018330656457692385,0.015460425987839699 +1,TSLA,2022-09-07,0.0018822919810190797,0.03325755521655083 +1,TSLA,2022-09-08,0.002089504152536392,0.019408589228987694 +1,TSLA,2022-09-09,0.00233916612342,0.035389244556427 +1,TSLA,2022-09-12,0.0024772246833890676,0.01569315604865551 +1,TSLA,2022-09-13,0.0025616588536649942,-0.041209444403648376 +1,TSLA,2022-09-14,0.0024814517237246037,0.0352458730340004 +1,TSLA,2022-09-15,0.0025164929684251547,0.0037601953372359276 +1,TSLA,2022-09-16,0.0025148610584437847,-0.0013177201617509127 +1,TSLA,2022-09-19,0.0025018765591084957,0.01868053711950779 +1,TSLA,2022-09-20,0.0025217970833182335,-0.0011006681015715003 +1,TSLA,2022-09-21,0.0025100086349993944,-0.026021592319011688 +1,TSLA,2022-09-22,0.0024201972410082817,-0.041438572108745575 +1,TSLA,2022-09-23,0.0022597508504986763,-0.047036655247211456 +1,TSLA,2022-09-26,0.0019270150223746896,0.0024668031837791204 +1,TSLA,2022-09-27,0.001701260800473392,0.02479773759841919 +1,TSLA,2022-09-28,0.0017482595285400748,0.017065662890672684 +1,TSLA,2022-09-29,0.0018598402384668589,-0.07053031027317047 +1,TSLA,2022-09-30,0.0014334265142679214,-0.011097446084022522 +1,TSLA,2022-10-03,0.0011948865139856935,-0.090083546936512 +1,TSLA,2022-10-04,0.0011091491905972362,0.028629185631871223 +1,TSLA,2022-10-05,0.0011978672118857503,-0.03521018475294113 +1,TSLA,2022-10-06,0.0009789831237867475,-0.011191466823220253 +1,TSLA,2022-10-07,0.0008290060213766992,-0.0653311088681221 +1,TSLA,2022-10-10,-0.00036921646096743643,-0.0004932431038469076 +1,TSLA,2022-10-11,-0.0005532990326173604,-0.02940186858177185 +1,TSLA,2022-10-12,-0.0006748628802597523,0.00341221084818244 +1,TSLA,2022-10-13,-0.00022050950792618096,0.020412569865584373 +1,TSLA,2022-10-14,0.0005330072017386556,-0.07845410704612732 +1,TSLA,2022-10-17,-0.0005803257809020579,0.06770743429660797 +1,TSLA,2022-10-18,0.00042711643618531525,0.0038221655413508415 +1,TSLA,2022-10-19,0.0007985454285517335,0.008366694673895836 +1,TSLA,2022-10-20,0.0010244707809761167,-0.06878698617219925 +1,TSLA,2022-10-21,0.0010107788257300854,0.03395945951342583 +1,TSLA,2022-10-24,0.0012043104507029057,-0.014987724833190441 +1,TSLA,2022-10-25,0.0012968629598617554,0.051525212824344635 +1,TSLA,2022-10-26,0.0014807492261752486,0.009931638836860657 +1,TSLA,2022-10-27,0.001659988658502698,0.002001187764108181 +1,TSLA,2022-10-28,0.001851552864536643,0.01512344740331173 +1,TSLA,2022-10-31,0.001968691125512123,-0.004297735169529915 +1,TSLA,2022-11-01,0.0020154775120317936,0.0012298580259084702 +1,TSLA,2022-11-02,0.0020609721541404724,-0.05801089480519295 +1,TSLA,2022-11-03,0.001960607012733817,0.00153385812882334 +1,TSLA,2022-11-04,0.0019442606717348099,-0.03709208220243454 +1,TSLA,2022-11-07,0.001841599470935762,-0.051377009600400925 +1,TSLA,2022-11-08,0.0015887946356087923,-0.029766853898763657 +1,TSLA,2022-11-09,0.0013678972609341145,-0.07436539232730865 +1,TSLA,2022-11-10,0.0007548995781689882,0.07132888585329056 +1,TSLA,2022-11-11,0.0008913695928640664,0.027155201882123947 +1,TSLA,2022-11-14,0.0009727270808070898,-0.0259499941021204 +1,TSLA,2022-11-15,0.0008144170860759914,0.018009159713983536 +1,TSLA,2022-11-16,0.0009456878178752959,-0.039340049028396606 +1,TSLA,2022-11-17,0.0007865903899073601,-0.020266035571694374 +1,TSLA,2022-11-18,-0.0001067171833710745,-0.01640281081199646 +1,TSLA,2022-11-21,-0.0011780863860622048,-0.07082202285528183 +1,TSLA,2022-11-22,-0.0025534587912261486,0.012079065665602684 +1,TSLA,2022-11-23,-0.0023624093737453222,0.07530952990055084 +1,TSLA,2022-11-25,-0.0010587753495201468,-0.001857599476352334 +1,TSLA,2022-11-28,0.00022471549164038152,0.00032805270166136324 +1,TSLA,2022-11-29,0.000998015864752233,-0.011491515673696995 +1,TSLA,2022-11-30,0.0011964659206569195,0.07390252500772476 +1,TSLA,2022-12-01,0.0014885732671245933,0.0 +1,TSLA,2022-12-02,0.0016454386059194803,0.0008214584086090326 +1,TSLA,2022-12-05,0.0018418962135910988,-0.06580521166324615 +1,TSLA,2022-12-06,0.0018372766207903624,-0.01451975479722023 +1,TSLA,2022-12-07,0.0018182347994297743,-0.03267127275466919 +1,TSLA,2022-12-08,0.0017130059422925115,-0.0034533869475126266 +1,TSLA,2022-12-09,0.0016457216115668416,0.031833380460739136 +1,TSLA,2022-12-12,0.0017783914227038622,-0.0647730901837349 +1,TSLA,2022-12-13,0.0015376671217381954,-0.04179828241467476 +1,TSLA,2022-12-14,0.0014431197196245193,-0.02612261101603508 +1,TSLA,2022-12-15,0.0012766045983880758,0.005533102434128523 +1,TSLA,2022-12-16,0.0012649691198021173,-0.048336803913116455 +1,TSLA,2022-12-19,0.0010807221988216043,-0.0023992054630070925 +1,TSLA,2022-12-20,0.0010283507872372866,-0.08396483957767487 +1,TSLA,2022-12-21,0.000490303966216743,-0.0016704490408301353 +1,TSLA,2022-12-22,-0.00011995837849099189,-0.09302312135696411 +1,TSLA,2022-12-23,-0.002036002464592457,-0.017706675454974174 +1,TSLA,2022-12-27,-0.002728983759880066,-0.12113825976848602 +1,TSLA,2022-12-28,-0.0038867543917149305,0.03255326300859451 +1,TSLA,2022-12-29,-0.0035972390323877335,0.07772639393806458 +1,TSLA,2022-12-30,-0.0038565832655876875,0.011102159507572651 +1,TSLA,2023-01-03,-0.0033360193483531475,-0.13058999180793762 +1,TSLA,2023-01-04,-0.00342517695389688,0.049978841096162796 +1,TSLA,2023-01-05,-0.003072245977818966,-0.029469076544046402 +1,TSLA,2023-01-06,-0.0030500099528580904,0.02435215562582016 +1,TSLA,2023-01-09,-0.0026604621671140194,0.05765457823872566 +1,TSLA,2023-01-10,-0.0019044828368350863,-0.0077110277488827705 +1,TSLA,2023-01-11,-0.001327958540059626,0.03610920533537865 +1,TSLA,2023-01-12,-0.00014295900473371148,0.0027554628904908895 +1,TSLA,2023-01-13,0.0006553013809025288,-0.009432465769350529 +1,TSLA,2023-01-17,0.001065578660927713,0.07163646072149277 +1,TSLA,2023-01-18,0.0013134261826053262,-0.020825332030653954 +1,TSLA,2023-01-19,0.0014123236760497093,-0.012580753304064274 +1,TSLA,2023-01-20,0.0015129672829061747,0.0479772724211216 +1,TSLA,2023-01-23,0.0016305597964674234,0.07457364350557327 +1,TSLA,2023-01-24,0.0017403123201802373,0.0009734348277561367 +1,TSLA,2023-01-25,0.0018088885117322206,0.003745795926079154 +1,TSLA,2023-01-26,0.0018378860550001264,0.10406500101089478 +1,TSLA,2023-01-27,0.001905455719679594,0.1043616384267807 +1,TSLA,2023-01-30,0.0019099862547591329,-0.0652657300233841 +1,TSLA,2023-01-31,0.001816819771192968,0.038606639951467514 +1,TSLA,2023-02-01,0.0018042027950286865,0.04619721695780754 +1,TSLA,2023-02-02,0.0018270105356350541,0.03711744397878647 +1,TSLA,2023-02-03,0.0018230985151603818,0.00904165580868721 +1,TSLA,2023-02-06,0.0018067042110487819,0.024849222972989082 +1,TSLA,2023-02-07,0.0018124969210475683,0.010470780543982983 +1,TSLA,2023-02-08,0.0018123439513146877,0.022507838904857635 +1,TSLA,2023-02-09,0.0018082790775224566,0.029516909271478653 +1,TSLA,2023-02-10,0.0017946510342881083,-0.05161833390593529 +1,TSLA,2023-02-13,0.0017080828547477722,-0.011493498459458351 +1,TSLA,2023-02-14,0.0016932337312027812,0.0723780170083046 +1,TSLA,2023-02-15,0.0017031233292073011,0.0235671978443861 +1,TSLA,2023-02-16,0.0017607213230803609,-0.05863124132156372 +1,TSLA,2023-02-17,0.001643105992116034,0.030561678111553192 +1,TSLA,2023-02-21,0.0016991314478218555,-0.05394722521305084 +1,TSLA,2023-02-22,0.001570184133015573,0.01752803660929203 +1,TSLA,2023-02-23,0.0015711244195699692,0.006006057374179363 +1,TSLA,2023-02-24,0.0016466573579236865,-0.026019778102636337 +1,TSLA,2023-02-27,0.0015877926489338279,0.05316324159502983 +1,TSLA,2023-02-28,0.0017392029985785484,-0.009290230460464954 +1,TSLA,2023-03-01,0.001813300303183496,-0.014395089820027351 +1,TSLA,2023-03-02,0.0018516442505642772,-0.060322657227516174 +1,TSLA,2023-03-03,0.00181563978549093,0.03545612841844559 +1,TSLA,2023-03-06,0.0019171003950759768,-0.02032754383981228 +1,TSLA,2023-03-07,0.001904700300656259,-0.03198003023862839 +1,TSLA,2023-03-08,0.001795698655769229,-0.03089156560599804 +1,TSLA,2023-03-09,0.0017316780285909772,-0.05117763951420784 +1,TSLA,2023-03-10,0.0015073230024427176,0.0030026831664144993 +1,TSLA,2023-03-13,0.0014094297075644135,0.005978365428745747 +1,TSLA,2023-03-14,0.001383138936944306,0.04909578338265419 +1,TSLA,2023-03-15,0.0015256116166710854,-0.01545216515660286 +1,TSLA,2023-03-16,0.0015694651519879699,0.0201883427798748 +1,TSLA,2023-03-17,0.0016815091948956251,-0.021963216364383698 +1,TSLA,2023-03-20,0.0017014092300087214,0.017172500491142273 +1,TSLA,2023-03-21,0.001775825978256762,0.07529223710298538 +1,TSLA,2023-03-22,0.0020066015422344208,-0.03308514505624771 +1,TSLA,2023-03-23,0.002033186610788107,0.005582128185778856 +1,TSLA,2023-03-24,0.002091909758746624,-0.009460894390940666 +1,TSLA,2023-03-27,0.0021363841369748116,0.007325624581426382 +1,TSLA,2023-03-28,0.002173089189454913,-0.013753472827374935 +1,TSLA,2023-03-29,0.002170261461287737,0.02448762208223343 +1,TSLA,2023-03-30,0.002307185437530279,0.007194983772933483 +1,TSLA,2023-03-31,0.0022961595095694065,0.060504160821437836 +1,TSLA,2023-04-03,0.0023918799124658108,-0.06311918795108795 +1,TSLA,2023-04-04,0.0022522807121276855,-0.011307735927402973 +1,TSLA,2023-04-05,0.002202358329668641,-0.03734894469380379 +1,TSLA,2023-04-06,0.002033088356256485,-0.0024826324079185724 +1,TSLA,2023-04-10,0.0019886461086571217,-0.0029764510691165924 +1,TSLA,2023-04-11,0.0018425009911879897,0.012281322851777077 +1,TSLA,2023-04-12,0.0018843711586669087,-0.034032631665468216 +1,TSLA,2023-04-13,0.0017570352647453547,0.029256539419293404 +1,TSLA,2023-04-14,0.0018630423583090305,-0.004853036720305681 +1,TSLA,2023-04-17,0.0019028264796361327,0.01096663810312748 +1,TSLA,2023-04-18,0.0020076443906873465,-0.014703352935612202 +1,TSLA,2023-04-19,0.0020594634115695953,-0.02038986049592495 +1,TSLA,2023-04-20,0.0021493046078830957,-0.10254036635160446 +1,TSLA,2023-04-21,0.0017662857426330447,0.01274133287370205 +1,TSLA,2023-04-24,0.0016287292819470167,-0.015444550663232803 +1,TSLA,2023-04-25,0.0014205334009602666,-0.011633104644715786 +1,TSLA,2023-04-26,0.001304949400946498,-0.04402465373277664 +1,TSLA,2023-04-27,0.0009288918226957321,0.04103272035717964 +1,TSLA,2023-04-28,0.0010953795863315463,0.025394247844815254 +1,TSLA,2023-05-01,0.001284844009205699,-0.015208459459245205 +1,TSLA,2023-05-02,0.0012984218774363399,-0.009436987340450287 +1,TSLA,2023-05-03,0.001370501471683383,0.0018696443876251578 +1,TSLA,2023-05-04,0.0014290945837274194,0.00366674130782485 +1,TSLA,2023-05-05,0.0015411203494295478,0.053505491465330124 +1,TSLA,2023-05-08,0.0017340037738904357,0.010121460072696209 +1,TSLA,2023-05-09,0.0019104655366390944,-0.015486902557313442 +1,TSLA,2023-05-10,0.002124093472957611,-0.003612788626924157 +1,TSLA,2023-05-11,0.002259995089843869,0.020786425098776817 +1,TSLA,2023-05-12,0.002364461775869131,-0.024114595726132393 +1,TSLA,2023-05-15,0.0022912658751010895,-0.00975086074322462 +1,TSLA,2023-05-16,0.0022738080006092787,0.0010214088251814246 +1,TSLA,2023-05-17,0.002303807530552149,0.04313493147492409 +1,TSLA,2023-05-18,0.0024047524202615023,0.017277685925364494 +1,TSLA,2023-05-19,0.0024425622541457415,0.01820625551044941 +1,TSLA,2023-05-22,0.0024407249875366688,0.04732459783554077 +1,TSLA,2023-05-23,0.0024827481247484684,-0.016549549996852875 +1,TSLA,2023-05-24,0.0024264510720968246,-0.01556985080242157 +1,TSLA,2023-05-25,0.002352401614189148,0.00854733306914568 +1,TSLA,2023-05-26,0.0023572698701173067,0.04608376696705818 +1,TSLA,2023-05-30,0.002395100425928831,0.0405300073325634 +1,TSLA,2023-05-31,0.002418492455035448,0.013676132075488567 +1,TSLA,2023-06-01,0.0024283064994961023,0.017450978979468346 +1,TSLA,2023-06-02,0.002414899878203869,0.030608082190155983 +1,TSLA,2023-06-05,0.0024209367111325264,0.016868649050593376 +1,GOOGL,2022-08-17,0.001058352179825306,-0.017824245616793633 +1,GOOGL,2022-08-18,0.0009730177116580307,0.005172688513994217 +1,GOOGL,2022-08-19,0.0009623469086363912,-0.024940267205238342 +1,GOOGL,2022-08-22,0.0008004747214727104,-0.025665612891316414 +1,GOOGL,2022-08-23,0.0005788372945971787,-0.0033319026697427034 +1,GOOGL,2022-08-24,0.000555062317289412,-0.0014940829714760184 +1,GOOGL,2022-08-25,0.000491102400701493,0.02570234425365925 +1,GOOGL,2022-08-26,0.0006394214578904212,-0.05561142414808273 +1,GOOGL,2022-08-29,3.679091969388537e-05,-0.008372723124921322 +1,GOOGL,2022-08-30,-0.0006460158620029688,-0.004396445583552122 +1,GOOGL,2022-08-31,-0.0013091090368106961,-0.006631123833358288 +1,GOOGL,2022-09-01,-0.0017306889640167356,0.013947644270956516 +1,GOOGL,2022-09-02,-0.0014719667378813028,-0.017372578382492065 +1,GOOGL,2022-09-06,-0.001594243454746902,-0.009689691476523876 +1,GOOGL,2022-09-07,-0.0017039914382621646,0.02441621758043766 +1,GOOGL,2022-09-08,-0.0012373459758237004,-0.009824228473007679 +1,GOOGL,2022-09-09,-0.000939325662329793,0.020728543400764465 +1,GOOGL,2022-09-12,-9.774167119758204e-05,0.001896064030006528 +1,GOOGL,2022-09-13,0.0004100051592104137,-0.06080499663949013 +1,GOOGL,2022-09-14,-0.0007049137493595481,0.006497208960354328 +1,GOOGL,2022-09-15,-0.000737472262699157,-0.020105401054024696 +1,GOOGL,2022-09-16,-0.001276327413506806,-0.0010695267701521516 +1,GOOGL,2022-09-19,-0.001101594534702599,0.0026229864452034235 +1,GOOGL,2022-09-20,-0.0009098190348595381,-0.01890278421342373 +1,GOOGL,2022-09-21,-0.0013510707067325711,-0.01856154389679432 +1,GOOGL,2022-09-22,-0.0016636039363220334,0.00862528383731842 +1,GOOGL,2022-09-23,-0.001665179617702961,-0.014079230837523937 +1,GOOGL,2022-09-26,-0.0016779076540842652,-0.005789433140307665 +1,GOOGL,2022-09-27,-0.001691071200184524,-0.006848340388387442 +1,GOOGL,2022-09-28,-0.001630032667890191,0.025817766785621643 +1,GOOGL,2022-09-29,-0.0012577931629493833,-0.026638569310307503 +1,GOOGL,2022-09-30,-0.0013299148995429277,-0.01833588443696499 +1,GOOGL,2022-10-03,-0.0014623698079958558,0.03078126348555088 +1,GOOGL,2022-10-04,-0.0010553303873166442,0.029960304498672485 +1,GOOGL,2022-10-05,-0.0003375086816959083,-0.002068389905616641 +1,GOOGL,2022-10-06,0.0003509397793095559,-9.857986879069358e-05 +1,GOOGL,2022-10-07,0.000515454972628504,-0.027388041839003563 +1,GOOGL,2022-10-10,0.0004808102094102651,-0.00834437645971775 +1,GOOGL,2022-10-11,0.00047954136971384287,-0.006972989998757839 +1,GOOGL,2022-10-12,0.0004923680098727345,0.0039027559105306864 +1,GOOGL,2022-10-13,0.0005431098979897797,0.015258156694471836 +1,GOOGL,2022-10-14,0.0006342748529277742,-0.02556123398244381 +1,GOOGL,2022-10-17,0.0005592601955868304,0.03470555692911148 +1,GOOGL,2022-10-18,0.0006916087586432695,0.007970630191266537 +1,GOOGL,2022-10-19,0.0007859846227802336,-0.011377462185919285 +1,GOOGL,2022-10-20,0.000801575486548245,0.0034068331588059664 +1,GOOGL,2022-10-21,0.0008201231248676777,0.01153658889234066 +1,GOOGL,2022-10-24,0.0008612226811237633,0.013651253655552864 +1,GOOGL,2022-10-25,0.0009072316461242735,0.01893775165081024 +1,GOOGL,2022-10-26,0.0009428878547623754,-0.09585607051849365 +1,GOOGL,2022-10-27,0.0008076548692770302,-0.028962578624486923 +1,GOOGL,2022-10-28,0.0007145148701965809,0.043187420815229416 +1,GOOGL,2022-10-31,0.0007492383010685444,-0.018658777698874474 +1,GOOGL,2022-11-01,0.0006919075967743993,-0.04368745535612106 +1,GOOGL,2022-11-02,0.0004956629709340632,-0.03945499658584595 +1,GOOGL,2022-11-03,-3.7972215068293735e-05,-0.04155530035495758 +1,GOOGL,2022-11-04,-0.0013023933861404657,0.03706089407205582 +1,GOOGL,2022-11-07,-0.001035243272781372,0.02182069607079029 +1,GOOGL,2022-11-08,-0.0007547728600911796,0.004622661508619785 +1,GOOGL,2022-11-09,-0.00031593788298778236,-0.017932560294866562 +1,GOOGL,2022-11-10,-0.0004411014961078763,0.07307664304971695 +1,GOOGL,2022-11-11,0.00014298202586360276,0.025953704491257668 +1,GOOGL,2022-11-14,0.0004296344122849405,-0.007391858845949173 +1,GOOGL,2022-11-15,0.0005571937072090805,0.028229109942913055 +1,GOOGL,2022-11-16,0.0006622371729463339,0.004156309645622969 +1,GOOGL,2022-11-17,0.0007336973794735968,-0.004969427362084389 +1,GOOGL,2022-11-18,0.0007791767129674554,-0.009499921463429928 +1,GOOGL,2022-11-21,0.0008034176426008344,-0.0189614687114954 +1,GOOGL,2022-11-22,0.0008087822352536023,0.015053654089570045 +1,GOOGL,2022-11-23,0.0008451244793832302,0.014424051158130169 +1,GOOGL,2022-11-25,0.0008436822681687772,-0.010208417661488056 +1,GOOGL,2022-11-28,0.000833530502859503,-0.014573135413229465 +1,GOOGL,2022-11-29,0.0008126142784021795,-0.008993900381028652 +1,GOOGL,2022-11-30,0.0007829364622011781,0.059146616607904434 +1,GOOGL,2022-12-01,0.0008453552727587521,0.0 +1,GOOGL,2022-12-02,0.0008437790675088763,-0.005461044609546661 +1,GOOGL,2022-12-05,0.0008528545149601996,-0.00960397906601429 +1,GOOGL,2022-12-06,0.0008408063440583646,-0.025451775640249252 +1,GOOGL,2022-12-07,0.0007502539665438235,-0.021259598433971405 +1,GOOGL,2022-12-08,0.0006525288918055594,-0.013040158897638321 +1,GOOGL,2022-12-09,0.0005628220969811082,-0.009435161016881466 +1,GOOGL,2022-12-12,0.0005601823213510215,0.005157453939318657 +1,GOOGL,2022-12-13,0.0006705564446747303,0.024559346958994865 +1,GOOGL,2022-12-14,0.0007501465734094381,-0.0058733439072966576 +1,GOOGL,2022-12-15,0.0007798733422532678,-0.04529334604740143 +1,GOOGL,2022-12-16,0.0005928679602220654,-0.006625637412071228 +1,GOOGL,2022-12-19,0.0005226425710134208,-0.020370010286569595 +1,GOOGL,2022-12-20,0.00038905919063836336,0.006536657456308603 +1,GOOGL,2022-12-21,0.000380896293791011,0.0062710875645279884 +1,GOOGL,2022-12-22,0.0003967552038375288,-0.020526321604847908 +1,GOOGL,2022-12-23,-6.75118135404773e-05,0.016611631959676743 +1,GOOGL,2022-12-27,0.00010824263154063374,-0.02083655446767807 +1,GOOGL,2022-12-28,-0.0002551404759287834,-0.015801090747117996 +1,GOOGL,2022-12-29,-0.0008969599730335176,0.027857549488544464 +1,GOOGL,2022-12-30,-0.00046726211439818144,-0.0024901707656681538 +1,GOOGL,2023-01-03,-8.777707989793271e-05,0.010036666877567768 +1,GOOGL,2023-01-04,0.00043546914821490645,-0.011738304048776627 +1,GOOGL,2023-01-05,0.0005286751547828317,-0.021575355902314186 +1,GOOGL,2023-01-06,0.0005337972543202341,0.01313856802880764 +1,GOOGL,2023-01-09,0.0006436480907723308,0.007755286525934935 +1,GOOGL,2023-01-10,0.0007470686105079949,0.004534215200692415 +1,GOOGL,2023-01-11,0.0008247857913374901,0.034459345042705536 +1,GOOGL,2023-01-12,0.0009264907566830516,-0.004270571283996105 +1,GOOGL,2023-01-13,0.0009794352808967233,0.010805037803947926 +1,GOOGL,2023-01-17,0.0011007311986759305,-0.00905077438801527 +1,GOOGL,2023-01-18,0.0011167709017172456,-0.001863815588876605 +1,GOOGL,2023-01-19,0.0011159158311784267,0.020959533751010895 +1,GOOGL,2023-01-20,0.0011269471142441034,0.052034616470336914 +1,GOOGL,2023-01-23,0.0011357141193002462,0.017896488308906555 +1,GOOGL,2023-01-24,0.0011268238304182887,-0.02116643823683262 +1,GOOGL,2023-01-25,0.001100382418371737,-0.025711672380566597 +1,GOOGL,2023-01-26,0.001057991641573608,0.023867566138505936 +1,GOOGL,2023-01-27,0.001077157212421298,0.01879277639091015 +1,GOOGL,2023-01-30,0.0010862177005037665,-0.02475806325674057 +1,GOOGL,2023-01-31,0.0010443938663229346,0.019410155713558197 +1,GOOGL,2023-02-01,0.0010570110753178596,0.015958528965711594 +1,GOOGL,2023-02-02,0.0010575024643912911,0.07026010006666183 +1,GOOGL,2023-02-03,0.0010965641122311354,-0.02785813994705677 +1,GOOGL,2023-02-06,0.0010673680808395147,-0.01810522936284542 +1,GOOGL,2023-02-07,0.0010388250229880214,0.045034635812044144 +1,GOOGL,2023-02-08,0.0010640773689374328,-0.07994198054075241 +1,GOOGL,2023-02-09,0.0008843340328894556,-0.04486818239092827 +1,GOOGL,2023-02-10,0.0006577637977898121,-0.004641865845769644 +1,GOOGL,2023-02-13,0.0004900600761175156,0.00042297542677260935 +1,GOOGL,2023-02-14,0.0004196623631287366,0.0007396547589451075 +1,GOOGL,2023-02-15,0.0003922392788808793,0.023589354008436203 +1,GOOGL,2023-02-16,0.00047223040019162,-0.014861231669783592 +1,GOOGL,2023-02-17,0.0004610980104189366,-0.012219831347465515 +1,GOOGL,2023-02-21,0.00045244480133987963,-0.02750782109797001 +1,GOOGL,2023-02-22,0.00016171149036381394,-0.001526318141259253 +1,GOOGL,2023-02-23,0.00013777690764982253,-0.00832714419811964 +1,GOOGL,2023-02-24,0.00011557382094906643,-0.01955399662256241 +1,GOOGL,2023-02-27,-0.00020292292174417526,0.008268308825790882 +1,GOOGL,2023-02-28,3.3465668821008876e-05,0.002111950656399131 +1,GOOGL,2023-03-01,0.0002708827378228307,0.0033254921436309814 +1,GOOGL,2023-03-02,0.0004085278487764299,0.017986822873353958 +1,GOOGL,2023-03-03,0.0005513100186362863,0.017776021733880043 +1,GOOGL,2023-03-06,0.0006499242153950036,0.015679901465773582 +1,GOOGL,2023-03-07,0.0007586753345094621,-0.013440119102597237 +1,GOOGL,2023-03-08,0.0008104435401037335,0.004146615043282509 +1,GOOGL,2023-03-09,0.0008876736392267048,-0.02069014310836792 +1,GOOGL,2023-03-10,0.0008925714064389467,-0.018475541844964027 +1,GOOGL,2023-03-13,0.0008277138113044202,0.005282234400510788 +1,GOOGL,2023-03-14,0.000831039622426033,0.030908172950148582 +1,GOOGL,2023-03-15,0.0009140395559370518,0.022517725825309753 +1,GOOGL,2023-03-16,0.001019537216052413,0.042871780693531036 +1,GOOGL,2023-03-17,0.0010837236186489463,0.012875291518867016 +1,GOOGL,2023-03-20,0.0010953187011182308,-0.003944001160562038 +1,GOOGL,2023-03-21,0.0010830610990524292,0.03590172156691551 +1,GOOGL,2023-03-22,0.0010978266363963485,-0.014883373863995075 +1,GOOGL,2023-03-23,0.001041287207044661,0.021343547850847244 +1,GOOGL,2023-03-24,0.0010415700962767005,-0.0015161405317485332 +1,GOOGL,2023-03-27,0.0009956387802958488,-0.028669778257608414 +1,GOOGL,2023-03-28,0.0009311747271567583,-0.014054706320166588 +1,GOOGL,2023-03-29,0.0008798213093541563,0.0035568736493587494 +1,GOOGL,2023-03-30,0.000878205755725503,-0.004943653009831905 +1,GOOGL,2023-03-31,0.0008723114151507616,0.027760425582528114 +1,GOOGL,2023-04-03,0.0009353333152830601,0.006055121775716543 +1,GOOGL,2023-04-04,0.0009915429400280118,0.0034437209833413363 +1,GOOGL,2023-04-05,0.0010349387302994728,-0.002390173263847828 +1,GOOGL,2023-04-06,0.0010048545664176345,0.037112560123205185 +1,GOOGL,2023-04-10,0.0010880099143832922,-0.01843108981847763 +1,GOOGL,2023-04-11,0.0010740122525021434,-0.010293249972164631 +1,GOOGL,2023-04-12,0.0010680307168513536,-0.006762312259525061 +1,GOOGL,2023-04-13,0.0010773433605208993,0.026313604786992073 +1,GOOGL,2023-04-14,0.0011093737557530403,0.013315124437212944 +1,GOOGL,2023-04-17,0.0011479867389425635,-0.026998620480298996 +1,GOOGL,2023-04-18,0.001093178754672408,-0.01396893709897995 +1,GOOGL,2023-04-19,0.0010557901114225388,-0.0030668701510876417 +1,GOOGL,2023-04-20,0.001065568532794714,0.010598262771964073 +1,GOOGL,2023-04-21,0.00109441252425313,0.001139104482717812 +1,GOOGL,2023-04-24,0.0010929660638794303,0.005298440810292959 +1,GOOGL,2023-04-25,0.0010991113958880305,-0.020208533853292465 +1,GOOGL,2023-04-26,0.0009909197688102722,-0.001349097234196961 +1,GOOGL,2023-04-27,0.0009260430233553052,0.03672920539975166 +1,GOOGL,2023-04-28,0.0010588085278868675,-0.002326197223737836 +1,GOOGL,2023-05-01,0.0010871983831748366,-0.0013051327550783753 +1,GOOGL,2023-05-02,0.0010927703697234392,-0.017692947760224342 +1,GOOGL,2023-05-03,0.0010323692113161087,0.000854261452332139 +1,GOOGL,2023-05-04,0.0010228289756923914,-0.006853877566754818 +1,GOOGL,2023-05-05,0.0009886522311717272,0.008370522409677505 +1,GOOGL,2023-05-08,0.0010511210421100259,0.020625019446015358 +1,GOOGL,2023-05-09,0.0011302793864160776,-0.0039047745522111654 +1,GOOGL,2023-05-10,0.0011174526298418641,0.040169857442379 +1,GOOGL,2023-05-11,0.0011573482770472765,0.04222762957215309 +1,GOOGL,2023-05-12,0.0011722308117896318,0.008031630888581276 +1,GOOGL,2023-05-15,0.0011617077980190516,-0.008546529337763786 +1,GOOGL,2023-05-16,0.0011269620154052973,0.025423014536499977 +1,GOOGL,2023-05-17,0.0011259696912020445,0.011067270301282406 +1,GOOGL,2023-05-18,0.0011083697900176048,0.01633406989276409 +1,GOOGL,2023-05-19,0.0010954176541417837,-0.0005700934561900795 +1,GOOGL,2023-05-22,0.0010498787742108107,0.01848231814801693 +1,GOOGL,2023-05-23,0.001031039748340845,-0.020112905651330948 +1,GOOGL,2023-05-24,0.000963430677074939,-0.013636939227581024 +1,GOOGL,2023-05-25,0.0008890371536836028,0.021115470677614212 +1,GOOGL,2023-05-26,0.0008894115453585982,0.009109686128795147 +1,GOOGL,2023-05-30,0.0008754266309551895,-0.00757226999849081 +1,GOOGL,2023-05-31,0.0008463975391350687,-0.006489655934274197 +1,GOOGL,2023-06-01,0.0008196179405786097,0.006894000340253115 +1,GOOGL,2023-06-02,0.0008466527797281742,0.007649237755686045 +1,GOOGL,2023-06-05,0.0009720455855131149,0.01069091446697712 +1,AMZN,2022-08-17,0.000815235311165452,-0.01868426240980625 +1,AMZN,2022-08-18,0.0007477314211428165,0.0014064485440030694 +1,AMZN,2022-08-19,0.0007390335667878389,-0.029018592089414597 +1,AMZN,2022-08-22,0.0005412089521996677,-0.036917027086019516 +1,AMZN,2022-08-23,-0.00010520513751544058,0.002998007694259286 +1,AMZN,2022-08-24,-0.00025315835955552757,0.0013462565839290619 +1,AMZN,2022-08-25,-9.353991117677651e-06,0.025676457211375237 +1,AMZN,2022-08-26,0.0005548293120227754,-0.04873552545905113 +1,AMZN,2022-08-29,-0.0002973034861497581,-0.00736939487978816 +1,AMZN,2022-08-30,-0.0005535681266337633,-0.008200553245842457 +1,AMZN,2022-08-31,-0.0007428170647472143,-0.015342759899795055 +1,AMZN,2022-09-01,-0.0010882989736273885,0.008248627185821533 +1,AMZN,2022-09-02,-0.0008655391866341233,-0.0024282122030854225 +1,AMZN,2022-09-06,-0.000773489533457905,-0.011040262877941132 +1,AMZN,2022-09-07,-0.0010420373873785138,0.026371851563453674 +1,AMZN,2022-09-08,-0.0005028233281336725,0.0026225359179079533 +1,AMZN,2022-09-09,-1.7321293853456154e-05,0.026228245347738266 +1,AMZN,2022-09-12,0.0005555336247198284,0.023581046611070633 +1,AMZN,2022-09-13,0.0007687900215387344,-0.07318946719169617 +1,AMZN,2022-09-14,0.0005206007626838982,0.01354920119047165 +1,AMZN,2022-09-15,0.0006064474582672119,-0.01781630329787731 +1,AMZN,2022-09-16,0.0005056780064478517,-0.022017622366547585 +1,AMZN,2022-09-19,7.17599323252216e-05,0.009106028825044632 +1,AMZN,2022-09-20,0.00026397730107419193,-0.020012831315398216 +1,AMZN,2022-09-21,-0.0003658290079329163,-0.03032676689326763 +1,AMZN,2022-09-22,-0.0012772256741300225,-0.010430481284856796 +1,AMZN,2022-09-23,-0.0017610493814572692,-0.030553234741091728 +1,AMZN,2022-09-26,-0.0017154216766357422,0.011968891136348248 +1,AMZN,2022-09-27,-0.0018654877785593271,-0.006447119638323784 +1,AMZN,2022-09-28,-0.0019095498137176037,0.03098086453974247 +1,AMZN,2022-09-29,-0.0015046364860609174,-0.027577873319387436 +1,AMZN,2022-09-30,-0.0016177771613001823,-0.015803690999746323 +1,AMZN,2022-10-03,-0.0017456747591495514,0.025167331099510193 +1,AMZN,2022-10-04,-0.0014716931618750095,0.043978892266750336 +1,AMZN,2022-10-05,-0.0007541959057562053,-0.0011568287154659629 +1,AMZN,2022-10-06,1.7621327060624026e-05,-0.005388563498854637 +1,AMZN,2022-10-07,0.0005025338032282889,-0.04888996481895447 +1,AMZN,2022-10-10,-0.00014200790610630065,-0.007799184415489435 +1,AMZN,2022-10-11,-0.0002732355787884444,-0.012927389703691006 +1,AMZN,2022-10-12,-0.0004293599631637335,0.006130377762019634 +1,AMZN,2022-10-13,-0.00023978450917638838,-0.0032826426904648542 +1,AMZN,2022-10-14,0.00014822650700807571,-0.05132601037621498 +1,AMZN,2022-10-17,-0.0009495080448687077,0.062460821121931076 +1,AMZN,2022-10-18,-0.00018846910097636282,0.022334186360239983 +1,AMZN,2022-10-19,0.0005101599381305277,-0.011148202233016491 +1,AMZN,2022-10-20,0.000631409406196326,0.0015630456618964672 +1,AMZN,2022-10-21,0.0006983335479162633,0.0347052738070488 +1,AMZN,2022-10-24,0.0008355200407095253,0.004181656986474991 +1,AMZN,2022-10-25,0.0009185167145915329,0.006488658022135496 +1,AMZN,2022-10-26,0.0009770359611138701,-0.04182438552379608 +1,AMZN,2022-10-27,0.0009556661243550479,-0.04148511588573456 +1,AMZN,2022-10-28,0.0008485899888910353,-0.07046806067228317 +1,AMZN,2022-10-31,0.0005868853186257184,-0.009424419142305851 +1,AMZN,2022-11-01,5.0549999286886305e-05,-0.056733593344688416 +1,AMZN,2022-11-02,-0.0012330823810771108,-0.049451589584350586 +1,AMZN,2022-11-03,-0.0019925509113818407,-0.03109058178961277 +1,AMZN,2022-11-04,-0.0014893242623656988,0.018638217821717262 +1,AMZN,2022-11-07,-0.0016124111134558916,-0.004958465229719877 +1,AMZN,2022-11-08,-0.0015748157165944576,-0.006093812640756369 +1,AMZN,2022-11-09,-0.0015852147480472922,-0.04361358657479286 +1,AMZN,2022-11-10,-0.001292116241529584,0.11491534858942032 +1,AMZN,2022-11-11,-0.0014545946614816785,0.04214993119239807 +1,AMZN,2022-11-14,-0.0017019464867189527,-0.023084154352545738 +1,AMZN,2022-11-15,-0.0018168046372011304,0.0045586321502923965 +1,AMZN,2022-11-16,-0.0017958314856514335,-0.018566275015473366 +1,AMZN,2022-11-17,-0.0015399130061268806,-0.023650676012039185 +1,AMZN,2022-11-18,-0.0014772363938391209,-0.00751365115866065 +1,AMZN,2022-11-21,-0.0014014063635841012,-0.01800692081451416 +1,AMZN,2022-11-22,-0.0014058889355510473,0.007971580140292645 +1,AMZN,2022-11-23,-0.001150650205090642,0.00992908701300621 +1,AMZN,2022-11-25,-0.0008119437261484563,-0.007678331341594458 +1,AMZN,2022-11-28,-0.00040210390579886734,0.005764248315244913 +1,AMZN,2022-11-29,-3.6735760659212247e-05,-0.0164193082600832 +1,AMZN,2022-11-30,0.00013325249892659485,0.04361405596137047 +1,AMZN,2022-12-01,0.0005133395316079259,-0.010831192135810852 +1,AMZN,2022-12-02,0.00056370411766693,-0.014449470676481724 +1,AMZN,2022-12-05,0.0005728169344365597,-0.03370736166834831 +1,AMZN,2022-12-06,0.00016895431326702237,-0.030795717611908913 +1,AMZN,2022-12-07,-0.0005533575313165784,0.002376766176894307 +1,AMZN,2022-12-08,-0.0006553073180839419,0.021140536293387413 +1,AMZN,2022-12-09,-0.0002547872136346996,-0.014043946750462055 +1,AMZN,2022-12-12,-7.954498869366944e-05,0.01625516451895237 +1,AMZN,2022-12-13,0.0005410527228377759,0.021198289468884468 +1,AMZN,2022-12-14,0.000678140320815146,-0.009887579828500748 +1,AMZN,2022-12-15,0.0007614494534209371,-0.034775540232658386 +1,AMZN,2022-12-16,0.000696198723744601,-0.006692740600556135 +1,AMZN,2022-12-19,0.0006663312669843435,-0.034035030752420425 +1,AMZN,2022-12-20,0.0004459784540813416,0.0031744693405926228 +1,AMZN,2022-12-21,0.00029502384131774306,0.01837681606411934 +1,AMZN,2022-12-22,0.0005274701397866011,-0.034947220236063004 +1,AMZN,2022-12-23,-1.155529753305018e-05,0.017274437472224236 +1,AMZN,2022-12-27,7.918469054857269e-05,-0.026265688240528107 +1,AMZN,2022-12-28,-0.00037048186641186476,-0.014800721779465675 +1,AMZN,2022-12-29,-0.0008726014057174325,0.028435656800866127 +1,AMZN,2022-12-30,-0.0005107655888423324,-0.0021405681036412716 +1,AMZN,2023-01-03,-0.00018927162454929203,0.02143527753651142 +1,AMZN,2023-01-04,0.00044243026059120893,-0.007955122739076614 +1,AMZN,2023-01-05,0.0006056943675503135,-0.02401157282292843 +1,AMZN,2023-01-06,0.0006363088032230735,0.03499173745512962 +1,AMZN,2023-01-09,0.0007596637587994337,0.014760401099920273 +1,AMZN,2023-01-10,0.0008566592005081475,0.028326693922281265 +1,AMZN,2023-01-11,0.0009385121520608664,0.05645956099033356 +1,AMZN,2023-01-12,0.0009844814194366336,0.001891157473437488 +1,AMZN,2023-01-13,0.0009871178772300482,0.029476316645741463 +1,AMZN,2023-01-17,0.0010007907403632998,-0.021322326734662056 +1,AMZN,2023-01-18,0.000977494870312512,-0.0061616189777851105 +1,AMZN,2023-01-19,0.0009473027312196791,-0.018822578713297844 +1,AMZN,2023-01-20,0.000898952130228281,0.0374002605676651 +1,AMZN,2023-01-23,0.0009133414714597166,0.0027724681422114372 +1,AMZN,2023-01-24,0.0009127079974859953,-0.012381472624838352 +1,AMZN,2023-01-25,0.0009074424160644412,0.008888953365385532 +1,AMZN,2023-01-26,0.0009078842704184353,0.020774686709046364 +1,AMZN,2023-01-27,0.0009414073429070413,0.02998335100710392 +1,AMZN,2023-01-30,0.0009556319564580917,-0.016667822375893593 +1,AMZN,2023-01-31,0.0009368705214001238,0.025335155427455902 +1,AMZN,2023-02-01,0.0009682417148724198,0.019397614523768425 +1,AMZN,2023-02-02,0.0009700347436591983,0.07120315730571747 +1,AMZN,2023-02-03,0.0010130612645298243,-0.08808283507823944 +1,AMZN,2023-02-06,0.0009228229173459113,-0.011772272177040577 +1,AMZN,2023-02-07,0.0009063073084689677,-0.0006852973019704223 +1,AMZN,2023-02-08,0.0009086508071050048,-0.020380578935146332 +1,AMZN,2023-02-09,0.000878221879247576,-0.018256649374961853 +1,AMZN,2023-02-10,0.0007876405725255609,-0.006433489266782999 +1,AMZN,2023-02-13,0.0007089928258210421,0.019579628482460976 +1,AMZN,2023-02-14,0.0007703315932303667,0.0016060636844485998 +1,AMZN,2023-02-15,0.0007585774292238057,0.014537811279296875 +1,AMZN,2023-02-16,0.0008351245778612792,-0.030206521973013878 +1,AMZN,2023-02-17,0.0007695028325542808,-0.009726256132125854 +1,AMZN,2023-02-21,0.0007741849403828382,-0.027324624359607697 +1,AMZN,2023-02-22,0.0006802091957069933,0.012712248601019382 +1,AMZN,2023-02-23,0.0007105563418008387,0.00031312330975197256 +1,AMZN,2023-02-24,0.0007522511878050864,-0.024509992450475693 +1,AMZN,2023-02-27,0.0007036454626359046,0.0027769124135375023 +1,AMZN,2023-02-28,0.0007318492862395942,0.005000289063900709 +1,AMZN,2023-03-01,0.0007755495607852936,-0.022103959694504738 +1,AMZN,2023-03-02,0.0007191906915977597,-0.0004340848245192319 +1,AMZN,2023-03-03,0.0007640224066562951,0.029623128473758698 +1,AMZN,2023-03-06,0.0008646136848255992,-0.012192056514322758 +1,AMZN,2023-03-07,0.0008219387382268906,-0.0021355794742703438 +1,AMZN,2023-03-08,0.0008080021943897009,0.003947251010686159 +1,AMZN,2023-03-09,0.0008388534188270569,-0.017941053956747055 +1,AMZN,2023-03-10,0.0007943719974718988,-0.01661418192088604 +1,AMZN,2023-03-13,0.0006675298791378736,0.01856350526213646 +1,AMZN,2023-03-14,0.0007940656505525112,0.026161301881074905 +1,AMZN,2023-03-15,0.0009235760080628097,0.013816419057548046 +1,AMZN,2023-03-16,0.0010549037251621485,0.039140790700912476 +1,AMZN,2023-03-17,0.0011213262332603335,-0.010955474339425564 +1,AMZN,2023-03-20,0.0011706654913723469,-0.012610742822289467 +1,AMZN,2023-03-21,0.001173220225609839,0.029247764497995377 +1,AMZN,2023-03-22,0.0012337729567661881,-0.019166747108101845 +1,AMZN,2023-03-23,0.001182498992420733,0.00010133362957276404 +1,AMZN,2023-03-24,0.0011680620955303311,-0.005893147084861994 +1,AMZN,2023-03-27,0.0011369520798325539,-0.0009175342274829745 +1,AMZN,2023-03-28,0.0011106145102530718,-0.008193440735340118 +1,AMZN,2023-03-29,0.0010748760541900992,0.030484938994050026 +1,AMZN,2023-03-30,0.001156741171143949,0.01730574667453766 +1,AMZN,2023-03-31,0.0012001435970887542,0.012567761354148388 +1,AMZN,2023-04-03,0.001237233285792172,-0.008556175045669079 +1,AMZN,2023-04-04,0.0012173049617558718,0.014925585128366947 +1,AMZN,2023-04-05,0.001242024009115994,-0.027799874544143677 +1,AMZN,2023-04-06,0.0011448577279224992,0.009450741112232208 +1,AMZN,2023-04-10,0.0011807573027908802,0.0010772229870781302 +1,AMZN,2023-04-11,0.0011985715245828032,-0.022268226370215416 +1,AMZN,2023-04-12,0.0011022962862625718,-0.021138550713658333 +1,AMZN,2023-04-13,0.0010155853815376759,0.045655425637960434 +1,AMZN,2023-04-14,0.0011517514940351248,0.0010736481053754687 +1,AMZN,2023-04-17,0.0012055605184286833,0.0022411285899579525 +1,AMZN,2023-04-18,0.0012365399161353707,-0.004291801247745752 +1,AMZN,2023-04-19,0.0012194153387099504,0.01936168782413006 +1,AMZN,2023-04-20,0.0012716790661215782,-0.004709109663963318 +1,AMZN,2023-04-21,0.001271322718821466,0.02989264391362667 +1,AMZN,2023-04-24,0.001293999725021422,-0.007036665920168161 +1,AMZN,2023-04-25,0.0012584199430420995,-0.034872766584157944 +1,AMZN,2023-04-26,0.0011082050623372197,0.023224398493766785 +1,AMZN,2023-04-27,0.001125573879107833,0.0450727716088295 +1,AMZN,2023-04-28,0.0012047610944136977,-0.040605779737234116 +1,AMZN,2023-05-01,0.001106566982343793,-0.03277396038174629 +1,AMZN,2023-05-02,0.000989229534752667,0.015363918617367744 +1,AMZN,2023-05-03,0.001018153503537178,0.00019301690917927772 +1,AMZN,2023-05-04,0.0009638696210458875,0.003371045459061861 +1,AMZN,2023-05-05,0.0009677900816313922,0.015835527330636978 +1,AMZN,2023-05-08,0.0010372604010626674,0.0016076239990070462 +1,AMZN,2023-05-09,0.0010981536470353603,0.0074370866641402245 +1,AMZN,2023-05-10,0.0011930960463359952,0.03293503448367119 +1,AMZN,2023-05-11,0.0012880177237093449,0.0178985558450222 +1,AMZN,2023-05-12,0.0013164461124688387,-0.017263494431972504 +1,AMZN,2023-05-15,0.0012841399293392897,0.008489121682941914 +1,AMZN,2023-05-16,0.0012848344631493092,0.01959105022251606 +1,AMZN,2023-05-17,0.001296146772801876,0.01834912598133087 +1,AMZN,2023-05-18,0.0012972684344276786,0.022684486582875252 +1,AMZN,2023-05-19,0.0012937251012772322,-0.016211971640586853 +1,AMZN,2023-05-22,0.0012492791283875704,-0.010723944753408432 +1,AMZN,2023-05-23,0.0012036137050017715,-0.0001739501894917339 +1,AMZN,2023-05-24,0.0011886714491993189,0.01518974732607603 +1,AMZN,2023-05-25,0.001209837500937283,-0.015102769248187542 +1,AMZN,2023-05-26,0.0011914080241695046,0.04347586631774902 +1,AMZN,2023-05-30,0.0012054055696353316,0.012822303920984268 +1,AMZN,2023-05-31,0.001209633657708764,-0.008916851133108139 +1,AMZN,2023-06-01,0.001162493834272027,0.017999211326241493 +1,AMZN,2023-06-02,0.0011788299307227135,0.01198300626128912 +1,AMZN,2023-06-05,0.0011747459648177028,0.008415221236646175 +1,META,2022-08-17,0.001323455129750073,-0.026079460978507996 +1,META,2022-08-18,0.0012754449853673577,-0.0010871972190216184 +1,META,2022-08-19,0.0012679699575528502,-0.03911538049578667 +1,META,2022-08-22,0.0011401430238038301,-0.029668986797332764 +1,META,2022-08-23,0.0009269727161154151,-0.011969533748924732 +1,META,2022-08-24,0.0007277637487277389,0.013256770558655262 +1,META,2022-08-25,0.0007312781526707113,0.033252015709877014 +1,META,2022-08-26,0.0008452633628621697,-0.04235884174704552 +1,META,2022-08-29,0.00034358614357188344,-0.016264580190181732 +1,META,2022-08-30,-0.00023787631653249264,-0.01270825695246458 +1,META,2022-08-31,-0.0005481677944771945,0.03605617582798004 +1,META,2022-09-01,0.00020708967349492013,0.014804331585764885 +1,META,2022-09-02,0.0005841967067681253,-0.03095308318734169 +1,META,2022-09-06,0.000527911470271647,-0.01116502657532692 +1,META,2022-09-07,0.0004640562110580504,0.011601501144468784 +1,META,2022-09-08,0.0006135525763966143,0.010358250699937344 +1,META,2022-09-09,0.0007963106036186218,0.04281922057271004 +1,META,2022-09-12,0.0010257504181936383,-0.0011237631551921368 +1,META,2022-09-13,0.001171328010968864,-0.09837477654218674 +1,META,2022-09-14,0.0008392620948143303,-0.010899675078690052 +1,META,2022-09-15,0.0007222230196930468,-0.012756824493408203 +1,META,2022-09-16,0.00024467892944812775,-0.022039880976080894 +1,META,2022-09-19,-0.00011447972792666405,0.011756622232496738 +1,META,2022-09-20,-0.00022025460202712566,-0.013124693185091019 +1,META,2022-09-21,-0.0009506809874437749,-0.02755109593272209 +1,META,2022-09-22,-0.001918597030453384,0.0049135563895106316 +1,META,2022-09-23,-0.002002087654545903,-0.01701861247420311 +1,META,2022-09-26,-0.0021298909559845924,-0.029195088893175125 +1,META,2022-09-27,-0.0021558331791311502,-0.014551235362887383 +1,META,2022-09-28,-0.0020811762660741806,0.05225666984915733 +1,META,2022-09-29,-0.0019691933412104845,-0.0374118909239769 +1,META,2022-09-30,-0.0020398639608174562,-0.005366131663322449 +1,META,2022-10-03,-0.002035262994468212,0.021365074440836906 +1,META,2022-10-04,-0.0016569626750424504,0.01197636965662241 +1,META,2022-10-05,-0.0010625168215483427,-0.009310259483754635 +1,META,2022-10-06,-0.0008872905746102333,0.0006471557426266372 +1,META,2022-10-07,-0.0005311095155775547,-0.04125063121318817 +1,META,2022-10-10,-0.0010745978215709329,0.002544499933719635 +1,META,2022-10-11,-0.0009765533613972366,-0.040031109005212784 +1,META,2022-10-12,-0.0009610803099349141,-0.008123761042952538 +1,META,2022-10-13,-0.0010718274861574173,0.021646222099661827 +1,META,2022-10-14,-0.000557944702450186,-0.02746705524623394 +1,META,2022-10-17,-0.0008813929744064808,0.05584263056516647 +1,META,2022-10-18,0.0002435045753372833,-0.009293769486248493 +1,META,2022-10-19,0.0006342375418171287,0.003232585731893778 +1,META,2022-10-20,0.0007750744116492569,-0.012841952964663506 +1,META,2022-10-21,0.0008191412780433893,-0.011623524129390717 +1,META,2022-10-24,0.0008401054656133056,-0.002233326667919755 +1,META,2022-10-25,0.0008398852660320699,0.05831856653094292 +1,META,2022-10-26,0.0010145207634195685,-0.05754779651761055 +1,META,2022-10-27,0.001020224066451192,-0.28179386258125305 +1,META,2022-10-28,-0.0018259321805089712,0.012782806530594826 +1,META,2022-10-31,-0.002176691312342882,-0.06281930953264236 +1,META,2022-11-01,-0.0014654751867055893,0.02166123129427433 +1,META,2022-11-02,-0.001360889058560133,-0.05018824711441994 +1,META,2022-11-03,-0.001015006098896265,-0.018166903406381607 +1,META,2022-11-04,-0.0005808369605802,0.020924415439367294 +1,META,2022-11-07,-0.0008357681799679995,0.06327115744352341 +1,META,2022-11-08,-0.001098712789826095,-0.00258822669275105 +1,META,2022-11-09,-0.0014090965269133449,0.050531260669231415 +1,META,2022-11-10,-0.0017283533234149218,0.09757418930530548 +1,META,2022-11-11,-0.0021857470273971558,0.01022733561694622 +1,META,2022-11-14,-0.0018894207896664739,0.010561604984104633 +1,META,2022-11-15,-0.0013477288885042071,0.024731138721108437 +1,META,2022-11-16,-0.0007628837483935058,-0.03343628719449043 +1,META,2022-11-17,-0.00042226348887197673,-0.0158452820032835 +1,META,2022-11-18,-0.0001269766071345657,0.005369305610656738 +1,META,2022-11-21,0.00022013128909748048,-0.019738448783755302 +1,META,2022-11-22,0.0005349086131900549,0.014279570430517197 +1,META,2022-11-23,0.0006932471296750009,0.007152982521802187 +1,META,2022-11-25,0.0007682298310101032,-0.007422364316880703 +1,META,2022-11-28,0.0008075978839769959,-0.023889631032943726 +1,META,2022-11-29,0.000751741521526128,0.006231686100363731 +1,META,2022-11-30,0.0007422775961458683,0.0759725570678711 +1,META,2022-12-01,0.0008691576076671481,0.019620075821876526 +1,META,2022-12-02,0.0009203008376061916,0.02500850521028042 +1,META,2022-12-05,0.0009696421911939979,-0.00862087681889534 +1,META,2022-12-06,0.0009865897009149194,-0.07028867304325104 +1,META,2022-12-07,0.000835736165754497,-0.0016664440045133233 +1,META,2022-12-08,0.0008345330716110766,0.012213400565087795 +1,META,2022-12-09,0.0008532851934432983,0.004930054768919945 +1,META,2022-12-12,0.0009109938400797546,-0.010320419445633888 +1,META,2022-12-13,0.000941430451348424,0.046333715319633484 +1,META,2022-12-14,0.0009952576365321875,0.011913789436221123 +1,META,2022-12-15,0.0010375601705163717,-0.04577229171991348 +1,META,2022-12-16,0.0009563876083120704,0.027847858145833015 +1,META,2022-12-19,0.0009800285333767533,-0.04233013093471527 +1,META,2022-12-20,0.0008835232583805919,0.022542541846632957 +1,META,2022-12-21,0.0008873269543983042,0.02254701592028141 +1,META,2022-12-22,0.000962850812356919,-0.022290699183940887 +1,META,2022-12-23,0.0009095589630305767,0.007824596017599106 +1,META,2022-12-27,0.0009384427685290575,-0.009875915944576263 +1,META,2022-12-28,0.0009387522004544735,-0.010838679037988186 +1,META,2022-12-29,0.0009269972215406597,0.03934705629944801 +1,META,2022-12-30,0.0010355223203077912,0.0006649094866588712 +1,META,2023-01-03,0.0010759999277070165,0.035910602658987045 +1,META,2023-01-04,0.0011649222578853369,0.020864572376012802 +1,META,2023-01-05,0.0011868650326505303,-0.0033817430958151817 +1,META,2023-01-06,0.001204192521981895,0.02397378347814083 +1,META,2023-01-09,0.0012131626717746258,-0.004239206667989492 +1,META,2023-01-10,0.0011869025183841586,0.02682502754032612 +1,META,2023-01-11,0.0011984099401161075,-0.0007522710948251188 +1,META,2023-01-12,0.0011890842579305172,0.028340039774775505 +1,META,2023-01-13,0.0011789713753387332,0.0019730713684111834 +1,META,2023-01-17,0.001175413723103702,-0.011897021904587746 +1,META,2023-01-18,0.0011734968284144998,-0.01743837259709835 +1,META,2023-01-19,0.0011354556772857904,0.02325783669948578 +1,META,2023-01-20,0.0011267919326201081,0.023374944925308228 +1,META,2023-01-23,0.0011401948286220431,0.02759886160492897 +1,META,2023-01-24,0.0011635018745437264,-0.0009079491137526929 +1,META,2023-01-25,0.0011756655294448137,-0.011523626744747162 +1,META,2023-01-26,0.001167014823295176,0.040171727538108826 +1,META,2023-01-27,0.0012176916934549809,0.029697326943278313 +1,META,2023-01-30,0.0012451867805793881,-0.031327906996011734 +1,META,2023-01-31,0.00120775296818465,0.012904162518680096 +1,META,2023-02-01,0.0012366626178845763,0.027477005496621132 +1,META,2023-02-02,0.001257002237252891,0.20930756628513336 +1,META,2023-02-03,0.0013392310356721282,-0.01193736307322979 +1,META,2023-02-06,0.001323662349022925,-0.0025227339938282967 +1,META,2023-02-07,0.0013191188918426633,0.0294448621571064 +1,META,2023-02-08,0.0013387792278081179,-0.04368091747164726 +1,META,2023-02-09,0.0012709490256384015,-0.030499286949634552 +1,META,2023-02-10,0.0011303883511573076,-0.021417107433080673 +1,META,2023-02-13,0.0010599893284961581,0.029868263751268387 +1,META,2023-02-14,0.0010645644506439567,0.00027859778492711484 +1,META,2023-02-15,0.0010572895407676697,-0.013010505586862564 +1,META,2023-02-16,0.001055326429195702,-0.02700391411781311 +1,META,2023-02-17,0.0009756592917256057,0.002548467367887497 +1,META,2023-02-21,0.000951232563238591,-0.004638280253857374 +1,META,2023-02-22,0.0009094279957935214,-0.0055944304913282394 +1,META,2023-02-23,0.0007404009811580181,0.00536191975697875 +1,META,2023-02-24,0.0007937920745462179,-0.009637073613703251 +1,META,2023-02-27,0.0008228600490838289,-0.005001069512218237 +1,META,2023-02-28,0.0008753963629715145,0.03135419636964798 +1,META,2023-03-01,0.001053933403454721,-0.008726698346436024 +1,META,2023-03-02,0.0011497939703986049,0.00638027535751462 +1,META,2023-03-03,0.0012782311532646418,0.05960959941148758 +1,META,2023-03-06,0.0014061157125979662,-0.0018912152154371142 +1,META,2023-03-07,0.001402733731083572,-0.00211134715937078 +1,META,2023-03-08,0.0014018615474924445,0.0024899763520807028 +1,META,2023-03-09,0.0014122407883405685,-0.017891639843583107 +1,META,2023-03-10,0.0013480042107403278,-0.012071209959685802 +1,META,2023-03-13,0.001279032789170742,0.007713387254625559 +1,META,2023-03-14,0.001274669193662703,0.07001699507236481 +1,META,2023-03-15,0.0013838318409398198,0.019042259082198143 +1,META,2023-03-16,0.0014022329123690724,0.03566483408212662 +1,META,2023-03-17,0.0013865806395187974,-0.04654539003968239 +1,META,2023-03-20,0.0012254588073119521,0.011184006929397583 +1,META,2023-03-21,0.001191480434499681,0.02175241895020008 +1,META,2023-03-22,0.001209487090818584,-0.011692401021718979 +1,META,2023-03-23,0.0011411532759666443,0.022124551236629486 +1,META,2023-03-24,0.0011558772530406713,0.008433161303400993 +1,META,2023-03-27,0.001172010088339448,-0.015507249161601067 +1,META,2023-03-28,0.0011440473608672619,-0.010705855675041676 +1,META,2023-03-29,0.0011296040611341596,0.023004325106739998 +1,META,2023-03-30,0.0011961187701672316,0.012052631005644798 +1,META,2023-03-31,0.0012801624834537506,0.019534695893526077 +1,META,2023-04-03,0.0013161139795556664,0.005317749921232462 +1,META,2023-04-04,0.0013176955981180072,0.007713881321251392 +1,META,2023-04-05,0.0013219569809734821,-0.015204406343400478 +1,META,2023-04-06,0.0012764106504619122,0.021610859781503677 +1,META,2023-04-10,0.0013226564042270184,-0.0062666721642017365 +1,META,2023-04-11,0.0013164679985493422,-0.004199801478534937 +1,META,2023-04-12,0.0013149842852726579,0.0007011929410509765 +1,META,2023-04-13,0.0013456266606226563,0.029241181910037994 +1,META,2023-04-14,0.0013652279740199447,0.005160203669220209 +1,META,2023-04-17,0.0013780392473563552,-0.011945097707211971 +1,META,2023-04-18,0.0013934425078332424,-0.004441940225660801 +1,META,2023-04-19,0.001387688796967268,-0.010101906023919582 +1,META,2023-04-20,0.00137852574698627,-0.012267496436834335 +1,META,2023-04-21,0.001317243673838675,-0.0008453817572444677 +1,META,2023-04-24,0.001275319722481072,-0.0004697967378888279 +1,META,2023-04-25,0.0012693674070760608,-0.02493339590728283 +1,META,2023-04-26,0.001004435122013092,0.008873936720192432 +1,META,2023-04-27,0.0009443864692002535,0.13037455081939697 +1,META,2023-04-28,0.0011808465933427215,0.0073504988104105 +1,META,2023-05-01,0.0013530944706872106,0.011830583214759827 +1,META,2023-05-02,0.0013942542718723416,-0.016334736719727516 +1,META,2023-05-03,0.0013496476458385587,-0.009280468337237835 +1,META,2023-05-04,0.001293676090426743,-0.014918993227183819 +1,META,2023-05-05,0.0012448988854885101,-0.0031738937832415104 +1,META,2023-05-08,0.0012545743957161903,0.0021027070470154285 +1,META,2023-05-09,0.0012618651380762458,0.0004286256153136492 +1,META,2023-05-10,0.001267633168026805,-0.0012435009703040123 +1,META,2023-05-11,0.0012729595182463527,0.011559869162738323 +1,META,2023-05-12,0.0013107401318848133,-0.008432713337242603 +1,META,2023-05-15,0.0012904596514999866,0.02136867120862007 +1,META,2023-05-16,0.0013336457777768373,-0.000167436184710823 +1,META,2023-05-17,0.0013102652737870812,0.01525044534355402 +1,META,2023-05-18,0.0013667577877640724,0.017820417881011963 +1,META,2023-05-19,0.0014187284978106618,-0.004913798999041319 +1,META,2023-05-22,0.0013914507580921054,0.010851153172552586 +1,META,2023-05-23,0.0013882961357012391,-0.006383055821061134 +1,META,2023-05-24,0.0013792337849736214,0.009960776194930077 +1,META,2023-05-25,0.001430840347893536,0.013867467641830444 +1,META,2023-05-26,0.001466987538151443,0.03633381426334381 +1,META,2023-05-30,0.0014866478741168976,0.0018300210358574986 +1,META,2023-05-31,0.0014636055566370487,0.008345155045390129 +1,META,2023-06-01,0.0014693881385028362,0.029369669035077095 +1,META,2023-06-02,0.0014547965256497264,0.0 +1,META,2023-06-05,0.001459443592466414,-0.004485193639993668 +1,SPY,2022-08-17,0.0007754392572678626,-0.007123260293155909 +1,SPY,2022-08-18,0.0007601601537317038,0.0029021359514445066 +1,SPY,2022-08-19,0.0007658129907213151,-0.01352927926927805 +1,SPY,2022-08-22,0.0007288348278962076,-0.021042486652731895 +1,SPY,2022-08-23,0.0006177612813189626,-0.0024220780469477177 +1,SPY,2022-08-24,0.000588491908274591,0.003196279052644968 +1,SPY,2022-08-25,0.0005895431968383491,0.014018830843269825 +1,SPY,2022-08-26,0.0006859175628051162,-0.034435298293828964 +1,SPY,2022-08-29,0.0005291764973662794,-0.006634212099015713 +1,SPY,2022-08-30,0.00047067852574400604,-0.011038564145565033 +1,SPY,2022-08-31,0.0004154874477535486,-0.007638221140950918 +1,SPY,2022-09-01,0.0003542829363141209,0.0031330478377640247 +1,SPY,2022-09-02,0.0003741577093023807,-0.010600297711789608 +1,SPY,2022-09-06,0.00031682688859291375,-0.0037803445011377335 +1,SPY,2022-09-07,0.0002597401035018265,0.0178054329007864 +1,SPY,2022-09-08,0.0003857940318994224,0.006515113171190023 +1,SPY,2022-09-09,0.0004626120498869568,0.015415722504258156 +1,SPY,2022-09-12,0.0005570288631133735,0.010690443217754364 +1,SPY,2022-09-13,0.0006936350837349892,-0.04445638135075569 +1,SPY,2022-09-14,0.0005397010827437043,0.003808551002293825 +1,SPY,2022-09-15,0.0005476335063576698,-0.01141811441630125 +1,SPY,2022-09-16,0.0005060742842033505,-0.007658184040337801 +1,SPY,2022-09-19,0.0004867218667641282,0.00772494450211525 +1,SPY,2022-09-20,0.000511665886733681,-0.011544962413609028 +1,SPY,2022-09-21,0.000465964840259403,-0.017597733065485954 +1,SPY,2022-09-22,0.00035419114283286035,-0.008435261435806751 +1,SPY,2022-09-23,0.0002745427191257477,-0.01689661666750908 +1,SPY,2022-09-26,0.00020398585184011608,-0.009941991418600082 +1,SPY,2022-09-27,-2.0870758817181922e-05,-0.0025560539215803146 +1,SPY,2022-09-28,2.4827360903145745e-05,0.01948542892932892 +1,SPY,2022-09-29,0.00027146824868395925,-0.0211101695895195 +1,SPY,2022-09-30,0.00017918609955813736,-0.015584530308842659 +1,SPY,2022-10-03,-0.0002208879159297794,0.02605872042477131 +1,SPY,2022-10-04,0.00022146879928186536,0.03051636926829815 +1,SPY,2022-10-05,0.00037477989098988473,-0.002330913208425045 +1,SPY,2022-10-06,0.0004722398007288575,-0.010369392111897469 +1,SPY,2022-10-07,0.0005033137858845294,-0.02829025313258171 +1,SPY,2022-10-10,0.0004344726330600679,-0.007664783857762814 +1,SPY,2022-10-11,0.0004130242159590125,-0.006353213917464018 +1,SPY,2022-10-12,0.00041253899689763784,-0.003303934121504426 +1,SPY,2022-10-13,0.00038482362288050354,0.026048781350255013 +1,SPY,2022-10-14,0.0004824904608540237,-0.023052221164107323 +1,SPY,2022-10-17,0.0004704716266132891,0.025372236967086792 +1,SPY,2022-10-18,0.0005495910882018507,0.011681257747113705 +1,SPY,2022-10-19,0.0006254409090615809,-0.007111857179552317 +1,SPY,2022-10-20,0.0006784943980164826,-0.008420521393418312 +1,SPY,2022-10-21,0.000685778446495533,0.024010760709643364 +1,SPY,2022-10-24,0.0007503204396925867,0.012162182480096817 +1,SPY,2022-10-25,0.0007740448345430195,0.015842504799365997 +1,SPY,2022-10-26,0.0007830008398741484,-0.007562628947198391 +1,SPY,2022-10-27,0.0007728405180387199,-0.005354209337383509 +1,SPY,2022-10-28,0.0007743267924524844,0.023511994630098343 +1,SPY,2022-10-31,0.000783923955168575,-0.0072495657950639725 +1,SPY,2022-11-01,0.0007759507279843092,-0.004385340493172407 +1,SPY,2022-11-02,0.0007672540377825499,-0.025416504591703415 +1,SPY,2022-11-03,0.0007251287461258471,-0.01035023108124733 +1,SPY,2022-11-04,0.0006902181776240468,0.014290515333414078 +1,SPY,2022-11-07,0.0007116994238458574,0.00951998122036457 +1,SPY,2022-11-08,0.0007415217696689069,0.005381239578127861 +1,SPY,2022-11-09,0.0007665255106985569,-0.020817484706640244 +1,SPY,2022-11-10,0.0007441838970407844,0.05349738523364067 +1,SPY,2022-11-11,0.0007836725562810898,0.009631861001253128 +1,SPY,2022-11-14,0.0007920377538539469,-0.008543095551431179 +1,SPY,2022-11-15,0.0007883352809585631,0.008492889814078808 +1,SPY,2022-11-16,0.0007926941616460681,-0.007657998241484165 +1,SPY,2022-11-17,0.0007865503430366516,-0.0030645194929093122 +1,SPY,2022-11-18,0.0007821601466275752,0.004530077800154686 +1,SPY,2022-11-21,0.0007846305961720645,-0.0036427814047783613 +1,SPY,2022-11-22,0.0007812268449924886,0.013367452658712864 +1,SPY,2022-11-23,0.0007895592716522515,0.0062818569131195545 +1,SPY,2022-11-25,0.0007904262165538967,-0.0002239100867882371 +1,SPY,2022-11-28,0.0007922227960079908,-0.01608569733798504 +1,SPY,2022-11-29,0.0007736310362815857,-0.0017189147183671594 +1,SPY,2022-11-30,0.0007661342388018966,0.03101450204849243 +1,SPY,2022-12-01,0.0007847879896871746,-0.0007360081071965396 +1,SPY,2022-12-02,0.000776522618252784,-0.0011543140280991793 +1,SPY,2022-12-05,0.0007789989467710257,-0.01815304160118103 +1,SPY,2022-12-06,0.0007377653964795172,-0.014519861899316311 +1,SPY,2022-12-07,0.0006824846495874226,-0.0017024753615260124 +1,SPY,2022-12-08,0.0006632736185565591,0.007803258951753378 +1,SPY,2022-12-09,0.0006887443596497178,-0.007498141843825579 +1,SPY,2022-12-12,0.0006755270296707749,0.014314291998744011 +1,SPY,2022-12-13,0.0007636280497536063,0.007541297003626823 +1,SPY,2022-12-14,0.0007960855728015304,-0.006414057221263647 +1,SPY,2022-12-15,0.0008007868891581893,-0.024765631183981895 +1,SPY,2022-12-16,0.0007519946084357798,-0.011876443400979042 +1,SPY,2022-12-19,0.0007245786837302148,-0.008516005240380764 +1,SPY,2022-12-20,0.0006969499518163502,0.0013676014496013522 +1,SPY,2022-12-21,0.0006722413236275315,0.01484163198620081 +1,SPY,2022-12-22,0.0007172327022999525,-0.014369049109518528 +1,SPY,2022-12-23,0.0006955380667932332,0.005735896062105894 +1,SPY,2022-12-27,0.0007007850217632949,-0.003951225429773331 +1,SPY,2022-12-28,0.0006961325416341424,-0.012505702674388885 +1,SPY,2022-12-29,0.0006450380897149444,0.017840268090367317 +1,SPY,2022-12-30,0.0007048073457553983,-0.0026374782901257277 +1,SPY,2023-01-03,0.0007187430164776742,-0.004218899179250002 +1,SPY,2023-01-04,0.0007280494901351631,0.007690387312322855 +1,SPY,2023-01-05,0.000757684581913054,-0.011478832922875881 +1,SPY,2023-01-06,0.0007531989249400795,0.02267296053469181 +1,SPY,2023-01-09,0.0008029746823012829,-0.0005667998339049518 +1,SPY,2023-01-10,0.0008016130304895341,0.006988144014030695 +1,SPY,2023-01-11,0.0008150984649546444,0.012568522244691849 +1,SPY,2023-01-12,0.0008171784575097263,0.0036341319791972637 +1,SPY,2023-01-13,0.0008138642879202962,0.0038720874581485987 +1,SPY,2023-01-17,0.0008121092105284333,-0.0018335069762542844 +1,SPY,2023-01-18,0.0008082326385192573,-0.015914104878902435 +1,SPY,2023-01-19,0.0007787301437929273,-0.007306354586035013 +1,SPY,2023-01-20,0.0007439740584231913,0.01845763809978962 +1,SPY,2023-01-23,0.0007770559168420732,0.011927164159715176 +1,SPY,2023-01-24,0.000796079752035439,-0.0010738970013335347 +1,SPY,2023-01-25,0.0008028873126022518,0.000374675786588341 +1,SPY,2023-01-26,0.0008042117697186768,0.010930363088846207 +1,SPY,2023-01-27,0.0008153315866366029,0.0022950023412704468 +1,SPY,2023-01-30,0.0008116458775475621,-0.01262596808373928 +1,SPY,2023-01-31,0.0007886951789259911,0.014596435241401196 +1,SPY,2023-02-01,0.000805139250587672,0.01057165116071701 +1,SPY,2023-02-02,0.0008038168889470398,0.014451889321208 +1,SPY,2023-02-03,0.0008167967316694558,-0.010685940273106098 +1,SPY,2023-02-06,0.000809629971627146,-0.006130046211183071 +1,SPY,2023-02-07,0.0008023008122108877,0.012993901036679745 +1,SPY,2023-02-08,0.0008077998645603657,-0.010995181277394295 +1,SPY,2023-02-09,0.0007972709136083722,-0.00870676338672638 +1,SPY,2023-02-10,0.0007703955634497106,0.0023307902738451958 +1,SPY,2023-02-13,0.0007616151124238968,0.011670723557472229 +1,SPY,2023-02-14,0.0007825760985724628,-0.0004602568515110761 +1,SPY,2023-02-15,0.0007811940740793943,0.003241951810196042 +1,SPY,2023-02-16,0.0007964855176396668,-0.013864470645785332 +1,SPY,2023-02-17,0.0007579767261631787,-0.0025013426784425974 +1,SPY,2023-02-21,0.0007529002032242715,-0.020264817401766777 +1,SPY,2023-02-22,0.0006781622068956494,-0.0013791073579341173 +1,SPY,2023-02-23,0.000639814417809248,0.0053052110597491264 +1,SPY,2023-02-24,0.0006669381982646883,-0.010739844292402267 +1,SPY,2023-02-27,0.000623247935436666,0.0034003157634288073 +1,SPY,2023-02-28,0.0006501961615867913,-0.003702870337292552 +1,SPY,2023-03-01,0.0006630542920902371,-0.003843564074486494 +1,SPY,2023-03-02,0.0006436093826778233,0.007747349329292774 +1,SPY,2023-03-03,0.0007131346501410007,0.015910666435956955 +1,SPY,2023-03-06,0.00075558852404356,0.0006924226763658226 +1,SPY,2023-03-07,0.0007678514812141657,-0.015447492711246014 +1,SPY,2023-03-08,0.000734304019715637,0.0016308922786265612 +1,SPY,2023-03-09,0.0007340986048802733,-0.018622277304530144 +1,SPY,2023-03-10,0.0006534673739224672,-0.014534569345414639 +1,SPY,2023-03-13,0.0005713236751034856,-0.0014262418262660503 +1,SPY,2023-03-14,0.0005419610533863306,0.016395000740885735 +1,SPY,2023-03-15,0.0005916013033129275,-0.006273949518799782 +1,SPY,2023-03-16,0.000583869987167418,0.017392896115779877 +1,SPY,2023-03-17,0.0006883530877530575,-0.01176149770617485 +1,SPY,2023-03-20,0.0006807827739976346,0.009569671005010605 +1,SPY,2023-03-21,0.0007206255686469376,0.013045044615864754 +1,SPY,2023-03-22,0.0007708938792347908,-0.017193306237459183 +1,SPY,2023-03-23,0.0007377354777418077,0.0026997625827789307 +1,SPY,2023-03-24,0.0007459477055817842,0.006540393456816673 +1,SPY,2023-03-27,0.0007679789559915662,0.0018680939683690667 +1,SPY,2023-03-28,0.0007762989844195545,-0.00224721129052341 +1,SPY,2023-03-29,0.0007769539370201528,0.01443042978644371 +1,SPY,2023-03-30,0.0008125631138682365,0.005838102661073208 +1,SPY,2023-03-31,0.0008183885947801173,0.013996233232319355 +1,SPY,2023-04-03,0.0008292206330224872,0.0038032412994652987 +1,SPY,2023-04-04,0.0008228181395679712,-0.005563479848206043 +1,SPY,2023-04-05,0.0008089182083494961,-0.002621804364025593 +1,SPY,2023-04-06,0.0007973459432832897,0.003893420100212097 +1,SPY,2023-04-10,0.0007982755778357387,0.0010256771929562092 +1,SPY,2023-04-11,0.0007975025800988078,0.0002686130173970014 +1,SPY,2023-04-12,0.000794071878772229,-0.004084320273250341 +1,SPY,2023-04-13,0.0007881247438490391,0.013195488601922989 +1,SPY,2023-04-14,0.0008046467555686831,-0.002445857273414731 +1,SPY,2023-04-17,0.0008051545009948313,0.003581828437745571 +1,SPY,2023-04-18,0.0008154292008839548,0.0006519030430354178 +1,SPY,2023-04-19,0.0008162881713360548,-0.00016880901239346713 +1,SPY,2023-04-20,0.0008205829653888941,-0.005472104996442795 +1,SPY,2023-04-21,0.0008099403348751366,0.0007767330971546471 +1,SPY,2023-04-24,0.000811567937489599,0.001042540417984128 +1,SPY,2023-04-25,0.0008149811765179038,-0.016001170501112938 +1,SPY,2023-04-26,0.0007462274516001344,-0.004244604613631964 +1,SPY,2023-04-27,0.000718482886441052,0.019712574779987335 +1,SPY,2023-04-28,0.0007799278246238828,0.008498945273458958 +1,SPY,2023-05-01,0.0008187317289412022,-0.0010103135136887431 +1,SPY,2023-05-02,0.000814865343272686,-0.011302992701530457 +1,SPY,2023-05-03,0.0007786907954141498,-0.006887642666697502 +1,SPY,2023-05-04,0.0007448053220286965,-0.0071081314235925674 +1,SPY,2023-05-05,0.0007125117117539048,0.018343333154916763 +1,SPY,2023-05-08,0.0007659820257686079,0.00026649321080185473 +1,SPY,2023-05-09,0.0007787126232869923,-0.004395064897835255 +1,SPY,2023-05-10,0.0007730736979283392,0.004661564249545336 +1,SPY,2023-05-11,0.000792002072557807,-0.0017457050271332264 +1,SPY,2023-05-12,0.0007923692464828491,-0.0013109726132825017 +1,SPY,2023-05-15,0.0007847085944376886,0.0034440532326698303 +1,SPY,2023-05-16,0.0007964607793837786,-0.006705075036734343 +1,SPY,2023-05-17,0.0007767528295516968,0.01206585206091404 +1,SPY,2023-05-18,0.0008086530142463744,0.00958716869354248 +1,SPY,2023-05-19,0.0008220480522140861,-0.001456062076613307 +1,SPY,2023-05-22,0.0008224808261729777,0.0004059523926116526 +1,SPY,2023-05-23,0.0008206397760659456,-0.01128606591373682 +1,SPY,2023-05-24,0.0007842867635190487,-0.00727136991918087 +1,SPY,2023-05-25,0.0007401651819236577,0.008622664026916027 +1,SPY,2023-05-26,0.0007576547213830054,0.01286751963198185 +1,SPY,2023-05-30,0.000799202302005142,0.00038083974504843354 +1,SPY,2023-05-31,0.0008021077373996377,-0.005560695193707943 +1,SPY,2023-06-01,0.0007871207781136036,0.009456113912165165 +1,SPY,2023-06-02,0.0008095709490589797,0.01435764878988266 +1,SPY,2023-06-05,0.0008249987149611115,-0.0019178248476237059 +2,AAPL,2023-06-06,0.0005863954429514706,-0.0020624478347599506 +2,AAPL,2023-06-07,0.0005712196580134332,-0.007786569185554981 +2,AAPL,2023-06-08,0.000546675524674356,0.015346954576671124 +2,AAPL,2023-06-09,0.0005540643469430506,0.0021574159618467093 +2,AAPL,2023-06-12,0.0005599638097919524,0.015517693012952805 +2,AAPL,2023-06-13,0.000595630262978375,-0.0026152078062295914 +2,AAPL,2023-06-14,0.0005996192339807749,0.0034853979013860226 +2,AAPL,2023-06-15,0.0006012512603774667,0.01113645825535059 +2,AAPL,2023-06-16,0.0006142518250271678,-0.005876974668353796 +2,AAPL,2023-06-20,0.0006002107984386384,0.0004863539361394942 +2,AAPL,2023-06-21,0.0006042021559551358,-0.0056915380991995335 +2,AAPL,2023-06-22,0.0005926425219513476,0.016390299424529076 +2,AAPL,2023-06-23,0.000626739114522934,-0.0017127158353105187 +2,AAPL,2023-06-26,0.0006305439746938646,-0.0075815594755113125 +2,AAPL,2023-06-27,0.0006204252713359892,0.01494666188955307 +2,AAPL,2023-06-28,0.000641109247226268,0.006307884585112333 +2,AAPL,2023-06-29,0.0006482701282948256,0.0017949335742741823 +2,AAPL,2023-06-30,0.0006580896442756057,0.022839806973934174 +2,AAPL,2023-07-03,0.0006747351144440472,-0.007815319113433361 +2,AAPL,2023-07-05,0.0006671081064268947,-0.005888581741601229 +2,AAPL,2023-07-06,0.0006510668317787349,0.0025055608712136745 +2,AAPL,2023-07-07,0.0006511359242722392,-0.005908595398068428 +2,AAPL,2023-07-10,0.0006446149200201035,-0.01091526448726654 +2,AAPL,2023-07-11,0.0006337158847600222,-0.002813957864418626 +2,AAPL,2023-07-12,0.0006303483387455344,0.00894536916166544 +2,AAPL,2023-07-13,0.0006281731184571981,0.00404931977391243 +2,AAPL,2023-07-14,0.0006381123093888164,0.0007868342217989266 +2,AAPL,2023-07-17,0.0006420875433832407,0.017157617956399918 +2,AAPL,2023-07-18,0.0006738650263287127,-0.0013411499094218016 +2,AAPL,2023-07-19,0.0006769057363271713,0.007046912331134081 +2,AAPL,2023-07-20,0.0006726922583766282,-0.010148928500711918 +2,AAPL,2023-07-21,0.0006486453348770738,-0.006180605385452509 +2,AAPL,2023-07-24,0.000635686214081943,0.004211178049445152 +2,AAPL,2023-07-25,0.0006371248164214194,0.00450333533808589 +2,AAPL,2023-07-26,0.0006491080275736749,0.004534740932285786 +2,AAPL,2023-07-27,0.0006628612754866481,-0.006602724548429251 +2,AAPL,2023-07-28,0.0006548556266352534,0.01341759692877531 +2,AAPL,2023-07-31,0.0006603868096135557,0.0031609286088496447 +2,AAPL,2023-08-01,0.0006679459474980831,-0.0042850361205637455 +2,AAPL,2023-08-02,0.0006626357208006084,-0.015611071139574051 +2,AAPL,2023-08-03,0.0006098001613281667,-0.007348672486841679 +2,AAPL,2023-08-04,0.0005448709125630558,-0.04921121150255203 +2,AAPL,2023-08-07,0.0006068768561817706,-0.01740434765815735 +2,AAPL,2023-08-08,0.0006921631866134703,0.005297696217894554 +2,AAPL,2023-08-09,0.0007030829438008368,-0.008994937874376774 +2,AAPL,2023-08-10,0.0006423959857784212,-0.0012351969489827752 +2,AAPL,2023-08-11,0.00048778398195281625,0.0003374739899300039 +2,AAPL,2023-08-14,0.0003813648072537035,0.009349295869469643 +2,AAPL,2023-08-15,0.00042452127672731876,-0.011263417080044746 +2,AAPL,2023-08-16,0.0003986996889580041,-0.004971386399120092 +2,AAPL,2023-08-17,0.0003757691301871091,-0.014662192203104496 +2,AAPL,2023-08-18,0.0003415114479139447,0.0028121243230998516 +2,AAPL,2023-08-21,0.00035328284138813615,0.0077069723047316074 +2,AAPL,2023-08-22,0.00040618053753860295,0.007873710244894028 +2,AAPL,2023-08-23,0.00047938700299710035,0.021711556240916252 +2,AAPL,2023-08-24,0.0006082257023081183,-0.026519102975726128 +2,AAPL,2023-08-25,0.0006193526205606759,0.012564071454107761 +2,AAPL,2023-08-28,0.0006170116830617189,0.008807011879980564 +2,AAPL,2023-08-29,0.0005986064788885415,0.02157582901418209 +2,AAPL,2023-08-30,0.0005354933673515916,0.01899089850485325 +2,AAPL,2023-08-31,0.00047520003863610327,0.0011718306923285127 +2,AAPL,2023-09-01,0.00046388438204303384,0.008427628315985203 +2,AAPL,2023-09-05,0.0004743920871987939,0.001265977043658495 +2,AAPL,2023-09-06,0.0004819143796339631,-0.03644971176981926 +2,AAPL,2023-09-07,0.0004752092354465276,-0.029685672372579575 +2,AAPL,2023-09-08,0.0006193364970386028,0.0034857739228755236 +2,AAPL,2023-09-11,0.0006656993646174669,0.006600812077522278 +2,AAPL,2023-09-12,0.0006871383520774543,-0.017208127304911613 +2,AAPL,2023-09-13,0.0007075622561387718,-0.01192549616098404 +2,AAPL,2023-09-14,0.0006189014529809356,0.008744248189032078 +2,AAPL,2023-09-15,0.0006186621030792594,-0.00416261563077569 +2,AAPL,2023-09-18,0.0006127372616901994,0.016772065311670303 +2,AAPL,2023-09-19,0.0006943522021174431,0.006161569617688656 +2,AAPL,2023-09-20,0.0006757536320947111,-0.02019464410841465 +2,AAPL,2023-09-21,0.0006854994571767747,-0.00892915390431881 +2,AAPL,2023-09-22,0.0006932657561264932,0.004932170733809471 +2,AAPL,2023-09-25,0.000678050855640322,0.007353425025939941 +2,AAPL,2023-09-26,0.0006638187915086746,-0.023676708340644836 +2,AAPL,2023-09-27,0.0006814252701587975,-0.008937235921621323 +2,AAPL,2023-09-28,0.0006796644302085042,0.0015244833193719387 +2,AAPL,2023-09-29,0.0006715850904583931,0.0030418315436691046 +2,AAPL,2023-10-02,0.0006659917416982353,0.014726603403687477 +2,AAPL,2023-10-03,0.000614981516264379,-0.00780021958053112 +2,AAPL,2023-10-04,0.0005643418407998979,0.00728214718401432 +2,AAPL,2023-10-05,0.0005152030498720706,0.00717203039675951 +2,AAPL,2023-10-06,0.0004646048473659903,0.014642754569649696 +2,AAPL,2023-10-09,0.0004267655313014984,0.00841582752764225 +2,AAPL,2023-10-10,0.0004323474131524563,-0.003357784589752555 +2,AAPL,2023-10-11,0.000442005752120167,0.007872987538576126 +2,AAPL,2023-10-12,0.00044330168748274446,0.0050482493825256824 +2,AAPL,2023-10-13,0.0004445469530764967,-0.010346046648919582 +2,AAPL,2023-10-16,0.00044904695823788643,-0.0007273044902831316 +2,AAPL,2023-10-17,0.00045587410568259656,-0.008823464624583721 +2,AAPL,2023-10-18,0.0004446942766662687,-0.007422210648655891 +2,AAPL,2023-10-19,0.000496045162435621,-0.002163186902180314 +2,AAPL,2023-10-20,0.0005419108201749623,-0.014813512563705444 +2,AAPL,2023-10-23,0.0006238917703740299,0.0006938488222658634 +2,AAPL,2023-10-24,0.0006419356213882565,0.0025400312151759863 +2,AAPL,2023-10-25,0.0006142311030998826,-0.013583376072347164 +2,AAPL,2023-10-26,0.0006536425789818168,-0.024913476780056953 +2,AAPL,2023-10-27,0.000698122545145452,0.007937943562865257 +2,AAPL,2023-10-30,0.0006873869569972157,0.01223001815378666 +2,AAPL,2023-10-31,0.0006548740202561021,0.002814801875501871 +2,AAPL,2023-11-01,0.0006271994789130986,0.018565282225608826 +2,AAPL,2023-11-02,0.0005526855238713324,0.020482094958424568 +2,AAPL,2023-11-03,0.00046048691729083657,-0.005194477271288633 +2,AAPL,2023-11-06,0.000440295523731038,0.014499475248157978 +2,AAPL,2023-11-07,0.0004383205669000745,0.014347190037369728 +2,AAPL,2023-11-08,0.000459467206383124,0.005867797881364822 +2,AAPL,2023-11-09,0.00048129979404620826,-0.002628105925396085 +2,AAPL,2023-11-10,0.0004834496940020472,0.022954564541578293 +2,AAPL,2023-11-13,0.0005041981348767877,-0.008620775304734707 +2,AAPL,2023-11-14,0.0004905000678263605,0.014184791594743729 +2,AAPL,2023-11-15,0.0004922333755530417,0.003036146517843008 +2,AAPL,2023-11-16,0.0004791107785422355,0.009001660160720348 +2,AAPL,2023-11-17,0.0004658455145545304,-0.00010535367619013414 +2,AAPL,2023-11-20,0.00047613916103728116,0.009235428646206856 +2,AAPL,2023-11-21,0.00047832587733864784,-0.004239944275468588 +2,AAPL,2023-11-22,0.00047697933041490614,0.0035082963295280933 +2,AAPL,2023-11-24,0.0004815967404283583,-0.0070289443247020245 +2,AAPL,2023-11-27,0.0004926706897094846,-0.0009478537831455469 +2,AAPL,2023-11-28,0.0004930067807435989,0.0032088879961520433 +2,AAPL,2023-11-29,0.00048326552496291697,-0.0054243458434939384 +2,AAPL,2023-11-30,0.0004817394365090877,0.003058183239772916 +2,AAPL,2023-12-01,0.0004789404629264027,0.006768209394067526 +2,AAPL,2023-12-04,0.0004904333618469536,-0.009509749710559845 +2,AAPL,2023-12-05,0.0004824852221645415,0.020844345912337303 +2,AAPL,2023-12-06,0.0005210910458117723,-0.005703074857592583 +2,AAPL,2023-12-07,0.0005222350009717047,0.010088058188557625 +2,AAPL,2023-12-08,0.0005614185938611627,0.007385253440588713 +2,AAPL,2023-12-11,0.0005909276660531759,-0.013011575676500797 +2,AAPL,2023-12-12,0.0005780145875178277,0.007888687774538994 +2,AAPL,2023-12-13,0.0005954253720119596,0.016553832218050957 +2,AAPL,2023-12-14,0.0006264928379096091,0.0007573642651550472 +2,AAPL,2023-12-15,0.0006216452457010746,-0.0027293877210468054 +2,AAPL,2023-12-18,0.0006225060787983239,-0.008539646863937378 +2,AAPL,2023-12-19,0.000607611145824194,0.005345760844647884 +2,AAPL,2023-12-20,0.0006163879297673702,-0.010771778412163258 +2,AAPL,2023-12-21,0.000597234582528472,-0.0007701196009293199 +2,AAPL,2023-12-22,0.0005950478953309357,-0.00556290103122592 +2,AAPL,2023-12-26,0.0005639666924253106,-0.002845059847459197 +2,AAPL,2023-12-27,0.000543494476005435,0.0005177333950996399 +2,AAPL,2023-12-28,0.0005418854998424649,0.0022238504607230425 +2,AAPL,2023-12-29,0.000563888403121382,-0.005438880994915962 +2,AAPL,2024-01-02,0.0005593124078586698,-0.03644273057579994 +2,AAPL,2024-01-03,0.0005154378013685346,-0.007515631150454283 +2,AAPL,2024-01-04,0.0006114781717769802,-0.012781376019120216 +2,AAPL,2024-01-05,0.0006643919623456895,-0.004021128173917532 +2,AAPL,2024-01-08,0.0006803273572586477,0.023887163028120995 +2,AAPL,2024-01-09,0.000656669435556978,-0.0022659352980554104 +2,AAPL,2024-01-10,0.0006451443186961114,0.005655281245708466 +2,AAPL,2024-01-11,0.0006094295531511307,-0.003227636683732271 +2,AAPL,2024-01-12,0.0005937358364462852,0.0017765017691999674 +2,AAPL,2024-01-16,0.0005585298058576882,-0.012393544428050518 +2,AAPL,2024-01-17,0.0005988688790239394,-0.005186849273741245 +2,AAPL,2024-01-18,0.0006332623888738453,0.03205139562487602 +2,AAPL,2024-01-19,0.000533412559889257,0.015413680113852024 +2,AAPL,2024-01-22,0.0004737383860629052,0.01208977960050106 +2,AAPL,2024-01-23,0.0004987129359506071,0.006631209049373865 +2,AAPL,2024-01-24,0.000536020495928824,-0.003489911090582609 +2,AAPL,2024-01-25,0.0005526394816115499,-0.001698227133601904 +2,AAPL,2024-01-26,0.0005540666170418262,-0.009053532965481281 +2,AAPL,2024-01-29,0.0005380852380767465,-0.0035922557581216097 +2,AAPL,2024-01-30,0.0005260537145659328,-0.019433416426181793 +2,AAPL,2024-01-31,0.0004972881288267672,-0.019547581672668457 +2,AAPL,2024-02-01,0.0005812807939946651,0.013252552598714828 +2,AAPL,2024-02-02,0.0005867705913260579,-0.005419934634119272 +2,AAPL,2024-02-05,0.0006153222057037055,0.009798543527722359 +2,AAPL,2024-02-06,0.0005792529555037618,0.008594710379838943 +2,AAPL,2024-02-07,0.0005262010381557047,0.0005809088470414281 +2,AAPL,2024-02-08,0.0004936765762977302,-0.005771265830844641 +2,AAPL,2024-02-09,0.00048751465510576963,0.004085601773113012 +2,AAPL,2024-02-12,0.0004856156883761287,-0.00904263649135828 +2,AAPL,2024-02-13,0.00048194199916906655,-0.011338522657752037 +2,AAPL,2024-02-14,0.0005032060435041785,-0.004821205046027899 +2,AAPL,2024-02-15,0.0005148876807652414,-0.0015762554248794913 +2,AAPL,2024-02-16,0.0005194498226046562,-0.008465951308608055 +2,AAPL,2024-02-20,0.0005632300744764507,-0.004122362472116947 +2,AAPL,2024-02-21,0.0006034955149516463,0.004177357070147991 +2,AAPL,2024-02-22,0.0005850373418070376,0.01118097361177206 +2,AAPL,2024-02-23,0.0005103140138089657,-0.010084673762321472 +2,AAPL,2024-02-26,0.0005093817599117756,-0.00747924018651247 +2,AAPL,2024-02-27,0.0005296238232403994,0.008081545121967793 +2,AAPL,2024-02-28,0.00048332769074477255,-0.006647175177931786 +2,AAPL,2024-02-29,0.0004990742891095579,-0.003700043074786663 +2,AAPL,2024-03-01,0.0005143697489984334,-0.006048694718629122 +2,AAPL,2024-03-04,0.0005205915658734739,-0.025708815082907677 +2,AAPL,2024-03-05,0.0006140423938632011,-0.02885337546467781 +2,AAPL,2024-03-06,0.0006942555191926658,-0.005895434878766537 +2,AAPL,2024-03-07,0.0006927961949259043,-0.0007099430658854544 +2,AAPL,2024-03-08,0.0006218638736754656,0.010184502229094505 +2,AAPL,2024-03-11,0.0006125876680016518,0.011762363836169243 +2,AAPL,2024-03-12,0.0006649559363722801,0.0027746357955038548 +2,AAPL,2024-03-13,0.0006624331581406295,-0.012196561321616173 +2,AAPL,2024-03-14,0.0006557417800650001,0.010868118144571781 +2,AAPL,2024-03-15,0.000641977007035166,-0.002199026523157954 +2,AAPL,2024-03-18,0.0006379419937729836,0.006352144759148359 +2,AAPL,2024-03-19,0.0006126060616225004,0.013493713922798634 +2,AAPL,2024-03-20,0.0005580556462518871,0.014602024108171463 +2,AAPL,2024-03-21,0.0004942819359712303,-0.04171569645404816 +2,AAPL,2024-03-22,0.0005349501734599471,0.005296133458614349 +2,MSFT,2023-06-06,0.00045575210242532194,-0.006750129163265228 +2,MSFT,2023-06-07,0.00045121193397790194,-0.03135443851351738 +2,MSFT,2023-06-08,0.0004890020936727524,0.005796769633889198 +2,MSFT,2023-06-09,0.0005016808863729239,0.004692881368100643 +2,MSFT,2023-06-12,0.000491606944706291,0.015365337952971458 +2,MSFT,2023-06-13,0.00045489027979783714,0.007325929589569569 +2,MSFT,2023-06-14,0.000455270434031263,0.009082416072487831 +2,MSFT,2023-06-15,0.00047415902372449636,0.0313984751701355 +2,MSFT,2023-06-16,0.0005037219962105155,-0.016714783385396004 +2,MSFT,2023-06-20,0.0004904125235043466,-0.012581159360706806 +2,MSFT,2023-06-21,0.00047681143041700125,-0.013371190056204796 +2,MSFT,2023-06-22,0.0004534604086074978,0.01826963573694229 +2,MSFT,2023-06-23,0.0004805351491086185,-0.013902392238378525 +2,MSFT,2023-06-26,0.00047551546595059335,-0.01934874802827835 +2,MSFT,2023-06-27,0.00045367208076640964,0.018004899844527245 +2,MSFT,2023-06-28,0.0004694547096733004,0.003818548284471035 +2,MSFT,2023-06-29,0.0004832458507735282,-0.0023848137352615595 +2,MSFT,2023-06-30,0.0004927841364406049,0.016252806410193443 +2,MSFT,2023-07-03,0.0005214788252487779,-0.007516283541917801 +2,MSFT,2023-07-05,0.0005234076525084674,0.00047321064630523324 +2,MSFT,2023-07-06,0.0005278160679154098,0.009184366092085838 +2,MSFT,2023-07-07,0.0005472726770676672,-0.011938335373997688 +2,MSFT,2023-07-10,0.0005405509728007019,-0.016112927347421646 +2,MSFT,2023-07-11,0.0005302956560626626,0.0019269561162218451 +2,MSFT,2023-07-12,0.0005354341119527817,0.014126495458185673 +2,MSFT,2023-07-13,0.0005502966232597828,0.016062403097748756 +2,MSFT,2023-07-14,0.0005860910168848932,0.007501279003918171 +2,MSFT,2023-07-17,0.0005870359600521624,0.001418188912793994 +2,MSFT,2023-07-18,0.0005913666682317853,0.039028268307447433 +2,MSFT,2023-07-19,0.0005711356643587351,-0.012343096546828747 +2,MSFT,2023-07-20,0.0005462316330522299,-0.023393232375383377 +2,MSFT,2023-07-21,0.0004990220186300576,-0.008977167308330536 +2,MSFT,2023-07-24,0.0004674351657740772,0.0038902703672647476 +2,MSFT,2023-07-25,0.0004693186201620847,0.016866203397512436 +2,MSFT,2023-07-26,0.0004753686080221087,-0.038363970816135406 +2,MSFT,2023-07-27,0.0004897170001640916,-0.021093126386404037 +2,MSFT,2023-07-28,0.0005311790737323463,0.02286769077181816 +2,MSFT,2023-07-31,0.0005056270747445524,-0.007266941945999861 +2,MSFT,2023-08-01,0.0005206666537560523,0.0012495683040469885 +2,MSFT,2023-08-02,0.0005100506241433322,-0.026634441688656807 +2,MSFT,2023-08-03,0.0006009815842844546,-0.00256819068454206 +2,MSFT,2023-08-04,0.0006326721049845219,0.0034227906726300716 +2,MSFT,2023-08-07,0.0006424976163543761,0.007083123084157705 +2,MSFT,2023-08-08,0.0006265616393648088,-0.012375191785395145 +2,MSFT,2023-08-09,0.000636458455119282,-0.011785030364990234 +2,MSFT,2023-08-10,0.0006374239455908537,0.002170062158256769 +2,MSFT,2023-08-11,0.0006289656739681959,-0.00596317695453763 +2,MSFT,2023-08-14,0.0006271318416111171,0.009394488297402859 +2,MSFT,2023-08-15,0.0006206412799656391,-0.006750289350748062 +2,MSFT,2023-08-16,0.0006253845058381557,-0.002431389642879367 +2,MSFT,2023-08-17,0.0006175439339131117,-0.011046881787478924 +2,MSFT,2023-08-18,0.0006255054613575339,-0.0012632677098736167 +2,MSFT,2023-08-21,0.0006148634711280465,0.016918741166591644 +2,MSFT,2023-08-22,0.0005489250761456788,0.0018000553827732801 +2,MSFT,2023-08-23,0.0004894318990409374,0.01398129016160965 +2,MSFT,2023-08-24,0.0004368311201687902,-0.021732941269874573 +2,MSFT,2023-08-25,0.00045008445158600807,0.009363269433379173 +2,MSFT,2023-08-28,0.00043030595406889915,0.002226718468591571 +2,MSFT,2023-08-29,0.0004349498194642365,0.014445753768086433 +2,MSFT,2023-08-30,0.0004436327435541898,0.0011562526924535632 +2,MSFT,2023-08-31,0.0004551840538624674,-0.0031377384439110756 +2,MSFT,2023-09-01,0.00047244835877791047,0.002742194104939699 +2,MSFT,2023-09-05,0.00048483340651728213,0.014769261702895164 +2,MSFT,2023-09-06,0.0005169883370399475,-0.002010948024690151 +2,MSFT,2023-09-07,0.000528111937455833,-0.008962105959653854 +2,MSFT,2023-09-08,0.0005237877485342324,0.013129192404448986 +2,MSFT,2023-09-11,0.0005306088132783771,0.010919076390564442 +2,MSFT,2023-09-12,0.0005367624689824879,-0.01842617802321911 +2,MSFT,2023-09-13,0.000506244832649827,0.012847742065787315 +2,MSFT,2023-09-14,0.0005150400684215128,0.007825056090950966 +2,MSFT,2023-09-15,0.000523258582688868,-0.025355612859129906 +2,MSFT,2023-09-18,0.00046666839625686407,-0.0035191928036510944 +2,MSFT,2023-09-19,0.00047056059702299535,-0.0012466433690860868 +2,MSFT,2023-09-20,0.000474126631161198,-0.024268953129649162 +2,MSFT,2023-09-21,0.0005950612248852849,-0.003873075358569622 +2,MSFT,2023-09-22,0.000618103367742151,-0.007917897775769234 +2,MSFT,2023-09-25,0.0006407307810150087,0.0016704231966286898 +2,MSFT,2023-09-26,0.0006367997266352177,-0.017151974141597748 +2,MSFT,2023-09-27,0.0006508652004413307,0.0020801404025405645 +2,MSFT,2023-09-28,0.0006403852021321654,0.002713831840083003 +2,MSFT,2023-09-29,0.0006319225649349391,0.006704896222800016 +2,MSFT,2023-10-02,0.000622362713329494,0.01897927187383175 +2,MSFT,2023-10-03,0.000585110392421484,-0.026481518521904945 +2,MSFT,2023-10-04,0.0006090899696573615,0.017617138102650642 +2,MSFT,2023-10-05,0.0005801619845442474,0.0012533541303128004 +2,MSFT,2023-10-06,0.0005532514187507331,0.024436060339212418 +2,MSFT,2023-10-09,0.0004704936291091144,0.0077921259216964245 +2,MSFT,2023-10-10,0.0004105749831069261,-0.004345213994383812 +2,MSFT,2023-10-11,0.0004157329094596207,0.012197322212159634 +2,MSFT,2023-10-12,0.0004175645299255848,-0.003797612152993679 +2,MSFT,2023-10-13,0.00043063642806373537,-0.010411755181849003 +2,MSFT,2023-10-16,0.0004189231258351356,0.014871126040816307 +2,MSFT,2023-10-17,0.0004343450127635151,-0.0017454816261306405 +2,MSFT,2023-10-18,0.0004325825138948858,-0.005889668129384518 +2,MSFT,2023-10-19,0.00042607681825757027,0.0036587610375136137 +2,MSFT,2023-10-20,0.00043653303873725235,-0.014134153723716736 +2,MSFT,2023-10-23,0.00045678671449422836,0.008079562336206436 +2,MSFT,2023-10-24,0.00045699405018240213,0.003667426761239767 +2,MSFT,2023-10-25,0.00044416190939955413,0.030216693878173828 +2,MSFT,2023-10-26,0.0004478251503314823,-0.038235947489738464 +2,MSFT,2023-10-27,0.000464381038909778,0.005838312674313784 +2,MSFT,2023-10-30,0.00046625800314359367,0.022485781461000443 +2,MSFT,2023-10-31,0.00045839586528018117,0.002368926303461194 +2,MSFT,2023-11-01,0.00048582698218524456,0.023269804194569588 +2,MSFT,2023-11-02,0.0005293539143167436,0.006480592302978039 +2,MSFT,2023-11-03,0.0005521951825357974,0.012779632583260536 +2,MSFT,2023-11-06,0.0005640078452415764,0.010517126880586147 +2,MSFT,2023-11-07,0.0005705395014956594,0.011156658641994 +2,MSFT,2023-11-08,0.0005701658665202558,0.007378543261438608 +2,MSFT,2023-11-09,0.0005666062934324145,-0.006934637203812599 +2,MSFT,2023-11-10,0.0005449377931654453,0.02459179051220417 +2,MSFT,2023-11-13,0.0005502058775164187,-0.008121241815388203 +2,MSFT,2023-11-14,0.0005251269321888685,0.009742824360728264 +2,MSFT,2023-11-15,0.0005180445150472224,0.00040597422048449516 +2,MSFT,2023-11-16,0.000501229427754879,0.017430325970053673 +2,MSFT,2023-11-17,0.0004978621145710349,-0.016943592578172684 +2,MSFT,2023-11-20,0.00048516603419557214,0.020314104855060577 +2,MSFT,2023-11-21,0.0004898444749414921,-0.011645383201539516 +2,MSFT,2023-11-22,0.0004800837195944041,0.012730991467833519 +2,MSFT,2023-11-24,0.00047186302253976464,-0.0011120670242235065 +2,MSFT,2023-11-27,0.0004722453304566443,0.0031215886119753122 +2,MSFT,2023-11-28,0.00046920415479689837,0.010744675993919373 +2,MSFT,2023-11-29,0.00048110104398801923,-0.010111097246408463 +2,MSFT,2023-11-30,0.0004636423254851252,0.00015855788660701364 +2,MSFT,2023-12-01,0.0004671327769756317,-0.011680182069540024 +2,MSFT,2023-12-04,0.00046174373710528016,-0.014442743733525276 +2,MSFT,2023-12-05,0.0004593289631884545,0.009114925749599934 +2,MSFT,2023-12-06,0.00045409976155497134,-0.010036428458988667 +2,MSFT,2023-12-07,0.00045370665611699224,0.005812921095639467 +2,MSFT,2023-12-08,0.0004572122124955058,0.008803167380392551 +2,MSFT,2023-12-11,0.00045954278903082013,-0.00786019116640091 +2,MSFT,2023-12-12,0.0004739711293950677,0.008260807022452354 +2,MSFT,2023-12-13,0.0005013180198147893,-2.65088674495928e-05 +2,MSFT,2023-12-14,0.000521651585586369,-0.022802481427788734 +2,MSFT,2023-12-15,0.0004695475799962878,0.013031837530434132 +2,MSFT,2023-12-18,0.00048019387759268284,0.005165735725313425 +2,MSFT,2023-12-19,0.0004900021012872458,0.0016355434199795127 +2,MSFT,2023-12-20,0.0005125043098814785,-0.007097969297319651 +2,MSFT,2023-12-21,0.0005088021862320602,0.007847821339964867 +2,MSFT,2023-12-22,0.0005354859749786556,0.002780287293717265 +2,MSFT,2023-12-26,0.0005497912061400712,0.0002135931426892057 +2,MSFT,2023-12-27,0.0005638069706037641,-0.0015760317910462618 +2,MSFT,2023-12-28,0.0005685912328772247,0.003229584777727723 +2,MSFT,2023-12-29,0.0005937166279181838,0.0020230207592248917 +2,MSFT,2024-01-02,0.0006129000685177743,-0.01384386233985424 +2,MSFT,2024-01-03,0.0005649279919452965,-0.0007283890736289322 +2,MSFT,2024-01-04,0.0005659258458763361,-0.007203548680990934 +2,MSFT,2024-01-05,0.0005390757578425109,-0.0005163308815099299 +2,MSFT,2024-01-08,0.0005204074550420046,0.01869543455541134 +2,MSFT,2024-01-09,0.0005750170676037669,0.00293180625885725 +2,MSFT,2024-01-10,0.0006026382325217128,0.018403610214591026 +2,MSFT,2024-01-11,0.0006300229579210281,0.0048476397059857845 +2,MSFT,2024-01-12,0.0006312616751529276,0.00993404071778059 +2,MSFT,2024-01-16,0.0006348914466798306,0.004623000510036945 +2,MSFT,2024-01-17,0.0006435862160287797,-0.002052064286544919 +2,MSFT,2024-01-18,0.0006388160400092602,0.011233964934945107 +2,MSFT,2024-01-19,0.0006343557615764439,0.012113051488995552 +2,MSFT,2024-01-22,0.0006318631931208074,-0.005432597361505032 +2,MSFT,2024-01-23,0.0006166453822515905,0.006009427830576897 +2,MSFT,2024-01-24,0.0006051178206689656,0.009133388288319111 +2,MSFT,2024-01-25,0.0006022818852216005,0.005721919238567352 +2,MSFT,2024-01-26,0.0005927846650592983,-0.002324520144611597 +2,MSFT,2024-01-29,0.0005826200358569622,0.014232429675757885 +2,MSFT,2024-01-30,0.0005825184634886682,-0.002761782379820943 +2,MSFT,2024-01-31,0.0005680987960658967,-0.027316071093082428 +2,MSFT,2024-02-01,0.000486170407384634,0.015474120154976845 +2,MSFT,2024-02-02,0.0004887148388661444,0.018258219584822655 +2,MSFT,2024-02-05,0.0005091585335321724,-0.01363769918680191 +2,MSFT,2024-02-06,0.0004974041949026287,-0.0003945866774301976 +2,MSFT,2024-02-07,0.0005010393797419965,0.020890522748231888 +2,MSFT,2024-02-08,0.0005440867971628904,0.00014492898480966687 +2,MSFT,2024-02-09,0.0005599104333668947,0.015431670472025871 +2,MSFT,2024-02-12,0.0005746908718720078,-0.012658478692173958 +2,MSFT,2024-02-13,0.0005568044725805521,-0.02176368050277233 +2,MSFT,2024-02-14,0.0004971688031218946,0.009618890471756458 +2,MSFT,2024-02-15,0.0004996073548682034,-0.00718107633292675 +2,MSFT,2024-02-16,0.0004895312595181167,-0.006167964078485966 +2,MSFT,2024-02-20,0.00047280691796913743,-0.0031480705365538597 +2,MSFT,2024-02-21,0.00047669047489762306,-0.0015155249275267124 +2,MSFT,2024-02-22,0.00047761277528479695,0.023273680359125137 +2,MSFT,2024-02-23,0.0005137549014762044,-0.0031874035485088825 +2,MSFT,2024-02-26,0.0005305159720592201,-0.006847062148153782 +2,MSFT,2024-02-27,0.0005335204186849296,-0.0001471461437176913 +2,MSFT,2024-02-28,0.0005314749432727695,0.0005889117019250989 +2,MSFT,2024-02-29,0.0005367041449062526,0.014415347948670387 +2,MSFT,2024-03-01,0.0005690340185537934,0.004486477933824062 +2,MSFT,2024-03-04,0.0005857432843185961,-0.0013967574341222644 +2,MSFT,2024-03-05,0.0006004913011565804,-0.03001820482313633 +2,MSFT,2024-03-06,0.0005369201535359025,-0.0013917827745899558 +2,MSFT,2024-03-07,0.000501760805491358,0.017381489276885986 +2,MSFT,2024-03-08,0.0005360172945074737,-0.0071625495329499245 +2,MSFT,2024-03-11,0.0005198696744628251,-0.004193710163235664 +2,MSFT,2024-03-12,0.0005101521383039653,0.026251865550875664 +2,MSFT,2024-03-13,0.0005650013918057084,-0.0004334972763899714 +2,MSFT,2024-03-14,0.0005819590878672898,0.024087121710181236 +2,MSFT,2024-03-15,0.0006081158062443137,-0.020912347361445427 +2,MSFT,2024-03-18,0.0005873545887880027,0.002159124705940485 +2,MSFT,2024-03-19,0.0005845315754413605,0.00975277740508318 +2,MSFT,2024-03-20,0.0005914238863624632,0.009024033322930336 +2,MSFT,2024-03-21,0.0006078933365643024,0.009688889607787132 +2,MSFT,2024-03-22,0.0006113017443567514,-0.0014684279449284077 +2,NVDA,2023-06-06,0.0011703821364790201,-0.01328651886433363 +2,NVDA,2023-06-07,0.0011080894619226456,-0.03087260015308857 +2,NVDA,2023-06-08,0.000998536474071443,0.027243852615356445 +2,NVDA,2023-06-09,0.0010292725637555122,0.006729009095579386 +2,NVDA,2023-06-12,0.0010696026729419827,0.018197862431406975 +2,NVDA,2023-06-13,0.0011633906979113817,0.03826356306672096 +2,NVDA,2023-06-14,0.0011426914716139436,0.04702204465866089 +2,NVDA,2023-06-15,0.0010791394161060452,-0.008032805286347866 +2,NVDA,2023-06-16,0.0010647064773365855,0.0009137820452451706 +2,NVDA,2023-06-20,0.0010416066506877542,0.025805002078413963 +2,NVDA,2023-06-21,0.0009662472293712199,-0.017570283263921738 +2,NVDA,2023-06-22,0.000957137846853584,-0.00046467705396935344 +2,NVDA,2023-06-23,0.0008864151313900948,-0.01914781890809536 +2,NVDA,2023-06-26,0.0008336555329151452,-0.038077596575021744 +2,NVDA,2023-06-27,0.0009412355138920248,0.030156835913658142 +2,NVDA,2023-06-28,0.0008891132310964167,-0.0182911679148674 +2,NVDA,2023-06-29,0.0009341296972706914,-0.0072004045359790325 +2,NVDA,2023-06-30,0.000963362108450383,0.0356130488216877 +2,NVDA,2023-07-03,0.0008420817903243005,0.002620335901156068 +2,NVDA,2023-07-05,0.0008002175600267947,-0.0022658519446849823 +2,NVDA,2023-07-06,0.0007827773224562407,-0.005069741979241371 +2,NVDA,2023-07-07,0.0007854296127334237,0.009455598890781403 +2,NVDA,2023-07-10,0.0007767438655719161,-0.00762840686365962 +2,NVDA,2023-07-11,0.0007791633252054453,0.005319859366863966 +2,NVDA,2023-07-12,0.0007766484632156789,0.0346936397254467 +2,NVDA,2023-07-13,0.0008032896439544857,0.04618155211210251 +2,NVDA,2023-07-14,0.0008375748293474317,-0.011110392399132252 +2,NVDA,2023-07-17,0.0007863264181651175,0.021582288667559624 +2,NVDA,2023-07-18,0.0007877079187892377,0.021990278735756874 +2,NVDA,2023-07-19,0.0007736298139207065,-0.00881886761635542 +2,NVDA,2023-07-20,0.0007615857175551355,-0.03363288193941116 +2,NVDA,2023-07-21,0.000797523302026093,-0.026963962242007256 +2,NVDA,2023-07-24,0.0009561074548400939,0.00681496225297451 +2,NVDA,2023-07-25,0.001004108227789402,0.023635895922780037 +2,NVDA,2023-07-26,0.0009492038516327739,-0.004981850739568472 +2,NVDA,2023-07-27,0.0009251233423128724,0.009808279573917389 +2,NVDA,2023-07-28,0.0008591633522883058,0.018349289894104004 +2,NVDA,2023-07-31,0.0007662110147066414,-0.0004494361055549234 +2,NVDA,2023-08-01,0.0007585975690744817,-0.0047621335834264755 +2,NVDA,2023-08-02,0.00075418601045385,-0.049318134784698486 +2,NVDA,2023-08-03,0.0009224519599229097,0.005541463848203421 +2,NVDA,2023-08-04,0.000956622650846839,0.003699878230690956 +2,NVDA,2023-08-07,0.0009716700878925622,0.016360552981495857 +2,NVDA,2023-08-08,0.0008736879681237042,-0.01671862043440342 +2,NVDA,2023-08-09,0.000870753254275769,-0.0483940914273262 +2,NVDA,2023-08-10,0.000999166164547205,-0.0039085280150175095 +2,NVDA,2023-08-11,0.0010497886687517166,-0.03683605417609215 +2,NVDA,2023-08-14,0.0011300176847726107,0.06853094696998596 +2,NVDA,2023-08-15,0.0009925792692229152,0.004265005234628916 +2,NVDA,2023-08-16,0.000890460389200598,-0.010386284440755844 +2,NVDA,2023-08-17,0.0008389410213567317,-0.0032707559876143932 +2,NVDA,2023-08-18,0.000805945775937289,-0.001038697431795299 +2,NVDA,2023-08-21,0.0007926881080493331,0.08131580054759979 +2,NVDA,2023-08-22,0.0007416954613290727,-0.02804756350815296 +2,NVDA,2023-08-23,0.0007428097887896001,0.031215021386742592 +2,NVDA,2023-08-24,0.0007509956485591829,0.0009969748789444566 +2,NVDA,2023-08-25,0.0007466680253855884,-0.024576956406235695 +2,NVDA,2023-08-28,0.0007665544981136918,0.01759806089103222 +2,NVDA,2023-08-29,0.0007742251036688685,0.04077158123254776 +2,NVDA,2023-08-30,0.0007833039853721857,0.009791241958737373 +2,NVDA,2023-08-31,0.0007972561870701611,0.0018454306991770864 +2,NVDA,2023-09-01,0.0007998397923074663,-0.01728975772857666 +2,NVDA,2023-09-05,0.0008011601748876274,0.000803750881459564 +2,NVDA,2023-09-06,0.0008090140181593597,-0.031026160344481468 +2,NVDA,2023-09-07,0.0008238783339038491,-0.017577553167939186 +2,NVDA,2023-09-08,0.0008635710692033172,-0.014573627151548862 +2,NVDA,2023-09-11,0.0009678309434093535,-0.008683132007718086 +2,NVDA,2023-09-12,0.0010280247079208493,-0.006840737536549568 +2,NVDA,2023-09-13,0.001084558549337089,0.013613150455057621 +2,NVDA,2023-09-14,0.0010376988211646676,0.0021083648316562176 +2,NVDA,2023-09-15,0.0009650680003687739,-0.03757668659090996 +2,NVDA,2023-09-18,0.0010695339879021049,0.0015022630104795098 +2,NVDA,2023-09-19,0.001028650556690991,-0.010195961222052574 +2,NVDA,2023-09-20,0.0010739379795268178,-0.029876623302698135 +2,NVDA,2023-09-21,0.001210036687552929,-0.029357492923736572 +2,NVDA,2023-09-22,0.0012582320487126708,0.014354192651808262 +2,NVDA,2023-09-25,0.0012431235518306494,0.014600851573050022 +2,NVDA,2023-09-26,0.0012185927480459213,-0.0073933652602136135 +2,NVDA,2023-09-27,0.001178346574306488,0.013202683068811893 +2,NVDA,2023-09-28,0.0011824567336589098,0.01451695617288351 +2,NVDA,2023-09-29,0.0011408519931137562,0.009470300748944283 +2,NVDA,2023-10-02,0.0011090664193034172,0.029068194329738617 +2,NVDA,2023-10-03,0.0009786500595510006,-0.028654547408223152 +2,NVDA,2023-10-04,0.0009396327077411115,0.011969292536377907 +2,NVDA,2023-10-05,0.0008641206077300012,0.014583790674805641 +2,NVDA,2023-10-06,0.00077107670949772,0.02374926581978798 +2,NVDA,2023-10-09,0.0007371159736067057,-0.010743247345089912 +2,NVDA,2023-10-10,0.0007385165081359446,0.0115296496078372 +2,NVDA,2023-10-11,0.0007431265548802912,0.021770967170596123 +2,NVDA,2023-10-12,0.0007458894979208708,0.002965290332213044 +2,NVDA,2023-10-13,0.0007409207173623145,-0.03212186321616173 +2,NVDA,2023-10-16,0.0008342585060745478,0.013849600218236446 +2,NVDA,2023-10-17,0.0008570567588321865,-0.04792478680610657 +2,NVDA,2023-10-18,0.0010936030885204673,-0.04045433923602104 +2,NVDA,2023-10-19,0.0012180890189483762,-0.002253727288916707 +2,NVDA,2023-10-20,0.0012051634257659316,-0.0171047355979681 +2,NVDA,2023-10-23,0.0011118714464828372,0.03765159100294113 +2,NVDA,2023-10-24,0.001220573321916163,0.015882665291428566 +2,NVDA,2023-10-25,0.0012053007958456874,-0.044107452034950256 +2,NVDA,2023-10-26,0.0012315565254539251,-0.03539730980992317 +2,NVDA,2023-10-27,0.0011473357444629073,0.004305540584027767 +2,NVDA,2023-10-30,0.001078612869605422,0.016189277172088623 +2,NVDA,2023-10-31,0.0010867948876693845,-0.009299545548856258 +2,NVDA,2023-11-01,0.001083986135199666,0.03718622773885727 +2,NVDA,2023-11-02,0.0011242665350437164,0.027521057054400444 +2,NVDA,2023-11-03,0.0010744797764346004,0.033874720335006714 +2,NVDA,2023-11-06,0.0009555235737934709,0.016440030187368393 +2,NVDA,2023-11-07,0.0008511148625984788,0.004449024330824614 +2,NVDA,2023-11-08,0.0007805753848515451,0.013379789888858795 +2,NVDA,2023-11-09,0.0007290522335097194,0.008040710352361202 +2,NVDA,2023-11-10,0.0007167143048718572,0.029072700068354607 +2,NVDA,2023-11-13,0.0007309450884349644,0.0058789607137441635 +2,NVDA,2023-11-14,0.0007240682025440037,0.02108430303633213 +2,NVDA,2023-11-15,0.0007387492805719376,-0.015587128698825836 +2,NVDA,2023-11-16,0.0007748052012175322,0.012036480940878391 +2,NVDA,2023-11-17,0.000817661639302969,-0.003685084404423833 +2,NVDA,2023-11-20,0.0008551753708161414,0.022286245599389076 +2,NVDA,2023-11-21,0.000852729135658592,-0.009267278015613556 +2,NVDA,2023-11-22,0.0009045537444762886,-0.02489490620791912 +2,NVDA,2023-11-24,0.000985778751783073,-0.019484136253595352 +2,NVDA,2023-11-27,0.001052540261298418,0.00970669835805893 +2,NVDA,2023-11-28,0.0010106683475896716,-0.0087652076035738 +2,NVDA,2023-11-29,0.0010085618123412132,0.0066485414281487465 +2,NVDA,2023-11-30,0.0009597137686796486,-0.028871173039078712 +2,NVDA,2023-12-01,0.000987133476883173,-0.00010705244494602084 +2,NVDA,2023-12-04,0.0009129036916419864,-0.027203217148780823 +2,NVDA,2023-12-05,0.0009162429487332702,0.023026593029499054 +2,NVDA,2023-12-06,0.0008062587003223598,-0.023092517629265785 +2,NVDA,2023-12-07,0.0008350942516699433,0.023736609145998955 +2,NVDA,2023-12-08,0.0007745266193524003,0.01934133656322956 +2,NVDA,2023-12-11,0.0007595173083245754,-0.018676185980439186 +2,NVDA,2023-12-12,0.0007665773737244308,0.021849729120731354 +2,NVDA,2023-12-13,0.0007667758036404848,0.00900301430374384 +2,NVDA,2023-12-14,0.0008281486807391047,0.005433488171547651 +2,NVDA,2023-12-15,0.0008525993907824159,0.011106844060122967 +2,NVDA,2023-12-18,0.0008781758951954544,0.023988880217075348 +2,NVDA,2023-12-19,0.0009141859482042491,-0.00949033722281456 +2,NVDA,2023-12-20,0.0009307942818850279,-0.030560510233044624 +2,NVDA,2023-12-21,0.0008799542556516826,0.018105139955878258 +2,NVDA,2023-12-22,0.0008867204305715859,-0.0032713476102799177 +2,NVDA,2023-12-26,0.0008670781971886754,0.009153241291642189 +2,NVDA,2023-12-27,0.0008810609579086304,0.002796492073684931 +2,NVDA,2023-12-28,0.0008822515956126153,0.0021224990487098694 +2,NVDA,2023-12-29,0.0008928378811106086,0.0 +2,NVDA,2024-01-02,0.0008920097607187927,-0.027722179889678955 +2,NVDA,2024-01-03,0.0008041979162953794,-0.0125134801492095 +2,NVDA,2024-01-04,0.0008534046355634928,0.008977956138551235 +2,NVDA,2024-01-05,0.0008582970476709306,0.02263874001801014 +2,NVDA,2024-01-08,0.0008082354906946421,0.062299326062202454 +2,NVDA,2024-01-09,0.0008692076662555337,0.01683262176811695 +2,NVDA,2024-01-10,0.0008871325990185142,0.022514570504426956 +2,NVDA,2024-01-11,0.0009160444606095552,0.008646930567920208 +2,NVDA,2024-01-12,0.0009124610223807395,-0.002044993219897151 +2,NVDA,2024-01-16,0.0008900405955500901,0.030103445053100586 +2,NVDA,2024-01-17,0.0009130067192018032,-0.005852331407368183 +2,NVDA,2024-01-18,0.0008963106665760279,0.018629061058163643 +2,NVDA,2024-01-19,0.0008736841264180839,0.04089837521314621 +2,NVDA,2024-01-22,0.0008576558902859688,0.002736121416091919 +2,NVDA,2024-01-23,0.0008456461946479976,0.003664469113573432 +2,NVDA,2024-01-24,0.0008517102105543017,0.024565108120441437 +2,NVDA,2024-01-25,0.0008621666929684579,0.004146924242377281 +2,NVDA,2024-01-26,0.0008626666385680437,-0.009555761702358723 +2,NVDA,2024-01-29,0.0008856175700202584,0.023224499076604843 +2,NVDA,2024-01-30,0.0008735200390219688,0.004934527911245823 +2,NVDA,2024-01-31,0.0008815914043225348,-0.020064838230609894 +2,NVDA,2024-02-01,0.0009548098896630108,0.024087145924568176 +2,NVDA,2024-02-02,0.0008832934545353055,0.048512790352106094 +2,NVDA,2024-02-05,0.000852145254611969,0.04683065414428711 +2,NVDA,2024-02-06,0.0008408071589656174,-0.016124814748764038 +2,NVDA,2024-02-07,0.0008545494638383389,0.02712668851017952 +2,NVDA,2024-02-08,0.0008543319418095052,-0.0065552229061722755 +2,NVDA,2024-02-09,0.0008453103364445269,0.03515828773379326 +2,NVDA,2024-02-12,0.0008493670029565692,0.0015929511282593012 +2,NVDA,2024-02-13,0.0008437075302936137,-0.0016622489783912897 +2,NVDA,2024-02-14,0.0008343806257471442,0.024270769208669662 +2,NVDA,2024-02-15,0.000842028355691582,-0.01694968156516552 +2,NVDA,2024-02-16,0.0008498975075781345,-0.0006194502930156887 +2,NVDA,2024-02-20,0.0008536183158867061,-0.04450816288590431 +2,NVDA,2024-02-21,0.0010000095935538411,-0.028923047706484795 +2,NVDA,2024-02-22,0.0011351733701303601,0.15187005698680878 +2,NVDA,2024-02-23,0.000966048741247505,0.0035459110513329506 +2,NVDA,2024-02-26,0.0009768028976395726,0.0034829406067728996 +2,NVDA,2024-02-27,0.0009627324179746211,-0.004955751821398735 +2,NVDA,2024-02-28,0.0009641444776207209,-0.01327707152813673 +2,NVDA,2024-02-29,0.000982813537120819,0.0184857789427042 +2,NVDA,2024-03-01,0.0009201316861435771,0.03925129398703575 +2,NVDA,2024-03-04,0.0008333807927556336,0.03531978651881218 +2,NVDA,2024-03-05,0.0008306216332130134,0.008539821021258831 +2,NVDA,2024-03-06,0.0008236226276494563,0.03133124113082886 +2,NVDA,2024-03-07,0.0008140591089613736,0.043774109333753586 +2,NVDA,2024-03-08,0.0008117082761600614,-0.05707525461912155 +2,NVDA,2024-03-11,0.0009974526474252343,-0.020242711529135704 +2,NVDA,2024-03-12,0.0011030558962374926,0.06912646442651749 +2,NVDA,2024-03-13,0.0010995526099577546,-0.011214522644877434 +2,NVDA,2024-03-14,0.0011405657278373837,-0.03292769938707352 +2,NVDA,2024-03-15,0.001163745648227632,-0.0012173826107755303 +2,NVDA,2024-03-18,0.0011033611372113228,0.007011161185801029 +2,NVDA,2024-03-19,0.0010936640901491046,0.010604415088891983 +2,NVDA,2024-03-20,0.0011445613345131278,0.010836123488843441 +2,NVDA,2024-03-21,0.0011304031359031796,0.011693613603711128 +2,NVDA,2024-03-22,0.0010709002381190658,0.030736342072486877 +2,TSLA,2023-06-06,0.0010227651800960302,0.016859950497746468 +2,TSLA,2023-06-07,0.0010220921831205487,0.014623072929680347 +2,TSLA,2023-06-08,0.0010081796208396554,0.04480209946632385 +2,TSLA,2023-06-09,0.0009967254009097815,0.03981660678982735 +2,TSLA,2023-06-12,0.0009672293090261519,0.021974490955471992 +2,TSLA,2023-06-13,0.0009756116196513176,0.034927017986774445 +2,TSLA,2023-06-14,0.0009743114933371544,-0.007449046708643436 +2,TSLA,2023-06-15,0.000985852675512433,-0.003471944248303771 +2,TSLA,2023-06-16,0.0009999803733080626,0.017969714477658272 +2,TSLA,2023-06-20,0.0009813203942030668,0.05201270803809166 +2,TSLA,2023-06-21,0.000980404787696898,-0.056166619062423706 +2,TSLA,2023-06-22,0.001038385322317481,0.019654473289847374 +2,TSLA,2023-06-23,0.0010150100570172071,-0.03073851205408573 +2,TSLA,2023-06-26,0.0010663203429430723,-0.06251408159732819 +2,TSLA,2023-06-27,0.0012391130439937115,0.037296198308467865 +2,TSLA,2023-06-28,0.0011788205010816455,0.023813875392079353 +2,TSLA,2023-06-29,0.001071781967766583,0.00490525271743536 +2,TSLA,2023-06-30,0.0010131833842024207,0.016446493566036224 +2,TSLA,2023-07-03,0.0009677328635007143,0.06668034940958023 +2,TSLA,2023-07-05,0.0010027866810560226,0.009461225010454655 +2,TSLA,2023-07-06,0.001083661918528378,-0.021252285689115524 +2,TSLA,2023-07-07,0.001086747506633401,-0.0076593137346208096 +2,TSLA,2023-07-10,0.0010833918349817395,-0.017719777300953865 +2,TSLA,2023-07-11,0.0010786352213472128,0.0006674942560493946 +2,TSLA,2023-07-12,0.0010809792438521981,0.008121354505419731 +2,TSLA,2023-07-13,0.0010857540182769299,0.02149605005979538 +2,TSLA,2023-07-14,0.0011194070102646947,0.012444771826267242 +2,TSLA,2023-07-17,0.0011296526063233614,0.03148433938622475 +2,TSLA,2023-07-18,0.0011606274638324976,0.010141906328499317 +2,TSLA,2023-07-19,0.001165539724752307,-0.0071159605868160725 +2,TSLA,2023-07-20,0.0011483445996418595,-0.1024426594376564 +2,TSLA,2023-07-21,0.001014414825476706,-0.011015200056135654 +2,TSLA,2023-07-24,0.0011278123129159212,0.03417588397860527 +2,TSLA,2023-07-25,0.0010916047031059861,-0.014148526825010777 +2,TSLA,2023-07-26,0.001081844442524016,-0.003511861665174365 +2,TSLA,2023-07-27,0.0010625389404594898,-0.03322998806834221 +2,TSLA,2023-07-28,0.0010991401504725218,0.04110506922006607 +2,TSLA,2023-07-31,0.001028295373544097,0.0037087358068674803 +2,TSLA,2023-08-01,0.001020375406369567,-0.024069223552942276 +2,TSLA,2023-08-02,0.0010141127277165651,-0.02702135220170021 +2,TSLA,2023-08-03,0.0009915294358506799,0.020295601338148117 +2,TSLA,2023-08-04,0.0009750714525580406,-0.021279912441968918 +2,TSLA,2023-08-07,0.0009865759639069438,-0.009538785554468632 +2,TSLA,2023-08-08,0.0009696785127744079,-0.006983965635299683 +2,TSLA,2023-08-09,0.000985262100584805,-0.03053763322532177 +2,TSLA,2023-08-10,0.0011158956913277507,0.0129224369302392 +2,TSLA,2023-08-11,0.0011024546111002564,-0.011024937964975834 +2,TSLA,2023-08-14,0.001097730128094554,-0.01198165025562048 +2,TSLA,2023-08-15,0.0010914033045992255,-0.02877160534262657 +2,TSLA,2023-08-16,0.0011946558952331543,-0.032103247940540314 +2,TSLA,2023-08-17,0.0012528150109574199,-0.028687750920653343 +2,TSLA,2023-08-18,0.0013107223203405738,-0.01716126687824726 +2,TSLA,2023-08-21,0.0013097655028104782,0.0707145631313324 +2,TSLA,2023-08-22,0.0012523846235126257,0.008224490098655224 +2,TSLA,2023-08-23,0.001202310319058597,0.015615669079124928 +2,TSLA,2023-08-24,0.0011105394223704934,-0.02921607345342636 +2,TSLA,2023-08-25,0.0011056455550715327,0.03649340569972992 +2,TSLA,2023-08-28,0.000968172331340611,0.0009635784663259983 +2,TSLA,2023-08-29,0.0008758887415751815,0.07406604290008545 +2,TSLA,2023-08-30,0.0008811626466922462,-0.0010893200524151325 +2,TSLA,2023-08-31,0.0009103475022129714,0.004582682158797979 +2,TSLA,2023-09-01,0.0009562557679601014,-0.05197056010365486 +2,TSLA,2023-09-05,0.0009378247195854783,0.04579063504934311 +2,TSLA,2023-09-06,0.0009968307567760348,-0.017978070303797722 +2,TSLA,2023-09-07,0.0010003146016970277,-0.0017083203420042992 +2,TSLA,2023-09-08,0.000998954870738089,-0.011960403993725777 +2,TSLA,2023-09-11,0.0009883202146738768,0.0961511880159378 +2,TSLA,2023-09-12,0.0010414891876280308,-0.02254919707775116 +2,TSLA,2023-09-13,0.0010315458057448268,0.014180336147546768 +2,TSLA,2023-09-14,0.0010472850408405066,0.01732063852250576 +2,TSLA,2023-09-15,0.0010754534741863608,-0.005995308514684439 +2,TSLA,2023-09-18,0.001088564982637763,-0.033764638006687164 +2,TSLA,2023-09-19,0.0010619530221447349,0.004588376265019178 +2,TSLA,2023-09-20,0.0010651667835190892,-0.0147803770378232 +2,TSLA,2023-09-21,0.0010458383476361632,-0.02658899687230587 +2,TSLA,2023-09-22,0.0010112697491422296,-0.04323655739426613 +2,TSLA,2023-09-25,0.0010335372062399983,0.00857955776154995 +2,TSLA,2023-09-26,0.0010212360648438334,-0.011687985621392727 +2,TSLA,2023-09-27,0.001027141697704792,-0.014939798042178154 +2,TSLA,2023-09-28,0.0010262764990329742,0.024154987186193466 +2,TSLA,2023-09-29,0.0010150832822546363,0.015465456061065197 +2,TSLA,2023-10-02,0.0010249076876789331,0.0055000134743750095 +2,TSLA,2023-10-03,0.0010544175747781992,-0.020356863737106323 +2,TSLA,2023-10-04,0.0010088159469887614,0.05764957517385483 +2,TSLA,2023-10-05,0.0010704543674364686,-0.004259387031197548 +2,TSLA,2023-10-06,0.0011099717812612653,0.0018441397696733475 +2,TSLA,2023-10-09,0.0011163260787725449,-0.003306367201730609 +2,TSLA,2023-10-10,0.0011021570535376668,0.015097009018063545 +2,TSLA,2023-10-11,0.0011289521353319287,-0.002392682246863842 +2,TSLA,2023-10-12,0.0011361625511199236,-0.01578998565673828 +2,TSLA,2023-10-13,0.001123870606534183,-0.03039509244263172 +2,TSLA,2023-10-16,0.0010557726491242647,0.0110883554443717 +2,TSLA,2023-10-17,0.001084298244677484,0.0036559109576046467 +2,TSLA,2023-10-18,0.0010850674007087946,-0.048931486904621124 +2,TSLA,2023-10-19,0.0010008731624111533,-0.09761624783277512 +2,TSLA,2023-10-20,0.0013121414231136441,-0.037588294595479965 +2,TSLA,2023-10-23,0.0014364985981956124,0.0004244409501552582 +2,TSLA,2023-10-24,0.0014643421163782477,0.020719371736049652 +2,TSLA,2023-10-25,0.001378957531414926,-0.019117502495646477 +2,TSLA,2023-10-26,0.0012052677338942885,-0.0318550243973732 +2,TSLA,2023-10-27,0.0009148934623226523,0.007456619758158922 +2,TSLA,2023-10-30,0.0006877781706862152,-0.04913755878806114 +2,TSLA,2023-10-31,0.00043237084173597395,0.017479076981544495 +2,TSLA,2023-11-01,0.0003054042172152549,0.023715784773230553 +2,TSLA,2023-11-02,0.00043161545181646943,0.0606074184179306 +2,TSLA,2023-11-03,0.0007263067527674139,0.006613987032324076 +2,TSLA,2023-11-06,0.0009416931425221264,-0.003141875611618161 +2,TSLA,2023-11-07,0.0010922686196863651,0.013183964416384697 +2,TSLA,2023-11-08,0.0011883198749274015,-0.00031507379026152194 +2,TSLA,2023-11-09,0.0011870517628267407,-0.056160490959882736 +2,TSLA,2023-11-10,0.0012154995929449797,0.021996498107910156 +2,TSLA,2023-11-13,0.0011889744782820344,0.041341833770275116 +2,TSLA,2023-11-14,0.0010857220040634274,0.05943801999092102 +2,TSLA,2023-11-15,0.000980308628641069,0.02261415496468544 +2,TSLA,2023-11-16,0.0009253313182853162,-0.038835350424051285 +2,TSLA,2023-11-17,0.0009705483680590987,0.0030349320732057095 +2,TSLA,2023-11-20,0.000995159731246531,0.005533119197934866 +2,TSLA,2023-11-21,0.0010059501510113478,0.02349097467958927 +2,TSLA,2023-11-22,0.0010097086196765304,-0.029408274218440056 +2,TSLA,2023-11-24,0.0010183198610320687,0.005280385725200176 +2,TSLA,2023-11-27,0.0010222295532003045,0.0026721747126430273 +2,TSLA,2023-11-28,0.0010259789414703846,0.044083356857299805 +2,TSLA,2023-11-29,0.0010647318558767438,-0.010512266308069229 +2,TSLA,2023-11-30,0.0010659038089215755,-0.016769619658589363 +2,TSLA,2023-12-01,0.001061861403286457,-0.005220199469476938 +2,TSLA,2023-12-04,0.0010624474380165339,-0.013701443560421467 +2,TSLA,2023-12-05,0.0010148131987079978,0.013240755535662174 +2,TSLA,2023-12-06,0.0010202426929026842,0.0027191294357180595 +2,TSLA,2023-12-07,0.0010302182054147124,0.013568409718573093 +2,TSLA,2023-12-08,0.001078946515917778,0.004933396354317665 +2,TSLA,2023-12-11,0.0011397425550967455,-0.016957230865955353 +2,TSLA,2023-12-12,0.0011519017862156034,-0.011452714912593365 +2,TSLA,2023-12-13,0.0011358557967469096,0.009573866613209248 +2,TSLA,2023-12-14,0.0011839387007057667,0.04797596111893654 +2,TSLA,2023-12-15,0.0012269355356693268,0.00971168838441372 +2,TSLA,2023-12-18,0.0012890729121863842,-0.005617318209260702 +2,TSLA,2023-12-19,0.001306141959503293,0.020185250788927078 +2,TSLA,2023-12-20,0.0013306160690262914,-0.039976779371500015 +2,TSLA,2023-12-21,0.0012737319339066744,0.029345860704779625 +2,TSLA,2023-12-22,0.0012772295158356428,-0.007731210440397263 +2,TSLA,2023-12-26,0.0012706280685961246,0.015987740829586983 +2,TSLA,2023-12-27,0.0012874522944912314,0.0186474546790123 +2,TSLA,2023-12-28,0.0012863993179053068,-0.03210415318608284 +2,TSLA,2023-12-29,0.0012716901255771518,-0.01873832754790783 +2,TSLA,2024-01-02,0.0012431370560079813,-0.00024148747615981847 +2,TSLA,2024-01-03,0.0012231997679919004,-0.04096122458577156 +2,TSLA,2024-01-04,0.0011276794830337167,-0.0021831500343978405 +2,TSLA,2024-01-05,0.0010413702111691236,-0.0018509415676817298 +2,TSLA,2024-01-08,0.001040669740177691,0.012386614456772804 +2,TSLA,2024-01-09,0.0010461451020091772,-0.023096838966012 +2,TSLA,2024-01-10,0.0010327819036319852,-0.004350632894784212 +2,TSLA,2024-01-11,0.0010324568720534444,-0.029145965352654457 +2,TSLA,2024-01-12,0.0010280573042109609,-0.0373493991792202 +2,TSLA,2024-01-16,0.0011065977159887552,0.004649070557206869 +2,TSLA,2024-01-17,0.0011426404817029834,-0.020025473088026047 +2,TSLA,2024-01-18,0.0012616505846381187,-0.017172815278172493 +2,TSLA,2024-01-19,0.0013045556843280792,0.0014620114816352725 +2,TSLA,2024-01-22,0.0013204413698986173,-0.01610524021089077 +2,TSLA,2024-01-23,0.0013725804165005684,0.0016270106425508857 +2,TSLA,2024-01-24,0.0013614649651572108,-0.006283434573560953 +2,TSLA,2024-01-25,0.001371060498058796,-0.1292581707239151 +2,TSLA,2024-01-26,0.0014653813559561968,0.0033890658523887396 +2,TSLA,2024-01-29,0.0013644818682223558,0.04105548933148384 +2,TSLA,2024-01-30,0.0013978281058371067,0.003450822550803423 +2,TSLA,2024-01-31,0.0013565024128183722,-0.022699469700455666 +2,TSLA,2024-02-01,0.001358713605441153,0.008347821421921253 +2,TSLA,2024-02-02,0.0013343081809580326,-0.005042859353125095 +2,TSLA,2024-02-05,0.0013130020815879107,-0.03713468834757805 +2,TSLA,2024-02-06,0.001325738150626421,0.022067798301577568 +2,TSLA,2024-02-07,0.0013047022512182593,0.013309177942574024 +2,TSLA,2024-02-08,0.0012973224511370063,0.01050015352666378 +2,TSLA,2024-02-09,0.0012902036542072892,0.02093365788459778 +2,TSLA,2024-02-12,0.0012434163363650441,-0.028506003320217133 +2,TSLA,2024-02-13,0.0012171384878456593,-0.02208876796066761 +2,TSLA,2024-02-14,0.0012025301111862063,0.025167010724544525 +2,TSLA,2024-02-15,0.0010885465890169144,0.060353342443704605 +2,TSLA,2024-02-16,0.0009608566761016846,-0.0024975037667900324 +2,TSLA,2024-02-20,0.0009737163200043142,-0.031447067856788635 +2,TSLA,2024-02-21,0.0009778410894796252,0.005199145525693893 +2,TSLA,2024-02-22,0.0009822177235037088,0.013463405892252922 +2,TSLA,2024-02-23,0.0010310971410945058,-0.02794368751347065 +2,TSLA,2024-02-26,0.0009944959310814738,0.037973709404468536 +2,TSLA,2024-02-27,0.0010583775583654642,0.0016536061884835362 +2,TSLA,2024-02-28,0.0010581349488347769,0.011499231681227684 +2,TSLA,2024-02-29,0.0010906296083703637,-0.0007921787328086793 +2,TSLA,2024-03-01,0.0011087494203820825,0.0037575173191726208 +2,TSLA,2024-03-04,0.0011268967064097524,-0.07424464076757431 +2,TSLA,2024-03-05,0.0010173172922804952,-0.04012679681181908 +2,TSLA,2024-03-06,0.0011903754202648997,-0.02351212315261364 +2,TSLA,2024-03-07,0.0013443157076835632,0.011881108395755291 +2,TSLA,2024-03-08,0.001381406793370843,-0.018701624125242233 +2,TSLA,2024-03-11,0.0014234192203730345,0.013763678260147572 +2,TSLA,2024-03-12,0.0014083529822528362,-0.0012947061331942677 +2,TSLA,2024-03-13,0.0013916706666350365,-0.04646099731326103 +2,TSLA,2024-03-14,0.0014154443051666021,-0.04205689951777458 +2,TSLA,2024-03-15,0.0014364024391397834,0.006563075818121433 +2,TSLA,2024-03-18,0.0014136177487671375,0.06066415086388588 +2,TSLA,2024-03-19,0.0013429835671558976,-0.01437203399837017 +2,TSLA,2024-03-20,0.0013430063845589757,0.025017132982611656 +2,TSLA,2024-03-21,0.0012816289672628045,-0.016299696639180183 +2,TSLA,2024-03-22,0.001215293537825346,-0.011581712402403355 +2,GOOGL,2023-06-06,0.0005108852055855095,0.010263851843774319 +2,GOOGL,2023-06-07,0.000452764390502125,-0.038514021784067154 +2,GOOGL,2023-06-08,0.0005141383735463023,-0.002943090396001935 +2,GOOGL,2023-06-09,0.0005087858298793435,0.0007366637582890689 +2,GOOGL,2023-06-12,0.0004988756845705211,0.011469529010355473 +2,GOOGL,2023-06-13,0.0004504435637500137,0.001535490620881319 +2,GOOGL,2023-06-14,0.00044903953676111996,-0.001292917411774397 +2,GOOGL,2023-06-15,0.00044407451059669256,0.011416852474212646 +2,GOOGL,2023-06-16,0.0004526802513282746,-0.012549488805234432 +2,GOOGL,2023-06-20,0.0004482865915633738,-0.003486971603706479 +2,GOOGL,2023-06-21,0.00045210003736428916,-0.020932432264089584 +2,GOOGL,2023-06-22,0.00046236003981903195,0.021338460966944695 +2,GOOGL,2023-06-23,0.00045855544158257544,-0.006599122658371925 +2,GOOGL,2023-06-26,0.0004736741539090872,-0.03324209526181221 +2,GOOGL,2023-06-27,0.0004670482303481549,-8.45579052111134e-05 +2,GOOGL,2023-06-28,0.00046397221740335226,0.015513227321207523 +2,GOOGL,2023-06-29,0.00045839601079933345,-0.009026977233588696 +2,GOOGL,2023-06-30,0.00045830520684830844,0.005024879705160856 +2,GOOGL,2023-07-03,0.00046465208288282156,0.001669642748311162 +2,GOOGL,2023-07-05,0.00046192819718271494,0.015311766415834427 +2,GOOGL,2023-07-06,0.000489811587613076,-0.01356191374361515 +2,GOOGL,2023-07-07,0.0004963821265846491,-0.0052588945254683495 +2,GOOGL,2023-07-10,0.0004893531440757215,-0.025687094777822495 +2,GOOGL,2023-07-11,0.00047208191244862974,0.005907753482460976 +2,GOOGL,2023-07-12,0.00046998029574751854,0.015165366232395172 +2,GOOGL,2023-07-13,0.00047001129132695496,0.04609192535281181 +2,GOOGL,2023-07-14,0.0005001889658160508,0.007041058503091335 +2,GOOGL,2023-07-17,0.0005230829119682312,-0.006158210337162018 +2,GOOGL,2023-07-18,0.0005305171944200993,-0.007165617309510708 +2,GOOGL,2023-07-19,0.0005108010373078287,-0.014077381230890751 +2,GOOGL,2023-07-20,0.0004895989550277591,-0.02346419356763363 +2,GOOGL,2023-07-21,0.00046964368084445596,0.006855745799839497 +2,GOOGL,2023-07-24,0.00047881412319839,0.012502803467214108 +2,GOOGL,2023-07-25,0.00047159247333183885,0.005579567514359951 +2,GOOGL,2023-07-26,0.0004766327911056578,0.056162551045417786 +2,GOOGL,2023-07-27,0.0004700577992480248,0.0010050467681139708 +2,GOOGL,2023-07-28,0.0004835798463318497,0.024277999997138977 +2,GOOGL,2023-07-31,0.00048589182551950216,0.0010552468011155725 +2,GOOGL,2023-08-01,0.0004841113113798201,-0.008854500018060207 +2,GOOGL,2023-08-02,0.00046719660167582333,-0.02439242973923683 +2,GOOGL,2023-08-03,0.00047378268209286034,0.0005449639284051955 +2,GOOGL,2023-08-04,0.0005116204265505075,-0.002650466514751315 +2,GOOGL,2023-08-07,0.0005581259028986096,0.026345795020461082 +2,GOOGL,2023-08-08,0.000512920378241688,-0.0009886457119137049 +2,GOOGL,2023-08-09,0.0004922830266878009,-0.013330656103789806 +2,GOOGL,2023-08-10,0.0005065136938355863,0.00023137136304285377 +2,GOOGL,2023-08-11,0.0005145325558260083,-0.0010030358098447323 +2,GOOGL,2023-08-14,0.0005085643497295678,0.013569360598921776 +2,GOOGL,2023-08-15,0.0004929584683850408,-0.011872531846165657 +2,GOOGL,2023-08-16,0.0005474495701491833,-0.008356798440217972 +2,GOOGL,2023-08-17,0.000592971860896796,0.009434918873012066 +2,GOOGL,2023-08-18,0.0005546645843423903,-0.019116338342428207 +2,GOOGL,2023-08-21,0.0005756540922448039,0.007114058826118708 +2,GOOGL,2023-08-22,0.0005028641317039728,0.005515637807548046 +2,GOOGL,2023-08-23,0.0004629380418919027,0.025168683379888535 +2,GOOGL,2023-08-24,0.0004674202937167138,-0.019760161638259888 +2,GOOGL,2023-08-25,0.00045728651457466185,0.0007700010901317 +2,GOOGL,2023-08-28,0.00046785431914031506,0.008662617765367031 +2,GOOGL,2023-08-29,0.0004913041484542191,0.026811139658093452 +2,GOOGL,2023-08-30,0.0005157527630217373,0.009687567129731178 +2,GOOGL,2023-08-31,0.0005392557941377163,0.0021318038925528526 +2,GOOGL,2023-09-01,0.0005439262604340911,-0.0037520560435950756 +2,GOOGL,2023-09-05,0.0005396499764174223,0.0008103408035822213 +2,GOOGL,2023-09-06,0.0005470376927405596,-0.009695454500615597 +2,GOOGL,2023-09-07,0.0005321470671333373,0.005931982304900885 +2,GOOGL,2023-09-08,0.000531664292793721,0.008246234618127346 +2,GOOGL,2023-09-11,0.000541341898497194,0.003951887600123882 +2,GOOGL,2023-09-12,0.0005490684416145086,-0.011606820859014988 +2,GOOGL,2023-09-13,0.0005334802553988993,0.010071630589663982 +2,GOOGL,2023-09-14,0.0005441565881483257,0.01011623628437519 +2,GOOGL,2023-09-15,0.0005590449436567724,-0.005081458482891321 +2,GOOGL,2023-09-18,0.0005488846218213439,0.005877709947526455 +2,GOOGL,2023-09-19,0.000546094321180135,-0.001230747438967228 +2,GOOGL,2023-09-20,0.0005468229064717889,-0.031645774841308594 +2,GOOGL,2023-09-21,0.0004961119848303497,-0.024984387680888176 +2,GOOGL,2023-09-22,0.0006161980563774705,-0.0014575052773579955 +2,GOOGL,2023-09-25,0.0006494029657915235,0.006581032648682594 +2,GOOGL,2023-09-26,0.0006422344595193863,-0.019563116133213043 +2,GOOGL,2023-09-27,0.0006685233674943447,0.0152060491964221 +2,GOOGL,2023-09-28,0.0006474541733041406,0.013468055985867977 +2,GOOGL,2023-09-29,0.0006147187086753547,-0.011019840836524963 +2,GOOGL,2023-10-02,0.0006140897748991847,0.02497965656220913 +2,GOOGL,2023-10-03,0.0005359273054637015,-0.013053405098617077 +2,GOOGL,2023-10-04,0.0005059068789705634,0.0209969375282526 +2,GOOGL,2023-10-05,0.0004345386696513742,-0.0012579065514728427 +2,GOOGL,2023-10-06,0.00042916840175166726,0.018412338569760323 +2,GOOGL,2023-10-09,0.00043506131623871624,0.006086931563913822 +2,GOOGL,2023-10-10,0.000457671849289909,-0.0026042135432362556 +2,GOOGL,2023-10-11,0.0004633122880477458,0.017875105142593384 +2,GOOGL,2023-10-12,0.00047514462494291365,-0.011305459775030613 +2,GOOGL,2023-10-13,0.00046011447557248175,-0.011652914807200432 +2,GOOGL,2023-10-16,0.00044376225559972227,0.012587953358888626 +2,GOOGL,2023-10-17,0.0004508133861236274,0.004447300452739 +2,GOOGL,2023-10-18,0.00045132936793379486,-0.012676458805799484 +2,GOOGL,2023-10-19,0.00045757440966553986,-0.0015233849408105016 +2,GOOGL,2023-10-20,0.00048492185305804014,-0.015731189399957657 +2,GOOGL,2023-10-23,0.0005587991327047348,0.00661546690389514 +2,GOOGL,2023-10-24,0.0005570584908127785,0.016781412065029144 +2,GOOGL,2023-10-25,0.0004734394315164536,-0.0999242439866066 +2,GOOGL,2023-10-26,0.0006897852290421724,-0.026868464425206184 +2,GOOGL,2023-10-27,0.0006183084915392101,-0.0008999672718346119 +2,GOOGL,2023-10-30,0.00048000997048802674,0.018570879474282265 +2,GOOGL,2023-10-31,0.0004038760671392083,-0.0030578235164284706 +2,GOOGL,2023-11-01,0.0003244047984480858,0.018920432776212692 +2,GOOGL,2023-11-02,0.0003578068281058222,0.008190910331904888 +2,GOOGL,2023-11-03,0.0004252397920936346,0.012549538165330887 +2,GOOGL,2023-11-06,0.0005115628591738641,0.008868384175002575 +2,GOOGL,2023-11-07,0.0005901615950278938,0.00551270367577672 +2,GOOGL,2023-11-08,0.0006216989713720977,0.0066207535564899445 +2,GOOGL,2023-11-09,0.0006201864453032613,-0.012210399843752384 +2,GOOGL,2023-11-10,0.0006220466457307339,0.017882879823446274 +2,GOOGL,2023-11-13,0.0006024235626682639,-0.003778268815949559 +2,GOOGL,2023-11-14,0.000558668514713645,0.011516468599438667 +2,GOOGL,2023-11-15,0.0005413861363194883,0.007455931045114994 +2,GOOGL,2023-11-16,0.0005063830176368356,0.01701412722468376 +2,GOOGL,2023-11-17,0.00048187904758378863,-0.011901495978236198 +2,GOOGL,2023-11-20,0.00048923579743132,0.00692283408716321 +2,GOOGL,2023-11-21,0.00048016058281064034,0.005270581692457199 +2,GOOGL,2023-11-22,0.0004684677696786821,0.011035955511033535 +2,GOOGL,2023-11-24,0.00046743135317228734,-0.013082088902592659 +2,GOOGL,2023-11-27,0.0004713289672508836,-0.002050667069852352 +2,GOOGL,2023-11-28,0.00046978762838989496,0.005774502642452717 +2,GOOGL,2023-11-29,0.0004775053239427507,-0.016238950192928314 +2,GOOGL,2023-11-30,0.00047057378105819225,-0.018391834571957588 +2,GOOGL,2023-12-01,0.0005184944020584226,-0.005068143364042044 +2,GOOGL,2023-12-04,0.0005618419381789863,-0.019837353378534317 +2,GOOGL,2023-12-05,0.0006193582084961236,0.013217722997069359 +2,GOOGL,2023-12-06,0.0005933527718298137,-0.0074326773174107075 +2,GOOGL,2023-12-07,0.0006052493117749691,0.05178161337971687 +2,GOOGL,2023-12-08,0.00048552421503700316,-0.014269327744841576 +2,GOOGL,2023-12-11,0.0004805724893230945,-0.012673383578658104 +2,GOOGL,2023-12-12,0.00048676657024770975,-0.005793721880763769 +2,GOOGL,2023-12-13,0.0004894129233434796,0.0003772304335143417 +2,GOOGL,2023-12-14,0.0004965548869222403,-0.004763442557305098 +2,GOOGL,2023-12-15,0.0004978924407623708,0.00498961890116334 +2,GOOGL,2023-12-18,0.0004982755635865033,0.023846257477998734 +2,GOOGL,2023-12-19,0.000503393413964659,0.006239811424165964 +2,GOOGL,2023-12-20,0.0005150485667400062,0.01229124516248703 +2,GOOGL,2023-12-21,0.0005289249238558114,0.014923754148185253 +2,GOOGL,2023-12-22,0.0005501491250470281,0.007590982131659985 +2,GOOGL,2023-12-26,0.0005566864856518805,0.00021213725267443806 +2,GOOGL,2023-12-27,0.0005647496436722577,-0.008159367367625237 +2,GOOGL,2023-12-28,0.0005591601366177201,-0.0009979279711842537 +2,GOOGL,2023-12-29,0.0005636910791508853,-0.0038582070264965296 +2,GOOGL,2024-01-02,0.0005623025936074555,-0.010940850712358952 +2,GOOGL,2024-01-03,0.0005465261056087911,0.005413418170064688 +2,GOOGL,2024-01-04,0.0005564539460465312,-0.018379826098680496 +2,GOOGL,2024-01-05,0.0005382990930229425,-0.004850856959819794 +2,GOOGL,2024-01-08,0.000532778212800622,0.022654622793197632 +2,GOOGL,2024-01-09,0.000555045495275408,0.015083074569702148 +2,GOOGL,2024-01-10,0.0005626723868772388,0.009391644038259983 +2,GOOGL,2024-01-11,0.0005811904557049274,-0.0014066682197153568 +2,GOOGL,2024-01-12,0.0005763627123087645,0.004003886133432388 +2,GOOGL,2024-01-16,0.0005786658730357885,-0.001122083282098174 +2,GOOGL,2024-01-17,0.000588901515584439,-0.007184446323662996 +2,GOOGL,2024-01-18,0.000588507333304733,0.014108018949627876 +2,GOOGL,2024-01-19,0.0005917317466810346,0.020010333508253098 +2,GOOGL,2024-01-22,0.0006048927898518741,-0.00266749644652009 +2,GOOGL,2024-01-23,0.0005988426273688674,0.007166218012571335 +2,GOOGL,2024-01-24,0.0006022109882906079,0.011226031929254532 +2,GOOGL,2024-01-25,0.0006125064101070166,0.021094026044011116 +2,GOOGL,2024-01-26,0.0006154163274914026,0.0021049303468316793 +2,GOOGL,2024-01-29,0.0006120657199062407,0.00863625481724739 +2,GOOGL,2024-01-30,0.0006088900263421237,-0.013444250449538231 +2,GOOGL,2024-01-31,0.0005921103875152767,-0.07796505838632584 +2,GOOGL,2024-02-01,0.0005952395731583238,0.0075375898741185665 +2,GOOGL,2024-02-02,0.0006763252313248813,0.008605411276221275 +2,GOOGL,2024-02-05,0.0006897475686855614,0.00908895954489708 +2,GOOGL,2024-02-06,0.0006777669186703861,0.002918984740972519 +2,GOOGL,2024-02-07,0.000655984622426331,0.009943420067429543 +2,GOOGL,2024-02-08,0.0005739488988183439,0.0025391154922544956 +2,GOOGL,2024-02-09,0.0005276426672935486,0.020956171676516533 +2,GOOGL,2024-02-12,0.0005295649170875549,-0.009914534166455269 +2,GOOGL,2024-02-13,0.0005449848249554634,-0.01633281633257866 +2,GOOGL,2024-02-14,0.0005199958686716855,0.005496679339557886 +2,GOOGL,2024-02-15,0.0005282096099108458,-0.021960509940981865 +2,GOOGL,2024-02-16,0.0005056455847807229,-0.015885228291153908 +2,GOOGL,2024-02-20,0.000502961571328342,0.004260765854269266 +2,GOOGL,2024-02-21,0.0005124774761497974,0.010082137770950794 +2,GOOGL,2024-02-22,0.0005091268685646355,0.010745462961494923 +2,GOOGL,2024-02-23,0.0005090294289402664,-0.0009027495980262756 +2,GOOGL,2024-02-26,0.0005051871994510293,-0.045402348041534424 +2,GOOGL,2024-02-27,0.0005699914763681591,0.00947741698473692 +2,GOOGL,2024-02-28,0.0005704056238755584,-0.018165482208132744 +2,GOOGL,2024-02-29,0.0006313720950856805,0.015136506408452988 +2,GOOGL,2024-03-01,0.0005886778817512095,-0.009579152800142765 +2,GOOGL,2024-03-04,0.0005946062155999243,-0.028025124222040176 +2,GOOGL,2024-03-05,0.00066744489595294,-0.00511243287473917 +2,GOOGL,2024-03-06,0.0006724785780534148,-0.009618480689823627 +2,GOOGL,2024-03-07,0.0006792993517592549,0.022425180301070213 +2,GOOGL,2024-03-08,0.0006652347510680556,0.007635630667209625 +2,GOOGL,2024-03-11,0.0006588236428797245,0.016552241519093513 +2,GOOGL,2024-03-12,0.0006109849782660604,0.006010944023728371 +2,GOOGL,2024-03-13,0.0005455893697217107,0.009270928800106049 +2,GOOGL,2024-03-14,0.0004992300528101623,0.023402439430356026 +2,GOOGL,2024-03-15,0.0005050565232522786,-0.013508213683962822 +2,GOOGL,2024-03-18,0.000524706207215786,0.045012217015028 +2,GOOGL,2024-03-19,0.0005304662045091391,-0.004411124624311924 +2,GOOGL,2024-03-20,0.0005388438585214317,0.011563213542103767 +2,GOOGL,2024-03-21,0.00054182019084692,-0.007693967781960964 +2,GOOGL,2024-03-22,0.0005314339650794864,0.02124977484345436 +2,AMZN,2023-06-06,0.0005433482583612204,0.010400613769888878 +2,AMZN,2023-06-07,0.0005357979680411518,-0.0434219054877758 +2,AMZN,2023-06-08,0.0005901993135921657,0.024606069549918175 +2,AMZN,2023-06-09,0.0005708590033464134,-0.006621468812227249 +2,AMZN,2023-06-12,0.0005872024921700358,0.02512131631374359 +2,AMZN,2023-06-13,0.00054162711603567,0.0007108476129360497 +2,AMZN,2023-06-14,0.0005401616217568517,-0.001896677422337234 +2,AMZN,2023-06-15,0.0005354385357350111,0.005443174857646227 +2,AMZN,2023-06-16,0.0005441430257633328,-0.012826800346374512 +2,AMZN,2023-06-20,0.0005366357509046793,0.0023082823026925325 +2,AMZN,2023-06-21,0.0005403944524005055,-0.007581513375043869 +2,AMZN,2023-06-22,0.0005443759146146476,0.041734758764505386 +2,AMZN,2023-06-23,0.0005596005939878523,-0.006320293061435223 +2,AMZN,2023-06-26,0.0005629037041217089,-0.015585134737193584 +2,AMZN,2023-06-27,0.0005349778803065419,0.01442456804215908 +2,AMZN,2023-06-28,0.000559319625608623,-0.0010843421332538128 +2,AMZN,2023-06-29,0.000559319625608623,-0.008873661048710346 +2,AMZN,2023-06-30,0.0005477828090079129,0.019051138311624527 +2,AMZN,2023-07-03,0.0005840588128194213,-0.0010745214531198144 +2,AMZN,2023-07-05,0.0005940820556133986,0.0012279637157917023 +2,AMZN,2023-07-06,0.0006021208828315139,-0.015614479780197144 +2,AMZN,2023-07-07,0.0005801456863991916,0.011001878418028355 +2,AMZN,2023-07-10,0.0005877643707208335,-0.02063053660094738 +2,AMZN,2023-07-11,0.0005585527396760881,0.01289534941315651 +2,AMZN,2023-07-12,0.0005765464738942683,0.015563949942588806 +2,AMZN,2023-07-13,0.0005875391070730984,0.02640666626393795 +2,AMZN,2023-07-14,0.0006079728482291102,0.00282541336491704 +2,AMZN,2023-07-17,0.0005985773168504238,-0.008350742980837822 +2,AMZN,2023-07-18,0.0005864633712917566,-0.005480668041855097 +2,AMZN,2023-07-19,0.0005596005939878523,0.018867772072553635 +2,AMZN,2023-07-20,0.0005802190862596035,-0.040711138397455215 +2,AMZN,2023-07-21,0.0005496026715263724,0.0003076879947911948 +2,AMZN,2023-07-24,0.0005505088483914733,-0.00927361287176609 +2,AMZN,2023-07-25,0.0006007439806126058,0.002558849286288023 +2,AMZN,2023-07-26,0.000608205737080425,-0.007618281524628401 +2,AMZN,2023-07-27,0.0006334409699775279,0.0007800788735039532 +2,AMZN,2023-07-28,0.0006286849966272712,0.03041013330221176 +2,AMZN,2023-07-31,0.0005563937011174858,0.011057211086153984 +2,AMZN,2023-08-01,0.0005510099581442773,-0.014998135156929493 +2,AMZN,2023-08-02,0.00055062270257622,-0.026781097054481506 +2,AMZN,2023-08-03,0.0005353018641471863,0.00544491782784462 +2,AMZN,2023-08-04,0.0005401312373578548,0.07945180684328079 +2,AMZN,2023-08-07,0.0005346969119273126,0.018808843567967415 +2,AMZN,2023-08-08,0.0005678343586623669,-0.01616138592362404 +2,AMZN,2023-08-09,0.0005722764763049781,-0.015047594904899597 +2,AMZN,2023-08-10,0.0005501468549482524,0.005137245636433363 +2,AMZN,2023-08-11,0.0005437912186607718,-0.0010831058025360107 +2,AMZN,2023-08-14,0.0005391491577029228,0.015485316514968872 +2,AMZN,2023-08-15,0.0005567860207520425,-0.020846134051680565 +2,AMZN,2023-08-16,0.0005426116986200213,-0.019066287204623222 +2,AMZN,2023-08-17,0.0005444316193461418,-0.008102713152766228 +2,AMZN,2023-08-18,0.0005958715919405222,-0.005688596982508898 +2,AMZN,2023-08-21,0.0006334359059110284,0.010899635031819344 +2,AMZN,2023-08-22,0.0006069325609132648,-0.0031978064216673374 +2,AMZN,2023-08-23,0.0005948413745500147,0.009415528737008572 +2,AMZN,2023-08-24,0.0005787156405858696,-0.02753022313117981 +2,AMZN,2023-08-25,0.0006681199301965535,0.01071302779018879 +2,AMZN,2023-08-28,0.0006288166041485965,-0.0009008643100969493 +2,AMZN,2023-08-29,0.0006102609913796186,0.013206714764237404 +2,AMZN,2023-08-30,0.0005552420043386519,0.0011853001778945327 +2,AMZN,2023-08-31,0.0005554799572564662,0.02153288945555687 +2,AMZN,2023-09-01,0.0005697048618458211,0.0007967306883074343 +2,AMZN,2023-09-05,0.0005685076466761529,-0.006173016503453255 +2,AMZN,2023-09-06,0.0005783739034086466,-0.014011920429766178 +2,AMZN,2023-09-07,0.0005481371772475541,0.018228281289339066 +2,AMZN,2023-09-08,0.0005690366378985345,0.0027527520433068275 +2,AMZN,2023-09-11,0.0005831653252243996,0.034624796360731125 +2,AMZN,2023-09-12,0.0006096104625612497,-0.013153992593288422 +2,AMZN,2023-09-13,0.0006001542205922306,0.02530902996659279 +2,AMZN,2023-09-14,0.000613295822404325,-0.000897916906978935 +2,AMZN,2023-09-15,0.0006113037816248834,-0.03037659265100956 +2,AMZN,2023-09-18,0.0005515111261047423,-0.0029247349593788385 +2,AMZN,2023-09-19,0.0005513213109225035,-0.016930563375353813 +2,AMZN,2023-09-20,0.0006070489762350917,-0.01714838668704033 +2,AMZN,2023-09-21,0.0007280315621756017,-0.045053280889987946 +2,AMZN,2023-09-22,0.0008048004237934947,-0.0016251248307526112 +2,AMZN,2023-09-25,0.0007477211183868349,0.016514137387275696 +2,AMZN,2023-09-26,0.0007338379509747028,-0.04113311320543289 +2,AMZN,2023-09-27,0.0005078113172203302,0.0 +2,AMZN,2023-09-28,0.00030840712133795023,0.0 +2,AMZN,2023-09-29,0.00022666205768473446,0.009008352644741535 +2,AMZN,2023-10-02,0.0002580985601525754,0.018240461125969887 +2,AMZN,2023-10-03,0.0003662761300802231,-0.03730076923966408 +2,AMZN,2023-10-04,0.0002672840200830251,0.018115852028131485 +2,AMZN,2023-10-05,0.00032539095263928175,-0.008222697302699089 +2,AMZN,2023-10-06,0.00033567487844266,0.01575331948697567 +2,AMZN,2023-10-09,0.0004211381892673671,0.0023417030461132526 +2,AMZN,2023-10-10,0.00047677726252004504,0.009466985240578651 +2,AMZN,2023-10-11,0.0006259108777157962,0.017986832186579704 +2,AMZN,2023-10-12,0.0006888573989272118,0.003785589011386037 +2,AMZN,2023-10-13,0.0006722481921315193,-0.01938110776245594 +2,AMZN,2023-10-16,0.0006717140786349773,0.021042248234152794 +2,AMZN,2023-10-17,0.0006340611143968999,-0.008181258104741573 +2,AMZN,2023-10-18,0.0006091219838708639,-0.025733286514878273 +2,AMZN,2023-10-19,0.0006711218156851828,0.002104931976646185 +2,AMZN,2023-10-20,0.0006924844929017127,-0.025477545335888863 +2,AMZN,2023-10-23,0.0007616017828695476,0.011043687351047993 +2,AMZN,2023-10-24,0.0007601590477861464,0.015679217875003815 +2,AMZN,2023-10-25,0.0007264824816957116,-0.057387202978134155 +2,AMZN,2023-10-26,0.0007482425426132977,-0.015106527134776115 +2,AMZN,2023-10-27,0.0006379539845511317,0.06609495729207993 +2,AMZN,2023-10-30,0.000765180797316134,0.038169413805007935 +2,AMZN,2023-10-31,0.0007323622703552246,0.0028592166490852833 +2,AMZN,2023-11-01,0.0006663886015303433,0.028955362737178802 +2,AMZN,2023-11-02,0.0005926418816670775,0.007779930252581835 +2,AMZN,2023-11-03,0.0005418523796834052,0.0038312748074531555 +2,AMZN,2023-11-06,0.0005112941726110876,0.00819146167486906 +2,AMZN,2023-11-07,0.0004973704926669598,0.021031053736805916 +2,AMZN,2023-11-08,0.000496583292260766,-0.004424354061484337 +2,AMZN,2023-11-09,0.0004983500111848116,-0.010471269488334656 +2,AMZN,2023-11-10,0.0005236232536844909,0.020834026858210564 +2,AMZN,2023-11-13,0.000521671783644706,-0.006779695861041546 +2,AMZN,2023-11-14,0.0005523666623048484,0.022262487560510635 +2,AMZN,2023-11-15,0.0005706261727027595,-0.017993606626987457 +2,AMZN,2023-11-16,0.0006328512099571526,-0.0025871084071695805 +2,AMZN,2023-11-17,0.0006780545809306204,0.01631917618215084 +2,AMZN,2023-11-20,0.0006619439227506518,0.006522369105368853 +2,AMZN,2023-11-21,0.0006345192668959498,-0.015378098003566265 +2,AMZN,2023-11-22,0.0006772395572625101,0.019339323043823242 +2,AMZN,2023-11-24,0.0005989797646179795,0.0002044558059424162 +2,AMZN,2023-11-27,0.0005213629920035601,0.006723903585225344 +2,AMZN,2023-11-28,0.0005064369761385024,-0.004749615211039782 +2,AMZN,2023-11-29,0.0005101627320982516,-0.004840584937483072 +2,AMZN,2023-11-30,0.0005052473279647529,-0.001573209068737924 +2,AMZN,2023-12-01,0.000504736031871289,0.006413794122636318 +2,AMZN,2023-12-04,0.0005170524818822742,-0.015006979927420616 +2,AMZN,2023-12-05,0.0004998712101951241,0.013986300677061081 +2,AMZN,2023-12-06,0.0005016708746552467,-0.01619802415370941 +2,AMZN,2023-12-07,0.0004915742320008576,0.01619802415370941 +2,AMZN,2023-12-08,0.0004970262525603175,0.003669682890176773 +2,AMZN,2023-12-11,0.0004984664265066385,-0.010432734154164791 +2,AMZN,2023-12-12,0.0004958112840540707,0.010839635506272316 +2,AMZN,2023-12-13,0.0005018986412324011,0.009179334156215191 +2,AMZN,2023-12-14,0.0005206011119298637,-0.009586235508322716 +2,AMZN,2023-12-15,0.0005125723546370864,0.017149638384580612 +2,AMZN,2023-12-18,0.0005192874232307076,0.026971809566020966 +2,AMZN,2023-12-19,0.0005419561639428139,-0.0018191003473475575 +2,AMZN,2023-12-20,0.00055289565352723,-0.010918340645730495 +2,AMZN,2023-12-21,0.0005340160569176078,0.011243426240980625 +2,AMZN,2023-12-22,0.0005520856939256191,-0.002733830828219652 +2,AMZN,2023-12-26,0.0005538448458537459,-6.514686538139358e-05 +2,AMZN,2023-12-27,0.0005621494492515922,-0.0004564454429782927 +2,AMZN,2023-12-28,0.0005649083759635687,0.00026087992591783404 +2,AMZN,2023-12-29,0.0005766578251495957,-0.009432812221348286 +2,AMZN,2024-01-02,0.0005710336845368147,-0.01331725250929594 +2,AMZN,2024-01-03,0.0005336186732165515,-0.009785544127225876 +2,AMZN,2024-01-04,0.0005428901640698314,-0.02661905623972416 +2,AMZN,2024-01-05,0.0006143968203105032,0.004623714368790388 +2,AMZN,2024-01-08,0.0006416646065190434,0.026229677721858025 +2,AMZN,2024-01-09,0.0005534904776141047,0.015109877102077007 +2,AMZN,2024-01-10,0.0005422016838565469,0.015470650978386402 +2,AMZN,2024-01-11,0.0005827375571243465,0.009387897327542305 +2,AMZN,2024-01-12,0.0006128452369011939,-0.0036152240354567766 +2,AMZN,2024-01-16,0.0006214460008777678,-0.009487311355769634 +2,AMZN,2024-01-17,0.000621694081928581,-0.009512302465736866 +2,AMZN,2024-01-18,0.0006061377935111523,0.011729719117283821 +2,AMZN,2024-01-19,0.0006073780241422355,0.01191567163914442 +2,AMZN,2024-01-22,0.0006285787094384432,-0.0036114933900535107 +2,AMZN,2024-01-23,0.0006325525464490056,0.00797948520630598 +2,AMZN,2024-01-24,0.0006448006606660783,0.005433174781501293 +2,AMZN,2024-01-25,0.0006580789340659976,0.005594095680862665 +2,AMZN,2024-01-26,0.0006595140439458191,0.008647102862596512 +2,AMZN,2024-01-29,0.0006568867829628289,0.013359332457184792 +2,AMZN,2024-01-30,0.0006680338410660625,-0.014113732613623142 +2,AMZN,2024-01-31,0.0006427529733628035,-0.02418961375951767 +2,AMZN,2024-02-01,0.0005700844922102988,0.025949064642190933 +2,AMZN,2024-02-02,0.0006027334602549672,0.07572554796934128 +2,AMZN,2024-02-05,0.0006391739589162171,-0.008768909610807896 +2,AMZN,2024-02-06,0.0006430288776755333,-0.006834432482719421 +2,AMZN,2024-02-07,0.0006363340653479099,0.00812536757439375 +2,AMZN,2024-02-08,0.0006409280467778444,-0.004054431337863207 +2,AMZN,2024-02-09,0.0006325044669210911,0.02678135596215725 +2,AMZN,2024-02-12,0.0006406622705981135,-0.012168901972472668 +2,AMZN,2024-02-13,0.0006143664359115064,-0.02170298621058464 +2,AMZN,2024-02-14,0.0005706818774342537,0.013780304230749607 +2,AMZN,2024-02-15,0.0005762756336480379,-0.0069252741523087025 +2,AMZN,2024-02-16,0.0005810543661937118,-0.0017094019567593932 +2,AMZN,2024-02-20,0.0005811201990582049,-0.014439139515161514 +2,AMZN,2024-02-21,0.0005840411176905036,0.008996959775686264 +2,AMZN,2024-02-22,0.0005817048950120807,0.03491339087486267 +2,AMZN,2024-02-23,0.0005921457777731121,0.002345761051401496 +2,AMZN,2024-02-26,0.0006153991562314332,-0.0014869599835947156 +2,AMZN,2024-02-27,0.0006304644048213959,-0.00683381874114275 +2,AMZN,2024-02-28,0.0006212308653630316,-0.0021920378785580397 +2,AMZN,2024-02-29,0.0006207347614690661,0.020576804876327515 +2,AMZN,2024-03-01,0.0006602000212296844,0.008225900121033192 +2,AMZN,2024-03-04,0.0006809931946918368,-0.0035975270438939333 +2,AMZN,2024-03-05,0.0006664316751994193,-0.019676532596349716 +2,AMZN,2024-03-06,0.0006288368604145944,-0.0035094853956252337 +2,AMZN,2024-03-07,0.0005993872764520347,0.018897105008363724 +2,AMZN,2024-03-08,0.0006211017607711256,-0.008348296396434307 +2,AMZN,2024-03-11,0.0005964385345578194,-0.019522080197930336 +2,AMZN,2024-03-12,0.0005684418138116598,0.01975013129413128 +2,AMZN,2024-03-13,0.0005619798321276903,0.006648685783147812 +2,AMZN,2024-03-14,0.0005597246345132589,0.012327433563768864 +2,AMZN,2024-03-15,0.0005990557256154716,-0.02452200837433338 +2,AMZN,2024-03-18,0.0005530323251150548,0.00034392409725114703 +2,AMZN,2024-03-19,0.000548008072655648,0.008105519227683544 +2,AMZN,2024-03-20,0.0005604308098554611,0.012710239738225937 +2,AMZN,2024-03-21,0.0006131641566753387,0.0 +2,AMZN,2024-03-22,0.0006182973156683147,0.004033399745821953 +2,META,2023-06-06,0.0006193661247380078,-0.0009953344706445932 +2,META,2023-06-07,0.0006220091599971056,-0.028128689154982567 +2,META,2023-06-08,0.0006606978131458163,0.0037107327952980995 +2,META,2023-06-09,0.000705184880644083,0.0013975102920085192 +2,META,2023-06-12,0.0007269905181601644,0.022762088105082512 +2,META,2023-06-13,0.0006539862370118499,0.0009957050206139684 +2,META,2023-06-14,0.0006444577011279762,0.007454090751707554 +2,META,2023-06-15,0.0006396810058504343,0.030551055446267128 +2,META,2023-06-16,0.0006723133847117424,-0.0029495269991457462 +2,META,2023-06-20,0.0006748259766027331,0.011780914850533009 +2,META,2023-06-21,0.0007079335046000779,-0.009505811147391796 +2,META,2023-06-22,0.0007058588671498001,0.011438366957008839 +2,META,2023-06-23,0.0007327765924856067,0.013423998840153217 +2,META,2023-06-26,0.0007469482370652258,-0.03618176653981209 +2,META,2023-06-27,0.0006974639254622161,0.030346084386110306 +2,META,2023-06-28,0.0007203069399110973,-0.006150140892714262 +2,META,2023-06-29,0.0007172042387537658,-0.013267286121845245 +2,META,2023-06-30,0.0007015604642219841,0.01917373016476631 +2,META,2023-07-03,0.000738960166927427,-0.0033509558998048306 +2,META,2023-07-05,0.0007470942218787968,0.028775852173566818 +2,META,2023-07-06,0.0007682631839998066,-0.008118035271763802 +2,META,2023-07-07,0.0007610049797222018,-0.005012627691030502 +2,META,2023-07-10,0.0007498179911635816,0.012212960049510002 +2,META,2023-07-11,0.0007698595291003585,0.014146351255476475 +2,META,2023-07-12,0.0007948516868054867,0.036374885588884354 +2,META,2023-07-13,0.000789922836702317,0.013071260415017605 +2,META,2023-07-14,0.0007872953428886831,-0.014591889455914497 +2,META,2023-07-17,0.0007606943836435676,0.005649842321872711 +2,META,2023-07-18,0.0007546505657956004,0.004593098536133766 +2,META,2023-07-19,0.0007420473266392946,0.012610457837581635 +2,META,2023-07-20,0.0007480290369130671,-0.04362663999199867 +2,META,2023-07-21,0.0006884789327159524,-0.027683401480317116 +2,META,2023-07-24,0.0007518770871683955,-0.009046511724591255 +2,META,2023-07-25,0.0008556534885428846,0.009759766981005669 +2,META,2023-07-26,0.0008434353512711823,0.01382735650986433 +2,META,2023-07-27,0.0007777854916639626,0.04306872561573982 +2,META,2023-07-28,0.0007000323967076838,0.043227992951869965 +2,META,2023-07-31,0.0007175583159551024,-0.02136477828025818 +2,META,2023-08-01,0.0007413640851154923,0.012817584909498692 +2,META,2023-08-02,0.0007717447588220239,-0.026374125853180885 +2,META,2023-08-03,0.0007203597342595458,-0.003569756168872118 +2,META,2023-08-04,0.000702426943462342,-0.007885610684752464 +2,META,2023-08-07,0.000681938196066767,0.018588287755846977 +2,META,2023-08-08,0.0006962589104659855,-0.01246029231697321 +2,META,2023-08-09,0.0006844165618531406,-0.024052521213889122 +2,META,2023-08-10,0.0006906467606313527,0.0017351185670122504 +2,META,2023-08-11,0.0006905349437147379,-0.013500683940947056 +2,META,2023-08-14,0.0006908020586706698,0.014971617609262466 +2,META,2023-08-15,0.0006912927492521703,-0.01394449733197689 +2,META,2023-08-16,0.0007037313771434128,-0.025695672258734703 +2,META,2023-08-17,0.0007897395989857614,-0.0317610427737236 +2,META,2023-08-18,0.000902109663002193,-0.0064747752621769905 +2,META,2023-08-21,0.0009239556966349483,0.023205997422337532 +2,META,2023-08-22,0.0008750894339755177,-0.007965482771396637 +2,META,2023-08-23,0.0008752415888011456,0.022825194522738457 +2,META,2023-08-24,0.0007987215067259967,-0.025784704834222794 +2,META,2023-08-25,0.0008865403942763805,-0.004369002301245928 +2,META,2023-08-28,0.0008963608997873962,0.01653505675494671 +2,META,2023-08-29,0.0008563212468288839,0.026282889768481255 +2,META,2023-08-30,0.0007625982398167253,-0.009745735675096512 +2,META,2023-08-31,0.0007030636770650744,0.0026736510917544365 +2,META,2023-09-01,0.000650628877338022,0.0016544903628528118 +2,META,2023-09-05,0.0006433023372665048,0.012639938853681087 +2,META,2023-09-06,0.000667483895085752,-0.003270263783633709 +2,META,2023-09-07,0.0007038090261630714,-0.0016725469613447785 +2,META,2023-09-08,0.0007066818652674556,-0.00261514401063323 +2,META,2023-09-11,0.0007132319733500481,0.03194567933678627 +2,META,2023-09-12,0.0007506844704039395,-0.019369615241885185 +2,META,2023-09-13,0.0007370470557361841,0.01120799034833908 +2,META,2023-09-14,0.0007509174174629152,0.021596958860754967 +2,META,2023-09-15,0.000769303587730974,-0.0372900553047657 +2,META,2023-09-18,0.0007081571384333074,0.007431343197822571 +2,META,2023-09-19,0.0006988832610659301,0.008294549770653248 +2,META,2023-09-20,0.0007037096656858921,-0.01785930246114731 +2,META,2023-09-21,0.0006973459385335445,-0.013234885409474373 +2,META,2023-09-22,0.0007332672830671072,0.01126399077475071 +2,META,2023-09-25,0.0007035450544208288,0.005834244657307863 +2,META,2023-09-26,0.0006942712352611125,-0.006235459819436073 +2,META,2023-09-27,0.0006948830559849739,-0.00408927071839571 +2,META,2023-09-28,0.0006899883155710995,0.020675623789429665 +2,META,2023-09-29,0.0007199994288384914,-0.012413954362273216 +2,META,2023-10-02,0.0007176235085353255,0.021779030561447144 +2,META,2023-10-03,0.0007605981081724167,-0.01935049332678318 +2,META,2023-10-04,0.0007298105629161,0.015301009640097618 +2,META,2023-10-05,0.0007503614760935307,-0.0025886583607643843 +2,META,2023-10-06,0.0007537126075476408,0.0343136265873909 +2,META,2023-10-09,0.0007731764926575124,0.009246083907783031 +2,META,2023-10-10,0.0007767233182676136,0.010871808975934982 +2,META,2023-10-11,0.0007780898595228791,0.01841006986796856 +2,META,2023-10-12,0.0007802670006640255,-0.011227373965084553 +2,META,2023-10-13,0.0007561226957477629,-0.029649225994944572 +2,META,2023-10-16,0.0006858949200250208,0.020320124924182892 +2,META,2023-10-17,0.0006988832610659301,0.0088353231549263 +2,META,2023-10-18,0.0006984857609495521,-0.021936409175395966 +2,META,2023-10-19,0.0006960663595236838,-0.01321113109588623 +2,META,2023-10-20,0.0007868295069783926,-0.013388005085289478 +2,META,2023-10-23,0.0008811611915007234,0.01721692830324173 +2,META,2023-10-24,0.0008387270499952137,-0.004660394042730331 +2,META,2023-10-25,0.0008101414423435926,-0.04254993423819542 +2,META,2023-10-26,0.0009285584092140198,-0.038039542734622955 +2,META,2023-10-27,0.0009649332496337593,0.028647568076848984 +2,META,2023-10-30,0.0009524977649562061,0.01978735812008381 +2,META,2023-10-31,0.0009092684485949576,-0.00460308650508523 +2,META,2023-11-01,0.0008744279039092362,0.03451548144221306 +2,META,2023-11-02,0.0007374166161753237,-0.0031473760027438402 +2,META,2023-11-03,0.000673996692057699,0.01192710641771555 +2,META,2023-11-06,0.0006778385723009706,0.0038068867288529873 +2,META,2023-11-07,0.0006802144926041365,0.009517782367765903 +2,META,2023-11-08,0.0007304534665308893,0.003006536513566971 +2,META,2023-11-09,0.0007602316327393055,0.0024051342625170946 +2,META,2023-11-10,0.00076721963705495,0.025320030748844147 +2,META,2023-11-13,0.0008062840788625181,0.0012767899315804243 +2,META,2023-11-14,0.0008071412448771298,0.02139815129339695 +2,META,2023-11-15,0.0008220707532018423,-0.010762030258774757 +2,META,2023-11-16,0.0008069269242696464,0.004438225645571947 +2,META,2023-11-17,0.0008096289820969105,0.0025402952451258898 +2,META,2023-11-20,0.0008232168038375676,0.01460745558142662 +2,META,2023-11-21,0.0008379847276955843,-0.008833667263388634 +2,META,2023-11-22,0.0008157629054039717,0.013294795528054237 +2,META,2023-11-24,0.0008507121820002794,-0.009592188522219658 +2,META,2023-11-27,0.0008612470119260252,-0.010491609573364258 +2,META,2023-11-28,0.000834105652756989,0.012736090458929539 +2,META,2023-11-29,0.0008591474615968764,-0.02023342065513134 +2,META,2023-11-30,0.0008125980966724455,-0.015318612568080425 +2,META,2023-12-01,0.0007650828338228166,-0.007147617172449827 +2,META,2023-12-04,0.0007346804486587644,-0.014887575060129166 +2,META,2023-12-05,0.0007322020246647298,-0.005420465022325516 +2,META,2023-12-06,0.0007570295711047947,-0.0026427353732287884 +2,META,2023-12-07,0.0007797762518748641,0.02838529646396637 +2,META,2023-12-08,0.0007260494749061763,0.018685918301343918 +2,META,2023-12-11,0.0007792358519509435,-0.022705281153321266 +2,META,2023-12-12,0.0007774718105792999,0.027113132178783417 +2,META,2023-12-13,0.0008138311095535755,0.0015546496724709868 +2,META,2023-12-14,0.000842606124933809,-0.004701063968241215 +2,META,2023-12-15,0.0008397146593779325,0.005238751880824566 +2,META,2023-12-18,0.0008563150186091661,0.02855069190263748 +2,META,2023-12-19,0.0008926743175834417,0.01651874929666519 +2,META,2023-12-20,0.0009144209325313568,-0.003087271936237812 +2,META,2023-12-21,0.0009157346794381738,0.01367731112986803 +2,META,2023-12-22,0.0009310927707701921,-0.0019788616336882114 +2,META,2023-12-26,0.000917067052796483,0.004066350869834423 +2,META,2023-12-27,0.0009233221062459052,0.008419191464781761 +2,META,2023-12-28,0.0009153154096566141,0.0013685536105185747 +2,META,2023-12-29,0.0009117965819314122,-0.012242634780704975 +2,META,2024-01-02,0.0008847017888911068,-0.02190718986093998 +2,META,2024-01-03,0.0008171791560016572,-0.005269426852464676 +2,META,2024-01-04,0.000785242416895926,0.007663244381546974 +2,META,2024-01-05,0.0007761518354527652,0.013818783685564995 +2,META,2024-01-08,0.0008118900004774332,0.01888563483953476 +2,META,2024-01-09,0.0008562187431380153,-0.003435344435274601 +2,META,2024-01-10,0.0008632502285763621,0.03583300858736038 +2,META,2024-01-11,0.0009017587290145457,-0.002161737298592925 +2,META,2024-01-12,0.0009253113530576229,0.012954231351613998 +2,META,2024-01-16,0.0009310927707701921,-0.018950488418340683 +2,META,2024-01-17,0.000904364453162998,0.0024732896126806736 +2,META,2024-01-18,0.0009050756925716996,0.020846949890255928 +2,META,2024-01-19,0.0009122686460614204,0.019274508580565453 +2,META,2024-01-22,0.0009225208195857704,-0.004364772699773312 +2,META,2024-01-23,0.000907398818526417,0.008918233215808868 +2,META,2024-01-24,0.0009087808430194855,0.01417723298072815 +2,META,2024-01-25,0.0009181043715216219,0.006327503360807896 +2,META,2024-01-26,0.0009153464925475419,0.002438619500026107 +2,META,2024-01-29,0.0009184025693684816,0.01730525493621826 +2,META,2024-01-30,0.000922955630812794,-0.002396808471530676 +2,META,2024-01-31,0.0009104175842367113,-0.02510889619588852 +2,META,2024-02-01,0.0008514078799635172,0.011823002249002457 +2,META,2024-02-02,0.0008611693629063666,0.18496514856815338 +2,META,2024-02-05,0.000883729662746191,-0.03335074335336685 +2,META,2024-02-06,0.0008505972800776362,-0.010261205956339836 +2,META,2024-02-07,0.0008114271913655102,0.03217816352844238 +2,META,2024-02-08,0.0008035385399125516,0.0008727913373149931 +2,META,2024-02-09,0.0007848914829082787,-0.0040295543149113655 +2,META,2024-02-12,0.0007616851362399757,0.0016863220371305943 +2,META,2024-02-13,0.0007453021826222539,-0.018902163952589035 +2,META,2024-02-14,0.0007395285647362471,0.02819979004561901 +2,META,2024-02-15,0.0007389974780380726,0.02245979942381382 +2,META,2024-02-16,0.0007358451257459819,-0.02237517759203911 +2,META,2024-02-20,0.0007318324642255902,-0.003322578500956297 +2,META,2024-02-21,0.0007303447928279638,-0.006856379099190235 +2,META,2024-02-22,0.00073557801079005,0.0379437692463398 +2,META,2024-02-23,0.0007273383671417832,-0.004329243209213018 +2,META,2024-02-26,0.0007224685396067798,-0.004742311779409647 +2,META,2024-02-27,0.0007311025983653963,0.010962148196995258 +2,META,2024-02-28,0.0007296614930965006,-0.00624054903164506 +2,META,2024-02-29,0.0007292701629921794,0.012544485740363598 +2,META,2024-03-01,0.0007839535246603191,0.024526918306946754 +2,META,2024-03-04,0.00083824252942577,-0.00821609701961279 +2,META,2024-03-05,0.0008222167380154133,-0.016127247363328934 +2,META,2024-03-06,0.0007689805934205651,0.011903088539838791 +2,META,2024-03-07,0.0007616323418915272,0.0319383405148983 +2,META,2024-03-08,0.0007687259349040687,-0.012257712893188 +2,META,2024-03-11,0.000710952328518033,-0.0452004075050354 +2,META,2024-03-12,0.0007456655730493367,0.03287045657634735 +2,META,2024-03-13,0.0007565264240838587,-0.0083993598818779 +2,META,2024-03-14,0.0007948237471282482,-0.007575587369501591 +2,META,2024-03-15,0.0008292575366795063,-0.015841564163565636 +2,META,2024-03-18,0.0008593089878559113,0.026258300989866257 +2,META,2024-03-19,0.0007848107488825917,-0.001490057329647243 +2,META,2024-03-20,0.0007305745966732502,0.018527813255786896 +2,META,2024-03-21,0.0006533743580803275,0.004421258810907602 +2,META,2024-03-22,0.0006406406755559146,0.0035778821911662817 +2,SPY,2023-06-06,0.00047099668881855905,0.002174797235056758 +2,SPY,2023-06-07,0.0004726049955934286,-0.0034636424388736486 +2,SPY,2023-06-08,0.0004719761782325804,0.0060304817743599415 +2,SPY,2023-06-09,0.000474305561510846,0.0017925795400515199 +2,SPY,2023-06-12,0.00047240295680239797,0.009031042456626892 +2,SPY,2023-06-13,0.00048639686428941786,0.0065711019560694695 +2,SPY,2023-06-14,0.000489177939016372,0.0011902990518137813 +2,SPY,2023-06-15,0.0004862292262259871,0.012321500107645988 +2,SPY,2023-06-16,0.0004947524867020547,-0.0034121398348361254 +2,SPY,2023-06-20,0.00048973283264786,-0.005201653577387333 +2,SPY,2023-06-21,0.0004874305159319192,-0.005136935971677303 +2,SPY,2023-06-22,0.000479314272524789,0.0036031375639140606 +2,SPY,2023-06-23,0.00048416704521514475,-0.007588720414787531 +2,SPY,2023-06-26,0.00047298934077844024,-0.004094037692993879 +2,SPY,2023-06-27,0.0004664206353481859,0.010903646238148212 +2,SPY,2023-06-28,0.00048477755626663566,0.0005041107069700956 +2,SPY,2023-06-29,0.0004921039217151701,0.003933676518499851 +2,SPY,2023-06-30,0.0005030056927353144,0.01173168420791626 +2,SPY,2023-07-03,0.0005259870085865259,0.001149852410890162 +2,SPY,2023-07-05,0.0005431894678622484,-0.0014883464900776744 +2,SPY,2023-07-06,0.0005478848470374942,-0.007861537858843803 +2,SPY,2023-07-07,0.0005350812571123242,-0.002527856733649969 +2,SPY,2023-07-10,0.000523697875905782,0.002527856733649969 +2,SPY,2023-07-11,0.0005292658461257815,0.006348350550979376 +2,SPY,2023-07-12,0.0005404369439929724,0.008013916201889515 +2,SPY,2023-07-13,0.000538109743501991,0.007905391044914722 +2,SPY,2023-07-14,0.0005421133828349411,-0.0006229392602108419 +2,SPY,2023-07-17,0.0005391880986280739,0.003466201713308692 +2,SPY,2023-07-18,0.0005364384851418436,0.007403245661407709 +2,SPY,2023-07-19,0.0005234548007138073,0.0022211770992726088 +2,SPY,2023-07-20,0.0005209650844335556,-0.006656670477241278 +2,SPY,2023-07-21,0.0005030452157370746,0.0 +2,SPY,2023-07-24,0.000497553322929889,0.00445746211335063 +2,SPY,2023-07-25,0.0005024273414164782,0.002726346254348755 +2,SPY,2023-07-26,0.0005079777911305428,0.00015362970589194447 +2,SPY,2023-07-27,0.0005143919843249023,-0.006651914678514004 +2,SPY,2023-07-28,0.0004978959332220256,0.009742510505020618 +2,SPY,2023-07-31,0.0004975401679985225,0.0019023313652724028 +2,SPY,2023-08-01,0.0004974764888174832,-0.002865681191906333 +2,SPY,2023-08-02,0.0004937122575938702,-0.01400839351117611 +2,SPY,2023-08-03,0.00044492684537544847,-0.002870054915547371 +2,SPY,2023-08-04,0.0004328582144808024,-0.0045330035500228405 +2,SPY,2023-08-07,0.0004117926873732358,0.00869054812937975 +2,SPY,2023-08-08,0.0004294483223930001,-0.004357998259365559 +2,SPY,2023-08-09,0.0004324043693486601,-0.00670775817707181 +2,SPY,2023-08-10,0.0004248437180649489,0.0003589534026104957 +2,SPY,2023-08-11,0.00042146749910898507,-0.0005834003095515072 +2,SPY,2023-08-14,0.00042429176392033696,0.005504786502569914 +2,SPY,2023-08-15,0.00043684057891368866,-0.011717140674591064 +2,SPY,2023-08-16,0.00041974132182076573,-0.007365358527749777 +2,SPY,2023-08-17,0.0004016406019218266,-0.007648835889995098 +2,SPY,2023-08-18,0.0003831225913017988,0.00048104007146321237 +2,SPY,2023-08-21,0.0003744975256267935,0.006485301069915295 +2,SPY,2023-08-22,0.00038307279464788735,-0.0027124504558742046 +2,SPY,2023-08-23,0.0003792851639445871,0.0110762445256114 +2,SPY,2023-08-24,0.00039853667840361595,-0.013956079259514809 +2,SPY,2023-08-25,0.0003824725281447172,0.007025209721177816 +2,SPY,2023-08-28,0.00038998338277451694,0.006321425549685955 +2,SPY,2023-08-29,0.00040329794865101576,0.014351213350892067 +2,SPY,2023-08-30,0.0004293839156161994,0.004110200330615044 +2,SPY,2023-08-31,0.0004499838687479496,-0.0014642919413745403 +2,SPY,2023-09-01,0.000456987414509058,0.001863291603513062 +2,SPY,2023-09-05,0.0004585188580676913,-0.004331281408667564 +2,SPY,2023-09-06,0.00045829705777578056,-0.006744927726686001 +2,SPY,2023-09-07,0.0004443470679689199,-0.003074954031035304 +2,SPY,2023-09-08,0.00043004422332160175,0.0015050640795379877 +2,SPY,2023-09-11,0.00042663433123379946,0.006554901599884033 +2,SPY,2023-09-12,0.0004381246108096093,-0.005500671919435263 +2,SPY,2023-09-13,0.0004316972044762224,0.0011652878019958735 +2,SPY,2023-09-14,0.000435564637882635,0.00858551636338234 +2,SPY,2023-09-15,0.00045313313603401184,-0.012121628038585186 +2,SPY,2023-09-18,0.00042675144504755735,0.0005864023696631193 +2,SPY,2023-09-19,0.00041525528649799526,-0.0020760532934218645 +2,SPY,2023-09-20,0.00041220997809432447,-0.009235854260623455 +2,SPY,2023-09-21,0.0003922615433111787,-0.016666477546095848 +2,SPY,2023-09-22,0.00036749179707840085,-0.002251106547191739 +2,SPY,2023-09-25,0.00034408370265737176,0.004196392372250557 +2,SPY,2023-09-26,0.00035078052314929664,-0.01480023842304945 +2,SPY,2023-09-27,0.0003188074042554945,0.0003991234698332846 +2,SPY,2023-09-28,0.00030932147637940943,0.005780509673058987 +2,SPY,2023-09-29,0.0003060565213672817,-0.002429819665849209 +2,SPY,2023-10-02,0.0002999804855789989,-0.0003977142332587391 +2,SPY,2023-10-03,0.0002927185269072652,-0.013476348482072353 +2,SPY,2023-10-04,0.0002865853894036263,0.007255451753735542 +2,SPY,2023-10-05,0.000280986656434834,-0.0003768579044844955 +2,SPY,2023-10-06,0.0002768271369859576,0.011802849359810352 +2,SPY,2023-10-09,0.0002765621175058186,0.0063819377683103085 +2,SPY,2023-10-10,0.0003026319609489292,0.005191267933696508 +2,SPY,2023-10-11,0.000338306330377236,0.004087962210178375 +2,SPY,2023-10-12,0.0003584846272133291,-0.006115116644650698 +2,SPY,2023-10-13,0.00036431176704354584,-0.0049933940172195435 +2,SPY,2023-10-16,0.0003576559538487345,0.010466529987752438 +2,SPY,2023-10-17,0.00038177560782060027,-4.589736272464506e-05 +2,SPY,2023-10-18,0.00039012834895402193,-0.013414667919278145 +2,SPY,2023-10-19,0.00036086380714550614,-0.008825279772281647 +2,SPY,2023-10-20,0.0003415683750063181,-0.012364099733531475 +2,SPY,2023-10-23,0.00030219272593967617,-0.001734733348712325 +2,SPY,2023-10-24,0.0003020873118657619,0.0075110383331775665 +2,SPY,2023-10-25,0.00029888679273426533,-0.014455955475568771 +2,SPY,2023-10-26,0.0002962177386507392,-0.012046962976455688 +2,SPY,2023-10-27,0.00032241203007288277,-0.004543195944279432 +2,SPY,2023-10-30,0.0003455448604654521,0.011884966865181923 +2,SPY,2023-10-31,0.0003137840540148318,0.006260605063289404 +2,SPY,2023-11-01,0.0002887332229875028,0.010608301497995853 +2,SPY,2023-11-02,0.00029684582841582596,0.018983017653226852 +2,SPY,2023-11-03,0.0003336138906888664,0.009082013741135597 +2,SPY,2023-11-06,0.00036076715332455933,0.0022978479973971844 +2,SPY,2023-11-07,0.00037579034687951207,0.00284193130210042 +2,SPY,2023-11-08,0.0003913318214472383,0.0007322880555875599 +2,SPY,2023-11-09,0.00040121673373505473,-0.007829470559954643 +2,SPY,2023-11-10,0.0003939862654078752,0.015484286472201347 +2,SPY,2023-11-13,0.00040471594547852874,-0.0009537073783576488 +2,SPY,2023-11-14,0.00040086169610731304,0.01921497844159603 +2,SPY,2023-11-15,0.00040303589776158333,0.00211470783688128 +2,SPY,2023-11-16,0.0004006830567959696,0.0012226253747940063 +2,SPY,2023-11-17,0.0003946377837564796,0.0012429797789081931 +2,SPY,2023-11-20,0.0003958983870688826,0.0076681505888700485 +2,SPY,2023-11-21,0.00039108001510612667,-0.002181872259825468 +2,SPY,2023-11-22,0.00038213576772250235,0.0038535387720912695 +2,SPY,2023-11-24,0.0003833875816781074,0.0006150712142698467 +2,SPY,2023-11-27,0.00038216065149754286,-0.0018025926547124982 +2,SPY,2023-11-28,0.0003806907043326646,0.0009897220879793167 +2,SPY,2023-11-29,0.0003818824770860374,-0.0007037495961412787 +2,SPY,2023-11-30,0.0003803115105256438,0.003929764963686466 +2,SPY,2023-12-01,0.00038754273555241525,0.005898433271795511 +2,SPY,2023-12-04,0.00039485006709583104,-0.005263310391455889 +2,SPY,2023-12-05,0.0003931809915229678,-0.0001970758312381804 +2,SPY,2023-12-06,0.0003859893186017871,-0.004037774633616209 +2,SPY,2023-12-07,0.00037462636828422546,0.007601392455399036 +2,SPY,2023-12-08,0.00038920011138543487,0.0042898948304355145 +2,SPY,2023-12-11,0.0004072203009855002,0.003881986252963543 +2,SPY,2023-12-12,0.0004259403212927282,0.004556814208626747 +2,SPY,2023-12-13,0.00043434282997623086,0.013695846311748028 +2,SPY,2023-12-14,0.0004488704144023359,0.003204226726666093 +2,SPY,2023-12-15,0.00044746999628841877,-0.0016476850723847747 +2,SPY,2023-12-18,0.00044987918226979673,0.005609259009361267 +2,SPY,2023-12-19,0.00045403503463603556,0.0060624657198786736 +2,SPY,2023-12-20,0.00045873114140704274,-0.013954238034784794 +2,SPY,2023-12-21,0.0004245933669153601,0.00943734124302864 +2,SPY,2023-12-22,0.00042446597944945097,0.002007646718993783 +2,SPY,2023-12-26,0.00042233424028381705,0.004213512875139713 +2,SPY,2023-12-27,0.0004292821395210922,0.0018066003685817122 +2,SPY,2023-12-28,0.0004329336225055158,0.00037770686321891844 +2,SPY,2023-12-29,0.0004376495198812336,-0.0028993829619139433 +2,SPY,2024-01-02,0.00043829885544255376,-0.0056119696237146854 +2,SPY,2024-01-03,0.00042522657895460725,-0.008200210519134998 +2,SPY,2024-01-04,0.00041178244282491505,-0.0032262741588056087 +2,SPY,2024-01-05,0.00038619284168817103,0.0013686643214896321 +2,SPY,2024-01-08,0.00038949877489358187,0.014175043441355228 +2,SPY,2024-01-09,0.0004197589005343616,-0.0015182136557996273 +2,SPY,2024-01-10,0.00042988682980649173,0.0056394669227302074 +2,SPY,2024-01-11,0.0004522019880823791,-0.0004406381631270051 +2,SPY,2024-01-12,0.00046207589912228286,0.000692542118486017 +2,SPY,2024-01-16,0.0004607340379152447,-0.00367812835611403 +2,SPY,2024-01-17,0.0004605041758622974,-0.005574135575443506 +2,SPY,2024-01-18,0.0004463389632292092,0.008853436447679996 +2,SPY,2024-01-19,0.000453376182122156,0.012389152310788631 +2,SPY,2024-01-22,0.000466602185042575,0.0021122198086231947 +2,SPY,2024-01-23,0.0004746166814584285,0.0029120389372110367 +2,SPY,2024-01-24,0.00047842555795796216,0.0010927304392680526 +2,SPY,2024-01-25,0.00047756684944033623,0.005424039904028177 +2,SPY,2024-01-26,0.00048033182974904776,-0.001271206303499639 +2,SPY,2024-01-29,0.0004806517099495977,0.007888179272413254 +2,SPY,2024-01-30,0.00048635221901349723,-0.0007737274281680584 +2,SPY,2024-01-31,0.0004867006791755557,-0.016451917588710785 +2,SPY,2024-02-01,0.0004549750010482967,0.013003334403038025 +2,SPY,2024-02-02,0.00046782908611930907,0.010472205467522144 +2,SPY,2024-02-05,0.00047642411664128304,-0.003647713689133525 +2,SPY,2024-02-06,0.000474840693641454,0.0028991110157221556 +2,SPY,2024-02-07,0.00047776231076568365,0.008305716328322887 +2,SPY,2024-02-08,0.0004824489005841315,0.00044152679038234055 +2,SPY,2024-02-09,0.00048344157403334975,0.005762825254350901 +2,SPY,2024-02-12,0.0004836084845010191,-0.00043892633402720094 +2,SPY,2024-02-13,0.0004780587914865464,-0.013868842273950577 +2,SPY,2024-02-14,0.0004467218241188675,0.00904655922204256 +2,SPY,2024-02-15,0.0004520014044828713,0.006876099389046431 +2,SPY,2024-02-16,0.0004648401227314025,-0.004992415197193623 +2,SPY,2024-02-20,0.00046377352555282414,-0.005520655307918787 +2,SPY,2024-02-21,0.00045603574835695326,0.0009054094552993774 +2,SPY,2024-02-22,0.0004593724152073264,0.02048424817621708 +2,SPY,2024-02-23,0.00047695706598460674,0.000689420267008245 +2,SPY,2024-02-26,0.00047995333443395793,-0.003669240977615118 +2,SPY,2024-02-27,0.0004813632695004344,0.0018560249591246247 +2,SPY,2024-02-28,0.0004814892017748207,-0.0013225771253928542 +2,SPY,2024-02-29,0.0004799006273970008,0.003588645486161113 +2,SPY,2024-03-01,0.0004862936621066183,0.009344411082565784 +2,SPY,2024-03-04,0.0004917525802738965,-0.0010729130590334535 +2,SPY,2024-03-05,0.0004912576987408102,-0.010044406168162823 +2,SPY,2024-03-06,0.00047381874173879623,0.005054334178566933 +2,SPY,2024-03-07,0.00047579602687619627,0.009877508506178856 +2,SPY,2024-03-08,0.00048750374116934836,-0.006020172033458948 +2,SPY,2024-03-11,0.0004724241734948009,-0.0008602325688116252 +2,SPY,2024-03-12,0.00046920901513658464,0.01069977879524231 +2,SPY,2024-03-13,0.00047940504737198353,-0.0015687593258917332 +2,SPY,2024-03-14,0.0004782667092513293,-0.0019787175115197897 +2,SPY,2024-03-15,0.0004773911496158689,-0.006890268996357918 +2,SPY,2024-03-18,0.000460134499007836,0.005925564561039209 +2,SPY,2024-03-19,0.0004675809177570045,0.005541827064007521 +2,SPY,2024-03-20,0.0004869488475378603,0.009206828661262989 +2,SPY,2024-03-21,0.0004998227232135832,0.0032993429340422153 +2,SPY,2024-03-22,0.0004985408741049469,-0.001897792681120336 +3,AAPL,2024-03-25,0.0008724028593860567,-0.008334826678037643 +3,AAPL,2024-03-26,0.0008575069950893521,-0.006694938521832228 +3,AAPL,2024-03-27,0.0008319310727529228,0.020990770310163498 +3,AAPL,2024-03-28,0.0008708958048373461,-0.010615297593176365 +3,AAPL,2024-04-01,0.0008776385220699012,-0.008491892367601395 +3,AAPL,2024-04-02,0.0008632529061287642,-0.007023297715932131 +3,AAPL,2024-04-03,0.0008647540234960616,0.0047857253812253475 +3,AAPL,2024-04-04,0.0008912418852560222,-0.0049041337333619595 +3,AAPL,2024-04-05,0.0008948954637162387,0.004491711966693401 +3,AAPL,2024-04-08,0.0009115322609432042,-0.006685816682875156 +3,AAPL,2024-04-09,0.0009167874231934547,0.007216432131826878 +3,AAPL,2024-04-10,0.0009345820872113109,-0.011201840825378895 +3,AAPL,2024-04-11,0.0009167431853711605,0.04236089065670967 +3,AAPL,2024-04-12,0.001016118098050356,0.008589675650000572 +3,AAPL,2024-04-15,0.001055426779203117,-0.022106138989329338 +3,AAPL,2024-04-16,0.0010403672931715846,-0.01935320347547531 +3,AAPL,2024-04-17,0.0009947082726284862,-0.008180788718163967 +3,AAPL,2024-04-18,0.0009610195993445814,-0.005730851553380489 +3,AAPL,2024-04-19,0.0009480438311584294,-0.012287675403058529 +3,AAPL,2024-04-22,0.0009222645894624293,0.00507803400978446 +3,AAPL,2024-04-23,0.0009125476935878396,0.006371361669152975 +3,AAPL,2024-04-24,0.0009312442853115499,0.012622218579053879 +3,AAPL,2024-04-25,0.0009616805473342538,0.0051341671496629715 +3,AAPL,2024-04-26,0.0010038487380370498,-0.0034790378995239735 +3,AAPL,2024-04-29,0.0010207585291936994,0.024505414068698883 +3,AAPL,2024-04-30,0.0010683651780709624,-0.018439890816807747 +3,AAPL,2024-05-01,0.001043476746417582,-0.006065521854907274 +3,AAPL,2024-05-02,0.0010445569641888142,0.02179287001490593 +3,AAPL,2024-05-03,0.0010783708421513438,0.05809544026851654 +3,AAPL,2024-05-06,0.0010906961979344487,-0.00914859026670456 +3,AAPL,2024-05-07,0.001073910272680223,0.0037901371251791716 +3,AAPL,2024-05-08,0.0010573919862508774,0.0018623888026922941 +3,AAPL,2024-05-09,0.0010504431556910276,0.009964455850422382 +3,AAPL,2024-05-10,0.0010585981654003263,-0.006914051715284586 +3,AAPL,2024-05-13,0.0010103461099788547,0.017491452395915985 +3,AAPL,2024-05-14,0.0010306028416380286,0.0061544617637991905 +3,AAPL,2024-05-15,0.0010277298279106617,0.012143993750214577 +3,AAPL,2024-05-16,0.0010305335745215416,0.0006322248955257237 +3,AAPL,2024-05-17,0.0010105951223522425,0.00015805463772267103 +3,AAPL,2024-05-20,0.0010169872548431158,0.006143113598227501 +3,AAPL,2024-05-21,0.0010145454434677958,0.006833919323980808 +3,AAPL,2024-05-22,0.0010180446552112699,-0.007566985674202442 +3,AAPL,2024-05-23,0.0009861441794782877,-0.021282942965626717 +3,AAPL,2024-05-24,0.0009119545575231314,0.016452081501483917 +3,AAPL,2024-05-28,0.0009443741291761398,5.262179911369458e-05 +3,AAPL,2024-05-29,0.000953761104028672,0.00157777254935354 +3,AAPL,2024-05-30,0.0009752677869983017,0.0052412813529372215 +3,AAPL,2024-05-31,0.001042987685650587,0.005006127990782261 +3,AAPL,2024-06-03,0.001108161173760891,0.00921636912971735 +3,AAPL,2024-06-04,0.0011525263544172049,0.0016477518947795033 +3,AAPL,2024-06-05,0.0011675014393404126,0.0077904281206429005 +3,AAPL,2024-06-06,0.0011807247065007687,-0.007122011389583349 +3,AAPL,2024-06-07,0.0011797396000474691,0.012316148728132248 +3,AAPL,2024-06-10,0.0011955918744206429,-0.019333453848958015 +3,AAPL,2024-06-11,0.001166833215393126,0.07013139873743057 +3,AAPL,2024-06-12,0.0012034651590511203,0.028177453204989433 +3,AAPL,2024-06-13,0.0011798214400187135,0.005476267542690039 +3,AAPL,2024-06-14,0.0011458531953394413,-0.008202020078897476 +3,AAPL,2024-06-17,0.0011086816666647792,0.019480541348457336 +3,AAPL,2024-06-18,0.0011001015082001686,-0.011045299470424652 +3,AAPL,2024-06-20,0.001061008544638753,-0.021747589111328125 +3,AAPL,2024-06-21,0.0009703903924673796,-0.010499440133571625 +3,AAPL,2024-06-24,0.0008618910796940327,0.003127771895378828 +3,AAPL,2024-06-25,0.0008651323732919991,0.004458195064216852 +3,AAPL,2024-06-26,0.000871645868755877,0.01979607343673706 +3,AAPL,2024-06-27,0.0009177221800200641,0.00397796556353569 +3,AAPL,2024-06-28,0.0009619089541956782,-0.01638757437467575 +3,AAPL,2024-07-01,0.0009460244327783585,0.028688957914710045 +3,AAPL,2024-07-02,0.0009958241134881973,0.016109557822346687 +3,AAPL,2024-07-03,0.0010435644071549177,0.005794092081487179 +3,AAPL,2024-07-05,0.001073902123607695,0.02139018103480339 +3,AAPL,2024-07-08,0.0010960439685732126,0.00651745218783617 +3,AAPL,2024-07-09,0.0010936926119029522,0.003767683170735836 +3,AAPL,2024-07-10,0.0010955214966088533,0.018629107624292374 +3,AAPL,2024-07-11,0.0011247306829318404,-0.02349466271698475 +3,AAPL,2024-07-12,0.0010648240568116307,0.012966428883373737 +3,AAPL,2024-07-15,0.0010661287233233452,0.016604717820882797 +3,AAPL,2024-07-16,0.0010661743581295013,0.00179012562148273 +3,AAPL,2024-07-17,0.0010669997427612543,-0.025621341541409492 +3,AAPL,2024-07-18,0.000974962895270437,-0.02074863202869892 +3,AAPL,2024-07-19,0.0007880984339863062,0.0005797070334665477 +3,AAPL,2024-07-22,0.000725465128198266,-0.0015615582233294845 +3,AAPL,2024-07-23,0.000736322661396116,0.004677378572523594 +3,AAPL,2024-07-24,0.0007512886077165604,-0.029175840318202972 +3,AAPL,2024-07-25,0.0006240615621209145,-0.004816047381609678 +3,AAPL,2024-07-26,0.0005836618947796524,0.0021586110815405846 +3,AAPL,2024-07-29,0.0005956088425591588,0.001283898833207786 +3,AAPL,2024-07-30,0.0006249381694942713,0.0025627927388995886 +3,AAPL,2024-07-31,0.0006862091249786317,0.014879509806632996 +3,AAPL,2024-08-01,0.0007542770472355187,-0.016892533749341965 +3,AAPL,2024-08-02,0.0007397548179142177,0.006845848169177771 +3,AAPL,2024-08-05,0.0007800106541253626,-0.04936562106013298 +3,AAPL,2024-08-06,0.0005898523377254605,-0.009796065278351307 +3,AAPL,2024-08-07,0.0004820596659556031,0.012420694343745708 +3,AAPL,2024-08-08,0.0004584801208693534,0.016496486961841583 +3,AAPL,2024-08-09,0.0004713604284916073,0.013642442412674427 +3,AAPL,2024-08-12,0.0005545665044337511,0.007104648742824793 +3,AAPL,2024-08-13,0.0006336029036901891,0.017046812921762466 +3,AAPL,2024-08-14,0.0007230247720144689,0.002031750278547406 +3,AAPL,2024-08-15,0.0007863638456910849,0.013439791277050972 +3,AAPL,2024-08-16,0.0008570999489165843,0.005901044700294733 +3,AAPL,2024-08-19,0.0009194895974360406,-0.0007080741343088448 +3,AAPL,2024-08-20,0.0009438608540222049,0.0027409906033426523 +3,AAPL,2024-08-21,0.0009613219881430268,-0.000485873082652688 +3,AAPL,2024-08-22,0.0009643081575632095,-0.008293768391013145 +3,AAPL,2024-08-23,0.0009343770798295736,0.01023543905466795 +3,AAPL,2024-08-26,0.0009701364324428141,0.0014978406252339482 +3,AAPL,2024-08-27,0.0009625446400605142,0.0037345795426517725 +3,AAPL,2024-08-28,0.0009725865093059838,-0.006776459980756044 +3,AAPL,2024-08-29,0.0009307774598710239,0.014464940875768661 +3,AAPL,2024-08-30,0.0009409317281097174,-0.0034437819849699736 +3,AAPL,2024-09-03,0.0009062575991265476,-0.027582140639424324 +3,AAPL,2024-09-04,0.0008152052760124207,-0.008656161837279797 +3,AAPL,2024-09-05,0.0006880730506964028,0.006903944071382284 +3,AAPL,2024-09-06,0.000702332123182714,-0.0070397378876805305 +3,AAPL,2024-09-09,0.0006405748426914215,0.00040753683424554765 +3,AAPL,2024-09-10,0.0006746474537067115,-0.0036281065549701452 +3,AAPL,2024-09-11,0.0006919369334354997,0.011518632061779499 +3,AAPL,2024-09-12,0.0007579461671411991,0.000493893981911242 +3,AAPL,2024-09-13,0.0008059128886088729,-0.0012127524241805077 +3,AAPL,2024-09-16,0.0008313785656355321,-0.028168337419629097 +3,AAPL,2024-09-17,0.0007478706538677216,0.002170393243432045 +3,AAPL,2024-09-18,0.0006990808178670704,0.017829852178692818 +3,AAPL,2024-09-19,0.0007809470989741385,0.03639500215649605 +3,AAPL,2024-09-20,0.0008933692588470876,-0.002931661903858185 +3,AAPL,2024-09-23,0.0009707119897939265,-0.007609902881085873 +3,AAPL,2024-09-24,0.0009828959591686726,0.00396608654409647 +3,AAPL,2024-09-25,0.001011537853628397,-0.004407796077430248 +3,AAPL,2024-09-26,0.0009871780639514327,0.005067374091595411 +3,AAPL,2024-09-27,0.0010163290426135063,0.001185875036753714 +3,AAPL,2024-09-30,0.0010286346077919006,0.02261430397629738 +3,AAPL,2024-10-01,0.0010742438025772572,-0.02957455813884735 +3,AAPL,2024-10-02,0.0010157509241253138,0.0025165709666907787 +3,AAPL,2024-10-03,0.0010059090564027429,-0.00490659661591053 +3,AAPL,2024-10-04,0.0009977350709959865,0.004994862247258425 +3,AAPL,2024-10-07,0.0010087050031870604,-0.022788507863879204 +3,AAPL,2024-10-08,0.0009206332615576684,0.01823672465980053 +3,AAPL,2024-10-09,0.0009325331775471568,0.01656038500368595 +3,AAPL,2024-10-10,0.000989374122582376,-0.0021805004216730595 +3,AAPL,2024-10-11,0.0010226789163425565,-0.006526695564389229 +3,AAPL,2024-10-14,0.001020318130031228,0.016345493495464325 +3,AAPL,2024-10-15,0.0010801198659464717,0.010964352637529373 +3,AAPL,2024-10-16,0.0011073780478909612,-0.00889116432517767 +3,AAPL,2024-10-17,0.0010968671413138509,0.0015949252992868423 +3,AAPL,2024-10-18,0.0011114244116470218,0.012201857753098011 +3,AAPL,2024-10-21,0.0011443269904702902,0.006278147455304861 +3,AAPL,2024-10-22,0.0011522347340360284,-0.002625213237479329 +3,AAPL,2024-10-23,0.0011556699173524976,-0.021860208362340927 +3,AAPL,2024-10-24,0.0010921271750703454,-0.0008237360161729157 +3,AAPL,2024-10-25,0.0010856955777853727,0.003636554814875126 +3,AAPL,2024-10-28,0.001068643992766738,0.008562709204852581 +3,AAPL,2024-10-29,0.0010927609400823712,0.001156082609668374 +3,AAPL,2024-10-30,0.0011233043624088168,-0.01539582759141922 +3,AAPL,2024-10-31,0.0010634706122800708,-0.01837725006043911 +3,AAPL,2024-11-01,0.000920232618227601,-0.01336858794093132 +3,AAPL,2024-11-04,0.0008763691294007003,-0.004045669920742512 +3,AAPL,2024-11-05,0.0008866126299835742,0.006465183105319738 +3,AAPL,2024-11-06,0.0009248440619558096,-0.0032722707837820053 +3,AAPL,2024-11-07,0.0009133394341915846,0.02114691399037838 +3,AAPL,2024-11-08,0.0010118797654286027,-0.0011889140587300062 +3,AAPL,2024-11-11,0.0010618066880851984,-0.012101531028747559 +3,AAPL,2024-11-12,0.001065399032086134,0.0 +3,AAPL,2024-11-13,0.0010680350242182612,0.003961295820772648 +3,AAPL,2024-11-14,0.0010788148501887918,0.013676491566002369 +3,AAPL,2024-11-15,0.0011392979649826884,-0.01420963741838932 +3,AAPL,2024-11-18,0.0011176305124536157,0.013332890346646309 +3,AAPL,2024-11-19,0.0011630349326878786,0.001139628468081355 +3,AAPL,2024-11-20,0.0011962028220295906,0.0031490607652813196 +3,AAPL,2024-11-21,0.001216329401358962,-0.002098159398883581 +3,AAPL,2024-11-22,0.001224486157298088,0.0058901188895106316 +3,AAPL,2024-11-25,0.0012341318652033806,0.012966327369213104 +3,AAPL,2024-11-26,0.0012621561763808131,0.009360522963106632 +3,AAPL,2024-11-27,0.0012719014193862677,-0.0005531837814487517 +3,AAPL,2024-11-29,0.0012838022084906697,0.010163967497646809 +3,AAPL,2024-12-02,0.0012884394964203238,0.009477471001446247 +3,AAPL,2024-12-03,0.0012795949587598443,0.01269099023193121 +3,AAPL,2024-12-04,0.0012923342874273658,0.0014825835824012756 +3,AAPL,2024-12-05,0.0012854891829192638,0.00012344947026576847 +3,AAPL,2024-12-06,0.0012675476027652621,-0.0008233266416937113 +3,AAPL,2024-12-09,0.0012530743842944503,0.015972914174199104 +3,AAPL,2024-12-10,0.0012706684647127986,0.004125335719436407 +3,AAPL,2024-12-11,0.0012697342317551374,-0.005179551895707846 +3,AAPL,2024-12-12,0.0012555422727018595,0.005946028511971235 +3,AAPL,2024-12-13,0.0012603707145899534,0.0006853067898191512 +3,AAPL,2024-12-16,0.0012613352155312896,0.011659380048513412 +3,AAPL,2024-12-17,0.0013004192151129246,0.009672712534666061 +3,AAPL,2024-12-18,0.0013138384092599154,-0.021654488518834114 +3,AAPL,2024-12-19,0.0012123559135943651,0.0069901603274047375 +3,AAPL,2024-12-20,0.0011852245079353452,0.018641037866473198 +3,AAPL,2024-12-23,0.0012226647231727839,0.0030601585749536753 +3,AAPL,2024-12-24,0.0012173973955214024,0.011412668973207474 +3,AAPL,2024-12-26,0.001227818662300706,0.0031706616282463074 +3,AAPL,2024-12-27,0.0012293484760448337,-0.013330507092177868 +3,AAPL,2024-12-30,0.00118537456728518,-0.013352212496101856 +3,AAPL,2024-12-31,0.0011043684789910913,-0.007082877680659294 +3,AAPL,2025-01-02,0.0010401230538263917,-0.026586202904582024 +3,AAPL,2025-01-03,0.0008670230163261294,-0.0020114362705498934 +3,AAPL,2025-01-06,0.0008475082577206194,0.0067163389176130295 +3,AAPL,2025-01-07,0.0008897251100279391,-0.011453023180365562 +3,AAPL,2025-01-08,0.0008487295708619058,0.0020209134090691805 +3,AAPL,2025-01-10,0.0008447070722468197,-0.024399057030677795 +3,MSFT,2024-03-25,0.0011825042311102152,-0.013809585943818092 +3,MSFT,2024-03-26,0.0011614782270044088,-0.002865604590624571 +3,MSFT,2024-03-27,0.0011373200686648488,-0.0005217751604504883 +3,MSFT,2024-03-28,0.0011285132495686412,-0.001686156028881669 +3,MSFT,2024-04-01,0.001120385597459972,0.009109348058700562 +3,MSFT,2024-04-02,0.0011361254146322608,-0.007399465423077345 +3,MSFT,2024-04-03,0.001115561812184751,-0.0023517871741205454 +3,MSFT,2024-04-04,0.001123135327361524,-0.006131294649094343 +3,MSFT,2024-04-05,0.0010910618584603071,0.018117696046829224 +3,MSFT,2024-04-08,0.0011387247359380126,-0.0021880476269870996 +3,MSFT,2024-04-09,0.0011556255631148815,0.003972416277974844 +3,MSFT,2024-04-10,0.001175642479211092,-0.007109702564775944 +3,MSFT,2024-04-11,0.0011637419229373336,0.010973013006150723 +3,MSFT,2024-04-12,0.001199193298816681,-0.014191417954862118 +3,MSFT,2024-04-15,0.0011441786773502827,-0.019772136583924294 +3,MSFT,2024-04-16,0.0010265229502692819,0.0022697991225868464 +3,MSFT,2024-04-17,0.0009430479840375483,-0.006631112657487392 +3,MSFT,2024-04-18,0.0008908591698855162,-0.01855195313692093 +3,MSFT,2024-04-19,0.0008246582583524287,-0.0128207728266716 +3,MSFT,2024-04-22,0.0007696281536482275,0.004599675536155701 +3,MSFT,2024-04-23,0.0007495994213968515,0.01635093055665493 +3,MSFT,2024-04-24,0.0008039911626838148,0.003649046178907156 +3,MSFT,2024-04-25,0.0008430347661487758,-0.024800172075629234 +3,MSFT,2024-04-26,0.0008370500290766358,0.018079504370689392 +3,MSFT,2024-04-29,0.0008693495183251798,-0.010067252442240715 +3,MSFT,2024-04-30,0.0008752703433856368,-0.03264642506837845 +3,MSFT,2024-05-01,0.0006659639766439795,0.014306357130408287 +3,MSFT,2024-05-02,0.000689211068674922,0.007316104136407375 +3,MSFT,2024-05-03,0.0007116838241927326,0.021927490830421448 +3,MSFT,2024-05-06,0.0007772322278469801,0.01677686534821987 +3,MSFT,2024-05-07,0.0008436099742539227,-0.010208197869360447 +3,MSFT,2024-05-08,0.0008920825202949345,0.0029272984247654676 +3,MSFT,2024-05-09,0.0009615713497623801,0.004326367285102606 +3,MSFT,2024-05-10,0.0010288029443472624,0.005852068308740854 +3,MSFT,2024-05-13,0.0010710920905694366,-0.0024624038487672806 +3,MSFT,2024-05-14,0.0010959588689729571,0.006841147784143686 +3,MSFT,2024-05-15,0.0011235263664275408,0.017332756891846657 +3,MSFT,2024-05-16,0.0011391707230359316,-0.0049522449262440205 +3,MSFT,2024-05-17,0.0011237700236961246,-0.0018544519552960992 +3,MSFT,2024-05-20,0.0011247106594964862,0.012134344317018986 +3,MSFT,2024-05-21,0.0011352879228070378,0.008661328814923763 +3,MSFT,2024-05-22,0.0011357907205820084,0.003443678142502904 +3,MSFT,2024-05-23,0.0011375705944374204,-0.008209860883653164 +3,MSFT,2024-05-24,0.0010982186067849398,0.007373237982392311 +3,MSFT,2024-05-28,0.0011118216207250953,0.00037197486381046474 +3,MSFT,2024-05-29,0.0011055065551772714,-0.0026759966276586056 +3,MSFT,2024-05-30,0.0010986822890117764,-0.03437020257115364 +3,MSFT,2024-05-31,0.0010102546075358987,0.0011087714228779078 +3,MSFT,2024-06-03,0.0010164887644350529,-0.0038859781343489885 +3,MSFT,2024-06-04,0.001028930302709341,0.006147743668407202 +3,MSFT,2024-06-05,0.0010424257488921285,0.018903503194451332 +3,MSFT,2024-06-06,0.001098615932278335,0.0012019980931654572 +3,MSFT,2024-06-07,0.0011298783356323838,-0.0015794364735484123 +3,MSFT,2024-06-10,0.0011377750197425485,0.00943977851420641 +3,MSFT,2024-06-11,0.0011680846801027656,0.011178987100720406 +3,MSFT,2024-06-12,0.0011891878675669432,0.019182560965418816 +3,MSFT,2024-06-13,0.0011960258707404137,0.0011783735826611519 +3,MSFT,2024-06-14,0.001196631113998592,0.0022393427789211273 +3,MSFT,2024-06-17,0.0012010078644379973,0.013020087033510208 +3,MSFT,2024-06-18,0.001199305639602244,-0.004537734668701887 +3,MSFT,2024-06-20,0.0011896733194589615,-0.001434841426089406 +3,MSFT,2024-06-21,0.00118035648483783,0.009112434461712837 +3,MSFT,2024-06-24,0.0011823616223409772,-0.004702172242105007 +3,MSFT,2024-06-25,0.0011778257321566343,0.0073000420816242695 +3,MSFT,2024-06-26,0.0011764081427827477,0.0026795759331434965 +3,MSFT,2024-06-27,0.0011734608560800552,0.0015249080024659634 +3,MSFT,2024-06-28,0.0011746914824470878,-0.013114223256707191 +3,MSFT,2024-07-01,0.001146807917393744,0.02164577506482601 +3,MSFT,2024-07-02,0.0011652675457298756,0.005567535292357206 +3,MSFT,2024-07-03,0.0011754074366763234,0.003238830715417862 +3,MSFT,2024-07-05,0.0011833059834316373,0.014628870412707329 +3,MSFT,2024-07-08,0.0011937766103073955,-0.002827258547767997 +3,MSFT,2024-07-09,0.0011864249827340245,-0.014474422670900822 +3,MSFT,2024-07-10,0.0011579666752368212,0.014495963230729103 +3,MSFT,2024-07-11,0.001178388250991702,-0.025084147229790688 +3,MSFT,2024-07-12,0.0011364667443558574,-0.0025324022863060236 +3,MSFT,2024-07-15,0.001130500459112227,0.0009035709081217647 +3,MSFT,2024-07-16,0.0011331163113936782,-0.009828616864979267 +3,MSFT,2024-07-17,0.0011137435212731361,-0.013437521643936634 +3,MSFT,2024-07-18,0.001083620241843164,-0.007127534132450819 +3,MSFT,2024-07-19,0.0010399224702268839,-0.007430484518408775 +3,MSFT,2024-07-22,0.0009763247217051685,0.013249539770185947 +3,MSFT,2024-07-23,0.0010003139032050967,0.004302860703319311 +3,MSFT,2024-07-24,0.0010248704347759485,-0.03651343286037445 +3,MSFT,2024-07-25,0.0008228139486163855,-0.02478599362075329 +3,MSFT,2024-07-26,0.0006663904641754925,0.016286347061395645 +3,MSFT,2024-07-29,0.000637553574051708,0.0034273751080036163 +3,MSFT,2024-07-30,0.0006015570252202451,-0.008968428708612919 +3,MSFT,2024-07-31,0.0005228322115726769,-0.010864725336432457 +3,MSFT,2024-08-01,0.0004810011887457222,-0.002968602580949664 +3,MSFT,2024-08-02,0.0004313377139624208,-0.02088233456015587 +3,MSFT,2024-08-05,0.00031902483897283673,-0.03320201858878136 +3,MSFT,2024-08-06,0.00012023989256704226,0.01122355181723833 +3,MSFT,2024-08-07,9.42516780924052e-05,-0.0029572497587651014 +3,MSFT,2024-08-08,9.948963270289823e-05,0.01063530147075653 +3,MSFT,2024-08-09,0.00011010500020347536,0.008235222660005093 +3,MSFT,2024-08-12,0.00012211814464535564,0.001944041228853166 +3,MSFT,2024-08-13,0.00020548046450130641,0.017543794587254524 +3,MSFT,2024-08-14,0.00029773724963888526,0.006860244087874889 +3,MSFT,2024-08-15,0.0003812729846686125,0.011754576116800308 +3,MSFT,2024-08-16,0.0004982601967640221,-0.006098960526287556 +3,MSFT,2024-08-19,0.0005700151086784899,0.007285704370588064 +3,MSFT,2024-08-20,0.0006255359621718526,0.007727477699518204 +3,MSFT,2024-08-21,0.0006771498010493815,-0.0015548344235867262 +3,MSFT,2024-08-22,0.0007171885808929801,-0.020460540428757668 +3,MSFT,2024-08-23,0.0007496936013922095,0.002979499055072665 +3,MSFT,2024-08-26,0.000776905391830951,-0.007949229329824448 +3,MSFT,2024-08-27,0.0007513387245126069,0.0008460430544801056 +3,MSFT,2024-08-28,0.0007452119025401771,-0.00785969477146864 +3,MSFT,2024-08-29,0.0006659323698841035,0.0061185103841125965 +3,MSFT,2024-08-30,0.0006797132664360106,0.009683792479336262 +3,MSFT,2024-09-03,0.0007092411397024989,-0.018631568178534508 +3,MSFT,2024-09-04,0.0006466790800914168,-0.0013197952648624778 +3,MSFT,2024-09-05,0.0006620101048611104,-0.0012479695724323392 +3,MSFT,2024-09-06,0.000680251105222851,-0.016516901552677155 +3,MSFT,2024-09-09,0.0006190870772115886,0.009957575239241123 +3,MSFT,2024-09-10,0.0006424118182621896,0.02068580873310566 +3,MSFT,2024-09-11,0.0007198770181275904,0.021117623895406723 +3,MSFT,2024-09-12,0.0007877980824559927,0.009317290969192982 +3,MSFT,2024-09-13,0.0008144823368638754,0.008372368291020393 +3,MSFT,2024-09-16,0.0008374881581403315,0.0017401836812496185 +3,MSFT,2024-09-17,0.0008659837767481804,0.00879423413425684 +3,MSFT,2024-09-18,0.00089360709534958,-0.010023493319749832 +3,MSFT,2024-09-19,0.0008871645550243556,0.01812565326690674 +3,MSFT,2024-09-20,0.0008885649149306118,-0.007826310582458973 +3,MSFT,2024-09-23,0.0008769941050559282,-0.00405168579891324 +3,MSFT,2024-09-24,0.0008625861955806613,-0.010061819106340408 +3,MSFT,2024-09-25,0.0008473146590404212,0.0068269832991063595 +3,MSFT,2024-09-26,0.0008383493986912072,-0.0018530023517087102 +3,MSFT,2024-09-27,0.000848142197355628,-0.007657239679247141 +3,MSFT,2024-09-30,0.0008183082682080567,0.005312814377248287 +3,MSFT,2024-10-01,0.0008242258918471634,-0.02258642204105854 +3,MSFT,2024-10-02,0.0007040094933472574,-0.008498359471559525 +3,MSFT,2024-10-03,0.0006333639612421393,-0.001415406703017652 +3,MSFT,2024-10-04,0.0006264285184442997,-0.0011530007468536496 +3,MSFT,2024-10-07,0.0006410772330127656,-0.015794841572642326 +3,MSFT,2024-10-08,0.0006291685276664793,0.012544979341328144 +3,MSFT,2024-10-09,0.000656230840831995,0.006608979776501656 +3,MSFT,2024-10-10,0.0006945198401808739,-0.003888085950165987 +3,MSFT,2024-10-11,0.0007163052796386182,0.001153759192675352 +3,MSFT,2024-10-14,0.0007292114896699786,0.006750798784196377 +3,MSFT,2024-10-15,0.0007372075924649835,-0.0009548899251967669 +3,MSFT,2024-10-16,0.0007444579969160259,-0.0062764366157352924 +3,MSFT,2024-10-17,0.0007349025690928102,0.0014407428679987788 +3,MSFT,2024-10-18,0.0007543379324488342,0.0034496334847062826 +3,MSFT,2024-10-21,0.0007857914315536618,0.0014816715847700834 +3,MSFT,2024-10-22,0.0008083780994638801,0.020631875842809677 +3,MSFT,2024-10-23,0.0008362240623682737,-0.006830079481005669 +3,MSFT,2024-10-24,0.0008659366867505014,0.00030608809902332723 +3,MSFT,2024-10-25,0.0008913773344829679,0.008019967004656792 +3,MSFT,2024-10-28,0.000925145111978054,-0.0036503192968666553 +3,MSFT,2024-10-29,0.000946899235714227,0.012486648745834827 +3,MSFT,2024-10-30,0.001005665515549481,0.0013417683076113462 +3,MSFT,2024-10-31,0.001021030475385487,-0.062436893582344055 +3,MSFT,2024-11-01,0.0008718027384020388,0.009844338521361351 +3,MSFT,2024-11-04,0.0008323649526573718,-0.0046651591546833515 +3,MSFT,2024-11-05,0.0007552360184490681,0.007317787501960993 +3,MSFT,2024-11-06,0.0007637468515895307,0.02097131311893463 +3,MSFT,2024-11-07,0.0007991492166183889,0.012417268939316273 +3,MSFT,2024-11-08,0.0008880449458956718,-0.006816208828240633 +3,MSFT,2024-11-11,0.0009223321685567498,-0.01077885553240776 +3,MSFT,2024-11-12,0.0009245782857760787,0.01193773653358221 +3,MSFT,2024-11-13,0.0009743296541273594,0.005116581916809082 +3,MSFT,2024-11-14,0.0010078437626361847,0.003966841846704483 +3,MSFT,2024-11-15,0.0010371414246037602,-0.028247950598597527 +3,MSFT,2024-11-18,0.0009501199820078909,0.0018296841299161315 +3,MSFT,2024-11-19,0.0009387112804688513,0.004870605655014515 +3,MSFT,2024-11-20,0.0009530920651741326,-0.005520365666598082 +3,MSFT,2024-11-21,0.0009253135067410767,-0.004326054826378822 +3,MSFT,2024-11-22,0.0009034854592755437,0.009953505359590054 +3,MSFT,2024-11-25,0.0009249461581930518,0.0042833006009459496 +3,MSFT,2024-11-26,0.0009577490272931755,0.02173013985157013 +3,MSFT,2024-11-27,0.0010511359432712197,-0.011751135811209679 +3,MSFT,2024-11-29,0.0010732116643339396,0.0011104911100119352 +3,MSFT,2024-12-02,0.0010815808782353997,0.017602667212486267 +3,MSFT,2024-12-03,0.0011089694453403354,0.0005103024886921048 +3,MSFT,2024-12-04,0.00113045540638268,0.014321780763566494 +3,MSFT,2024-12-05,0.0011415471090003848,0.01181778684258461 +3,MSFT,2024-12-06,0.0011531220516189933,0.0021440356504172087 +3,MSFT,2024-12-09,0.0011446328135207295,0.005508211441338062 +3,MSFT,2024-12-10,0.0011460387613624334,-0.006049483548849821 +3,MSFT,2024-12-11,0.00112333323340863,0.012686236761510372 +3,MSFT,2024-12-12,0.001125797745771706,0.0012687256094068289 +3,MSFT,2024-12-13,0.0011096068192273378,-0.005106958094984293 +3,MSFT,2024-12-16,0.0010901116766035557,0.009612375870347023 +3,MSFT,2024-12-17,0.0011326776584610343,0.006335171405225992 +3,MSFT,2024-12-18,0.0011488011805340648,-0.038284651935100555 +3,MSFT,2024-12-19,0.0009919751901179552,-0.0008235315908677876 +3,MSFT,2024-12-20,0.0009364009601995349,-0.0009843244915828109 +3,MSFT,2024-12-23,0.0009221974760293961,-0.0030968531500548124 +3,MSFT,2024-12-24,0.0008669676608406007,0.009330257773399353 +3,MSFT,2024-12-26,0.0009244799148291349,-0.00278079928830266 +3,MSFT,2024-12-27,0.0009564252104610205,-0.01745305210351944 +3,MSFT,2024-12-30,0.0008837106288410723,-0.013327858410775661 +3,MSFT,2024-12-31,0.0008126111351884902,-0.007869299501180649 +3,MSFT,2025-01-02,0.000749547325540334,-0.006951835937798023 +3,MSFT,2025-01-03,0.0006974571733735502,0.01133131142705679 +3,MSFT,2025-01-06,0.0007295482791960239,0.010573389008641243 +3,MSFT,2025-01-07,0.0007812074036337435,-0.012890930287539959 +3,MSFT,2025-01-08,0.0007663015858270228,0.005171660799533129 +3,MSFT,2025-01-10,0.0007636278751306236,-0.013301808387041092 +3,NVDA,2024-03-25,0.0011161811416968703,0.007533418480306864 +3,NVDA,2024-03-26,0.001253429101780057,-0.026030054315924644 +3,NVDA,2024-03-27,0.0011930069886147976,-0.025284364819526672 +3,NVDA,2024-03-28,0.0011603779857978225,0.001173942000605166 +3,NVDA,2024-04-01,0.0012027323246002197,7.747518247924745e-05 +3,NVDA,2024-04-02,0.0012238806812092662,-0.010132865980267525 +3,NVDA,2024-04-03,0.0012053105747327209,-0.005470148753374815 +3,NVDA,2024-04-04,0.001194122014567256,-0.03498987853527069 +3,NVDA,2024-04-05,0.0008527113823220134,0.024185750633478165 +3,NVDA,2024-04-08,0.0008777136681601405,-0.009992217645049095 +3,NVDA,2024-04-09,0.0008431934984400868,-0.020628441125154495 +3,NVDA,2024-04-10,0.0008071178453974426,0.019549177959561348 +3,NVDA,2024-04-11,0.0009577824966982007,0.04027445241808891 +3,NVDA,2024-04-12,0.0011613834649324417,-0.027182601392269135 +3,NVDA,2024-04-15,0.0011777731124311686,-0.025089247152209282 +3,NVDA,2024-04-16,0.0011024479754269123,0.016308000311255455 +3,NVDA,2024-04-17,0.0011836725752800703,-0.03943350911140442 +3,NVDA,2024-04-18,0.001019214279949665,0.007539708632975817 +3,NVDA,2024-04-19,0.001017239410430193,-0.10541151463985443 +3,NVDA,2024-04-22,0.0006344467401504517,0.04262178763747215 +3,NVDA,2024-04-23,0.0005941716954112053,0.035881076008081436 +3,NVDA,2024-04-24,0.0006745073478668928,-0.0338834747672081 +3,NVDA,2024-04-25,0.0006401566206477582,0.036416083574295044 +3,NVDA,2024-04-26,0.000716189038939774,0.05992406606674194 +3,NVDA,2024-04-29,0.0009395148372277617,0.00025049695977941155 +3,NVDA,2024-04-30,0.0010702083818614483,-0.01556082908064127 +3,NVDA,2024-05-01,0.001105177914723754,-0.03967645764350891 +3,NVDA,2024-05-02,0.0010582900140434504,0.03288281336426735 +3,NVDA,2024-05-03,0.0011531265918165445,0.034045640379190445 +3,NVDA,2024-05-06,0.0012838937109336257,0.03704642876982689 +3,NVDA,2024-05-07,0.0013687961036339402,-0.017362793907523155 +3,NVDA,2024-05-08,0.001347574288956821,-0.0015693497844040394 +3,NVDA,2024-05-09,0.0013482047943398356,-0.018587471917271614 +3,NVDA,2024-05-10,0.0013299904530867934,0.012663541361689568 +3,NVDA,2024-05-13,0.0013325429754331708,0.005780133418738842 +3,NVDA,2024-05-14,0.0013604157138615847,0.010530654340982437 +3,NVDA,2024-05-15,0.0014119551051408052,0.03521071746945381 +3,NVDA,2024-05-16,0.0014619563007727265,-0.00286796223372221 +3,NVDA,2024-05-17,0.0014343233779072762,-0.020125091075897217 +3,NVDA,2024-05-20,0.0014357782201841474,0.024576852098107338 +3,NVDA,2024-05-21,0.0015168108511716127,0.006373366806656122 +3,NVDA,2024-05-22,0.0015830674674361944,-0.004581406246870756 +3,NVDA,2024-05-23,0.0016158982180058956,0.0891060158610344 +3,NVDA,2024-05-24,0.0016875973669812083,0.025397473946213722 +3,NVDA,2024-05-28,0.0017193160019814968,0.06747576594352722 +3,NVDA,2024-05-29,0.0017253151163458824,0.00807949248701334 +3,NVDA,2024-05-30,0.0016964435344561934,-0.03839370608329773 +3,NVDA,2024-05-31,0.0016325903125107288,-0.007877020165324211 +3,NVDA,2024-06-03,0.0015965721104294062,0.047793757170438766 +3,NVDA,2024-06-04,0.0016442039050161839,0.012418022379279137 +3,NVDA,2024-06-05,0.0016400456661358476,0.050270892679691315 +3,NVDA,2024-06-06,0.0016390790697187185,-0.01184714026749134 +3,NVDA,2024-06-07,0.0015872119693085551,-0.0009093921980820596 +3,NVDA,2024-06-10,0.0015506410272791982,0.0074337078258395195 +3,NVDA,2024-06-11,0.0015602015191689134,-0.007169670891016722 +3,NVDA,2024-06-12,0.0015552097465842962,0.03486595302820206 +3,NVDA,2024-06-13,0.0015859653940424323,0.03461752086877823 +3,NVDA,2024-06-14,0.0016035136068239808,0.017362602055072784 +3,NVDA,2024-06-17,0.0016230264445766807,-0.006847853772342205 +3,NVDA,2024-06-18,0.0016142729436978698,0.034517280757427216 +3,NVDA,2024-06-20,0.0016429105307906866,-0.03604532405734062 +3,NVDA,2024-06-21,0.0015322994440793991,-0.032721057534217834 +3,NVDA,2024-06-24,0.0014627750497311354,-0.06917928159236908 +3,NVDA,2024-06-25,0.001238341210409999,0.06537958234548569 +3,NVDA,2024-06-26,0.0012729335576295853,0.002455576788634062 +3,NVDA,2024-06-27,0.0012247400591149926,-0.019250519573688507 +3,NVDA,2024-06-28,0.0011676106369122863,-0.0036359054502099752 +3,NVDA,2024-07-01,0.0011465033749118447,0.006132958456873894 +3,NVDA,2024-07-02,0.0011499355314299464,-0.013200311921536922 +3,NVDA,2024-07-03,0.00111871596891433,0.044717855751514435 +3,NVDA,2024-07-05,0.0012781312689185143,-0.01928376406431198 +3,NVDA,2024-07-08,0.0013256099773570895,0.018659666180610657 +3,NVDA,2024-07-09,0.0013637930387631059,0.024502456188201904 +3,NVDA,2024-07-10,0.0014428774593397975,0.026514068245887756 +3,NVDA,2024-07-11,0.0015391879715025425,-0.05727626383304596 +3,NVDA,2024-07-12,0.0014889794401824474,0.01433924213051796 +3,NVDA,2024-07-15,0.0015174334403127432,-0.006209210027009249 +3,NVDA,2024-07-16,0.0015056952834129333,-0.016326826065778732 +3,NVDA,2024-07-17,0.0014468507142737508,-0.06853507459163666 +3,NVDA,2024-07-18,0.0010061046341434121,0.025934157893061638 +3,NVDA,2024-07-19,0.0010645439615473151,-0.02644278109073639 +3,NVDA,2024-07-22,0.0009682207019068301,0.046473827213048935 +3,NVDA,2024-07-23,0.0010867418022826314,-0.007719628978520632 +3,NVDA,2024-07-24,0.001174332108348608,-0.07045624405145645 +3,NVDA,2024-07-25,0.0009130398975685239,-0.017393415793776512 +3,NVDA,2024-07-26,0.0007470991695299745,0.006922836881130934 +3,NVDA,2024-07-29,0.0007105942931957543,-0.013087157160043716 +3,NVDA,2024-07-30,0.0005444195121526718,-0.07304016500711441 +3,NVDA,2024-07-31,0.00010593064507702366,0.12055353075265884 +3,NVDA,2024-08-01,0.00017589970957487822,-0.06907223910093307 +3,NVDA,2024-08-02,3.904402910848148e-05,-0.017923595383763313 +3,NVDA,2024-08-05,1.7685475540929474e-05,-0.0656888484954834 +3,NVDA,2024-08-06,0.0005672581610269845,0.037131838500499725 +3,NVDA,2024-08-07,0.0003034958499483764,-0.05258168280124664 +3,NVDA,2024-08-08,0.00045707260142080486,0.05946430191397667 +3,NVDA,2024-08-09,0.0001445401576347649,-0.0020980078261345625 +3,NVDA,2024-08-12,-0.00011317522148601711,0.03995475918054581 +3,NVDA,2024-08-13,-5.106231037643738e-05,0.06326513737440109 +3,NVDA,2024-08-14,6.10958450124599e-05,0.016565917059779167 +3,NVDA,2024-08-15,0.00023914308985695243,0.03968311846256256 +3,NVDA,2024-08-16,0.0004107239656150341,0.013902530074119568 +3,NVDA,2024-08-19,0.0005802962114103138,0.042586296796798706 +3,NVDA,2024-08-20,0.0007253717631101608,-0.021380623802542686 +3,NVDA,2024-08-21,0.0008105208980850875,0.009775224141776562 +3,NVDA,2024-08-22,0.0009185050148516893,-0.037746429443359375 +3,NVDA,2024-08-23,0.0008080422994680703,0.04449409991502762 +3,NVDA,2024-08-26,0.0009108993108384311,-0.022750528529286385 +3,NVDA,2024-08-27,0.0007916039903648198,0.014445300213992596 +3,NVDA,2024-08-28,0.0008181074517779052,-0.021189430728554726 +3,NVDA,2024-08-29,0.0006396084791049361,-0.06597814708948135 +3,NVDA,2024-08-30,0.0003545311337802559,0.01502409391105175 +3,NVDA,2024-09-03,0.00020487942674662918,-0.10009659081697464 +3,NVDA,2024-09-04,-9.001166472444311e-05,-0.016713043674826622 +3,NVDA,2024-09-05,-2.3567878088215366e-05,0.009371309541165829 +3,NVDA,2024-09-06,-0.00013199572276789695,-0.041712336242198944 +3,NVDA,2024-09-09,0.00011987399193458259,0.03478596732020378 +3,NVDA,2024-09-10,-6.252425373531878e-05,0.015193483792245388 +3,NVDA,2024-09-11,-0.00017078546807169914,0.07834780216217041 +3,NVDA,2024-09-12,-0.00013333169044926763,0.01898025907576084 +3,NVDA,2024-09-13,4.104797335457988e-05,-0.00033575089764781296 +3,NVDA,2024-09-16,0.00018703819660004228,-0.019671611487865448 +3,NVDA,2024-09-17,0.00031552842119708657,-0.010242418386042118 +3,NVDA,2024-09-18,0.00040641697705723345,-0.019392648711800575 +3,NVDA,2024-09-19,0.0004488784761633724,0.038925591856241226 +3,NVDA,2024-09-20,0.000600877741817385,-0.0159921795129776 +3,NVDA,2024-09-23,0.0006710092420689762,0.002238769084215164 +3,NVDA,2024-09-24,0.0007430093828588724,0.03888670355081558 +3,NVDA,2024-09-25,0.0008750347187742591,0.021606458351016045 +3,NVDA,2024-09-26,0.0009371944470331073,0.004281921312212944 +3,NVDA,2024-09-27,0.0009982259944081306,-0.0215132012963295 +3,NVDA,2024-09-30,0.0009493622928857803,0.00032945387647487223 +3,NVDA,2024-10-01,0.0009017099509947002,-0.0372464582324028 +3,NVDA,2024-10-02,0.000657315831631422,0.015688329935073853 +3,NVDA,2024-10-03,0.0006585591472685337,0.03310196474194527 +3,NVDA,2024-10-04,0.0008504242869094014,0.01670938730239868 +3,NVDA,2024-10-07,0.0010271023493260145,0.022166773676872253 +3,NVDA,2024-10-08,0.0011580177815631032,0.03968140855431557 +3,NVDA,2024-10-09,0.0011953864013776183,-0.0018077412387356162 +3,NVDA,2024-10-10,0.0012334448983892798,0.01615242287516594 +3,NVDA,2024-10-11,0.0012776959920302033,-7.414295396301895e-05 +3,NVDA,2024-10-14,0.0013060306664556265,0.023968670517206192 +3,NVDA,2024-10-15,0.0013262307038530707,-0.0479937307536602 +3,NVDA,2024-10-16,0.0012773912167176604,0.030826682224869728 +3,NVDA,2024-10-17,0.0012820118572562933,0.008875924162566662 +3,NVDA,2024-10-18,0.001295449212193489,0.007783825974911451 +3,NVDA,2024-10-21,0.0013207253068685532,0.040543828159570694 +3,NVDA,2024-10-22,0.0013492677826434374,-0.0008354647434316576 +3,NVDA,2024-10-23,0.001370136276818812,-0.028467286378145218 +3,NVDA,2024-10-24,0.0013331759255379438,0.006072021555155516 +3,NVDA,2024-10-25,0.0013496835017576814,0.008015632629394531 +3,NVDA,2024-10-28,0.0013635074719786644,-0.0072325970977544785 +3,NVDA,2024-10-29,0.001371406251564622,0.00518158171325922 +3,NVDA,2024-10-30,0.0014286907389760017,-0.013614438474178314 +3,NVDA,2024-10-31,0.0014413842000067234,-0.048373993486166 +3,NVDA,2024-11-01,0.0013376027345657349,0.01969047449529171 +3,NVDA,2024-11-04,0.0013526218244805932,0.004788998980075121 +3,NVDA,2024-11-05,0.0013161931419745088,0.027976863086223602 +3,NVDA,2024-11-06,0.001361542847007513,0.03993241488933563 +3,NVDA,2024-11-07,0.001408648444339633,0.02220906876027584 +3,NVDA,2024-11-08,0.0014821338700130582,-0.008431654423475266 +3,NVDA,2024-11-11,0.0014647565549239516,-0.016183799132704735 +3,NVDA,2024-11-12,0.0014336914755403996,0.02064444310963154 +3,NVDA,2024-11-13,0.001470305840484798,-0.013715673238039017 +3,NVDA,2024-11-14,0.001458853716030717,0.003344523021951318 +3,NVDA,2024-11-15,0.0014739439357072115,-0.033112358301877975 +3,NVDA,2024-11-18,0.0014230678789317608,-0.01297305803745985 +3,NVDA,2024-11-19,0.001349465805105865,0.0477873831987381 +3,NVDA,2024-11-20,0.001452424912713468,-0.007647719234228134 +3,NVDA,2024-11-21,0.0014584974851459265,0.005332530941814184 +3,NVDA,2024-11-22,0.001458916929550469,-0.03271056339144707 +3,NVDA,2024-11-25,0.001382510527037084,-0.042672932147979736 +3,NVDA,2024-11-26,0.0012555388966575265,0.006595061160624027 +3,NVDA,2024-11-27,0.0012667733244597912,-0.01160675659775734 +3,NVDA,2024-11-29,0.0013095967005938292,0.021273482590913773 +3,NVDA,2024-12-02,0.0014074590289965272,0.00274489214643836 +3,NVDA,2024-12-03,0.0014684961643069983,0.011689326725900173 +3,NVDA,2024-12-04,0.0015654335729777813,0.034200768917798996 +3,NVDA,2024-12-05,0.0017164559103548527,-0.0004822657792828977 +3,NVDA,2024-12-06,0.0018123254412785172,-0.018226563930511475 +3,NVDA,2024-12-09,0.0018347784643992782,-0.025814997032284737 +3,NVDA,2024-12-10,0.0018293901812285185,-0.02731258235871792 +3,NVDA,2024-12-11,0.0017768859397619963,0.03090825118124485 +3,NVDA,2024-12-12,0.0018094246042892337,-0.014241909608244896 +3,NVDA,2024-12-13,0.001805988373234868,-0.022755954414606094 +3,NVDA,2024-12-16,0.0017631578957661986,-0.01690191589295864 +3,NVDA,2024-12-17,0.0017420521471649408,-0.012271893210709095 +3,NVDA,2024-12-18,0.001705029048025608,-0.011415398679673672 +3,NVDA,2024-12-19,0.001555180293507874,0.013637014664709568 +3,NVDA,2024-12-20,0.0015237678308039904,0.030298518016934395 +3,NVDA,2024-12-23,0.0016037954483181238,0.036232396960258484 +3,NVDA,2024-12-24,0.001697603496722877,0.003930224571377039 +3,NVDA,2024-12-26,0.0017828898271545768,-0.002070418791845441 +3,NVDA,2024-12-27,0.0018415115773677826,-0.02108830027282238 +3,NVDA,2024-12-30,0.001821783953346312,0.0034972303546965122 +3,NVDA,2024-12-31,0.0018180662300437689,-0.02354949526488781 +3,NVDA,2025-01-02,0.0017358502373099327,0.029495809227228165 +3,NVDA,2025-01-03,0.001805438776500523,0.043574362993240356 +3,NVDA,2025-01-06,0.0019145552068948746,0.03375620394945145 +3,NVDA,2025-01-07,0.0019505255622789264,-0.06418618559837341 +3,NVDA,2025-01-08,0.0017949293833225965,-0.0002140784345101565 +3,NVDA,2025-01-10,0.0017308532260358334,-0.030434735119342804 +3,TSLA,2024-03-25,0.0016709818737581372,0.010481683537364006 +3,TSLA,2024-03-26,0.0017367557156831026,0.02877728082239628 +3,TSLA,2024-03-27,0.001829344779253006,0.012084082700312138 +3,TSLA,2024-03-28,0.0019229594618082047,-0.0227219071239233 +3,TSLA,2024-04-01,0.0019564912654459476,-0.0032477283384650946 +3,TSLA,2024-04-02,0.0019922954961657524,-0.05026651918888092 +3,TSLA,2024-04-03,0.001870012958534062,0.010447544045746326 +3,TSLA,2024-04-04,0.0018859668634831905,0.01608326844871044 +3,TSLA,2024-04-05,0.001950076431967318,-0.036967433989048004 +3,TSLA,2024-04-08,0.0018922571325674653,0.04783676192164421 +3,TSLA,2024-04-09,0.0019901469349861145,0.02229560911655426 +3,TSLA,2024-04-10,0.0020715550053864717,-0.029373442754149437 +3,TSLA,2024-04-11,0.0020142458379268646,0.016399556770920753 +3,TSLA,2024-04-12,0.002060088561847806,-0.020541749894618988 +3,TSLA,2024-04-15,0.0020191108342260122,-0.05757465958595276 +3,TSLA,2024-04-16,0.001852197339758277,-0.027435068041086197 +3,TSLA,2024-04-17,0.0017853806493803859,-0.010622084140777588 +3,TSLA,2024-04-18,0.001698221080005169,-0.03615564852952957 +3,TSLA,2024-04-19,0.0015810972545295954,-0.01939578354358673 +3,TSLA,2024-04-22,0.0014509418979287148,-0.03459355607628822 +3,TSLA,2024-04-23,0.0013510980643332005,0.01834522746503353 +3,TSLA,2024-04-24,0.0013739758869633079,0.1138741597533226 +3,TSLA,2024-04-25,0.001584445359185338,0.04845814406871796 +3,TSLA,2024-04-26,0.0017593082739040256,-0.01116801518946886 +3,TSLA,2024-04-29,0.00187220040243119,0.1424272358417511 +3,TSLA,2024-04-30,0.0020215658005326986,-0.057100843638181686 +3,TSLA,2024-05-01,0.002101232297718525,-0.01811370626091957 +3,TSLA,2024-05-02,0.0021199751645326614,0.00011105007433798164 +3,TSLA,2024-05-03,0.0020907639991492033,0.006533843465149403 +3,TSLA,2024-05-06,0.0020790626294910908,0.01951143704354763 +3,TSLA,2024-05-07,0.002097350312396884,-0.038342103362083435 +3,TSLA,2024-05-08,0.0020276675932109356,-0.01753085106611252 +3,TSLA,2024-05-09,0.0020064832642674446,-0.015864649787545204 +3,TSLA,2024-05-10,0.0020059298258274794,-0.020562350749969482 +3,TSLA,2024-05-13,0.0019681404810398817,0.02009703405201435 +3,TSLA,2024-05-14,0.0019938857294619083,0.032397542148828506 +3,TSLA,2024-05-15,0.002071821829304099,-0.02025441825389862 +3,TSLA,2024-05-16,0.0020859495270997286,0.0048733907751739025 +3,TSLA,2024-05-17,0.002096073469147086,0.014874021522700787 +3,TSLA,2024-05-20,0.002187249483540654,-0.014245067723095417 +3,TSLA,2024-05-21,0.0022195056080818176,0.06446711719036102 +3,TSLA,2024-05-22,0.002339243656024337,-0.03539954125881195 +3,TSLA,2024-05-23,0.0023262519389390945,-0.03600781783461571 +3,TSLA,2024-05-24,0.002270284341648221,0.03116576001048088 +3,TSLA,2024-05-28,0.0023179021663963795,-0.01398941595107317 +3,TSLA,2024-05-29,0.0022939136251807213,-0.0031733328942209482 +3,TSLA,2024-05-30,0.0022866218350827694,0.0146489217877388 +3,TSLA,2024-05-31,0.0023392564617097378,-0.003978997468948364 +3,TSLA,2024-06-03,0.0023424543906003237,-0.010102570988237858 +3,TSLA,2024-06-04,0.0023296931758522987,-0.008659480139613152 +3,TSLA,2024-06-05,0.0022940391208976507,0.0013151257298886776 +3,TSLA,2024-06-06,0.0022930079139769077,0.016660453751683235 +3,TSLA,2024-06-07,0.002340540522709489,-0.002588526112958789 +3,TSLA,2024-06-10,0.002334070857614279,-0.0210102666169405 +3,TSLA,2024-06-11,0.0023031688760966063,-0.018174340948462486 +3,TSLA,2024-06-12,0.0022846569772809744,0.03811347857117653 +3,TSLA,2024-06-13,0.002397140022367239,0.028799010440707207 +3,TSLA,2024-06-14,0.002406659536063671,-0.024746084585785866 +3,TSLA,2024-06-17,0.002365668537095189,0.05161910876631737 +3,TSLA,2024-06-18,0.002471292857080698,-0.013860021717846394 +3,TSLA,2024-06-20,0.0024771273601800203,-0.01795748993754387 +3,TSLA,2024-06-21,0.0024435545783489943,0.007899471558630466 +3,TSLA,2024-06-24,0.002459216397255659,-0.002352322917431593 +3,TSLA,2024-06-25,0.0024809481110423803,0.02579011395573616 +3,TSLA,2024-06-26,0.002524878131225705,0.047022055834531784 +3,TSLA,2024-06-27,0.0025623589754104614,0.005332819651812315 +3,TSLA,2024-06-28,0.0025820210576057434,0.0023273814003914595 +3,TSLA,2024-07-01,0.0025559745263308287,0.05877983197569847 +3,TSLA,2024-07-02,0.002537661697715521,0.09710194915533066 +3,TSLA,2024-07-03,0.0025383075699210167,0.06337305158376694 +3,TSLA,2024-07-05,0.0025002630427479744,0.020606882870197296 +3,TSLA,2024-07-08,0.002439763629809022,0.005629790015518665 +3,TSLA,2024-07-09,0.002321176929399371,0.036450885236263275 +3,TSLA,2024-07-10,0.0022507316898554564,0.0035389719996601343 +3,TSLA,2024-07-11,0.0021949331276118755,-0.08822077512741089 +3,TSLA,2024-07-12,0.0019822034519165754,0.029434315860271454 +3,TSLA,2024-07-15,0.0019007499795407057,0.01760982908308506 +3,TSLA,2024-07-16,0.0018865079618990421,0.015396997332572937 +3,TSLA,2024-07-17,0.0019498341716825962,-0.0319196991622448 +3,TSLA,2024-07-18,0.0018446078756824136,0.0029333021957427263 +3,TSLA,2024-07-19,0.0017812525620684028,-0.041076138615608215 +3,TSLA,2024-07-22,0.0016219319077208638,0.05018271878361702 +3,TSLA,2024-07-23,0.0017600468127056956,-0.02060764841735363 +3,TSLA,2024-07-24,0.0017245883354917169,-0.13164293766021729 +3,TSLA,2024-07-25,0.001340752001851797,0.0195311289280653 +3,TSLA,2024-07-26,0.0012111518299207091,-0.002045209053903818 +3,TSLA,2024-07-29,0.0012608931865543127,0.05445028096437454 +3,TSLA,2024-07-30,0.0013588961446657777,-0.04170208051800728 +3,TSLA,2024-07-31,0.0014321579365059733,0.04157282039523125 +3,TSLA,2024-08-01,0.001600838266313076,-0.06778709590435028 +3,TSLA,2024-08-02,0.0013926567044109106,-0.04330171272158623 +3,TSLA,2024-08-05,0.0012945180060341954,-0.04324861988425255 +3,TSLA,2024-08-06,0.0011278899619355798,0.008810602128505707 +3,TSLA,2024-08-07,0.0010172172915190458,-0.04526768997311592 +3,TSLA,2024-08-08,0.0008414986659772694,0.03625589981675148 +3,TSLA,2024-08-09,0.0008713784045539796,0.00581690389662981 +3,TSLA,2024-08-12,0.000903337262570858,-0.012629388831555843 +3,TSLA,2024-08-13,0.0009359808173030615,0.05103246867656708 +3,TSLA,2024-08-14,0.0011287557426840067,-0.031526751816272736 +3,TSLA,2024-08-15,0.0011792322620749474,0.06143631041049957 +3,TSLA,2024-08-16,0.001369113801047206,0.009203782305121422 +3,TSLA,2024-08-19,0.0015217707259580493,0.030081596225500107 +3,TSLA,2024-08-20,0.0016687872121110559,-0.007300267461687326 +3,TSLA,2024-08-21,0.001786142704077065,0.00976670440286398 +3,TSLA,2024-08-22,0.0019310350762680173,-0.05813634395599365 +3,TSLA,2024-08-23,0.0018539008451625705,0.04483558610081673 +3,TSLA,2024-08-26,0.001974425045773387,-0.03280344232916832 +3,TSLA,2024-08-27,0.0018733739852905273,-0.0189390629529953 +3,TSLA,2024-08-28,0.0018062398303300142,-0.016676723957061768 +3,TSLA,2024-08-29,0.0016860004980117083,0.0025726237799972296 +3,TSLA,2024-08-30,0.0016850276151672006,0.03725543990731239 +3,TSLA,2024-09-03,0.0017777838511392474,-0.016529275104403496 +3,TSLA,2024-09-04,0.0017999674892053008,0.040981508791446686 +3,TSLA,2024-09-05,0.0019492711871862411,0.047876015305519104 +3,TSLA,2024-09-06,0.002092067152261734,-0.08824048191308975 +3,TSLA,2024-09-09,0.001888758153654635,0.025949973613023758 +3,TSLA,2024-09-10,0.0019102173391729593,0.044759273529052734 +3,TSLA,2024-09-11,0.0020459850784391165,0.008628742769360542 +3,TSLA,2024-09-12,0.002117871306836605,0.0073372065089643 +3,TSLA,2024-09-13,0.00215002428740263,0.002086485270410776 +3,TSLA,2024-09-16,0.0021564187481999397,-0.01535897608846426 +3,TSLA,2024-09-17,0.0021320567466318607,0.004794890061020851 +3,TSLA,2024-09-18,0.002112995833158493,-0.0029445961117744446 +3,TSLA,2024-09-19,0.002095072064548731,0.07100962102413177 +3,TSLA,2024-09-20,0.0021517793647944927,-0.02351975254714489 +3,TSLA,2024-09-23,0.002105413470417261,0.048140376806259155 +3,TSLA,2024-09-24,0.0021422244608402252,0.016935793682932854 +3,TSLA,2024-09-25,0.0021424884907901287,0.010757149197161198 +3,TSLA,2024-09-26,0.002108038403093815,-0.010953821241855621 +3,TSLA,2024-09-27,0.002076344797387719,0.024249227717518806 +3,TSLA,2024-09-30,0.0020972397178411484,0.004482044838368893 +3,TSLA,2024-10-01,0.002074992284178734,-0.013894251547753811 +3,TSLA,2024-10-02,0.002004055306315422,-0.035503827035427094 +3,TSLA,2024-10-03,0.0018739969236776233,-0.034148067235946655 +3,TSLA,2024-10-04,0.0017528812168166041,0.0383957102894783 +3,TSLA,2024-10-07,0.0018433664226904511,-0.03768957778811455 +3,TSLA,2024-10-08,0.001772532588802278,0.015124010853469372 +3,TSLA,2024-10-09,0.001794563140720129,-0.014210915192961693 +3,TSLA,2024-10-10,0.001736837555654347,-0.009503629989922047 +3,TSLA,2024-10-11,0.0017509242752566934,-0.0919235423207283 +3,TSLA,2024-10-14,0.0016318939160555601,0.006224848795682192 +3,TSLA,2024-10-15,0.0015768687007948756,0.001869048224762082 +3,TSLA,2024-10-16,0.0015950106317177415,0.007983687333762646 +3,TSLA,2024-10-17,0.0016187200089916587,-0.0019899713806807995 +3,TSLA,2024-10-18,0.0016786718042567372,-0.0008605378097854555 +3,TSLA,2024-10-21,0.0017269030213356018,-0.008417707867920399 +3,TSLA,2024-10-22,0.0017269810196012259,-0.0040291473269462585 +3,TSLA,2024-10-23,0.001735338126309216,-0.020018311217427254 +3,TSLA,2024-10-24,0.0016751217190176249,0.198186993598938 +3,TSLA,2024-10-25,0.0019378636498004198,0.03289133310317993 +3,TSLA,2024-10-28,0.002120153047144413,-0.02512824535369873 +3,TSLA,2024-10-29,0.0022119716741144657,-0.011455485597252846 +3,TSLA,2024-10-30,0.0022441840264946222,-0.00761990062892437 +3,TSLA,2024-10-31,0.00224266666918993,-0.030353065580129623 +3,TSLA,2024-11-01,0.0021660556085407734,-0.003488207468762994 +3,TSLA,2024-11-04,0.0021504447795450687,-0.024969778954982758 +3,TSLA,2024-11-05,0.0021382556296885014,0.034801628440618515 +3,TSLA,2024-11-06,0.0021967533975839615,0.13759465515613556 +3,TSLA,2024-11-07,0.0022203847765922546,0.028630012646317482 +3,TSLA,2024-11-08,0.002286785515025258,0.07869717478752136 +3,TSLA,2024-11-11,0.002224523574113846,0.08580689877271652 +3,TSLA,2024-11-12,0.0021734493784606457,-0.06342678517103195 +3,TSLA,2024-11-13,0.0020272189285606146,0.00531326700001955 +3,TSLA,2024-11-14,0.0019365756306797266,-0.059448134154081345 +3,TSLA,2024-11-15,0.0016899973852559924,0.03019697219133377 +3,TSLA,2024-11-18,0.0016837592702358961,0.05466435104608536 +3,TSLA,2024-11-19,0.0017921413527801633,0.021205952391028404 +3,TSLA,2024-11-20,0.0018663608934730291,-0.011540326289832592 +3,TSLA,2024-11-21,0.001899821450933814,-0.007012172602117062 +3,TSLA,2024-11-22,0.0018821869743987918,0.037334538996219635 +3,TSLA,2024-11-25,0.0019031683914363384,-0.040430888533592224 +3,TSLA,2024-11-26,0.0018042291048914194,-0.0010637551313266158 +3,TSLA,2024-11-27,0.0017638239078223705,-0.01591402105987072 +3,TSLA,2024-11-29,0.0016928835539147258,0.03619593754410744 +3,TSLA,2024-12-02,0.0017759312177076936,0.03397975116968155 +3,TSLA,2024-12-03,0.001907729427330196,-0.016005713492631912 +3,TSLA,2024-12-04,0.0020076893270015717,0.018355289474129677 +3,TSLA,2024-12-05,0.002153118373826146,0.0317862331867218 +3,TSLA,2024-12-06,0.0023195366375148296,0.0520210899412632 +3,TSLA,2024-12-09,0.002366695087403059,0.0014634148683398962 +3,TSLA,2024-12-10,0.0023510458413511515,0.028328310698270798 +3,TSLA,2024-12-11,0.0023394040763378143,0.05761135369539261 +3,TSLA,2024-12-12,0.0023234360851347446,-0.01582716777920723 +3,TSLA,2024-12-13,0.002252366626635194,0.04244900122284889 +3,TSLA,2024-12-16,0.0022570150904357433,0.059600573033094406 +3,TSLA,2024-12-17,0.0022455183789134026,0.03572413697838783 +3,TSLA,2024-12-18,0.0022150645963847637,-0.08642421662807465 +3,TSLA,2024-12-19,0.0018456036923453212,-0.009038042277097702 +3,TSLA,2024-12-20,0.001601704629138112,-0.0352567695081234 +3,TSLA,2024-12-23,0.0015076857525855303,0.02240426279604435 +3,TSLA,2024-12-24,0.0014636183623224497,0.0709911659359932 +3,TSLA,2024-12-26,0.0016035522567108274,-0.017787253484129906 +3,TSLA,2024-12-27,0.0016392309917137027,-0.05074525997042656 +3,TSLA,2024-12-30,0.0014814883470535278,-0.03356928750872612 +3,TSLA,2024-12-31,0.0012539413291960955,-0.033050209283828735 +3,TSLA,2025-01-02,0.0011637465795502067,-0.06274403631687164 +3,TSLA,2025-01-03,0.001077729742974043,0.0789550393819809 +3,TSLA,2025-01-06,0.0011646868661046028,0.001485070795752108 +3,TSLA,2025-01-07,0.0013274677330628037,-0.04145067185163498 +3,TSLA,2025-01-08,0.0013545291731134057,0.0014697002479806542 +3,TSLA,2025-01-10,0.001374647719785571,-0.0005065652076154947 +3,GOOGL,2024-03-25,0.0010967582929879427,-0.004653645679354668 +3,GOOGL,2024-03-26,0.0010888536926358938,0.003989856690168381 +3,GOOGL,2024-03-27,0.0010778550058603287,0.0013267287285998464 +3,GOOGL,2024-03-28,0.0010803270852193236,0.0003974512219429016 +3,GOOGL,2024-04-01,0.0010785071644932032,0.02976561337709427 +3,GOOGL,2024-04-02,0.0010982340900227427,-0.0059993695467710495 +3,GOOGL,2024-04-03,0.0010966656263917685,0.002326524816453457 +3,GOOGL,2024-04-04,0.0011114281369373202,-0.02874642238020897 +3,GOOGL,2024-04-05,0.0010208000894635916,0.013002179563045502 +3,GOOGL,2024-04-08,0.0010136761702597141,0.015292414464056492 +3,GOOGL,2024-04-09,0.0010511964792385697,0.011237879283726215 +3,GOOGL,2024-04-10,0.0010609464952722192,-0.0029416843317449093 +3,GOOGL,2024-04-11,0.001040972420014441,0.020726539194583893 +3,GOOGL,2024-04-12,0.001085995347239077,-0.010594907216727734 +3,GOOGL,2024-04-15,0.001038934919051826,-0.018363211303949356 +3,GOOGL,2024-04-16,0.0009765930008143187,-0.0029748857486993074 +3,GOOGL,2024-04-17,0.0009466343908570707,0.006906130816787481 +3,GOOGL,2024-04-18,0.0009471452212892473,0.003467380767688155 +3,GOOGL,2024-04-19,0.0009560808539390564,-0.012383341789245605 +3,GOOGL,2024-04-22,0.000920376623980701,0.014112386852502823 +3,GOOGL,2024-04-23,0.0009491095552220941,0.012590003199875355 +3,GOOGL,2024-04-24,0.0010120320366695523,0.005482209846377373 +3,GOOGL,2024-04-25,0.0010391483083367348,-0.019865496084094048 +3,GOOGL,2024-04-26,0.0009989100508391857,0.09734784811735153 +3,GOOGL,2024-04-29,0.00106029212474823,-0.034312933683395386 +3,GOOGL,2024-04-30,0.001014677225612104,-0.02049129270017147 +3,GOOGL,2024-05-01,0.0009365324513055384,0.0066127353347837925 +3,GOOGL,2024-05-02,0.0009405392338521779,0.01670340821146965 +3,GOOGL,2024-05-03,0.0009709146106615663,0.0037143025547266006 +3,GOOGL,2024-05-06,0.0009844765299931169,0.005129171069711447 +3,GOOGL,2024-05-07,0.0009983489289879799,0.018565258011221886 +3,GOOGL,2024-05-08,0.001017852104268968,-0.010979659855365753 +3,GOOGL,2024-05-09,0.0010056431638076901,0.0034183321986347437 +3,GOOGL,2024-05-10,0.00101692124735564,-0.007737591862678528 +3,GOOGL,2024-05-13,0.0009957007132470608,0.00290117715485394 +3,GOOGL,2024-05-14,0.0010067940456792712,0.007069757673889399 +3,GOOGL,2024-05-15,0.0010343975154682994,0.012658750638365746 +3,GOOGL,2024-05-16,0.0010557918576523662,0.00963393785059452 +3,GOOGL,2024-05-17,0.0010687983594834805,0.010735793970525265 +3,GOOGL,2024-05-20,0.0010909808333963156,0.0048726690001785755 +3,GOOGL,2024-05-21,0.0010926692048087716,0.005243037361651659 +3,GOOGL,2024-05-22,0.001104537514038384,-0.00829989742487669 +3,GOOGL,2024-05-23,0.0010948404669761658,-0.01617494970560074 +3,GOOGL,2024-05-24,0.0010715419193729758,0.00826314091682434 +3,GOOGL,2024-05-28,0.001074143685400486,0.008025262504816055 +3,GOOGL,2024-05-29,0.0010777004063129425,-0.0028384923934936523 +3,GOOGL,2024-05-30,0.0010798517614603043,-0.021781902760267258 +3,GOOGL,2024-05-31,0.0010631898185238242,0.0022633939515799284 +3,GOOGL,2024-06-03,0.0010822168551385403,0.0038765177596360445 +3,GOOGL,2024-06-04,0.0010961778461933136,0.003573974594473839 +3,GOOGL,2024-06-05,0.0011082565179094672,0.009278401732444763 +3,GOOGL,2024-06-06,0.0011396304471418262,0.007497037760913372 +3,GOOGL,2024-06-07,0.0011698352172970772,-0.012927728705108166 +3,GOOGL,2024-06-10,0.001148979994468391,0.0042947749607264996 +3,GOOGL,2024-06-11,0.0011718067107722163,0.009157363325357437 +3,GOOGL,2024-06-12,0.0011967058526352048,0.006602511275559664 +3,GOOGL,2024-06-13,0.0012048321077600121,-0.014903075993061066 +3,GOOGL,2024-06-14,0.00117836007848382,0.00926254503428936 +3,GOOGL,2024-06-17,0.0011989898048341274,0.002542285481467843 +3,GOOGL,2024-06-18,0.0012117607984691858,-0.012204683385789394 +3,GOOGL,2024-06-20,0.0011984321754425764,0.006887154653668404 +3,GOOGL,2024-06-21,0.0012124096974730492,0.0187120009213686 +3,GOOGL,2024-06-24,0.0012364143040031195,-0.0022851501125842333 +3,GOOGL,2024-06-25,0.001248259679414332,0.026484759524464607 +3,GOOGL,2024-06-26,0.0012570777907967567,-0.0008154016686603427 +3,GOOGL,2024-06-27,0.0012538734590634704,0.008286230266094208 +3,GOOGL,2024-06-28,0.0012598733883351088,-0.01773926615715027 +3,GOOGL,2024-07-01,0.001237649703398347,0.004601066466420889 +3,GOOGL,2024-07-02,0.00124046066775918,0.012220881879329681 +3,GOOGL,2024-07-03,0.001254690927453339,0.0031260959804058075 +3,GOOGL,2024-07-05,0.0012618765467777848,0.025398600846529007 +3,GOOGL,2024-07-08,0.001272103050723672,-0.008271402679383755 +3,GOOGL,2024-07-09,0.0012591229751706123,-0.00026448414428159595 +3,GOOGL,2024-07-10,0.0012533796252682805,0.011574285104870796 +3,GOOGL,2024-07-11,0.0012634359300136566,-0.029783157631754875 +3,GOOGL,2024-07-12,0.0012269640574231744,-0.0026981811970472336 +3,GOOGL,2024-07-15,0.0012082882458344102,0.00785799976438284 +3,GOOGL,2024-07-16,0.0012146364897489548,-0.014091274701058865 +3,GOOGL,2024-07-17,0.00117651023901999,-0.015893343836069107 +3,GOOGL,2024-07-18,0.0010871553095057607,-0.018566889688372612 +3,GOOGL,2024-07-19,0.0009515238925814629,-0.00016893101565074176 +3,GOOGL,2024-07-22,0.0009052740642800927,0.022320199757814407 +3,GOOGL,2024-07-23,0.000948642729781568,0.0006602234789170325 +3,GOOGL,2024-07-24,0.0009873637463897467,-0.051701657474040985 +3,GOOGL,2024-07-25,0.0007558109355159104,-0.03148135915398598 +3,GOOGL,2024-07-26,0.0005998304113745689,-0.001675272942520678 +3,GOOGL,2024-07-29,0.000509456847794354,0.015036146156489849 +3,GOOGL,2024-07-30,0.000467658624984324,0.004472850821912289 +3,GOOGL,2024-07-31,0.00047903115046210587,0.007313594687730074 +3,GOOGL,2024-08-01,0.0005062794662080705,-0.004557419568300247 +3,GOOGL,2024-08-02,0.000520532310474664,-0.02430301532149315 +3,GOOGL,2024-08-05,0.00043321429984644055,-0.04548070579767227 +3,GOOGL,2024-08-06,0.00012210485874675214,-0.006046582944691181 +3,GOOGL,2024-08-07,7.814479613443837e-05,0.004098225850611925 +3,GOOGL,2024-08-08,9.051665983861312e-05,0.019254565238952637 +3,GOOGL,2024-08-09,0.0001232670620083809,0.010070642456412315 +3,GOOGL,2024-08-12,0.00016396251157857478,-0.008467189967632294 +3,GOOGL,2024-08-13,0.0002408905711490661,0.011456741951406002 +3,GOOGL,2024-08-14,0.0003166140813846141,-0.023358019068837166 +3,GOOGL,2024-08-15,0.0003368883626535535,0.005782327614724636 +3,GOOGL,2024-08-16,0.0003718875232152641,0.010238755494356155 +3,GOOGL,2024-08-19,0.0004380292375572026,0.02251102589070797 +3,GOOGL,2024-08-20,0.0005423197872005403,0.0030552102252840996 +3,GOOGL,2024-08-21,0.000620679056737572,-0.007987132295966148 +3,GOOGL,2024-08-22,0.0006740319076925516,-0.012437611818313599 +3,GOOGL,2024-08-23,0.000696913106366992,0.011049848981201649 +3,GOOGL,2024-08-26,0.0007358194561675191,0.0032551116310060024 +3,GOOGL,2024-08-27,0.0007657195092178881,-0.008946971967816353 +3,GOOGL,2024-08-28,0.0007929623243398964,-0.011174646206200123 +3,GOOGL,2024-08-29,0.0007613504421897233,-0.00659214798361063 +3,GOOGL,2024-08-30,0.0007386574288830161,0.009841362945735455 +3,GOOGL,2024-09-03,0.0007654359214939177,-0.03754251077771187 +3,GOOGL,2024-09-04,0.0006529095699079335,-0.005799759645015001 +3,GOOGL,2024-09-05,0.0005925293080508709,0.005036900285631418 +3,GOOGL,2024-09-06,0.0005784794921055436,-0.0410233736038208 +3,GOOGL,2024-09-09,0.00033094282844103873,-0.013425822369754314 +3,GOOGL,2024-09-10,0.0002535928215365857,-0.00033627706579864025 +3,GOOGL,2024-09-11,0.00021057405683677644,0.016677049919962883 +3,GOOGL,2024-09-12,0.00022277097741607577,0.023084180429577827 +3,GOOGL,2024-09-13,0.0002757131296675652,0.01774837076663971 +3,GOOGL,2024-09-16,0.0003856919938698411,0.00380320125259459 +3,GOOGL,2024-09-17,0.00046993792057037354,0.007940122857689857 +3,GOOGL,2024-09-18,0.000540038279723376,0.0030709269922226667 +3,GOOGL,2024-09-19,0.0005985182942822576,0.014474401250481606 +3,GOOGL,2024-09-20,0.0006504338816739619,0.008903211914002895 +3,GOOGL,2024-09-23,0.0006972530973143876,-0.010693293064832687 +3,GOOGL,2024-09-24,0.0007321226876229048,0.0027148618828505278 +3,GOOGL,2024-09-25,0.0007697246037423611,-0.004941573366522789 +3,GOOGL,2024-09-26,0.0007740323198959231,0.0076490845531225204 +3,GOOGL,2024-09-27,0.0007997063803486526,0.0074690780602395535 +3,GOOGL,2024-09-30,0.0008142604492604733,0.01152230054140091 +3,GOOGL,2024-10-01,0.0008255300926975906,0.006850371602922678 +3,GOOGL,2024-10-02,0.0008537449757568538,-0.00678991200402379 +3,GOOGL,2024-10-03,0.000848740222863853,0.0 +3,GOOGL,2024-10-04,0.0008497503586113453,0.007208692841231823 +3,GOOGL,2024-10-07,0.0008760650525800884,-0.024725347757339478 +3,GOOGL,2024-10-08,0.000812704034615308,0.008553216233849525 +3,GOOGL,2024-10-09,0.000802066526375711,-0.015449008904397488 +3,GOOGL,2024-10-10,0.0007769684889353812,0.0013582210522145033 +3,GOOGL,2024-10-11,0.0007878821925260127,0.007131548132747412 +3,GOOGL,2024-10-14,0.0008037723018787801,0.010481524281203747 +3,GOOGL,2024-10-15,0.0008253595442511141,0.003026507329195738 +3,GOOGL,2024-10-16,0.0008488849271088839,-0.0018149351235479116 +3,GOOGL,2024-10-17,0.0008549757185392082,-0.013593902811408043 +3,GOOGL,2024-10-18,0.0008513834909535944,0.003002893179655075 +3,GOOGL,2024-10-21,0.0008666455396451056,0.0039696344174444675 +3,GOOGL,2024-10-22,0.0008753784350119531,0.006500404793769121 +3,GOOGL,2024-10-23,0.0008996908436529338,-0.014394174329936504 +3,GOOGL,2024-10-24,0.0008787860861048102,-0.0003685456467792392 +3,GOOGL,2024-10-25,0.0008882966358214617,0.015549647621810436 +3,GOOGL,2024-10-28,0.0009281962411478162,0.008735145442187786 +3,GOOGL,2024-10-29,0.0009597932803444564,0.017598580569028854 +3,GOOGL,2024-10-30,0.0009947813814505935,0.027781039476394653 +3,GOOGL,2024-10-31,0.0009972125990316272,-0.01938888430595398 +3,GOOGL,2024-11-01,0.0009696743218228221,0.0010514244204387069 +3,GOOGL,2024-11-04,0.000958687742240727,-0.012040137313306332 +3,GOOGL,2024-11-05,0.0009637758485041559,0.002950081368908286 +3,GOOGL,2024-11-06,0.0009745904826559126,0.039109669625759125 +3,GOOGL,2024-11-07,0.0009574826108291745,0.023737214505672455 +3,GOOGL,2024-11-08,0.0010043684160336852,-0.013366949744522572 +3,GOOGL,2024-11-11,0.0009775938233360648,0.011151609942317009 +3,GOOGL,2024-11-12,0.0009826197056099772,0.007017230149358511 +3,GOOGL,2024-11-13,0.0009872830705717206,-0.015201479196548462 +3,GOOGL,2024-11-14,0.0009522718610242009,-0.018620343878865242 +3,GOOGL,2024-11-15,0.0008973721996881068,-0.017755569890141487 +3,GOOGL,2024-11-18,0.0008131925715133548,0.01615939289331436 +3,GOOGL,2024-11-19,0.0008334594313055277,0.015958884730935097 +3,GOOGL,2024-11-20,0.0008695154683664441,-0.012087163515388966 +3,GOOGL,2024-11-21,0.0008522832649759948,-0.04861118271946907 +3,GOOGL,2024-11-22,0.000751666899304837,-0.01726931892335415 +3,GOOGL,2024-11-25,0.00063203094759956,0.017388490960001945 +3,GOOGL,2024-11-26,0.0006718238582834601,0.008730174973607063 +3,GOOGL,2024-11-27,0.0007358180591836572,0.0006502785254269838 +3,GOOGL,2024-11-29,0.0007857745513319969,-0.0016560291405767202 +3,GOOGL,2024-12-02,0.0008128102053888142,0.014922239817678928 +3,GOOGL,2024-12-03,0.0008439852390438318,-0.0008751476416364312 +3,GOOGL,2024-12-04,0.000880060251802206,0.017529580742120743 +3,GOOGL,2024-12-05,0.000931587943341583,-0.009970883838832378 +3,GOOGL,2024-12-06,0.0009994301944971085,0.011919030919671059 +3,GOOGL,2024-12-09,0.001046572346240282,0.004915796685963869 +3,GOOGL,2024-12-10,0.0010816078865900636,0.05437641218304634 +3,GOOGL,2024-12-11,0.001113441656343639,0.053774360567331314 +3,GOOGL,2024-12-12,0.0011237799189984798,-0.01776168867945671 +3,GOOGL,2024-12-13,0.0011105129960924387,-0.011210736818611622 +3,GOOGL,2024-12-16,0.0010837872978299856,0.035400014370679855 +3,GOOGL,2024-12-17,0.0011007650755345821,-0.006325309164822102 +3,GOOGL,2024-12-18,0.0010590276215225458,-0.03658363223075867 +3,GOOGL,2024-12-19,0.0009244032553397119,0.0005835714982822537 +3,GOOGL,2024-12-20,0.0008427135762758553,0.015266761183738708 +3,GOOGL,2024-12-23,0.0008413299219682813,0.016682641580700874 +3,GOOGL,2024-12-24,0.0008352125296369195,0.007575304247438908 +3,GOOGL,2024-12-26,0.0008631075033918023,-0.0026038363575935364 +3,GOOGL,2024-12-27,0.0008815102046355605,-0.014625933952629566 +3,GOOGL,2024-12-30,0.0008514164946973324,-0.007916699163615704 +3,GOOGL,2024-12-31,0.0007896643946878612,-0.010196108371019363 +3,GOOGL,2025-01-02,0.0007060632342472672,0.0006863906164653599 +3,GOOGL,2025-01-03,0.0007047882536426187,0.012381516396999359 +3,GOOGL,2025-01-06,0.0007862446364015341,0.02614258974790573 +3,GOOGL,2025-01-07,0.0008845720440149307,-0.007034326437860727 +3,GOOGL,2025-01-08,0.0009375744848512113,-0.007908831350505352 +3,GOOGL,2025-01-10,0.0009825066663324833,-0.009896681644022465 +3,AMZN,2024-03-25,0.0013068849220871925,0.004685220308601856 +3,AMZN,2024-03-26,0.0013355468399822712,-0.007876936346292496 +3,AMZN,2024-03-27,0.0013079717755317688,0.008544428274035454 +3,AMZN,2024-03-28,0.001327333739027381,0.0030537934508174658 +3,AMZN,2024-04-01,0.00133504590485245,0.0032655145041644573 +3,AMZN,2024-04-02,0.0013336503179743886,-0.0015484091127291322 +3,AMZN,2024-04-03,0.0013357471907511353,0.009474051184952259 +3,AMZN,2024-04-04,0.001367300865240395,-0.013300069607794285 +3,AMZN,2024-04-05,0.0013039418263360858,0.02777731791138649 +3,AMZN,2024-04-08,0.0013374264817684889,0.0006481668096967041 +3,AMZN,2024-04-09,0.0013384902849793434,0.002588556380942464 +3,AMZN,2024-04-10,0.001342945033684373,0.0015069093788042665 +3,AMZN,2024-04-11,0.0013382951728999615,0.01653374172747135 +3,AMZN,2024-04-12,0.0013618578668683767,-0.015566164627671242 +3,AMZN,2024-04-15,0.0012945999624207616,-0.013577002100646496 +3,AMZN,2024-04-16,0.0011779536725953221,-0.0016350785735994577 +3,AMZN,2024-04-17,0.0011095236986875534,-0.011190509423613548 +3,AMZN,2024-04-18,0.0009789059404283762,-0.011428681202232838 +3,AMZN,2024-04-19,0.0008889262098819017,-0.025944627821445465 +3,AMZN,2024-04-22,0.0007786836940795183,0.014778820797801018 +3,AMZN,2024-04-23,0.0008027395233511925,0.01294968742877245 +3,AMZN,2024-04-24,0.0009042916353791952,-0.016567345708608627 +3,AMZN,2024-04-25,0.0008830936858430505,-0.016673704609274864 +3,AMZN,2024-04-26,0.0008652374381199479,0.03368654474616051 +3,AMZN,2024-04-29,0.0009521086467429996,0.00743256788700819 +3,AMZN,2024-04-30,0.0010280436836183071,-0.033490076661109924 +3,AMZN,2024-05-01,0.0009138273308053613,0.022599831223487854 +3,AMZN,2024-05-02,0.0009806470479816198,0.03145536407828331 +3,AMZN,2024-05-03,0.0010783392935991287,0.008033933117985725 +3,AMZN,2024-05-06,0.0011537015670910478,0.01328333094716072 +3,AMZN,2024-05-07,0.0012013696832582355,0.00031790154753252864 +3,AMZN,2024-05-08,0.001200746395625174,-0.004034374840557575 +3,AMZN,2024-05-09,0.0012028904166072607,0.007947062142193317 +3,AMZN,2024-05-10,0.0012216957984492183,-0.010716874152421951 +3,AMZN,2024-05-13,0.001192575553432107,-0.004865607246756554 +3,AMZN,2024-05-14,0.0011770897544920444,0.002676374511793256 +3,AMZN,2024-05-15,0.001188000082038343,-0.005789979360997677 +3,AMZN,2024-05-16,0.0011732198763638735,-0.012770048342645168 +3,AMZN,2024-05-17,0.0011137359542772174,0.005809980444610119 +3,AMZN,2024-05-20,0.0011455405037850142,-0.006300279404968023 +3,AMZN,2024-05-21,0.0011270121904090047,-0.0021271349396556616 +3,AMZN,2024-05-22,0.0010912423022091389,-0.0001091460871975869 +3,AMZN,2024-05-23,0.00107165751978755,-0.011423056945204735 +3,AMZN,2024-05-24,0.000969499524217099,-0.0016583920223638415 +3,AMZN,2024-05-28,0.0009795399382710457,0.007715628948062658 +3,AMZN,2024-05-29,0.0010533948661759496,-0.0007138953078538179 +3,AMZN,2024-05-30,0.0011016594944521785,-0.014944634400308132 +3,AMZN,2024-05-31,0.001110563986003399,-0.016191070899367332 +3,AMZN,2024-06-03,0.0011316967429593205,0.01071093138307333 +3,AMZN,2024-06-04,0.0011977049289271235,0.005591604858636856 +3,AMZN,2024-06-05,0.0012357602827250957,0.010759365744888783 +3,AMZN,2024-06-06,0.0012718248181045055,0.02031303383409977 +3,AMZN,2024-06-07,0.0013195871142670512,-0.0037909438833594322 +3,AMZN,2024-06-10,0.0013319788267835975,0.014864526689052582 +3,AMZN,2024-06-11,0.0013664945727214217,0.0009083768236450851 +3,AMZN,2024-06-12,0.001383372931741178,-0.0018175796139985323 +3,AMZN,2024-06-13,0.0013949415879324079,-0.01650877855718136 +3,AMZN,2024-06-14,0.0013701884308829904,-0.0009251853334717453 +3,AMZN,2024-06-17,0.001370136276818812,0.0021755360066890717 +3,AMZN,2024-06-18,0.0013760016299784184,-0.00681442953646183 +3,AMZN,2024-06-20,0.001370609737932682,0.01783684827387333 +3,AMZN,2024-06-21,0.0013980244984850287,0.01588601991534233 +3,AMZN,2024-06-24,0.001420138869434595,-0.01873800717294216 +3,AMZN,2024-06-25,0.0014017432695254683,0.004140733741223812 +3,AMZN,2024-06-26,0.0013937782496213913,0.03827288746833801 +3,AMZN,2024-06-27,0.0014123782748356462,0.021663369610905647 +3,AMZN,2024-06-28,0.001418541418388486,-0.023524509742856026 +3,AMZN,2024-07-01,0.0013794469414278865,0.02023373916745186 +3,AMZN,2024-07-02,0.0013817142462357879,0.014098940417170525 +3,AMZN,2024-07-03,0.0013877381570637226,-0.012123208492994308 +3,AMZN,2024-07-05,0.0013678886462002993,0.012123208492994308 +3,AMZN,2024-07-08,0.0013770562363788486,-0.003556349780410528 +3,AMZN,2024-07-09,0.0013574421172961593,0.00025087452377192676 +3,AMZN,2024-07-10,0.0013546241680160165,0.0022548900451511145 +3,AMZN,2024-07-11,0.001354789244942367,-0.024010829627513885 +3,AMZN,2024-07-12,0.001306155463680625,-0.0028751755598932505 +3,AMZN,2024-07-15,0.0012767940061166883,-0.00914241187274456 +3,AMZN,2024-07-16,0.0012289370642974973,0.0015554679557681084 +3,AMZN,2024-07-17,0.001224795589223504,-0.02672431990504265 +3,AMZN,2024-07-18,0.0010461901547387242,-0.022493375465273857 +3,AMZN,2024-07-19,0.000872877542860806,-0.0033798280637711287 +3,AMZN,2024-07-22,0.0007801332394592464,-0.003172184806317091 +3,AMZN,2024-07-23,0.0007554471958428621,0.020924443379044533 +3,AMZN,2024-07-24,0.0008001388632692397,-0.03039119765162468 +3,AMZN,2024-07-25,0.0006999030010774732,-0.0054341694340109825 +3,AMZN,2024-07-26,0.000603778928052634,0.01462696772068739 +3,AMZN,2024-07-29,0.0006089287926442921,0.0038282624445855618 +3,AMZN,2024-07-30,0.000659574696328491,-0.008166388608515263 +3,AMZN,2024-07-31,0.0006652701995335519,0.02858959138393402 +3,AMZN,2024-08-01,0.0007814045529812574,-0.01568547636270523 +3,AMZN,2024-08-02,0.0007689485792070627,-0.09194762259721756 +3,AMZN,2024-08-05,0.0002651502436492592,-0.04183991998434067 +3,AMZN,2024-08-06,0.00017451128223910928,0.005635490640997887 +3,AMZN,2024-08-07,0.00017591743380762637,0.005174089688807726 +3,AMZN,2024-08-08,0.0001592744665686041,0.01844407431781292 +3,AMZN,2024-08-09,-4.71449238830246e-05,0.006852219812572002 +3,AMZN,2024-08-12,4.118020297028124e-05,-0.0008389728027395904 +3,AMZN,2024-08-13,9.806815069168806e-05,0.02035493031144142 +3,AMZN,2024-08-14,0.00011410308798076585,-0.0007639034884050488 +3,AMZN,2024-08-15,0.00020238700381014496,0.04309096559882164 +3,AMZN,2024-08-16,0.0003336530062370002,-0.0029888576827943325 +3,AMZN,2024-08-19,0.00046227211714722216,0.0065301042050123215 +3,AMZN,2024-08-20,0.0005612316308543086,0.0036964681930840015 +3,AMZN,2024-08-21,0.0006363004213199019,0.006852561607956886 +3,AMZN,2024-08-22,0.0006968665402382612,-0.022345392033457756 +3,AMZN,2024-08-23,0.0007268863264471292,0.005153271369636059 +3,AMZN,2024-08-26,0.0007768424111418426,-0.00873661506921053 +3,AMZN,2024-08-27,0.000771518680267036,-0.013654075562953949 +3,AMZN,2024-08-28,0.0007326480117626488,-0.013491667807102203 +3,AMZN,2024-08-29,0.000619183003436774,0.007698580157011747 +3,AMZN,2024-08-30,0.000659987039398402,0.03639672324061394 +3,AMZN,2024-09-03,0.0007537189521826804,-0.012685159221291542 +3,AMZN,2024-09-04,0.000816144747659564,-0.016706138849258423 +3,AMZN,2024-09-05,0.0008068344322964549,0.025968076661229134 +3,AMZN,2024-09-06,0.0008735592709854245,-0.03722371906042099 +3,AMZN,2024-09-09,0.0007870076806284487,0.023127388209104538 +3,AMZN,2024-09-10,0.0008321235072799027,0.023384692147374153 +3,AMZN,2024-09-11,0.0008818205096758902,0.027304144576191902 +3,AMZN,2024-09-12,0.0008989766356535256,0.013350735418498516 +3,AMZN,2024-09-13,0.0009122467017732561,-0.0027309691067785025 +3,AMZN,2024-09-16,0.0009392581414431334,-0.008616597391664982 +3,AMZN,2024-09-17,0.0009531118557788432,0.0107056749984622 +3,AMZN,2024-09-18,0.0009530035313218832,-0.0024109315127134323 +3,AMZN,2024-09-19,0.0009484395268373191,0.01828380674123764 +3,AMZN,2024-09-20,0.0009485350456088781,0.009070295840501785 +3,AMZN,2024-09-23,0.0009512306423857808,0.011829539202153683 +3,AMZN,2024-09-24,0.0009473695536144078,0.0004125507257413119 +3,AMZN,2024-09-25,0.0009481383021920919,-0.007400007452815771 +3,AMZN,2024-09-26,0.0009210067219100893,-0.007141186390072107 +3,AMZN,2024-09-27,0.0009189497795887291,-0.01682841032743454 +3,AMZN,2024-09-30,0.000870066462084651,-0.008763076737523079 +3,AMZN,2024-10-01,0.0008209098014049232,-0.006460997741669416 +3,AMZN,2024-10-02,0.0006920032319612801,-0.002000651555135846 +3,AMZN,2024-10-03,0.0006390887429006398,-0.015270736999809742 +3,AMZN,2024-10-04,0.0005740987253375351,0.024697907269001007 +3,AMZN,2024-10-07,0.0007041548960842192,-0.031093362718820572 +3,AMZN,2024-10-08,0.0006512104300782084,0.010563467629253864 +3,AMZN,2024-10-09,0.0006926234345883131,0.013319378718733788 +3,AMZN,2024-10-10,0.0007421262562274933,0.00796086061745882 +3,AMZN,2024-10-11,0.0007818193989805877,0.011559045873582363 +3,AMZN,2024-10-14,0.0008050346514210105,-0.006802098825573921 +3,AMZN,2024-10-15,0.0008145400788635015,0.0007995585328899324 +3,AMZN,2024-10-16,0.0008379550999961793,-0.00427147326990962 +3,AMZN,2024-10-17,0.000853330479003489,0.003418620675802231 +3,AMZN,2024-10-18,0.0008749148692004383,0.0077553060837090015 +3,AMZN,2024-10-21,0.0008922183187678456,0.0004232229257468134 +3,AMZN,2024-10-22,0.0009159267647191882,0.0033265051897615194 +3,AMZN,2024-10-23,0.0009429825004190207,-0.026656799018383026 +3,AMZN,2024-10-24,0.000912319403141737,0.009000563062727451 +3,AMZN,2024-10-25,0.0009350533946417272,0.007749681826680899 +3,AMZN,2024-10-28,0.000955544353928417,0.002976970747113228 +3,AMZN,2024-10-29,0.0009846002794802189,0.012868709862232208 +3,AMZN,2024-10-30,0.0010455368319526315,0.009907234460115433 +3,AMZN,2024-10-31,0.0010788216022774577,-0.03339535370469093 +3,AMZN,2024-11-01,0.0009964766213670373,0.060018524527549744 +3,AMZN,2024-11-04,0.001093172817490995,-0.010921822860836983 +3,AMZN,2024-11-05,0.0011368865380063653,0.01882266253232956 +3,AMZN,2024-11-06,0.001198051730170846,0.0373392291367054 +3,AMZN,2024-11-07,0.0011944131692871451,0.014192148111760616 +3,AMZN,2024-11-08,0.001225693617016077,-0.008942557498812675 +3,AMZN,2024-11-11,0.0011822136584669352,-0.006457525305449963 +3,AMZN,2024-11-12,0.001138758147135377,0.009958025068044662 +3,AMZN,2024-11-13,0.0011455982457846403,0.02453966997563839 +3,AMZN,2024-11-14,0.0011536943493410945,-0.012312812730669975 +3,AMZN,2024-11-15,0.0011155179236084223,-0.04284746199846268 +3,AMZN,2024-11-18,0.0009580891346558928,-0.0045015220530331135 +3,AMZN,2024-11-19,0.0008630824740976095,0.014324300922453403 +3,AMZN,2024-11-20,0.0008659335435368121,-0.008491035550832748 +3,AMZN,2024-11-21,0.0007560159428976476,-0.022430287674069405 +3,AMZN,2024-11-22,0.0006655227043665946,-0.006371752824634314 +3,AMZN,2024-11-25,0.0006406765314750373,0.02172854170203209 +3,AMZN,2024-11-26,0.0006887280032970011,0.03132358193397522 +3,AMZN,2024-11-27,0.0008539441623724997,-0.010251516476273537 +3,AMZN,2024-11-29,0.0009354828507639468,0.010395828634500504 +3,AMZN,2024-12-02,0.0010153435869142413,0.013473721221089363 +3,AMZN,2024-12-03,0.0010920738568529487,0.012872961349785328 +3,AMZN,2024-12-04,0.0011771575082093477,0.021872980520129204 +3,AMZN,2024-12-05,0.0012238204944878817,0.0108956852927804 +3,AMZN,2024-12-06,0.00125960074365139,0.02895772084593773 +3,AMZN,2024-12-09,0.0012656761100515723,-0.0041490281000733376 +3,AMZN,2024-12-10,0.0012391560012474656,-0.004654999356716871 +3,AMZN,2024-12-11,0.0011986774625256658,0.022930946201086044 +3,AMZN,2024-12-12,0.0011973053915426135,-0.005618085619062185 +3,AMZN,2024-12-13,0.0011642638128250837,-0.006616567727178335 +3,AMZN,2024-12-16,0.0011410982115194201,0.023763516917824745 +3,AMZN,2024-12-17,0.0012072352692484856,-0.0076711238361895084 +3,AMZN,2024-12-18,0.0011804860550910234,-0.047078412026166916 +3,AMZN,2024-12-19,0.0009673979366198182,0.012482931837439537 +3,AMZN,2024-12-20,0.000863187073264271,0.007273430470377207 +3,AMZN,2024-12-23,0.0009175435989163816,0.0006222471711225808 +3,AMZN,2024-12-24,0.0008877154905349016,0.017573311924934387 +3,AMZN,2024-12-26,0.0009928143117576838,-0.00877006258815527 +3,AMZN,2024-12-27,0.0010156594216823578,-0.014640914276242256 +3,AMZN,2024-12-30,0.0009489361546002328,-0.011010096408426762 +3,AMZN,2024-12-31,0.0008395607001148164,-0.008668296039104462 +3,AMZN,2025-01-02,0.0007654133369214833,0.003776086959987879 +3,AMZN,2025-01-03,0.0007814769633114338,0.017866864800453186 +3,AMZN,2025-01-06,0.0009052061941474676,0.01513972319662571 +3,AMZN,2025-01-07,0.001023092307150364,-0.02446088381111622 +3,AMZN,2025-01-08,0.000984254409559071,9.00606537470594e-05 +3,AMZN,2025-01-10,0.0009746506693772972,-0.014465087093412876 +3,META,2024-03-25,0.0013886544620618224,-0.012956689111888409 +3,META,2024-03-26,0.0013879942707717419,-0.014275816269218922 +3,META,2024-03-27,0.0013187108561396599,-0.004102179314941168 +3,META,2024-03-28,0.001298190327361226,-0.016907989978790283 +3,META,2024-04-01,0.0011988384649157524,0.011812756769359112 +3,META,2024-04-02,0.0012109855888411403,0.012177471071481705 +3,META,2024-04-03,0.0013349370565265417,0.01866375468671322 +3,META,2024-04-04,0.001485329819843173,0.008215093985199928 +3,META,2024-04-05,0.001527389045804739,0.03163249418139458 +3,META,2024-04-08,0.0015825224108994007,-0.015460140071809292 +3,META,2024-04-09,0.001583180739544332,-0.0045359437353909016 +3,META,2024-04-10,0.0015761770773679018,0.005652317311614752 +3,META,2024-04-11,0.0015867827460169792,0.006385490298271179 +3,META,2024-04-12,0.001610634266398847,-0.0217580609023571 +3,META,2024-04-15,0.0015460666036233306,-0.023061245679855347 +3,META,2024-04-16,0.0014697194565087557,-0.0009400653652846813 +3,META,2024-04-17,0.0014395604375749826,-0.011248319409787655 +3,META,2024-04-18,0.001380539033561945,0.015322024002671242 +3,META,2024-04-19,0.0014150800416246057,-0.0421888530254364 +3,META,2024-04-22,0.0012702374951913953,0.0013709783088415861 +3,META,2024-04-23,0.0011902275728061795,0.029393766075372696 +3,META,2024-04-24,0.0012615157756954432,-0.005254737567156553 +3,META,2024-04-25,0.0012743452098220587,-0.11161666363477707 +3,META,2024-04-26,0.0010538476053625345,0.004318147897720337 +3,META,2024-04-29,0.0009571309201419353,-0.0243645291775465 +3,META,2024-04-30,0.0008246530196629465,-0.005679252091795206 +3,META,2024-05-01,0.0006846331525593996,0.020751550793647766 +3,META,2024-05-02,0.0006775155779905617,0.005653596017509699 +3,META,2024-05-03,0.000681402743794024,0.02300797589123249 +3,META,2024-05-06,0.0007521488005295396,0.029905075207352638 +3,META,2024-05-07,0.0008535168599337339,0.005482211709022522 +3,META,2024-05-08,0.0009276064811274409,0.009268311783671379 +3,META,2024-05-09,0.000998223666101694,0.0059493537992239 +3,META,2024-05-10,0.0010611338075250387,0.0016394117847085 +3,META,2024-05-13,0.001107801217585802,-0.0173482708632946 +3,META,2024-05-14,0.0011525950394570827,0.008171402849256992 +3,META,2024-05-15,0.001213112729601562,0.020328110083937645 +3,META,2024-05-16,0.0012595797888934612,-0.017407706007361412 +3,META,2024-05-17,0.0013072896981611848,-0.0027932566590607166 +3,META,2024-05-20,0.0013445209478959441,-0.006526674143970013 +3,META,2024-05-21,0.00135621998924762,-0.009020136669278145 +3,META,2024-05-22,0.0013664846774190664,0.006756628397852182 +3,META,2024-05-23,0.0013888980029150844,-0.004284718073904514 +3,META,2024-05-24,0.0013062456855550408,0.02635745145380497 +3,META,2024-05-28,0.0013716701650992036,0.0035485930275171995 +3,META,2024-05-29,0.0013994688633829355,-0.01165297906845808 +3,META,2024-05-30,0.0013570499140769243,-0.01553015410900116 +3,META,2024-05-31,0.0013056600000709295,-0.0004711666260845959 +3,META,2024-06-03,0.0013281804276630282,0.022578148171305656 +3,META,2024-06-04,0.001448682858608663,-0.0010477162431925535 +3,META,2024-06-05,0.0014725183136761189,0.0371834971010685 +3,META,2024-06-06,0.0015008928021416068,-0.0026294365525245667 +3,META,2024-06-07,0.0015133809065446258,-0.001621548435650766 +3,META,2024-06-10,0.0015145514626055956,0.019366592168807983 +3,META,2024-06-11,0.0015551216201856732,0.009643040597438812 +3,META,2024-06-12,0.0015750630991533399,0.002695933450013399 +3,META,2024-06-13,0.0015828534960746765,-0.00935904961079359 +3,META,2024-06-14,0.0015746046556159854,0.0011115148663520813 +3,META,2024-06-17,0.001582419965416193,0.004887199029326439 +3,META,2024-06-18,0.0015911714872345328,-0.01419341191649437 +3,META,2024-06-20,0.0015875324606895447,0.004414852242916822 +3,META,2024-06-21,0.00159161735791713,-0.013889141380786896 +3,META,2024-06-24,0.001573317451402545,0.008312533609569073 +3,META,2024-06-25,0.0015951191307976842,0.023160744458436966 +3,META,2024-06-26,0.0016203648410737514,0.004923246800899506 +3,META,2024-06-27,0.0016341734444722533,0.012472635135054588 +3,META,2024-06-28,0.0016522847581654787,-0.029969779774546623 +3,META,2024-07-01,0.0016165231354534626,0.0009119592723436654 +3,META,2024-07-02,0.001606576843187213,0.009505311958491802 +3,META,2024-07-03,0.0016111736185848713,0.000902392144780606 +3,META,2024-07-05,0.0016173649346455932,0.05707002058625221 +3,META,2024-07-08,0.001670905272476375,-0.019809111952781677 +3,META,2024-07-09,0.0016499076737090945,0.0012837463291361928 +3,META,2024-07-10,0.0016481922939419746,0.008810067549347878 +3,META,2024-07-11,0.001652529463171959,-0.04199599474668503 +3,META,2024-07-12,0.0016216348158195615,-0.027345482259988785 +3,META,2024-07-15,0.0015728725120425224,-0.005447076633572578 +3,META,2024-07-16,0.0015362147241830826,-0.012921708635985851 +3,META,2024-07-17,0.0015060185687616467,-0.05843354016542435 +3,META,2024-07-18,0.001358953770250082,0.029559558257460594 +3,META,2024-07-19,0.001357533154077828,0.001973429461941123 +3,META,2024-07-22,0.0013453791616484523,0.022008858621120453 +3,META,2024-07-23,0.0013694424415007234,0.0026432096492499113 +3,META,2024-07-24,0.0013980624498799443,-0.05774463713169098 +3,META,2024-07-25,0.001228921813890338,-0.01718689128756523 +3,META,2024-07-26,0.0010453123832121491,0.02674490213394165 +3,META,2024-07-29,0.0010602729162201285,2.1506135453819297e-05 +3,META,2024-07-30,0.0010573245817795396,-0.005425869021564722 +3,META,2024-07-31,0.0010396521538496017,0.02481956221163273 +3,META,2024-08-01,0.0011093529174104333,0.047120943665504456 +3,META,2024-08-02,0.0012074806727468967,-0.019475528970360756 +3,META,2024-08-05,0.001267793821170926,-0.025751635432243347 +3,META,2024-08-06,0.0012208281550556421,0.03786703944206238 +3,META,2024-08-07,0.001258160686120391,-0.010518752969801426 +3,META,2024-08-08,0.0012952955439686775,0.04148608446121216 +3,META,2024-08-09,0.0013755240943282843,0.015846218913793564 +3,META,2024-08-12,0.0014361835783347487,-0.003521380014717579 +3,META,2024-08-13,0.0014580945717170835,0.024108614772558212 +3,META,2024-08-14,0.0015054336981847882,-0.0033733288291841745 +3,META,2024-08-15,0.0014876802451908588,0.019867265596985817 +3,META,2024-08-16,0.001492518582381308,-0.018615147098898888 +3,META,2024-08-19,0.0014633152168244123,0.003520393278449774 +3,META,2024-08-20,0.0014501821715384722,-0.0048295543529093266 +3,META,2024-08-21,0.001433487981557846,0.015877554193139076 +3,META,2024-08-22,0.0014642284950241446,-0.006053815595805645 +3,META,2024-08-23,0.0014353302540257573,-0.007415762171149254 +3,META,2024-08-26,0.001455014804378152,-0.013115794397890568 +3,META,2024-08-27,0.0014018092770129442,-0.003883681260049343 +3,META,2024-08-28,0.0013948874548077583,-0.004479359835386276 +3,META,2024-08-29,0.001323775970377028,0.002782534807920456 +3,META,2024-08-30,0.0012583943316712976,0.005945250857621431 +3,META,2024-09-03,0.0012520801974460483,-0.01848924346268177 +3,META,2024-09-04,0.0011743122013285756,0.0019130983855575323 +3,META,2024-09-05,0.0012628893600776792,0.008003154769539833 +3,META,2024-09-06,0.0013524825917556882,-0.0326240174472332 +3,META,2024-09-09,0.001244623214006424,0.008994564414024353 +3,META,2024-09-10,0.001269257627427578,0.0 +3,META,2024-09-11,0.001289996551349759,0.013850007206201553 +3,META,2024-09-12,0.0013618477387353778,0.026547951623797417 +3,META,2024-09-13,0.0014778566546738148,-0.0018663632217794657 +3,META,2024-09-16,0.0015637482283636928,0.01732618734240532 +3,META,2024-09-17,0.0016282963333651423,0.0056842174381017685 +3,META,2024-09-18,0.0016344329342246056,0.003034604014828801 +3,META,2024-09-19,0.0016451491974294186,0.03856269270181656 +3,META,2024-09-20,0.0016450161347165704,0.004016344901174307 +3,META,2024-09-23,0.0016374714905396104,0.005436205305159092 +3,META,2024-09-24,0.0016024779761210084,-0.0019150635926052928 +3,META,2024-09-25,0.001588613260537386,0.008801054209470749 +3,META,2024-09-26,0.001553292735479772,-0.0008270930266007781 +3,META,2024-09-27,0.001546316547319293,-0.0008456299547106028 +3,META,2024-09-30,0.0015159082831814885,0.008913838304579258 +3,META,2024-10-01,0.0015073420945554972,0.007015286944806576 +3,META,2024-10-02,0.0015207069227471948,-0.006369289942085743 +3,META,2024-10-03,0.0014977491227909923,0.01723851077258587 +3,META,2024-10-04,0.0015487545169889927,0.022347403690218925 +3,META,2024-10-07,0.0015798291424289346,-0.018904129043221474 +3,META,2024-10-08,0.0015124920755624771,0.013773057609796524 +3,META,2024-10-09,0.0015124217607080936,-0.004022121429443359 +3,META,2024-10-10,0.0014982407446950674,-0.011376825161278248 +3,META,2024-10-11,0.0014762058854103088,0.010427995584905148 +3,META,2024-10-14,0.0015032477676868439,0.0007963157841004431 +3,META,2024-10-15,0.0014914973871782422,-0.007053751032799482 +3,META,2024-10-16,0.0014794630696997046,-0.016302205622196198 +3,META,2024-10-17,0.0014234798727557063,0.00024283805396407843 +3,META,2024-10-18,0.0014737889869138598,-0.0007977985660545528 +3,META,2024-10-21,0.0015020148130133748,-0.002274902770295739 +3,META,2024-10-22,0.001502139843069017,0.011839324608445168 +3,META,2024-10-23,0.0015643280930817127,-0.03198329731822014 +3,META,2024-10-24,0.0014780692290514708,0.0072296480648219585 +3,META,2024-10-25,0.0015060629229992628,0.009587815031409264 +3,META,2024-10-28,0.0015405029989778996,0.00852880533784628 +3,META,2024-10-29,0.0015941531164571643,0.025815922766923904 +3,META,2024-10-30,0.0016649059252813458,-0.0024977633729577065 +3,META,2024-10-31,0.0016838376177474856,-0.04178708419203758 +3,META,2024-11-01,0.0015207623364403844,-0.0007403750205412507 +3,META,2024-11-04,0.0014302843483164907,-0.011491010896861553 +3,META,2024-11-05,0.0012993233976885676,0.020740045234560966 +3,META,2024-11-06,0.0013753791572526097,-0.000664024380967021 +3,META,2024-11-07,0.0013964965473860502,0.03377346321940422 +3,META,2024-11-08,0.0015864750603213906,-0.003996581304818392 +3,META,2024-11-11,0.0016290521016344428,-0.010524527169764042 +3,META,2024-11-12,0.0016343718161806464,0.0028253733180463314 +3,META,2024-11-13,0.0016522568184882402,-0.008275884203612804 +3,META,2024-11-14,0.0016329080099239945,-0.004908644128590822 +3,META,2024-11-15,0.00162227894179523,-0.04081038013100624 +3,META,2024-11-18,0.001399857341311872,0.0005772688309662044 +3,META,2024-11-19,0.0012997535523027182,0.011994987726211548 +3,META,2024-11-20,0.0013121067313477397,0.007864131592214108 +3,META,2024-11-21,0.0013549071736633778,-0.004306039772927761 +3,META,2024-11-22,0.0013668539468199015,-0.0070396289229393005 +3,META,2024-11-25,0.0013479264453053474,0.01062051858752966 +3,META,2024-11-26,0.0014057133812457323,0.014807168394327164 +3,META,2024-11-27,0.0015010858187451959,-0.007595622446388006 +3,META,2024-11-29,0.0015558862360194325,0.008954628370702267 +3,META,2024-12-02,0.001611547078937292,0.03172105550765991 +3,META,2024-12-03,0.0016753919189795852,0.03451709821820259 +3,META,2024-12-04,0.0017252943944185972,0.0002118511329172179 +3,META,2024-12-05,0.0017390318680554628,-0.007933255285024643 +3,META,2024-12-06,0.0017224967014044523,0.02407842129468918 +3,META,2024-12-09,0.0017124919686466455,-0.016487471759319305 +3,META,2024-12-10,0.001666220254264772,0.009327836334705353 +3,META,2024-12-11,0.0016495662275701761,0.021342750638723373 +3,META,2024-12-12,0.0016434341669082642,-0.0029918968211859465 +3,META,2024-12-13,0.0016170763410627842,-0.0166891198605299 +3,META,2024-12-16,0.001572021865285933,0.007057298440486193 +3,META,2024-12-17,0.0016236953670158982,-0.007719026878476143 +3,META,2024-12-18,0.0016040686750784516,-0.03658042103052139 +3,META,2024-12-19,0.001350029488094151,-0.002716438379138708 +3,META,2024-12-20,0.0012069951044395566,-0.017479900270700455 +3,META,2024-12-23,0.0011825861874967813,0.02464042790234089 +3,META,2024-12-24,0.0012392285279929638,0.013084093108773232 +3,META,2024-12-26,0.0013384729390963912,-0.007266150787472725 +3,META,2024-12-27,0.0013989879516884685,-0.005884306970983744 +3,META,2024-12-30,0.0014233858091756701,-0.014391190372407436 +3,META,2024-12-31,0.0013887569075450301,-0.009738494642078876 +3,META,2025-01-02,0.0013291563373059034,0.023178724572062492 +3,META,2025-01-03,0.001388891483657062,0.008954574353992939 +3,META,2025-01-06,0.0014827076811343431,0.04142049327492714 +3,META,2025-01-07,0.001632597530260682,-0.019726676866412163 +3,META,2025-01-08,0.0016385981580242515,-0.011672008782625198 +3,META,2025-01-10,0.0016165999695658684,0.008381119929254055 +3,SPY,2024-03-25,0.0008960445993579924,-0.002766657155007124 +3,SPY,2024-03-26,0.0008885654387995601,-0.001848558778874576 +3,SPY,2024-03-27,0.000876308826263994,0.008368568494915962 +3,SPY,2024-03-28,0.0008971237693913281,-0.00019129691645503044 +3,SPY,2024-04-01,0.0008992123184725642,-0.0017409671563655138 +3,SPY,2024-04-02,0.0008957417448982596,-0.006378494668751955 +3,SPY,2024-04-03,0.0008794772438704967,0.0010979323415085673 +3,SPY,2024-04-04,0.0008880029781721532,-0.012281196191906929 +3,SPY,2024-04-05,0.0008303381619043648,0.01039254479110241 +3,SPY,2024-04-08,0.0008433176553808153,0.0005592787056230009 +3,SPY,2024-04-09,0.0008545887540094554,0.0011560029815882444 +3,SPY,2024-04-10,0.0008622874738648534,-0.010063635185360909 +3,SPY,2024-04-11,0.0007954061729833484,0.007518771104514599 +3,SPY,2024-04-12,0.0008315416052937508,-0.013899296522140503 +3,SPY,2024-04-15,0.0007599599775858223,-0.012607306241989136 +3,SPY,2024-04-16,0.0006796061061322689,-0.0018253903836011887 +3,SPY,2024-04-17,0.0006483163451775908,-0.0059358193539083 +3,SPY,2024-04-18,0.000614477670751512,-0.0020598256960511208 +3,SPY,2024-04-19,0.0005879069212824106,-0.008766712620854378 +3,SPY,2024-04-22,0.0005519241094589233,0.009166988544166088 +3,SPY,2024-04-23,0.0005838160286657512,0.011796780861914158 +3,SPY,2024-04-24,0.0006585129885934293,-0.00047488906420767307 +3,SPY,2024-04-25,0.0006975078140385449,-0.0038060706574469805 +3,SPY,2024-04-26,0.0007107799756340683,0.009429419413208961 +3,SPY,2024-04-29,0.0007475671009160578,0.003534986637532711 +3,SPY,2024-04-30,0.0007898319163359702,-0.01596779190003872 +3,SPY,2024-05-01,0.0007382892654277384,-0.0032526212744414806 +3,SPY,2024-05-02,0.0007354594417847693,0.009310102090239525 +3,SPY,2024-05-03,0.0007679926347918808,0.012319138273596764 +3,SPY,2024-05-06,0.0008149853674694896,0.010273776948451996 +3,SPY,2024-05-07,0.0008383792592212558,0.0011028756853193045 +3,SPY,2024-05-08,0.0008434181800112128,9.653770393924788e-05 +3,SPY,2024-05-09,0.0008506763842888176,0.005745389498770237 +3,SPY,2024-05-10,0.000865275040268898,0.0012873397208750248 +3,SPY,2024-05-13,0.0008601009612902999,0.00013429844693746418 +3,SPY,2024-05-14,0.0008694683783687651,0.004577548708766699 +3,SPY,2024-05-15,0.000876353238709271,0.01230708509683609 +3,SPY,2024-05-16,0.0008819284266792238,-0.002059522084891796 +3,SPY,2024-05-17,0.0008673685370013118,0.00143627414945513 +3,SPY,2024-05-20,0.0008711870759725571,0.001151509233750403 +3,SPY,2024-05-21,0.0008716057636775076,0.0024494642857462168 +3,SPY,2024-05-22,0.0008794523891992867,-0.0028833134565502405 +3,SPY,2024-05-23,0.0008724250947125256,-0.007330967113375664 +3,SPY,2024-05-24,0.0008532156934961677,0.0065946015529334545 +3,SPY,2024-05-28,0.0008613239624537528,0.000698625750374049 +3,SPY,2024-05-29,0.0008643282926641405,-0.007027262356132269 +3,SPY,2024-05-30,0.0008455064962618053,-0.006655678618699312 +3,SPY,2024-05-31,0.0008252845727838576,0.009066744707524776 +3,SPY,2024-06-03,0.0008446454303339124,0.0008149083587341011 +3,SPY,2024-06-04,0.0008599627180956304,0.0011172655504196882 +3,SPY,2024-06-05,0.0008679007296450436,0.011815224774181843 +3,SPY,2024-06-06,0.0009070896776393056,-1.8757655197987333e-05 +3,SPY,2024-06-07,0.0009182205540128052,-0.0012163640931248665 +3,SPY,2024-06-10,0.0009084765915758908,0.0030848903115838766 +3,SPY,2024-06-11,0.0009227637783624232,0.0024053268134593964 +3,SPY,2024-06-12,0.0009277048520743847,0.008179450407624245 +3,SPY,2024-06-13,0.000924026477150619,0.0020117168314754963 +3,SPY,2024-06-14,0.0009154522558674216,0.0006080851308070123 +3,SPY,2024-06-17,0.0009124202770181,0.007927552796900272 +3,SPY,2024-06-18,0.0009143390925601125,0.0025373834650963545 +3,SPY,2024-06-20,0.0009126334334723651,-0.00272036949172616 +3,SPY,2024-06-21,0.0008946576272137463,-0.0013416220899671316 +3,SPY,2024-06-24,0.0008868610020726919,-0.0032558052334934473 +3,SPY,2024-06-25,0.0008768526604399085,0.003843588288873434 +3,SPY,2024-06-26,0.0008768884581513703,0.0012473779497668147 +3,SPY,2024-06-27,0.0008738716132938862,0.0015751057071611285 +3,SPY,2024-06-28,0.0008899162639863789,-0.003942942712455988 +3,SPY,2024-07-01,0.0008695645956322551,0.0020561383571475744 +3,SPY,2024-07-02,0.0008793947636149824,0.006707005202770233 +3,SPY,2024-07-03,0.0008977051475085318,0.004452706314623356 +3,SPY,2024-07-05,0.0009087808430194855,0.005749921780079603 +3,SPY,2024-07-08,0.000918121833819896,0.0011533189099282026 +3,SPY,2024-07-09,0.0009129981626756489,0.0009719246882013977 +3,SPY,2024-07-10,0.0009031586232595146,0.009846755303442478 +3,SPY,2024-07-11,0.0009130688267759979,-0.008660065941512585 +3,SPY,2024-07-12,0.0008900809334591031,0.006287816446274519 +3,SPY,2024-07-15,0.0008945855079218745,0.002746290061622858 +3,SPY,2024-07-16,0.0008970689377747476,0.005912601016461849 +3,SPY,2024-07-17,0.0009100132156163454,-0.014120464213192463 +3,SPY,2024-07-18,0.0008759102784097195,-0.0077143218368291855 +3,SPY,2024-07-19,0.000850202573928982,-0.006662901025265455 +3,SPY,2024-07-22,0.0008138175471685827,0.010257069952785969 +3,SPY,2024-07-23,0.0008291745325550437,-0.0015696255723014474 +3,SPY,2024-07-24,0.0008144322200678289,-0.022923504933714867 +3,SPY,2024-07-25,0.0006798399845138192,-0.005223698448389769 +3,SPY,2024-07-26,0.0006177861941978335,0.011137301102280617 +3,SPY,2024-07-29,0.0006592395948246121,0.0005876292707398534 +3,SPY,2024-07-30,0.0006745322607457638,-0.0050794342532753944 +3,SPY,2024-07-31,0.0006617764593102038,0.01612403802573681 +3,SPY,2024-08-01,0.0007290979265235364,-0.014262206852436066 +3,SPY,2024-08-02,0.0006775595247745514,-0.018793758004903793 +3,SPY,2024-08-05,0.0005998638225719333,-0.02955632284283638 +3,SPY,2024-08-06,0.0004507187695708126,0.009177186526358128 +3,SPY,2024-08-07,0.00042046274757012725,-0.006706363521516323 +3,SPY,2024-08-08,0.0003568700631149113,0.02285432070493698 +3,SPY,2024-08-09,0.00043372309301048517,0.00439976342022419 +3,SPY,2024-08-12,0.0005047254962846637,0.0005253843264654279 +3,SPY,2024-08-13,0.0005502027343027294,0.016311731189489365 +3,SPY,2024-08-14,0.0006186776445247233,0.0031500444747507572 +3,SPY,2024-08-15,0.0006629146519117057,0.016994699835777283 +3,SPY,2024-08-16,0.0007254584925249219,0.0022395970299839973 +3,SPY,2024-08-19,0.0007738841813988984,0.00951601006090641 +3,SPY,2024-08-20,0.0007950884755700827,-0.0016272722277790308 +3,SPY,2024-08-21,0.0007976543856784701,0.0034305681474506855 +3,SPY,2024-08-22,0.0007986940909177065,-0.007879587821662426 +3,SPY,2024-08-23,0.0007752084056846797,0.010569334030151367 +3,SPY,2024-08-26,0.0007973956526257098,-0.0023867653217166662 +3,SPY,2024-08-27,0.0007866019732318819,0.0013721291907131672 +3,SPY,2024-08-28,0.000791501603089273,-0.005821990314871073 +3,SPY,2024-08-29,0.0007696074899286032,8.941311534726992e-05 +3,SPY,2024-08-30,0.0007708063931204379,0.0095010194927454 +3,SPY,2024-09-03,0.0007902096258476377,-0.02079395018517971 +3,SPY,2024-09-04,0.0007438855245709419,-0.0020489287562668324 +3,SPY,2024-09-05,0.0006862955051474273,-0.0024351433385163546 +3,SPY,2024-09-06,0.0006632941658608615,-0.016973096877336502 +3,SPY,2024-09-09,0.0005704713985323906,0.011133579537272453 +3,SPY,2024-09-10,0.0006152744172140956,0.004346456844359636 +3,SPY,2024-09-11,0.0006677143392153084,0.010206697508692741 +3,SPY,2024-09-12,0.0007245134911499918,0.008387845940887928 +3,SPY,2024-09-13,0.0007699447451159358,0.0052093034610152245 +3,SPY,2024-09-16,0.0007930382271297276,0.0014757262542843819 +3,SPY,2024-09-17,0.0008049003081396222,0.00040865002665668726 +3,SPY,2024-09-18,0.0008056515944190323,-0.0029704542830586433 +3,SPY,2024-09-19,0.000799929432105273,0.016920531168580055 +3,SPY,2024-09-20,0.0008058860548771918,-0.0017300986219197512 +3,SPY,2024-09-23,0.0008031012257561088,0.002495897002518177 +3,SPY,2024-09-24,0.00080289994366467,0.002857182640582323 +3,SPY,2024-09-25,0.000809193414170295,-0.002208119025453925 +3,SPY,2024-09-26,0.0007983723771758378,0.003956743516027927 +3,SPY,2024-09-27,0.0008025856222957373,-0.0014511251356452703 +3,SPY,2024-09-30,0.0007960583898238838,0.00399918993934989 +3,SPY,2024-10-01,0.0007953239837661386,-0.008998755365610123 +3,SPY,2024-10-02,0.0007774268160574138,0.0004218751273583621 +3,SPY,2024-10-03,0.0007658767281100154,-0.0018298511859029531 +3,SPY,2024-10-04,0.0007558942888863385,0.009046273306012154 +3,SPY,2024-10-07,0.0007805267232470214,-0.009081597439944744 +3,SPY,2024-10-08,0.0007657757378183305,0.00941321812570095 +3,SPY,2024-10-09,0.0007878486067056656,0.006902497727423906 +3,SPY,2024-10-10,0.0008012242033146322,-0.0017516780644655228 +3,SPY,2024-10-11,0.000804750481620431,0.005970484111458063 +3,SPY,2024-10-14,0.0008110748021863401,0.00814529974013567 +3,SPY,2024-10-15,0.0008106043096631765,-0.007800157181918621 +3,SPY,2024-10-16,0.0007981226081028581,0.004336995538324118 +3,SPY,2024-10-17,0.000797805842012167,8.589374192524701e-05 +3,SPY,2024-10-18,0.000799577625002712,0.00383916893042624 +3,SPY,2024-10-21,0.000809496094007045,-0.0016437366139143705 +3,SPY,2024-10-22,0.0008036356884986162,-0.0005313208675943315 +3,SPY,2024-10-23,0.0008051121840253472,-0.009179368615150452 +3,SPY,2024-10-24,0.0007831772090867162,0.002160467207431793 +3,SPY,2024-10-25,0.0007889058906584978,-0.00034546450478956103 +3,SPY,2024-10-28,0.0007802864420227706,0.003086554352194071 +3,SPY,2024-10-29,0.0007879511686041951,0.0016171785537153482 +3,SPY,2024-10-30,0.000803689647000283,-0.003030009102076292 +3,SPY,2024-10-31,0.0008021408575586975,-0.019797559827566147 +3,SPY,2024-11-01,0.0007108558202162385,0.0042114886455237865 +3,SPY,2024-11-04,0.0006939272861927748,-0.0021561065223068 +3,SPY,2024-11-05,0.0006761792465113103,0.012019291520118713 +3,SPY,2024-11-06,0.0007578906370326877,0.024561475962400436 +3,SPY,2024-11-07,0.0008082740823738277,0.007702321745455265 +3,SPY,2024-11-08,0.00086071970872581,0.004322148393839598 +3,SPY,2024-11-11,0.0008658092119731009,0.0009525362984277308 +3,SPY,2024-11-12,0.000865315436385572,-0.0031112756114453077 +3,SPY,2024-11-13,0.0008543133735656738,0.0004858593747485429 +3,SPY,2024-11-14,0.0008488714811392128,-0.0064510744996368885 +3,SPY,2024-11-15,0.0008392537711188197,-0.012891167774796486 +3,SPY,2024-11-18,0.0008139307028613985,0.004088932182639837 +3,SPY,2024-11-19,0.0008137166732922196,0.0036488096229732037 +3,SPY,2024-11-20,0.0008172972593456507,0.0003388758341316134 +3,SPY,2024-11-21,0.0008179389405995607,0.005353888962417841 +3,SPY,2024-11-22,0.0008330580894835293,0.0030947052873671055 +3,SPY,2024-11-25,0.0008417345234192908,0.0033863645512610674 +3,SPY,2024-11-26,0.0008516125963069499,0.005207899492233992 +3,SPY,2024-11-27,0.0008722556522116065,-0.00303479190915823 +3,SPY,2024-11-29,0.0008760786149650812,0.006192937958985567 +3,SPY,2024-12-02,0.0008871409809216857,0.001790722832083702 +3,SPY,2024-12-03,0.0008880822570063174,0.0004636315570678562 +3,SPY,2024-12-04,0.0009027905762195587,0.006190413609147072 +3,SPY,2024-12-05,0.000912054325453937,-0.0016470950795337558 +3,SPY,2024-12-06,0.0009248204296454787,0.0018940026639029384 +3,SPY,2024-12-09,0.000924488645978272,-0.005163080990314484 +3,SPY,2024-12-10,0.000907409586943686,-0.003113730810582638 +3,SPY,2024-12-11,0.0008921141270548105,0.007700805086642504 +3,SPY,2024-12-12,0.0009031040244735777,-0.00516606355085969 +3,SPY,2024-12-13,0.0008854164043441415,-0.00019853480625897646 +3,SPY,2024-12-16,0.0008809075807221234,0.0042608631774783134 +3,SPY,2024-12-17,0.0009164868388324976,-0.0041285022161901 +3,SPY,2024-12-18,0.0009030298097059131,-0.030256718397140503 +3,SPY,2024-12-19,0.0007744799950160086,-0.0003070936945732683 +3,SPY,2024-12-20,0.0006780123803764582,0.011939452961087227 +3,SPY,2024-12-23,0.000734143890440464,0.005970454774796963 +3,SPY,2024-12-24,0.0007645985460840166,0.011053675785660744 +3,SPY,2024-12-26,0.0008146999753080308,6.658957863692194e-05 +3,SPY,2024-12-27,0.0008397632045671344,-0.010582380928099155 +3,SPY,2024-12-30,0.0008315426530316472,-0.011477092280983925 +3,SPY,2024-12-31,0.0007924669189378619,-0.0036445579025894403 +3,SPY,2025-01-02,0.0007213020580820739,-0.002460253657773137 +3,SPY,2025-01-03,0.000650228641461581,0.012425986118614674 +3,SPY,2025-01-06,0.0007204188732430339,0.005743981804698706 +3,SPY,2025-01-07,0.0007810049573890865,-0.011368421837687492 +3,SPY,2025-01-08,0.000748149526771158,0.0014598399866372347 +3,SPY,2025-01-10,0.0007437755120918155,-0.015385068953037262 +4,AAPL,2025-01-13,-0.0004283898160792887,-0.01039794646203518 +4,AAPL,2025-01-14,-0.0007054057787172496,-0.0047896429896354675 +4,AAPL,2025-01-15,-0.0007979501970112324,0.019484858959913254 +4,AAPL,2025-01-16,-0.0006088856607675552,-0.041238877922296524 +4,AAPL,2025-01-17,-0.0006663950625807047,0.007506965193897486 +4,AAPL,2025-01-21,-0.0004829749814234674,-0.032436124980449677 +4,AAPL,2025-01-22,9.969929669750854e-05,0.005330720450729132 +4,AAPL,2025-01-23,0.000211956343264319,-0.0007599411183036864 +4,AAPL,2025-01-24,0.0002753114385996014,-0.0039422232657670975 +4,AAPL,2025-01-27,0.0002601078595034778,0.03128569573163986 +4,AAPL,2025-01-28,-0.0007323662284761667,0.03589194267988205 +4,AAPL,2025-01-29,-0.0005098808906041086,0.0046062953770160675 +4,AAPL,2025-01-30,-0.00012244575191289186,-0.007422196678817272 +4,AAPL,2025-01-31,0.0002688647364266217,-0.006714791990816593 +4,AAPL,2025-02-03,0.00029033448663540184,-0.03444225341081619 +4,AAPL,2025-02-04,-0.00014203728642314672,0.02079024538397789 +4,AAPL,2025-02-05,4.188101684121648e-06,-0.0014185270993039012 +4,AAPL,2025-02-06,1.2721905477519613e-05,0.003220972139388323 +4,AAPL,2025-02-07,9.467543713981286e-05,-0.024260656908154488 +4,AAPL,2025-02-10,-0.00015929140499792993,0.0011866980930790305 +4,AAPL,2025-02-11,-9.444583702133968e-05,0.021596940234303474 +4,AAPL,2025-02-12,0.00019903456268366426,0.0181051604449749 +4,AAPL,2025-02-13,0.00035964875132776797,0.019482234492897987 +4,AAPL,2025-02-14,0.00041028112173080444,0.01263049803674221 +4,AAPL,2025-02-18,0.00040648868889547884,-0.0005315837333910167 +4,AAPL,2025-02-19,0.0004090715083293617,0.001634846325032413 +4,AAPL,2025-02-20,0.0004139012307859957,0.003912785556167364 +4,AAPL,2025-02-21,0.00041162269189953804,-0.0011395912151783705 +4,AAPL,2025-02-24,0.0004212734056636691,0.006292531732469797 +4,AAPL,2025-02-25,0.00041268725180998445,-0.00024290071451105177 +4,AAPL,2025-02-26,0.00038854850572533906,-0.02741251513361931 +4,AAPL,2025-02-27,0.00016745273023843765,-0.012812557630240917 +4,AAPL,2025-02-28,-0.0002482440904714167,0.018951214849948883 +4,AAPL,2025-03-03,-0.0001842689234763384,-0.01587964966893196 +4,AAPL,2025-03-04,-0.00031350631616078317,-0.008861677721142769 +4,AAPL,2025-03-05,-0.00042458975804038346,-0.00080553611041978 +4,AAPL,2025-03-06,-0.00040975265437737107,-0.0017407508566975594 +4,AAPL,2025-03-07,-0.0003378446854185313,0.01576765812933445 +4,AAPL,2025-03-10,-0.00012610512203536928,-0.04969414323568344 +4,AAPL,2025-03-11,-0.0007589503657072783,-0.029623810201883316 +4,AAPL,2025-03-12,-0.0004694358503911644,-0.017633378505706787 +4,AAPL,2025-03-13,2.884822060877923e-05,-0.03422253951430321 +4,AAPL,2025-03-14,0.0006540235481224954,0.01800745166838169 +4,AAPL,2025-03-17,0.0006250583101063967,0.0023860190995037556 +4,AAPL,2025-03-18,0.0006249017897062004,-0.006140284240245819 +4,AAPL,2025-03-19,0.0006692979950457811,0.011918035335838795 +4,AAPL,2025-03-20,0.00061114999698475,-0.005310680717229843 +4,AAPL,2025-03-21,0.0006063066539354622,0.019289741292595863 +4,AAPL,2025-03-24,0.0003516417637001723,0.0112073365598917 +4,AAPL,2025-03-25,1.7511809346615337e-05,0.013589204289019108 +4,AAPL,2025-03-26,-0.0004625697620213032,-0.009971301071345806 +4,AAPL,2025-03-27,-0.0005681674228981137,0.010418228805065155 +4,AAPL,2025-03-28,-0.0006790299667045474,-0.02694004960358143 +4,AAPL,2025-03-31,-0.0006904639885760844,0.01922657899558544 +4,AAPL,2025-04-01,-0.0004244970332365483,0.0047605279833078384 +4,AAPL,2025-04-02,-0.0002889945462811738,0.003131381468847394 +4,AAPL,2025-04-03,-0.00011755385639844462,-0.09701328724622726 +4,AAPL,2025-04-04,0.00019405814236961305,-0.07568024098873138 +4,AAPL,2025-04-07,0.0016917696921154857,-0.03742597624659538 +4,AAPL,2025-04-08,0.0029740354511886835,-0.05110190808773041 +4,AAPL,2025-04-09,0.0041973828338086605,0.14261743426322937 +4,AAPL,2025-04-10,0.003372473642230034,-0.043318603187799454 +4,AAPL,2025-04-11,0.0036741422954946756,0.039792127907276154 +4,AAPL,2025-04-14,0.003320938441902399,0.021814361214637756 +4,AAPL,2025-04-15,0.003145891707390547,-0.0018781628459692001 +4,AAPL,2025-04-16,0.00284266727976501,-0.03971163555979729 +4,AAPL,2025-04-17,0.0028957705944776535,0.013853269629180431 +4,AAPL,2025-04-21,0.0029272346291691065,-0.01958325318992138 +4,AAPL,2025-04-22,0.0027452821377664804,0.03349760174751282 +4,AAPL,2025-04-23,0.0025159164797514677,0.02404041774570942 +4,AAPL,2025-04-24,0.0020275472197681665,0.018258392810821533 +4,AAPL,2025-04-25,0.0007028714753687382,0.004357709549367428 +4,AAPL,2025-04-28,0.0006102954503148794,0.004100949969142675 +4,AAPL,2025-04-29,0.00023195581161417067,0.005078935530036688 +4,AAPL,2025-04-30,4.5835116907255724e-05,0.006089044269174337 +4,AAPL,2025-05-01,-0.00017514177307020873,0.003851469373330474 +4,AAPL,2025-05-02,-0.00025807967176660895,-0.03807755187153816 +4,AAPL,2025-05-05,0.00017321882478427142,-0.03196397051215172 +4,AAPL,2025-05-06,0.0005875931237824261,-0.0019123200327157974 +4,AAPL,2025-05-07,0.0005550138303078711,-0.011450359597802162 +4,AAPL,2025-05-08,0.0006779833929613233,0.00629868358373642 +4,AAPL,2025-05-09,0.0004941035876981914,0.005252211820334196 +4,AAPL,2025-05-12,9.980923096009064e-06,0.06123270466923714 +4,AAPL,2025-05-13,-0.0006796505767852068,0.010101133957505226 +4,AAPL,2025-05-14,-0.00032002010266296566,-0.0028217711951583624 +4,AAPL,2025-05-15,-0.00028208590811118484,-0.004153083078563213 +4,AAPL,2025-05-16,-0.00018150503456126899,-0.0008990378119051456 +4,AAPL,2025-05-19,-0.00018052448285743594,-0.01180849689990282 +4,AAPL,2025-05-20,-0.00018451215873938054,-0.009238837286829948 +4,AAPL,2025-05-21,-0.0002310565032530576,-0.02332916110754013 +4,AAPL,2025-05-22,-0.00046183133963495493,-0.0036187029909342527 +4,AAPL,2025-05-23,-0.0005915366346016526,-0.030711090192198753 +4,AAPL,2025-05-27,-0.00028460330213420093,0.02498370036482811 +4,AAPL,2025-05-28,-0.00035142796696163714,0.0010482444195076823 +4,AAPL,2025-05-29,-0.0005542339640669525,-0.0023480006493628025 +4,AAPL,2025-05-30,-0.0006542018381878734,0.004491048399358988 +4,AAPL,2025-06-02,-0.0006967607187107205,0.004223110154271126 +4,AAPL,2025-06-03,-0.0005753798177465796,0.0077538033947348595 +4,AAPL,2025-06-04,-0.0005210411618463695,-0.0022162317764014006 +4,AAPL,2025-06-05,-0.00046154664596542716,-0.01085650734603405 +4,AAPL,2025-06-06,-0.0005782800144515932,0.01626524142920971 +4,AAPL,2025-06-09,-0.00037498591700568795,-0.012186448089778423 +4,AAPL,2025-06-10,-0.00042512855725362897,0.006037801969796419 +4,AAPL,2025-06-11,-0.00032185798045247793,-0.019380366429686546 +4,AAPL,2025-06-12,-0.0004975938936695457,0.002110680565237999 +4,AAPL,2025-06-13,-0.00040746541344560683,-0.01390138640999794 +4,AAPL,2025-06-16,-0.0006583182257600129,0.009978054091334343 +4,AAPL,2025-06-17,-0.0005390663864091039,-0.014109778217971325 +4,AAPL,2025-06-18,-0.0006821592105552554,0.004793273750692606 +4,AAPL,2025-06-20,-0.0005470930482260883,0.022235369309782982 +4,AAPL,2025-06-23,-0.00015032677038107067,0.0024845199659466743 +4,AAPL,2025-06-24,3.3739015634637326e-05,-0.00597314303740859 +4,AAPL,2025-06-25,8.022555994102731e-05,0.006270770914852619 +4,AAPL,2025-06-26,-2.0159216091997223e-06,-0.002782147377729416 +4,AAPL,2025-06-27,2.896601836255286e-05,0.0003979564644396305 +4,AAPL,2025-06-30,7.407715747831389e-05,0.020136140286922455 +4,AAPL,2025-07-01,0.00027605475042946637,0.012833409942686558 +4,AAPL,2025-07-02,0.00033194877323694527,0.021987272426486015 +4,AAPL,2025-07-03,0.0003871807421091944,0.005211253184825182 +4,AAPL,2025-07-07,0.00035254814429208636,-0.017001532018184662 +4,AAPL,2025-07-08,0.00017171526269521564,0.00028572347946465015 +4,AAPL,2025-07-09,0.0002974012750200927,0.0053663095459342 +4,AAPL,2025-07-10,0.0004079077043570578,0.0059969923458993435 +4,AAPL,2025-07-11,0.0004184920690022409,-0.005902376025915146 +4,AAPL,2025-07-14,0.00040984811494126916,-0.012101594358682632 +4,AAPL,2025-07-15,0.0002365488326177001,0.0023460006341338158 +4,AAPL,2025-07-16,0.0003802928258664906,0.005008801817893982 +4,AAPL,2025-07-17,0.000409755390137434,-0.0006663876120001078 +4,AAPL,2025-07-18,0.00043888529762625694,0.005507932510226965 +4,AAPL,2025-07-21,0.0004096223274245858,0.0061370874755084515 +4,AAPL,2025-07-22,0.00040176804759539664,0.008995498530566692 +4,AAPL,2025-07-23,0.0003764425637200475,-0.001166782807558775 +4,AAPL,2025-07-24,0.000382664060452953,-0.0018227346008643508 +4,AAPL,2025-07-25,0.00038327486254274845,0.0005613277317024767 +4,AAPL,2025-07-28,0.00037266541039571166,0.0007944126264192164 +4,AAPL,2025-07-29,0.00036058240220882,-0.013072567991912365 +4,AAPL,2025-07-30,0.00037243307451717556,-0.010563613846898079 +4,AAPL,2025-07-31,0.00037736096419394016,-0.007104769814759493 +4,AAPL,2025-08-01,0.00031793193193152547,-0.02532144822180271 +4,AAPL,2025-08-04,-0.00018232416186947376,0.0047814263962209225 +4,AAPL,2025-08-05,-0.00035325001226738095,-0.0021167488303035498 +4,AAPL,2025-08-06,-0.00048039431567303836,0.049653250724077225 +4,AAPL,2025-08-07,0.00030651752604171634,0.031298793852329254 +4,AAPL,2025-08-08,0.00037038035225123167,0.041485339403152466 +4,AAPL,2025-08-11,0.00037632696330547333,-0.008372346870601177 +4,AAPL,2025-08-12,0.00040180076030083,0.010813678614795208 +4,AAPL,2025-08-13,0.00039906741585582495,0.015897424891591072 +4,AAPL,2025-08-14,0.0003994153521489352,-0.0023599497508257627 +4,AAPL,2025-08-15,0.0003475308185443282,-0.0051252469420433044 +4,AAPL,2025-08-18,0.00018764416745398194,-0.003027136204764247 +4,AAPL,2025-08-19,-8.77073616720736e-05,-0.0014302554773166776 +4,AAPL,2025-08-20,-0.00026724228519015014,-0.01993192918598652 +4,AAPL,2025-08-21,-0.0005130494246259332,-0.004923439584672451 +4,AAPL,2025-08-22,-0.0006521731265820563,0.012636642903089523 +4,AAPL,2025-08-25,-0.0004916014731861651,-0.002637768629938364 +4,AAPL,2025-08-26,-0.0005567415500991046,0.0094200624153018 +4,AAPL,2025-08-27,-0.0004683113074861467,0.005132819525897503 +4,AAPL,2025-08-28,-0.00036862483830191195,0.008940696716308594 +4,AAPL,2025-08-29,-0.0001533666072646156,-0.0018076964188367128 +4,AAPL,2025-09-02,0.00015676692419219762,-0.010479368269443512 +4,AAPL,2025-09-03,0.00011399647337384522,0.037382371723651886 +4,AAPL,2025-09-04,0.00036542629823088646,0.005478243343532085 +4,AAPL,2025-09-05,0.0003480685409158468,-0.0003753805358428508 +4,AAPL,2025-09-08,0.0003445782349444926,-0.007580039091408253 +4,AAPL,2025-09-09,0.0003420597640797496,-0.014950642362236977 +4,AAPL,2025-09-10,0.00034500143374316394,-0.032791197299957275 +4,AAPL,2025-09-11,0.0002706644299905747,0.014185244217514992 +4,AAPL,2025-09-12,0.0002831979072652757,0.017410414293408394 +4,AAPL,2025-09-15,0.0003376826934982091,0.01117334421724081 +4,AAPL,2025-09-16,0.0003436009574215859,0.006107180844992399 +4,AAPL,2025-09-17,0.00033973544486798346,0.0035210703499615192 +4,AAPL,2025-09-18,0.00033270465792156756,-0.0046554142609238625 +4,AAPL,2025-09-19,0.0003314994100946933,0.031530577689409256 +4,AAPL,2025-09-22,0.00031720224069431424,0.04219288378953934 +4,AAPL,2025-09-23,0.0003311132895760238,-0.006464121397584677 +4,AAPL,2025-09-24,0.0003401946451049298,-0.008367259986698627 +4,AAPL,2025-09-25,0.0003509633243083954,0.01791161298751831 +4,AAPL,2025-09-26,0.0003491909010335803,-0.00550423888489604 +4,AAPL,2025-09-29,0.0003582024364732206,-0.004040114115923643 +4,AAPL,2025-09-30,0.00036857303348369896,0.000785764423198998 +4,AAPL,2025-10-01,0.0003646082477644086,0.003215200500562787 +4,AAPL,2025-10-02,0.0003619490598794073,0.006555081810802221 +4,AAPL,2025-10-03,0.00036063475999981165,0.003455285681411624 +4,AAPL,2025-10-06,0.00035850456333719194,-0.005167905706912279 +4,AAPL,2025-10-07,0.00036217266460880637,-0.0008183880127035081 +4,AAPL,2025-10-08,0.00036376077332533896,0.006141320802271366 +4,AAPL,2025-10-09,0.00034327045432291925,-0.01570037566125393 +4,AAPL,2025-10-10,0.00036717799957841635,-0.035132065415382385 +4,AAPL,2025-10-13,-2.565621616668068e-05,0.009697220288217068 +4,AAPL,2025-10-14,-4.1450098251516465e-06,0.00044403222273103893 +4,AAPL,2025-10-15,2.9421940780594014e-05,0.0063165402971208096 +4,AAPL,2025-10-16,0.00029666503542102873,-0.007608874700963497 +4,AAPL,2025-10-17,0.00031828531064093113,0.019370688125491142 +4,AAPL,2025-10-20,0.00037257923395372927,0.038680825382471085 +4,AAPL,2025-10-21,0.0003399983106646687,0.002019112231209874 +4,AAPL,2025-10-22,0.0003533072886057198,-0.016576780006289482 +4,AAPL,2025-10-23,0.000371373986126855,0.004362503532320261 +4,AAPL,2025-10-24,0.00036199053283780813,0.012404496781527996 +4,AAPL,2025-10-27,0.0003592015418689698,0.022535545751452446 +4,AAPL,2025-10-28,0.00036429084138944745,0.0007064546225592494 +4,AAPL,2025-10-29,0.0003764676512219012,0.002598830033093691 +4,MSFT,2025-01-13,-0.00045460095861926675,-0.004209787119179964 +4,MSFT,2025-01-14,-0.0006211067666299641,-0.003650119761005044 +4,MSFT,2025-01-15,-0.0006223393720574677,0.025275032967329025 +4,MSFT,2025-01-16,-0.00023380355560220778,-0.00406633410602808 +4,MSFT,2025-01-17,-3.21503757731989e-05,0.010426470078527927 +4,MSFT,2025-01-21,0.0002818084030877799,-0.0012361494591459632 +4,MSFT,2025-01-22,0.0003292529727332294,0.04047662392258644 +4,MSFT,2025-01-23,0.0003027183120138943,0.001142349443398416 +4,MSFT,2025-01-24,0.00030875494121573865,-0.0059499843046069145 +4,MSFT,2025-01-27,0.0003147124662064016,-0.021625634282827377 +4,MSFT,2025-01-28,0.0003238973440602422,0.028671851381659508 +4,MSFT,2025-01-29,0.0003285390848759562,-0.010949693620204926 +4,MSFT,2025-01-30,0.00031760084675624967,-0.06380178779363632 +4,MSFT,2025-01-31,-0.00030289962887763977,0.0001686743344180286 +4,MSFT,2025-02-03,-0.0005091031198389828,-0.010024459101259708 +4,MSFT,2025-02-04,-0.0006930141244083643,0.003522339276969433 +4,MSFT,2025-02-05,-0.0006168922991491854,0.002228586468845606 +4,MSFT,2025-02-06,-0.0005510482587851584,0.00610286695882678 +4,MSFT,2025-02-07,-0.00042429662426002324,-0.014705265872180462 +4,MSFT,2025-02-10,-0.0005154787213541567,0.00600996520370245 +4,MSFT,2025-02-11,-0.00040546568925492465,-0.0018938817083835602 +4,MSFT,2025-02-12,-0.00038001060602255166,-0.005850310903042555 +4,MSFT,2025-02-13,-0.0003931397804990411,0.003660434391349554 +4,MSFT,2025-02-14,-0.0002969297638628632,-0.0051528336480259895 +4,MSFT,2025-02-18,-0.00035615480737760663,0.002958151279017329 +4,MSFT,2025-02-19,-0.0002764358650892973,0.012445420026779175 +4,MSFT,2025-02-20,6.837063119746745e-05,0.005276690702885389 +4,MSFT,2025-02-21,0.00032585818553343415,-0.01921594701707363 +4,MSFT,2025-02-24,0.00011560152051970363,-0.010366846807301044 +4,MSFT,2025-02-25,-6.919800216564909e-05,-0.01521420106291771 +4,MSFT,2025-02-26,-0.00032700810697861016,0.004588660318404436 +4,MSFT,2025-02-27,-3.240614023525268e-05,-0.018176421523094177 +4,MSFT,2025-02-28,-0.00014042542898096144,0.011298085562884808 +4,MSFT,2025-03-03,-0.00026799464831128716,-0.0216436218470335 +4,MSFT,2025-03-04,-0.0005977347609587014,0.0003086937067564577 +4,MSFT,2025-03-05,-0.0007155613275244832,0.031435176730155945 +4,MSFT,2025-03-06,-0.0004486485559027642,-0.010352028533816338 +4,MSFT,2025-03-07,-0.00047644556616432965,-0.009061090648174286 +4,MSFT,2025-03-10,-0.0006228827405720949,-0.034005943685770035 +4,MSFT,2025-03-11,-0.00019005165086127818,0.0007626153528690338 +4,MSFT,2025-03-12,8.388053174712695e-06,0.007384896744042635 +4,MSFT,2025-03-13,-0.00011334536247886717,-0.0118106659501791 +4,MSFT,2025-03-14,7.153428305173293e-05,0.025518564507365227 +4,MSFT,2025-03-17,-0.0005025955615565181,0.0003603327786549926 +4,MSFT,2025-03-18,-0.0007806175854057074,-0.013416257686913013 +4,MSFT,2025-03-19,-0.0006386978784576058,0.011149648576974869 +4,MSFT,2025-03-20,-0.0007028862019069493,-0.002530080499127507 +4,MSFT,2025-03-21,-0.0006009805947542191,0.011361085809767246 +4,MSFT,2025-03-24,-0.00035787324304692447,0.004640715196728706 +4,MSFT,2025-03-25,-0.00011611766967689618,0.005277637392282486 +4,MSFT,2025-03-26,0.00018405971059110016,-0.013220925815403461 +4,MSFT,2025-03-27,0.00016565916303079575,0.001562862889841199 +4,MSFT,2025-03-28,0.0002987688931170851,-0.030624257400631905 +4,MSFT,2025-03-31,-0.0004989311564713717,-0.00904276967048645 +4,MSFT,2025-04-01,-0.0006475941627286375,0.0179523304104805 +4,MSFT,2025-04-02,-0.00048398389481008053,-0.00013079818745609373 +4,MSFT,2025-04-03,-0.00040835203253664076,-0.023913966491818428 +4,MSFT,2025-04-04,-0.0007518457714468241,-0.036213699728250504 +4,MSFT,2025-04-07,0.0005773476441390812,-0.005517591722309589 +4,MSFT,2025-04-08,0.0006951670511625707,-0.009264269843697548 +4,MSFT,2025-04-09,0.0010622742120176554,0.09652476012706757 +4,MSFT,2025-04-10,-0.00019250604964327067,-0.023684794083237648 +4,MSFT,2025-04-11,-0.0005899457610212266,0.01844693347811699 +4,MSFT,2025-04-14,-0.0006576675223186612,-0.0016489950940012932 +4,MSFT,2025-04-15,-0.0006107334629632533,-0.005377931520342827 +4,MSFT,2025-04-16,-0.00057931465562433,-0.03729276359081268 +4,MSFT,2025-04-17,-0.0006462793680839241,-0.01035983581095934 +4,MSFT,2025-04-21,-7.159591041272506e-05,-0.023828396573662758 +4,MSFT,2025-04-22,0.0003257693606428802,0.021214628592133522 +4,MSFT,2025-04-23,0.0003037141577806324,0.020426923409104347 +4,MSFT,2025-04-24,1.0422344530525152e-05,0.03390134498476982 +4,MSFT,2025-04-25,-0.0006846366450190544,0.011679773218929768 +4,MSFT,2025-04-28,-0.00043968658428639174,-0.0017626150511205196 +4,MSFT,2025-04-29,-0.0002450663596391678,0.007335787173360586 +4,MSFT,2025-04-30,-0.00014403897512238473,0.003091310616582632 +4,MSFT,2025-05-01,-0.00012407713802531362,0.07348621636629105 +4,MSFT,2025-05-02,-0.00016623591363895684,0.022959541529417038 +4,MSFT,2025-05-05,-0.00016887160018086433,0.0020426157861948013 +4,MSFT,2025-05-06,-0.00023930708994157612,-0.0065787057392299175 +4,MSFT,2025-05-07,-0.0003528945962898433,9.23119077924639e-05 +4,MSFT,2025-05-08,-0.0004920666106045246,0.011061313562095165 +4,MSFT,2025-05-09,-0.000480426853755489,0.0012771347537636757 +4,MSFT,2025-05-12,-0.00038335093995556235,0.02371762879192829 +4,MSFT,2025-05-13,-0.00045492040226235986,-0.00026708311634138227 +4,MSFT,2025-05-14,-0.00044099619844928384,0.008424933068454266 +4,MSFT,2025-05-15,-0.0005255346186459064,0.002253580605611205 +4,MSFT,2025-05-16,-0.0004626282025128603,0.0025126407854259014 +4,MSFT,2025-05-19,-0.0004927876871079206,0.010075254365801811 +4,MSFT,2025-05-20,-0.0002412566391285509,-0.0015265950933098793 +4,MSFT,2025-05-21,-0.00010436490265419707,-0.012297934852540493 +4,MSFT,2025-05-22,-0.0001687699113972485,0.00504722585901618 +4,MSFT,2025-05-23,-7.906388054834679e-05,-0.010342175140976906 +4,MSFT,2025-05-27,-5.2815819799434394e-05,0.023077888414263725 +4,MSFT,2025-05-28,0.00030246563255786896,-0.0072545544244349 +4,MSFT,2025-05-29,0.0003577145398594439,0.0028820389416068792 +4,MSFT,2025-05-30,0.00036656868178397417,0.0036558585707098246 +4,MSFT,2025-06-02,0.0003785679582506418,0.0034912670962512493 +4,MSFT,2025-06-03,0.000370266439858824,0.002162280725315213 +4,MSFT,2025-06-04,0.00037107584648765624,0.0019421163015067577 +4,MSFT,2025-06-05,0.00037063416675664485,0.008179910480976105 +4,MSFT,2025-06-06,0.0003655065956991166,0.0057565439492464066 +4,MSFT,2025-06-09,0.0003588711260817945,0.005025909747928381 +4,MSFT,2025-06-10,0.0003519080055411905,-0.0038785277865827084 +4,MSFT,2025-06-11,0.0003525705251377076,0.003603508695960045 +4,MSFT,2025-06-12,0.00035094350459985435,0.013137471862137318 +4,MSFT,2025-06-13,0.00033688783878460526,-0.008198597468435764 +4,MSFT,2025-06-16,0.0003607508260756731,0.008762250654399395 +4,MSFT,2025-06-17,0.000355255528120324,-0.0022984726820141077 +4,MSFT,2025-06-18,0.00036598730366677046,0.004591610282659531 +4,MSFT,2025-06-20,0.00036485743476077914,-0.005931285209953785 +4,MSFT,2025-06-23,0.0003794944495894015,0.017853928729891777 +4,MSFT,2025-06-24,0.00036686655948869884,0.008421151898801327 +4,MSFT,2025-06-25,0.00036614754935726523,0.00439755292609334 +4,MSFT,2025-06-26,0.0003575625305529684,0.010467752814292908 +4,MSFT,2025-06-27,0.0003496554563753307,-0.003040122799575329 +4,MSFT,2025-06-30,0.00035746803041547537,0.002959668170660734 +4,MSFT,2025-07-01,0.00035455398028716445,-0.010834317654371262 +4,MSFT,2025-07-02,0.00036575208650901914,-0.0019529267447069287 +4,MSFT,2025-07-03,0.00036496733082458377,0.015658017247915268 +4,MSFT,2025-07-07,0.00034131694701500237,-0.0022477121092379093 +4,MSFT,2025-07-08,0.0003475744160823524,-0.0022125132381916046 +4,MSFT,2025-07-09,0.00034735974622890353,0.013778460212051868 +4,MSFT,2025-07-10,0.00034125943784601986,-0.004039912484586239 +4,MSFT,2025-07-11,0.0003451657248660922,0.003662464441731572 +4,MSFT,2025-07-14,0.00033727713162079453,-0.0005963115836493671 +4,MSFT,2025-07-15,0.0003462658205535263,0.005551044829189777 +4,MSFT,2025-07-16,0.00033612261177040637,-0.00039555682451464236 +4,MSFT,2025-07-17,0.0003311675973236561,0.011953135952353477 +4,MSFT,2025-07-18,0.0003242352686356753,-0.0032297703437507153 +4,MSFT,2025-07-21,0.0003287301224190742,1.9661010810523294e-05 +4,MSFT,2025-07-22,0.000322115229209885,-0.009435489773750305 +4,MSFT,2025-07-23,0.00032856373582035303,0.0011867793509736657 +4,MSFT,2025-07-24,0.0003216057375539094,0.009855084121227264 +4,MSFT,2025-07-25,0.0003046165220439434,0.005524198990315199 +4,MSFT,2025-07-28,0.0003040413139387965,-0.0023581874556839466 +4,MSFT,2025-07-29,0.000307296373648569,0.00013654098438564688 +4,MSFT,2025-07-30,0.00030548960785381496,0.0013063097139820457 +4,MSFT,2025-07-31,0.0003025323967449367,0.03871544450521469 +4,MSFT,2025-08-01,0.00032487930729985237,-0.017757408320903778 +4,MSFT,2025-08-04,0.0003296597278676927,0.021760638803243637 +4,MSFT,2025-08-05,0.0003298897936474532,-0.014839678071439266 +4,MSFT,2025-08-06,0.000351223920006305,-0.005338692106306553 +4,MSFT,2025-08-07,0.00036339371581561863,-0.007840949110686779 +4,MSFT,2025-08-08,0.00035325976205058396,0.002301202155649662 +4,MSFT,2025-08-11,0.0003572605492081493,-0.0005173797253519297 +4,MSFT,2025-08-12,0.00035033439053222537,0.014215180650353432 +4,MSFT,2025-08-13,0.0003413796075619757,-0.01649831049144268 +4,MSFT,2025-08-14,0.00034894258715212345,0.0036430221516638994 +4,MSFT,2025-08-15,0.00034678864176385105,-0.004431127104908228 +4,MSFT,2025-08-18,0.0003477993595879525,-0.005919247400015593 +4,MSFT,2025-08-19,0.000328356254613027,-0.014276749454438686 +4,MSFT,2025-08-20,0.0002877865044865757,-0.007976380176842213 +4,MSFT,2025-08-21,0.00027339288499206305,-0.00128835067152977 +4,MSFT,2025-08-22,0.0002595282858237624,0.005912343040108681 +4,MSFT,2025-08-25,0.00029428943525999784,-0.005872572772204876 +4,MSFT,2025-08-26,0.00027455255622044206,-0.0044122012332081795 +4,MSFT,2025-08-27,0.0002773012383840978,0.009318231604993343 +4,MSFT,2025-08-28,0.0003128584648948163,0.00570659339427948 +4,MSFT,2025-08-29,0.00031812163069844246,-0.005805262364447117 +4,MSFT,2025-09-02,0.00030036919633857906,-0.00310341315343976 +4,MSFT,2025-09-03,0.0003091319231316447,0.0004552818136289716 +4,MSFT,2025-09-04,0.00031964591471478343,0.005171140655875206 +4,MSFT,2025-09-05,0.0003128420212306082,-0.025864610448479652 +4,MSFT,2025-09-08,0.0002882672124542296,0.0064437976107001305 +4,MSFT,2025-09-09,0.000306497240671888,0.0004214302753098309 +4,MSFT,2025-09-10,0.0003058162401430309,0.003924787975847721 +4,MSFT,2025-09-11,0.000311747076921165,0.001278264564462006 +4,MSFT,2025-09-12,0.00030645719380117953,0.017588553950190544 +4,MSFT,2025-09-15,0.00028558631311170757,0.010651038959622383 +4,MSFT,2025-09-16,0.000368572655133903,-0.012339060194790363 +4,MSFT,2025-09-17,0.00038567796582356095,0.0019233089406043291 +4,MSFT,2025-09-18,0.0003935172571800649,-0.003082998562604189 +4,MSFT,2025-09-19,0.0003766173904296011,0.018473176285624504 +4,MSFT,2025-09-22,0.0004214303335174918,-0.006741669960319996 +4,MSFT,2025-09-23,0.00041211090865544975,-0.010198557749390602 +4,MSFT,2025-09-24,0.0003603327786549926,0.0018049085047096014 +4,MSFT,2025-09-25,0.00033637118758633733,-0.006134580820798874 +4,MSFT,2025-09-26,0.0002784013340715319,0.008699106983840466 +4,MSFT,2025-09-29,0.0003229246358387172,0.006120520178228617 +4,MSFT,2025-09-30,0.0003746791335288435,0.00648893415927887 +4,MSFT,2025-10-01,0.0004228539764881134,0.0033922079019248486 +4,MSFT,2025-10-02,0.0004411066183820367,-0.007668304722756147 +4,MSFT,2025-10-03,0.0003778314858209342,0.003116838401183486 +4,MSFT,2025-10-06,0.00037415834958665073,0.021455787122249603 +4,MSFT,2025-10-07,0.00039930734783411026,-0.008721815422177315 +4,MSFT,2025-10-08,0.00034565877285785973,0.0016589481383562088 +4,MSFT,2025-10-09,0.00034360753488726914,-0.004678791388869286 +4,MSFT,2025-10-10,0.00030593539122492075,-0.02214234322309494 +4,MSFT,2025-10-13,0.00029803242068737745,0.0060292938724160194 +4,MSFT,2025-10-14,0.000295330974040553,-0.000934337789658457 +4,MSFT,2025-10-15,0.0002961321733891964,-0.00027254014275968075 +4,MSFT,2025-10-16,0.000294264784315601,-0.003551118541508913 +4,MSFT,2025-10-17,0.0002957377291750163,0.0038432723376899958 +4,MSFT,2025-10-20,0.0002822439419105649,0.006230654660612345 +4,MSFT,2025-10-21,0.0002539466950111091,0.001682128058746457 +4,MSFT,2025-10-22,0.0002523494476918131,0.005547964945435524 +4,MSFT,2025-10-23,0.00028241341351531446,3.858399577438831e-05 +4,MSFT,2025-10-24,0.0003309775493107736,0.00584189360961318 +4,MSFT,2025-10-27,0.00039268319960683584,0.014993829652667046 +4,MSFT,2025-10-28,0.00044759828597307205,0.019654160365462303 +4,MSFT,2025-10-29,0.00043563186773099005,-0.000959739089012146 +4,NVDA,2025-01-13,0.0002199933514930308,-0.0199159923940897 +4,NVDA,2025-01-14,-0.0005307477549649775,-0.011095074005424976 +4,NVDA,2025-01-15,-0.0007576910429634154,0.0334361307322979 +4,NVDA,2025-01-16,-0.00036786904092878103,-0.01979244500398636 +4,NVDA,2025-01-17,-0.0004183602868579328,0.030524292960762978 +4,NVDA,2025-01-21,0.0001747932838043198,0.02240353263914585 +4,NVDA,2025-01-22,0.0005466146976687014,0.0433553010225296 +4,NVDA,2025-01-23,0.000613706128206104,0.001019429531879723 +4,NVDA,2025-01-24,0.0006030691438354552,-0.031744521111249924 +4,NVDA,2025-01-27,0.0006303985137492418,-0.18594606220722198 +4,NVDA,2025-01-28,-0.0009788933675736189,0.08549726009368896 +4,NVDA,2025-01-29,-0.0012142694322392344,-0.04187554866075516 +4,NVDA,2025-01-30,0.0005502240383066237,0.007650486659258604 +4,NVDA,2025-01-31,0.0009340838296338916,-0.037434935569763184 +4,NVDA,2025-02-03,0.00247830874286592,-0.028811121359467506 +4,NVDA,2025-02-04,0.0036806692369282246,0.01691417768597603 +4,NVDA,2025-02-05,0.003572731511667371,0.05077483132481575 +4,NVDA,2025-02-06,0.0021683326922357082,0.03037567436695099 +4,NVDA,2025-02-07,0.000979874050244689,0.008974412456154823 +4,NVDA,2025-02-10,-0.0001468013651901856,0.028322793543338776 +4,NVDA,2025-02-11,-0.0013977595372125506,-0.005781279411166906 +4,NVDA,2025-02-12,-0.001424226793460548,-0.012578953057527542 +4,NVDA,2025-02-13,-0.0014129403280094266,0.031155191361904144 +4,NVDA,2025-02-14,-0.0007573014008812606,0.025973565876483917 +4,NVDA,2025-02-18,-0.0005470749456435442,0.003953279461711645 +4,NVDA,2025-02-19,-0.0005355533212423325,-0.0012202010257169604 +4,NVDA,2025-02-20,-0.0006219666684046388,0.0063005127012729645 +4,NVDA,2025-02-21,-0.00046047900104895234,-0.041384171694517136 +4,NVDA,2025-02-24,-0.0008993993396870792,-0.031357541680336 +4,NVDA,2025-02-25,-0.0013842331245541573,-0.028416689485311508 +4,NVDA,2025-02-26,-0.0006027594790793955,0.03606312349438667 +4,NVDA,2025-02-27,-0.0012816337402909994,-0.0885915532708168 +4,NVDA,2025-02-28,0.0011246156645938754,0.03893262892961502 +4,NVDA,2025-03-03,0.0009724511182866991,-0.09094896167516708 +4,NVDA,2025-03-04,0.002423382829874754,0.016779374331235886 +4,NVDA,2025-03-05,0.002486185170710087,0.011230823583900928 +4,NVDA,2025-03-06,0.0024091496597975492,-0.059085942804813385 +4,NVDA,2025-03-07,0.00404225941747427,0.01899186335504055 +4,NVDA,2025-03-10,0.004056990146636963,-0.05199885368347168 +4,NVDA,2025-03-11,0.005591536406427622,0.01650184392929077 +4,NVDA,2025-03-12,0.0053296335972845554,0.062294550240039825 +4,NVDA,2025-03-13,0.003983912989497185,-0.0013833539560437202 +4,NVDA,2025-03-14,0.0033758620265871286,0.05134950578212738 +4,NVDA,2025-03-17,0.0011794870952144265,-0.017745042219758034 +4,NVDA,2025-03-18,0.0010471554705873132,-0.034903090447187424 +4,NVDA,2025-03-19,0.0010842352639883757,0.017944173887372017 +4,NVDA,2025-03-20,0.0004396408039610833,0.008557597175240517 +4,NVDA,2025-03-21,-0.00041399424662813544,-0.007027110550552607 +4,NVDA,2025-03-24,-0.0008317460888065398,0.031034322455525398 +4,NVDA,2025-03-25,-0.0010608775774016976,-0.0059480504132807255 +4,NVDA,2025-03-26,-0.0008228248334489763,-0.05913425609469414 +4,NVDA,2025-03-27,-0.001223872066475451,-0.020694417878985405 +4,NVDA,2025-03-28,-0.0006287599680945277,-0.015920743346214294 +4,NVDA,2025-03-31,-8.888060983736068e-05,-0.01183226890861988 +4,NVDA,2025-04-01,0.0004652836068999022,0.016199588775634766 +4,NVDA,2025-04-02,0.00034085309016518295,0.002448071027174592 +4,NVDA,2025-04-03,0.00011878874647663906,-0.08128099143505096 +4,NVDA,2025-04-04,0.0014135220553725958,-0.07642299681901932 +4,NVDA,2025-04-07,0.004380129277706146,0.0346999429166317 +4,NVDA,2025-04-08,0.004801379516720772,-0.013818793930113316 +4,NVDA,2025-04-09,0.005436648149043322,0.1716206818819046 +4,NVDA,2025-04-10,0.0013257721439003944,-0.06094729155302048 +4,NVDA,2025-04-11,0.0012824892764911056,0.03075767122209072 +4,NVDA,2025-04-14,0.0011470726458355784,-0.0019852372352033854 +4,NVDA,2025-04-15,0.0011015139752998948,0.013368756510317326 +4,NVDA,2025-04-16,0.0004240665293764323,-0.07119163125753403 +4,NVDA,2025-04-17,0.0011241130996495485,-0.029131049290299416 +4,NVDA,2025-04-21,0.0013655577786266804,-0.04617750644683838 +4,NVDA,2025-04-22,0.0019628694280982018,0.020225301384925842 +4,NVDA,2025-04-23,0.0022275822702795267,0.03790133818984032 +4,NVDA,2025-04-24,0.0015603125793859363,0.03557804971933365 +4,NVDA,2025-04-25,0.0010627082083374262,0.04213288798928261 +4,NVDA,2025-04-28,0.00012540789612103254,-0.020752545446157455 +4,NVDA,2025-04-29,-0.0001894132437882945,0.0026634882669895887 +4,NVDA,2025-04-30,-0.000388911459594965,-0.0009176938910968602 +4,NVDA,2025-05-01,-0.0006082426989451051,0.0243971049785614 +4,NVDA,2025-05-02,-0.000946629501413554,0.025564171373844147 +4,NVDA,2025-05-05,-0.0010267606703564525,-0.005956621374934912 +4,NVDA,2025-05-06,-0.0007330327061936259,-0.00246300152502954 +4,NVDA,2025-05-07,-0.0005861104000359774,0.030531374737620354 +4,NVDA,2025-05-08,-0.0004591801844071597,0.002644749591127038 +4,NVDA,2025-05-09,-0.00033890584018081427,-0.006153288763016462 +4,NVDA,2025-05-12,-3.581529381335713e-05,0.05300632491707802 +4,NVDA,2025-05-13,3.776821176870726e-05,0.05481155589222908 +4,NVDA,2025-05-14,0.00019086073734797537,0.040794216096401215 +4,NVDA,2025-05-15,-5.657535803038627e-05,-0.0037754520308226347 +4,NVDA,2025-05-16,-0.00020008879073429853,0.004218720365315676 +4,NVDA,2025-05-19,-0.0005163009627722204,0.001254804665222764 +4,NVDA,2025-05-20,-0.00034243895788677037,-0.008816764689981937 +4,NVDA,2025-05-21,-0.0004358413571026176,-0.019385842606425285 +4,NVDA,2025-05-22,-0.0007400255417451262,0.0077844224870204926 +4,NVDA,2025-05-23,-0.0008179552969522774,-0.011661475524306297 +4,NVDA,2025-05-27,-0.0007902946672402322,0.03156297281384468 +4,NVDA,2025-05-28,-0.0007185671129263937,-0.00510519789531827 +4,NVDA,2025-05-29,-0.0006139479810371995,0.03197352960705757 +4,NVDA,2025-05-30,-0.00036308419657871127,-0.0296025387942791 +4,NVDA,2025-06-02,-0.0006970014073885977,0.016513347625732422 +4,NVDA,2025-06-03,-0.0003097544249612838,0.027568254619836807 +4,NVDA,2025-06-04,5.805016553495079e-05,0.004944560583680868 +4,NVDA,2025-06-05,0.000561279826797545,-0.013692475855350494 +4,NVDA,2025-06-06,0.0004160685639362782,0.01228222157806158 +4,NVDA,2025-06-09,0.0007079329807311296,0.006400659680366516 +4,NVDA,2025-06-10,0.0007464997470378876,0.0092815225943923 +4,NVDA,2025-06-11,0.0007063443190418184,-0.007810831535607576 +4,NVDA,2025-06-12,0.0007126011187210679,0.015078527852892876 +4,NVDA,2025-06-13,0.0007014371221885085,-0.021117979660630226 +4,NVDA,2025-06-16,0.0007178923115134239,0.018977774307131767 +4,NVDA,2025-06-17,0.0007359418668784201,-0.0039473604410886765 +4,NVDA,2025-06-18,0.0007154904888011515,0.009392502717673779 +4,NVDA,2025-06-20,0.0007414005813188851,-0.011267573572695255 +4,NVDA,2025-06-23,0.0007293914095498621,0.0022220024839043617 +4,NVDA,2025-06-24,0.0007381874602288008,0.025543199852108955 +4,NVDA,2025-06-25,0.0007508817943744361,0.04242729768157005 +4,NVDA,2025-06-26,0.0007119818474166095,0.00459060724824667 +4,NVDA,2025-06-27,0.0007232079515233636,0.017457233741879463 +4,NVDA,2025-06-30,0.0007377470028586686,0.0015202657086774707 +4,NVDA,2025-07-01,0.000775833788793534,-0.030134854838252068 +4,NVDA,2025-07-02,0.0007297734846360981,0.025440121069550514 +4,NVDA,2025-07-03,0.0007500065257772803,0.013203286565840244 +4,NVDA,2025-07-07,0.0007325197802856565,-0.0069274441339075565 +4,NVDA,2025-07-08,0.0007092487066984177,0.011061049066483974 +4,NVDA,2025-07-09,0.0007310629007406533,0.017839858308434486 +4,NVDA,2025-07-10,0.0007347258506342769,0.007462398149073124 +4,NVDA,2025-07-11,0.0007416622247546911,0.004984412807971239 +4,NVDA,2025-07-14,0.0007212259224615991,-0.005167294759303331 +4,NVDA,2025-07-15,0.0006753708003088832,0.039614394307136536 +4,NVDA,2025-07-16,0.0007128439610823989,0.0039173574186861515 +4,NVDA,2025-07-17,0.0007472620927728713,0.009466668590903282 +4,NVDA,2025-07-18,0.000751412590034306,-0.003416249994188547 +4,NVDA,2025-07-21,0.0007537033525295556,-0.005992021411657333 +4,NVDA,2025-07-22,0.0007530257571488619,-0.025709928944706917 +4,NVDA,2025-07-23,0.0006837451946921647,0.022202732041478157 +4,NVDA,2025-07-24,0.0007111950544640422,0.017183879390358925 +4,NVDA,2025-07-25,0.000676321389619261,-0.0013824420748278499 +4,NVDA,2025-07-28,0.0006675798795185983,0.01855873130261898 +4,NVDA,2025-07-29,0.0006364764994941652,-0.007040409371256828 +4,NVDA,2025-07-30,0.0006550869438797235,0.021197235211730003 +4,NVDA,2025-07-31,0.0006253726896829903,-0.007840156555175781 +4,NVDA,2025-08-01,0.0006620402564294636,-0.023608168587088585 +4,NVDA,2025-08-04,0.0006647432455793023,0.035511985421180725 +4,NVDA,2025-08-05,0.0006892189849168062,-0.009713695384562016 +4,NVDA,2025-08-06,0.0006649371352978051,0.006486212834715843 +4,NVDA,2025-08-07,0.0006973600247874856,0.007496170699596405 +4,NVDA,2025-08-08,0.0006740004755556583,0.010619938373565674 +4,NVDA,2025-08-11,0.0006371597992256284,-0.003509139409288764 +4,NVDA,2025-08-12,0.000647776061668992,0.006023808848112822 +4,NVDA,2025-08-13,0.0006459144060499966,-0.00860871747136116 +4,NVDA,2025-08-14,0.0006644985405728221,0.00236517284065485 +4,NVDA,2025-08-15,0.0006672523450106382,-0.008662868291139603 +4,NVDA,2025-08-18,0.000673633418045938,0.008607884868979454 +4,NVDA,2025-08-19,0.00066172587685287,-0.035625096410512924 +4,NVDA,2025-08-20,0.00028889175155200064,-0.0013673901557922363 +4,NVDA,2025-08-21,0.00033800891833379865,-0.0023975283838808537 +4,NVDA,2025-08-22,0.00020283980120439082,0.0170556902885437 +4,NVDA,2025-08-25,0.0005771948490291834,0.010173550806939602 +4,NVDA,2025-08-26,0.0006388218607753515,0.010841353796422482 +4,NVDA,2025-08-27,0.0005859193624928594,-0.0009356600930914283 +4,NVDA,2025-08-28,0.000585524074267596,-0.007905716076493263 +4,NVDA,2025-08-29,0.0005897743394598365,-0.033811647444963455 +4,NVDA,2025-09-02,0.000564453424885869,-0.01971297897398472 +4,NVDA,2025-09-03,0.00012536931899376214,-0.0009372442145831883 +4,NVDA,2025-09-04,-0.0003095002903137356,0.006076844874769449 +4,NVDA,2025-09-05,-0.0004315346304792911,-0.027402250096201897 +4,NVDA,2025-09-08,-0.0007721924339421093,0.007694043219089508 +4,NVDA,2025-09-09,-0.0006876011611893773,0.014451487921178341 +4,NVDA,2025-09-10,-0.00041104372940026224,0.03775344416499138 +4,NVDA,2025-09-11,0.0005304644582793117,-0.0008464691927656531 +4,NVDA,2025-09-12,0.0006279401713982224,0.003662239294499159 +4,NVDA,2025-09-15,0.0006004018941894174,-0.0003938477602787316 +4,NVDA,2025-09-16,0.0005943389842286706,-0.0162779800593853 +4,NVDA,2025-09-17,0.0006078426958993077,-0.026597240939736366 +4,NVDA,2025-09-18,0.0006083847838453948,0.03434396907687187 +4,NVDA,2025-09-19,0.0005700683686882257,0.002436745911836624 +4,NVDA,2025-09-22,0.0005663865595124662,0.03853048384189606 +4,NVDA,2025-09-23,0.000545613351278007,-0.028617653995752335 +4,NVDA,2025-09-24,0.0005739873740822077,-0.008216168731451035 +4,NVDA,2025-09-25,0.0005751092103309929,0.004060334526002407 +4,NVDA,2025-09-26,0.000571209064219147,0.0028099152259528637 +4,NVDA,2025-09-29,0.0005654623382724822,0.02033175528049469 +4,NVDA,2025-09-30,0.0005604798789136112,0.025677895173430443 +4,NVDA,2025-10-01,0.0006852247170172632,0.0035312240943312645 +4,NVDA,2025-10-02,0.0007237914833240211,0.008773564361035824 +4,NVDA,2025-10-03,0.0007323409663513303,-0.006746300030499697 +4,NVDA,2025-10-06,0.0007195675862021744,-0.01114804670214653 +4,NVDA,2025-10-07,0.0006813848158344626,-0.002698535332456231 +4,NVDA,2025-10-08,0.0006333367782644928,0.021756859496235847 +4,NVDA,2025-10-09,0.0006752089248038828,0.018130889162421227 +4,NVDA,2025-10-10,0.0006689106812700629,-0.05009961873292923 +4,NVDA,2025-10-13,0.0006096478318795562,0.027782635763287544 +4,NVDA,2025-10-14,0.0006045505288057029,-0.04501927271485329 +4,NVDA,2025-10-15,0.0004719545249827206,-0.0011115006636828184 +4,NVDA,2025-10-16,0.00016522547230124474,0.01095014251768589 +4,NVDA,2025-10-17,0.00042542556184343994,0.0077255102805793285 +4,NVDA,2025-10-20,0.00046311705955304205,-0.003170659299939871 +4,NVDA,2025-10-21,0.0005170642398297787,-0.008136321790516376 +4,NVDA,2025-10-22,0.0004636911617126316,-0.004869487602263689 +4,NVDA,2025-10-23,0.0004928275593556464,0.010374246165156364 +4,NVDA,2025-10-24,0.0005692740669474006,0.022258097305893898 +4,NVDA,2025-10-27,0.0005219620070420206,0.027692146599292755 +4,NVDA,2025-10-28,0.0004994947230443358,0.04861848056316376 +4,NVDA,2025-10-29,0.0006003510789014399,0.02945788763463497 +4,TSLA,2025-01-13,-0.0006426096661016345,0.02147819474339485 +4,TSLA,2025-01-14,-0.00048530171625316143,-0.017382638528943062 +4,TSLA,2025-01-15,-0.000565372291021049,0.07731423527002335 +4,TSLA,2025-01-16,0.0003633236628957093,-0.03420596942305565 +4,TSLA,2025-01-17,0.00017668191867414862,0.03018125332891941 +4,TSLA,2025-01-21,0.000736369111109525,-0.005713813938200474 +4,TSLA,2025-01-22,0.0008310045814141631,-0.02135504223406315 +4,TSLA,2025-01-23,0.0007725456380285323,-0.006598243955522776 +4,TSLA,2025-01-24,0.0003259119112044573,-0.01416458748281002 +4,TSLA,2025-01-27,-0.00025133430608548224,-0.023466648533940315 +4,TSLA,2025-01-28,-0.0006571677513420582,0.0023640734143555164 +4,TSLA,2025-01-29,-0.0004683138686232269,-0.02284170500934124 +4,TSLA,2025-01-30,-0.0006385775050148368,0.028327902778983116 +4,TSLA,2025-01-31,9.28601948544383e-05,0.01073464099317789 +4,TSLA,2025-02-03,0.0004496453911997378,-0.053090088069438934 +4,TSLA,2025-02-04,-0.0004918520571663976,0.021988535299897194 +4,TSLA,2025-02-05,-3.965393625549041e-05,-0.036453522741794586 +4,TSLA,2025-02-06,-0.0004772191750817001,-0.01023279968649149 +4,TSLA,2025-02-07,-0.0004727087216451764,-0.03451714292168617 +4,TSLA,2025-02-10,-0.0009449930512346327,-0.030577193945646286 +4,TSLA,2025-02-11,-0.001275869202800095,-0.06547988951206207 +4,TSLA,2025-02-12,-0.0010830715764313936,0.02409105747938156 +4,TSLA,2025-02-13,-0.0011466438882052898,0.056134287267923355 +4,TSLA,2025-02-14,-0.0012482875026762486,-0.00028100283816456795 +4,TSLA,2025-02-18,-0.0010895380983129144,-0.004873622674494982 +4,TSLA,2025-02-19,-0.0008082336280494928,0.018050814047455788 +4,TSLA,2025-02-20,-0.00046300108078867197,-0.017232170328497887 +4,TSLA,2025-02-21,-0.00034781702561303973,-0.04797223210334778 +4,TSLA,2025-02-24,-0.0009179326589219272,-0.021756544709205627 +4,TSLA,2025-02-25,-0.001328253885731101,-0.0876249372959137 +4,TSLA,2025-02-26,-0.0004180235555395484,-0.04043677821755409 +4,TSLA,2025-02-27,0.00039778888458386064,-0.030905907973647118 +4,TSLA,2025-02-28,0.0013224141439422965,0.03837459161877632 +4,TSLA,2025-03-03,0.0009447652264498174,-0.02884405106306076 +4,TSLA,2025-03-04,0.0008418228826485574,-0.045311182737350464 +4,TSLA,2025-03-05,0.0013356393901631236,0.025621017441153526 +4,TSLA,2025-03-06,0.001075591892004013,-0.05770651996135712 +4,TSLA,2025-03-07,0.001444040797650814,-0.0029651003424078226 +4,TSLA,2025-03-10,0.0015121190808713436,-0.16754573583602905 +4,TSLA,2025-03-11,0.005339965224266052,0.03724507987499237 +4,TSLA,2025-03-12,0.005587236490100622,0.07319368422031403 +4,TSLA,2025-03-13,0.004515998065471649,-0.030323348939418793 +4,TSLA,2025-03-14,0.004891623742878437,0.037912677973508835 +4,TSLA,2025-03-17,0.0033205102663487196,-0.049068231135606766 +4,TSLA,2025-03-18,0.003430943703278899,-0.054835446178913116 +4,TSLA,2025-03-19,0.004308911971747875,0.045761190354824066 +4,TSLA,2025-03-20,0.0029629170894622803,0.0016944590024650097 +4,TSLA,2025-03-21,0.002017838414758444,0.05135471746325493 +4,TSLA,2025-03-24,0.001316731795668602,0.11273548007011414 +4,TSLA,2025-03-25,-0.0001605950528755784,0.03442346304655075 +4,TSLA,2025-03-26,-0.0016091944416984916,-0.0574239045381546 +4,TSLA,2025-03-27,-0.0015530530363321304,0.00392526900395751 +4,TSLA,2025-03-28,-0.0013428255915641785,-0.0357048325240612 +4,TSLA,2025-03-31,-0.0015352492919191718,-0.016797412186861038 +4,TSLA,2025-04-01,-0.001117404201067984,0.03525624796748161 +4,TSLA,2025-04-02,-0.001527798012830317,0.05189662054181099 +4,TSLA,2025-04-03,-0.0011355264578014612,-0.056301724165678024 +4,TSLA,2025-04-04,-0.001553828245960176,-0.1100357323884964 +4,TSLA,2025-04-07,0.0012941649183630943,-0.025978781282901764 +4,TSLA,2025-04-08,0.0016250592889264226,-0.05023572966456413 +4,TSLA,2025-04-09,0.0026419400237500668,0.2044905722141266 +4,TSLA,2025-04-10,0.00023616652470082045,-0.0755220279097557 +4,TSLA,2025-04-11,3.6089797504246235e-05,-0.00035662594018504024 +4,TSLA,2025-04-14,-4.1118131775874645e-05,0.00015855641686357558 +4,TSLA,2025-04-15,9.975052671507001e-05,0.006950209382921457 +4,TSLA,2025-04-16,-0.0004140480305068195,-0.05069074407219887 +4,TSLA,2025-04-17,-0.00024418332031928003,-0.0007454979349859059 +4,TSLA,2025-04-21,0.0001363961782772094,-0.059180762618780136 +4,TSLA,2025-04-22,0.0008329912088811398,0.044994380325078964 +4,TSLA,2025-04-23,0.0007650795741938055,0.052271947264671326 +4,TSLA,2025-04-24,-0.00019789120415225625,0.03437870740890503 +4,TSLA,2025-04-25,-0.0013803121400997043,0.09351850301027298 +4,TSLA,2025-04-28,-0.0006249350844882429,0.0032583903521299362 +4,TSLA,2025-04-29,-0.00038059367216192186,0.021284373477101326 +4,TSLA,2025-04-30,-0.0002675855066627264,-0.03438223525881767 +4,TSLA,2025-05-01,-0.0006262950482778251,-0.005829314235597849 +4,TSLA,2025-05-02,-0.0009216226171702147,0.023568641394376755 +4,TSLA,2025-05-05,-0.0006499601295217872,-0.024495847523212433 +4,TSLA,2025-05-06,-0.000793136132415384,-0.01767474040389061 +4,TSLA,2025-05-07,-0.0008818944334052503,0.003154616104438901 +4,TSLA,2025-05-08,-0.0009752175537869334,0.03065977431833744 +4,TSLA,2025-05-09,-0.0006278657237999141,0.046108197420835495 +4,TSLA,2025-05-12,-2.767972728179302e-05,0.06528002768754959 +4,TSLA,2025-05-13,-1.2786194020009134e-05,0.048104915767908096 +4,TSLA,2025-05-14,0.00022542872466146946,0.039931923151016235 +4,TSLA,2025-05-15,-1.168464859802043e-05,-0.014076946303248405 +4,TSLA,2025-05-16,-0.00014346442185342312,0.020670490339398384 +4,TSLA,2025-05-19,-0.00023522363335359842,-0.022802190855145454 +4,TSLA,2025-05-20,-0.0002652736147865653,0.005044436082243919 +4,TSLA,2025-05-21,-0.00023353505821432918,-0.0271227415651083 +4,TSLA,2025-05-22,-0.0004639167455025017,0.019004251807928085 +4,TSLA,2025-05-23,-0.0004172801272943616,-0.004997253883630037 +4,TSLA,2025-05-27,-0.00031278515234589577,0.0670972540974617 +4,TSLA,2025-05-28,-0.0002055906952591613,-0.016644185408949852 +4,TSLA,2025-05-29,-0.00032627113978378475,0.004277748987078667 +4,TSLA,2025-05-30,-0.00027339468942955136,-0.03396601602435112 +4,TSLA,2025-06-02,-0.0007755430997349322,-0.010941091924905777 +4,TSLA,2025-06-03,-0.0007687117322348058,0.004599945619702339 +4,TSLA,2025-06-04,-0.0010328651405870914,-0.03614067658782005 +4,TSLA,2025-06-05,-0.0012185549130663276,-0.15384948253631592 +4,TSLA,2025-06-06,-0.0006638450431637466,0.03601383417844772 +4,TSLA,2025-06-09,-0.0013082833029329777,0.044531211256980896 +4,TSLA,2025-06-10,-0.001224704086780548,0.05519232153892517 +4,TSLA,2025-06-11,-0.00048646898358128965,0.001042102579958737 +4,TSLA,2025-06-12,-2.2842898033559322e-05,-0.022679682821035385 +4,TSLA,2025-06-13,7.787827053107321e-05,0.01924274116754532 +4,TSLA,2025-06-16,0.0005516516976058483,0.011674257926642895 +4,TSLA,2025-06-17,0.0008127883193083107,-0.03960360959172249 +4,TSLA,2025-06-18,0.00019347028865013272,0.017857560887932777 +4,TSLA,2025-06-20,0.00049282779218629,0.0003415528335608542 +4,TSLA,2025-06-23,0.0006529213860630989,0.07910624891519547 +4,TSLA,2025-06-24,0.0008878407534211874,-0.023827554658055305 +4,TSLA,2025-06-25,0.0009041032753884792,-0.03868634253740311 +4,TSLA,2025-06-26,0.0008754381560720503,-0.005418374668806791 +4,TSLA,2025-06-27,0.0008738402393646538,-0.006621400360018015 +4,TSLA,2025-06-30,0.0008477158844470978,-0.018619263544678688 +4,TSLA,2025-07-01,0.0007552291499450803,-0.054835326969623566 +4,TSLA,2025-07-02,6.219597707968205e-05,0.04848766699433327 +4,TSLA,2025-07-03,0.0007373006665147841,-0.0009508330258540809 +4,TSLA,2025-07-07,0.0007567409193143249,-0.07030747830867767 +4,TSLA,2025-07-08,-3.641049625002779e-05,0.013080017641186714 +4,TSLA,2025-07-09,0.00015648691623937339,-0.0065017081797122955 +4,TSLA,2025-07-10,9.757462976267561e-05,0.046198856085538864 +4,TSLA,2025-07-11,0.0007476633763872087,0.011678449809551239 +4,TSLA,2025-07-14,0.0008162516169250011,0.010754958726465702 +4,TSLA,2025-07-15,0.0008344837697222829,-0.019500985741615295 +4,TSLA,2025-07-16,0.00084402144420892,0.03444095328450203 +4,TSLA,2025-07-17,0.0007577540818601847,-0.0070506613701581955 +4,TSLA,2025-07-18,0.0007426792290061712,0.031555913388729095 +4,TSLA,2025-07-21,0.0007168540614657104,-0.0035251006484031677 +4,TSLA,2025-07-22,0.0007301134173758328,0.010959829203784466 +4,TSLA,2025-07-23,0.0007211696356534958,0.0013540922664105892 +4,TSLA,2025-07-24,0.0007182502886280417,-0.08552543073892593 +4,TSLA,2025-07-25,0.0007916776230558753,0.034637201577425 +4,TSLA,2025-07-28,0.000785410578828305,0.02970684878528118 +4,TSLA,2025-07-29,0.0007408977253362536,-0.013574890792369843 +4,TSLA,2025-07-30,0.0007575138006359339,-0.006747506558895111 +4,TSLA,2025-07-31,0.0007596103823743761,-0.03434052690863609 +4,TSLA,2025-08-01,0.0007164914277382195,-0.018465032801032066 +4,TSLA,2025-08-04,0.0007015480659902096,0.021671423688530922 +4,TSLA,2025-08-05,0.0007561856182292104,-0.001747657428495586 +4,TSLA,2025-08-06,0.000751360144931823,0.035604994744062424 +4,TSLA,2025-08-07,0.0006870239740237594,0.007349951192736626 +4,TSLA,2025-08-08,0.0006686172564513981,0.022641798481345177 +4,TSLA,2025-08-11,0.000663882412482053,0.028057128190994263 +4,TSLA,2025-08-12,0.0007451429846696556,0.005324552766978741 +4,TSLA,2025-08-13,0.0007895606104284525,-0.004292710218578577 +4,TSLA,2025-08-14,0.0007516887853853405,-0.011260099709033966 +4,TSLA,2025-08-15,0.0006456321571022272,-0.015072159469127655 +4,TSLA,2025-08-18,0.0006448569474741817,0.0138198621571064 +4,TSLA,2025-08-19,0.0006347526796162128,-0.017608491703867912 +4,TSLA,2025-08-20,0.0006484313053078949,-0.016564741730690002 +4,TSLA,2025-08-21,0.00066231848904863,-0.011770166456699371 +4,TSLA,2025-08-22,0.0006991703994572163,0.06031041592359543 +4,TSLA,2025-08-25,0.0006338029634207487,0.019196337088942528 +4,TSLA,2025-08-26,0.0006275540799833834,0.014521880075335503 +4,TSLA,2025-08-27,0.0006188210682012141,-0.005903612822294235 +4,TSLA,2025-08-28,0.0006246325210668147,-0.010408659465610981 +4,TSLA,2025-08-29,0.0006215069442987442,-0.03562932088971138 +4,TSLA,2025-09-02,0.0006521008908748627,-0.013600348494946957 +4,TSLA,2025-09-03,0.0006746576400473714,0.01425907388329506 +4,TSLA,2025-09-04,0.0006330459727905691,0.013202304020524025 +4,TSLA,2025-09-05,0.0005984243471175432,0.03571755811572075 +4,TSLA,2025-09-08,0.0006321438704617321,-0.012736110016703606 +4,TSLA,2025-09-09,0.0006681526429019868,0.0016441652551293373 +4,TSLA,2025-09-10,0.0006295327912084758,0.002360549522563815 +4,TSLA,2025-09-11,0.0005979755660519004,0.058682724833488464 +4,TSLA,2025-09-12,0.0007537717465311289,0.07098109275102615 +4,TSLA,2025-09-15,0.0007848847308196127,0.034992046654224396 +4,TSLA,2025-09-16,0.0006698797224089503,0.02784968540072441 +4,TSLA,2025-09-17,0.0006304348935373127,0.010006195865571499 +4,TSLA,2025-09-18,0.0006044057663530111,-0.021384159103035927 +4,TSLA,2025-09-19,0.0006399838603101671,0.021877208724617958 +4,TSLA,2025-09-22,0.0006340455147437751,0.018924599513411522 +4,TSLA,2025-09-23,0.000631568138487637,-0.019441083073616028 +4,TSLA,2025-09-24,0.0006781866541132331,0.039008449763059616 +4,TSLA,2025-09-25,0.0006762373959645629,-0.04480186104774475 +4,TSLA,2025-09-26,0.0006407340988516808,0.03938961774110794 +4,TSLA,2025-09-29,0.0006985856452956796,0.00636028777807951 +4,TSLA,2025-09-30,0.0007156006759032607,0.0034011942334473133 +4,TSLA,2025-10-01,0.0007133749313652515,0.03260699659585953 +4,TSLA,2025-10-02,0.0006799863185733557,-0.05240962654352188 +4,TSLA,2025-10-03,0.00046080592437647283,-0.014252493157982826 +4,TSLA,2025-10-06,5.893893467145972e-05,0.053054098039865494 +4,TSLA,2025-10-07,0.0006464911857619882,-0.04549830034375191 +4,TSLA,2025-10-08,0.0003027930506505072,0.012847468256950378 +4,TSLA,2025-10-09,0.0006193854496814311,-0.007206358481198549 +4,TSLA,2025-10-10,0.0006668516434729099,-0.05195334926247597 +4,TSLA,2025-10-13,0.0005535510717891157,0.052779536694288254 +4,TSLA,2025-10-14,0.0006441203295253217,-0.0153966648504138 +4,TSLA,2025-10-15,0.0006464911857619882,0.013674605637788773 +4,TSLA,2025-10-16,0.00064305734122172,-0.014816787093877792 +4,TSLA,2025-10-17,0.0006663348176516593,0.024331310763955116 +4,TSLA,2025-10-20,0.0006119420868344605,0.018314775079488754 +4,TSLA,2025-10-21,0.0005651875399053097,-0.010853642597794533 +4,TSLA,2025-10-22,0.0005908653838559985,-0.008235365152359009 +4,TSLA,2025-10-23,0.0005818014033138752,0.022547291591763496 +4,TSLA,2025-10-24,0.000592114229220897,-0.03457919880747795 +4,TSLA,2025-10-27,0.0005899904645048082,0.04221181571483612 +4,TSLA,2025-10-28,0.0005856183124706149,0.01781041920185089 +4,TSLA,2025-10-29,0.000680027122143656,0.002082342514768243 +4,GOOGL,2025-01-13,0.00036068697227165103,-0.005378034431487322 +4,GOOGL,2025-01-14,0.0003370035847183317,-0.007092797197401524 +4,GOOGL,2025-01-15,0.00029910486773587763,0.030583161860704422 +4,GOOGL,2025-01-16,0.000354175892425701,-0.013592339120805264 +4,GOOGL,2025-01-17,0.0003307636652607471,0.015890900045633316 +4,GOOGL,2025-01-21,0.0003617072943598032,0.010404886677861214 +4,GOOGL,2025-01-22,0.000353845622157678,0.0016144069377332926 +4,GOOGL,2025-01-23,0.0003557801537681371,-0.001968017779290676 +4,GOOGL,2025-01-24,0.0003615891910158098,0.011200962588191032 +4,GOOGL,2025-01-27,0.0003485450870357454,-0.04286167770624161 +4,GOOGL,2025-01-28,5.64092661079485e-05,0.018031682819128036 +4,GOOGL,2025-01-29,0.0002055030781775713,0.0005631165695376694 +4,GOOGL,2025-01-30,0.00021354190539568663,0.027557918801903725 +4,GOOGL,2025-01-31,0.00036976250703446567,0.015560191124677658 +4,GOOGL,2025-02-03,0.0003828984627034515,-0.013769619166851044 +4,GOOGL,2025-02-04,0.0003708320145960897,0.025270696729421616 +4,GOOGL,2025-02-05,0.0003778822429012507,-0.075719453394413 +4,GOOGL,2025-02-06,-0.00016139345825649798,0.0014101974666118622 +4,GOOGL,2025-02-07,-0.0003009601205121726,-0.03321800008416176 +4,GOOGL,2025-02-10,-0.0007268131012097001,0.00607848446816206 +4,GOOGL,2025-02-11,-0.0006972025730647147,-0.006186324637383223 +4,GOOGL,2025-02-12,-0.000803439412266016,-0.009270180016756058 +4,GOOGL,2025-02-13,-0.0008242500480264425,0.013685256242752075 +4,GOOGL,2025-02-14,-0.0007025457452982664,-0.00490087503567338 +4,GOOGL,2025-02-18,-0.0007108765421435237,-0.007913371548056602 +4,GOOGL,2025-02-19,-0.0006997997988946736,0.00812922790646553 +4,GOOGL,2025-02-20,-0.0006131968111731112,-0.003839458804577589 +4,GOOGL,2025-02-21,-0.0005563586018979549,-0.026908451691269875 +4,GOOGL,2025-02-24,-0.000836593157146126,-0.002284769434481859 +4,GOOGL,2025-02-25,-0.0006903622997924685,-0.021598411723971367 +4,GOOGL,2025-02-26,-0.00041183701250702143,-0.015453345142304897 +4,GOOGL,2025-02-27,-0.0003339038521517068,-0.024794036522507668 +4,GOOGL,2025-02-28,0.00021585097420029342,0.010508308187127113 +4,GOOGL,2025-03-03,7.402117626043037e-05,-0.019390344619750977 +4,GOOGL,2025-03-04,0.0001728321803966537,0.023141983896493912 +4,GOOGL,2025-03-05,-0.00018936037668026984,0.012211540713906288 +4,GOOGL,2025-03-06,-0.0006752502522431314,-0.0038798160385340452 +4,GOOGL,2025-03-07,-0.0005326702957972884,0.008723069913685322 +4,GOOGL,2025-03-10,-0.0005865826387889683,-0.04589514061808586 +4,GOOGL,2025-03-11,0.0004864003276452422,-0.011093945242464542 +4,GOOGL,2025-03-12,0.0005983866285532713,0.01854192279279232 +4,GOOGL,2025-03-13,0.0005533081130124629,-0.02637537568807602 +4,GOOGL,2025-03-14,0.0006627518450841308,0.01663389429450035 +4,GOOGL,2025-03-17,0.0005935858935117722,-0.007277642376720905 +4,GOOGL,2025-03-18,0.0005815156036987901,-0.02228054776787758 +4,GOOGL,2025-03-19,0.0006108948728069663,0.019843067973852158 +4,GOOGL,2025-03-20,0.00041805775254033506,-0.0066732135601341724 +4,GOOGL,2025-03-21,0.0003027956699952483,0.007283094339072704 +4,GOOGL,2025-03-24,2.274157668580301e-05,0.02225191704928875 +4,GOOGL,2025-03-25,-0.000626317982096225,0.017029721289873123 +4,GOOGL,2025-03-26,-0.0005872923647984862,-0.032778091728687286 +4,GOOGL,2025-03-27,-0.0007648200844414532,-0.01723223179578781 +4,GOOGL,2025-03-28,-0.0007870402769185603,-0.049983639270067215 +4,GOOGL,2025-03-31,0.0005223645130172372,0.0020065815187990665 +4,GOOGL,2025-04-01,0.0006205330137163401,0.015591785311698914 +4,GOOGL,2025-04-02,0.0006261758389882743,-0.00019100452482234687 +4,GOOGL,2025-04-03,0.0006152401329018176,-0.04107674956321716 +4,GOOGL,2025-04-04,0.0014782941434532404,-0.03456054627895355 +4,GOOGL,2025-04-07,0.0031771573703736067,0.00786720309406519 +4,GOOGL,2025-04-08,0.003507178509607911,-0.01406786311417818 +4,GOOGL,2025-04-09,0.0036956483963876963,0.09241605550050735 +4,GOOGL,2025-04-10,0.0007885937229730189,-0.0378178209066391 +4,GOOGL,2025-04-11,0.0007560961530543864,0.027876289561390877 +4,GOOGL,2025-04-14,0.0006488302024081349,0.01220730785280466 +4,GOOGL,2025-04-15,0.000589255359955132,-0.0175031665712595 +4,GOOGL,2025-04-16,0.0005859735538251698,-0.019248725846409798 +4,GOOGL,2025-04-17,0.0005191729287616909,-0.014253571629524231 +4,GOOGL,2025-04-21,0.0007089349091984332,-0.023358900099992752 +4,GOOGL,2025-04-22,0.0007845168584026396,0.025407418608665466 +4,GOOGL,2025-04-23,0.0007430460536852479,0.025293273851275444 +4,GOOGL,2025-04-24,0.0005656342837028205,0.02498289756476879 +4,GOOGL,2025-04-25,-0.0002865632704924792,0.016685722395777702 +4,GOOGL,2025-04-28,-0.0006037374841980636,-0.008370301686227322 +4,GOOGL,2025-04-29,-0.000785043986979872,-0.0028056784067302942 +4,GOOGL,2025-04-30,-0.0007421378395520151,-0.008527866564691067 +4,GOOGL,2025-05-01,-0.0005396270425990224,0.01562049426138401 +4,GOOGL,2025-05-02,-0.0007032735156826675,0.016783295199275017 +4,GOOGL,2025-05-05,-0.0005541397840715945,0.0010968799469992518 +4,GOOGL,2025-05-06,-0.0004176985239610076,-0.0059860204346477985 +4,GOOGL,2025-05-07,-0.0003721415705513209,-0.07536691427230835 +4,GOOGL,2025-05-08,6.443660095101222e-05,0.018975839018821716 +4,GOOGL,2025-05-09,-0.0002587467315606773,-0.00996633991599083 +4,GOOGL,2025-05-12,-0.0004377332516014576,0.036699507385492325 +4,GOOGL,2025-05-13,-0.0007058067712932825,0.006729652639478445 +4,GOOGL,2025-05-14,-0.0004216277156956494,0.03595339506864548 +4,GOOGL,2025-05-15,-2.3455122573068365e-05,-0.008562847040593624 +4,GOOGL,2025-05-16,0.0002105794264934957,0.013509278185665607 +4,GOOGL,2025-05-19,0.00029728407389484346,0.002103744773194194 +4,GOOGL,2025-05-20,0.00043568279943428934,-0.01549108698964119 +4,GOOGL,2025-05-21,0.000422542478190735,0.027547471225261688 +4,GOOGL,2025-05-22,0.00044245089520700276,0.013611084781587124 +4,GOOGL,2025-05-23,0.0004357735742814839,-0.014145220629870892 +4,GOOGL,2025-05-27,0.0004263973096385598,0.025955649092793465 +4,GOOGL,2025-05-28,0.00042550277430564165,-0.0031280710827559233 +4,GOOGL,2025-05-29,0.0004129650187678635,-0.002905096160247922 +4,GOOGL,2025-05-30,0.0003906376368831843,-0.0006984449573792517 +4,GOOGL,2025-06-02,0.00027865622541867197,-0.015905562788248062 +4,GOOGL,2025-06-03,0.00016312841034960002,-0.017004668712615967 +4,GOOGL,2025-06-04,-0.00017852311430033296,0.011189930140972137 +4,GOOGL,2025-06-05,-9.417181718163192e-05,0.0009518005535937846 +4,GOOGL,2025-06-06,-0.0001185474538942799,0.032001152634620667 +4,GOOGL,2025-06-09,0.0003382918075658381,0.014990652911365032 +4,GOOGL,2025-06-10,0.00044038734631612897,0.014153489843010902 +4,GOOGL,2025-06-11,0.00042715517338365316,-0.007023576181381941 +4,GOOGL,2025-06-12,0.0004149596788920462,-0.009347117505967617 +4,GOOGL,2025-06-13,0.0004097761702723801,-0.005879598204046488 +4,GOOGL,2025-06-16,0.0004084190586581826,0.011951051652431488 +4,GOOGL,2025-06-17,0.0004141515528317541,-0.0046497066505253315 +4,GOOGL,2025-06-18,0.0004105919797439128,-0.015060058794915676 +4,GOOGL,2025-06-20,0.0004019702901132405,-0.03930378332734108 +4,GOOGL,2025-06-23,-0.00021843616559635848,-0.008739572949707508 +4,GOOGL,2025-06-24,-0.0004028785042464733,0.009519261308014393 +4,GOOGL,2025-06-25,-0.00039360939990729094,0.02317485585808754 +4,GOOGL,2025-06-26,2.857904473785311e-05,0.01661759428679943 +4,GOOGL,2025-06-27,0.0003935246495530009,0.02834850363433361 +4,GOOGL,2025-06-30,0.0004426871018949896,-0.012966607697308064 +4,GOOGL,2025-07-01,0.0004510682192631066,-0.002215440385043621 +4,GOOGL,2025-07-02,0.0004438703472260386,0.015798047184944153 +4,GOOGL,2025-07-03,0.00042421018588356674,0.004969707690179348 +4,GOOGL,2025-07-07,0.00041767064249143004,-0.015379752963781357 +4,GOOGL,2025-07-08,0.00042774787289090455,-0.013840421102941036 +4,GOOGL,2025-07-09,0.00040914956480264664,0.01287848874926567 +4,GOOGL,2025-07-10,0.00042048547766171396,0.005645769648253918 +4,GOOGL,2025-07-11,0.00041500889346934855,0.014365551061928272 +4,GOOGL,2025-07-14,0.0003982521593570709,0.00757425045594573 +4,GOOGL,2025-07-15,0.00039858787204138935,0.002420609351247549 +4,GOOGL,2025-07-16,0.0003937783476430923,0.005315426737070084 +4,GOOGL,2025-07-17,0.0003847542393486947,0.003328398335725069 +4,GOOGL,2025-07-18,0.000380467448849231,0.008029526099562645 +4,GOOGL,2025-07-21,0.0003832746297121048,0.026870165020227432 +4,GOOGL,2025-07-22,0.0003708331205416471,0.006501663010567427 +4,GOOGL,2025-07-23,0.0003727173316292465,-0.005818082019686699 +4,GOOGL,2025-07-24,0.0003689368604682386,0.01014659646898508 +4,GOOGL,2025-07-25,0.00036767160054296255,0.005241915117949247 +4,GOOGL,2025-07-28,0.0003645264951046556,-0.0031106858514249325 +4,GOOGL,2025-07-29,0.00036615811404772103,0.01632659323513508 +4,GOOGL,2025-07-30,0.0003488272486720234,0.003976860549300909 +4,GOOGL,2025-07-31,0.00034640170633792877,-0.023840725421905518 +4,GOOGL,2025-08-01,0.000380615092581138,-0.01453968696296215 +4,GOOGL,2025-08-04,0.00037081341724842787,0.030769897624850273 +4,GOOGL,2025-08-05,0.0003796899109147489,-0.0018988216761499643 +4,GOOGL,2025-08-06,0.00036514547537080944,0.007267967332154512 +4,GOOGL,2025-08-07,0.000387874199077487,0.0021904450841248035 +4,GOOGL,2025-08-08,0.00038951344322413206,0.024628080427646637 +4,GOOGL,2025-08-11,0.000375183328287676,-0.0020873858593404293 +4,GOOGL,2025-08-12,0.0003865181643050164,0.011574546806514263 +4,GOOGL,2025-08-13,0.0003705936251208186,-0.006809765938669443 +4,GOOGL,2025-08-14,0.000379140954464674,0.004840742330998182 +4,GOOGL,2025-08-15,0.0003686350246425718,0.004719264339655638 +4,GOOGL,2025-08-18,0.00036510280915535986,-0.0019636854995042086 +4,GOOGL,2025-08-19,0.00037602210068143904,-0.0095292367041111 +4,GOOGL,2025-08-20,0.00036812215694226325,-0.011225100606679916 +4,GOOGL,2025-08-21,0.00032792368438094854,0.002154833637177944 +4,GOOGL,2025-08-22,0.0003098426095675677,0.03124643675982952 +4,GOOGL,2025-08-25,0.000369054963812232,0.011578187346458435 +4,GOOGL,2025-08-26,0.0003837186377495527,-0.006496190559118986 +4,GOOGL,2025-08-27,0.0003690396551974118,0.0016399931628257036 +4,GOOGL,2025-08-28,0.0003582603530958295,0.01985182613134384 +4,GOOGL,2025-08-29,0.0003730989992618561,0.0059828259982168674 +4,GOOGL,2025-09-02,0.0003713088226504624,-0.007354062050580978 +4,GOOGL,2025-09-03,0.0003808840992860496,0.0874292254447937 +4,GOOGL,2025-09-04,0.0003603862423915416,0.007084987126290798 +4,GOOGL,2025-09-05,0.0003928925725631416,0.011555753648281097 +4,GOOGL,2025-09-08,0.00039730293792672455,-0.0031994557939469814 +4,GOOGL,2025-09-09,0.0003537001903168857,0.023604100570082664 +4,GOOGL,2025-09-10,0.00027588949888013303,-0.0019215545617043972 +4,GOOGL,2025-09-11,-3.585290687624365e-05,0.0050048306584358215 +4,GOOGL,2025-09-12,-0.00023019639775156975,0.0017872820608317852 +4,GOOGL,2025-09-15,-0.00030917389085516334,0.0439135767519474 +4,GOOGL,2025-09-16,-0.0002194980188505724,-0.0017900463426485658 +4,GOOGL,2025-09-17,-0.0003454519319348037,-0.006511094514280558 +4,GOOGL,2025-09-18,-0.00043678347719833255,0.00996903795748949 +4,GOOGL,2025-09-19,-0.0003986562369391322,0.01061679981648922 +4,GOOGL,2025-09-22,-0.0002706923405639827,-0.00863493513315916 +4,GOOGL,2025-09-23,-0.0002516412641853094,-0.0034510239493101835 +4,GOOGL,2025-09-24,-0.00026449727010913193,-0.018124038353562355 +4,GOOGL,2025-09-25,-0.00047157754306681454,-0.005477475468069315 +4,GOOGL,2025-09-26,-0.00043816465768031776,0.00304673844948411 +4,GOOGL,2025-09-29,-0.00018245121464133263,-0.010151132009923458 +4,GOOGL,2025-09-30,-0.0001592828775756061,-0.003900139359757304 +4,GOOGL,2025-10-01,0.00016866186342667788,0.007376992143690586 +4,GOOGL,2025-10-02,0.0003731930337380618,0.003220594022423029 +4,GOOGL,2025-10-03,0.0003659470530692488,-0.0013847085647284985 +4,GOOGL,2025-10-06,0.0003434272075537592,0.02049357071518898 +4,GOOGL,2025-10-07,0.00031044299248605967,-0.018823962658643723 +4,GOOGL,2025-10-08,0.00033035906380973756,-0.004649455659091473 +4,GOOGL,2025-10-09,0.00032740531605668366,-0.012712310068309307 +4,GOOGL,2025-10-10,0.0003429996140766889,-0.020749429240822792 +4,GOOGL,2025-10-13,0.00035931236925534904,0.031538527458906174 +4,GOOGL,2025-10-14,0.0003702928952407092,0.0053104436956346035 +4,GOOGL,2025-10-15,0.00039113411912694573,0.022479210048913956 +4,GOOGL,2025-10-16,0.0003598624316509813,0.0017115108203142881 +4,GOOGL,2025-10-17,0.0003708757576532662,0.007290579844266176 +4,GOOGL,2025-10-20,0.0003597946197260171,0.012749077752232552 +4,GOOGL,2025-10-21,0.00034352453076280653,-0.0240243598818779 +4,GOOGL,2025-10-22,0.0003717976505868137,0.004898952320218086 +4,GOOGL,2025-10-23,0.00037583071389235556,0.005507524125277996 +4,GOOGL,2025-10-24,0.00036291350261308253,0.026668256148695946 +4,GOOGL,2025-10-27,0.00035904007381759584,0.035340528935194016 +4,GOOGL,2025-10-28,0.00036657476448453963,-0.006707044318318367 +4,GOOGL,2025-10-29,0.00038097595097497106,0.02619888447225094 +4,AMZN,2025-01-13,3.79646044166293e-05,-0.002194768749177456 +4,AMZN,2025-01-14,-0.00024770121672190726,-0.003209448419511318 +4,AMZN,2025-01-15,-0.00029882387025281787,0.025346562266349792 +4,AMZN,2025-01-16,0.00032660525175742805,-0.012117002159357071 +4,AMZN,2025-01-17,0.0002958841505460441,0.023646414279937744 +4,AMZN,2025-01-21,0.00040881228051148355,0.020892051979899406 +4,AMZN,2025-01-22,0.000385953055229038,0.01846650429069996 +4,AMZN,2025-01-23,0.0003863852471113205,0.001743102096952498 +4,AMZN,2025-01-24,0.00038746511563658714,-0.002424106700345874 +4,AMZN,2025-01-27,0.00039536639815196395,0.002424106700345874 +4,AMZN,2025-01-28,0.0004046775575261563,0.011529556475579739 +4,AMZN,2025-01-29,0.0004200467374175787,-0.004545214585959911 +4,AMZN,2025-01-30,0.00043089702376164496,-0.010303065180778503 +4,AMZN,2025-01-31,0.0004056847537867725,0.012872777879238129 +4,AMZN,2025-02-03,0.00042237513116560876,-0.0010944834211841226 +4,AMZN,2025-02-04,0.00042667731759138405,0.01935490220785141 +4,AMZN,2025-02-05,0.00042579323053359985,-0.02463374473154545 +4,AMZN,2025-02-06,0.0004360414168331772,0.01120013277977705 +4,AMZN,2025-02-07,0.0004265332536306232,-0.04137522354722023 +4,AMZN,2025-02-10,5.3913732699584216e-05,0.017262345179915428 +4,AMZN,2025-02-11,0.0003523789928294718,-0.0016312727238982916 +4,AMZN,2025-02-12,0.0003758033853955567,-0.01659160852432251 +4,AMZN,2025-02-13,0.00026647557388059795,0.006270442623645067 +4,AMZN,2025-02-14,0.00038567479350604117,-0.007363076787441969 +4,AMZN,2025-02-18,0.00038745402707718313,-0.008916663937270641 +4,AMZN,2025-02-19,0.00038810662226751447,-8.819719369057566e-05 +4,AMZN,2025-02-20,0.00039735250174999237,-0.01668522134423256 +4,AMZN,2025-02-21,0.0003729061281774193,-0.028673529624938965 +4,AMZN,2025-02-24,-0.00020377678447403014,-0.018030235543847084 +4,AMZN,2025-02-25,-0.0006010200013406575,0.00042300455970689654 +4,AMZN,2025-02-26,-0.0008140744175761938,0.00725744990631938 +4,AMZN,2025-02-27,-0.000797805143520236,-0.026520738378167152 +4,AMZN,2025-02-28,-0.0003908074868377298,0.016816668212413788 +4,AMZN,2025-03-03,-0.0004297537379898131,-0.03479859605431557 +4,AMZN,2025-03-04,0.0002813442551996559,-0.005968419834971428 +4,AMZN,2025-03-05,0.0006471103406511247,0.02212822064757347 +4,AMZN,2025-03-06,0.0003383470175322145,-0.03745611384510994 +4,AMZN,2025-03-07,0.0009518146398477256,-0.007250922732055187 +4,AMZN,2025-03-10,0.0017891720635816455,-0.023922555148601532 +4,AMZN,2025-03-11,0.0029150384943932295,0.01048255991190672 +4,AMZN,2025-03-12,0.0027201620396226645,0.01163158193230629 +4,AMZN,2025-03-13,0.002204043325036764,-0.025460919365286827 +4,AMZN,2025-03-14,0.0025594718754291534,0.02072347328066826 +4,AMZN,2025-03-17,0.0015983748016878963,-0.011227182112634182 +4,AMZN,2025-03-18,0.0013592136092483997,-0.01503012701869011 +4,AMZN,2025-03-19,0.0013715194072574377,0.014007778838276863 +4,AMZN,2025-03-20,0.0007063793018460274,-0.0030218278989195824 +4,AMZN,2025-03-21,0.0006378982798196375,0.0064424485899508 +4,AMZN,2025-03-24,0.0003945291100535542,0.035300374031066895 +4,AMZN,2025-03-25,-0.0005682586343027651,0.011981521733105183 +4,AMZN,2025-03-26,-0.0006811030325479805,-0.022515950724482536 +4,AMZN,2025-03-27,-0.000706384249497205,0.0011428644647821784 +4,AMZN,2025-03-28,-0.0005547684268094599,-0.04385599121451378 +4,AMZN,2025-03-31,-0.0004576385545078665,-0.012846835888922215 +4,AMZN,2025-04-01,-5.178294304641895e-05,0.009988858364522457 +4,AMZN,2025-04-02,-3.031509550055489e-05,0.019785262644290924 +4,AMZN,2025-04-03,-0.0006355262012220919,-0.09408135712146759 +4,AMZN,2025-04-04,0.0012244267854839563,-0.04242073744535446 +4,AMZN,2025-04-07,0.0035143529530614614,0.024606997147202492 +4,AMZN,2025-04-08,0.004226948134601116,-0.02659725770354271 +4,AMZN,2025-04-09,0.004872547462582588,0.1131235882639885 +4,AMZN,2025-04-10,0.0026104438584297895,-0.05308511108160019 +4,AMZN,2025-04-11,0.0028494393918663263,0.01994107849895954 +4,AMZN,2025-04-14,0.002477898495271802,-0.014987066388130188 +4,AMZN,2025-04-15,0.002912080381065607,-0.013989328406751156 +4,AMZN,2025-04-16,0.002868750598281622,-0.029726389795541763 +4,AMZN,2025-04-17,0.002903326414525509,-0.009915347211062908 +4,AMZN,2025-04-21,0.0035345314536243677,-0.03112652711570263 +4,AMZN,2025-04-22,0.003706911811605096,0.034423284232616425 +4,AMZN,2025-04-23,0.0034386729821562767,0.041953202337026596 +4,AMZN,2025-04-24,0.0026082058902829885,0.0323609821498394 +4,AMZN,2025-04-25,0.0007436996093019843,0.013048475608229637 +4,AMZN,2025-04-28,0.00019605587294790894,-0.006849205121397972 +4,AMZN,2025-04-29,-0.00022933750005904585,-0.0016529238782823086 +4,AMZN,2025-04-30,-0.00040226479177363217,-0.015976248309016228 +4,AMZN,2025-05-01,-0.000344553409377113,0.030860381200909615 +4,AMZN,2025-05-02,-0.0007841622573323548,-0.0011573530500754714 +4,AMZN,2025-05-05,-0.0007855314761400223,-0.01929212175309658 +4,AMZN,2025-05-06,-0.0008236244320869446,-0.007216810714453459 +4,AMZN,2025-05-07,-0.0008369527058675885,0.019801633432507515 +4,AMZN,2025-05-08,-0.0007543264073319733,0.017700480297207832 +4,AMZN,2025-05-09,-0.0005588440108112991,0.005089047364890575 +4,AMZN,2025-05-12,-0.00028427597135305405,0.07760926336050034 +4,AMZN,2025-05-13,-0.00030866818269714713,0.012999854050576687 +4,AMZN,2025-05-14,-0.00033308379352092743,-0.005312830209732056 +4,AMZN,2025-05-15,-0.00052683986723423,-0.02445840649306774 +4,AMZN,2025-05-16,-0.0007146340212784708,0.0020449815783649683 +4,AMZN,2025-05-19,-0.000823729089461267,0.0027687076944857836 +4,AMZN,2025-05-20,-0.0006416322430595756,-0.010189476422965527 +4,AMZN,2025-05-21,-0.0006716699572280049,-0.014561387710273266 +4,AMZN,2025-05-22,-0.000727267237380147,0.009796777740120888 +4,AMZN,2025-05-23,-0.0006983179482631385,-0.010443315841257572 +4,AMZN,2025-05-27,-0.0006403947481885552,0.024718089029192924 +4,AMZN,2025-05-28,-0.0005400629015639424,-0.006330074276775122 +4,AMZN,2025-05-29,-0.000503494287841022,0.00477558420971036 +4,AMZN,2025-05-30,-0.0003588956897147,-0.0033600502647459507 +4,AMZN,2025-06-02,-0.000500821101013571,0.007967779412865639 +4,AMZN,2025-06-03,-0.00029186822939664125,-0.004559068940579891 +4,AMZN,2025-06-04,-0.0002657780423760414,0.007361824158579111 +4,AMZN,2025-06-05,0.00022938736947253346,0.0032760442700237036 +4,AMZN,2025-06-06,0.0002728796098381281,0.02685937099158764 +4,AMZN,2025-06-09,0.00046850484795868397,0.015840481966733932 +4,AMZN,2025-06-10,0.0004461147473193705,0.0028993089217692614 +4,AMZN,2025-06-11,0.0004458931216504425,-0.020473795011639595 +4,AMZN,2025-06-12,0.00040247474680654705,0.00018763975822366774 +4,AMZN,2025-06-13,0.00040204994729720056,-0.005360427312552929 +4,AMZN,2025-06-16,0.00035962893161922693,0.018683401867747307 +4,AMZN,2025-06-17,0.0004358998266980052,-0.005940789356827736 +4,AMZN,2025-06-18,0.0003280766832176596,-0.010764379985630512 +4,AMZN,2025-06-20,0.0001718508283374831,-0.013405860401690006 +4,AMZN,2025-06-23,-7.668614125577733e-05,-0.005835109390318394 +4,AMZN,2025-06-24,-0.00020182639127597213,0.020416637882590294 +4,AMZN,2025-06-25,0.00021303437824826688,-0.0036726605612784624 +4,AMZN,2025-06-26,0.00028137810295447707,0.023911042138934135 +4,AMZN,2025-06-27,0.0004698408010881394,0.02806599996984005 +4,AMZN,2025-06-30,0.00046899367589503527,-0.017665207386016846 +4,AMZN,2025-07-01,0.00046127213863655925,0.0048653376288712025 +4,AMZN,2025-07-02,0.0004598844680003822,-0.002452467568218708 +4,AMZN,2025-07-03,0.00045898190001025796,0.015744829550385475 +4,AMZN,2025-07-07,0.0004597182269208133,0.00026851752772927284 +4,AMZN,2025-07-08,0.00045768904965370893,-0.018562963232398033 +4,AMZN,2025-07-09,0.00047602690756320953,0.0143926115706563 +4,AMZN,2025-07-10,0.00045065212179906666,-0.0012589874677360058 +4,AMZN,2025-07-11,0.0004523587122093886,0.012341462075710297 +4,AMZN,2025-07-14,0.00043719023233279586,0.0029730808455497026 +4,AMZN,2025-07-15,0.00043704494601115584,0.0029201137367635965 +4,AMZN,2025-07-16,0.0004364292835816741,-0.014059063047170639 +4,AMZN,2025-07-17,0.00044877806794829667,0.003086778335273266 +4,AMZN,2025-07-18,0.0004317392304074019,0.009999861009418964 +4,AMZN,2025-07-21,0.0004144085687585175,0.01392112672328949 +4,AMZN,2025-07-22,0.0004003359645139426,-0.008012835867702961 +4,AMZN,2025-07-23,0.000407065061153844,0.0035983542911708355 +4,AMZN,2025-07-24,0.00038660934660583735,0.01711152121424675 +4,AMZN,2025-07-25,0.0003853928064927459,-0.003407570067793131 +4,AMZN,2025-07-28,0.0003917537396773696,0.005816059652715921 +4,AMZN,2025-07-29,0.0003975507279392332,-0.007675754837691784 +4,AMZN,2025-07-30,0.0003845666069537401,-0.0035559104289859533 +4,AMZN,2025-07-31,0.0003695212653838098,0.0168860275298357 +4,AMZN,2025-08-01,0.00040816215914674103,-0.0863165333867073 +4,AMZN,2025-08-04,0.00031546931131742895,-0.014540622942149639 +4,AMZN,2025-08-05,-0.0005141365109011531,0.009873169474303722 +4,AMZN,2025-08-06,-0.0007330617518164217,0.03926568478345871 +4,AMZN,2025-08-07,-0.00040445284685119987,0.0036817898508161306 +4,AMZN,2025-08-08,-0.0002108321787090972,-0.001973902340978384 +4,AMZN,2025-08-11,1.660141788306646e-05,-0.0062614199705421925 +4,AMZN,2025-08-12,-9.424828749615699e-05,0.0007678847177885473 +4,AMZN,2025-08-13,0.00012868856720160693,0.013855775818228722 +4,AMZN,2025-08-14,0.0003778756654355675,0.02818818762898445 +4,AMZN,2025-08-15,0.00040827912744134665,0.0002164587494917214 +4,AMZN,2025-08-18,0.00040295865619555116,0.001989132957533002 +4,AMZN,2025-08-19,0.0003991120320279151,-0.015147235244512558 +4,AMZN,2025-08-20,0.0004150217573624104,-0.018591996282339096 +4,AMZN,2025-08-21,0.00038711787783540785,-0.008345348760485649 +4,AMZN,2025-08-22,0.0003317558148410171,0.03057093359529972 +4,AMZN,2025-08-25,0.00040402618469670415,-0.003940606489777565 +4,AMZN,2025-08-26,0.0003920726594515145,0.00337240775115788 +4,AMZN,2025-08-27,0.0004034179146401584,0.0017910075839608908 +4,AMZN,2025-08-28,0.00041338044684380293,0.01076590921729803 +4,AMZN,2025-08-29,0.0003898550639860332,-0.011289769783616066 +4,AMZN,2025-09-02,0.0003841750440187752,-0.016111647710204124 +4,AMZN,2025-09-03,0.0003680350782815367,0.0028804184403270483 +4,AMZN,2025-09-04,0.000383080419851467,0.04198414459824562 +4,AMZN,2025-09-05,0.0003533849667292088,-0.014316138811409473 +4,AMZN,2025-09-08,0.0003718718362506479,0.01499481126666069 +4,AMZN,2025-09-09,0.0003642192459665239,0.010124998167157173 +4,AMZN,2025-09-10,0.0003566737868823111,-0.0337655209004879 +4,AMZN,2025-09-11,0.0003945044882129878,-0.0016511904541403055 +4,AMZN,2025-09-12,0.0003888010687660426,-0.007858600467443466 +4,AMZN,2025-09-15,0.0003276457136962563,0.014274139888584614 +4,AMZN,2025-09-16,0.0003863396996166557,0.011257359758019447 +4,AMZN,2025-09-17,0.00037265740684233606,-0.010436704382300377 +4,AMZN,2025-09-18,0.00038325527566485107,-0.001685208990238607 +4,AMZN,2025-09-19,0.0003777488600462675,0.001080590533092618 +4,AMZN,2025-09-22,0.0003608836268540472,-0.016771933063864708 +4,AMZN,2025-09-23,0.00038368007517419755,-0.03087186999619007 +4,AMZN,2025-09-24,0.0002907323359977454,-0.0022679860703647137 +4,AMZN,2025-09-25,-6.796971138101071e-05,-0.009398795664310455 +4,AMZN,2025-09-26,-0.000253070960752666,0.0074441684409976006 +4,AMZN,2025-09-29,-5.745557791669853e-05,0.01081580575555563 +4,AMZN,2025-09-30,0.0002955332165583968,-0.011771724559366703 +4,AMZN,2025-10-01,0.0002204456104664132,0.004815991036593914 +4,AMZN,2025-10-02,0.000306143396301195,0.008035429753363132 +4,AMZN,2025-10-03,0.00036394098424352705,-0.013124777004122734 +4,AMZN,2025-10-06,0.000358924618922174,0.00631231814622879 +4,AMZN,2025-10-07,0.00038187619065865874,0.003975811414420605 +4,AMZN,2025-10-08,0.00038267901982180774,0.015391813591122627 +4,AMZN,2025-10-09,0.0003602889191824943,0.011126943863928318 +4,AMZN,2025-10-10,0.00034795122337527573,-0.05121477320790291 +4,AMZN,2025-10-13,0.00016439033788628876,0.016955828294157982 +4,AMZN,2025-10-14,0.00018366645963396877,-0.016863377764821053 +4,AMZN,2025-10-15,-0.0003030940715689212,-0.0037966156378388405 +4,AMZN,2025-10-16,-0.0005136476829648018,-0.005115842446684837 +4,AMZN,2025-10-17,-0.0005679631140083075,-0.0066899643279612064 +4,AMZN,2025-10-20,-0.0007344297482632101,0.016018234193325043 +4,AMZN,2025-10-21,-0.00027829306782223284,0.02531435713171959 +4,AMZN,2025-10-22,0.00025213576736859977,-0.01854683831334114 +4,AMZN,2025-10-23,0.00024033123918343335,0.014304176904261112 +4,AMZN,2025-10-24,0.00039098909473977983,0.014013301581144333 +4,AMZN,2025-10-27,0.00040208688005805016,0.012234712950885296 +4,AMZN,2025-10-28,0.00039403658593073487,0.00999525561928749 +4,AMZN,2025-10-29,0.00039237679447978735,0.004569708835333586 +4,META,2025-01-13,0.0004176653746981174,-0.012302194721996784 +4,META,2025-01-14,0.00043611254659481347,-0.02341727912425995 +4,META,2025-01-15,0.0004702577134594321,0.03776327148079872 +4,META,2025-01-16,0.0004333888355176896,-0.00947566982358694 +4,META,2025-01-17,0.0004503093659877777,0.002401822479441762 +4,META,2025-01-21,0.00045281281927600503,0.006003915332257748 +4,META,2025-01-22,0.0004251892678439617,0.011355124413967133 +4,META,2025-01-23,0.0004186691658105701,0.02055717073380947 +4,META,2025-01-24,0.0004379253659863025,0.017197422683238983 +4,META,2025-01-27,0.0004476935137063265,0.018954714760184288 +4,META,2025-01-28,0.00044699088903144,0.021661754697561264 +4,META,2025-01-29,0.0004337544087320566,0.0031979347113519907 +4,META,2025-01-30,0.00043961082701571286,0.015416635200381279 +4,META,2025-01-31,0.00045299262274056673,0.0031681531108915806 +4,META,2025-02-03,0.0004670141206588596,0.011942742392420769 +4,META,2025-02-04,0.000474409171147272,0.009603042155504227 +4,META,2025-02-05,0.0004800603201147169,0.0009651543805375695 +4,META,2025-02-06,0.0005001674871891737,0.010050536133348942 +4,META,2025-02-07,0.0004931574803777039,0.0035471529699862003 +4,META,2025-02-10,0.0004981269594281912,0.004022589884698391 +4,META,2025-02-11,0.000492800900246948,0.0033397283405065536 +4,META,2025-02-12,0.0004981958772987127,0.00772217009216547 +4,META,2025-02-13,0.0004996550851501524,0.004374423995614052 +4,META,2025-02-14,0.00046913555706851184,0.011069988831877708 +4,META,2025-02-18,0.0004644447471946478,-0.027943206951022148 +4,META,2025-02-19,0.0005004896083846688,-0.01774510368704796 +4,META,2025-02-20,0.0005451759789139032,-0.012770037166774273 +4,META,2025-02-21,0.0005304248770698905,-0.016381746158003807 +4,META,2025-02-24,0.0002700955665204674,-0.02281706966459751 +4,META,2025-02-25,-0.0001012777429423295,-0.016038157045841217 +4,META,2025-02-26,-0.0005634591216221452,0.024340389296412468 +4,META,2025-02-27,-0.00021744407422374934,-0.023215502500534058 +4,META,2025-02-28,-0.0006115958094596863,0.01501801423728466 +4,META,2025-03-03,-0.0005351014551706612,-0.019875967875123024 +4,META,2025-03-04,-0.000631878268904984,-0.02324335277080536 +4,META,2025-03-05,-0.0010336227715015411,0.025408700108528137 +4,META,2025-03-06,-0.0009519102168269455,-0.04444825276732445 +4,META,2025-03-07,-0.0006242449744604528,-0.00362172513268888 +4,META,2025-03-10,-0.0002266541705466807,-0.04523301497101784 +4,META,2025-03-11,0.0007636894006282091,0.012827356345951557 +4,META,2025-03-12,0.000829411088488996,0.0226081945002079 +4,META,2025-03-13,0.0007254654192365706,-0.047802772372961044 +4,META,2025-03-14,0.0014706121291965246,0.029199352487921715 +4,META,2025-03-17,0.000770204234868288,-0.00445367768406868 +4,META,2025-03-18,0.000661877915263176,-0.037974245846271515 +4,META,2025-03-19,0.0007696244865655899,0.0029148550238460302 +4,META,2025-03-20,0.0007791304378770292,0.003316096728667617 +4,META,2025-03-21,0.0007336590206250548,0.017340078949928284 +4,META,2025-03-24,0.00030525276088155806,0.037202879786491394 +4,META,2025-03-25,-0.0009446395561099052,0.011982669122517109 +4,META,2025-03-26,-0.0008194181718863547,-0.024781359359622 +4,META,2025-03-27,-0.0007514409953728318,-0.013843532651662827 +4,META,2025-03-28,-0.0007689937483519316,-0.043828971683979034 +4,META,2025-03-31,-0.0004866598465014249,-0.0006591131095774472 +4,META,2025-04-01,-0.00047108845319598913,0.01658734865486622 +4,META,2025-04-02,-0.0007587685831822455,-0.003538666758686304 +4,META,2025-04-03,-0.0010152430040761828,-0.09385211020708084 +4,META,2025-04-04,0.0008777987095527351,-0.05190538242459297 +4,META,2025-04-07,0.003424215828999877,0.022567398846149445 +4,META,2025-04-08,0.00394087191671133,-0.011298342607915401 +4,META,2025-04-09,0.004103252664208412,0.1376345455646515 +4,META,2025-04-10,0.000985966995358467,-0.06977741420269012 +4,META,2025-04-11,0.0011910191969946027,-0.004991393536329269 +4,META,2025-04-14,0.0015507396310567856,-0.022492850199341774 +4,META,2025-04-15,0.002400689758360386,-0.018918002024292946 +4,META,2025-04-16,0.0026233119424432516,-0.03753019496798515 +4,META,2025-04-17,0.0029449004214257,-0.001653687097132206 +4,META,2025-04-21,0.0035721894819289446,-0.034116119146347046 +4,META,2025-04-22,0.003723344299942255,0.03172039985656738 +4,META,2025-04-23,0.0036604399792850018,0.039180051535367966 +4,META,2025-04-24,0.00310498452745378,0.02445480413734913 +4,META,2025-04-25,0.0009647422120906413,0.026139577850699425 +4,META,2025-04-28,0.00042438850505277514,0.004502904135733843 +4,META,2025-04-29,-0.00040185428224503994,0.00851324200630188 +4,META,2025-04-30,-0.0008588713826611638,-0.009860099293291569 +4,META,2025-05-01,-0.0009794977959245443,0.041407618671655655 +4,META,2025-05-02,-0.0007536163320764899,0.04244469478726387 +4,META,2025-05-05,-0.0004350585804786533,0.0037614982575178146 +4,META,2025-05-06,-0.00033486890606582165,-0.020159421488642693 +4,META,2025-05-07,-0.0004501827643252909,0.016045987606048584 +4,META,2025-05-08,-0.0005405938136391342,0.0020087219309061766 +4,META,2025-05-09,-0.0005383824463933706,-0.009273591451346874 +4,META,2025-05-12,-0.00034024586784653366,0.07624323666095734 +4,META,2025-05-13,-0.00034095902810804546,0.025629408657550812 +4,META,2025-05-14,-0.00037199092912487686,0.005062991753220558 +4,META,2025-05-15,-0.0005571382353082299,-0.02375715970993042 +4,META,2025-05-16,-0.0006730049499310553,-0.005513236857950687 +4,META,2025-05-19,-0.0008454147027805448,0.0001405775110470131 +4,META,2025-05-20,-0.0006343547720462084,-0.005213227588683367 +4,META,2025-05-21,-0.0006139689357951283,-0.0025145700201392174 +4,META,2025-05-22,-0.0005109147168695927,0.0016823773039504886 +4,META,2025-05-23,-0.0004886217066086829,-0.015052116475999355 +4,META,2025-05-27,-0.00043559042387641966,0.024044346064329147 +4,META,2025-05-28,-0.000203471994609572,0.001959757413715124 +4,META,2025-05-29,9.528874943498522e-05,0.0022815559059381485 +4,META,2025-05-30,0.00048197800060734153,0.003775352379307151 +4,META,2025-06-02,0.00047310575610026717,0.035516880452632904 +4,META,2025-06-03,0.0006254083127714694,-0.006054999772459269 +4,META,2025-06-04,0.0006265185074880719,0.03115101531147957 +4,META,2025-06-05,0.0005941636627539992,-0.004852249752730131 +4,META,2025-06-06,0.0006190905114635825,0.018939640372991562 +4,META,2025-06-09,0.0006071978714317083,-0.005245183128863573 +4,META,2025-06-10,0.0006154274451546371,0.01194467768073082 +4,META,2025-06-11,0.0005756850587204099,-0.011829370632767677 +4,META,2025-06-12,0.000604595523327589,-0.001124237896874547 +4,META,2025-06-13,0.0006105687934905291,-0.015245018526911736 +4,META,2025-06-16,0.0005973518127575517,0.02856900915503502 +4,META,2025-06-17,0.0006169675616547465,-0.006988984532654285 +4,META,2025-06-18,0.0005879237432964146,-0.002096240408718586 +4,META,2025-06-20,0.000594382407143712,-0.019476424902677536 +4,META,2025-06-23,0.00024080004368443042,0.023435572162270546 +4,META,2025-06-24,0.0005741104250773787,0.01938050240278244 +4,META,2025-06-25,0.0006485672784037888,-0.004954576026648283 +4,META,2025-06-26,0.0006489178631454706,0.024269921705126762 +4,META,2025-06-27,0.0005795758333988488,0.010330772958695889 +4,META,2025-06-30,0.0005586596671491861,0.00606095977127552 +4,META,2025-07-01,0.0005528272013179958,-0.02589855156838894 +4,META,2025-07-02,0.0006100054597482085,-0.00788664910942316 +4,META,2025-07-03,0.0006136550800874829,0.007594658061861992 +4,META,2025-07-07,0.000599413295276463,-0.000918425852432847 +4,META,2025-07-08,0.0005967750330455601,0.0032245293259620667 +4,META,2025-07-09,0.0005961757269687951,0.016664179041981697 +4,META,2025-07-10,0.0005606357590295374,-0.007588986307382584 +4,META,2025-07-11,0.0005730242701247334,-0.013469615951180458 +4,META,2025-07-14,0.0005800747312605381,0.004741210490465164 +4,META,2025-07-15,0.0005818650824949145,-0.014713980257511139 +4,META,2025-07-16,0.0005030185566283762,-0.010585431009531021 +4,META,2025-07-17,0.0004950512084178627,-0.0021362039260566235 +4,META,2025-07-18,0.00048819099902175367,0.004083456005901098 +4,META,2025-07-21,0.000530652585439384,0.012263352982699871 +4,META,2025-07-22,0.0004928578273393214,-0.011511021293699741 +4,META,2025-07-23,0.0005000910605303943,0.01236626598984003 +4,META,2025-07-24,0.0004666560562327504,0.001708128023892641 +4,META,2025-07-25,0.00045382260577753186,-0.002970219124108553 +4,META,2025-07-28,0.0004467886174097657,0.006921615917235613 +4,META,2025-07-29,0.00046638489584438503,-0.024873754009604454 +4,META,2025-07-30,0.000461331510450691,-0.006866378244012594 +4,META,2025-07-31,0.0004813832347281277,0.10663412511348724 +4,META,2025-08-01,0.00043211388401687145,-0.03076154924929142 +4,META,2025-08-04,0.0004727132327388972,0.034542642533779144 +4,META,2025-08-05,0.0005166235496290028,-0.0167684406042099 +4,META,2025-08-06,0.000461169722257182,0.011110866442322731 +4,META,2025-08-07,0.0004569238517433405,-0.013248191215097904 +4,META,2025-08-08,0.0004656612582039088,0.009757683612406254 +4,META,2025-08-11,0.0004593808844219893,-0.004468764644116163 +4,META,2025-08-12,0.0004678441327996552,0.0310206301510334 +4,META,2025-08-13,0.0004584474954754114,-0.012636441737413406 +4,META,2025-08-14,0.00047043748782016337,0.0026243727188557386 +4,META,2025-08-15,0.00046656467020511627,0.003955664113163948 +4,META,2025-08-18,0.0004601854016073048,-0.023007482290267944 +4,META,2025-08-19,0.0004776093119289726,-0.02092454768717289 +4,META,2025-08-20,0.00044693544623441994,-0.005015970673412085 +4,META,2025-08-21,0.00044791377149522305,-0.01159537024796009 +4,META,2025-08-22,0.0004025996313430369,0.021006321534514427 +4,META,2025-08-25,0.0004845024668611586,-0.00197597686201334 +4,META,2025-08-26,0.0004758384602610022,0.0010613994672894478 +4,META,2025-08-27,0.00044227458420209587,-0.008951162919402122 +4,META,2025-08-28,0.00043151312274858356,0.004978299606591463 +4,META,2025-08-29,0.0004619322717189789,-0.016660209745168686 +4,META,2025-09-02,0.0004255952953826636,-0.004871785640716553 +4,META,2025-09-03,0.0003967611992266029,0.00263557443395257 +4,META,2025-09-04,0.0003949558886233717,0.015615890733897686 +4,META,2025-09-05,0.0004306366899982095,0.005063061602413654 +4,META,2025-09-08,0.0004344615445006639,-0.0001994035264942795 +4,META,2025-09-09,0.00042794295586645603,0.017655236646533012 +4,META,2025-09-10,0.00040338916005566716,-0.018080709502100945 +4,META,2025-09-11,0.00041198128019459546,-0.0014373292215168476 +4,META,2025-09-12,0.000406324106734246,0.006226581521332264 +4,META,2025-09-15,0.0004032813012599945,0.0119845662266016 +4,META,2025-09-16,0.0004945747787132859,0.01852753944694996 +4,META,2025-09-17,0.0005916212685406208,-0.004219497088342905 +4,META,2025-09-18,0.0005786949186585844,0.0058227465488016605 +4,META,2025-09-19,0.0005637714639306068,-0.0023995451629161835 +4,META,2025-09-22,0.0005431714234873652,-0.016455143690109253 +4,META,2025-09-23,0.0004629690374713391,-0.012837550602853298 +4,META,2025-09-24,0.0003987492818851024,0.006939045153558254 +4,META,2025-09-25,0.0003893182147294283,-0.015567694790661335 +4,META,2025-09-26,0.00041093703475780785,-0.00691384868696332 +4,META,2025-09-29,0.0003984901122748852,-0.00047065585386008024 +4,META,2025-09-30,0.00038940960075706244,-0.012207625433802605 +4,META,2025-10-01,0.00038543491973541677,-0.023476753383874893 +4,META,2025-10-02,0.0003998474567197263,0.01344532985240221 +4,META,2025-10-03,0.00037586898542940617,-0.0229418333619833 +4,META,2025-10-06,0.00038936614873819053,0.0071518332697451115 +4,META,2025-10-07,0.00037766832974739373,-0.0036115723196417093 +4,META,2025-10-08,0.000380827987100929,0.006653126794844866 +4,META,2025-10-09,0.00038072012830525637,0.02159450389444828 +4,META,2025-10-10,0.00037141787470318377,-0.03921801224350929 +4,META,2025-10-13,0.00047298139543272555,0.014637789689004421 +4,META,2025-10-14,0.0004379852907732129,-0.009899284690618515 +4,META,2025-10-15,0.00026659879949875176,0.012480851262807846 +4,META,2025-10-16,0.0003723317931871861,-0.007666375488042831 +4,META,2025-10-17,0.000360544043360278,0.006788014434278011 +4,META,2025-10-20,0.00038346630753949285,0.02104848250746727 +4,META,2025-10-21,0.0004110883455723524,0.0015012852381914854 +4,META,2025-10-22,0.00041212659562006593,0.00019083978259004653 +4,META,2025-10-23,0.0004108905850443989,0.0008041809778660536 +4,META,2025-10-24,0.00040090069524012506,0.00592248747125268 +4,META,2025-10-27,0.00039550423389300704,0.016734344884753227 +4,META,2025-10-28,0.0004229614860378206,0.0008255266584455967 +4,META,2025-10-29,0.00041861971840262413,0.0003059878072235733 +4,SPY,2025-01-13,0.00015218142652884126,0.001549276988953352 +4,SPY,2025-01-14,0.00014722577179782093,0.0013748978963121772 +4,SPY,2025-01-15,0.00015341176185756922,0.018026676028966904 +4,SPY,2025-01-16,0.00015524729678872973,-0.0019250581972301006 +4,SPY,2025-01-17,0.0002036079386016354,0.009989836253225803 +4,SPY,2025-01-21,0.00027656008023768663,0.009111841209232807 +4,SPY,2025-01-22,0.00033684345544315875,0.005605796352028847 +4,SPY,2025-01-23,0.00034964820952154696,0.005443115718662739 +4,SPY,2025-01-24,0.0003543538332451135,-0.002923534717410803 +4,SPY,2025-01-27,0.0003365219454281032,-0.014246356673538685 +4,SPY,2025-01-28,0.00024601753102615476,0.008555612526834011 +4,SPY,2025-01-29,0.00023937267542351037,-0.004492839798331261 +4,SPY,2025-01-30,0.00022343953605741262,0.005352730862796307 +4,SPY,2025-01-31,0.0002473138156346977,-0.005336225964128971 +4,SPY,2025-02-03,0.00021957955323159695,-0.006752195302397013 +4,SPY,2025-02-04,0.00017628722707740963,0.006685864645987749 +4,SPY,2025-02-05,0.00020409705757629126,0.004046328831464052 +4,SPY,2025-02-06,0.00023338451865129173,0.0034697058144956827 +4,SPY,2025-02-07,0.0002685385406948626,-0.009195869788527489 +4,SPY,2025-02-10,0.00022261106641963124,0.006768268533051014 +4,SPY,2025-02-11,0.00027013570070266724,0.000760252121835947 +4,SPY,2025-02-12,0.0003101526526734233,-0.003226685104891658 +4,SPY,2025-02-13,0.000314222153974697,0.010502160526812077 +4,SPY,2025-02-14,0.0003858326526824385,-4.907635957351886e-05 +4,SPY,2025-02-18,0.00041625084122642875,0.0029314944986253977 +4,SPY,2025-02-19,0.0004248390905559063,0.002352049108594656 +4,SPY,2025-02-20,0.0004329334478825331,-0.004168923012912273 +4,SPY,2025-02-21,0.00042309699347242713,-0.01725207269191742 +4,SPY,2025-02-24,0.00029235993861220777,-0.0045607914216816425 +4,SPY,2025-02-25,0.00015651471039745957,-0.00498559046536684 +4,SPY,2025-02-26,0.0001362888142466545,0.0005047746235504746 +4,SPY,2025-02-27,0.0001357969595119357,-0.01609077863395214 +4,SPY,2025-02-28,0.0001082701564882882,0.015485081821680069 +4,SPY,2025-03-03,0.00012829064507968724,-0.01767526939511299 +4,SPY,2025-03-04,0.00015371745394077152,-0.011907374486327171 +4,SPY,2025-03-05,0.00011931014159927145,0.010690384544432163 +4,SPY,2025-03-06,0.0001299640571232885,-0.017910489812493324 +4,SPY,2025-03-07,-3.0124485874694074e-06,0.0055891284719109535 +4,SPY,2025-03-10,-4.032967990497127e-05,-0.02699677273631096 +4,SPY,2025-03-11,-0.00042457220843061805,-0.008347636088728905 +4,SPY,2025-03-12,-0.000543111062142998,0.005292458925396204 +4,SPY,2025-03-13,-0.0005419590743258595,-0.013419972732663155 +4,SPY,2025-03-14,-0.0005545130698010325,0.020445242524147034 +4,SPY,2025-03-17,-0.0004724726313725114,0.007681975606828928 +4,SPY,2025-03-18,-0.00033015492954291403,-0.010867433622479439 +4,SPY,2025-03-19,-0.00034985324600711465,0.010832076892256737 +4,SPY,2025-03-20,-0.00022801908198744059,-0.002896107267588377 +4,SPY,2025-03-21,-0.0001799586316337809,0.0003298375813756138 +4,SPY,2025-03-24,-5.581355799222365e-05,0.017750129103660583 +4,SPY,2025-03-25,0.00016785833577159792,0.0024009370245039463 +4,SPY,2025-03-26,0.00017379633209202439,-0.0120100611820817 +4,SPY,2025-03-27,0.0001851111010182649,-0.0026592686772346497 +4,SPY,2025-03-28,0.00018570601241663098,-0.02034386247396469 +4,SPY,2025-03-31,0.00013077053881715983,0.006690260022878647 +4,SPY,2025-04-01,0.00014034801279194653,0.002820572117343545 +4,SPY,2025-04-02,0.0001456079917261377,0.006308358628302813 +4,SPY,2025-04-03,0.00018237360927741975,-0.05053653568029404 +4,SPY,2025-04-04,-0.0003672915045171976,-0.06032641977071762 +4,SPY,2025-04-07,0.00029044918483123183,-0.001782776671461761 +4,SPY,2025-04-08,0.0006914567784406245,-0.015786711126565933 +4,SPY,2025-04-09,0.001569318468682468,0.09986280649900436 +4,SPY,2025-04-10,6.420157296815887e-05,-0.04480811953544617 +4,SPY,2025-04-11,0.00022765157336834818,0.017685461789369583 +4,SPY,2025-04-14,7.798214937793091e-05,0.00965486466884613 +4,SPY,2025-04-15,-5.3504714742302895e-05,-0.002804951509460807 +4,SPY,2025-04-16,-0.00022017273295205086,-0.022478844970464706 +4,SPY,2025-04-17,-0.0001798143784981221,0.0014258180744946003 +4,SPY,2025-04-21,-4.753717075800523e-05,-0.02409062720835209 +4,SPY,2025-04-22,0.0001635013468330726,0.02568511851131916 +4,SPY,2025-04-23,1.688783049758058e-05,0.015376651659607887 +4,SPY,2025-04-24,-0.0003599280898924917,0.020830444991588593 +4,SPY,2025-04-25,-0.0003408658958505839,0.007199333980679512 +4,SPY,2025-04-28,-0.0002118461998179555,0.00038131242035888135 +4,SPY,2025-04-29,-7.686860044486821e-05,0.0062796310521662235 +4,SPY,2025-04-30,2.2804539185017347e-05,0.00039675136213190854 +4,SPY,2025-05-01,5.03231021866668e-05,0.007061762735247612 +4,SPY,2025-05-02,1.4789883607591037e-05,0.014735151082277298 +4,SPY,2025-05-05,0.00019792342209257185,-0.005750719457864761 +4,SPY,2025-05-06,0.00020481491810642183,-0.008393452502787113 +4,SPY,2025-05-07,0.00020149900228716433,0.004196487832814455 +4,SPY,2025-05-08,0.00020191735529806465,0.0069437106139957905 +4,SPY,2025-05-09,0.00020803327788598835,-0.001274924143217504 +4,SPY,2025-05-12,0.00023615841928403825,0.032513104379177094 +4,SPY,2025-05-13,0.0002329379931325093,0.006582255940884352 +4,SPY,2025-05-14,0.000233020429732278,0.0012771611800417304 +4,SPY,2025-05-15,0.0002333755837753415,0.004872395657002926 +4,SPY,2025-05-16,0.00023063122353050858,0.00631406856700778 +4,SPY,2025-05-19,0.0002320930507266894,0.001093221828341484 +4,SPY,2025-05-20,0.0002291796845383942,-0.003367818659171462 +4,SPY,2025-05-21,0.00022969147539697587,-0.01699436455965042 +4,SPY,2025-05-22,0.00023454615438822657,0.00039463021676056087 +4,SPY,2025-05-23,0.00021687296975869685,-0.006849146913737059 +4,SPY,2025-05-27,0.00021718896459788084,0.02057729661464691 +4,SPY,2025-05-28,0.00022401862952392548,-0.005802148021757603 +4,SPY,2025-05-29,0.00022624160919804126,0.003939776681363583 +4,SPY,2025-05-30,0.00022178741346579045,-0.0011193418176844716 +4,SPY,2025-06-02,0.0002223960473202169,0.005617220886051655 +4,SPY,2025-06-03,0.0002159572613891214,0.005686462856829166 +4,SPY,2025-06-04,0.0002139568532584235,-0.000268652307568118 +4,SPY,2025-06-05,0.00021174419089220464,-0.004844367504119873 +4,SPY,2025-06-06,0.00021356460638344288,0.01021655835211277 +4,SPY,2025-06-09,0.00020348085672594607,0.000900822866242379 +4,SPY,2025-06-10,0.00019373097165953368,0.0056538088247179985 +4,SPY,2025-06-11,0.00018499982252251357,-0.0028562552761286497 +4,SPY,2025-06-12,0.00018894979439210147,0.003966604359447956 +4,SPY,2025-06-13,0.00018069469660986215,-0.011243232525885105 +4,SPY,2025-06-16,0.00019970606081187725,0.009469368495047092 +4,SPY,2025-06-17,0.00019473322026897222,-0.008581787347793579 +4,SPY,2025-06-18,0.00020142756693530828,-0.00015072443056851625 +4,SPY,2025-06-20,0.00019958721532020718,-0.0023513399064540863 +4,SPY,2025-06-23,0.00019722686556633562,0.009829021990299225 +4,SPY,2025-06-24,0.0001923021045513451,0.010986611247062683 +4,SPY,2025-06-25,0.0001966312702279538,0.0005602274904958904 +4,SPY,2025-06-26,0.00017905425920616835,0.0077933622524142265 +4,SPY,2025-06-27,0.00017835013568401337,0.004956020973622799 +4,SPY,2025-06-30,0.00018639226618688554,0.004769785795360804 +4,SPY,2025-07-01,0.00018659079796634614,-0.0003236666671000421 +4,SPY,2025-07-02,0.00018774349882733077,0.004523120820522308 +4,SPY,2025-07-03,0.0001962871028808877,0.00785040482878685 +4,SPY,2025-07-07,0.00021258433116599917,-0.007479777559638023 +4,SPY,2025-07-08,0.00023290228273253888,-0.0005479847895912826 +4,SPY,2025-07-09,0.00024222351203206927,0.005978846922516823 +4,SPY,2025-07-10,0.0002582603774499148,0.002816288499161601 +4,SPY,2025-07-11,0.00027041323482990265,-0.0035217006225138903 +4,SPY,2025-07-14,0.00026747307856567204,0.0019064645748585463 +4,SPY,2025-07-15,0.00026755896396934986,-0.004282367881387472 +4,SPY,2025-07-16,0.00024497200502082705,0.0033375979401171207 +4,SPY,2025-07-17,0.0002690990804694593,0.006100890226662159 +4,SPY,2025-07-18,0.00031647190917283297,-0.000732504588086158 +4,SPY,2025-07-21,0.0003288603911641985,0.0018941516755148768 +4,SPY,2025-07-22,0.0003454516117926687,0.00014318519970402122 +4,SPY,2025-07-23,0.0003594867011997849,0.008471492677927017 +4,SPY,2025-07-24,0.00039208665839396417,0.00033107216586358845 +4,SPY,2025-07-25,0.0003953668347094208,0.004215440712869167 +4,SPY,2025-07-28,0.0004037167236674577,-0.00025119740166701376 +4,SPY,2025-07-29,0.00039716047467663884,-0.002640952356159687 +4,SPY,2025-07-30,0.0003766467561945319,-0.0012602604692801833 +4,SPY,2025-07-31,0.00035797542659565806,-0.003758314996957779 +4,SPY,2025-08-01,0.00032531985198147595,-0.016526129096746445 +4,SPY,2025-08-04,0.00018089322838932276,0.015085403807461262 +4,SPY,2025-08-05,0.00021997111616656184,-0.005082821939140558 +4,SPY,2025-08-06,0.0001946171250892803,0.007630572188645601 +4,SPY,2025-08-07,0.0002550385834183544,-0.0008379873470403254 +4,SPY,2025-08-08,0.0002664742642082274,0.007767213508486748 +4,SPY,2025-08-11,0.0003276389907114208,-0.0019794590771198273 +4,SPY,2025-08-12,0.00033898535184562206,0.010589808225631714 +4,SPY,2025-08-13,0.000380589859560132,0.0034172870218753815 +4,SPY,2025-08-14,0.0003903040196746588,9.300924284616485e-05 +4,SPY,2025-08-15,0.0003833314694929868,-0.002343942876905203 +4,SPY,2025-08-18,0.0003722962865140289,-0.00021764033590443432 +4,SPY,2025-08-19,0.0003524104249663651,-0.0054399664513766766 +4,SPY,2025-08-20,0.00031484797364100814,-0.0026606169994920492 +4,SPY,2025-08-21,0.0002898086095228791,-0.004019781481474638 +4,SPY,2025-08-22,0.00022984878160059452,0.015239916741847992 +4,SPY,2025-08-25,0.0003185629902873188,-0.004410541150718927 +4,SPY,2025-08-26,0.00030337381758727133,0.004178036004304886 +4,SPY,2025-08-27,0.0003406965406611562,0.0022760520223528147 +4,SPY,2025-08-28,0.00035790877882391214,0.003535163588821888 +4,SPY,2025-08-29,0.00037196173798292875,-0.005981587804853916 +4,SPY,2025-09-02,0.0003346479497849941,-0.007437940686941147 +4,SPY,2025-09-03,0.0002496837987564504,0.005405009258538485 +4,SPY,2025-09-04,0.00028703195857815444,0.00832268688827753 +4,SPY,2025-09-05,0.0003531729453243315,-0.0029004914686083794 +4,SPY,2025-09-08,0.0003486308269202709,0.002453660359606147 +4,SPY,2025-09-09,0.00036602787440642715,0.002309216186404228 +4,SPY,2025-09-10,0.00037849877844564617,0.002886634785681963 +4,SPY,2025-09-11,0.0003871303051710129,0.008275855332612991 +4,SPY,2025-09-12,0.0004038067127112299,-0.00033468642504885793 +4,SPY,2025-09-15,0.00039640002069063485,0.005309747066348791 +4,SPY,2025-09-16,0.0004092666204087436,-0.0013777401763945818 +4,SPY,2025-09-17,0.0004018853360321373,-0.0012432296061888337 +4,SPY,2025-09-18,0.00038188748294487596,0.004661617334932089 +4,SPY,2025-09-19,0.00037535460432991385,0.0049406434409320354 +4,SPY,2025-09-22,0.0003867195046041161,0.004719892982393503 +4,SPY,2025-09-23,0.00041079233051277697,-0.00545843318104744 +4,SPY,2025-09-24,0.0003925558412447572,-0.0031866435892879963 +4,SPY,2025-09-25,0.00037055418943054974,-0.004624142311513424 +4,SPY,2025-09-26,0.0003264711704105139,0.005712592508643866 +4,SPY,2025-09-29,0.0003560794284567237,0.0028065978549420834 +4,SPY,2025-09-30,0.0003809868940152228,0.003759665647521615 +4,SPY,2025-10-01,0.000422859302489087,0.0034017800353467464 +4,SPY,2025-10-02,0.0004438154282979667,0.0011511619668453932 +4,SPY,2025-10-03,0.0004587586736306548,-1.4713555174239445e-05 +4,SPY,2025-10-06,0.0004569698648992926,0.0035797646269202232 +4,SPY,2025-10-07,0.00045850174501538277,-0.003714311867952347 +4,SPY,2025-10-08,0.00044715951662510633,0.00594525458291173 +4,SPY,2025-10-09,0.0004521179071161896,-0.0029011790174990892 +4,SPY,2025-10-10,0.0004480759089346975,-0.027399832382798195 +4,SPY,2025-10-13,0.0002030982286669314,0.015227587893605232 +4,SPY,2025-10-14,0.00020268124353606254,-0.0012223931262269616 +4,SPY,2025-10-15,0.00017771607963368297,0.0044297040440142155 +4,SPY,2025-10-16,0.00020385868265293539,-0.006833522580564022 +4,SPY,2025-10-17,0.00016840858734212816,0.005660249385982752 +4,SPY,2025-10-20,0.00020637498528230935,0.010346787050366402 +4,SPY,2025-10-21,0.0002848501899279654,-1.4942989764676895e-05 +4,SPY,2025-10-22,0.0003367431345395744,-0.005212569609284401 +4,SPY,2025-10-23,0.00032431347062811255,0.0059125423431396484 +4,SPY,2025-10-24,0.00036114914109930396,0.008139340206980705 +4,SPY,2025-10-27,0.00038901943480595946,0.011728614568710327 +4,SPY,2025-10-28,0.0004108019347768277,0.0026524949353188276 +4,SPY,2025-10-29,0.0004072888696100563,0.0004801657923962921 diff --git a/ml_engine/walk_forward_reports/walk_forward_chart.png b/ml_engine/walk_forward_reports/walk_forward_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..b403a648609bc248bddb1e11bf471a94dce5a6e6 --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:587f6937ca2e0f7283eb47be691216738802e25fb1369bc95e4a99b974408afc +size 37124 diff --git a/ml_engine/walk_forward_reports/walk_forward_chart_seed123.png b/ml_engine/walk_forward_reports/walk_forward_chart_seed123.png new file mode 100644 index 0000000000000000000000000000000000000000..12e2cdb401eba27cd187de6f03f965b91d30cc54 --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_chart_seed123.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2326752de6b788c703007ca46b4274bfb7d5cdc153acb186f06a58713aaf93a9 +size 33959 diff --git a/ml_engine/walk_forward_reports/walk_forward_chart_seed42.png b/ml_engine/walk_forward_reports/walk_forward_chart_seed42.png new file mode 100644 index 0000000000000000000000000000000000000000..b7ffa917395cb81220b5195aaf6cd8cc68c61bbb --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_chart_seed42.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55e0262d458fc91457210cca1659dc1096561884496ac30a1e458112ed166072 +size 35523 diff --git a/ml_engine/walk_forward_reports/walk_forward_chart_seed7.png b/ml_engine/walk_forward_reports/walk_forward_chart_seed7.png new file mode 100644 index 0000000000000000000000000000000000000000..5a019445e8cc4445eeef417dab9c375e8b66f1dc --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_chart_seed7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e3488e39c1e58333039e2f0eec52674e4ab9a0a8eb9ce2902438531ffc7f970 +size 34057 diff --git a/ml_engine/walk_forward_reports/walk_forward_chart_seed999.png b/ml_engine/walk_forward_reports/walk_forward_chart_seed999.png new file mode 100644 index 0000000000000000000000000000000000000000..97d2d9cb6a1998a9b4dc7f922c9db11a4b675b60 --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_chart_seed999.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cb75404b631503402f458393c47d76a3445c932a197a5f05aa0c75d88f211b4 +size 34065 diff --git a/ml_engine/walk_forward_reports/walk_forward_results.csv b/ml_engine/walk_forward_reports/walk_forward_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..d5a34681bfa466819ece5e0e9df9236fd100240d --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_results.csv @@ -0,0 +1,21 @@ +fold,ticker,n_test,directional_accuracy,mae_price,rmse_price +1,BTC-USD,59,0.4745762711864407,1602.5887451171875,2116.2251770546536 +1,ETH-USD,59,0.4915254237288136,81.11334991455078,111.53338205443248 +1,LTC-USD,59,0.3898305084745763,2.805001974105835,3.830678531909398 +1,XRP-USD,59,0.3728813559322034,0.06021074205636978,0.0778872956632858 +1,BCH-USD,59,0.4915254237288136,17.584733963012695,21.58944831542606 +2,BTC-USD,58,0.41379310344827586,1601.058349609375,2469.799283342677 +2,ETH-USD,58,0.43103448275862066,71.36322784423828,103.90145195689038 +2,LTC-USD,58,0.3793103448275862,1.5505378246307373,2.1995810283175015 +2,XRP-USD,58,0.3275862068965517,0.05483480915427208,0.08160073410022738 +2,BCH-USD,58,0.4482758620689655,14.988155364990234,23.682025206284486 +3,BTC-USD,58,0.5517241379310345,1344.887451171875,1707.7619125627552 +3,ETH-USD,58,0.5344827586206896,55.38052749633789,71.80187176573115 +3,LTC-USD,58,0.5344827586206896,0.9668501615524292,1.2953963525225722 +3,XRP-USD,58,0.43103448275862066,0.02684527076780796,0.03407636591270704 +3,BCH-USD,58,0.4827586206896552,8.204520225524902,10.297065420517345 +4,BTC-USD,58,0.43103448275862066,1175.3330078125,1527.7003141977814 +4,ETH-USD,58,0.46551724137931033,45.82375717163086,59.9267965710301 +4,LTC-USD,58,0.43103448275862066,1.0779625177383423,1.3548529377624576 +4,XRP-USD,58,0.41379310344827586,0.03114324063062668,0.03778639552644426 +4,BCH-USD,58,0.3793103448275862,10.829004287719727,14.044359501717285 diff --git a/ml_engine/walk_forward_reports/walk_forward_results_seed123.csv b/ml_engine/walk_forward_reports/walk_forward_results_seed123.csv new file mode 100644 index 0000000000000000000000000000000000000000..7a55bc72dcb8a012d7cebaa02fd41f368cf84d3d --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_results_seed123.csv @@ -0,0 +1,9 @@ +fold,ticker,n_test,directional_accuracy,mae_price,rmse_price +1,BTC-USD,59,0.5254237288135594,1594.9993896484375,2064.9320812075152 +1,ETH-USD,59,0.5084745762711864,80.42790985107422,109.96767991096293 +2,BTC-USD,58,0.5862068965517241,1556.4859619140625,2421.1636665041874 +2,ETH-USD,58,0.5689655172413793,70.28656768798828,101.15959022906577 +3,BTC-USD,58,0.5517241379310345,1345.3924560546875,1706.7166577964838 +3,ETH-USD,58,0.5344827586206896,55.39313507080078,71.92907612494061 +4,BTC-USD,58,0.43103448275862066,1222.539794921875,1576.019749241741 +4,ETH-USD,58,0.46551724137931033,47.28200912475586,61.13912357599367 diff --git a/ml_engine/walk_forward_reports/walk_forward_results_seed42.csv b/ml_engine/walk_forward_reports/walk_forward_results_seed42.csv new file mode 100644 index 0000000000000000000000000000000000000000..98adff670e21ab0a7f2ae441b6debfb61ad58b0f --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_results_seed42.csv @@ -0,0 +1,9 @@ +fold,ticker,n_test,accuracy,actionable_accuracy,signal_precision,n_signals,primary_metric +1,BTC-USD,261,0.31417624521072796,0.4823529411764706,0.3215686274509804,255,0.4823529411764706 +1,ETH-USD,217,0.5345622119815668,0.7116564417177914,0.5345622119815668,217,0.7116564417177914 +2,BTC-USD,261,0.42911877394636017,0.6021505376344086,0.42911877394636017,261,0.6021505376344086 +2,ETH-USD,217,0.29493087557603687,0.40764331210191085,0.29493087557603687,217,0.40764331210191085 +3,BTC-USD,261,0.2260536398467433,0.3089005235602094,0.2260536398467433,261,0.3089005235602094 +3,ETH-USD,217,0.3640552995391705,0.5602836879432624,0.3640552995391705,217,0.5602836879432624 +4,BTC-USD,261,0.4099616858237548,0.5245098039215687,0.4099616858237548,261,0.5245098039215687 +4,ETH-USD,217,0.39631336405529954,0.5,0.39631336405529954,217,0.5 diff --git a/ml_engine/walk_forward_reports/walk_forward_results_seed7.csv b/ml_engine/walk_forward_reports/walk_forward_results_seed7.csv new file mode 100644 index 0000000000000000000000000000000000000000..d584680c7634cd50ab8564fc77009b19c7527caa --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_results_seed7.csv @@ -0,0 +1,9 @@ +fold,ticker,n_test,directional_accuracy,mae_price,rmse_price +1,BTC-USD,59,0.5254237288135594,1577.722900390625,2036.6978789206808 +1,ETH-USD,59,0.5084745762711864,83.2860107421875,109.07382641759204 +2,BTC-USD,58,0.5862068965517241,1546.8499755859375,2402.144666750943 +2,ETH-USD,58,0.5689655172413793,69.45384216308594,99.85963293074184 +3,BTC-USD,58,0.4482758620689655,1350.9276123046875,1723.5387288947122 +3,ETH-USD,58,0.46551724137931033,55.47433090209961,72.20747829605324 +4,BTC-USD,58,0.43103448275862066,1084.1533203125,1424.9042511691794 +4,ETH-USD,58,0.46551724137931033,38.269676208496094,53.2132355481228 diff --git a/ml_engine/walk_forward_reports/walk_forward_results_seed999.csv b/ml_engine/walk_forward_reports/walk_forward_results_seed999.csv new file mode 100644 index 0000000000000000000000000000000000000000..92e51d034c0b4a28c841024bd02175f1aa192e66 --- /dev/null +++ b/ml_engine/walk_forward_reports/walk_forward_results_seed999.csv @@ -0,0 +1,9 @@ +fold,ticker,n_test,directional_accuracy,mae_price,rmse_price +1,BTC-USD,59,0.4745762711864407,1585.528076171875,2083.8355261392394 +1,ETH-USD,59,0.5084745762711864,80.20633697509766,109.97864228027413 +2,BTC-USD,58,0.5862068965517241,1558.387451171875,2406.7899783736843 +2,ETH-USD,58,0.5689655172413793,71.78616333007812,100.86589468664569 +3,BTC-USD,58,0.4482758620689655,1381.3580322265625,1755.6124999555 +3,ETH-USD,58,0.46551724137931033,56.72895050048828,73.42634888742256 +4,BTC-USD,58,0.43103448275862066,1062.188720703125,1395.7997707407749 +4,ETH-USD,58,0.46551724137931033,36.71179962158203,51.43057222864262 diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..4bba72462caaa00a5e08da3faa476eb4c4d30553 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,174 @@ +{ + "name": "kodaquant_backend", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@supabase/supabase-js": "^2.110.0", + "framer-motion": "^12.42.2", + "lucide-react": "^1.27.0" + } + }, + "node_modules/@supabase/auth-js": { + "version": "2.110.0", + "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.0.tgz", + "integrity": "sha512-Mi288WCTp6wxMFCOu/UgzgHEXODjdl2uVTLqK11eanzGZaldU3RyP8Am+ZbNuVzFP+5+iOvppxzv7N5Ym84xTg==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.110.0", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.110.0.tgz", + "integrity": "sha512-Fde5wlY8ZZy+9yqrWlQHo8MacSyUBArBEtN2boB4thJQigPnQD/cc61qZN0n3I1L0gwhWtHYwIMnOBKxSvF6Hw==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/phoenix": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.4.tgz", + "integrity": "sha512-Gt0pqoXuIqX/8dvG0OKp/wMCobXNH3klNbUPBNyOfN0YA1IswrM3HyWFMOPk1Jy+BRaIyDPcFx4jLBwHNmlyfQ==", + "license": "MIT" + }, + "node_modules/@supabase/postgrest-js": { + "version": "2.110.0", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.110.0.tgz", + "integrity": "sha512-ZbC1QZL3jcvBUfVKjJbgRM27G4Mg3Zzqdm44m5pJafe1e52Cli793EOnwQucomBAGEUDd03Nzaf7XV3ji/XexQ==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.110.0", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.110.0.tgz", + "integrity": "sha512-Wn2AWpneZuDFTkp/65tqctvoh+3JvyTjMam8sTMqVWy5BgkU8zAvFwilPYPPPhkINeKF8NAJKP7FclJ2iGCUMw==", + "license": "MIT", + "dependencies": { + "@supabase/phoenix": "0.4.4", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.110.0", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.110.0.tgz", + "integrity": "sha512-71+gU3HrhiylAhftY6FmO5PPdcsScnVcS766CVD+vTYK9qTDLbrx8FhgBYbqGm3iV/wkTfzrNJfjGsMeFRkJRQ==", + "license": "MIT", + "dependencies": { + "iceberg-js": "^0.8.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.110.0", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.110.0.tgz", + "integrity": "sha512-8yI84VJiEVW4zxZpLUmxXmjzQ7O2St9X/ymzlBETDHTURPWG3LmvbSiibq+7dqAJmyoUfxZnSfXeM4HCM8s4XQ==", + "license": "MIT", + "dependencies": { + "@supabase/auth-js": "2.110.0", + "@supabase/functions-js": "2.110.0", + "@supabase/postgrest-js": "2.110.0", + "@supabase/realtime-js": "2.110.0", + "@supabase/storage-js": "2.110.0" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/framer-motion": { + "version": "12.42.2", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.42.2.tgz", + "integrity": "sha512-5XY9luDiu0oHfHBjpDthFMh0ES+122w6p/papSJBweMkO8Sn+PW2QaEgRblQBpWFnuvZS5qvarpt/hO2pjGmnw==", + "license": "MIT", + "dependencies": { + "motion-dom": "^12.42.2", + "motion-utils": "^12.39.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/iceberg-js": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", + "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/lucide-react": { + "version": "1.27.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.27.0.tgz", + "integrity": "sha512-rJicGl/3Fly/E0rOH1YmPZ6e49JCnKknh1ox1vpHnkfjujAkKA6sqUZvH3MTAaXXjgexyUwgNwTJzTtYuAFYJw==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/motion-dom": { + "version": "12.42.2", + "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.42.2.tgz", + "integrity": "sha512-5gIMWLp/PycBtJRJWRgjxke5n8dlvkSn2DrYW+tr3XcqAZY1xZh6BJyooJXCM8wdfM7wfMjkBJNLge1CKPUIRA==", + "license": "MIT", + "dependencies": { + "motion-utils": "^12.39.0" + } + }, + "node_modules/motion-utils": { + "version": "12.39.0", + "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.39.0.tgz", + "integrity": "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ==", + "license": "MIT" + }, + "node_modules/react": { + "version": "19.2.8", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", + "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b0414ce6019fe08de274516400df37bb55ee6ebf --- /dev/null +++ b/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "@supabase/supabase-js": "^2.110.0", + "framer-motion": "^12.42.2", + "lucide-react": "^1.27.0" + } +} diff --git a/payments/__init__.py b/payments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/purify_scalers.py b/purify_scalers.py new file mode 100644 index 0000000000000000000000000000000000000000..1fbdbf1548b93b766524fee0b24bb14cbf9c6f5a --- /dev/null +++ b/purify_scalers.py @@ -0,0 +1,83 @@ +""" +purify_scalers.py +================== +Ejecutar UNA VEZ, desde la raíz del proyecto (mismo nivel que main.py): + + python purify_scalers.py + +Objetivo único: eliminar el `InconsistentVersionWarning` de scikit-learn + "Trying to unpickle estimator StandardScaler from version 1.6.1 when + using version 1.4.2" + "Trying to unpickle estimator MinMaxScaler from version 1.6.1 when + using version 1.4.2" + +re-serializando `services/scalers.pkl` con la firma binaria NATIVA de la +versión de scikit-learn instalada en este venv (1.4.2, LTS Lock). Es un +load + dump inmediato — joblib inyecta el `__getstate__`/metadata de +versión ACTUALES al guardar, así que la próxima carga no dispara ningún +warning de compatibilidad. Cero reentrenamiento, cero alteración de +valores: los `StandardScaler`/`MinMaxScaler` (mean_, scale_, data_min_, +data_max_, etc.) quedan bit-a-bit idénticos, solo cambia el metadato de +versión embebido por pickle. +""" + +import os +import warnings + +# Debe importarse y suprimirse ANTES de `joblib.load()`, porque el warning +# se dispara en `BaseEstimator.__setstate__` durante la deserialización, no +# al importar el módulo. +from sklearn.exceptions import InconsistentVersionWarning + +import joblib + +# Ruta ANCLADA a la ubicación de este script (se ejecuta desde la raíz del +# proyecto; `services/` vive un nivel abajo, tal cual el árbol de directorio +# provisto) — nunca al cwd del proceso que invoca el script. +_ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) +SCALERS_PATH = os.path.join(_ROOT_DIR, "services", "scalers.pkl") + +# Claves mínimas que `quanti_engine.py` espera encontrar en el bundle +# (`feature_scalers`, `target_scalers`, `asset_to_id`) — se valida ANTES de +# sobreescribir el archivo, para no hornear un dump corrupto o vacío sobre +# el único artefacto de scalers del proyecto. +_REQUIRED_KEYS = {"feature_scalers", "target_scalers", "asset_to_id", "lookback", "macro_tickers"} + + +def purify_scalers(path: str = SCALERS_PATH) -> None: + if not os.path.exists(path): + raise FileNotFoundError(f"No se encontró el bundle de scalers en: {path}") + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=InconsistentVersionWarning) + bundle = joblib.load(path) + + if not isinstance(bundle, dict) or not _REQUIRED_KEYS.issubset(bundle.keys()): + missing = _REQUIRED_KEYS - (bundle.keys() if isinstance(bundle, dict) else set()) + raise ValueError( + "El objeto cargado no tiene la forma esperada del bundle de " + f"KodaQuant — faltan claves: {sorted(missing)}. Se aborta el dump " + "para no sobreescribir services/scalers.pkl con una estructura desconocida." + ) + + # Backup defensivo antes de sobreescribir — un solo archivo, cero riesgo. + backup_path = path + ".bak" + if not os.path.exists(backup_path): + with open(path, "rb") as src, open(backup_path, "wb") as dst: + dst.write(src.read()) + + joblib.dump(bundle, path) + + n_features = len(bundle["feature_scalers"]) + n_targets = len(bundle["target_scalers"]) + print( + f"✅ scalers.pkl purificado y re-firmado con scikit-learn instalado.\n" + f" Ruta: {path}\n" + f" Backup preservado en: {backup_path}\n" + f" feature_scalers: {n_features} tickers | target_scalers: {n_targets} tickers\n" + f" Vuelve a levantar Uvicorn — el InconsistentVersionWarning no debería reaparecer." + ) + + +if __name__ == "__main__": + purify_scalers() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..78d16fb3f960346102c218e5adce4d73bdecd070 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,336 @@ +# --- Web framework (bounds mirror what gradio==6.22.0 itself requires, +# since HF's Gradio SDK auto-installs it alongside this file) ------------- +fastapi>=0.115.2,<1.0 +starlette>=1.0.1,<2.0 +uvicorn>=0.32.0,<1.0 +uvloop==0.22.1 +httptools==0.8.0 +watchfiles==1.2.0 +websockets==15.0.1 +h11==0.16.0 +h2==4.3.0 +hpack==4.2.0 +hyperframe==6.1.0 +anyio>=4.14.1,<5.0 + +# --- Data validation / settings ------------------------------------------- +# Range narrowed to what gradio[mcp]==6.22.0 itself requires +# (pydantic>=2.11.10,<=2.12.5) — ZeroGPU pulls in the mcp extra, whose +# pydantic bound is tighter than gradio's own base <=3.0. +pydantic>=2.11.10,<=2.12.5 +# pydantic_core intentionally NOT pinned here: it must match pydantic's +# own exact internal requirement. Pinning both and then loosening only +# pydantic re-creates the same class of conflict this file just fixed. +pydantic-settings==2.14.2 +annotated-types==0.7.0 +typing-inspection==0.4.2 +typing_extensions>=4.16.0,<5.0 +email-validator==2.3.0 + +# --- HTTP / networking ----------------------------------------------------- +httpx>=0.28.1,<1.0 +httpcore==1.0.9 +requests==2.34.2 +urllib3==2.7.0 +certifi==2026.6.17 +idna==3.18 +charset-normalizer==3.4.7 +dnspython==2.8.0 +yarl==1.24.2 +multidict==6.7.1 +propcache==0.5.2 +frozendict==2.4.7 + +# --- Auth / security --------------------------------------------------- +PyJWT==2.13.0 +cryptography==48.0.1 +cffi==2.0.0 +pycparser==3.0 + +# --- Pagos --------------------------------------------------------------- +stripe>=15.0,<16.0 + +# --- ZeroGPU probe (gradio.Server nativo, ver main.py) ------------------- +# `spaces` NO se pinea acá a propósito: la plataforma de HF Spaces ya lo +# fuerza a su propia versión en el build (ver el log de build: agrega +# "spaces==X.Y.Z" al pip install además de este archivo). Pinearlo de +# nuevo acá es un conflicto latente esperando pasar — ver la nota vieja +# más abajo, que documentaba el mismo riesgo sin eliminarlo. +# +# CRÍTICO: este pin (6.22.0) DEBE coincidir exacto con `sdk_version` en +# el front-matter YAML de README.md. HF inyecta `gradio[oauth,mcp]==` +# en el MISMO comando pip que procesa este archivo — si divergen, pip recibe +# dos pines `==` mutuamente excluyentes del mismo paquete y falla con +# ResolutionImpossible de inmediato (no es un conflicto de grafo real, es +# un doble pin). Root cause del build fallido del 2026-08-12 (commit 6dcbbd6): +# no existía README.md, así que HF usaba su default de plataforma (6.23.1) +# mientras este archivo fijaba 6.22.0. +gradio[oauth,mcp]==6.22.0 + +# --- Database / Supabase ------------------------------------------------- +supabase==2.31.0 +supabase-auth==2.31.0 +supabase-functions==2.31.0 +postgrest==2.31.0 +realtime==2.31.0 +storage3==2.31.0 +peewee==4.1.1 + +# --- Data / ML / forecasting (fixed — critical for the predictive models, +# not touched by the Gradio conflict) --------------------------------- +# FIX 2026-08-31 (RONDA 7) -- ResolutionImpossible real: `numpy==2.5.1` +# (pin único, toda plataforma) vs `tensorflow` resolviendo a 2.16.2 en +# macOS Intel local (Mac Intel i7 -- KodaQuant volvió a entrenamiento 100% +# local, ver historial de este archivo). Verificado en vivo contra el +# METADATA real del wheel (pip download + inspección del .whl, no +# supuesto): TensorFlow 2.16.2 es la ÚLTIMA versión con wheel +# macosx_x86_64 publicado (2.17+ solo publica arm64/Linux/Windows -- +# GH issue tensorflow/tensorflow#78836, confirmado independientemente por +# el fix ya existente de `torch==2.2.2; sys_platform != "linux"` más abajo +# en este mismo archivo, mismo problema de plataforma). Ese wheel 2.16.2 +# exige `numpy<2.0.0,>=1.26.0` (Requires-Dist real, cp312) -- choque +# directo y determinista contra `numpy==2.5.1`, no un conflicto de grafo +# resoluble reordenando otros pines. En Linux (HF Space, Zero GPU real) el +# rango `tensorflow>=2.16.1,<2.21` de abajo SÍ resuelve libremente a una +# versión reciente (verificado: TF 2.20.0 declara `numpy>=1.26.0` SIN techo +# superior) -- ahí `numpy==2.5.1` nunca fue el problema, motivo por el que +# el pin único enmascaraba el fallo real (solo reproducible en el entorno +# de desarrollo local, no en CI/HF). Split por plataforma, mismo patrón +# `sys_platform` ya establecido para `torch`: Linux mantiene `2.5.1` +# (último estable, sin restricción real de TensorFlow ahí); macOS/Windows +# reciben `1.26.4` (última serie 1.26.x, satisface también el piso de +# pandas==3.0.3 `numpy>=1.26.0`, scikit-learn==1.6.1 `numpy>=1.19.5` y +# statsmodels==0.14.5 `numpy<3,>=1.22.3` -- verificado contra el METADATA +# real de los 3 wheels, cero conflicto nuevo). +# +# CAVEAT HONESTO (no verificable en este entorno, sin acceso de red a +# PyPI para wheels de macOS ni a un runner macOS real): `keras==3.15.1` +# (pin único, sin split, más abajo) es un release MUCHO más nuevo que +# TensorFlow 2.16.2 (mediados de 2024) -- keras>=3.0.0 es todo lo que pide +# ese wheel de TF, pero eso es un piso, no una garantía de compatibilidad +# de API interna entre un keras de 2026 y el backend TF de 2.16.2. Si el +# entrenamiento local arranca pero falla con un error de Keras/TF distinto +# a numpy (no el síntoma reportado hoy), ese es el próximo sospechoso -- +# no se toca preventivamente el pin de keras sin evidencia real de fallo. +numpy==2.5.1; sys_platform == "linux" +numpy==1.26.4; sys_platform != "linux" +pandas==3.0.3 +# pyarrow -- engine de parquet para pandas (df.to_parquet/read_parquet, ver +# download_all en train_kodaquant_v5.py). pandas por si solo no trae ningun +# engine de parquet; sin esto, to_parquet() falla con ImportError. 25.0.1 = +# ultimo estable, wheels cp312 nativos, exige numpy>=1.21.2 (satisfecho por +# el pin de arriba). +pyarrow==25.0.1 +scikit-learn==1.6.1 +keras==3.15.1 +# TensorFlow -- split por plataforma (RONDA 7, ver nota extensa junto a +# `numpy` arriba): Linux (HF Space/Zero GPU real) resuelve libre dentro del +# rango a una versión reciente sin techo real de numpy (TF 2.20.0 +# verificado: `numpy>=1.26.0` sin `<`); macOS/Windows local topan en la +# ÚLTIMA versión con wheel Intel/Windows real (2.16.2 -- confirmado en vivo +# contra PyPI, mismo patrón/misma causa que el split de `torch` más abajo), +# que exige `numpy<2.0.0` -- de ahí el pin de `numpy==1.26.4` para esa rama. +tensorflow>=2.16.1,<2.21; sys_platform == "linux" +tensorflow==2.16.2; sys_platform != "linux" +# matplotlib -- graficas de evaluacion del modelo en train_kodaquant_v5.py +# (ml_engine/, plot_regime_evaluation -> evaluation_chart.png). 3.11.1 = +# ultimo estable, wheels cp312 nativos, compatible con numpy==2.5.1 fijado +# arriba. +matplotlib==3.11.1 +# scipy -- FALTABA POR COMPLETO en este archivo pese a ser import duro real: +# `from scipy.interpolate import CubicSpline` (train_kodaquant_v5.py, curva +# de Magnitude-Warping) y uso adicional en train_pipeline.py (test +# estadístico Champion vs. Challenger) -- `ModuleNotFoundError: No module +# named 'scipy'` real en cualquier `pip install -r requirements.txt` limpio +# (build de HF Space incluido). scipy==1.17.0 (verificado en vivo contra el +# METADATA real del wheel, agosto 2026): `Requires-Dist: numpy<2.7,>=1.26.4` +# -- UN SOLO pin sirve para AMBAS ramas de `numpy` de arriba sin split por +# plataforma (2.5.1 en Linux Y 1.26.4 en macOS/Windows caen dentro de ese +# rango) -- wheels macosx_x86_64 (Intel) confirmados hasta cp314, sin el +# problema de discontinuación de plataforma que sí afecta a torch/tensorflow. +scipy==1.17.0 +# AUDITORÍA 2026-09 -- CORRECCIÓN de la nota anterior de este archivo (yfinance +# "RETIRADOS"): esa migración a Twelve Data/Stooq (`services/market_data.py`) +# es real pero SOLO cubre el lado de INFERENCIA/producción (la Space viva, +# alto volumen concurrente -> motivo real de los bloqueos de Yahoo). El lado +# de ENTRENAMIENTO (`ml_engine/train_kodaquant_v5.py`, `import yfinance as yf`, +# `yf.download(...)` en `_download_with_backoff`/`_fetch_all_symbols_flat`) +# NUNCA migró y sigue dependiendo de `yfinance` en firme para OHLCV de +# equities/cripto y la mayoría de `MACRO_TICKERS` -- confirmado grepeando el +# import real en el módulo, no un supuesto. Con `yfinance` fuera de este +# archivo, `pip install -r requirements.txt` deja el propio script de +# entrenamiento en `ModuleNotFoundError` de arranque -- el bug real detrás +# del pedido de la Directiva Head Quant de "resolver errores residuales de +# dependencias". Restaurado + sus 3 dependencias duras reales (Requires-Dist +# del wheel de `yfinance==1.7.0`, verificado en vivo): `curl_cffi`, +# `multitasking`, `protobuf` -- `beautifulsoup4`/`lxml`/`peewee`/`pytz`/ +# `platformdirs`/`websockets`/`requests` ya estaban cubiertos por pines +# existentes en otras secciones de este archivo, cero duplicado. +yfinance==1.7.0 +curl_cffi==0.16.2 +multitasking==0.0.13 +# protobuf -- CONFLICTO REAL evitado a propósito: `tensorflow==2.16.2` +# (pin de la rama macOS/Windows, ver arriba) exige +# `protobuf<5.0.0dev,>=3.20.3` (excluyendo 4.21.0-4.21.5, Requires-Dist real +# del wheel) -- un protobuf sin techo (lo que pediría `yfinance` por sí solo) +# resolvería a la serie 7.x y chocaría de frente, el mismo patrón de doble-pin +# ya documentado arriba para `pydantic_core`/`gradio`. En Linux, la rama libre +# de `tensorflow` (>=2.16.1,<2.21) puede resolver a TF 2.20.0, que exige +# `protobuf>=5.28.0` -- rango incompatible con el techo `<5.0.0dev` de la +# rama macOS -- de ahí el split por plataforma, mismo criterio que +# numpy/scipy/torch/tensorflow arriba. +protobuf>=5.28.0; sys_platform == "linux" +protobuf>=3.20.3,<5.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5; sys_platform != "linux" + +# --- LLM / search -------------------------------------------------------- +groq>=0.31.0,<2.0.0 +ddgs>=9.0.0 + +# --- NLP / defensa en profundidad de idioma (V12 -- fix crash real) ------ +# `data_pipeline.py::_is_english_headline` (V11) ya importaba esto de forma +# opcional (try/except) pero el paquete NUNCA estuvo en este archivo --> +# ModuleNotFoundError real en cada boot del Space (ver changelog V12 del +# módulo). Puro-Python, sin key, sin dependencias nativas -- footprint +# mínimo para ZeroGPU. +langdetect==1.0.9 + +# FIX 2026-08-31 (RONDA 8) -- statsmodels==0.14.5 instalaba correctamente +# (pip show: 0.14.5) pero `from statsmodels.tsa.stattools import adfuller` +# colapsaba con `TypeError: deprecate_kwarg() missing 1 required positional +# argument: 'new_arg_name'`. Root cause: pandas 3.x cambió la firma de +# `pandas.util._decorators.deprecate_kwarg` de function-decorator +# (old_arg_name, new_arg_name) a class-decorator con firma distinta -- +# statsmodels/compat/pandas.py la re-exportaba tal cual, y stattools.py +# la usaba como `@deprecate_kwarg("unbiased", "adjusted")` (2 args string, +# firma original). Fix: parchado en vivo `statsmodels/compat/pandas.py` +# en el venv (standaloneimplementation con la firma original, sin depender +# de pandas._decorators) + purga de __pycache__. Pin no cambia. +statsmodels==0.15.0 + + +# --- NLP / Sentimiento (FinBERT) ------------------------------------------ +# FIX 2026-08-15 -- el conflicto que documentaba esta nota (transformers +# exigía huggingface-hub<1.0 frente al huggingface-hub>=1.16.0,<2.0 de +# gradio[oauth,mcp]==6.22.0) queda OBSOLETO: ese pin `<1.0` era propio de +# la serie transformers 4.x. Verificado en vivo contra PyPI (agosto 2026): +# transformers 5.15.0 declara `huggingface-hub<2.0,>=1.5.0` -- intersecta +# sin conflicto con el `>=1.16.0,<2.0` de gradio (resuelve a la última +# versión compatible de huggingface-hub dentro de ese rango; NO se pinea +# acá a propósito, mismo criterio que pydantic_core más arriba: pinear +# ambos extremos por separado es la forma más rápida de recrear un +# conflicto nuevo si cualquiera de los dos paquetes ajusta su rango). +# +# FIX 2026-08-15 (RONDA 2) -- HF rechazó el build con "torch version in +# requirements.txt is not compatible with ZeroGPU. Supported versions: +# 2.11.0, 2.10.0, 2.9.1, 2.8.0". El pin anterior (`torch==2.13.0+cpu` + +# `--extra-index-url .../whl/cpu`) tenía DOS problemas reales, no uno: +# 1. 2.13.0 no está en la whitelist que el validador de ZeroGPU chequea +# de forma ESTÁTICA contra este archivo (nunca llega a instalarse, +# el error es previo al build). +# 2. Ese validador espera el wheel CUDA real de PyPI (el que trae la +# Space cuando el hardware asignado es un ZeroGPU real) -- el índice +# CPU-only (`+cpu`, sin `nvidia-*-cu12`) es exactamente el paquete +# "liviano" que la optimización anterior buscaba a propósito, pero +# es justo lo que ZeroGPU no reconoce como compatible con su propio +# mecanismo de asignación dinámica de GPU (`spaces` parchea +# `torch.cuda` en tiempo de import; un build sin CUDA no tiene qué +# parchear). Se elimina el `--extra-index-url` por completo y se +# pinea la ÚLTIMA versión de la whitelist (2.11.0) del índice +# DEFAULT de PyPI -- el wheel real, tal como ZeroGPU lo espera. +# `_get_finbert_pipeline()` en data_pipeline.py sigue haciendo el +# import de torch de forma perezosa y DESPUÉS de que `import spaces` +# ya corrió en main.py -- el orden que exige ZeroGPU (`spaces` antes +# que cualquier import de torch) sigue respetado sin tocar nada ahí. +# Sin costo real: este Space es gratuito bajo el tier ZeroGPU +# (hardware compartido, cupo dinámico) -- no hay tarjeta ni pago +# involucrado por instalar el wheel CUDA completo. +# +# FIX 2026-08-30 (RONDA 4) -- `pip install -r requirements.txt` fallaba +# DURO en local (Mac Intel, `sys_platform == "darwin"`) con "Could not find +# a version that satisfies the requirement torch==2.11.0 (from versions: +# 2.2.0, 2.2.1, 2.2.2)": PyTorch dejó de publicar wheels macOS-x86_64 +# (Intel) después de 2.2.2 -- 2.11.0 JAMÁS va a existir para esa +# plataforma, no es un problema de índice/caché. Marcador de entorno PEP +# 508 -- Linux (HF Space, Zero GPU real) sigue recibiendo 2.11.0 exacto, +# sin cambio; macOS/Windows local reciben el último wheel Intel-compatible +# real. +torch==2.11.0; sys_platform == "linux" +torch==2.2.2; sys_platform != "linux" +# +# FIX 2026-08-31 (RONDA 5) -- FinBERT REAL en Mac Intel local, no solo +# degradado a neutral: `transformers==5.15.0` trae una compuerta interna +# ("PyTorch >= 2.5 is required but found 2.2.2") que, al no cumplirse, +# ANULA el símbolo `torch` dentro del propio paquete `transformers` -- +# cualquier código interno de `pipeline()` que lo referencie revienta con +# `NameError: name 'torch' is not defined`, pase lo que pase por parámetro +# (no es un kwarg que `data_pipeline.py` controle, es interno a +# `transformers`, confirmado leyendo `import_utils.py::is_torch_available` +# en el repo real de HF: compara versión y desactiva el backend entero). +# +# CORRECCIÓN 2026-08-31 (RONDA 6) -- el pin condicional `transformers== +# 4.44.2` para macOS de la RONDA 5 estaba MAL y se revierte: pip lo +# confirmó con un `ResolutionImpossible` real -- TODA la serie 4.x de +# `transformers` exige `huggingface-hub<1.0`, que choca de frente con el +# `huggingface-hub<2.0,>=1.16.0` que ya exige `gradio==6.22.0` en este +# MISMO archivo. No existe ninguna versión de `transformers` instalable +# por pip en este entorno que evada la compuerta `torch>=2.4/2.5` Y +# satisfaga a la vez la cota de `gradio` -- es un techo real del +# ecosistema (huggingface-hub<1.0 y la compuerta torch llegaron juntos en +# la migración a la serie 5.x), no un pin mal elegido. `transformers` +# vuelve a ser UNA sola versión para toda plataforma; el fix real de +# FinBERT en Mac Intel se movió a `data_pipeline.py::_get_finbert_pipeline` +# (fallback a backend TensorFlow -- ver docstring ahí, `tensorflow` YA es +# dependencia dura de este proyecto y SÍ publica wheels macOS-x86_64 +# vigentes; `ProsusAI/finbert` publica pesos TF nativos (`tf_model.h5`) en +# el hub, cero conversión de pesos, cero necesidad de torch en absoluto +# para ese camino). +transformers==5.15.0 + +# --- NLP / FinBERT vía ONNX Runtime (backend independiente de torch/TF) --- +# Camino primario de _score_text. `tokenizers` es Rust puro (wheels +# macosx_x86_64 vigentes, cero dependencia de torch); `onnxruntime` publica +# wheels para las 3 plataformas. `huggingface_hub` ya entra por gradio. +onnxruntime==1.19.2 +tokenizers>=0.22.0,<1.0 + +# --- Parsing / scraping --------------------------------------------------- +beautifulsoup4==4.15.0 +lxml==6.1.1 +html5lib==1.1 +soupsieve==2.8.4 +webencodings==0.5.1 + +# --- Email ----------------------------------------------------------------- +# aiosmtplib RETIRADO: Hugging Face Spaces bloquea a nivel de firewall de +# red TODO el egress saliente a puertos SMTP (25/465/587) -- confirmado con +# traceback real (TimeoutError en aiosmtplib.smtp._create_connection, nunca +# llega a abrir la conexión TCP, sin importar 587/STARTTLS ni 465/SSL). Solo +# 443 sale garantizado en este entorno (mismo puerto que ya usan Supabase/ +# Stripe sin problema). Migrado al SDK oficial de Resend sobre HTTPS. Ver +# core/security.py::_send_mail_message. +resend>=2.0.0,<3.0 + +# --- Misc / packaging ------------------------------------------------- +python-dotenv==1.2.2 +python-dateutil==2.9.0.post0 +pytz==2026.2 +PyYAML>=6.0.3,<7.0 +click==8.4.2 +deprecation==2.1.0 +packaging==26.2 +platformdirs==4.10.0 +# FIX 2026-08-15 (RONDA 3) -- ResolutionImpossible real en el build de HF: +# `torch==2.11.0` exige `setuptools<82` (verificado en el METADATA real +# del wheel: `Requires-Dist: setuptools<82`) contra el `setuptools==83.0.0` +# que este archivo pineaba -- dos pines `==`/`<` mutuamente excluyentes +# del mismo paquete, exactamente la misma clase de conflicto que ya se +# documentó arriba para `pydantic_core`/`spaces`. Se destina el pin acá +# por la misma razón: dejar que pip resuelva la versión de `setuptools` +# más alta que satisfaga TODOS los constraints reales (torch incluido) +# en vez de fijar un número que choca apenas cambie cualquiera de los dos +# extremos. Nada de este proyecto depende de una versión exacta de +# `setuptools` -- es pura herramienta de build para paquetes con +# `setup.py` legacy en la cadena de dependencias. +six==1.17.0 +StrEnum==0.4.15 +wheel==0.47.0 \ No newline at end of file diff --git a/services/__init__.py b/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/services/currency_engine.py b/services/currency_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..51e892adae9c69d1c71ff4b11b88a8caf66bff7e --- /dev/null +++ b/services/currency_engine.py @@ -0,0 +1,51 @@ +import logging + +# Configuración del logger interno +logger = logging.getLogger(__name__) + +# Matriz Propietaria de KodaQuant (100% Offline y Autónoma) +# Aquí tú tienes el control absoluto de las tasas del mercado. +KODAQUANT_EXCHANGE_RATES = { + "USD": 1.0, # Dólar Estadounidense (Base) + "MXN": 18.50, # Peso Mexicano + "EUR": 0.92, # Euro + "GBP": 0.78, # Libra Esterlina + "CAD": 1.36 # Dólar Canadiense +} + +async def convert_to_usd(amount: float, currency: str) -> dict: + """ + Motor cuantitativo de conversión interno. + Cero dependencias de APIs externas. Latencia cero. + """ + currency_code = currency.upper().strip() + + # 1. Validación estricta en la matriz local + if currency_code not in KODAQUANT_EXCHANGE_RATES: + logger.error(f"Fallo de motor: Divisa {currency_code} fuera del radar autónomo.") + raise ValueError(f"La divisa {currency_code} no está soportada en el ecosistema KodaQuant.") + + # 2. Si ya son dólares, retorna el monto puro + if currency_code == "USD": + return { + "original_amount": amount, + "original_currency": currency_code, + "usd_amount": float(amount), + "internal_rate": 1.0, + "status": "autonomous_success" + } + + # 3. Cálculo matemático instantáneo + internal_rate = KODAQUANT_EXCHANGE_RATES[currency_code] + budget_usd = round(amount / internal_rate, 2) + + logger.info(f"Conversión ejecutada localmente: {amount} {currency_code} -> {budget_usd} USD") + + # 4. Retorno del reporte estructurado + return { + "original_amount": amount, + "original_currency": currency_code, + "usd_amount": budget_usd, + "internal_rate": internal_rate, + "status": "autonomous_success" + } \ No newline at end of file diff --git a/services/data_pipeline.py b/services/data_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..80450657d1fd0d55e81b19850d741e94cbd7b704 --- /dev/null +++ b/services/data_pipeline.py @@ -0,0 +1,1041 @@ +""" +services/data_pipeline.py + +Fragmento de Ingeniería de Features — Pipeline NLP de Sentimiento de Noticias +============================================================================== +KodaQuant V5 — Requerimiento 1 (Cero Fricción / Anti-CAPTCHAs). + +Añade la variable continua `NEWS_SENTIMENT_SCORE` (rango [-1, 1]) al tensor +de entrada del modelo, calculada EXCLUSIVAMENTE con APIs nativas: + + 1) DDGS (DuckDuckGo News Search) -> fuente primaria, sin API key. + Reemplaza a `yfinance.Ticker(ticker).news` (yfinance retirado por + completo del proyecto, ver services/market_data.py) manteniendo el + mismo rol estructural: gratuita, sin key, no depende de que el + operador configure nada para tener AL MENOS cobertura básica. + 2) Finnhub REST API -> fallback, requiere FINNHUB_API_KEY. + `/company-news` para equities, `/news?category=crypto` para cripto + (ver `_is_crypto_ticker`/`_fetch_headlines_finnhub` — V6, fix de + "señal muerta" en crypto_specialist). + +PROHIBIDO en este módulo: Selenium, BeautifulSoup, requests directos a +portales de noticias, o cualquier scraping HTML iterativo. Cualquiera de +esos vectores colapsa el pipeline productivo ante CAPTCHAs, Cloudflare o +baneos de IP del proveedor de hosting — exactamente lo que este pipeline +está diseñado para evitar. DDGS consume el endpoint JSON de noticias de +DuckDuckGo (misma librería `ddgs` ya usada por +`quanti_engine.search_financial_web`, ya pineada en requirements.txt) — +no es scraping de HTML de portales de noticias individuales. + +V7 (auditoría "señal muerta" universal, post-fix-tz V6): dos fallos +independientes que colapsaban NEWS_SENTIMENT_SCORE a 0.0 EXACTO pese al +fix de timezone previo — (a) `_score_text` descartaba en silencio +cualquier etiqueta de FinBERT no reconocida (ej. LABEL_0/1/2 en vez de +positive/negative/neutral) sin loguear nada, para TODOS los tickers por +igual; (b) `get_daily_news_sentiment` exigía calce EXACTO de +fecha-calendario (`Series.reindex`), que nunca aterriza para titulares +publicados fin de semana/feriado en el universo de equities. Ver +docstrings de ambas funciones para el detalle completo. + +V8 (auditoría de atribución por gradiente, post-fix-señal-muerta V7): con +la señal ya viva (V7), NEWS_SENTIMENT_SCORE seguía rank 17/17 en +equity_specialist mientras SENTIMENT_SCORE (correlación móvil +activo<->VIX, ver train_kodaquant_v5.py/quanti_engine.py — variable de +régimen/beta derivada de precio, NO redundante con esta) dominaba el +Top 5. Diagnóstico: no es colisión de features, es cobertura de prensa +esporádica en equity (relleno neutro + saltos discretos = ruido de alta +frecuencia que el modelo aprende a ignorar). Fix: EMA regime-aware al +final de `get_daily_news_sentiment` — amortigua equity, no-op exacto en +cripto (flujo de noticias 24/7, la misma densidad que sostiene el +51.2%/52.3% de crypto_specialist). Ver constantes +`NEWS_SENTIMENT_EMA_SPAN_*` más abajo. Cero cambios en +train_kodaquant_v5.py/quanti_engine.py: ambos consumen esta función tal +cual, consistencia train/inferencia automática. + +V9 (consolidación del core, auditoría CTO 2026-08-16): `fetch_recent_headlines` +ahora cachea en disco vía `kodaquant_core.CacheManager` (TTL corto, +`KODAQUANT_NEWS_CACHE_TTL_SECONDS`, purga automática local en cada +llamada) -- reduce presión sobre DDGS/Finnhub sin tocar la lógica de +scoring/merge de abajo, que queda intacta. Ver `kodaquant_core.py` para el +resto de la consolidación (caché de OHLCV, cliente FRED, alineación de +calendario macro), compartida ahora con `train_kodaquant_v5.py`. + +V10 (auditoría "100% neutro" AMZN/META, post-rollback V23.6 equity): +`DDG_REGION` default venía en `"es-es"` -- sesga `ddgs.news(...)` hacia +resultados LOCALIZADOS a España (con mayor probabilidad de titulares en +español) para consultas de equities 100% US-listed (`"{TICKER} stock"`). +`ProsusAI/finbert` (`_score_text`) es un clasificador ENTRENADO +EXCLUSIVAMENTE en texto financiero en inglés (Financial PhraseBank) -- un +titular en español queda fuera de su distribución de entrenamiento y +tiende a colapsar a la clase "neutral" con score de confianza alto (no es +un titular sin opinión: es el modelo adivinando entre 3 clases sobre texto +que nunca vio en ese idioma). Esto es indistinguible, aguas abajo, del +caso legítimo "titular real sin carga direccional" -- exactamente el +síntoma reportado (9 titulares obtenidos para META, 0 warnings de +etiqueta-no-reconocida, score 100% neutro de todas formas: los titulares +SÍ llegaban y SÍ eran clasificables, solo que en el idioma equivocado para +este scorer). Fix: default cambiado a `"us-en"` (mercado real de todo el +universo de `equity_specialist`: AAPL/MSFT/NVDA/TSLA/GOOGL/AMZN/META/SPY, +todos NYSE/NASDAQ) -- sigue siendo 100% override-able vía env var +`DDG_REGION` si el operador necesita otra región por algún motivo. NO +toca `quanti_engine.py::DDG_REGION` (constante del mismo nombre pero +CONSUMIDOR DISTINTO: alimenta el RAG conversacional de Quanti para +usuarios que preguntan en español, vía `search_financial_web` -> Groq, +nunca pasa por FinBERT -- ahí "es-es" sigue siendo la región correcta y +no se toca). + +Analizador de sentimiento: FinBERT (`ProsusAI/finbert` vía `transformers`), +cargado perezosamente (singleton) y con selección automática de device +(GPU si disponible, CPU en runners de CI). `get_daily_news_sentiment` sigue +aceptando un `scorer_fn` intercambiable para no acoplar el resto del módulo +a este modelo en particular. + +Integración con `engineer_asset` (ver train_kodaquant_v5.py): + df["NEWS_SENTIMENT_SCORE"] = get_daily_news_sentiment(ticker, df.index) +Debe ejecutarse ANTES de que `TECH_COLS`/`feature_cols` arme el tensor de +entrada, junto al resto de los indicadores técnicos — nunca después de la +transformación a retornos logarítmicos del target. + +V11 (auditoría rescate 2026-08 -- "esto tiene que quedar perfecto"): 4 puntos +menores detectados en una corrida real de producción, ninguno bloqueante, +todos con fix real: + a) COLISIÓN DE ENV VAR (el único con impacto real en la señal): este + módulo y `quanti_engine.py` compartían el nombre `DDG_REGION` para + DOS propósitos incompatibles (RAG conversacional en español vs. + scoring FinBERT inglés-únicamente) -- fijar `DDG_REGION=es-es` para + el chat de Quanti reintroducía en silencio el bug "100% neutro" que + V10 creía cerrado. Fix: variable dedicada `NEWS_SENTIMENT_DDG_REGION`. + b) Filtro de idioma `langdetect` (opcional, gratis, sin key) como + defensa en profundidad DESPUÉS del fix de región -- poda la cola + larga de titulares fuera de idioma que un agregador global puede + colar incluso con la región correcta. + c) Reintento con query más amplia + fallback a `/news?category=general` + de Finnhub para ETFs (SPY, QQQ...) que nunca tienen perfil de + compañía en `/company-news` y antes se quedaban sin ninguna señal + de prensa cuando DDGS tampoco rendía para esa query específica. + d) `FutureWarning` cosmético de `huggingface_hub` (resume_download) + silenciado de forma acotada -- no afectaba nada, solo ruido de log. + +V12 (auditoría rescate 2026-08 -- crash real en despliegue HF Space): +`ModuleNotFoundError: No module named 'langdetect'` seguido de +`NameError: name 'logger' is not defined`, ambos en import-time de este +módulo (tumbaba todo el proceso, no solo esta feature). Causa raíz: el +bloque `try/except ImportError` de `langdetect` (V11, arriba) llamaba +`logger.warning(...)` en su rama `except`, pero `logger = +logging.getLogger(...)` se definía DEBAJO de ese bloque -- el except SÍ +atrapaba el `ModuleNotFoundError` real (es subclase de `ImportError`), +pero al intentar loguearlo lanzaba un `NameError` sin atrapar, que se +propagaba y abortaba la carga del módulo completo. Fix real: `logger` se +define ANTES de cualquier bloque que pueda loguear en su rama except +(orden, no manejo de excepciones nuevo). `langdetect` además se agrega a +requirements.txt (ver ese archivo) -- puro-Python, gratis, sin key -- para +que la defensa en profundidad V11 quede activa en producción en vez de +degradarse siempre al no-op silencioso. + +V13 (auditoría rescate 2026-08-31 -- re-verificación post-reporte de +`ModuleNotFoundError`/`NameError` en este mismo módulo): re-auditado línea +por línea contra el reporte. Ambos síntomas YA estaban resueltos por V12 +(arriba) en esta versión del archivo -- `logger` se define en la línea +correcta (antes del primer `except` que lo usa) y `langdetect==1.0.9` ya +está pineado en requirements.txt. Confirmado también con `pyflakes` (cero +warnings) y `ast.parse`/`py_compile` (sintaxis válida) sobre el archivo +completo -- CERO cambios funcionales en este módulo; el crash reportado no +reproduce contra este código fuente. Ver requirements.txt (RONDA 7) para +el crash real de esta corrida (`numpy`/`tensorflow`, módulo distinto). +""" + +from __future__ import annotations + +import logging +import os +import re +import sys +import threading +import time +import warnings +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Callable, Optional + +# V11 (auditoría 2026-08) -- `huggingface_hub` emite un FutureWarning +# cosmético ("resume_download is deprecated") en CADA carga de FinBERT vía +# `transformers.pipeline`, sin relación con ningún bug real de este módulo +# ni con la calidad de NEWS_SENTIMENT_SCORE. Acotado por `module=` a la +# librería exacta que lo emite -- nunca un `warnings.filterwarnings("ignore")` +# global, que enmascararía warnings reales de otras dependencias. +warnings.filterwarnings("ignore", category=FutureWarning, module=r"huggingface_hub\..*") + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (Directiva 2 — fin al Import Hell) ---- +# Este archivo vive ÚNICAMENTE en `ml_engine/` (Directiva 1: SINGLE SOURCE +# OF TRUTH). Sube desde este archivo hasta encontrar la raíz del proyecto +# -- el primer ancestro que contiene TANTO `ml_engine/` como `services/` +# como subdirectorios -- y la inserta en `sys.path[0]`. A partir de ahí, +# `ml_engine` y `services` son paquetes válidos sin importar desde qué +# directorio de trabajo se invoque `python .../data_pipeline.py` (directo, +# importado por `train_kodaquant_v5.py`, o vía `services.quanti_engine`). +# Reemplaza por completo el patrón try/except dual + copias duplicadas de +# `kodaquant_core.py` que causaba `ModuleNotFoundError`/`ImportError`. +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + # Fallback determinista: este archivo vive en ml_engine/, por lo que su + # abuelo es la raíz del proyecto por construcción, incluso si `services/` + # todavía no existe en el entorno actual (ej. checkout parcial/CI). + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# Núcleo compartido train/inferencia -- SINGLE SOURCE OF TRUTH en +# `ml_engine/kodaquant_core.py` (Directiva 1). Import directo y absoluto, +# sin fallback dual: con la raíz del proyecto ya en sys.path, esta ruta +# resuelve siempre, sin importar el cwd de invocación. +from ml_engine.kodaquant_core import CacheManager # noqa: E402 + +# --- PARCHE macOS Intel: runtimes OpenMP duplicados TensorFlow/PyTorch ---- +# `quanti_engine.py` carga TensorFlow/Keras (bundla Intel MKL -> libiomp5.dylib) +# EAGER al arrancar Uvicorn. PyTorch (bundla LLVM -> libomp.dylib) se importa +# LAZY aquí, recién en el primer request real. Ambos runtimes OpenMP en el +# mismo proceso es un conflicto conocido en macOS que puede impedir que +# torch cargue su extensión nativa. Debe fijarse ANTES del primer `import +# torch` — no tiene efecto si se fija después. +os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE") + +import pandas as pd +import requests # Únicamente para el endpoint JSON de Finnhub — API nativa, NO scraping. + +# --- Búsqueda de noticias vía DDGS (DuckDuckGo) — reemplaza a yfinance.news +# como fuente primaria, gratuita y sin API key (yfinance retirado por +# completo del proyecto, ver services/market_data.py). Mismo import +# defensivo (paquete renombrado `duckduckgo_search` -> `ddgs`) que ya usa +# `quanti_engine.search_financial_web`; `ddgs` ya está pineado en +# requirements.txt, cero dependencias nuevas. +logger = logging.getLogger("kodaquant.data_pipeline") + +try: + from ddgs import DDGS +except ImportError: # pragma: no cover + try: + from duckduckgo_search import DDGS # type: ignore[no-redef] + except ImportError: + DDGS = None # type: ignore[assignment,misc] # se valida en runtime, ver _fetch_headlines_ddg + +# V11 (auditoría 2026-08 — colisión de nombre de env var, root cause real +# del "100% neutro" que V10 creyó haber cerrado): V10 cambió el DEFAULT de +# este módulo a "us-en", pero seguía leyendo la MISMA variable de entorno +# `DDG_REGION` que usa `quanti_engine.py::DDG_REGION` para el buscador +# conversacional de Quanti (default "es-es", CORRECTO ahí -- los usuarios +# le hablan en español). Cualquier operador que fije `DDG_REGION=es-es` en +# su .env/entorno (lo natural para un producto en español) pisa SIN +# querer el default de ESTE módulo también -- las dos constantes comparten +# nombre pero NO deberían compartir valor: una alimenta un LLM que lee +# español perfectamente, la otra alimenta FinBERT, que es inglés-únicamente. +# Fix real: variable de entorno dedicada y jamás compartida con +# quanti_engine.py. Quien necesite tocar la región de este módulo usa +# `NEWS_SENTIMENT_DDG_REGION`, nunca `DDG_REGION`. +DDG_REGION = os.getenv("NEWS_SENTIMENT_DDG_REGION", "us-en") +DDG_SAFESEARCH = os.getenv("DDG_SAFESEARCH", "moderate") +MAX_DDG_HEADLINES = 10 # techo por-ticker -- Finnhub complementa si esto no alcanza + +# V11 — defensa en profundidad además del fix de región de arriba: agregadores +# de noticias globales pueden devolver un titular fuera de idioma incluso con +# la región correcta (ej. un medio hispano indexado igual bajo "us-en"). Un +# titular no-inglés que llega a FinBERT no lanza NINGÚN warning (ver V10) y +# se pierde como "neutral" falso -- indistinguible de una lectura neutra real. +# `langdetect` es puro-Python, gratuito, sin key, determinístico con seed fija +# -- se usa como filtro PREVIO al scorer, no como reemplazo del fix de región +# (más barato: si la región ya resuelve el 95% de los casos, este filtro solo +# poda la cola larga). Si no está instalado, se degrada a no-op con un único +# warning (nunca bloquea el pipeline). +try: + from langdetect import DetectorFactory as _LangDetectorFactory, detect_langs as _langdetect_detect_langs + _LangDetectorFactory.seed = 0 # determinístico -- sin esto, langdetect no es reproducible corrida a corrida + _LANGDETECT_AVAILABLE = True +except ImportError: # pragma: no cover + _LANGDETECT_AVAILABLE = False + logger.warning( + "langdetect no instalado (`pip install langdetect`) -- se omite el filtro de idioma " + "de defensa en profundidad; NEWS_SENTIMENT_DDG_REGION sigue siendo la defensa primaria." + ) + +# Caché de titulares (DDGS/Finnhub) — vida corta: la cobertura de prensa +# cambia varias veces al día, pero no vale la pena re-golpear DDGS/Finnhub +# en cada llamada de `get_daily_news_sentiment` dentro de la MISMA corrida +# (el radar escanea el universo completo en paralelo, ver +# `data_pipeline.get_daily_news_sentiment` invocado por cada régimen). +# Purga automática local (Requerimiento 1): `_headline_cache.purge_stale()` +# se invoca de forma perezosa en cada `fetch_recent_headlines` -- sin cron +# externo, sin intervención manual. +_HEADLINE_CACHE_DIR = Path(os.getenv("KODAQUANT_NEWS_CACHE_DIR", "cache/news")) +_HEADLINE_CACHE_TTL_SECONDS = int(os.getenv("KODAQUANT_NEWS_CACHE_TTL_SECONDS", str(2 * 3600))) +_headline_cache = CacheManager(_HEADLINE_CACHE_DIR, default_ttl_seconds=_HEADLINE_CACHE_TTL_SECONDS) + +# --------------------------------------------------------------------------- +# FinBERT — analizador de sentimiento transformer, carga perezosa (singleton) +# --------------------------------------------------------------------------- +_FINBERT_MODEL_NAME = "ProsusAI/finbert" +_FINBERT_LABEL_SIGN = {"positive": 1.0, "negative": -1.0, "neutral": 0.0} +# V7 (auditoría "señal muerta" UNIVERSAL — TODOS los activos, no solo cripto): +# ciertas combinaciones de `transformers`/config cacheado devuelven las +# etiquetas GENÉRICAS del clasificador (LABEL_0/LABEL_1/LABEL_2) en vez de +# las humanas positive/negative/neutral, cuando el `id2label` del modelo no +# se resuelve en tiempo de carga. Orden oficial de ProsusAI/finbert +# (config.json del modelo): 0=positive, 1=negative, 2=neutral. +_FINBERT_LABEL_ALIASES = {"label_0": "positive", "label_1": "negative", "label_2": "neutral"} +_finbert_pipeline = None +# RONDA 10 -- sentinela de FALLO cacheado (str del motivo, o None si aún no +# se intentó / tuvo éxito). Antes solo se cacheaba el ÉXITO (`_finbert_pipeline`) +# -- un fallo NUNCA quedaba memorizado, así que CADA titular individual +# repetía el import + intento de carga completo desde cero y volvía a +# producir el traceback entero -- la causa real de las "cientos de líneas +# de error" reportadas, no un crash único. Con esto: se diagnostica UNA +# vez, se loguea el traceback real completo UNA vez, y todo el resto del +# proceso degrada a NEUTRAL_SCORE con un mensaje corto de una línea. +_finbert_unavailable_reason: Optional[str] = None +# Protege la carga perezosa contra llamadas CONCURRENTES: bajo Uvicorn, +# get_daily_news_sentiment se dispara desde varios hilos a la vez (Plan A/Plan B +# en paralelo, radar escaneando el universo completo vía ThreadPoolExecutor). +# Sin lock, el primer request real puede disparar 2+ hilos importando +# torch/transformers simultáneamente -> ImportError transitorio de import +# parcial/circular, indistinguible de "no instalado" sin este fix. +_finbert_init_lock = threading.Lock() +# RONDA 10 -- piso REAL de transformers 5.x, verificado contra la guía de +# migración oficial de la librería (Python 3.10+, PyTorch 2.4+, +# huggingface_hub<2.0,>=1.3.0) -- NO 2.5 como asumía una auditoría previa. +_TRANSFORMERS_MIN_TORCH = (2, 4) + +# --- Backend ONNX (camino PRIMARIO, torch-independiente) ------------------- +_FINBERT_ONNX_REPO = os.getenv("KODAQUANT_FINBERT_ONNX_REPO", "Xenova/finbert").strip() +# V27 -- default cambiado de _FINBERT_MODEL_NAME (ProsusAI/finbert, sin +# export ONNX -> 404 permanente) a Xenova/finbert (mismo modelo base, +# mismas labels -- config.json id2label idéntico, verificado). Confirmado +# en producción: "[FinBERT/ONNX] sesión activa (Xenova/finbert ...)". +# KODAQUANT_FINBERT_ONNX_REPO sigue pisando esto si se necesita otro repo. +_FINBERT_ONNX_FILE = os.getenv("KODAQUANT_FINBERT_ONNX_FILE", "onnx/model.onnx").strip() +_FINBERT_ONNX_MAXLEN = 256 +_finbert_onnx = None # tuple(InferenceSession, Tokenizer, input_names) +_finbert_onnx_unavailable: Optional[str] = None +_finbert_onnx_lock = threading.Lock() + + +def _load_finbert_tokenizer(hf_hub_download): + """tokenizer.json (fast) con fallback a vocab.txt (WordPiece clásico).""" + from tokenizers import Tokenizer + try: + return Tokenizer.from_file(hf_hub_download(_FINBERT_ONNX_REPO, "tokenizer.json")) + except Exception: + from tokenizers import BertWordPieceTokenizer + vocab = hf_hub_download(_FINBERT_ONNX_REPO, "vocab.txt") + return BertWordPieceTokenizer(vocab, lowercase=True) + + +def _get_finbert_onnx(): + """Sesión ONNX + tokenizer (singleton thread-safe). Cero torch, cero TF. + + Esquiva `transformers.pipeline()` por completo -- ahí vive la NameError + de la compuerta torch>=2.4 diagnosticada en RONDA 10, que NINGÚN kwarg + de esta capa puede evitar. + """ + global _finbert_onnx, _finbert_onnx_unavailable + if _finbert_onnx is not None: + return _finbert_onnx + if _finbert_onnx_unavailable is not None: + raise FinBERTUnavailableError(_finbert_onnx_unavailable) + + with _finbert_onnx_lock: + if _finbert_onnx is not None: + return _finbert_onnx + if _finbert_onnx_unavailable is not None: + raise FinBERTUnavailableError(_finbert_onnx_unavailable) + try: + import numpy as _np + import onnxruntime as _ort + from huggingface_hub import hf_hub_download + except ImportError as exc: + _finbert_onnx_unavailable = ( + f"[FinBERT/ONNX] backend no instalado ({type(exc).__name__}: {exc}). " + "`pip install onnxruntime tokenizers` en el MISMO venv." + ) + logger.warning(_finbert_onnx_unavailable) + raise FinBERTUnavailableError(_finbert_onnx_unavailable) from exc + + try: + onnx_path = hf_hub_download(_FINBERT_ONNX_REPO, _FINBERT_ONNX_FILE) + tokenizer = _load_finbert_tokenizer(hf_hub_download) + opts = _ort.SessionOptions() + opts.intra_op_num_threads = 1 # ZeroGPU / Uvicorn multihilo + opts.graph_optimization_level = _ort.GraphOptimizationLevel.ORT_ENABLE_ALL + session = _ort.InferenceSession(onnx_path, opts, providers=["CPUExecutionProvider"]) + input_names = {i.name for i in session.get_inputs()} + _finbert_onnx = (session, tokenizer, input_names, _np) + logger.info("[FinBERT/ONNX] sesión activa (%s :: %s, inputs=%s).", + _FINBERT_ONNX_REPO, _FINBERT_ONNX_FILE, sorted(input_names)) + except Exception as exc: + _finbert_onnx_unavailable = ( + f"[FinBERT/ONNX] no se pudo abrir '{_FINBERT_ONNX_REPO}::{_FINBERT_ONNX_FILE}' " + f"({type(exc).__name__}: {exc}). Si es 404, ese repo no publica export ONNX -- " + "exportalo una vez y fijá KODAQUANT_FINBERT_ONNX_REPO/_FILE." + ) + logger.warning(_finbert_onnx_unavailable) + raise FinBERTUnavailableError(_finbert_onnx_unavailable) from exc + return _finbert_onnx + + +def _score_text_onnx(text: str) -> float: + session, tokenizer, input_names, _np = _get_finbert_onnx() + enc = tokenizer.encode(text) + ids = enc.ids[:_FINBERT_ONNX_MAXLEN] + mask = (enc.attention_mask[:_FINBERT_ONNX_MAXLEN] + if getattr(enc, "attention_mask", None) else [1] * len(ids)) + feed = {"input_ids": _np.asarray([ids], dtype=_np.int64), + "attention_mask": _np.asarray([mask], dtype=_np.int64)} + if "token_type_ids" in input_names: + feed["token_type_ids"] = _np.zeros((1, len(ids)), dtype=_np.int64) + logits = _np.asarray(session.run(None, {k: v for k, v in feed.items() + if k in input_names})[0][0], dtype=_np.float64) + exp = _np.exp(logits - logits.max()) + probs = exp / exp.sum() + # id2label oficial de ProsusAI/finbert: 0=positive, 1=negative, 2=neutral + return float(probs[0] - probs[1]) + + +def news_sentiment_available() -> bool: + """Probe determinista -- ¿hay ALGÚN backend capaz de puntuar sentimiento? + + Consumido por `train_kodaquant_v5.run_regime_pipeline` para decidir, UNA + vez y antes de construir el tensor, si NEWS_SENTIMENT_SCORE entra o se + excluye. Inyectar 0.0 constante es peor que excluirla: el feature_scaler + se ajusta sobre una constante y la red aprende un slot muerto. + """ + try: + _get_finbert_onnx() + return True + except Exception: + pass + try: + _get_finbert_pipeline() + return True + except Exception: + return False + + +class FinBERTUnavailableError(ImportError): + """RONDA 10 -- excepción DEDICADA para el caso 'ya diagnosticado, no + reintentable en este proceso' (piso de torch no alcanzado / backend TF + inexistente en transformers 5.x). `_score_text` la distingue de un + ImportError genérico para loguear corto (sin traceback repetido) en + vez de con `exc_info=True` en cada titular -- ver ahí.""" + + +def _get_finbert_pipeline(): + """Carga perezosa (singleton, thread-safe) del pipeline FinBERT — CPU-safe para runners sin GPU. + + RONDA 10 (fix REAL, reemplaza el intento fallido de RONDA 6-9) -- + diagnóstico verificado contra el TRACEBACK REAL producido en Mac Intel + (no solo contra el código fuente): el intento anterior de "fallback a + backend TensorFlow" era imposible de raíz, no un bug de esta función. + Evidencia: el segundo intento (`framework="tf"`) reventó con la + EXACTA MISMA `NameError: name 'torch' is not defined` en la EXACTA + MISMA línea (`transformers/pipelines/__init__.py::pipeline`, chequeo + `isinstance(dtype, str) and hasattr(torch, dtype)`) que el primero -- + esa línea corre ANTES de cualquier rama específica de framework, así + que reintentar con otro framework nunca podía esquivarla. Confirmado + además contra la guía de migración oficial de transformers 5.x: la + serie 5.x eliminó el backend TensorFlow POR COMPLETO y sin período de + gracia (PyTorch es el único backend soportado) -- no había ninguna + rama TF real a la que caer, el `except NameError: ... framework="tf"` + de las rondas previas apuntaba a código que ya no existe en la + librería instalada (`transformers==5.15.0`, ver requirements.txt). + El piso real es torch>=2.4 (Python 3.10+/huggingface_hub<2.0,>=1.3.0 + son los otros dos). En macOS Intel (x86_64) NINGÚN wheel de `torch` + >2.2.2 existe en PyPI -- techo real y permanente de esa plataforma, no + arreglable con más código. Pinear `transformers` a la serie 4.x (que + SÍ soportaba TF) NO es salida: esa serie exige `huggingface-hub<1.0` + en TODAS sus versiones (confirmado en vivo, incl. el último release + 4.57.x), lo que choca de frente con `huggingface-hub<2.0,>=1.16.0` que + ya exige `gradio[oauth,mcp]==6.22.0` en el MISMO requirements.txt -- + `ResolutionImpossible` real, no evitable sin romper el build de HF + Spaces (`gradio` no está platform-split, no puede estarlo: `sdk_version` + del README.md debe calzar exacto para TODA plataforma). + Conclusión honesta: FinBERT vía `transformers.pipeline()` es + IRRECUPERABLE en Mac Intel local con esta cadena de dependencias -- + no es arreglable sin (a) un Mac Apple Silicon/Linux real, o (b) + remover `gradio[mcp]` del proyecto para poder bajar a transformers 4.x. + Producción (HF Space, Linux, `torch==2.11.0`) NO está afectada -- ahí + `torch_ver >= _TRANSFORMERS_MIN_TORCH` es verdadero y el pipeline + PyTorch carga y sirve FinBERT completo, sin ninguna rama de este fix + involucrada. Este fix, entonces, es sobre CALIDAD DE FALLO en Mac + Intel (un diagnóstico honesto, una sola vez, degrade limpio a + NEUTRAL_SCORE) -- no sobre "hacer funcionar" algo que la librería ya + no soporta en esa plataforma. + """ + global _finbert_pipeline, _finbert_unavailable_reason + if _finbert_pipeline is not None: + return _finbert_pipeline + if _finbert_unavailable_reason is not None: + raise FinBERTUnavailableError(_finbert_unavailable_reason) + + with _finbert_init_lock: + if _finbert_pipeline is not None: # doble check: otro hilo ya lo cargó mientras esperábamos el lock + return _finbert_pipeline + if _finbert_unavailable_reason is not None: # ídem, otro hilo ya lo diagnosticó como inviable + raise FinBERTUnavailableError(_finbert_unavailable_reason) + + try: + import torch + from transformers import pipeline as _hf_pipeline + from transformers.utils import is_torch_available + except ModuleNotFoundError as exc: + # Caso real de "no instalado": el paquete no existe en este intérprete. + _finbert_unavailable_reason = ( + f"torch/transformers no están instalados en {sys.executable}: {exc}. " + "Ejecuta `pip install torch transformers` en el MISMO venv que corre Uvicorn." + ) + raise ImportError(_finbert_unavailable_reason) from exc + except ImportError as exc: + # CUALQUIER OTRO ImportError (símbolo nativo, dlopen roto, import + # circular parcial por carrera entre hilos, etc.) — antes se + # enmascaraba con el mismo mensaje genérico de "no instalado". + # Se preserva el tipo y mensaje reales para que el log no mienta. + _finbert_unavailable_reason = ( + f"torch/transformers están instalados pero fallaron al importar " + f"({type(exc).__name__}: {exc}). NO es un paquete faltante — revisa " + "conflictos nativos (runtimes OpenMP duplicados TF/PyTorch en macOS, " + "ver KMP_DUPLICATE_LIB_OK) o reinstala ambos paquetes emparejados." + ) + raise ImportError(_finbert_unavailable_reason) from exc + + _ver_match = re.match(r"(\d+)\.(\d+)", torch.__version__) + torch_ver = tuple(int(p) for p in _ver_match.groups()) if _ver_match else (0, 0) + if not is_torch_available() or torch_ver < _TRANSFORMERS_MIN_TORCH: + _finbert_unavailable_reason = ( + f"[FinBERT] no disponible en este proceso: torch {torch.__version__} " + f"instalado, transformers {__import__('transformers').__version__} exige " + f"torch>={'.'.join(map(str, _TRANSFORMERS_MIN_TORCH))} y ELIMINÓ el backend " + "TensorFlow por completo en la serie 5.x (verificado: framework='tf' dispara " + "la MISMA NameError compartida en pipeline() antes de cualquier rama TF real " + "-- no hay fallback posible). En macOS Intel ningún wheel de torch >2.2.2 " + "existe en PyPI (techo real de plataforma). NEWS_SENTIMENT_SCORE degradará a " + "NEUTRAL_SCORE de forma consistente en este proceso -- producción " + "(Linux, torch==2.11.0) no está afectada, ahí el piso SÍ se cumple." + ) + logger.error(_finbert_unavailable_reason) + raise FinBERTUnavailableError(_finbert_unavailable_reason) + + device = 0 if torch.cuda.is_available() else -1 + try: + _finbert_pipeline = _hf_pipeline( + "sentiment-analysis", model=_FINBERT_MODEL_NAME, + tokenizer=_FINBERT_MODEL_NAME, truncation=True, device=device, + dtype=None, # esquiva `isinstance(dtype, str) and hasattr(torch, dtype)` (ver docstring) + ) + except Exception as exc: + _finbert_unavailable_reason = ( + f"[FinBERT] pipeline PyTorch falló pese a pasar el check de versión/" + f"is_torch_available() ({type(exc).__name__}: {exc})." + ) + logger.error(_finbert_unavailable_reason, exc_info=True) + raise FinBERTUnavailableError(_finbert_unavailable_reason) from exc + return _finbert_pipeline + +FINNHUB_API_KEY = os.getenv("FINNHUB_API_KEY", "").strip() +# V6 (auditoría "señal muerta" crypto_specialist) — `/company-news` es +# EXCLUSIVO para equities listadas en EE. UU. (doc oficial Finnhub); jamás +# devuelve resultados para tickers cripto. `/news?category=crypto` es el +# endpoint correcto para ese universo — ver `_fetch_headlines_finnhub`. +FINNHUB_COMPANY_NEWS_URL = "https://finnhub.io/api/v1/company-news" +FINNHUB_CRYPTO_NEWS_URL = "https://finnhub.io/api/v1/news" +# V11 -- MISMO endpoint que FINNHUB_CRYPTO_NEWS_URL (Finnhub `/news` acepta +# `category` general/forex/crypto/merger); alias legible para el fallback de +# ETFs (`_fetch_headlines_finnhub`, ver auditoría 2026-08), nunca un endpoint nuevo. +FINNHUB_GENERAL_NEWS_URL = FINNHUB_CRYPTO_NEWS_URL + +NEWS_LOOKBACK_DAYS = 7 # ventana de titulares recientes a recolectar (fallback Finnhub) +MAX_HEADLINES_PER_TICKER = 60 # techo defensivo (rate-limit / ruido) +NEUTRAL_SCORE = 0.0 # relleno para días/activos sin cobertura de prensa +# V7 — tolerancia del merge_asof temporal (ver get_daily_news_sentiment): +# NEWS_LOOKBACK_DAYS + colchón de fin de semana/feriado, para que un titular +# del viernes siga cubriendo el lunes bursátil sin exigir calce EXACTO de +# fecha (el bug que _NEWS_MERGE_TOLERANCE_DAYS/pd.merge_asof reemplaza) y, +# a la vez, sin arrastrar sentimiento añejo indefinidamente como hacía el +# `.ffill()` sin cota que tenía este merge antes. +_NEWS_MERGE_TOLERANCE_DAYS = NEWS_LOOKBACK_DAYS + 3 + +_RETRY_ATTEMPTS = 3 +_RETRY_BACKOFF_SECONDS = 1.5 + +# --- V8 (Filtrado Regime-Aware — aislamiento de ruido equity sin tocar cripto) --- +# Auditoría de atribución por gradiente: NEWS_SENTIMENT_SCORE cae a +# rank 17/17 en equity_specialist. Causa raíz NO es colisión con +# SENTIMENT_SCORE (esa es la correlación móvil activo<->VIX de +# compute_sentiment_score en train_kodaquant_v5.py/quanti_engine.py — un +# proxy de régimen/beta derivado 100% de precio, variable estructuralmente +# distinta de esta, cero solapamiento de información): es que la cobertura +# de prensa por-ticker vía DDGS/Finnhub es ESPORÁDICA en equity (pocos +# titulares/semana), así que la señal día a día alterna tramos planos +# (relleno neutro) con saltos discretos cada vez que aterriza un titular — +# exactamente el patrón de alta frecuencia que un BiLSTM aprende a +# descontar como ruido. crypto_specialist NO sufre esto: `/news?category= +# crypto` entrega flujo 24/7 sin huecos, la misma densidad/volatilidad +# cruda que llevó a crypto_specialist a 51.2%/52.3% de asertividad — jamás +# se suaviza. +# Fix: EMA regime-aware aplicado DENTRO de get_daily_news_sentiment (única +# fuente de esta columna para train_kodaquant_v5.py Y quanti_engine.py) -> +# consistencia train/inferencia automática, cero cambios en esos dos +# archivos, cero impacto en TECH_COLS/N_FEATURES/(batch,60,17). +NEWS_SENTIMENT_EMA_SPAN_EQUITY = 5 # ~1 semana bursátil: amortigua saltos discretos sin borrar la tendencia real +NEWS_SENTIMENT_EMA_SPAN_CRYPTO = 1 # span=1 -> alpha=2/(span+1)=1.0 -> no-op matemático exacto, señal cruda intacta + + +def _score_text(text: str) -> float: + """Escalar direccional (∈[-1, 1]) de un titular vía FinBERT (ProsusAI/finbert).""" + if not text: + return NEUTRAL_SCORE + if _finbert_onnx is not None or _finbert_onnx_unavailable is None: + try: + return _score_text_onnx(text[:2048]) + except FinBERTUnavailableError: + pass # diagnosticado UNA vez en _get_finbert_onnx -> cae a torch + except Exception as exc: # noqa: BLE001 + logger.warning("[FinBERT/ONNX] fallo de inferencia (%s: %s) -> fallback torch.", + type(exc).__name__, exc) + try: + result = _get_finbert_pipeline()(text[:512])[0] + raw_label = str(result["label"]).lower() + label = _FINBERT_LABEL_ALIASES.get(raw_label, raw_label) + if label not in _FINBERT_LABEL_SIGN: + # FIX RAÍZ V7 (auditoría "señal muerta" universal — 10 titulares + # obtenidos, 100% neutro, TODOS los activos, sin ningún otro + # warning en el log): antes, una etiqueta no reconocida caía en + # `_FINBERT_LABEL_SIGN.get(label, 0.0)` -> 0.0 SILENCIOSO. No es + # una excepción (no dispara el except de abajo), así que NUNCA + # quedaba rastro en el log de por qué el score era siempre 0 — + # exactamente el síntoma reportado, y explica por qué persistía + # pese al fix de timezone (esa parte del pipeline nunca fue el + # problema: los titulares SÍ llegaban, pero cada uno puntuaba + # 0.0 antes de tocar cualquier lógica de fechas). Ahora es ruidoso. + logger.warning( + "FinBERT devolvió una etiqueta no reconocida %r (fuera de " + "_FINBERT_LABEL_SIGN/_FINBERT_LABEL_ALIASES) -> score forzado " + "a NEUTRAL_SCORE para este titular. Verifica la versión de " + "`transformers` / el config.json de %s (id2label esperado: " + "0=positive, 1=negative, 2=neutral).", result["label"], _FINBERT_MODEL_NAME, + ) + return NEUTRAL_SCORE + sign = _FINBERT_LABEL_SIGN[label] + return float(sign * result["score"]) + except FinBERTUnavailableError: + # RONDA 10 -- caso YA diagnosticado con traceback completo UNA vez + # dentro de `_get_finbert_pipeline` (logger.error/exc_info=True ahí). + # Repetir el traceback completo por CADA titular es exactamente la + # causa real de las "cientos de líneas de error" reportadas -- acá + # alcanza con un rastro corto, sin traceback, por titular. + logger.debug("FinBERT no disponible en este proceso (ver diagnóstico previo) -> NEUTRAL_SCORE.") + return NEUTRAL_SCORE + except Exception as exc: # noqa: BLE001 — fallo de inferencia del modelo local, causa NO diagnosticada aún + # exc_info=True: antes se logueaba solo %r del error (a veces ya + # reescrito con un mensaje genérico), sin traceback — la causa real + # (incl. __cause__ encadenado) quedaba invisible en los logs de + # Uvicorn. Ahora se propaga completa -- SOLO para fallos nuevos/no + # cacheados (ver FinBERTUnavailableError arriba para el caso ya + # conocido). + logger.warning( + "FinBERT falló al puntuar titular (%s: %s)", type(exc).__name__, exc, + exc_info=True, + ) + return NEUTRAL_SCORE + + +def _normalize_timestamp(ts_raw) -> Optional[datetime]: + """Normaliza epoch (int/float) o string de fecha a `datetime` UTC.""" + if ts_raw is None: + return None + try: + if isinstance(ts_raw, (int, float)): + return datetime.fromtimestamp(float(ts_raw), tz=timezone.utc) + return pd.Timestamp(ts_raw, tz="UTC").to_pydatetime() + except (ValueError, TypeError, OSError): + return None + + +# V11 -- umbral calibrado empíricamente (ver auditoría 2026-08): `detect()` +# ingenuo (top-1, sin probabilidad) da FALSOS POSITIVOS reales en titulares +# financieros cortos -- "Tesla stock drops on delivery miss" clasificó como +# sueco con `detect()`. `detect_langs()` expone la distribución de +# probabilidad completa; frases reales en español/inglés (>=20 chars) +# resuelven con >0.999 de confianza al idioma correcto, mientras que el +# ruido de titulares cortos ambiguos rara vez supera 0.97 -- de ahí el +# doble filtro (confianza alta Y longitud mínima) en vez de un simple +# top-1, que habría descartado titulares en inglés legítimos. +_LANGDETECT_MIN_CONFIDENCE = 0.97 +_LANGDETECT_MIN_LENGTH = 20 + + +def _is_english_headline(title: str) -> bool: + """ + Defensa en profundidad (V11) -- filtro de idioma PREVIO al scorer. + `True` (se deja pasar a FinBERT) salvo que `langdetect` esté MUY seguro + (`prob >= _LANGDETECT_MIN_CONFIDENCE`) de que el idioma NO es inglés, + sobre un titular con longitud suficiente para que esa confianza sea + confiable (`len >= _LANGDETECT_MIN_LENGTH`) -- en cualquier otro caso + (ambiguo, corto, o `langdetect` no instalado) se deja pasar: este + filtro poda la cola larga de titulares CLARAMENTE no-ingleses, nunca + reemplaza el fix de región (`NEWS_SENTIMENT_DDG_REGION`). + """ + if not _LANGDETECT_AVAILABLE or not title or len(title) < _LANGDETECT_MIN_LENGTH: + return True + try: + top = _langdetect_detect_langs(title)[0] + except Exception: # noqa: BLE001 -- langdetect lanza LangDetectException en texto ambiguo + return True + return not (top.lang != "en" and top.prob >= _LANGDETECT_MIN_CONFIDENCE) + + +def _fetch_headlines_ddg(ticker: str, max_results: int = MAX_DDG_HEADLINES) -> list[dict]: + """ + Fuente primaria — búsqueda de noticias vía DDGS (`ddgs.news`, JSON nativo + de DuckDuckGo, sin scraping de portales individuales, sin API key). + Reemplaza 1:1 el rol de `yfinance.Ticker(ticker).news` (retirado, ver + services/market_data.py): misma firma de retorno (`title`/`published_at`), + mismo lugar en `fetch_recent_headlines` (primaria, Finnhub complementa). + + V11 (auditoría 2026-08) -- dos mejoras sobre la fuente primaria: + (a) reintento con query MÁS AMPLIA si la query específica (`"{ticker} + stock"`) devuelve 0 resultados -- tickers de baja cobertura de + prensa dedicada (ETFs como SPY, sin "compañía" detrás) rendían + "No results found" en vez de degradarse a Finnhub con más señal. + (b) filtro de idioma (`_is_english_headline`) ANTES de devolver los + titulares -- ver V11 arriba. + """ + if DDGS is None: + logger.warning("DDGS no instalado (`pip install ddgs`) -- fuente primaria de noticias deshabilitada; solo Finnhub (si hay API key).") + return [] + + # Cripto: "-USD" es la convención de símbolo de todo el proyecto + # (REGIME_TICKERS/MACRO_SYMBOL_MAP), no específica de ningún proveedor + # -- se usa solo el símbolo base (ej. "BTC") para una query de noticias + # más natural que "BTC-USD". + is_crypto = _is_crypto_ticker(ticker) + base_symbol = ticker.split("-")[0] + queries = [f"{base_symbol} crypto"] if is_crypto else [f"{ticker} stock", f"{ticker} ETF", base_symbol] + + raw: list[dict] = [] + for query in queries: + try: + with DDGS() as ddgs: + raw = list( + ddgs.news(query, region=DDG_REGION, safesearch=DDG_SAFESEARCH, max_results=max_results) + ) + except Exception as exc: # noqa: BLE001 -- red/HTTP transitorio de DDG + logger.warning("DDGS.news falló para %s (query=%r): %r", ticker, query, exc) + continue + if raw: + break # primera query con resultados gana -- no seguimos ampliando innecesariamente + + headlines = [] + dropped_non_english = 0 + for item in raw: + title = (item.get("title") or "").strip() + published_at = _normalize_timestamp(item.get("date")) + if not title or published_at is None: + continue + if not _is_english_headline(title): + dropped_non_english += 1 + continue + headlines.append({"title": title, "published_at": published_at}) + if dropped_non_english: + logger.debug("%s: %d titular(es) descartado(s) por filtro de idioma (no-inglés).", ticker, dropped_non_english) + return headlines + + +def _is_crypto_ticker(ticker: str) -> bool: + """ + Heurística deliberadamente auto-contenida (sin importar `REGIME_TICKERS` + de quanti_engine.py/train_kodaquant_v5.py: SON quienes importan + data_pipeline.py, importar en sentido inverso crearía un ciclo). La + convención de todo el proyecto para cripto es SIEMPRE '-USD' + (BTC-USD, ETH-USD); ningún ticker de equity/ETF del universo entrenado + usa ese sufijo -> heurística exacta y suficiente para este propósito. + """ + return ticker.upper().endswith("-USD") + + +def _fetch_headlines_finnhub(ticker: str, lookback_days: int = NEWS_LOOKBACK_DAYS) -> list[dict]: + """ + Fallback — API REST gratuita de Finnhub, JSON puro, sin scraping. + Requiere `FINNHUB_API_KEY` en el entorno; si falta, se omite + silenciosamente (DDGS sigue siendo la fuente primaria y suficiente + en la mayoría de los casos). + + V6 (auditoría "señal muerta" `crypto_specialist`, NEWS_SENTIMENT_SCORE + rank 17/17, atribución 0.000000) — FIX de enrutamiento: `/company-news` + es EXCLUSIVO para equities listadas en EE. UU. (documentación oficial + de Finnhub) y nunca devuelve resultados para tickers cripto; antes se + llamaba ese mismo endpoint también para BTC-USD/ETH-USD, vaciando + silenciosamente el fallback justo para el régimen que más lo necesita. + Se enruta ahora vía `_is_crypto_ticker` al endpoint general + `/news?category=crypto` para cripto (sin filtro por símbolo: el tier + gratuito de Finnhub no ofrece news cripto por-moneda -> se filtra la + ventana `lookback_days` del lado del cliente, ya que ese endpoint no + acepta `from`/`to`) y mantiene `/company-news` intacto para equities. + """ + if not FINNHUB_API_KEY: + logger.debug("FINNHUB_API_KEY no configurada; se omite el fallback de Finnhub.") + return [] + + is_crypto = _is_crypto_ticker(ticker) + url = FINNHUB_CRYPTO_NEWS_URL if is_crypto else FINNHUB_COMPANY_NEWS_URL + today = datetime.now(timezone.utc).date() + since = today - timedelta(days=lookback_days) + if is_crypto: + params = {"category": "crypto", "token": FINNHUB_API_KEY} + else: + params = { + "symbol": ticker, + "from": since.isoformat(), + "to": today.isoformat(), + "token": FINNHUB_API_KEY, + } + + # `filter_clientside_by_date`: True para cualquier llamada al endpoint + # genérico `/news` (crypto O general), que NO acepta `from`/`to` + # server-side -- `/company-news` sí los acepta (ver `params` arriba), + # así que ese caso no necesita el recorte extra. + headlines = _fetch_finnhub_json(url, params, ticker, filter_clientside_by_date=is_crypto, since=since) + + # V11 (auditoría 2026-08) -- `/company-news` es EXCLUSIVO de compañías + # con perfil en Finnhub; ETFs (SPY, QQQ, ...) NUNCA tienen uno y + # devuelven [] SIEMPRE, sin importar cuántos reintentos. Fallback a + # `/news?category=general` (mercado agregado) filtrado client-side por + # el símbolo/nombre del ticker en el titular -- mejor que dejar el + # activo entero sin ninguna señal de prensa cuando DDGS tampoco rindió. + if not headlines and not is_crypto: + general_params = {"category": "general", "token": FINNHUB_API_KEY} + general = _fetch_finnhub_json(FINNHUB_GENERAL_NEWS_URL, general_params, ticker, + filter_clientside_by_date=True, since=since) + needle = ticker.upper() + headlines = [h for h in general if needle in h["title"].upper()] + + return headlines + + +def _fetch_finnhub_json(url: str, params: dict, ticker: str, filter_clientside_by_date: bool, since) -> list[dict]: + """Request GET con reintentos -- extraído de `_fetch_headlines_finnhub` para + reutilizarlo también en el fallback `/news?category=general` de ETFs. + `filter_clientside_by_date`: True para endpoints sin `from`/`to` + server-side (`/news`, crypto o general) -- recorta del lado del cliente + contra `since` para no arrastrar noticias arbitrariamente viejas.""" + last_exc: Exception | None = None + for attempt in range(1, _RETRY_ATTEMPTS + 1): + try: + response = requests.get(url, params=params, timeout=10) + response.raise_for_status() + payload = response.json() or [] + headlines = [] + for item in payload[:MAX_HEADLINES_PER_TICKER]: + title = item.get("headline") or item.get("summary") or "" + published_at = _normalize_timestamp(item.get("datetime")) + if filter_clientside_by_date and published_at is not None and published_at.date() < since: + continue + if title and published_at is not None: + headlines.append({"title": title, "published_at": published_at}) + return headlines + except Exception as exc: # noqa: BLE001 — red/HTTP transitorio + last_exc = exc + if attempt == _RETRY_ATTEMPTS: + break + time.sleep(_RETRY_BACKOFF_SECONDS * attempt) + + logger.warning("Finnhub falló tras %d intentos para %s: %r", _RETRY_ATTEMPTS, ticker, last_exc) + return [] + + +def fetch_recent_headlines(ticker: str) -> list[dict]: + """ + Orquesta ambas fuentes nativas (DDGS -> Finnhub) y deduplica por + título. DDGS es la fuente primaria (no exige API key); Finnhub + complementa cobertura solo cuando DDGS devuelve pocos titulares. + + CacheManager (kodaquant_core): cachea el resultado ya deduplicado por + `_HEADLINE_CACHE_TTL_SECONDS` -- evita re-golpear DDGS/Finnhub por + ticker dentro de la misma ventana corta cuando el radar escanea el + universo completo. Purga automática local en cada llamada (best-effort, + nunca bloquea el fetch real si falla). + """ + try: + _headline_cache.purge_stale() + except Exception as exc: # noqa: BLE001 -- la purga nunca debe tumbar el fetch real + logger.debug("[CacheManager] purge_stale falló (%r) -- se ignora.", exc) + + cache_key = f"headlines_{ticker}" + cached = _headline_cache.get_json(cache_key) + if cached is not None: + for h in cached: + h["published_at"] = _normalize_timestamp(h.get("published_at")) + return [h for h in cached if h.get("published_at") is not None] + + headlines = _fetch_headlines_ddg(ticker) + if len(headlines) < 5: + headlines += _fetch_headlines_finnhub(ticker) + + seen_titles: set[str] = set() + deduped: list[dict] = [] + for h in headlines: + if h["title"] not in seen_titles: + seen_titles.add(h["title"]) + deduped.append(h) + deduped = deduped[:MAX_HEADLINES_PER_TICKER] + + serializable = [ + {"title": h["title"], "published_at": h["published_at"].isoformat()} + for h in deduped + ] + _headline_cache.set_json(cache_key, serializable) + return deduped + + +def get_daily_news_sentiment( + ticker: str, + target_index: pd.DatetimeIndex, + scorer_fn: Callable[[str], float] = _score_text, +) -> pd.Series: + """ + Devuelve `NEWS_SENTIMENT_SCORE` alineado día a día contra `target_index` + (el mismo índice temporal que ya usan RSI/MACD/ATR/etc.). Cada titular se + promedia por día de publicación (UTC, normalizado a medianoche); los + días sin cobertura de prensa se rellenan hacia adelante (`ffill`) y, si + no hay ningún titular previo disponible, con `NEUTRAL_SCORE` (0.0) — la + misma convención de "lectura neutra" que SENTIMENT_SCORE ya usa en V4. + + Esta función debe llamarse ANTES de concatenar el tensor final al + espacio de entrada (batch, time_steps, features), junto al resto de los + indicadores técnicos en `engineer_asset`. + + FIX RAÍZ V7 (auditoría "señal muerta" — persiste tras el fix de tz V6, + NEWS_SENTIMENT_SCORE rank 17/17, atribución exacta 0.000000, EN TODOS + LOS ACTIVOS, no solo cripto): el fix V6 (despojar tz antes de comparar + fechas) era necesario pero NO suficiente — quedaban dos fallos + independientes, cualquiera de los dos basta por sí solo para colapsar + la columna entera a 0.0: + + (a) SCORER: ver `_score_text` — una etiqueta de FinBERT no reconocida + caía en `.get(label, 0.0)` -> 0.0 silencioso, SIN excepción, para + el 100% de los titulares, en TODOS los tickers por igual (fix + separado, ver ese docstring). + (b) MERGE: `Series.reindex` exige que la fecha-calendario del + titular calce EXACTA (bit a bit) con una fila del índice de + trading. Cripto cotiza 24/7 (hay fila para cada día), pero + equities NO — cualquier titular publicado un fin de semana o + feriado bursátil no tenía dónde aterrizar y quedaba NaN -> 0.0, + sin importar qué tan bien alineados estuvieran los tz. Se + reemplaza por `pd.merge_asof(direction="backward")`: busca el + titular MÁS RECIENTE publicado EN O ANTES de cada fecha del + índice (sin exigir igualdad exacta), acotado por + `_NEWS_MERGE_TOLERANCE_DAYS` para no arrastrar sentimiento añejo + indefinidamente como hacía el `.ffill()` sin cota anterior. + + Ambos lados de la fecha se normalizan ahora de forma SIMÉTRICA a + fecha-calendario UTC (`tz_convert("UTC")` real, no un `tz_localize(None)` + que solo despoja la etiqueta sin convertir el instante) — antes los + titulares se convertían a UTC pero `target_index` solo se despojaba de + su tz "tal cual", una asimetría de la que dependía silenciosamente el + calce. + """ + headlines = fetch_recent_headlines(ticker) + + if not headlines: + logger.info("Sin titulares recientes para %s -> NEWS_SENTIMENT_SCORE neutro.", ticker) + return pd.Series(NEUTRAL_SCORE, index=target_index, name="NEWS_SENTIMENT_SCORE") + + scored = pd.DataFrame(headlines) + scored["score"] = scored["title"].map(scorer_fn) + + # Diagnóstico (a): aísla un SCORER muerto de un MERGE con mala cobertura + # temporal — antes ambos colapsaban al mismo mensaje genérico y eran + # indistinguibles desde el log. + nonzero_scores = int((scored["score"].abs() > 1e-9).sum()) + + scored["date"] = ( + pd.DatetimeIndex(scored["published_at"]).tz_convert("UTC").tz_localize(None).normalize() + ) + daily = ( + scored.groupby("date")["score"].mean() + .sort_index() + .rename("headline_score") + .reset_index() + ) + + target_dt = pd.DatetimeIndex(target_index) + if target_dt.tz is not None: + target_dates = target_dt.tz_convert("UTC").tz_localize(None).normalize() + else: + target_dates = target_dt.normalize() + + # FIX: pandas 3.x ya no fuerza datetime64[ns] en todos lados -- conserva + # la resolución de origen de cada Serie (target_index puede venir en + # [us] del feed de mercado (Twelve Data/Stooq, ver services/market_data.py), + # "date" en [s] desde el parseo de published_at). + # merge_asof exige que ambas claves compartan EXACTAMENTE el mismo + # dtype, si no: "incompatible merge keys ... must be the same type". + # Se normalizan ambas a [ns] explícitamente antes de mergear. + frame = pd.DataFrame({"target_date": target_dates.astype("datetime64[ns]")}) + frame["orig_pos"] = range(len(frame)) + frame_sorted = frame.sort_values("target_date", kind="stable") + daily["date"] = daily["date"].astype("datetime64[ns]") + + merged = pd.merge_asof( + frame_sorted, + daily, + left_on="target_date", + right_on="date", + direction="backward", + tolerance=pd.Timedelta(days=_NEWS_MERGE_TOLERANCE_DAYS), + ).sort_values("orig_pos") + + aligned = pd.Series( + merged["headline_score"].to_numpy(), index=target_index, name="NEWS_SENTIMENT_SCORE", + ) + aligned = aligned.fillna(NEUTRAL_SCORE).clip(-1.0, 1.0) + + # Canario de cobertura, ahora DESAMBIGUADO: si la columna vuelve a + # colapsar a puro NEUTRAL_SCORE, el log dice CUÁL de las dos causas + # posibles es — nunca más un mensaje genérico "revisar fechas o API" + # cuando el problema real puede estar en el scorer y viceversa. + if (aligned == NEUTRAL_SCORE).all(): + if nonzero_scores == 0: + logger.warning( + "NEWS_SENTIMENT_SCORE 100%% neutro para %s: los %d titular(es) " + "obtenidos puntuaron EXACTAMENTE 0.0 en el scorer -> revisar, " + "en orden: (1) warnings de '_score_text'/etiqueta FinBERT no " + "reconocida arriba en el log; (2) idioma real de esos " + "titulares -- ProsusAI/finbert es inglés-únicamente, un " + "titular no-inglés puntúa 'neutral' SIN lanzar ningún warning " + "(ver V10, DDG_REGION); el merge de fechas es irrelevante, la " + "señal ya nace muerta antes de tocar cualquier lógica temporal.", + ticker, len(headlines), + ) + else: + logger.warning( + "NEWS_SENTIMENT_SCORE 100%% neutro para %s pese a %d titular(es) " + "obtenidos Y %d de ellos con score no-neutro real -> el scorer " + "funciona, es un problema de COBERTURA TEMPORAL: ninguna fecha " + "cae dentro de la tolerancia de %d día(s) contra target_index " + "(¿target_index desactualizado / caché parquet vieja / rango " + "histórico que no llega hasta fechas recientes?).", + ticker, len(headlines), nonzero_scores, _NEWS_MERGE_TOLERANCE_DAYS, + ) + + # V8 — suavizado EMA regime-aware (ver constantes arriba): el canario de + # cobertura recién evaluado corre SIEMPRE sobre la señal cruda (`aligned` + # sin suavizar) para no enmascarar un scorer/merge realmente muerto tras + # una EMA; el suavizado se aplica acá, al final, solo sobre lo que + # efectivamente entra al tensor. + ema_span = NEWS_SENTIMENT_EMA_SPAN_CRYPTO if _is_crypto_ticker(ticker) else NEWS_SENTIMENT_EMA_SPAN_EQUITY + if ema_span > 1: + aligned = aligned.ewm(span=ema_span, adjust=False).mean().rename("NEWS_SENTIMENT_SCORE") + + return aligned \ No newline at end of file diff --git a/services/free_alpha.py b/services/free_alpha.py new file mode 100644 index 0000000000000000000000000000000000000000..dd54c888247c55a4ce31639abea01c7e3e9f6c67 --- /dev/null +++ b/services/free_alpha.py @@ -0,0 +1,329 @@ +"""KodaQuant V28 -- alpha gratuito, UNA sola implementacion para train e inferencia. + +Copiar IDENTICO a `ml_engine/free_alpha.py` y `services/free_alpha.py` +(train importa de `ml_engine`, el motor de `services`; mismo patron que +`kodaquant_core.py`). Todo feature se calcula aca; ningun lado lo reimplementa, +asi TECH_COLS no puede desincronizarse por construccion. + +Causalidad: solo `.rolling()` trailing, `.shift(+n)`, `.diff()`. Cero `center=True`, +cero `shift(-n)`. `_selftest()` lo verifica por invariancia de prefijo. + +Fuentes (todas publicas, sin API key): + * Binance spot klines 1d (host espejo `data-api.binance.vision`, sirve donde + `api.binance.com` devuelve 451): volumen taker-buy REAL -> imbalance de agresor. + * Coinbase Exchange candles 1d (`api.exchange.coinbase.com`): prima Coinbase/Binance. + * Binance USD-M `premiumIndexKlines` 1d: base perpetuo-spot (puede estar geobloqueado). +Cualquier fuente caida -> columna 0.0 (neutra) + warning + `LAST_STATUS`. +""" +from __future__ import annotations + +import logging +import sys +import time +from typing import Optional + +import numpy as np +import pandas as pd + +logger = logging.getLogger("kodaquant.free_alpha") + +V28_EQUITY_COLS = [ + "OVERNIGHT_GAP_ZSCORE", # ln(Open_t / Close_{t-1}) z-scoreado + "INTRADAY_RET_ZSCORE", # ln(Close_t / Open_t) z-scoreado + "OVERNIGHT_MOM_ZSCORE", # media 10d del gap nocturno, z 120d (persistencia overnight) + "REL_STRENGTH_SPX_ZSCORE", # retorno 5d del activo menos retorno 5d de ^GSPC, z-scoreado +] +V28_CRYPTO_COLS = [ + "TAKER_IMBALANCE_ZSCORE", # (2*takerBuyBase/vol - 1), media 5d, z 60d -- flujo de agresor REAL + "TRADE_SIZE_ZSCORE", # log(quoteVol/trades), media 3d, z 60d -- retail vs ballena + "CB_PREMIUM_ZSCORE", # ln(close Coinbase USD / close Binance USDT), media 3d, z 60d + "PERP_BASIS_ZSCORE", # premium index perpetuo, media 3d, z 60d +] +V28_COLS = V28_EQUITY_COLS + V28_CRYPTO_COLS + +INDEX_PROXY_TICKERS = frozenset({"SPY"}) # rel-strength vs ^GSPC seria puro ruido de tracking + +Z_WINDOW, Z_MIN, Z_CLIP = 60, 30, 4.0 +OVERNIGHT_MOM_DAYS = 10 +REL_STRENGTH_DAYS = 5 +FLOW_SMOOTH_DAYS = 5 +PRICE_SMOOTH_DAYS = 3 +GAP_FFILL_LIMIT = 2 + +CRYPTO_SOURCES = { + "BTC-USD": {"spot": "BTCUSDT", "cb": "BTC-USD", "perp": "BTCUSDT"}, + "ETH-USD": {"spot": "ETHUSDT", "cb": "ETH-USD", "perp": "ETHUSDT"}, +} +_BINANCE_SPOT_URLS = ["https://data-api.binance.vision/api/v3/klines", + "https://api.binance.com/api/v3/klines"] +_BINANCE_PREMIUM_URLS = ["https://fapi.binance.com/fapi/v1/premiumIndexKlines"] +_COINBASE_URL = "https://api.exchange.coinbase.com/products/{product}/candles" + +LAST_STATUS: dict[str, dict[str, str]] = {} +_MEM_CACHE: dict[str, tuple[float, pd.DataFrame]] = {} +_MEM_TTL_SECONDS = 6 * 3600 + + +# ---------------------------------------------------------------------------- +# Primitivas +# ---------------------------------------------------------------------------- +def rolling_z(s: pd.Series, window: int = Z_WINDOW, min_periods: int = Z_MIN, + clip: float = Z_CLIP) -> pd.Series: + mean = s.rolling(window, min_periods=min_periods).mean() + std = s.rolling(window, min_periods=min_periods).std() + z = (s - mean) / std.replace(0.0, np.nan) + return z.replace([np.inf, -np.inf], np.nan).clip(-clip, clip).fillna(0.0) + + +def _naive_daily(index) -> pd.DatetimeIndex: + idx = pd.DatetimeIndex(index) + if idx.tz is not None: + idx = idx.tz_convert("UTC").tz_localize(None) + return idx.normalize() + + +# ---------------------------------------------------------------------------- +# EQUITY: descomposicion overnight/intraday + fuerza relativa +# ---------------------------------------------------------------------------- +def compute_equity_open_features(open_: Optional[pd.Series], close: pd.Series, + spx_logret: Optional[pd.Series] = None, + ticker: str = "") -> pd.DataFrame: + """Devuelve DataFrame(V28_EQUITY_COLS) alineado a `close.index`. + + `open_` None -> columnas overnight/intraday en 0.0 (neutras). + `spx_logret` = log-return diario de ^GSPC ya alineado al indice de `close`. + """ + out = pd.DataFrame(0.0, index=close.index, columns=V28_EQUITY_COLS) + if open_ is not None: + gap = np.log(open_ / close.shift(1)).replace([np.inf, -np.inf], np.nan) + intraday = np.log(close / open_).replace([np.inf, -np.inf], np.nan) + out["OVERNIGHT_GAP_ZSCORE"] = rolling_z(gap) + out["INTRADAY_RET_ZSCORE"] = rolling_z(intraday) + out["OVERNIGHT_MOM_ZSCORE"] = rolling_z( + gap.rolling(OVERNIGHT_MOM_DAYS, min_periods=OVERNIGHT_MOM_DAYS).mean(), + window=120, min_periods=60) + else: + logger.warning("[V28] '%s': sin columna Open -> features overnight/intraday = 0.0.", ticker) + if spx_logret is not None and ticker not in INDEX_PROXY_TICKERS: + asset_lr = np.log(close / close.shift(1)) + rel = (asset_lr.rolling(REL_STRENGTH_DAYS, min_periods=REL_STRENGTH_DAYS).sum() + - spx_logret.rolling(REL_STRENGTH_DAYS, min_periods=REL_STRENGTH_DAYS).sum()) + out["REL_STRENGTH_SPX_ZSCORE"] = rolling_z(rel) + return out + + +# ---------------------------------------------------------------------------- +# CRIPTO: fetchers +# ---------------------------------------------------------------------------- +def _http_get_json(urls: list[str], params: dict, timeout: int = 15, retries: int = 2): + import requests + for url in urls: + for attempt in range(retries + 1): + try: + r = requests.get(url, params=params, timeout=timeout, + headers={"User-Agent": "kodaquant/28"}) + if r.status_code in (403, 451): # geoblock -> siguiente host + break + if r.status_code in (418, 429): # rate limit + time.sleep(1.5 * (attempt + 1)) + continue + r.raise_for_status() + return r.json() + except Exception as exc: # noqa: BLE001 -- proveedor opcional + logger.debug("GET %s fallo (%r) intento %d", url, exc, attempt + 1) + time.sleep(0.4 * (attempt + 1)) + return None + + +def _paginate_binance_klines(urls: list[str], symbol: str, start_ms: int, limit: int) -> list: + rows: list = [] + cursor, now_ms = start_ms, int(time.time() * 1000) + for _ in range(40): + if cursor >= now_ms: + break + batch = _http_get_json(urls, {"symbol": symbol, "interval": "1d", + "startTime": cursor, "limit": limit}) + if not batch: + break + rows.extend(batch) + last_open = int(batch[-1][0]) + if last_open < cursor or len(batch) < limit: + break + cursor = last_open + 1 + time.sleep(0.12) + return rows + + +def fetch_binance_spot_daily(symbol: str, start: str = "2017-08-01") -> Optional[pd.DataFrame]: + start_ms = int(pd.Timestamp(start, tz="UTC").timestamp() * 1000) + rows = _paginate_binance_klines(_BINANCE_SPOT_URLS, symbol, start_ms, 1000) + if not rows: + return None + # [0]open_time [4]close [5]volume [7]quote_vol [8]trades [9]taker_buy_base + df = pd.DataFrame(rows).iloc[:, :10] + df.columns = ["open_time", "open", "high", "low", "close", "volume", + "close_time", "quote_volume", "trades", "taker_buy_base"] + df["date"] = pd.to_datetime(pd.to_numeric(df["open_time"]), unit="ms").dt.normalize() + for c in ("close", "volume", "quote_volume", "trades", "taker_buy_base"): + df[c] = pd.to_numeric(df[c], errors="coerce") + df = df.drop_duplicates("date", keep="last").set_index("date").sort_index() + return df[["close", "volume", "quote_volume", "trades", "taker_buy_base"]] + + +def fetch_binance_basis_daily(symbol: str, start: str = "2019-09-01") -> Optional[pd.Series]: + start_ms = int(pd.Timestamp(start, tz="UTC").timestamp() * 1000) + rows = _paginate_binance_klines(_BINANCE_PREMIUM_URLS, symbol, start_ms, 1500) + if not rows: + return None + df = pd.DataFrame(rows).iloc[:, :5] + df.columns = ["open_time", "open", "high", "low", "close"] + df["date"] = pd.to_datetime(pd.to_numeric(df["open_time"]), unit="ms").dt.normalize() + df["close"] = pd.to_numeric(df["close"], errors="coerce") + return df.drop_duplicates("date", keep="last").set_index("date").sort_index()["close"] + + +def fetch_coinbase_daily(product: str, start: str = "2016-01-01") -> Optional[pd.Series]: + cursor = pd.Timestamp(start, tz="UTC") + end_all = pd.Timestamp.now(tz="UTC") + rows: list = [] + while cursor < end_all: + chunk_end = min(cursor + pd.Timedelta(days=290), end_all) + data = _http_get_json([_COINBASE_URL.format(product=product)], + {"granularity": 86400, "start": cursor.isoformat(), + "end": chunk_end.isoformat()}) + if data is None: + break + rows.extend(data) # [time, low, high, open, close, volume] + cursor = chunk_end + time.sleep(0.25) + if not rows: + return None + df = pd.DataFrame(rows).iloc[:, :5] + df.columns = ["time", "low", "high", "open", "close"] + df["date"] = pd.to_datetime(pd.to_numeric(df["time"]), unit="s").dt.normalize() + df["close"] = pd.to_numeric(df["close"], errors="coerce") + return df.drop_duplicates("date", keep="last").set_index("date").sort_index()["close"] + + +def _cached(key: str, fetch, cache=None) -> Optional[pd.DataFrame]: + now = time.time() + hit = _MEM_CACHE.get(key) + if hit and now - hit[0] < _MEM_TTL_SECONDS: + return hit[1] + if cache is not None: + try: + df = cache.get_dataframe(key) + if df is not None and not df.empty: + _MEM_CACHE[key] = (now, df) + return df + except Exception: # noqa: BLE001 + pass + obj = fetch() + if obj is None or len(obj) == 0: + return None + df = obj.to_frame("v") if isinstance(obj, pd.Series) else obj + _MEM_CACHE[key] = (now, df) + if cache is not None: + try: + cache.set_dataframe(key, df) + except Exception: # noqa: BLE001 + pass + return df + + +# ---------------------------------------------------------------------------- +# CRIPTO: features (funcion pura, testeable sin red) +# ---------------------------------------------------------------------------- +def compute_crypto_flow_features(index, spot: Optional[pd.DataFrame], + coinbase: Optional[pd.Series], + basis: Optional[pd.Series]) -> pd.DataFrame: + idx = _naive_daily(index) + out = pd.DataFrame(0.0, index=idx, columns=V28_CRYPTO_COLS) + + def _align(s): + s = s.copy() + s.index = _naive_daily(s.index) + return s[~s.index.duplicated(keep="last")].reindex(idx).ffill(limit=GAP_FFILL_LIMIT) + + if spot is not None and len(spot): + sp = _align(spot) if isinstance(spot, pd.Series) else spot.copy() + if isinstance(sp, pd.DataFrame): + sp.index = _naive_daily(sp.index) + sp = sp[~sp.index.duplicated(keep="last")].reindex(idx).ffill(limit=GAP_FFILL_LIMIT) + vol = sp["volume"].replace(0.0, np.nan) + imb = (2.0 * sp["taker_buy_base"] / vol - 1.0).replace([np.inf, -np.inf], np.nan) + out["TAKER_IMBALANCE_ZSCORE"] = rolling_z(imb.rolling(FLOW_SMOOTH_DAYS, min_periods=3).mean()) + size = (sp["quote_volume"] / sp["trades"].replace(0.0, np.nan)).replace([np.inf, -np.inf], np.nan) + out["TRADE_SIZE_ZSCORE"] = rolling_z(np.log(size).rolling(PRICE_SMOOTH_DAYS, min_periods=2).mean()) + if coinbase is not None and len(coinbase): + prem = np.log(_align(coinbase) / sp["close"]).replace([np.inf, -np.inf], np.nan) + out["CB_PREMIUM_ZSCORE"] = rolling_z(prem.rolling(PRICE_SMOOTH_DAYS, min_periods=2).mean()) + if basis is not None and len(basis): + out["PERP_BASIS_ZSCORE"] = rolling_z(_align(basis).rolling(PRICE_SMOOTH_DAYS, min_periods=2).mean()) + return out + + +def build_crypto_flow_features(ticker: str, index, cache=None) -> pd.DataFrame: + """Descarga (con cache) + calcula. Cualquier fuente caida -> su columna queda 0.0.""" + src = CRYPTO_SOURCES.get(ticker) + if src is None: + return pd.DataFrame(0.0, index=_naive_daily(index), columns=V28_CRYPTO_COLS) + st = LAST_STATUS.setdefault(ticker, {}) + spot = _cached(f"v28_spot_{src['spot']}", lambda: fetch_binance_spot_daily(src["spot"]), cache) + cb = _cached(f"v28_cb_{src['cb']}", lambda: fetch_coinbase_daily(src["cb"]), cache) + bs = _cached(f"v28_basis_{src['perp']}", lambda: fetch_binance_basis_daily(src["perp"]), cache) + for name, obj in (("spot", spot), ("coinbase", cb), ("basis", bs)): + st[name] = "ok" if obj is not None else "DOWN" + if obj is None: + logger.warning("[V28] '%s': fuente '%s' no disponible -> sus features quedan en 0.0 " + "(riesgo de skew train/serve si difiere del entrenamiento).", ticker, name) + return compute_crypto_flow_features( + index, + spot, + cb["v"] if cb is not None else None, + bs["v"] if bs is not None else None, + ) + + +# ---------------------------------------------------------------------------- +# Autotest: causalidad (invariancia de prefijo) + forma +# ---------------------------------------------------------------------------- +def _selftest() -> None: + rng = np.random.default_rng(7) + n = 400 + idx = pd.bdate_range("2020-01-01", periods=n) + close = pd.Series(100 * np.exp(np.cumsum(rng.normal(0, 0.01, n))), index=idx) + open_ = close.shift(1) * np.exp(rng.normal(0, 0.003, n)) + open_.iloc[0] = close.iloc[0] + spx = pd.Series(rng.normal(0, 0.008, n), index=idx) + + full = compute_equity_open_features(open_, close, spx, "AAPL") + cut = 300 + pref = compute_equity_open_features(open_.iloc[:cut], close.iloc[:cut], spx.iloc[:cut], "AAPL") + np.testing.assert_allclose(full.iloc[:cut].values, pref.values, atol=1e-12, + err_msg="LOOKAHEAD en features equity V28") + assert list(full.columns) == V28_EQUITY_COLS and np.isfinite(full.values).all() + assert (compute_equity_open_features(open_, close, spx, "SPY")["REL_STRENGTH_SPX_ZSCORE"] == 0).all() + assert (compute_equity_open_features(None, close, spx, "AAPL")["OVERNIGHT_GAP_ZSCORE"] == 0).all() + + didx = pd.date_range("2019-01-01", periods=n, freq="D") + vol = pd.Series(rng.uniform(1e3, 2e3, n), index=didx) + spot = pd.DataFrame({ + "close": 20000 * np.exp(np.cumsum(rng.normal(0, 0.02, n))), + "volume": vol, "quote_volume": vol * 20000, + "trades": rng.integers(5e5, 9e5, n).astype(float), + "taker_buy_base": vol * rng.uniform(0.4, 0.6, n)}, index=didx) + cb = spot["close"] * np.exp(rng.normal(0, 0.001, n)) + basis = pd.Series(rng.normal(0.0003, 0.0002, n), index=didx) + f_full = compute_crypto_flow_features(didx, spot, cb, basis) + f_pref = compute_crypto_flow_features(didx[:300], spot.iloc[:300], cb.iloc[:300], basis.iloc[:300]) + np.testing.assert_allclose(f_full.iloc[:300].values, f_pref.values, atol=1e-12, + err_msg="LOOKAHEAD en features cripto V28") + assert list(f_full.columns) == V28_CRYPTO_COLS and np.isfinite(f_full.values).all() + assert (compute_crypto_flow_features(didx, None, None, None).values == 0).all() + print("free_alpha selftest OK (causalidad por prefijo, forma, degradacion a 0.0)") + + +if __name__ == "__main__": + if "--selftest" in sys.argv: + _selftest() \ No newline at end of file diff --git a/services/kodaquant_core.py b/services/kodaquant_core.py new file mode 100644 index 0000000000000000000000000000000000000000..323f4026a73c35304c9731fc15b2382c2ca0edda --- /dev/null +++ b/services/kodaquant_core.py @@ -0,0 +1,396 @@ +""" +kodaquant_core.py — KodaQuant V15: Núcleo Compartido Train/Inferencia +======================================================================== +Consolidación arquitectónica (auditoría CTO, 2026-08-16). Antes de este +módulo, tres piezas de lógica CRÍTICA vivían duplicadas e independientes +entre el pipeline de entrenamiento (`train_kodaquant_v5.py`) y el de +inferencia (`quanti_engine.py`/`market_data.py`), con implementaciones +DIVERGENTES: + + 1. CACHÉ EN DISCO — `market_data.py` (inferencia) cacheaba JSON con TTL + de horas (`_cache_get`/`_cache_set`); `train_kodaquant_v5.py` + (entrenamiento) cacheaba Parquet con staleness por antigüedad de + fecha (`_cache_is_stale`/`download_all`) + un purgado manual separado + (`purge_data_cache`). Dos formatos, dos políticas de expiración, cero + purga automática. `CacheManager` unifica ambos modos (JSON de vida + corta para respuestas de API en vivo, Parquet de vida larga para + descargas históricas masivas) bajo una sola clase, con purga + automática local (`purge_stale`) y purga total explícita + (`purge_all`, reemplazo directo de `purge_data_cache`). + + 2. CLIENTE FRED — vivía únicamente en `market_data.py` + (`_fred_series_daily`), usado SOLO en inferencia. `train_kodaquant_v5.py` + jamás lo importaba: el entrenamiento resolvía `^TNX` con el + `yf.download` genérico, mientras que la inferencia ya lo resolvía vía + FRED (serie oficial `DGS10`) con fallback a Stooq -- exactamente la + discrepancia "train ve una fuente, infiere con otra" reportada. Se + porta acá como `FredClient`, reutilizable desde ambos lados. + + 3. ALINEACIÓN DE CALENDARIO MACRO (5/7) CONTRA UN ACTIVO 24/7 — el fix + real ya existía, pero solo del lado de inferencia + (`market_data._macro_close_ffilled_to_daily_calendar`, fix + 2026-08-15): upsamplear cada serie macro a un calendario diario + CORRIDO (fin de semana incluido) y hacer forward-fill DENTRO de esa + serie, ANTES de reindexarla contra el calendario del activo objetivo. + `engineer_asset()` (entrenamiento) seguía dependiendo de un + `df.ffill()` ciego sobre el frame YA combinado, que no tiene la misma + garantía en huecos que no calzan por orden de columnas ni en el + arranque de la serie. `align_macro_to_calendar` es ahora la ÚNICA + implementación de esta lógica; train e inferencia la importan por + igual -- ver `data_pipeline.py`/`train_kodaquant_v5.py`. + +DESPLIEGUE EN DOS DIRECTORIOS (sin romper la topología actual del repo): +este archivo debe copiarse tal cual a AMBAS ubicaciones que hoy contienen +copias paralelas de `data_pipeline.py`/`market_data.py`: + - `services/kodaquant_core.py` (consumido por quanti_engine.py, + import de paquete: `from services.kodaquant_core import ...`) + - /kodaquant_core.py (consumido por + train_kodaquant_v5.py/train_pipeline.py, import plano: + `from kodaquant_core import ...`) +Cero dependencias externas nuevas: solo `pandas`/`numpy`/`requests`, ya +pineados en ambos entornos. `data_pipeline.py`, `train_kodaquant_v5.py` y +`quanti_engine.py` importan este módulo con el mismo patrón dual +try/except ya usado en el repo para `ddgs`/`duckduckgo_search` (ver +`data_pipeline.py`), así que una sola copia de este archivo sirve para +ambas ubicaciones sin ninguna otra modificación. + +PENDIENTE FUERA DE ESTE ALCANCE (no es uno de los 4 artefactos +entregados, se deja documentado para no perder el hilo): `market_data.py` +sigue con su propio `_fred_series_daily`/`_cache_get`/`_cache_set` +inline -- migrarlo para que importe `FredClient`/`CacheManager` de acá +es un cambio mecánico de una sola función, recomendado como siguiente +paso para que TODA la superficie del repo, no solo train, comparta el +mismo núcleo. +""" + +from __future__ import annotations + +import io +import json +import logging +import threading +import time +from datetime import datetime, timezone +from pathlib import Path +from typing import Optional + +import pandas as pd +import requests + +logger = logging.getLogger("kodaquant.core") + + +# =========================================================================== +# 1) CACHE MANAGER — disco unificado (JSON TTL-corto + Parquet TTL-largo), +# thread-safe, con purga automática local. +# =========================================================================== +class CacheManager: + """ + Caché en disco de dos modos, un solo punto de verdad: + + - `get_json`/`set_json` -> payloads pequeños de vida corta (Close + histórico de un símbolo, headlines de noticias). Expira por TTL + absoluto en segundos (`default_ttl_seconds`), igual semántica que + el cache JSON que ya usaba `market_data.py`. + - `get_dataframe`/`set_dataframe` -> descargas masivas (OHLCV + multi-símbolo de `download_all`). Expira por ANTIGÜEDAD DEL DATO + (última fecha en el índice vs. `datetime.now()`), no por edad del + archivo -- misma semántica que `_cache_is_stale` en + `train_kodaquant_v5.py`: un parquet escrito hace 5 minutos pero + cuya fila más reciente es de hace 3 días sigue estando "viejo". + + Cada instancia posee su PROPIO `cache_dir` -- entrenamiento e + inferencia deben instanciar `CacheManager` con directorios distintos + (no comparten el mismo caché en disco, cada uno con su propia purga), + pero ambos usan la MISMA clase/lógica. + """ + + def __init__(self, cache_dir: Path | str, default_ttl_seconds: int = 6 * 3600, + default_max_age_hours: float = 48.0) -> None: + self.cache_dir = Path(cache_dir) + self.cache_dir.mkdir(parents=True, exist_ok=True) + self.default_ttl_seconds = default_ttl_seconds + self.default_max_age_hours = default_max_age_hours + self._lock = threading.Lock() + + # -- helpers de path -------------------------------------------------- + def _safe_name(self, key: str) -> str: + return key.replace("/", "_").replace(":", "_").replace("^", "caret_").replace(" ", "_") + + def _json_path(self, key: str) -> Path: + return self.cache_dir / f"{self._safe_name(key)}.json" + + def _parquet_path(self, key: str) -> Path: + return self.cache_dir / f"{self._safe_name(key)}.parquet" + + # -- modo JSON (TTL absoluto) ------------------------------------------ + def get_json(self, key: str, ttl_seconds: Optional[int] = None, ignore_ttl: bool = False): + """ + Devuelve el payload cacheado (cualquier objeto JSON-serializable, + incluye DataFrames vía orient="split") o `None` si no existe/expiró. + `ignore_ttl=True` -- último recurso: devuelve lo último en disco sin + importar el TTL (ej. Twelve Data Y Stooq caídos a la vez); marca + `_stale_age_hours` en el resultado si el DataFrame lo soporta. + """ + ttl = self.default_ttl_seconds if ttl_seconds is None else ttl_seconds + path = self._json_path(key) + try: + with self._lock: + if not path.exists(): + return None + payload = json.loads(path.read_text()) + age_s = time.time() - payload.get("_cached_at", 0) + if not ignore_ttl and age_s > ttl: + return None + data = payload.get("data") + kind = payload.get("_kind", "raw") + if kind == "dataframe": + df = pd.read_json(io.StringIO(data), orient="split") + df.index = pd.to_datetime(df.index) + if ignore_ttl and age_s > ttl: + df.attrs["_stale_age_hours"] = round(age_s / 3600, 1) + return df + return data + except Exception as exc: # noqa: BLE001 -- caché corrupta jamás tumba el caller + logger.debug("[CacheManager] JSON ilegible para %s (%r) -- se ignora.", key, exc) + return None + + def set_json(self, key: str, value) -> None: + path = self._json_path(key) + if isinstance(value, pd.DataFrame): + payload = {"_kind": "dataframe", "data": value.to_json(orient="split", date_format="iso"), + "_cached_at": time.time()} + else: + payload = {"_kind": "raw", "data": value, "_cached_at": time.time()} + try: + with self._lock: + path.write_text(json.dumps(payload)) + except Exception as exc: # noqa: BLE001 -- fallo al escribir caché nunca tumba el caller + logger.debug("[CacheManager] No se pudo escribir caché JSON %s (%r).", key, exc) + + # -- modo DataFrame/Parquet (staleness por fecha del dato) ------------ + def get_dataframe(self, key: str, max_age_hours: Optional[float] = None, + required_columns: Optional[set[str]] = None) -> Optional[pd.DataFrame]: + """ + `None` si no existe, si le faltan columnas requeridas, o si su fila + más reciente supera `max_age_hours` de antigüedad respecto a AHORA + (no la edad del archivo) -- ver docstring de la clase. + """ + max_age = self.default_max_age_hours if max_age_hours is None else max_age_hours + path = self._parquet_path(key) + if not path.exists(): + return None + try: + with self._lock: + cached = pd.read_parquet(path) + except Exception as exc: # noqa: BLE001 + logger.warning("[CacheManager] Parquet corrupto para %s (%r) -- se ignora.", key, exc) + return None + + if required_columns and not required_columns.issubset(set(cached.columns)): + return None + if cached.empty: + return None + + max_date = pd.Timestamp(cached.index.max()) + max_date = max_date.tz_localize("UTC") if max_date.tzinfo is None else max_date.tz_convert("UTC") + age = datetime.now(timezone.utc) - max_date.to_pydatetime() + if age.total_seconds() > max_age * 3600: + logger.info("[CacheManager] %s obsoleto -- fecha más reciente %s tiene más de %.0fh -- recarga forzada.", + path.name, cached.index.max(), max_age) + return None + return cached + + def set_dataframe(self, key: str, df: pd.DataFrame) -> None: + path = self._parquet_path(key) + try: + with self._lock: + df.to_parquet(path) + except Exception as exc: # noqa: BLE001 + logger.warning("[CacheManager] No se pudo escribir parquet %s (%r).", key, exc) + + # -- purga automática local -------------------------------------------- + def purge_all(self) -> int: + """Vacía TODO el caché en disco (JSON + Parquet) de este `cache_dir`. Reemplazo directo de `purge_data_cache`.""" + removed = list(self.cache_dir.glob("*.json")) + list(self.cache_dir.glob("*.parquet")) + with self._lock: + for f in removed: + f.unlink(missing_ok=True) + if removed: + logger.warning("[CacheManager] Purga total -> %d archivo(s) purgado(s) de %s.", len(removed), self.cache_dir) + return len(removed) + + def purge_stale(self, ttl_seconds: Optional[int] = None, max_age_hours: Optional[float] = None) -> int: + """ + Purga automática local (Requerimiento 1): recorre `cache_dir` y + elimina solo las entradas efectivamente vencidas, sin tocar + entradas todavía válidas -- pensado para invocarse periódicamente + (ej. al arrancar cada corrida) sin tirar caché sano. + """ + ttl = self.default_ttl_seconds if ttl_seconds is None else ttl_seconds + max_age = self.default_max_age_hours if max_age_hours is None else max_age_hours + removed = 0 + now = time.time() + for path in self.cache_dir.glob("*.json"): + try: + payload = json.loads(path.read_text()) + if now - payload.get("_cached_at", 0) > ttl: + path.unlink(missing_ok=True) + removed += 1 + except Exception: # noqa: BLE001 -- JSON corrupto = candidato directo a purga + path.unlink(missing_ok=True) + removed += 1 + for path in self.cache_dir.glob("*.parquet"): + try: + cached = pd.read_parquet(path) + if cached.empty: + continue + max_date = pd.Timestamp(cached.index.max()) + max_date = max_date.tz_localize("UTC") if max_date.tzinfo is None else max_date.tz_convert("UTC") + age_h = (datetime.now(timezone.utc) - max_date.to_pydatetime()).total_seconds() / 3600 + if age_h > max_age: + path.unlink(missing_ok=True) + removed += 1 + except Exception: # noqa: BLE001 -- parquet corrupto = candidato directo a purga + path.unlink(missing_ok=True) + removed += 1 + if removed: + logger.info("[CacheManager] Purga automática -> %d entrada(s) vencida(s) purgada(s) de %s.", removed, self.cache_dir) + return removed + + +# =========================================================================== +# 2) CLIENTE FRED — fuente PRIMARIA para series macro sin ETF/futuro +# equivalente (ej. ^TNX / DGS10). Portado 1:1 de market_data.py, ahora +# reutilizable desde entrenamiento (antes solo lo veía inferencia). +# =========================================================================== +class FredClient: + """ + Cliente resiliente para `api.stlouisfed.org/fred/series/observations`. + 100% gratis, requiere `api_key` (opcional -- si no se provee, cada + llamada devuelve `None` sin tocar la red, igual que antes de RONDA 2 en + `market_data.py`). Reintenta con backoff exponencial ante 429/timeout. + """ + + BASE_URL = "https://api.stlouisfed.org/fred/series/observations" + + def __init__(self, api_key: str = "", timeout_s: float = 15.0) -> None: + self.api_key = (api_key or "").strip() + self.timeout_s = timeout_s + if not self.api_key: + logger.warning( + "[FredClient] Sin api_key -- toda serie FRED (ej. DGS10/^TNX) " + "devolverá None y caerá al fallback del caller (Stooq)." + ) + + def daily_series(self, series_id: str, tail_days: int, attempts: int = 3) -> Optional[pd.Series]: + """ + `pd.Series` de Close diario (valor oficial de la serie FRED) o + `None` si falta `api_key` o la request falla tras `attempts` + reintentos. FRED marca días sin observación (feriados, fin de + semana) con `"."` en vez de omitir la fila -- se filtran acá antes + de devolver, para que el caller nunca vea un NaN string. + """ + if not self.api_key: + return None + + params = { + "series_id": series_id, + "api_key": self.api_key, + "file_type": "json", + "sort_order": "desc", + "limit": max(tail_days, 30), + } + last_exc: Exception | None = None + for attempt in range(1, attempts + 1): + try: + resp = requests.get(self.BASE_URL, params=params, timeout=self.timeout_s) + if resp.status_code == 429: + raise RuntimeError(f"FRED rate limit (429): {resp.text[:200]}") + resp.raise_for_status() + payload = resp.json() + obs = payload.get("observations", []) + rows = [(o["date"], o["value"]) for o in obs if o.get("value") not in (None, ".")] + if not rows: + return None + dates, values = zip(*rows) + series = pd.Series( + [float(v) for v in values], + index=pd.to_datetime(dates), + name=series_id, + ).sort_index() + return series + except Exception as exc: # noqa: BLE001 -- red/HTTP transitorio + last_exc = exc + if attempt == attempts: + break + time.sleep(1.5 * attempt) + logger.warning("[FredClient] agotó reintentos para la serie '%s': %r", series_id, last_exc) + return None + + +# =========================================================================== +# 3) ALINEACIÓN DE CALENDARIO MACRO — fuente ÚNICA para ambos pipelines. +# =========================================================================== +def normalize_daily_index(index: pd.DatetimeIndex) -> pd.DatetimeIndex: + """ + tz-aware -> tz-naive + medianoche. Un solo símbolo (target O macro) + tz-aware colisionando contra el otro tz-naive hace fallar `.reindex()`/ + `.merge()` en TODAS las fechas, no solo fines de semana -- se normaliza + en el borde de ingesta para que ninguna comparación aguas abajo pueda + volver a pisar este bug (ver `market_data.py`, fix 2026-08-15). + """ + if index.tz is not None: + index = index.tz_localize(None) + return index.normalize() + + +def align_macro_to_calendar(macro_close: pd.Series, upto: pd.Timestamp) -> pd.Series: + """ + CAUSA RAÍZ real de "pérdida masiva de datos cripto en fines de semana": + los macro tickers (SPY/DGS10/XAU-USD/VIXY/UUP, todos vía bolsas + tradicionales) cotizan 5/7; un activo cripto cotiza 24/7. Reindexar la + serie macro DIRECTO contra un calendario de 7 días deja NaN cada + sábado/domingo -- un `.ffill()` posterior sobre el frame YA combinado + tapa la mayoría de esos huecos, pero cualquier fila líder anterior a la + primera fecha del macro ticker (o un hueco interno que el orden de + columnas no alcance a cubrir de forma determinista) sobrevive como NaN, + y un `dropna()` sobre el frame completo puede vaciarlo entero. + + Fix: upsamplear la serie macro a un calendario DIARIO CORRIDO (freq="D", + fin de semana incluido) y forward-fill DENTRO de esa serie -- ANTES de + reindexarla contra el calendario del activo objetivo. El valor de un + viernes de bolsa queda disponible como input válido para sábado/domingo + de cripto, sin depender del orden ni de la suerte del ffill final sobre + el frame ya combinado. NUNCA se hace `bfill` (relleno hacia atrás) -- + sería fuga de información (un valor FUTURO del macro ticker "explicando" + un día pasado). Único costo real: los primeros días, anteriores al + primer dato macro disponible, siguen sin cobertura y se recortan aguas + abajo por el `dropna()` normal del pipeline, exactamente igual que + antes de este fix. + """ + if macro_close.empty: + return macro_close + macro_close = macro_close[~macro_close.index.duplicated(keep="last")].sort_index() + macro_close.index = normalize_daily_index(pd.DatetimeIndex(macro_close.index)) + calendar_end = max(macro_close.index.max(), pd.Timestamp(upto)) + daily_calendar = pd.date_range(macro_close.index.min(), calendar_end, freq="D") + return macro_close.reindex(daily_calendar).ffill() + + +def project_macro_frame(macro_closes: dict[str, pd.Series], target_index: pd.DatetimeIndex) -> pd.DataFrame: + """ + Punto de entrada único: dado `{macro_ticker: pd.Series de Close crudo}` + y el índice del activo objetivo (24/7 o 5/7, no importa cuál), devuelve + un DataFrame `out[macro_ticker]` ya alineado con `align_macro_to_calendar` + -- MISMA llamada desde `engineer_asset` (entrenamiento) y + `fetch_feature_ohlcv`/`_fetch_feature_window` (inferencia), para que + ambos pipelines vean el mundo macro exactamente igual (Requerimiento 3). + """ + target_index = normalize_daily_index(pd.DatetimeIndex(target_index)) + target_last_date = target_index.max() if len(target_index) else pd.Timestamp.now(tz=timezone.utc).normalize() + out = pd.DataFrame(index=target_index) + for macro_ticker, macro_close in macro_closes.items(): + aligned = align_macro_to_calendar(macro_close, target_last_date) + out[macro_ticker] = aligned.reindex(target_index) + return out \ No newline at end of file diff --git a/services/kodaquant_models/crypto_specialist/evaluation_chart.png b/services/kodaquant_models/crypto_specialist/evaluation_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..acdf344ac73317d9f29f3b852fa551575dc826dd --- /dev/null +++ b/services/kodaquant_models/crypto_specialist/evaluation_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06baad106e5ba2458b9319739eff5c7ee41edf04f8de023706351784e0c66e09 +size 112629 diff --git a/services/kodaquant_models/crypto_specialist/meta_labeler.pkl b/services/kodaquant_models/crypto_specialist/meta_labeler.pkl new file mode 100644 index 0000000000000000000000000000000000000000..06f907405aa407d048fa1d0c795633b01bc6852d --- /dev/null +++ b/services/kodaquant_models/crypto_specialist/meta_labeler.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d7b07a2763ce2957c76ff92ae67ea0af46234e5d7ac91790bb3d88e16ba4879 +size 369494 diff --git a/services/kodaquant_models/crypto_specialist/model_v5.keras b/services/kodaquant_models/crypto_specialist/model_v5.keras new file mode 100644 index 0000000000000000000000000000000000000000..8ee8b2c24a6d228027db0636b07259952f79b5d1 --- /dev/null +++ b/services/kodaquant_models/crypto_specialist/model_v5.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6414d866fe358b2b9c0aae98636f219bcefcf712653afcabe043e1591b501418 +size 619054 diff --git a/services/kodaquant_models/crypto_specialist/scalers_dict.pkl b/services/kodaquant_models/crypto_specialist/scalers_dict.pkl new file mode 100644 index 0000000000000000000000000000000000000000..82472fdd023e8e170048561d30abb461f1938958 --- /dev/null +++ b/services/kodaquant_models/crypto_specialist/scalers_dict.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edf11c9df6ae2733e3dbd878ed41fb4531276fdd0bec7c5dc3991c3261779228 +size 5036 diff --git a/services/kodaquant_models/crypto_specialist_experimental/evaluation_chart.png b/services/kodaquant_models/crypto_specialist_experimental/evaluation_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..80d57fa3a0dc8b35221fa4514ca38321183a207a --- /dev/null +++ b/services/kodaquant_models/crypto_specialist_experimental/evaluation_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7e32d2f9a4072bbd9e91d6eb46509c5e0fb227db472a5115aaee5a31044b3de +size 230370 diff --git a/services/kodaquant_models/crypto_specialist_experimental/model_v5.keras b/services/kodaquant_models/crypto_specialist_experimental/model_v5.keras new file mode 100644 index 0000000000000000000000000000000000000000..8ade77a2ab5f85969e09d0135ea650db138ff8e8 --- /dev/null +++ b/services/kodaquant_models/crypto_specialist_experimental/model_v5.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:209fd8f2db2400ec27cc10d323d2d6b40dd1484f1dfa26868dc0a12675a933bc +size 5967593 diff --git a/services/kodaquant_models/crypto_specialist_experimental/scalers_dict.pkl b/services/kodaquant_models/crypto_specialist_experimental/scalers_dict.pkl new file mode 100644 index 0000000000000000000000000000000000000000..fbc9496ca57bf64c9689b9094d5f4e2f9d4755cf --- /dev/null +++ b/services/kodaquant_models/crypto_specialist_experimental/scalers_dict.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b4e796a5876441063f22ffa3345dde6de83bab3461e9ac030100f4cc6efcf48 +size 2856 diff --git a/services/kodaquant_models/equity_specialist/evaluation_chart.png b/services/kodaquant_models/equity_specialist/evaluation_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..eca8363fd8f9711b18acef40dba7b4f399ef996e --- /dev/null +++ b/services/kodaquant_models/equity_specialist/evaluation_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a876d15075bc0c91f66b48f9d4c4eae29120f29a2eaccc3a5feef8bebeb53f58 +size 884635 diff --git a/services/kodaquant_models/equity_specialist/model_v5.keras b/services/kodaquant_models/equity_specialist/model_v5.keras new file mode 100644 index 0000000000000000000000000000000000000000..c636866b1879d495305c650a984cc634a98828f7 --- /dev/null +++ b/services/kodaquant_models/equity_specialist/model_v5.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:072e9e68d2e4d6b6a2e6e0178bd8b43805b8e5fa89f3c8a464f46efda974f8ce +size 6926686 diff --git a/services/kodaquant_models/equity_specialist/scalers_dict.pkl b/services/kodaquant_models/equity_specialist/scalers_dict.pkl new file mode 100644 index 0000000000000000000000000000000000000000..5d046ef7a0572d214585889cf7d7c0a8d96f95c6 --- /dev/null +++ b/services/kodaquant_models/equity_specialist/scalers_dict.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07420b0a6575918ba5ecd285cf7c696fd453fa0a9f5a7203b818e4e5d3a6533e +size 17162 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260823/evaluation_chart.png b/services/kodaquant_models/equity_specialist_BACKUP_20260823/evaluation_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..cdd096acaef72c964dfecdbe5bee02d4c4af9933 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260823/evaluation_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ecc4615b60ea7b9a1672292d02dda0c32970bdc325f79c98e98a96de3b0cb2a6 +size 874518 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260823/model_v5.keras b/services/kodaquant_models/equity_specialist_BACKUP_20260823/model_v5.keras new file mode 100644 index 0000000000000000000000000000000000000000..a23f6d4af4e5ea4f8814e5572e74b8aa99384623 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260823/model_v5.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e32474d2f7631164f353618de7ec5970f9421561d9b595f990a67869490a1b1 +size 6658889 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260823/scalers_dict.pkl b/services/kodaquant_models/equity_specialist_BACKUP_20260823/scalers_dict.pkl new file mode 100644 index 0000000000000000000000000000000000000000..29ec87ffc4c9b01354cfacc4e422707579a9c3f3 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260823/scalers_dict.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa6e7f94268c5e168edcf11f6e155b68a07eea943bf578fcef49f9ce6609ce98 +size 9653 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/evaluation_chart.png b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/evaluation_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..396eb0b956eb6f3b5073da3023b41e6768b14d5c --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/evaluation_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90ade4d6610b75d87324815e53aaf0ea8327cfe61f6f5fcca52ae3811e594a53 +size 869872 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/model_v5.keras b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/model_v5.keras new file mode 100644 index 0000000000000000000000000000000000000000..3c02a563e887639981927ad65674cdba4f4441fa --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/model_v5.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4d6d1883cd9a23ef907a79c86f5f38e2bb7e94e3c30d2ac3db334f03c4acd02 +size 6658888 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/model_v5_best.keras b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/model_v5_best.keras new file mode 100644 index 0000000000000000000000000000000000000000..c7b21e413a3b822e708116ba20e2262deb5abf87 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/model_v5_best.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ddaa557cbbd1a6e190e8419198db7caf43ae96a2499e0a24476c16853850568 +size 6660457 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/scalers_dict.pkl b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/scalers_dict.pkl new file mode 100644 index 0000000000000000000000000000000000000000..867321e449960ba35d715501f2f03da96e179f68 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260824/equity_specialist/scalers_dict.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9a2c158469426bb25166f618e796d4a323ca5b9e66eb1d976cf741e6e06ba33 +size 9653 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260824/evaluation_chart.png b/services/kodaquant_models/equity_specialist_BACKUP_20260824/evaluation_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..396eb0b956eb6f3b5073da3023b41e6768b14d5c --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260824/evaluation_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90ade4d6610b75d87324815e53aaf0ea8327cfe61f6f5fcca52ae3811e594a53 +size 869872 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260824/model_v5.keras b/services/kodaquant_models/equity_specialist_BACKUP_20260824/model_v5.keras new file mode 100644 index 0000000000000000000000000000000000000000..3c02a563e887639981927ad65674cdba4f4441fa --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260824/model_v5.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4d6d1883cd9a23ef907a79c86f5f38e2bb7e94e3c30d2ac3db334f03c4acd02 +size 6658888 diff --git a/services/kodaquant_models/equity_specialist_BACKUP_20260824/scalers_dict.pkl b/services/kodaquant_models/equity_specialist_BACKUP_20260824/scalers_dict.pkl new file mode 100644 index 0000000000000000000000000000000000000000..867321e449960ba35d715501f2f03da96e179f68 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_BACKUP_20260824/scalers_dict.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9a2c158469426bb25166f618e796d4a323ca5b9e66eb1d976cf741e6e06ba33 +size 9653 diff --git a/services/kodaquant_models/equity_specialist_experimental/evaluation_chart.png b/services/kodaquant_models/equity_specialist_experimental/evaluation_chart.png new file mode 100644 index 0000000000000000000000000000000000000000..7ca7c53b2f3dfd03f1fdd223f8a83161c6be3b24 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_experimental/evaluation_chart.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f4bc1bb2fa71296c47534c86169111886a91f1343db8d0f92cb64be9a0a7d21 +size 863087 diff --git a/services/kodaquant_models/equity_specialist_experimental/model_v5.keras b/services/kodaquant_models/equity_specialist_experimental/model_v5.keras new file mode 100644 index 0000000000000000000000000000000000000000..b2eb703e8fc572ce4a87a1c72b533d89c21ee822 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_experimental/model_v5.keras @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab7f1935761970d9dd3fae10f2e693fe11bffc8a871004eebd1bca2c9c8535af +size 5968163 diff --git a/services/kodaquant_models/equity_specialist_experimental/scalers_dict.pkl b/services/kodaquant_models/equity_specialist_experimental/scalers_dict.pkl new file mode 100644 index 0000000000000000000000000000000000000000..24849d541f426ef1bd6a26880b6dd9e7b2645925 --- /dev/null +++ b/services/kodaquant_models/equity_specialist_experimental/scalers_dict.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9511db9c5036065aed45f1e778c4218b61e2aafd9ed26a911558d61d68ab543e +size 9342 diff --git a/services/live_trade.py b/services/live_trade.py new file mode 100644 index 0000000000000000000000000000000000000000..804bfb42b0257e5b299c878c4796e94574e1563a --- /dev/null +++ b/services/live_trade.py @@ -0,0 +1,414 @@ +""" +live_trade.py -- Inferencia diaria + órdenes a Alpaca (paper trading) +============================================================================= +Cierra el círculo: toma el modelo YA entrenado y validado +(`services/kodaquant_models/equity_specialist/model_v5.keras`, producido por +`python ml_engine/train_kodaquant_v5.py`), corre inferencia sobre el día de +HOY con el mismo pipeline exacto de features que el entrenamiento +(`tkv5.download_all`/`tkv5.engineer_asset` -- cero drift train/serve), y +envía órdenes a tu cuenta paper de Alpaca con el mismo sizing por +vol-target que ya validamos en `pnl_backtest.py`. + +SEGURIDAD: corre en modo DRY-RUN por default -- imprime qué órdenes +mandaría, pero NO llama a Alpaca. Hace falta `--live` explícito para que +efectivamente envíe órdenes (a tu cuenta *paper*, sin plata real, pero aun +así conviene el freno). + +REQUISITOS (una sola vez): + 1. python ml_engine/train_kodaquant_v5.py -- si todavía no corriste + el entrenamiento de producción completo (walk_forward_eval.py y + pnl_backtest.py entrenan modelos DESCARTABLES por fold -- ninguno + queda guardado en disco. Este es el que sí hay que generar una vez). + 2. export ALPACA_API_KEY=tu_key + export ALPACA_SECRET_KEY=tu_secret + (Dashboard de Alpaca -> "Generate New Key", con la cuenta en modo + Paper Trading activado.) + +USO: + python services/live_trade.py # dry-run equity_specialist (default, seguro) + python services/live_trade.py --regime crypto_specialist # dry-run V22 (target_mode="triple_barrier") + python services/live_trade.py --live # envía órdenes de verdad (a paper) + python services/live_trade.py --vol-target-annual 0.15 + python services/live_trade.py --regime crypto_specialist --min-confidence 0.5 +""" +from __future__ import annotations + +import argparse +import logging +import pickle +import sys +from pathlib import Path + +import numpy as np +import requests + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (mismo bootstrap que el resto del repo) - +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# Import como módulo -- el `if __name__ == "__main__"` de train_kodaquant_v5.py +# NO se ejecuta acá, es seguro traer sus funciones/constantes sin disparar +# un entrenamiento completo. +import ml_engine.train_kodaquant_v5 as tkv5 # noqa: E402 + +logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s") +logger = logging.getLogger("kodaquant.live_trade") + +ALPACA_BASE_URL = "https://paper-api.alpaca.markets" +VOL_LOOKBACK_DAYS = 20 +MAX_LEVERAGE = 3.0 + +# V22 — meta-labeling (López de Prado, cap. 3), MISMO criterio y MISMO +# valor que `quanti_engine.TB_MIN_SIGNAL_CONFIDENCE` +# (services/quanti_engine.py) — duplicado a propósito acá, no importado: +# este script vive del lado `ml_engine/` (importa `tkv5` directo, ver +# `_bootstrap_project_root`), nunca del lado `services/` donde vive +# quanti_engine.py — acoplar ambos módulos por un solo float no vale el +# import cruzado. Si calibrás uno con pnl_backtest.py/walk_forward_eval.py +# (ver MANUAL DE IGNICIÓN), replicá el número acá también. +TB_MIN_SIGNAL_CONFIDENCE = 0.45 + + +def _alpaca_headers() -> dict: + import os + key, secret = os.environ.get("ALPACA_API_KEY", ""), os.environ.get("ALPACA_SECRET_KEY", "") + if not key or not secret: + raise RuntimeError( + "Faltan ALPACA_API_KEY / ALPACA_SECRET_KEY en el entorno. " + "Generalas en el dashboard de Alpaca (modo Paper Trading) y " + "exportalas antes de correr este script." + ) + return {"APCA-API-KEY-ID": key, "APCA-API-SECRET-KEY": secret} + + +def _load_production_model(regime_name: str): + model_dir = tkv5.MODELS_ROOT / regime_name + model_path, scalers_path = model_dir / "model_v5.keras", model_dir / "scalers_dict.pkl" + if not model_path.exists() or not scalers_path.exists(): + raise RuntimeError( + f"No existe un modelo de producción entrenado en {model_dir}. " + f"Corré primero: python ml_engine/train_kodaquant_v5.py" + ) + model = tkv5.keras.models.load_model(model_path, compile=False) + with open(scalers_path, "rb") as f: + payload = pickle.load(f) + logger.info("Modelo cargado: %s (entrenado con tickers=%s)", model_path, payload["tickers"]) + return model, payload + + +def predict_today_regression(model, payload: dict) -> tuple[dict[str, float], dict]: + """ + target_mode="regression" (equity_specialist) — CERO cambios de + comportamiento respecto al script original; solo ahora también + devuelve `all_market_data` (el MISMO que usó para featurizar, con + force_refresh=True) para que `__main__` deje de re-descargar una + segunda copia potencialmente desalineada antes de llamar a + `size_orders_regression` (ver FIX abajo, `__main__`). + + Devuelve {ticker: r_hat} -- log-return de mañana predicho, en la + unidad real (ya invertido el StandardScaler del target), para cada + ticker. Reusa `download_all`/`engineer_asset` de train_kodaquant_v5.py + tal cual -- garantiza que el feature engineering de HOY sea IDÉNTICO + al que vio el modelo en entrenamiento (ninguna transformación nueva + definida acá). + """ + tickers, lookback = payload["tickers"], payload["lookback"] + feature_cols = ["LOG_RETURN_1D"] + payload["tech_cols"] + payload["macro_tickers"] + + logger.info("Descargando datos frescos (force_refresh=True) para inferencia de hoy...") + all_market_data = tkv5.download_all( + tickers, payload["macro_tickers"], tkv5.PERIOD, cache_tag=f"{payload['regime_name']}_live", + force_refresh=True, + ) + + predictions: dict[str, float] = {} + for ticker in tickers: + df_asset = tkv5.engineer_asset(all_market_data, ticker, payload["macro_tickers"]) + if len(df_asset) < lookback: + logger.warning("%s: historia insuficiente hoy (%d < %d) -- se salta.", ticker, len(df_asset), lookback) + continue + + window = df_asset[feature_cols].values[-lookback:] + window_scaled = payload["feature_scalers"][ticker].transform(window) + X = window_scaled.reshape(1, lookback, len(feature_cols)).astype(np.float32) + asset_id = np.array([[payload["asset_to_id"][ticker]]], dtype=np.int32) + + y_pred_scaled = model.predict([X, asset_id], verbose=0) + r_hat = float(payload["target_scalers"][ticker].inverse_transform(y_pred_scaled[:, 0:1])[0, 0]) + predictions[ticker] = r_hat + + realized_vol = float(df_asset["LOG_RETURN_1D"].tail(VOL_LOOKBACK_DAYS).std()) + logger.info(" %-6s r_hat=%+.4f vol_%dd=%.4f último_close=$%.2f", + ticker, r_hat, VOL_LOOKBACK_DAYS, realized_vol, df_asset["RAW_CLOSE"].iloc[-1]) + + return predictions, all_market_data + + +def predict_today_triple_barrier(model, payload: dict, min_confidence: float) -> tuple[dict[str, dict], dict]: + """ + V22 — target_mode="triple_barrier" (crypto_specialist). UN forward + pass determinista (`model.predict(..., verbose=0)`, MISMO contrato que + `train_kodaquant_v5.evaluate_asset_triple_barrier` — nunca + autoregresivo: la cabeza softmax clasifica el DESENLACE COMPLETO de la + apuesta -- SL/TIMEOUT/TP dentro de `max_holding_days` -- no un paso + aislado que tenga sentido encadenar día a día, ver docstring de + `services/quanti_engine.py::_forecast_asset_triple_barrier` para el + razonamiento completo). + + Devuelve {ticker: {...}} con el detalle real de clasificación + (`predicted_class`, `confidence`, `probabilities`, `actionable`, + `expected_return_pct`, niveles de barrera reales) — `actionable=False` + (clase TIMEOUT, o confianza de clasificación bajo `min_confidence`, + meta-labeling real, ver TB_MIN_SIGNAL_CONFIDENCE) es la señal para que + `size_orders_triple_barrier` NO genere ninguna orden para ese ticker, + nunca una convicción inventada. + """ + tickers, lookback = payload["tickers"], payload["lookback"] + feature_cols = ["LOG_RETURN_1D"] + payload["tech_cols"] + payload["macro_tickers"] + tb_params = payload.get("tb_params") or {} + pt_mult = float(tb_params.get("pt_mult", 2.0)) + sl_mult = float(tb_params.get("sl_mult", 2.0)) + vol_lookback = int(tb_params.get("vol_lookback", 20)) + class_names = list(payload.get("tb_class_names") or ["SL", "TIMEOUT", "TP"]) + + logger.info("Descargando datos frescos (force_refresh=True) para inferencia de hoy...") + all_market_data = tkv5.download_all( + tickers, payload["macro_tickers"], tkv5.PERIOD, cache_tag=f"{payload['regime_name']}_live", + force_refresh=True, + ) + + predictions: dict[str, dict] = {} + for ticker in tickers: + df_asset = tkv5.engineer_asset(all_market_data, ticker, payload["macro_tickers"]) + if len(df_asset) < lookback: + logger.warning("%s: historia insuficiente hoy (%d < %d) -- se salta.", ticker, len(df_asset), lookback) + continue + + window = df_asset[feature_cols].values[-lookback:] + window_scaled = payload["feature_scalers"][ticker].transform(window) + X = window_scaled.reshape(1, lookback, len(feature_cols)).astype(np.float32) + asset_id = np.array([[payload["asset_to_id"][ticker]]], dtype=np.int32) + + probs = model.predict([X, asset_id], verbose=0)[0] # (3,) softmax [SL, TIMEOUT, TP] + if probs.shape != (3,): + logger.warning("%s: salida del modelo con shape inesperado %s -- se salta (sin clase inventada).", + ticker, probs.shape) + continue + + predicted_idx = int(np.argmax(probs)) + predicted_class = class_names[predicted_idx] + confidence = float(probs[predicted_idx]) + actionable = predicted_class != "TIMEOUT" and confidence >= min_confidence + + last_price = float(df_asset["RAW_CLOSE"].iloc[-1]) + # Volatilidad realizada actual -- MISMA fórmula exacta que + # `compute_triple_barrier_labels` (train_kodaquant_v5.py): std de + # LOG_RETURN_1D en una ventana de `vol_lookback` días. + vol_t = float(df_asset["LOG_RETURN_1D"].tail(vol_lookback).std()) + vol_t = vol_t if vol_t > 0 else 1e-6 + barrier_upper = last_price * float(np.exp(pt_mult * vol_t)) + barrier_lower = last_price * float(np.exp(-sl_mult * vol_t)) + + p_sl, p_timeout, p_tp = float(probs[0]), float(probs[1]), float(probs[2]) + # Esperanza del retorno bajo la distribución de clases real del + # modelo sobre los niveles de barrera reales -- MISMA fórmula que + # `quanti_engine._forecast_asset_triple_barrier` (cero cifra + # inventada; TIMEOUT aporta 0.0 -- ver docstring de esa función + # para por qué). Solo informativo/logging acá, `size_orders_ + # triple_barrier` no la usa para el sizing (ver esa función). + expected_return_pct = (p_tp * pt_mult * vol_t - p_sl * sl_mult * vol_t) * 100.0 + + predictions[ticker] = { + "predicted_class": predicted_class, + "confidence": confidence, + "probabilities": {"SL": p_sl, "TIMEOUT": p_timeout, "TP": p_tp}, + "actionable": actionable, + "expected_return_pct": expected_return_pct, + "last_price": last_price, + "barrier_upper": barrier_upper, + "barrier_lower": barrier_lower, + } + logger.info( + " %-8s clase=%-7s confianza=%5.1f%% P(SL/TIMEOUT/TP)=%.2f/%.2f/%.2f " + "E[retorno]=%+.2f%% accionable=%-5s último_close=$%.2f", + ticker, predicted_class, confidence * 100, p_sl, p_timeout, p_tp, + expected_return_pct, str(actionable), last_price, + ) + + return predictions, all_market_data + + +def size_orders_regression(predictions: dict[str, float], all_market_data, payload: dict, + equity: float, vol_target_annual: float) -> list[dict]: + """Mismo esquema de sizing que `pnl_backtest.simulate_portfolio` + (Directiva: cero cambios a la matemática del modelo -- esto es + asignación de capital, una capa aparte) -- tamaño inversamente + proporcional a la volatilidad realizada reciente de CADA activo, + igual-ponderado como base entre los tickers activos hoy.""" + vol_target_daily = vol_target_annual / np.sqrt(252) + n_active = len(predictions) + orders = [] + for ticker, r_hat in predictions.items(): + df_asset = tkv5.engineer_asset(all_market_data, ticker, payload["macro_tickers"]) + realized_vol = float(df_asset["LOG_RETURN_1D"].tail(VOL_LOOKBACK_DAYS).std()) + last_price = float(df_asset["RAW_CLOSE"].iloc[-1]) + if realized_vol <= 0 or np.isnan(realized_vol): + continue + size_mult = min(vol_target_daily / realized_vol, MAX_LEVERAGE) + notional = (equity / n_active) * size_mult + orders.append({ + "symbol": ticker, "side": "buy" if r_hat > 0 else "sell", + "notional": round(notional, 2), "r_hat": r_hat, "last_price": last_price, + }) + return orders + + +def size_orders_triple_barrier(predictions: dict[str, dict], equity: float) -> list[dict]: + """ + V22 -- sizing para target_mode="triple_barrier". MISMO criterio que + `pnl_backtest.simulate_portfolio_triple_barrier`: cada señal + accionable es un TRADE DISCRETO completo (entrada hoy, salida al + tocar barrera o vencer `max_holding_days`), nunca un turnover diario + -- vol-target NO aplica acá (ver aviso en `__main__`, mismo criterio + que `--vol-target-annual` en pnl_backtest.py), igual-ponderado entre + las señales accionables del día. Tickers con `actionable=False` + (TIMEOUT, o confianza bajo `TB_MIN_SIGNAL_CONFIDENCE`) NO generan + ninguna orden -- meta-labeling real, nunca un descarte silencioso ni + una convicción inventada. + """ + actionable = {t: p for t, p in predictions.items() if p["actionable"]} + if not actionable: + return [] + + n_active = len(actionable) + orders = [] + for ticker, pred in actionable.items(): + notional = equity / n_active + orders.append({ + "symbol": ticker, + "side": "buy" if pred["predicted_class"] == "TP" else "sell", + "notional": round(notional, 2), + # r_hat acá es E[log-return] bajo la distribución de clases (no + # un r_hat de un solo paso, ver predict_today_triple_barrier) -- + # se preserva el nombre de campo por compatibilidad con el log + # de __main__, que es agnóstico a target_mode. + "r_hat": pred["expected_return_pct"] / 100.0, + "last_price": pred["last_price"], + "predicted_class": pred["predicted_class"], + "confidence": pred["confidence"], + }) + return orders + + +def get_account_equity() -> float: + resp = requests.get(f"{ALPACA_BASE_URL}/v2/account", headers=_alpaca_headers(), timeout=10) + resp.raise_for_status() + return float(resp.json()["equity"]) + + +def get_current_side(symbol: str) -> str | None: + resp = requests.get(f"{ALPACA_BASE_URL}/v2/positions/{symbol}", headers=_alpaca_headers(), timeout=10) + if resp.status_code == 404: + return None + resp.raise_for_status() + qty = float(resp.json()["qty"]) + return "buy" if qty > 0 else "sell" + + +def submit_order(order: dict) -> None: + """Sizing en `notional` (dólares) para longs -- Alpaca no permite + notional en shorts (requiere `qty` entera), así que para sell se + convierte a acciones enteras al precio actual.""" + current_side = get_current_side(order["symbol"]) + if current_side is not None and current_side != order["side"]: + logger.info(" %s: posición actual (%s) contraria a la señal -- cerrando primero.", + order["symbol"], current_side) + requests.delete(f"{ALPACA_BASE_URL}/v2/positions/{order['symbol']}", + headers=_alpaca_headers(), timeout=10).raise_for_status() + + payload = {"symbol": order["symbol"], "side": order["side"], "type": "market", "time_in_force": "day"} + if order["side"] == "buy": + payload["notional"] = str(order["notional"]) + else: + payload["qty"] = str(max(1, int(order["notional"] / order["last_price"]))) + + resp = requests.post(f"{ALPACA_BASE_URL}/v2/orders", headers=_alpaca_headers(), json=payload, timeout=10) + resp.raise_for_status() + logger.info(" Orden enviada: %s", resp.json().get("id")) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Inferencia diaria + órdenes a Alpaca (paper trading).") + parser.add_argument("--regime", default="equity_specialist", choices=list(tkv5.REGIMES)) + parser.add_argument("--vol-target-annual", type=float, default=0.15, + help="SOLO target_mode='regression' (equity_specialist). Se ignora explícitamente " + "en target_mode='triple_barrier' (crypto_specialist) -- ver size_orders_triple_barrier.") + parser.add_argument("--min-confidence", type=float, default=TB_MIN_SIGNAL_CONFIDENCE, + help="SOLO target_mode='triple_barrier'. Piso de confianza de clasificación " + "(softmax [SL, TIMEOUT, TP]) por debajo del cual la señal se descarta -- " + "meta-labeling, López de Prado cap. 3. Calibrá este número con " + "pnl_backtest.py/walk_forward_eval.py antes de subirlo/bajarlo en vivo " + "(ver MANUAL DE IGNICIÓN).") + parser.add_argument("--live", action="store_true", + help="Sin esto: dry-run, solo imprime las órdenes. Con esto: las envía a Alpaca de verdad " + "(a tu cuenta PAPER -- sin plata real, pero es el freno de seguridad del script).") + args = parser.parse_args() + + model, payload = _load_production_model(args.regime) + target_mode = payload.get("target_mode", "regression") + + # V22 — despacho por target_mode (ver docstring de módulo / + # `services/quanti_engine.py` para el razonamiento completo de por qué + # la cabeza softmax de Triple Barrier necesita un camino de + # predicción/sizing propio, nunca el autoregresivo de regresión). + # + # FIX (drift train/serve en el sizing): la versión anterior descargaba + # `all_market_data` DOS veces -- una acá (force_refresh=False, para + # `size_orders`) y otra dentro de `predict_today` (force_refresh=True, + # para featurizar la predicción) -- pudiendo quedar `size_orders` + # leyendo un caché más viejo que el que realmente vio el modelo. Ahora + # `predict_today_*` devuelve el MISMO `all_market_data` que usó para + # predecir, y `size_orders_*` reusa exactamente ese objeto -- una sola + # descarga, cero desalineación posible entre precio/vol usados para + # predecir y usados para dimensionar la orden. + if target_mode == "triple_barrier": + if args.vol_target_annual != 0.15: # el usuario tocó el flag explícitamente + logger.warning("--vol-target-annual se ignora en target_mode='triple_barrier' " + "(ver size_orders_triple_barrier).") + predictions, all_market_data = predict_today_triple_barrier(model, payload, args.min_confidence) + if not predictions: + logger.error("Sin predicciones -- no se genera ninguna orden.") + raise SystemExit(1) + equity = get_account_equity() if args.live else 100_000.0 + orders = size_orders_triple_barrier(predictions, equity) + else: + predictions, all_market_data = predict_today_regression(model, payload) + if not predictions: + logger.error("Sin predicciones -- no se genera ninguna orden.") + raise SystemExit(1) + equity = get_account_equity() if args.live else 100_000.0 # placeholder solo para el preview en dry-run + orders = size_orders_regression(predictions, all_market_data, payload, equity, args.vol_target_annual) + + logger.info("=" * 78) + logger.info("%s -- regimen=%s (target_mode=%s) -- equity=$%.2f -- %d orden(es)%s", + "ÓRDENES A ENVIAR (--live)" if args.live else "DRY-RUN (ninguna orden real)", + args.regime, target_mode, equity, len(orders), + "" if args.live else " -- agregá --live para enviarlas de verdad") + for o in orders: + logger.info(" %-6s %-4s $%9.2f (r_hat=%+.4f, precio=$%.2f)", + o["symbol"], o["side"].upper(), o["notional"], o["r_hat"], o["last_price"]) + logger.info("=" * 78) + + if args.live: + for o in orders: + submit_order(o) + logger.info("Listo -- revisá tu dashboard de Alpaca (modo Paper) para confirmar las posiciones.") \ No newline at end of file diff --git a/services/market_data.py b/services/market_data.py new file mode 100644 index 0000000000000000000000000000000000000000..15ce80fdea94615f445ca9b9c2dd6da8b3a15a37 --- /dev/null +++ b/services/market_data.py @@ -0,0 +1,921 @@ +# services/market_data.py +""" +Proveedor de datos de mercado — KodaQuant Terminal V5 +======================================================= +Reemplaza por completo `yfinance` + el pool de proxies gratuitos +(bloqueos recurrentes de Yahoo Finance / errores "Proxy CONNECT aborted" +en producción) por: + + 1. **Twelve Data** (https://twelvedata.com) — API REST oficial, HTTPS + puro, sin scraping ni impersonation TLS. Fuente PRIMARIA para el + universo cerrado y verificado de tickers que el motor realmente + opera (`REGIME_TICKERS` ∪ `PLAN_A_TICKER` en quanti_engine.py: + AAPL, MSFT, NVDA, TSLA, GOOGL, AMZN, META, SPY, BTC-USD, ETH-USD). + Plan Basic (gratuito, sin tarjeta): 800 créditos/día, 8 requests/min, + hasta 5.000 puntos de datos por request — verificado contra la + documentación pública de Twelve Data (agosto 2026). Registro: + https://twelvedata.com/pricing → plan "Basic" → Dashboard → API Keys. + + 2. **Stooq** (https://stooq.com, CSV público, sin key) como fallback de + ÚLTIMO RECURSO si Twelve Data no responde (rate limit agotado, caída + puntual, símbolo momentáneamente indisponible). Mismo rol que ya + cumplía en quanti_engine.py antes de esta migración — solo entrega + Close diario, así que bajo este fallback ATR_14/OBV_ROC_20/ADX_14/ + STOCH_K_14 quedan temporalmente degradados (Open/High/Low se + replican desde Close, Volume queda en NaN→0) hasta que Twelve Data + vuelva a responder. Nunca se usa como fuente silenciosa: cada vez + que se activa, queda logueado con `logger.warning`. + +CACHÉ EN DISCO (JSON, TTL configurable vía `KODAQUANT_DATA_CACHE_TTL_SECONDS`, +default 6h) + RATE LIMITER propio (ventana deslizante, 7 req/min — margen +de seguridad bajo el límite real de 8/min del plan Basic). El universo +completo escaneado por `services/prediccion.py` (10 tickers operables + +los macro tickers de `scalers["macro_tickers"]`, ~14-15 símbolos en +total) jamás se acerca al tope diario de 800 créditos incluso bajo +tráfico real, porque las barras diarias no cambian más de una vez por +sesión de mercado — no hay motivo para re-descargar 2 años de historia +en cada request de un usuario. + +--- AUDITORÍA DE PARIDAD TRAIN/SERVE (contra train_kodaquant_v5.py) --- +Reconciliado línea a línea contra el script de entrenamiento real. Hallazgos: + + • UNIVERSO DE TICKERS: `REGIME_TICKERS` en train_kodaquant_v5.py + (equity_specialist: AAPL/MSFT/NVDA/TSLA/GOOGL/AMZN/META/SPY; + crypto_specialist: BTC-USD/ETH-USD) coincide EXACTO con el universo + que ya cubren `_TICKER_MAP_TD`/`_STOOQ_SYMBOL_MAP` — sin cambios. + + • MACRO_TICKERS: `MACRO_TICKERS = ["^GSPC", "^TNX", "^VIX", "GC=F", + "DX-Y.NYB"]` (train_kodaquant_v5.py, línea 149) — exactamente los 5 + tickers que ya cubría `MACRO_SYMBOL_MAP` (abajo). Sin faltantes, sin + sobrantes. + + • TODOS los macro tickers entran al tensor ÚNICAMENTE como LOG-RETURN + diario (`engineer_asset()`: `df[macro_close_col] = np.log(macro_price + / macro_price.shift(1))`, aplicado ANTES del feature_scaler, idéntico + en `_fetch_feature_window` del lado de inferencia). Consecuencia + matemática directa: `log(k·x_t / k·x_{t-1}) = log(x_t / x_{t-1})` — + un factor de escala CONSTANTE y multiplicativo en cualquier macro + ticker (ej. un proveedor que reporte el mismo activo ×10 o ×100 + frente a otro) es matemáticamente INVISIBLE para el modelo. Esto no + exime de verificar la escala (una serie con escala INCONSISTENTE en + el tiempo, o con timestamps desalineados, sí correspería fuga/ruido + real) — pero sí acota el riesgo real de un desajuste de escala + puramente constante a cero impacto en el tensor de entrada. + + • ^TNX — HALLAZGO QUE CORRIGE UNA ADVERTENCIA PREVIA DE ESTE MÓDULO: + una versión anterior de este archivo asumía que yfinance publicaba + ^TNX bajo la vieja convención CBOE "rendimiento ×10" (ej. 42.0 = + 4.20%). Verificado en vivo contra la cotización real de Yahoo Finance + para ^TNX (agosto 2026): el valor publicado es 4.5580 — es decir, + yfinance/Yahoo publican ^TNX en PORCENTAJE DIRECTO (4.558 = 4.558%), + NO en la vieja convención ×10. Stooq (`10yusy.b`, "U.S. 10-Year + Government Bond Yield") publica la misma convención de porcentaje + directo. CONCLUSIÓN: no existe el desajuste de escala ×10 que se + sospechaba — la advertencia anterior era incorrecta y fue retirada. + No se aplica ninguna transformación compensatoria (no hay nada que + compensar), y por el punto anterior (macro = solo log-return) aunque + lo hubiera habido, habría sido matemáticamente inerte para el tensor. + + • auto_adjust=True — confirmado en train_kodaquant_v5.py línea 359 + (`yf.download(symbols, period=period, auto_adjust=True, ...)`), + aplicado de forma UNIFORME a tickers Y macro. Para los 5 macro + tickers (todos índices/futuros, sin dividendos ni splits) esto es un + no-op exacto — auto_adjust=True/False no cambia un solo valor. Para + los tickers de equity (AAPL, MSFT, ...) SÍ es relevante: ver el + caveat ya documentado en quanti_engine.py (`_fetch_feature_window`, + bloque "FIX PRICING") sobre la diferencia de metodología de ajuste + por dividendos entre Yahoo y Twelve Data — no es un bug de este + módulo, es una diferencia real entre proveedores que ninguna + transformación en `market_data.py` puede eliminar sin una fuente de + dividendos propia. + + • GC=F vs XAU/USD — riesgo real, NO corregible con un factor fijo. + GC=F es el futuro de oro COMEX del contrato más próximo; Twelve + Data's XAU/USD es el spot. Verificado en vivo (agosto 2026): ambos + cotizan en el mismo orden de magnitud (spot ~$4.320-4.410 vs futuro + ~$4.408-4.430) pero con una base (contango/backwardation) variable + en el tiempo — no una proporción constante, así que NO se puede + "corregir" con un multiplicador fijo sin inventar un número. Se deja + como proxy de mejor esfuerzo, documentado explícitamente en + `MACRO_SYMBOL_MAP` — igual que arriba, al entrar como log-return el + impacto se limita a la diferencia de VOLATILIDAD diaria entre spot y + futuro (correlacionadas >0.98 en la práctica), no a un sesgo de nivel. + + • ^GSPC↔SPX, ^VIX↔VIX, DX-Y.NYB↔DXY — mismo índice subyacente en + ambos proveedores (S&P 500 cash, CBOE VIX, ICE US Dollar Index + respectivamente), sin dualidad de convención conocida. `DX-Y.NYB` + verificado en vivo (~99.94) contra el nivel públicamente reportado + de DXY (~99-101) — mismo orden de magnitud, consistente. + +--- ADVERTENCIA VIGENTE — LEER ANTES DE DESPLEGAR A PRODUCCIÓN --- +Esta auditoría se hizo contra el CÓDIGO de entrenamiento (train_kodaquant_v5.py) +y contra cotizaciones en vivo de terceros (Yahoo, Investing.com, Barchart, +TradingView) — no contra tu `scalers_dict.pkl` real ni contra una llamada +en vivo a la API de Twelve Data (este entorno no tiene salida de red hacia +api.twelvedata.com/stooq.com). Si `MACRO_TICKERS` en tu copia real de +train_kodaquant_v5.py difiere de la verificada acá, o si tu plan de Twelve +Data no cubre alguno de estos símbolos, corregí `MACRO_SYMBOL_MAP` antes +de servir tráfico real — `resolve_macro_symbol()` sigue fallando ruidoso +ante cualquier ticker fuera del diccionario, nunca adivina un símbolo. + +--- ROOT CAUSE REAL DE "degradación total del radar" (FIX 2026-08-15 — RONDA 1) --- +El fix del 2026-08-15 de arriba (^GSPC/^VIX/DX-Y.NYB/^TNX directo a Stooq) +resolvía el 404 de Twelve Data pero destapó el bug real, más grave: +`services/prediccion._scan_universe` despacha los 10 tickers de +REGIME_TICKERS en PARALELO real (`asyncio.gather` sobre 10 +`run_in_executor`, ver prediccion.py) y CADA uno de esos 10 hilos llama a +`fetch_feature_ohlcv(ticker, macro_tickers, ...)`, que a su vez pide los +MISMOS 5 macro tickers compartidos por todo el universo. Sin coordinación +entre hilos, eso dispara hasta 10 requests SIMULTÁNEAS por cada uno de los +4 macro tickers que van directo a Stooq (~40 requests en una ráfaga de +milisegundos) contra un endpoint CSV público, anónimo, sin key y sin rate +limit documentado del lado servidor — el patrón clásico que Stooq +responde bloqueando/sirviendo una página de error en vez de CSV real +(`_stooq_daily_close` ya detectaba ese caso devolviendo `None`, pero +`_fetch_symbol_ohlcv` no tenía ningún colchón: en cuanto Stooq fallaba +para el símbolo, lanzaba `RuntimeError` de inmediato). Como ^GSPC (y el +resto de los macro tickers) es un input COMPARTIDO por los 10 modelos, un +solo bloqueo de Stooq tumba el forecast de LOS 10 tickers a la vez — +exactamente "degradación total del radar", no un fallo aislado. + +Tres capas de fix, todas en este módulo (`_fetch_symbol_ohlcv` + +`_stooq_daily_close`), cero cambios de contrato hacia quanti_engine.py/ +prediccion.py: + 1. SINGLE-FLIGHT por símbolo (`_lock_for` + `threading.Lock`): con 10 + hilos pidiendo '^GSPC' a la vez, solo el PRIMERO golpea la red: los + otros 9 esperan el lock y reusan lo que ese hilo dejó en caché. + Colapsa la ráfaga de ~10 requests por macro ticker a 1 sola. + 2. THROTTLE + REINTENTOS propios para Stooq (`_STOOQ_CONCURRENCY` + + `_stooq_throttle` + backoff en `_stooq_daily_close`) — antes Stooq + no tenía NINGÚN control del lado cliente (a diferencia de Twelve + Data, que sí tenía semáforo + rate limiter); un solo intento fallido + (glitch transitorio, no necesariamente bloqueo) mataba el símbolo + entero sin reintentar. + 3. CACHÉ STALE COMO ÚLTIMO RECURSO (`_cache_get(..., ignore_ttl=True)` + en `_fetch_symbol_ohlcv`): si Twelve Data Y Stooq fallan los DOS en + vivo, antes de lanzar `RuntimeError` (y tumbar el universo completo) + se busca la última descarga exitosa en disco sin importar el TTL de + 6h — para un macro factor que entra al tensor como log-return diario, + servir el dato de ayer en vez de "nada" es estrictamente mejor y + evita la cascada total. Solo se lanza `RuntimeError` si JAMÁS hubo + una descarga exitosa para ese símbolo (arranque en frío + ambos + proveedores caídos a la vez, caso genuinamente irrecuperable). + +--- RONDA 2 (FIX 2026-08-15, mismo día — logs de producción posteriores) --- +Los logs post-RONDA 1 muestran algo distinto de lo que la RONDA 1 asumía: +el single-flight lock SÍ funcionó (ya no hay ráfaga — los intentos contra +Stooq para '^spx' quedaron serializados, uno cada ~10s, uno por ticker del +universo) y AÚN ASÍ los 10 fallan, siempre con el mismo error ("Stooq +devolvió una respuesta sin columnas Close/Date"), incluso con reintentos y +backoff. Un fallo que persiste 100% de las veces YA SERIALIZADO, request +tras request, con el MISMO símbolo, deja de ser "ráfaga mal comportada" y +pasa a ser evidencia de un bloqueo ESTRUCTURAL: Stooq es conocido por +bloquear (servir HTML/CSV vacío con 200 OK en vez de datos reales) tráfico +proveniente de rangos de IP de datacenter/cloud -- Hugging Face Spaces +corre sobre infraestructura cloud (AWS/GCP/Azure), exactamente el patrón +que ese bloqueo apunta. Los reintentos de la RONDA 1 no podían arreglar +esto porque no es un glitch transitorio -- es un rechazo consistente del +lado del proveedor para ESTA clase de tráfico, independientemente de +cuántas veces se reintente. + +Auditoría de blast radius: `MACRO_TICKERS` tiene 5 entradas +(^GSPC/^TNX/^VIX/GC=F/DX-Y.NYB) pero `fetch_feature_ohlcv` los recorre en +un `for` secuencial que ABORTA en el primer `RuntimeError` -- como ^GSPC +es el PRIMERO de la lista y el único que alcanzamos a ver fallar en los +logs, los otros 3 símbolos ruteados directo a Stooq (^VIX, ^TNX, +DX-Y.NYB, ver MACRO_SYMBOL_MAP de la RONDA 1) NUNCA llegaron a intentarse +-- pero comparten el MISMO endpoint (`stooq.com/q/d/l/`) con el MISMO +patrón de bloqueo, así que hay que asumir que fallarían igual si ^GSPC no +abortara primero. Cuatro de los cinco macro tickers dependían de Stooq +como única fuente real (`twelvedata: None`) -- ese es el problema de raíz, +no la concurrencia (ya resuelta en RONDA 1). + +FIX DE RAÍZ -- dejar de depender de Stooq como fuente PRIMARIA para los +macro tickers, reemplazándolo por proveedores que SÍ están probados como +100% confiables en este mismo entorno (Twelve Data ya sirve AAPL/MSFT/ +TSLA/SPY/BTC-USD/... sin un solo fallo en los logs) o que son APIs reales +diseñadas para tráfico programático (no scraping de un endpoint CSV +público), en vez de reintentar contra un proveedor que rechaza el tráfico +de forma sistemática. Los 5 macro tickers entran al tensor SOLO como +log-return (ver auditoría más arriba) -- eso da libertad real para +sustituir cada índice/futuro por un ETF/activo LÍQUIDO Y REAL que trackea +la MISMA magnitud subyacente, con la MISMA garantía matemática ya +establecida arriba (un factor de escala/tracking constante es invisible +para el tensor; solo importa que el MOVIMIENTO diario sea el mismo +activo real, cero simulación): + + • ^GSPC (S&P 500 cash) -> **SPY** vía Twelve Data. SPY *es* el ETF que + trackea el S&P 500 -- no es un proxy aproximado, es prácticamente el + mismo activo con tracking error de puntos básicos. Ya está en + REGIME_TICKERS y se descarga con éxito en cada scan (ver logs) -- cero + riesgo de proveedor nuevo, cero costo extra relevante de créditos. + + • ^VIX (CBOE Volatility Index) -> **VIXY** (ProShares VIX Short-Term + Futures ETF) vía Twelve Data. Proxy, no el índice exacto (roll + yield/contango del futuro de corto plazo introduce deriva de largo + plazo que el índice cash no tiene) -- mismo tipo de caveat ya aceptado + para GC=F/XAU-USD arriba, documentado igual acá. El día a día + (dirección e intensidad del shock de volatilidad, que es lo que + SENTIMENT_SCORE/el tensor realmente necesitan) sigue correlacionado. + + • DX-Y.NYB (ICE US Dollar Index) -> **UUP** (Invesco DB US Dollar Index + Bullish Fund) vía Twelve Data. UUP está diseñado explícitamente para + trackear la MISMA canasta de divisas que el USDX -- proxy de alta + fidelidad, no una aproximación libre. + + • GC=F (oro) -> SIN CAMBIO, ya vía Twelve Data (XAU/USD) desde la + migración original -- nunca dependió de Stooq como primaria, por eso + nunca apareció en los logs de fallo. + + • ^TNX (rendimiento UST 10Y) -> este es el ÚNICO que NO se puede + resolver con un ETF de precio: un rendimiento (yield) y el precio de + un ETF de bonos se mueven en direcciones opuestas y con una escala + que depende de la duration del instrumento (NO es un factor constante + -- a diferencia de todos los casos de arriba, acá "precio de ETF" y + "yield" NO son la misma magnitud, son magnitudes relacionadas por una + transformación que varía en el tiempo). Inventar un signo/escala acá + violaría directamente "cero cifras inventadas". En vez de forzar un + proxy matemáticamente débil, se agrega **FRED** (Federal Reserve + Economic Data, `api.stlouisfed.org`, serie oficial `DGS10` = "10-Year + Treasury Constant Maturity Rate", el rendimiento UST10Y real y + oficial) como fuente PRIMARIA nueva -- 100% gratis (requiere API key + gratuita, sin tarjeta, alta de un minuto en + https://fred.stlouisfed.org/docs/api/api_key.html), y es una API REST + real diseñada para tráfico programático (no un endpoint de scraping + con protección anti-bot) -- no comparte el problema de Stooq. Stooq + (`10yusy.b`) queda como fallback secundario si `FRED_API_KEY` no está + configurada o la request a FRED falla puntualmente. + +Con esto, Stooq deja de ser la única fuente real de 4 de los 5 macro +tickers y pasa a ser lo que su nombre siempre debió indicar: un fallback +de ÚLTIMO recurso, nunca la primaria de nada crítico. +""" + +import io +import logging +import os +import sys +import threading +import time +from pathlib import Path +from typing import Optional + +import numpy as np +import pandas as pd +import requests + +logger = logging.getLogger("kodaquant.market_data") + +# --- RESOLUCIÓN ABSOLUTA DE IMPORTS (Directiva 2 — fin al Import Hell) ---- +# Este archivo vive en `services/`, hermano de `ml_engine/` (donde vive +# `kodaquant_core.py`, SINGLE SOURCE OF TRUTH -- Directiva 1). Sube desde +# este archivo hasta encontrar la raíz del proyecto -- el primer ancestro +# que contiene TANTO `ml_engine/` como `services/` como subdirectorios -- y +# la inserta en `sys.path[0]`. A partir de ahí, `ml_engine` es un paquete +# válido sin importar el cwd desde el que se invoque el proceso que importa +# este módulo (uvicorn, `services.quanti_engine`, un test, etc.). +def _bootstrap_project_root() -> Path: + here = Path(__file__).resolve() + for ancestor in (here.parent, *here.parents): + if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir(): + return ancestor + # Fallback determinista: este archivo vive en services/, por lo que su + # abuelo es la raíz del proyecto por construcción, incluso si + # `ml_engine/` todavía no existe en el entorno actual (ej. checkout + # parcial/CI). + return here.parent.parent + + +_PROJECT_ROOT = _bootstrap_project_root() +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +# Migración de Directiva 4: este módulo ya NO define su propia lógica de +# caché en disco ni su propio cliente FRED -- ambos vivían acá duplicados +# (con semántica ligeramente distinta) respecto de lo que ya usaba +# `train_kodaquant_v5.py`. Delegan por completo en el núcleo compartido +# `ml_engine/kodaquant_core.py`: +# - `CacheManager` -> reemplaza `_cache_get`/`_cache_set`/ +# `_cache_path`/`_CACHE_LOCK` (mismo formato JSON on-disk, incluye +# soporte nativo para `ignore_ttl=True` y `_stale_age_hours`). +# - `FredClient` -> reemplaza `_fred_series_daily` (mismo +# endpoint/retry/backoff 1:1). +# - `normalize_daily_index` -> reemplaza `_normalize_daily_index`. +# - `align_macro_to_calendar` -> reemplaza `_macro_close_ffilled_to_daily_calendar` +# (idéntica lógica: upsample a calendario diario corrido + ffill, sin +# bfill, ANTES de reindexar contra el calendario del activo objetivo). +# Toda la lógica NO relacionada con ingesta macro/caché (Twelve Data, Stooq, +# rate limiting, single-flight, mapeo de símbolos) permanece intacta abajo. +from ml_engine.kodaquant_core import ( # noqa: E402 + CacheManager, FredClient, align_macro_to_calendar, normalize_daily_index, +) + +# --------------------------------------------------------------------------- +# Config / credenciales +# --------------------------------------------------------------------------- +TWELVE_DATA_API_KEY = os.environ.get("TWELVE_DATA_API_KEY", "").strip() +TWELVE_DATA_BASE_URL = "https://api.twelvedata.com" +TWELVE_DATA_TIMEOUT_S = 20.0 + +# FRED (Federal Reserve Economic Data, api.stlouisfed.org) -- fuente +# PRIMARIA nueva (RONDA 2) para ^TNX (serie oficial DGS10, rendimiento +# UST10Y real). 100% gratis, sin tarjeta -- alta de la key en +# https://fred.stlouisfed.org/docs/api/api_key.html. API REST real +# diseñada para tráfico programático (no un endpoint de scraping con +# protección anti-bot como Stooq) -- ver ROOT CAUSE RONDA 2 en el +# docstring del módulo. Opcional: si no está configurada, ^TNX cae +# directo al fallback Stooq (mismo comportamiento que antes de RONDA 2). +# Directiva 4: el cliente HTTP/retry/backoff vive ahora en +# `kodaquant_core.FredClient` -- `FredClient` ya loguea su propio warning +# si `api_key` viene vacía, así que no se duplica acá. +FRED_API_KEY = os.environ.get("FRED_API_KEY", "").strip() +_fred_client = FredClient(api_key=FRED_API_KEY) + +# ~2 años de sesiones diarias (mismo horizonte que el "period=2y" que usaba +# yfinance) — suficiente burn-in para que RSI_14/EMA_20/MACD/MACD_SIGNAL +# (todos IIR recursivos, `ewm(adjust=False)`) converjan al mismo estado que +# vio el notebook de entrenamiento. +16 sesiones de margen sobre las ~504 +# de 2 años calendario, para no quedar corto en años con más feriados. +DEFAULT_HISTORY_SESSIONS = 520 + +if not TWELVE_DATA_API_KEY: + logger.warning( + "TWELVE_DATA_API_KEY no configurada -- TODA descarga de mercado va " + "a caer directo al fallback Stooq (cobertura reducida: solo Close " + "diario real; ATR_14/OBV_ROC_20/ADX_14/STOCH_K_14 quedarán " + "degradados hasta que se configure la key). Registrate gratis en " + "https://twelvedata.com/pricing (plan Basic) y seteá la variable " + "de entorno / Secret 'TWELVE_DATA_API_KEY'." + ) + +# (Warning de FRED_API_KEY ausente: ahora lo emite `FredClient.__init__` +# en `kodaquant_core.py`, ver instanciación de `_fred_client` arriba -- +# se evita duplicar el mismo log dos veces.) + +# --------------------------------------------------------------------------- +# Rate limiter -- ventana deslizante de 60s, 7 requests (margen de +# seguridad bajo el límite real de 8/min del plan Basic gratuito). +# --------------------------------------------------------------------------- +_RATE_LOCK = threading.Lock() +_RATE_WINDOW_S = 60.0 +_RATE_MAX_CALLS = 7 +_rate_call_log: list[float] = [] + +# Concurrencia real hacia Twelve Data -- evita disparar 10-15 requests +# simultáneas cuando el radar escanea todo REGIME_TICKERS en paralelo +# (mismo rol que _YF_CONCURRENCY cumplía bajo yfinance). +_TD_CONCURRENCY = threading.BoundedSemaphore(4) + +# FIX 2026-08-15 -- Stooq (fallback CSV público, sin key) NO tenía ningún +# control de concurrencia propio, a diferencia de Twelve Data arriba. Bajo +# un scan paralelo de las 10 tickers de REGIME_TICKERS, eso permitía +# ráfagas de hasta ~40 requests simultáneas contra un endpoint anónimo sin +# rate limit documentado -- el patrón real que dispara los bloqueos/CSV +# vacíos observados en producción (ver ROOT CAUSE en el docstring del +# módulo). El single-flight lock (`_lock_for`, más abajo) ya colapsa la +# mayor parte de esa ráfaga, pero este semáforo + throttle es la segunda +# capa de defensa para cualquier request que sí llegue a golpear la red. +_STOOQ_CONCURRENCY = threading.BoundedSemaphore(2) +_STOOQ_RATE_LOCK = threading.Lock() +_STOOQ_RATE_WINDOW_S = 10.0 +_STOOQ_RATE_MAX_CALLS = 3 +_stooq_call_log: list[float] = [] + + +def _stooq_throttle() -> None: + with _STOOQ_RATE_LOCK: + now = time.monotonic() + while _stooq_call_log and now - _stooq_call_log[0] > _STOOQ_RATE_WINDOW_S: + _stooq_call_log.pop(0) + if len(_stooq_call_log) >= _STOOQ_RATE_MAX_CALLS: + wait_s = _STOOQ_RATE_WINDOW_S - (now - _stooq_call_log[0]) + 0.05 + if wait_s > 0: + logger.debug("Rate limiter Stooq: esperando %.2fs.", wait_s) + time.sleep(wait_s) + _stooq_call_log.append(time.monotonic()) + + +# --------------------------------------------------------------------------- +# Single-flight por símbolo -- ver ROOT CAUSE en el docstring del módulo. +# Un `threading.Lock` dedicado por `internal_key` (creado on-demand, nunca +# liberado -- son ~15 símbolos como mucho, memoria irrelevante) asegura que +# de los N hilos que puedan pedir el MISMO ticker en paralelo (ej. '^GSPC' +# pedido por los 10 forecasts del universo a la vez), solo UNO llega a +# tocar la red; el resto espera el lock y reusa lo que ese hilo dejó en +# caché -- sin este mecanismo, cada hilo repetía la descarga completa. +# --------------------------------------------------------------------------- +_SYMBOL_LOCKS: dict[str, threading.Lock] = {} +_SYMBOL_LOCKS_META = threading.Lock() + + +def _lock_for(internal_key: str) -> threading.Lock: + with _SYMBOL_LOCKS_META: + lock = _SYMBOL_LOCKS.get(internal_key) + if lock is None: + lock = threading.Lock() + _SYMBOL_LOCKS[internal_key] = lock + return lock + + +def _throttle() -> None: + with _RATE_LOCK: + now = time.monotonic() + while _rate_call_log and now - _rate_call_log[0] > _RATE_WINDOW_S: + _rate_call_log.pop(0) + if len(_rate_call_log) >= _RATE_MAX_CALLS: + wait_s = _RATE_WINDOW_S - (now - _rate_call_log[0]) + 0.05 + if wait_s > 0: + logger.debug("Rate limiter Twelve Data: esperando %.2fs.", wait_s) + time.sleep(wait_s) + _rate_call_log.append(time.monotonic()) + + +# --------------------------------------------------------------------------- +# Caché en disco -- clave = ticker INTERNO (AAPL, BTC-USD, ^VIX, ...), +# nunca el símbolo externo, así todo el motor comparte una única entrada de +# caché por activo sin importar qué proveedor lo sirvió. +# +# Directiva 4: delega por completo en `kodaquant_core.CacheManager` +# (`get_json`/`set_json`, modo JSON de TTL absoluto -- mismo modo/formato +# on-disk que ya usaba este módulo, `{"_kind": ..., "data": ..., "_cached_at": +# ...}`, con soporte NATIVO para `ignore_ttl=True`/`_stale_age_hours`, ver +# `_fetch_symbol_ohlcv` más abajo). Subcarpeta `v2/` explícita: separa el +# formato unificado de `CacheManager` de cualquier entrada preexistente en +# `_CACHE_DIR` escrita por la caché JSON ad-hoc anterior (formato sin +# `"_kind"`) -- evita que una entrada vieja en disco se lea como dato crudo +# en vez de DataFrame durante el primer deploy post-migración. Se puede +# purgar `_CACHE_DIR` original manualmente una vez migrado; no es necesario +# para operar. +_CACHE_DIR = Path(os.environ.get("KODAQUANT_DATA_CACHE_DIR", "/tmp/kodaquant_market_cache")) +_CACHE_TTL_S = int(os.environ.get("KODAQUANT_DATA_CACHE_TTL_SECONDS", str(6 * 3600))) +_market_cache = CacheManager(_CACHE_DIR / "v2", default_ttl_seconds=_CACHE_TTL_S) + + +# --------------------------------------------------------------------------- +# Mapeo de símbolos +# --------------------------------------------------------------------------- + +# Universo cerrado y VERIFICADO (equities + crypto) -- idéntico a +# REGIME_TICKERS/PLAN_A_TICKER en quanti_engine.py. Formato Twelve Data +# para cripto es "BASE/QUOTE" (ver docs.twelvedata.com); equities usan el +# mismo ticker que Yahoo/NYSE/NASDAQ 1:1, sin traducción. +_TICKER_MAP_TD: dict[str, str] = { + "BTC-USD": "BTC/USD", + "ETH-USD": "ETH/USD", +} + +# Fallback Stooq para el mismo universo -- reutiliza el mapeo que ya vivía +# en quanti_engine.py (_STOOQ_SYMBOL_MAP) antes de esta migración. +_STOOQ_SYMBOL_MAP: dict[str, str] = { + "AAPL": "aapl.us", "MSFT": "msft.us", "NVDA": "nvda.us", "TSLA": "tsla.us", + "GOOGL": "googl.us", "AMZN": "amzn.us", "META": "meta.us", "SPY": "spy.us", + "BTC-USD": "btc.v", "ETH-USD": "eth.v", +} + +# Macro tickers -- auditado contra MACRO_TICKERS de train_kodaquant_v5.py +# (línea 149: ^GSPC, ^TNX, ^VIX, GC=F, DX-Y.NYB) -- ver la sección +# "AUDITORÍA DE PARIDAD TRAIN/SERVE" en el docstring del módulo para el +# detalle matemático completo de cada fila. +# +# RONDA 2 (FIX 2026-08-15) -- ver "ROOT CAUSE RONDA 2" en el docstring del +# módulo: Stooq demostró en producción (logs post-RONDA 1, requests YA +# serializadas por el single-flight lock, con reintentos) un rechazo +# CONSISTENTE, no transitorio, para tráfico desde este hosting -- dejó de +# ser candidato a fuente PRIMARIA de nada crítico. `twelvedata`/`fred` +# ahora cubren 4 de los 5 macro tickers como fuente real primaria; `stooq` +# queda como fallback de último recurso en los 5 (nunca se elimina del +# todo -- sigue siendo mejor que nada si Twelve Data/FRED tienen un +# hiccup puntual). Orden de intento real, ver `_fetch_symbol_ohlcv`: +# FRED (si hay `fred` Y `FRED_API_KEY` configurada) -> Twelve Data (si hay +# `twelvedata`) -> Stooq (si hay `stooq`) -> caché stale -> falla ruidosa. +MACRO_SYMBOL_MAP: dict[str, dict[str, Optional[str]]] = { + "^GSPC": {"twelvedata": "SPY", "stooq": "^spx", "fred": None}, + # RONDA 2: SPY *es* el ETF que trackea el S&P 500 (no un proxy + # aproximado) -- ya se descarga con éxito en cada scan del universo + # (está en REGIME_TICKERS), cero riesgo de proveedor nuevo. Stooq + # (^spx) queda como fallback si Twelve Data tuviera un hiccup puntual. + + "^VIX": {"twelvedata": "VIXY", "stooq": "^vix", "fred": None}, + # RONDA 2: VIXY (ProShares VIX Short-Term Futures ETF) vía Twelve + # Data -- proxy de futuros de corto plazo, no el índice cash exacto + # (roll yield/contango introduce deriva de largo plazo que el índice + # no tiene), mismo tipo de caveat ya aceptado para GC=F/XAU-USD abajo. + # El shock día a día (lo que SENTIMENT_SCORE/el tensor necesitan) + # sigue correlacionado. Cubierto por el plan Basic gratuito de TD + # como cualquier ETF/equity normal (mismo trato que SPY/AAPL). + + "GC=F": {"twelvedata": "XAU/USD", "stooq": "xauusd", "fred": None}, + # SIN CAMBIO en RONDA 2 -- ya vía Twelve Data desde la migración + # original, nunca dependió de Stooq como primaria (por eso nunca + # apareció en los logs de fallo). Oro SPOT -- GC=F en entrenamiento es + # el FUTURO COMEX del contrato próximo; verificado en vivo (ago-2026): + # mismo orden de magnitud, base variable en el tiempo (no una + # proporción fija) -- proxy de mejor esfuerzo, NO corregible con un + # multiplicador constante. Ver docstring del módulo. + + "DX-Y.NYB": {"twelvedata": "UUP", "stooq": "usdx.f", "fred": None}, + # RONDA 2: UUP (Invesco DB US Dollar Index Bullish Fund) vía Twelve + # Data -- diseñado explícitamente para trackear la MISMA canasta de + # divisas que el USDX, proxy de alta fidelidad (no una aproximación + # libre). Stooq (usdx.f) queda como fallback de último recurso. + + "^TNX": {"twelvedata": None, "stooq": "10yusy.b", "fred": "DGS10"}, + # RONDA 2: ÚNICO macro ticker donde NO hay un ETF de precio que sirva + # de proxy sin inventar un signo/escala -- un rendimiento (yield) y el + # precio de un ETF de bonos se mueven en direcciones opuestas con una + # escala que depende de la duration (no un factor CONSTANTE, a + # diferencia de todos los demás casos de esta tabla) -- forzar esa + # conversión violaría "cero cifras inventadas". En vez de eso: FRED + # (`api.stlouisfed.org`, serie oficial `DGS10` = rendimiento UST10Y + # real) como fuente PRIMARIA -- 100% gratis, API REST real diseñada + # para tráfico programático, no comparte el problema de bloqueo de + # Stooq. Requiere `FRED_API_KEY` (gratis, ver docstring del módulo); + # sin ella, cae directo a Stooq (mismo comportamiento que antes de + # RONDA 2, ya con las mejoras de resiliencia de RONDA 1 -- single- + # flight, reintentos, caché stale). Rendimiento UST 10Y, PORCENTAJE + # DIRECTO (4.558 = 4.558%) tanto en Stooq/yfinance/Yahoo como en FRED + # -- verificado en vivo, ago-2026, sin transformación de escala + # adicional necesaria entre proveedores. +} + + +def _resolve_td_symbol(internal_ticker: str) -> Optional[str]: + return _TICKER_MAP_TD.get(internal_ticker, internal_ticker) + + +def _resolve_stooq_symbol(internal_ticker: str) -> Optional[str]: + return _STOOQ_SYMBOL_MAP.get(internal_ticker.strip().upper()) + + +def resolve_macro_symbol(macro_ticker: str) -> dict[str, Optional[str]]: + """ + Fail-loud por diseño: un macro ticker sin entrada acá NUNCA se sirve + con un símbolo adivinado. Agregalo a MACRO_SYMBOL_MAP (arriba) con el + símbolo Twelve Data y/o Stooq correcto antes de desplegar. + """ + entry = MACRO_SYMBOL_MAP.get(macro_ticker) + if entry is None: + raise ValueError( + f"'{macro_ticker}' no tiene mapeo registrado en MACRO_SYMBOL_MAP " + "(services/market_data.py). Completá esa entrada (símbolo " + "Twelve Data y/o Stooq real) antes de servir tráfico -- nunca " + "se adivina un símbolo macro (misma regla 'cero cifras " + "inventadas' del resto del motor)." + ) + return entry + + +# --------------------------------------------------------------------------- +# Twelve Data -- cliente HTTP crudo +# --------------------------------------------------------------------------- + +def _td_time_series(td_symbol: str, outputsize: int, attempts: int = 3) -> Optional[pd.DataFrame]: + """ + Una llamada a `/time_series` (1 crédito) para UN símbolo, `interval=1day`. + Reintenta ante 429/5xx/timeout con backoff simple; nunca reintenta ante + un símbolo inválido (400 "symbol not found") -- eso es un error de + mapeo, no algo que un backoff pueda arreglar. + """ + if not TWELVE_DATA_API_KEY: + return None + + params = { + "symbol": td_symbol, + "interval": "1day", + "outputsize": str(outputsize), + "order": "ASC", + "timezone": "UTC", + "apikey": TWELVE_DATA_API_KEY, + } + + last_exc: Optional[Exception] = None + for attempt in range(attempts): + with _TD_CONCURRENCY: + _throttle() + try: + resp = requests.get( + f"{TWELVE_DATA_BASE_URL}/time_series", params=params, timeout=TWELVE_DATA_TIMEOUT_S + ) + if resp.status_code == 429: + raise RuntimeError(f"Twelve Data rate limit (429): {resp.text[:200]}") + resp.raise_for_status() + data = resp.json() + if isinstance(data, dict) and data.get("status") == "error": + code = data.get("code") + message = data.get("message", "") + if code == 400: # símbolo inválido / no encontrado -- no reintentar + logger.warning("Twelve Data: símbolo inválido '%s' (%s).", td_symbol, message) + return None + raise RuntimeError(f"Twelve Data error {code}: {message}") + return _td_payload_to_df(data) + except Exception as exc: # noqa: BLE001 -- reintentamos cualquier fallo transitorio + last_exc = exc + if attempt < attempts - 1: + time.sleep(1.5 * (attempt + 1)) + + logger.warning("Twelve Data agotó reintentos para '%s': %r", td_symbol, last_exc) + return None + + +def _td_payload_to_df(payload: dict) -> Optional[pd.DataFrame]: + values = payload.get("values") if isinstance(payload, dict) else None + if not values: + return None + df = pd.DataFrame(values) + if "datetime" not in df.columns: + return None + df["datetime"] = pd.to_datetime(df["datetime"]) + df = df.set_index("datetime").sort_index() + for col in ("open", "high", "low", "close", "volume"): + if col in df.columns: + df[col] = pd.to_numeric(df[col], errors="coerce") + else: + df[col] = np.nan + df = df[["open", "high", "low", "close", "volume"]].dropna(subset=["close"]) + return df if not df.empty else None + + +# --------------------------------------------------------------------------- +# FRED (Federal Reserve Economic Data) -- fuente PRIMARIA nueva (RONDA 2) +# para ^TNX (serie DGS10). Directiva 4: cliente HTTP/retry/backoff migrado +# 1:1 a `kodaquant_core.FredClient` (`_fred_client`, instanciado arriba) -- +# ya no vive inline en este módulo. `FredClient.daily_series(series_id, +# tail_days)` reemplaza directamente a la vieja `_fred_series_daily`. +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# Stooq -- fallback CSV sin key (mismo endpoint que ya usaba quanti_engine.py) +# --------------------------------------------------------------------------- + +def _stooq_daily_close(stooq_symbol: str, tail_days: int = 400, attempts: int = 3) -> Optional[pd.Series]: + """ + FIX 2026-08-15 (ver ROOT CAUSE en el docstring del módulo): antes esto + era un único intento sin throttle ni semáforo -- bajo ráfaga paralela + (10 tickers x hasta 4 macro tickers directo a Stooq) un solo glitch + transitorio o un bloqueo momentáneo del endpoint anónimo mataba el + símbolo entero de inmediato. Ahora reintenta con backoff (glitches + transitorios: timeout, 5xx, CSV vacío que Stooq a veces sirve bajo + carga) Y respeta `_STOOQ_CONCURRENCY`/`_stooq_throttle` para no ser, + en sí mismo, la causa de la próxima ráfaga. + """ + last_exc: Optional[Exception] = None + for attempt in range(attempts): + with _STOOQ_CONCURRENCY: + _stooq_throttle() + try: + resp = requests.get( + "https://stooq.com/q/d/l/", + # FIX 2026-08-15 (previo): antes se interpolaba + # stooq_symbol crudo en el f-string de la URL -- el '^' + # de los símbolos de índice (^spx, ^vix) viaja sin + # url-encodear (%5E). `params=` deja que `requests` lo + # encodee correctamente; evita un CSV vacío/malformado + # que silenciaba el fallback justo para índices. + params={"s": stooq_symbol, "i": "d"}, + timeout=10, + headers={"User-Agent": "Mozilla/5.0 (KodaQuant market_data fallback)"}, + ) + resp.raise_for_status() + df = pd.read_csv(io.StringIO(resp.text)) + if df.empty or "Close" not in df.columns or "Date" not in df.columns: + # Stooq devuelve 200 con un cuerpo que NO es el CSV + # esperado cuando bloquea/limita un cliente anónimo + # (página de error, CSV vacío) -- se trata como fallo + # transitorio, reintentable, no como "símbolo inválido". + raise ValueError( + f"Stooq devolvió una respuesta sin columnas Close/Date " + f"para '{stooq_symbol}' (posible bloqueo/rate-limit " + f"anónimo bajo carga)." + ) + df["Date"] = pd.to_datetime(df["Date"]) + series = df.set_index("Date").sort_index()["Close"].dropna() + if series.empty: + raise ValueError(f"Stooq devolvió CSV sin filas válidas para '{stooq_symbol}'.") + return series.tail(tail_days) + except Exception as exc: # noqa: BLE001 -- reintentamos cualquier fallo transitorio + last_exc = exc + if attempt < attempts - 1: + time.sleep(1.5 * (attempt + 1)) + + logger.warning("Stooq falló para '%s' tras %d intento(s): %r", stooq_symbol, attempts, last_exc) + return None + + +# --------------------------------------------------------------------------- +# Fetch unificado por símbolo -- Twelve Data primero (con caché), Stooq +# como último recurso. Usado tanto para el ticker operable como para cada +# macro ticker. +# --------------------------------------------------------------------------- + +def _fetch_symbol_ohlcv( + internal_key: str, + td_symbol: Optional[str], + stooq_symbol: Optional[str], + min_sessions: int, + fred_series_id: Optional[str] = None, +) -> pd.DataFrame: + cached = _market_cache.get_json(f"ohlcv:{internal_key}") + if cached is not None and len(cached) >= min(min_sessions, 30): + return cached + + # FIX 2026-08-15 -- SINGLE-FLIGHT (ver ROOT CAUSE RONDA 1 en el + # docstring del módulo). El universo completo (10 tickers, escaneado en + # paralelo por `prediccion._scan_universe`) comparte los MISMOS 5 macro + # tickers: sin este lock, hasta 10 hilos pedían '^GSPC' (u otro macro + # ticker) a la red AL MISMO TIEMPO. Con el lock, solo el primer hilo en + # tomarlo golpea la red; el resto espera y reusa lo que ese hilo deja + # en caché -- de ahí el segundo `_cache_get` adentro (double-checked): + # si otro hilo ya resolvió el símbolo mientras esperábamos el lock, no + # repetimos nada. + with _lock_for(internal_key): + cached = _market_cache.get_json(f"ohlcv:{internal_key}") + if cached is not None and len(cached) >= min(min_sessions, 30): + return cached + + df: Optional[pd.DataFrame] = None + + # RONDA 2 -- FRED primero si el símbolo lo tiene mapeado (hoy solo + # ^TNX, ver MACRO_SYMBOL_MAP). Es una API oficial diseñada para + # tráfico programático, no un endpoint de scraping con protección + # anti-bot como Stooq -- ver ROOT CAUSE RONDA 2. `_fred_client` + # ya devuelve `None` sin tocar la red si no hay `api_key` + # configurada, así que este bloque es un no-op limpio en ese caso. + if fred_series_id: + fred_series = _fred_client.daily_series(fred_series_id, tail_days=DEFAULT_HISTORY_SESSIONS + 30) + if fred_series is not None and not fred_series.empty: + df = pd.DataFrame({"close": fred_series}) + df["open"] = df["close"] + df["high"] = df["close"] + df["low"] = df["close"] + df["volume"] = np.nan + + if df is None or df.empty: + df = _td_time_series(td_symbol, outputsize=DEFAULT_HISTORY_SESSIONS) if td_symbol else None + + if df is None or df.empty: + if stooq_symbol is not None: + series = _stooq_daily_close(stooq_symbol, tail_days=DEFAULT_HISTORY_SESSIONS + 30) + if series is not None and not series.empty: + df = pd.DataFrame({"close": series}) + df["open"] = df["close"] + df["high"] = df["close"] + df["low"] = df["close"] + df["volume"] = np.nan + logger.warning( + "'%s': sirviendo desde fallback Stooq -- solo Close real; " + "Open/High/Low replicados desde Close y Volume=NaN " + "(ATR_14/OBV_ROC_20/ADX_14/STOCH_K_14 quedan degradados para " + "este ticker hasta que la fuente primaria vuelva a responder).", + internal_key, + ) + + if df is None or df.empty: + # FIX 2026-08-15 -- CACHÉ STALE COMO ÚLTIMO RECURSO, antes de + # rendirse. TODAS las fuentes configuradas fallaron en vivo; + # en vez de lanzar de inmediato (y con eso tumbar los 10 + # forecasts que dependen de este mismo macro ticker), se + # busca la última descarga exitosa en disco sin importar si + # el TTL de 6h venció. Solo si NUNCA hubo una descarga + # exitosa (arranque en frío + todas las fuentes caídas a la + # vez) se lanza el RuntimeError real. + stale = _market_cache.get_json(f"ohlcv:{internal_key}", ignore_ttl=True) + if stale is not None and not stale.empty: + stale_age_h = stale.attrs.get("_stale_age_hours") + logger.warning( + "'%s': todas las fuentes en vivo configuradas fallaron -- " + "sirviendo caché STALE (%s hs de antigüedad) en vez de " + "tumbar el forecast completo. Reintentará una descarga " + "en vivo en la próxima llamada.", + internal_key, stale_age_h if stale_age_h is not None else "?", + ) + return stale + + fuentes = [n for n, v in (("FRED", fred_series_id), ("Twelve Data", td_symbol), ("Stooq", stooq_symbol)) if v] + raise RuntimeError( + f"Sin datos para '{internal_key}': todas las fuentes configuradas " + f"({', '.join(fuentes) if fuentes else 'ninguna'}) fallaron y no hay " + "caché previa (ni siquiera stale) que servir -- radar degradado " + "para este símbolo." + ) + + _market_cache.set_json(f"ohlcv:{internal_key}", df) + return df + + +# --------------------------------------------------------------------------- +# API pública -- consumida por services/quanti_engine.py +# --------------------------------------------------------------------------- + +# Directiva 4: `_normalize_daily_index`/`_macro_close_ffilled_to_daily_calendar` +# migraron 1:1 a `kodaquant_core.normalize_daily_index`/`align_macro_to_calendar` +# (import al inicio del módulo) -- misma lógica exacta (upsample a +# calendario diario corrido + ffill, nunca bfill, ANTES de reindexar contra +# el calendario del activo objetivo), ahora compartida con +# `train_kodaquant_v5.py` en vez de vivir duplicada acá. + + +def fetch_feature_ohlcv(ticker: str, macro_tickers: list[str], min_sessions: int = DEFAULT_HISTORY_SESSIONS) -> pd.DataFrame: + """ + Reemplazo directo del antiguo `yf.download(all_symbols, period="2y", + auto_adjust=True, ...)` en `_fetch_feature_window`. Devuelve un + DataFrame indexado por fecha con EXACTAMENTE el mismo layout de + columnas que consumía ese bloque: + out[ticker] -- Close diario del ticker objetivo + out[f"{ticker}_Open"] -- V28: Open REAL (overnight/intraday de free_alpha). + Ausente si la fuente es degradada (Open=Close) o + tiene <90% de cobertura: nunca se sintetiza. + out[f"{ticker}_High"] -- High diario (requerido por ATR_14) + out[f"{ticker}_Low"] -- Low diario (requerido por ATR_14) + out[f"{ticker}_Volume"] -- Volume diario (requerido por OBV_ROC_20) + out[macro_ticker] -- Close diario de cada factor macro + + Ver `kodaquant_core.align_macro_to_calendar` para el fix de alineación + 24/7 (cripto) vs 5/5 (macro tickers) -- antes de esta fecha, este + mismo merge era la causa raíz real de + "'BTC-USD'/'ETH-USD': ventana de features vacía tras alinear con los + macro tickers" (ver logs de producción del 2026-08-15). + """ + td_symbol = _resolve_td_symbol(ticker) + stooq_symbol = _resolve_stooq_symbol(ticker) + target_df = _fetch_symbol_ohlcv(ticker, td_symbol, stooq_symbol, min_sessions) + + target_index = normalize_daily_index(target_df.index) + target_index = target_index[~target_index.duplicated(keep="last")] + # Puede desordenar la serie si la fuente ya venía ordenada pero con + # timestamps tz-aware cuya normalización cambia el orden relativo en + # un caso límite (feriados con horario de cierre distinto) -- sort + # explícito, nunca asumido. + target_df = target_df.loc[~target_df.index.duplicated(keep="last")].copy() + target_df.index = normalize_daily_index(target_df.index) + target_df = target_df.sort_index() + + out = pd.DataFrame(index=target_df.index) + out[ticker] = target_df["close"] + + # V28 -- Open real para free_alpha.compute_equity_open_features. Stooq/FRED + # replican Open=Close (gap == retorno diario, intraday == 0): emitirlo + # fabricaría un feature distinto al de train -> se omite la columna y el + # motor degrada a 0.0 con error explícito. Los NaN sueltos de Open se + # rellenan con Close del mismo día (nunca ffill: no se inventa un gap). + _o_raw = target_df["open"] if "open" in target_df.columns else None + if _o_raw is not None: + _o = pd.to_numeric(_o_raw, errors="coerce") + _o = _o.where(_o > 0.0) + if _o.notna().mean() >= 0.9 and (_o == target_df["close"]).mean() < 0.98: + out[f"{ticker}_Open"] = _o.fillna(target_df["close"]) + else: + logger.warning("'%s': Open degradado/ausente (cobertura=%.0f%%, Open==Close=%.0f%%) " + "-> '%s_Open' NO se emite; features overnight/intraday V28 = 0.0.", + ticker, 100.0 * _o.notna().mean(), + 100.0 * (_o == target_df["close"]).mean(), ticker) + else: + logger.warning("'%s': sin columna 'open' en la fuente -> '%s_Open' NO se emite.", ticker, ticker) + + out[f"{ticker}_High"] = target_df["high"] + out[f"{ticker}_Low"] = target_df["low"] + out[f"{ticker}_Volume"] = target_df["volume"] + + target_last_date = out.index.max() if not out.empty else pd.Timestamp.utcnow().normalize() + + for macro_ticker in macro_tickers: + mapping = resolve_macro_symbol(macro_ticker) + macro_df = _fetch_symbol_ohlcv( + macro_ticker, mapping.get("twelvedata"), mapping.get("stooq"), min_sessions, + fred_series_id=mapping.get("fred"), + ) + macro_close = macro_df["close"].copy() + macro_close.index = normalize_daily_index(macro_close.index) + macro_close_daily = align_macro_to_calendar(macro_close, target_last_date) + out[macro_ticker] = macro_close_daily.reindex(out.index) + + out = out.sort_index() + out = out.ffill().dropna() + if out.empty: + raise ValueError( + f"'{ticker}': ventana de features vacía tras alinear con los " + "macro tickers -- histórico insuficiente o símbolos macro " + "desalineados (fechas sin superposición real)." + ) + return out + + +def fetch_close_history(internal_key: str, min_days: int) -> pd.Series: + """ + Reemplazo directo del antiguo `yf.Ticker(symbol).history(period=...)` + en `get_market_sentiment` -- serie de Close diario para `internal_key` + (ticker operable O macro ticker, ambos soportados). Reutiliza la MISMA + caché de `fetch_feature_ohlcv` cuando el símbolo ya fue descargado + para un forecast en la misma ventana de TTL -- cero llamadas de red + adicionales en ese caso. + """ + if internal_key in MACRO_SYMBOL_MAP: + mapping = resolve_macro_symbol(internal_key) + td_symbol, stooq_symbol = mapping.get("twelvedata"), mapping.get("stooq") + fred_series_id = mapping.get("fred") + else: + td_symbol = _resolve_td_symbol(internal_key) + stooq_symbol = _resolve_stooq_symbol(internal_key) + fred_series_id = None + + df = _fetch_symbol_ohlcv(internal_key, td_symbol, stooq_symbol, min_days, fred_series_id=fred_series_id) + return df["close"].dropna() \ No newline at end of file diff --git a/services/mlops_state.json b/services/mlops_state.json new file mode 100644 index 0000000000000000000000000000000000000000..6856939e96056f3a08e0dcbf0328c03c2043a421 --- /dev/null +++ b/services/mlops_state.json @@ -0,0 +1,20 @@ +{ + "baseline_mae": { + "__global__": 0.017297450997422407 + }, + "last_run": "2026-07-19T04:04:11.311396+00:00", + "history": [ + { + "timestamp": "2026-07-19T03:32:29.232138+00:00", + "status": "error" + }, + { + "timestamp": "2026-07-19T04:03:23.907187+00:00", + "status": "error" + }, + { + "timestamp": "2026-07-19T04:04:11.311396+00:00", + "status": "rejected" + } + ] +} \ No newline at end of file diff --git a/services/online_learning.py b/services/online_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..8598098b27e7df4abe48dd62e84acaa61aa753da --- /dev/null +++ b/services/online_learning.py @@ -0,0 +1,455 @@ +# services/online_learning.py +""" +Continuous / Self-Correcting Online Learning — KodaQuant Terminal V5 +==================================================================== +Ciclo diario de auto-corrección MULTI-RÉGIMEN: cada especialista V5 +(`kodaquant_models/equity_specialist/`, `.../crypto_specialist/`, ver +`REGIME_TICKERS`/`_regime_for_ticker` en quanti_engine.py) se fine-tunea +de forma INDEPENDIENTE, con su propio micro-batch, su propio modelo y su +propio bundle de scalers — nunca mezclados entre sí (dimensiones/escalas +de features distintas entre equity y cripto). + +CICLO (1x/día, post-cierre de mercado): + 1. Por cada ticker con predicción pendiente de ayer (ledger SQLite): + descarga el cierre real (Twelve Data + fallback Stooq, ver + services/market_data.py — yfinance retirado del proyecto), calcula + el error vs. lo predicho, y resuelve a qué régimen pertenece + (`_regime_for_ticker`). + 2. Agrupa los samples en un micro-batch POR RÉGIMEN. + 3. Por cada régimen con batch no vacío: carga una copia fresca de + `model_v5.keras` (grafo de entrenamiento normal, no el bridge MC + Dropout de inferencia), recompila con `DirectionalHuberLoss` (misma + loss del entrenamiento original) + LR bajo de fine-tuning, corre una + micro-época, guarda atómicamente en su propia carpeta e invalida el + cache de `_get_keras_model()`. + 4. Marca en el ledger SOLO los tickers cuyo régimen fine-tuneó con + éxito (si cripto falla pero equity no, equity se marca aprendido y + cripto queda pendiente para el próximo ciclo). + 5. Re-loguea la predicción T+1 de HOY para MAÑANA, para todo el + universo (ambos regímenes), cerrando el círculo. + +Nunca debe fallar de forma que tumbe el proceso del scheduler: cada etapa +está aislada en try/except con logging explícito. +""" + +import os +import sqlite3 +import traceback +from contextlib import contextmanager +from datetime import datetime, timezone +from typing import Any, Iterator + +import numpy as np +import pandas as pd + +from services.market_data import fetch_close_history + +from services.quanti_engine import ( + REGIME_TICKERS, + BahdanauAttention, + DirectionalHuberLoss, + _fetch_feature_window, + _forecast_asset, + _get_keras_model, + _get_scalers, + _model_path, + _regime_for_ticker, + directional_accuracy_metric, + inference_lock, + keras, + MODELS_ROOT, +) + +# --------------------------------------------------------------------------- +# Ledger — SQLite local, único y compartido entre regímenes (una fila por +# ticker/target_date; el ticker ya determina su régimen vía +# `_regime_for_ticker`, la columna `regime` lo deja explícito para +# auditoría/reportes sin tener que re-resolverlo). +# --------------------------------------------------------------------------- + +_LEDGER_PATH = MODELS_ROOT / "online_learning_ledger.sqlite3" + +# Fine-tuning: LR deliberadamente ~100x menor que el de entrenamiento largo +# original — un micro-batch diario es señal muy pequeña frente al histórico +# con que se entrenó cada especialista; un LR alto destruiría ese +# conocimiento en una sola pasada (catastrophic forgetting). +FINE_TUNE_LEARNING_RATE = 1e-5 +FINE_TUNE_WEIGHT_DECAY = 1e-5 + + +def _utc_today_str() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%d") + + +def _utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +@contextmanager +def _ledger_conn() -> Iterator[sqlite3.Connection]: + conn = sqlite3.connect(_LEDGER_PATH) + try: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS prediction_ledger ( + ticker TEXT NOT NULL, + target_date TEXT NOT NULL, + regime TEXT NOT NULL DEFAULT '', + anchor_date TEXT NOT NULL, + anchor_price REAL NOT NULL, + predicted_price REAL NOT NULL, + predicted_log_return REAL NOT NULL, + logged_at TEXT NOT NULL, + actual_price REAL, + actual_log_return REAL, + error_log_return REAL, + learned_at TEXT, + PRIMARY KEY (ticker, target_date) + ) + """ + ) + try: + # Migración defensiva: ledgers V4 preexistentes no tienen esta + # columna — CREATE TABLE IF NOT EXISTS no la agrega a una + # tabla ya existente. + conn.execute("ALTER TABLE prediction_ledger ADD COLUMN regime TEXT NOT NULL DEFAULT ''") + except sqlite3.OperationalError: + pass # columna ya existe + yield conn + conn.commit() + finally: + conn.close() + + +def _iter_universe_by_regime() -> Iterator[tuple[str, str]]: + """ + (ticker, regime) para TODO el universo entrenado. La fuente de verdad + es `asset_to_id` de cada `scalers_dict.pkl` (no `REGIME_TICKERS` a + secas) — un régimen sin artefactos cargables se omite con log, nunca + tumba el resto del ciclo. + """ + for regime in REGIME_TICKERS: + try: + scalers = _get_scalers(regime) + except Exception as exc: # noqa: BLE001 + print(f"⚠️ [online_learning] No se pudieron cargar los scalers del régimen '{regime}': {exc!r}") + continue + for ticker in scalers["asset_to_id"]: + yield ticker, regime + + +# --------------------------------------------------------------------------- +# Paso A — loguear la predicción de HOY para MAÑANA (cierra el círculo) +# --------------------------------------------------------------------------- + +def log_next_day_prediction(ticker: str) -> dict[str, Any] | None: + """ + Corre un forecast real de 1 paso (`_forecast_asset`, mismo motor que ve + el usuario, CERO lógica duplicada; resuelve su propio régimen + internamente) y deja constancia en el ledger de qué se predijo para la + sesión siguiente. + """ + try: + regime = _regime_for_ticker(ticker) + except ValueError as exc: + print(f"⚠️ [online_learning] '{ticker}' no pertenece a ningún régimen V5 conocido: {exc!r}") + return None + + try: + result = _forecast_asset(ticker, steps=1) + except Exception as exc: # noqa: BLE001 + print(f"⚠️ [online_learning] No se pudo generar el forecast T+1 de {ticker} para loguear: {exc!r}") + return None + + if result.get("forecast_incomplete") or not result.get("forecast"): + print(f"⚠️ [online_learning] Forecast T+1 de {ticker} incompleto — no se loguea (evita ensuciar el ledger).") + return None + + anchor_price = float(result["last_price"]) + point = result["forecast"][0] + predicted_price = float(point["expected_path"]) + predicted_log_return = float(np.log(predicted_price / anchor_price)) + target_date = point["date"] + anchor_date = result["historical"][-1]["date"] if result.get("historical") else _utc_today_str() + + with _ledger_conn() as conn: + conn.execute( + """ + INSERT OR REPLACE INTO prediction_ledger + (ticker, target_date, regime, anchor_date, anchor_price, + predicted_price, predicted_log_return, logged_at, + actual_price, actual_log_return, error_log_return, learned_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, + COALESCE((SELECT actual_price FROM prediction_ledger WHERE ticker=? AND target_date=?), NULL), + COALESCE((SELECT actual_log_return FROM prediction_ledger WHERE ticker=? AND target_date=?), NULL), + COALESCE((SELECT error_log_return FROM prediction_ledger WHERE ticker=? AND target_date=?), NULL), + COALESCE((SELECT learned_at FROM prediction_ledger WHERE ticker=? AND target_date=?), NULL)) + """, + ( + ticker, target_date, regime, anchor_date, anchor_price, + predicted_price, predicted_log_return, _utc_now_iso(), + ticker, target_date, ticker, target_date, ticker, target_date, ticker, target_date, + ), + ) + + return { + "ticker": ticker, "target_date": target_date, "regime": regime, "anchor_date": anchor_date, + "anchor_price": anchor_price, "predicted_price": predicted_price, + "predicted_log_return": predicted_log_return, + } + + +def log_next_day_predictions_for_universe() -> dict[str, Any]: + logged, failed = [], [] + for ticker, _regime in _iter_universe_by_regime(): + row = log_next_day_prediction(ticker) + (logged if row else failed).append(ticker) + return {"logged": logged, "failed": failed} + + +# --------------------------------------------------------------------------- +# Paso B — reconstruir la ventana EXACTA que vio el modelo en `anchor_date` +# --------------------------------------------------------------------------- + +def _reconstruct_scaled_sample( + ticker: str, anchor_date: str, anchor_price: float, actual_price: float, +) -> tuple[np.ndarray, float] | None: + """ + Devuelve (ventana_normalizada (lookback, n_features), r_real_escalado) + lista para entrar al `.fit()` del especialista de `ticker`, o None si + no se pudo reconstruir (datos insuficientes, régimen desconocido, etc.). + """ + try: + regime = _regime_for_ticker(ticker) + scalers = _get_scalers(regime) + except Exception as exc: # noqa: BLE001 + print(f"⚠️ [online_learning] No se pudo resolver régimen/scalers de {ticker}: {exc!r}") + return None + + feature_scaler = scalers["feature_scalers"][ticker] + target_scaler = scalers["target_scalers"][ticker] + lookback = scalers["lookback"] + macro_tickers = scalers["macro_tickers"] + + try: + _close_df, raw_features = _fetch_feature_window( + ticker, macro_tickers, lookback, as_of_date=anchor_date, + ) + except Exception as exc: # noqa: BLE001 + print(f"⚠️ [online_learning] No se pudo reconstruir la ventana de {ticker} @ {anchor_date}: {exc!r}") + return None + + if raw_features.shape[0] < lookback: + print(f"⚠️ [online_learning] Ventana incompleta para {ticker} @ {anchor_date} (feriado/gap) — se omite hoy.") + return None + + scaled_window = feature_scaler.transform(raw_features).astype(np.float32) + + r_real = float(np.log(actual_price / anchor_price)) + r_real_scaled = float(target_scaler.transform(np.array([[r_real]]))[0, 0]) + return scaled_window, r_real_scaled + + +def _fetch_actual_close(ticker: str, target_date: str) -> float | None: + """ + Cierre real de `target_date` -- vía `fetch_close_history` + (services/market_data.py: Twelve Data + fallback Stooq, misma caché en + disco que ya usa `_fetch_feature_window`/`get_market_sentiment`; + yfinance retirado del proyecto). Reemplaza 1:1 el antiguo + `yf.download(ticker, start=..., end=..., auto_adjust=True, ...)` -- + incluso reutiliza la descarga ya cacheada de este mismo ticker si el + ciclo diario corrió después de un forecast reciente, cero llamada de + red extra en ese caso. + """ + try: + closes = fetch_close_history(ticker, min_days=10) + except Exception as exc: # noqa: BLE001 + print(f"⚠️ [online_learning] fetch_close_history falló pidiendo el cierre real de {ticker} @ {target_date}: {exc!r}") + return None + if closes.empty: + return None + target_ts = pd.Timestamp(target_date) + if target_ts not in closes.index: + return None + return float(closes.loc[target_ts]) + + +# --------------------------------------------------------------------------- +# Paso C.1 — fine-tuning de UN especialista sobre su propio micro-batch +# --------------------------------------------------------------------------- + +def _fine_tune_regime( + regime: str, X_batch: list[np.ndarray], asset_id_batch: list[int], y_batch: list[float], +) -> float: + """ + Carga fresca de `kodaquant_models//model_v5.keras` (grafo de + entrenamiento normal, NO el bridge MC Dropout de inferencia), bajo el + mismo `inference_lock` que serializa forward passes de usuarios reales + contra el modelo cacheado de ESE régimen. Recompila con + `DirectionalHuberLoss` (misma loss del entrenamiento original) + LR + bajo de fine-tuning. Guardado atómico en la carpeta del propio + régimen + invalidación de `_get_keras_model` cache. + """ + model_path = _model_path(regime) + X = np.stack(X_batch, axis=0) + asset_ids = np.array(asset_id_batch, dtype=np.int32).reshape(-1, 1) + y = np.array(y_batch, dtype=np.float32).reshape(-1, 1) + + with inference_lock: + finetune_model = keras.models.load_model( + model_path, + custom_objects={ + "BahdanauAttention": BahdanauAttention, + "DirectionalHuberLoss": DirectionalHuberLoss, + "directional_accuracy_metric": directional_accuracy_metric, + }, + compile=False, + ) + finetune_model.compile( + optimizer=keras.optimizers.AdamW( + learning_rate=FINE_TUNE_LEARNING_RATE, weight_decay=FINE_TUNE_WEIGHT_DECAY, + ), + loss=DirectionalHuberLoss(), + metrics=["mae", directional_accuracy_metric], + ) + history = finetune_model.fit( + [X, asset_ids], y, epochs=1, batch_size=len(X_batch), shuffle=True, verbose=0, + ) + + # Guardado ATÓMICO: nunca se sobrescribe el .keras del régimen en sitio. + tmp_path = f"{model_path}.tmp" + finetune_model.save(tmp_path) + os.replace(tmp_path, model_path) + + # Invalida el cache (todas las claves/regímenes) — la siguiente + # `_forecast_asset()` real recarga el `.keras` recién fine-tuneado + # del régimen que corresponda. + _get_keras_model.cache_clear() + + return float(history.history["loss"][-1]) + + +# --------------------------------------------------------------------------- +# Paso C.2 — el ciclo completo, multi-régimen +# --------------------------------------------------------------------------- + +def run_daily_online_learning_cycle() -> dict[str, Any]: + """ + Entry point para un cron/APScheduler diario post-cierre. Idempotente + por régimen: una fila del ledger solo se marca aprendida si el + fine-tuning de SU régimen tuvo éxito; si un régimen falla, sus filas + quedan pendientes para el próximo ciclo sin afectar al otro régimen. + """ + report: dict[str, Any] = { + "learned": [], "skipped": [], "errors": [], + "loss_by_regime": {}, "loss": None, + } + today = _utc_today_str() + + universe = [ticker for ticker, _regime in _iter_universe_by_regime()] + if not universe: + report["errors"].append("No se pudo cargar ningún especialista V5 (equity/crypto) — sin universo.") + return report + + with _ledger_conn() as conn: + rows = conn.execute( + """ + SELECT ticker, target_date, anchor_date, anchor_price, predicted_log_return + FROM prediction_ledger + WHERE target_date = ? AND actual_price IS NULL + """, + (today,), + ).fetchall() + + if not rows: + report["skipped"] = universe + report["errors"].append(f"Sin predicciones pendientes de ayer para hoy ({today}) — nada que aprender aún.") + return report + + # Micro-batches SEPARADOS por régimen — nunca se mezclan equity y + # cripto en el mismo `.fit()` (dimensiones/escalas de features distintas). + batches: dict[str, dict[str, list]] = {} + pending_updates: list[dict[str, Any]] = [] + + for ticker, target_date, anchor_date, anchor_price, predicted_log_return in rows: + try: + regime = _regime_for_ticker(ticker) + except ValueError as exc: + report["errors"].append(f"{ticker}: {exc!r}") + continue + + try: + actual_price = _fetch_actual_close(ticker, target_date) + if actual_price is None: + report["skipped"].append(ticker) + continue + + sample = _reconstruct_scaled_sample(ticker, anchor_date, anchor_price, actual_price) + if sample is None: + report["skipped"].append(ticker) + continue + scaled_window, r_real_scaled = sample + + scalers = _get_scalers(regime) + asset_id = scalers["asset_to_id"][ticker] + + bucket = batches.setdefault(regime, {"X": [], "asset_id": [], "y": []}) + bucket["X"].append(scaled_window) + bucket["asset_id"].append(asset_id) + bucket["y"].append(r_real_scaled) + + r_real = float(np.log(actual_price / anchor_price)) + pending_updates.append({ + "ticker": ticker, "target_date": target_date, "regime": regime, + "actual_price": actual_price, "actual_log_return": r_real, + "error_log_return": r_real - predicted_log_return, + }) + except Exception as exc: # noqa: BLE001 + report["errors"].append(f"{ticker}: {exc!r}\n{traceback.format_exc(limit=3)}") + + if not batches: + report["errors"].append("Ningún ticker tuvo datos completos hoy — ciclo sin fine-tuning.") + return report + + learned_tickers: set[str] = set() + for regime, bucket in batches.items(): + try: + report["loss_by_regime"][regime] = _fine_tune_regime( + regime, bucket["X"], bucket["asset_id"], bucket["y"], + ) + learned_tickers.update(u["ticker"] for u in pending_updates if u["regime"] == regime) + except Exception as exc: # noqa: BLE001 + report["errors"].append( + f"Fine-tuning del régimen '{regime}' falló, su modelo NO se tocó: " + f"{exc!r}\n{traceback.format_exc(limit=5)}" + ) + + successful_updates = [u for u in pending_updates if u["ticker"] in learned_tickers] + if not successful_updates: + report["errors"].append("Ningún régimen completó el fine-tuning — el ledger no se marca como aprendido.") + return report + + with _ledger_conn() as conn: + for u in successful_updates: + conn.execute( + """ + UPDATE prediction_ledger + SET actual_price = ?, actual_log_return = ?, error_log_return = ?, + learned_at = ?, regime = ? + WHERE ticker = ? AND target_date = ? + """, + (u["actual_price"], u["actual_log_return"], u["error_log_return"], + _utc_now_iso(), u["regime"], u["ticker"], u["target_date"]), + ) + report["learned"] = [u["ticker"] for u in successful_updates] + report["mean_abs_error_log_return"] = float( + np.mean([abs(u["error_log_return"]) for u in successful_updates]) + ) + if report["loss_by_regime"]: + report["loss"] = float(np.mean(list(report["loss_by_regime"].values()))) + + # Cierra el círculo: loguea la predicción de HOY para MAÑANA con los + # modelos YA fine-tuneados, para todo el universo (ambos regímenes). + report["next_day_logging"] = log_next_day_predictions_for_universe() + + return report \ No newline at end of file diff --git a/services/online_learning_ledger.sqlite3 b/services/online_learning_ledger.sqlite3 new file mode 100644 index 0000000000000000000000000000000000000000..a87028c0177f5cf8102d520a7f3d810fad293763 Binary files /dev/null and b/services/online_learning_ledger.sqlite3 differ diff --git a/services/prediccion.py b/services/prediccion.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce774a1d23725ed8b4461578fb36144168f13d1 --- /dev/null +++ b/services/prediccion.py @@ -0,0 +1,439 @@ +""" +services/prediccion.py + +Radar de mercado — KodaQuant Terminal V5. Orquesta el pipeline REAL de +inferencia expuesto por quanti_engine.py (Keras 3 + Monte Carlo + MC +Dropout, ver _forecast_asset) sobre todo el universo entrenado +(REGIME_TICKERS), traduce el edge direccional de cada especialista a +acción operativa (action) y dimensiona el capital sugerido +(allocation_pct) en proporción a la confianza estadística real del propio +forecast — cero simulación, cero cifras inventadas. +""" + +import asyncio +import logging +from datetime import datetime, timezone +from typing import Any, Dict, List, Tuple + +from services.quanti_engine import ( + DEFAULT_FORECAST_HORIZON_DAYS, + PLAN_A_TICKER, + REGIME_TICKERS, + _forecast_asset, + _safe_sentiment, +) + +logger = logging.getLogger("kodaquant.prediccion") + +# Universo real escaneado — mismos tickers entrenados por los especialistas +# V5 (equity_specialist + crypto_specialist); REGIME_TICKERS es la única +# fuente de verdad (ver quanti_engine.py). +_RADAR_UNIVERSE: List[str] = [t for tickers in REGIME_TICKERS.values() for t in tickers] +_CRYPTO_TICKERS = frozenset(REGIME_TICKERS.get("crypto_specialist", ())) + +TOP_N_RECOMMENDATIONS = 3 + +# FIX 2026-08-15 -- ver ROOT CAUSE de "degradación total del radar" en el +# docstring de services/market_data.py. Antes de esto, `_scan_universe` +# despachaba los 10 tickers de REGIME_TICKERS los 10 A LA VEZ (cada uno con +# inferencia Keras CPU-only real + I/O de red), maximizando tanto la +# contención de CPU como la ventana en la que todos pedían los mismos 5 +# macro tickers compartidos al mismo tiempo -- el single-flight lock nuevo +# en market_data.py ya colapsa esa ráfaga a 1 request por macro ticker, +# pero acotar la concurrencia acá es la segunda capa: con esto, el primer +# ticker despachado resuelve (y cachea) el macro context casi en solitario, +# y el resto del universo entra de a oleadas encontrando caché ya tibia. +_SCAN_CONCURRENCY = 4 + +# Alpha Seeker — candidatos reales para "Quanti's Choice" (selección +# automática de Plan B en modo discovery, ver _resolve_plan_b_ticker en +# quanti_engine.py). Tope de candidatos expuestos al motor de allocation. +_ALPHA_SEEKER_MAX_CANDIDATES = 5 + +# Umbrales de retorno proyectado (edge) -> acción operativa. Aplican tal +# cual al régimen de regresión (equity_specialist); el régimen +# target_mode="triple_barrier" (crypto_specialist, V22) usa su PROPIO +# mapeo de acción basado en la clase predicha real (SL/TIMEOUT/TP) y el +# filtro de confianza `tb_actionable` — ver `_action_for_forecast`. +_STRONG_BUY_THRESHOLD_PCT = 4.0 +_LIGHT_BUY_THRESHOLD_PCT = 1.0 +_SELL_THRESHOLD_PCT = -1.0 + +# V22 — Triple Barrier: confianza de clasificación (softmax MC-Dropout +# promediado, ver quanti_engine._forecast_asset_triple_barrier) por encima +# de la cual "TP" se traduce en COMPRA FUERTE en vez de COMPRA LIGERA. El +# piso de actionability en sí (por debajo del cual la señal se degrada +# directo a MANTENER) vive en quanti_engine.TB_MIN_SIGNAL_CONFIDENCE — este +# umbral es estrictamente mayor a ese piso, nunca al revés. +_TB_STRONG_CONFIDENCE_THRESHOLD = 0.60 + +# Cotas de asignación de capital por pick, moduladas por confianza real. +_MIN_ALLOCATION_PCT = 0.10 +_MAX_ALLOCATION_PCT = 0.45 +# Cripto: la misma razón señal/ruido implica menor confianza estructural +# (mayor volatilidad realizada) -> se amortigua el allocation_pct. Se +# aplica IGUAL sobre ambos target_mode (regresión heredado / triple_barrier +# V22) — es una propiedad del ACTIVO (cripto), no del mecanismo de forecast. +_CRYPTO_CONFIDENCE_DAMPENING = 0.6 +_CONFIDENCE_SCORE_CAP = 1.5 # techo de normalización — SOLO régimen de regresión (razón edge/banda, no acotada a 1.0) +_TB_CONFIDENCE_SCORE_CAP = 1.0 # techo de normalización — régimen triple_barrier (_tb_confidence_score ya vive en [0,1]) +_TB_BASELINE_CONFIDENCE = 1.0 / 3.0 # azar puro con 3 clases (SL/TIMEOUT/TP) — piso de "sin edge" para normalizar + +# Fallback SOLO si el universo entero falla en yfinance/Keras (degradación +# total del radar) — nunca sustituye una predicción real disponible. +_FALLBACK_MAE_MARGIN = 4.55 + + +def _action_for_return(predicted_return_pct: float) -> str: + """Mapeo edge -> acción del régimen de regresión (equity_specialist). Ver `_action_for_forecast`.""" + if predicted_return_pct >= _STRONG_BUY_THRESHOLD_PCT: + return "COMPRA FUERTE" + if predicted_return_pct >= _LIGHT_BUY_THRESHOLD_PCT: + return "COMPRA LIGERA" + if predicted_return_pct <= _SELL_THRESHOLD_PCT: + return "VENTA" + return "MANTENER" + + +def _action_for_forecast(forecast: Dict[str, Any]) -> str: + """ + V22 — despacho por target_mode. `equity_specialist` (regresión) sigue + exactamente el mapeo edge->acción de siempre (`_action_for_return`). + `crypto_specialist` (target_mode="triple_barrier") NO tiene un edge + continuo del que derivar la acción — tiene una CLASE (SL/TIMEOUT/TP) + con una confianza de clasificación real, ya filtrada por el piso de + convicción mínima del motor (`tb_actionable`, ver + quanti_engine.TB_MIN_SIGNAL_CONFIDENCE): una clase accionable de baja + confianza ya viene degradada a "sin convicción operativa" ANTES de + llegar acá, así que esta función confía en `tb_actionable` en vez de + re-derivar el filtro desde `predicted_return_pct`. + """ + if forecast.get("target_mode") == "triple_barrier": + if not forecast.get("tb_actionable", False): + return "MANTENER" + predicted_class = forecast.get("tb_predicted_class") + if predicted_class == "SL": + return "VENTA" + if predicted_class == "TP": + confidence = float(forecast.get("tb_confidence", 0.0)) + return "COMPRA FUERTE" if confidence >= _TB_STRONG_CONFIDENCE_THRESHOLD else "COMPRA LIGERA" + return "MANTENER" # TIMEOUT, o clase desconocida — nunca inventar convicción + + return _action_for_return(forecast.get("predicted_return_pct", 0.0)) + + +def _tb_confidence_score(forecast: Dict[str, Any]) -> float: + """ + Confianza real del régimen target_mode="triple_barrier": la confianza + de clasificación MC-Dropout-promediada (`tb_confidence`, ya calculada + por quanti_engine._forecast_asset_triple_barrier sobre la salida + softmax real del modelo) normalizada contra el azar de 3 clases + (33.3% = 0 confianza real, 100% = 1.0). Una señal descartada por el + piso de convicción del motor (`tb_actionable=False`) vale 0 acá + también — nunca debe recibir allocation de capital pese a tener un + `predicted_return_pct` nominal (ver quanti_engine, TIMEOUT/baja + confianza no se anulan ahí para preservar la esperanza estadística + honesta; el filtro operativo vive en esta capa). + """ + if not forecast.get("tb_actionable", False): + return 0.0 + raw_confidence = float(forecast.get("tb_confidence", 0.0)) + return max(0.0, (raw_confidence - _TB_BASELINE_CONFIDENCE) / (1.0 - _TB_BASELINE_CONFIDENCE)) + + +def _confidence_score(forecast: Dict[str, Any]) -> float: + """ + V22 — despacho por target_mode (ver `_tb_confidence_score` para + target_mode="triple_barrier"). + + Régimen de regresión (equity_specialist, sin cambios): razón + señal/ruido = |edge proyectado| / ancho medio de la banda P5-P95 + (ambos ya calculados por _forecast_asset vía Monte Carlo real). Edge + grande + banda angosta = alta confianza; edge chico + banda ancha = + ruido. Se deriva 100% de la salida del modelo, cero cifras inventadas. + + Penalización OOD (ver `real_ood_dampening` en quanti_engine.py, + auditoría SPY oob_frac=45.6% en T+1): `real_ood_dampening_applied` + es el MISMO factor que ya recortó la magnitud de `predicted_return_pct` + en origen porque el input real de T+1 ya caía fuera del rango de + entrenamiento del `feature_scaler` — se reaplica acá porque un input + OOD no solo degrada la magnitud de la señal, también la CONFIANZA que + merece esa señal (el band width por sí solo no lo captura: una banda + angosta sobre un input extrapolado sigue siendo una banda angosta + calculada por una red operando fuera de lo que aprendió). Con datos + in-distribution (`real_ood_dampening_applied` ausente o 1.0, forecasts + generados antes de este campo) esto es un no-op exacto — no cambia el + comportamiento previo. + """ + if forecast.get("target_mode") == "triple_barrier": + return _tb_confidence_score(forecast) + + points = forecast.get("forecast") or [] + last_price = forecast.get("last_price") or 0.0 + if not points or last_price <= 0: + return 0.0 + + avg_band_pct = sum( + (p["upper_bound"] - p["lower_bound"]) / last_price * 100 for p in points + ) / len(points) + if avg_band_pct <= 0: + return 0.0 + + raw_score = abs(forecast.get("predicted_return_pct", 0.0)) / avg_band_pct + ood_factor = float(forecast.get("real_ood_dampening_applied", 1.0)) + return raw_score * ood_factor + + +def _allocation_pct_for(ticker: str, forecast: Dict[str, Any]) -> float: + score = _confidence_score(forecast) + # V22: el techo de normalización depende de la ESCALA del propio score + # -- _tb_confidence_score ya vive en [0,1] por construcción (regla de + # 3 clases), mientras que la razón edge/banda de regresión no está + # acotada a 1.0 (de ahí _CONFIDENCE_SCORE_CAP=1.5 histórico). Usar el + # cap equivocado para cada régimen sub/sobre-comprimiría el rango real + # de confianza de ese régimen específico. + cap = _TB_CONFIDENCE_SCORE_CAP if forecast.get("target_mode") == "triple_barrier" else _CONFIDENCE_SCORE_CAP + normalized = min(score, cap) / cap + allocation = _MIN_ALLOCATION_PCT + normalized * (_MAX_ALLOCATION_PCT - _MIN_ALLOCATION_PCT) + + if ticker in _CRYPTO_TICKERS: + allocation *= _CRYPTO_CONFIDENCE_DAMPENING + + return round(allocation, 4) + + +def _build_macro_context(spy_sentiment: Dict[str, Any], btc_sentiment: Dict[str, Any]) -> str: + """ + Contexto macro derivado de get_market_sentiment (momentum de retornos + log REALES vía yfinance, mismo mecanismo que usa quanti_engine) sobre + el ancla de renta variable (PLAN_A_TICKER) y el proxy de apetito por + riesgo cripto — reemplaza el texto VIX/DXY simulado. + """ + spy_score = spy_sentiment.get("sentiment_score", 0.0) + spy_label = spy_sentiment.get("sentiment_label", "Neutral") + btc_score = btc_sentiment.get("sentiment_score", 0.0) + btc_label = btc_sentiment.get("sentiment_label", "Neutral") + + if btc_score > 0.2: + risk_appetite = "apetito por riesgo elevado" + elif btc_score < -0.2: + risk_appetite = "aversión al riesgo dominante" + else: + risk_appetite = "apetito por riesgo mixto" + + return ( + f"El benchmark de renta variable ({PLAN_A_TICKER}) registra sentimiento " + f"{spy_label} (momentum normalizado: {spy_score:+.2f}). El proxy de " + f"apetito por riesgo cripto (BTC-USD) marca sentimiento {btc_label} " + f"(momentum normalizado: {btc_score:+.2f}), vía KodaQuant Sentinel — " + f"ambas lecturas derivadas de retornos logarítmicos realizados, sin " + f"cifras simuladas. El régimen combinado sugiere {risk_appetite} en " + "el universo escaneado por el radar." + ) + + +def _derive_mae_margin(candidates: List[Tuple[str, Dict[str, Any]]]) -> float: + """ + Margen de error real: promedio del semiancho de la banda P5-P95 en el + día terminal proyectado sobre los picks recomendados — reemplaza el + MAE fijo simulado por dispersión Monte Carlo genuina de cada forecast. + """ + margins = [] + for _, forecast in candidates: + points = forecast.get("forecast") or [] + if not points: + continue + terminal = points[-1] + margins.append((terminal["upper_bound"] - terminal["lower_bound"]) / 2) + + if not margins: + return _FALLBACK_MAE_MARGIN + return round(sum(margins) / len(margins), 2) + + +def _rank_alpha_seeker_candidates( + valid_forecasts: List[Tuple[str, Dict[str, Any]]] +) -> List[Dict[str, Any]]: + """ + Alpha Seeker: universo REAL de candidatos para "Quanti's Choice". + + Distinto de `recommendations` (top movers en valor ABSOLUTO — incluye + VENTAs, correcto para el scanner general que debe mostrar todo el + mercado). `top_assets` es el contrato que consume + `_resolve_plan_b_ticker` (quanti_engine.py) para decidir en QUÉ activo + invertir el capital de riesgo: solo admite edge direccional POSITIVO y + de grado de compra real (`predicted_return_pct >= _LIGHT_BUY_THRESHOLD_PCT`) + — un algoritmo de "mejor oportunidad" nunca puede devolver un activo en + caída. Ranking por Alpha Score = retorno CON signo * (1 + razón + señal/ruido) — nunca abs(), y nunca un campo fantasma tipo + `risk_score` que nadie completa. 100% derivado de `_forecast_asset`, + cero cifras inventadas. + """ + candidates = [] + for ticker, forecast in valid_forecasts: + predicted_return_pct = forecast.get("predicted_return_pct", 0.0) + is_triple_barrier = forecast.get("target_mode") == "triple_barrier" + + if is_triple_barrier: + # V22: "mejor oportunidad" exige una clase TP real Y accionable + # (ver quanti_engine.TB_MIN_SIGNAL_CONFIDENCE) -- un + # predicted_return_pct nominal por encima del umbral pero con + # confianza de clasificación por debajo del piso NO es edge de + # compra real, es una esperanza estadística sin convicción + # suficiente para operarla (ver _action_for_forecast). + if forecast.get("tb_predicted_class") != "TP" or not forecast.get("tb_actionable", False): + continue + elif predicted_return_pct < _LIGHT_BUY_THRESHOLD_PCT: + continue # sin edge de compra real -> nunca candidato a "mejor oportunidad" + + confidence = _confidence_score(forecast) + candidates.append( + { + "symbol": ticker, + "action": _action_for_forecast(forecast), + "predicted_return_pct": predicted_return_pct, + "confidence_score": round(confidence, 4), + "data_reliability": forecast.get("forecast_reliability", "normal"), + "target_mode": forecast.get("target_mode", "regression"), + "tb_probabilities": forecast.get("tb_probabilities"), + } + ) + + candidates.sort( + key=lambda c: c["predicted_return_pct"] * (1 + c["confidence_score"]), + reverse=True, + ) + return candidates[:_ALPHA_SEEKER_MAX_CANDIDATES] + + +async def _scan_universe() -> Tuple[List[Tuple[str, Dict[str, Any]]], Dict[str, Any], Dict[str, Any]]: + """ + Despacha _forecast_asset (síncrona/bloqueante, Keras) para TODO + _RADAR_UNIVERSE vía executor + get_market_sentiment (async, Circuit + Breaker propio) en paralelo — mismo patrón que + quanti_engine._build_investment_plans. + """ + loop = asyncio.get_running_loop() + semaphore = asyncio.Semaphore(_SCAN_CONCURRENCY) + + async def _safe_forecast(ticker: str): + async with semaphore: # FIX 2026-08-15 — ver _SCAN_CONCURRENCY arriba + try: + return await loop.run_in_executor(None, _forecast_asset, ticker, DEFAULT_FORECAST_HORIZON_DAYS) + except Exception as exc: # noqa: BLE001 — un ticker caído no tumba el radar completo + logger.warning("Forecast radar falló para %s: %r", ticker, exc) + return None + + *forecasts, spy_sentiment, btc_sentiment = await asyncio.gather( + *(_safe_forecast(t) for t in _RADAR_UNIVERSE), + _safe_sentiment(PLAN_A_TICKER), + _safe_sentiment("BTC-USD"), + ) + + valid = [ + (ticker, forecast) + for ticker, forecast in zip(_RADAR_UNIVERSE, forecasts) + if forecast is not None and not forecast.get("forecast_incomplete") + ] + return valid, spy_sentiment, btc_sentiment + + +async def generate_predictions(usd_budget: float) -> Dict[str, Any]: + """ + Genera el reporte de predicciones de mercado con inferencia REAL del + especialista Keras V5 correspondiente (equity/crypto, ver + quanti_engine._forecast_asset) — cero mock. Estructura de retorno + intacta para no romper frontend/endpoints existentes. + """ + try: + if usd_budget is None or usd_budget <= 0: + raise ValueError("usd_budget debe ser un valor numérico positivo.") + + valid_forecasts, spy_sentiment, btc_sentiment = await _scan_universe() + if not valid_forecasts: + raise RuntimeError( + "El pipeline Keras/yfinance no devolvió ningún forecast válido " + "para el universo V5 — degradación total del radar." + ) + + # Alpha Seeker: candidatos reales para "Quanti's Choice" — se deriva + # ANTES del sort de abajo (ese sort es para `recommendations`, el + # scanner general de top movers; este es un ranking independiente, + # solo-positivo, para decidir en qué activo invertir Plan B). + top_assets = _rank_alpha_seeker_candidates(valid_forecasts) + + # Ranking por convicción real: edge absoluto ponderado por razón + # señal/ruido (_confidence_score), no solo magnitud del movimiento. + valid_forecasts.sort( + key=lambda item: abs(item[1]["predicted_return_pct"]) * (1 + _confidence_score(item[1])), + reverse=True, + ) + top_candidates = valid_forecasts[:TOP_N_RECOMMENDATIONS] + + recommendations = [] + for ticker, forecast in top_candidates: + allocation_pct = _allocation_pct_for(ticker, forecast) + recommendations.append( + { + "ticker": ticker, + "action": _action_for_forecast(forecast), + "current_price_usd": forecast["last_price"], + "projected_growth_pct": forecast["predicted_return_pct"], + "projected_price_usd": forecast["predicted_price"], + "suggested_allocation_usd": round(usd_budget * allocation_pct, 2), + "suggested_allocation_pct": allocation_pct, + # Transparencia OOD (ver _confidence_score/quanti_engine.py + # real_ood_dampening): "degraded" ya está reflejado en + # suggested_allocation_pct (recortado vía _confidence_score + # más arriba) — estos dos campos son para que el frontend + # explique EL PORQUÉ del recorte, no solo lo aplique en + # silencio. Default "normal"/0.0 para forecasts generados + # antes de este campo (backward-compatible). + "data_reliability": forecast.get("forecast_reliability", "normal"), + "real_data_ood_frac": forecast.get("real_data_ood_frac", 0.0), + # V22 — Triple Barrier: detalle de clasificación real + # (None para equity_specialist/regresión, ver + # quanti_engine._forecast_asset_triple_barrier). El + # frontend puede mostrar P(TP) vs P(SL) directamente + # cuando target_mode="triple_barrier". + "target_mode": forecast.get("target_mode", "regression"), + "tb_probabilities": forecast.get("tb_probabilities"), + "tb_confidence": forecast.get("tb_confidence"), + "tb_actionable": forecast.get("tb_actionable"), + } + ) + + return { + "status": "success", + "generated_at": datetime.now(timezone.utc).isoformat(), + "usd_budget": usd_budget, + "macro_context": _build_macro_context(spy_sentiment, btc_sentiment), + "recommendations": recommendations, + "top_assets": top_assets, + "mae_margin": _derive_mae_margin(top_candidates), + "error": None, + } + + except Exception as exc: + logger.exception("Error generando predicciones en generate_predictions") + return { + "status": "error", + "generated_at": datetime.now(timezone.utc).isoformat(), + "usd_budget": usd_budget, + "macro_context": None, + "recommendations": [], + "top_assets": [], + "mae_margin": _FALLBACK_MAE_MARGIN, + "error": str(exc), + } + + +if __name__ == "__main__": + # Prueba manual: python -m services.prediccion + async def _main() -> None: + result = await generate_predictions(usd_budget=1000.0) + import json + + print(json.dumps(result, indent=2, ensure_ascii=False)) + + asyncio.run(_main()) \ No newline at end of file diff --git a/services/quanti_engine.py b/services/quanti_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..c611cb1026fdb806db65394c5698de9e4d6882c8 --- /dev/null +++ b/services/quanti_engine.py @@ -0,0 +1,5213 @@ +# services/quanti_engine.py +""" +Quanti AI Engine — KodaQuant Terminal +====================================== +Inferencia matemática 100% Keras 3 / TensorFlow NATIVO — carga in-process +del especialista V5 correspondiente al régimen del ticker consultado +(`kodaquant_models/equity_specialist/model_v5.keras` o +`.../crypto_specialist/model_v5.keras`, CERO ONNX Runtime en este proceso) ++ voz generativa vía Groq LPU en la nube (`llama-3.3-70b-versatile`, SDK +oficial `groq`, cliente `AsyncGroq`), con Circuit Breaker a fallback +matemático si la API de Groq no responde. Soporte de inferencia local +(llama.cpp/Metal) retirado permanentemente — ver GROQ_API_KEY más abajo. + +Requisitos locales (Mac): `pip install keras tensorflow scikit-learn pandas +requests httpx transformers torch` — sin re-entrenar nada, sin Colab. Cada +especialista V5 (modelo + `scalers_dict.pkl`) vive en su propia carpeta bajo +`services/kodaquant_models//`, ver `REGIME_TICKERS`/`_regime_for_ticker`. +Datos de mercado vía Twelve Data (API oficial, requiere `TWELVE_DATA_API_KEY`) ++ fallback Stooq — ver `services/market_data.py`; yfinance fue retirado por +completo (bloqueos recurrentes de Yahoo Finance en producción). + +Pipeline de inferencia (replica EXACTA del notebook de entrenamiento): + scalers.pkl (pickle) + -> feature_scalers[ticker] (MinMaxScaler, fit en train) + -> target_scalers[ticker] (StandardScaler sobre log-returns) + -> asset_to_id[ticker] (embedding categórico) + Twelve Data (live) -> engineer_asset() -> ventana (lookback, n_features) + -> feature_scaler.transform() -> tensor (1, lookback, n_features) + keras.Model(..., training=True) -> log-return escalado + -> target_scaler.inverse_transform() -> log-return real (r_hat) + -> P_hat = P_prev * exp(r_hat) (reconstrucción autoregresiva) + +Motor predictivo AUTOREGRESIVO (sliding window). En cada paso del bucle: +(1) la ventana histórica reciente entra al modelo Keras, (2) el modelo +predice el retorno logarítmico de T+1 — con `Dropout(0.4)` MANTENIDO VIVO +vía `training=True` (MC Dropout real, ver `_forecast_asset`) —, (3) ese +log-return se perturba con ruido gaussiano calibrado a la volatilidad +histórica REAL del activo (`VOLATILITY_INJECTION_*`, ver `_forecast_asset`) +cuando la inyección está activa, (4) el precio resultante se anexa al +final de la ventana y el dato más viejo se descarta, (5) se repite hasta +completar `steps`. Con la inyección activa, el path devuelto es señal del +modelo + ruido calibrado con volatilidad real — NO una inferencia 100% +determinista de la red en cada punto; `variance_source` en cada forecast +lo declara explícitamente. Ver `_forecast_asset`. + +La IA generativa (Quanti) SOLO narra los números ya calculados por este +motor (modelo + volatilidad inyectada); tiene prohibido recalcularlos o +inventar cifras adicionales (ver REGLA INQUEBRANTABLE en +_build_system_prompt). + +Contrato dinámico con el Command Center (frontend): + generate_quanti_strategy() acepta analysis_mode / target_asset + (selección de activo), forecast_horizon_days (horizonte de + proyección) y risk_profile / risk_score (perfil de riesgo). El + `risk_score` (0-100) es ahora la ÚNICA fuente de verdad matemática + del split Plan A / Plan B — ver `_resolve_risk_split`. `risk_profile` + queda como etiqueta narrativa/contextual, no participa en el cálculo. + +V15 (consolidación del core, auditoría CTO 2026-08-16): este archivo ahora +importa `services/kodaquant_core.py` -- el mismo módulo que +`train_kodaquant_v5.py` usa para caché/FRED/alineación de calendario +macro -- consolidando ambos pipelines sobre una única base de código. La +ingesta en vivo (`fetch_feature_ohlcv`, `_fetch_feature_window`) y el NLP +de sentimiento (`services.data_pipeline.get_daily_news_sentiment`, ahora +con caché propia vía `CacheManager`) quedan sin cambios de comportamiento +-- cero riesgo sobre el motor de forecast en producción. +""" + + +import asyncio +import json +import math +import os +import pickle +import re +import hashlib +import threading +import time +import traceback +import logging +from datetime import datetime, timezone, timedelta +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import TYPE_CHECKING, Any, AsyncGenerator, Optional + +logger = logging.getLogger("kodaquant.quanti_engine") +# FIX REAL (el motivo de que ningún logger.info se viera en terminal): +# ni este módulo ni main.py llamaban a logging.basicConfig() — el root +# logger de Python queda en WARNING por defecto, así que TODO logger.info() +# (el tuyo y el mío) se silenciaba en el "handler de último recurso" sin +# excepción ni rastro. print() sí aparecía porque ignora por completo el +# nivel de logging — de ahí que vieras std(cursor_prices) pero nunca la +# auditoría dual-head. Idempotente: si algo más arriba en el stack (uvicorn, +# gunicorn) ya configuró el root logger, basicConfig() es un no-op y no lo +# pisa. +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s", +) +logger.setLevel(logging.INFO) + +# --- PARCHE HuggingFace tokenizers: deadlock en el fork de Uvicorn -------- +# `transformers` (cargado perezosamente por `_get_finbert_pipeline` en +# services/data_pipeline.py) trae un tokenizer Rust que paraleliza con su +# propio pool de hilos. Bajo un worker de Uvicorn que hace fork DESPUÉS de +# que ese pool ya se inicializó en el proceso padre (o bajo llamadas +# concurrentes vía ThreadPoolExecutor, mismo patrón que +# `_finbert_init_lock` en data_pipeline.py), el pool nativo puede quedar en +# un estado inconsistente tras el fork y colgar el proceso. Debe fijarse +# ANTES de cualquier import que pueda cargar `tokenizers` transitivamente — +# por eso vive aquí (tras `import os`, antes de `from services.data_pipeline +# import get_daily_news_sentiment` más abajo) y no dentro de data_pipeline.py. +os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") +# ------------------------------------------------------------------------- + +import numpy as np +import pandas as pd +import requests # AUDITORÍA RESCATE 2026-08 — Fear&Greed/Binance funding/blockchain.info (ver TECH_COLS nuevo) + +# --- Proveedor de datos de mercado: Twelve Data (API oficial, gratuita) + +# Stooq (fallback sin key) -- yfinance y el pool de proxies fueron +# RETIRADOS por completo (bloqueos recurrentes de Yahoo Finance / "Proxy +# CONNECT aborted" en producción). Toda la lógica de red, rate limiting, +# caché en disco y mapeo de símbolos vive ahora en services/market_data.py +# -- este archivo solo importa las dos funciones públicas que necesita. +# Ver ese módulo para el detalle completo de la migración. +from services.market_data import fetch_feature_ohlcv, fetch_close_history, DEFAULT_HISTORY_SESSIONS + +# --- kodaquant_core (CONSOLIDACIÓN DEL CORE, Directiva 1/3) ----------------- +# Mismo núcleo (CacheManager/FredClient/alineación de calendario macro) que +# ahora importa `train_kodaquant_v5.py` -- este proceso de inferencia lo +# importa acá para que ambos lados queden sobre la MISMA base de código, +# aunque hoy `services/market_data.py` siga resolviendo su propio caché/FRED +# inline (ver nota de migración pendiente en el docstring de +# `kodaquant_core.py`). Nunca se usa `services.kodaquant_core` para +# recalcular nada que `market_data.py` ya resuelva -- solo se deja +# disponible como próximo punto de enganche cuando ese módulo migre. +from services.kodaquant_core import CacheManager, FredClient # noqa: F401 +# V28 -- MISMA implementación que ml_engine/free_alpha.py (copia idéntica). +from services import free_alpha as _free_alpha # noqa: E402 +from services.free_alpha import ( # noqa: E402 + V28_COLS, V28_CRYPTO_COLS, V28_EQUITY_COLS, + build_crypto_flow_features, compute_equity_open_features, +) + +_V28_CACHE_UTC_DAY: Optional[str] = None + + +def _v28_flush_cache_on_utc_rollover() -> None: + """La caché en RAM de free_alpha (TTL 6h) puede retener la vela PARCIAL del día D + si se pobló antes de las 00:00 UTC; al rotar el día UTC se descarta para que la + última fila consolidada use el taker-volume completo (paridad con train).""" + global _V28_CACHE_UTC_DAY + today = datetime.now(timezone.utc).strftime("%Y-%m-%d") + if _V28_CACHE_UTC_DAY != today: + _free_alpha._MEM_CACHE.clear() + _V28_CACHE_UTC_DAY = today + + +from groq import ( + AsyncGroq, + APIConnectionError as GroqAPIConnectionError, + APIStatusError as GroqAPIStatusError, + AuthenticationError as GroqAuthenticationError, + RateLimitError as GroqRateLimitError, +) + +# --------------------------------------------------------------------------- +# Alias de tipo SOLO para el type checker (Pylance). El símbolo `keras` de +# abajo es una variable de runtime reasignada dentro de un try/except (puede +# apuntar a `keras` standalone o a `tensorflow.keras` según el entorno) — +# Pylance no puede tratar una variable así como un módulo real del que +# extraer `.Model` en una anotación de tipo (`reportInvalidTypeForm`). Este +# bloque, evaluado únicamente por el type checker (TYPE_CHECKING es False en +# runtime), le da a Pylance un import ESTÁTICO real desde el que resolver +# `KerasModel`, totalmente desacoplado de la lógica dinámica de carga. +# --------------------------------------------------------------------------- +if TYPE_CHECKING: + from keras import Model as KerasModel +else: + KerasModel = Any + +# --------------------------------------------------------------------------- +# Import de Keras 3 A PRUEBA DE BALAS (TF 2.16+ / Python 3.12 / venv macOS). +# +# `from keras import layers` puede reventar con +# "ImportError: cannot import name 'layers' from 'keras' (unknown location)" +# cuando el símbolo `keras` resuelto por Python es un namespace package roto +# (0 bytes / sin __init__.py real) en vez del paquete instalado — un +# `import keras` desnudo NO lanza error en ese caso, solo falla al pedirle +# un atributo. Por eso accedemos vía `keras.layers` (atributo), no vía +# `from keras import layers` (import con nombre), y con try/except real en +# vez de asumir que el primer camino siempre funciona. +# +# Fallback: `tensorflow.keras` (shim oficial hacia el mismo Keras 3 en +# TF>=2.16). Si AMBOS caminos fallan, es un entorno con tensorflow/keras +# incompletos o desalineados — fallamos ruidosamente con el fix exacto en +# vez de dejar un ImportError críptico más abajo en el archivo. +_keras_primary_error: Exception | None = None +keras = None +layers = None + +try: + # Debe fijarse ANTES del primer `import keras` — Keras 3 resuelve el + # backend al importarse. El notebook de entrenamiento corrió sobre + # backend TensorFlow (Colab estándar); fijamos el mismo backend + # explícitamente en vez de asumir el default del entorno. + os.environ.setdefault("KERAS_BACKEND", "tensorflow") + os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3") # silencia el ruido de logs de TF en consola + + import keras as _keras_standalone + _ = _keras_standalone.layers # fuerza la resolución real del atributo, no solo el import del nombre + keras = _keras_standalone + layers = _keras_standalone.layers +except Exception as exc: # noqa: BLE001 — namespace package roto no siempre lanza ImportError "limpio" + _keras_primary_error = exc + +if keras is None or layers is None: + try: + import tensorflow as tf + _ = tf.keras.layers # idem: confirma el atributo antes de darlo por bueno + keras = tf.keras + layers = tf.keras.layers + except Exception as exc2: # noqa: BLE001 + raise ImportError( + "No se pudo cargar Keras 3 en este entorno (ni `keras` standalone " + "ni el shim `tensorflow.keras`). En tu venv (macOS / Python 3.12) " + "reinstala ambos paquetes EMPAREJADOS y en ese orden:\n" + " pip uninstall -y keras tensorflow tf-keras tensorflow-macos tensorflow-metal\n" + " pip install --upgrade 'tensorflow>=2.16,<3' 'keras>=3,<4'\n" + f"Fallo #1 (import keras / keras.layers): {_keras_primary_error!r}\n" + f"Fallo #2 (import tensorflow / tensorflow.keras): {exc2!r}" + ) from exc2 + +# --------------------------------------------------------------------------- +# CAUSA RAÍZ DEL SILENT HANG — Metal/GPU despachado desde un hilo que no es +# el principal. `_build_mc_dropout_bridge` fue auditado nodo por nodo contra +# la topología real de `equity_specialist` (MHA 8h/128u + bloque residual +# extra) reconstruyendo el grafo en un entorno de control: el recorrido +# `node.arguments.fill_in()` termina limpio, sin recursión sin cota y sin +# excepción — NO es la causa. La causa real: en este proceso, absolutamente +# TODA inferencia Keras (la verificación de `_verify_stochastic_variance` Y +# cada paso del bucle MC Dropout de `_forecast_asset`) corre exclusivamente +# dentro de `loop.run_in_executor(None, _forecast_asset, ...)` — un hilo de +# `ThreadPoolExecutor`, nunca el hilo principal (ver `_build_investment_plans` +# más abajo). Con `tensorflow-metal` instalado (macOS, ver bloque de arriba), +# TensorFlow detecta y usa el GPU Metal por defecto; despachar el PRIMER +# kernel Metal de un modelo desde un hilo secundario es un deadlock conocido +# y documentado del plugin `tensorflow-metal` (el command queue de Metal no +# es re-entrante de forma segura entre hilos para ese primer dispatch) — no +# lanza excepción, solo cuelga el proceso para siempre, exactamente el +# síntoma reportado: "[ARTIFACT LOAD]" se imprime (CPU, antes de tocar el +# grafo) y después silencio total. Como hay UN solo dispositivo GPU +# compartido por proceso, un solo hilo atascado ahí bloquea cualquier otra +# inferencia Keras subsiguiente — de ahí que "cuelgue el servidor" entero +# para datos en vivo y predicciones, no solo esa request puntual. +# +# FIX — CERO ambigüedad, CERO dependencia del hilo que dispare la primera +# llamada: se fuerza CPU-only ANTES de que exista un solo `keras.Input` o +# `model.load()` en el proceso (acá, inmediatamente tras resolver el import +# de Keras/TensorFlow, antes de que cualquier otro código del módulo pueda +# tocar un tensor). `set_visible_devices([], "GPU")` debe correr antes de +# que TensorFlow inicialice su lista de dispositivos — si corriera más tarde +# (ej. dentro de `_get_keras_model`), ya sería tarde para una llamada +# concurrente que arrancó antes. Modelo objetivo (128 unidades, batch de +# Monte Carlo ~100 filas): CPU resuelve un forward pass en milisegundos — +# cero costo real de rendimiento a cambio de eliminar la clase ENTERA de +# deadlocks de GPU/threading, nativo (sin librerías nuevas), agnóstico a la +# topología de cualquiera de los dos especialistas. +try: + import tensorflow as _tf_device_guard + _tf_device_guard.config.set_visible_devices([], "GPU") + logging.getLogger("kodaquant.quanti_engine").info( + "[DEVICE GUARD] GPU (Metal/CUDA) deshabilitada — inferencia Keras fijada a CPU " + "(mitigación de hang de threading en tensorflow-metal; ver docstring de este bloque)." + ) +except Exception as _device_guard_exc: # noqa: BLE001 — nunca tumbar el arranque por esto + logging.getLogger("kodaquant.quanti_engine").warning( + "[DEVICE GUARD] No se pudo forzar CPU-only en TensorFlow (%r) — si el proceso " + "corre con tensorflow-metal y cuelga tras '[ARTIFACT LOAD]', esta es la causa.", + _device_guard_exc, + ) +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# [ZERO GPU BUDGET] — Hugging Face Spaces free tier (CPU-only, 2 vCPU / 16GB +# compartidos) sin este guard TensorFlow por defecto abre un pool de hilos +# intra/inter-op dimensionado a `os.cpu_count()` REAL del host físico del +# contenedor (a veces reportado >2 en Spaces pese a la cuota real asignada, +# ver issues públicos de HF), sobre-suscribiendo CPU y degradando latencia +# por contención de hilos en vez de por trabajo real — mismo síntoma con el +# que ya lidia `_KERAS_CALL_TIMEOUT_SECONDS` más abajo, pero atacado en la +# causa en vez del síntoma. Debe fijarse ANTES del primer op de TF (mismo +# requisito de ordenamiento que `set_visible_devices` arriba) — por eso vive +# en el mismo bloque, nunca dentro de `_get_keras_model`. Configurable vía +# env var para correr sin este techo en el Mac local (`KODAQUANT_TF_THREADS` +# no seteada -> default conservador de 2, seguro tanto en el tier gratuito +# de Spaces como en un i7 de 4-8 hilos). +try: + _tf_thread_budget = max(1, int(os.environ.get("KODAQUANT_TF_THREADS", "2"))) + _tf_device_guard.config.threading.set_intra_op_parallelism_threads(_tf_thread_budget) + _tf_device_guard.config.threading.set_inter_op_parallelism_threads(_tf_thread_budget) + logging.getLogger("kodaquant.quanti_engine").info( + "[ZERO GPU BUDGET] TF intra/inter-op threads fijados a %d (KODAQUANT_TF_THREADS).", + _tf_thread_budget, + ) +except Exception as _thread_guard_exc: # noqa: BLE001 — nunca tumbar el arranque por esto + logging.getLogger("kodaquant.quanti_engine").warning( + "[ZERO GPU BUDGET] No se pudo acotar el pool de hilos de TF (%r) — probablemente " + "una op de TF ya corrió antes de este bloque (import circular / reload de módulo). " + "No es fatal, solo pierde la optimización de CPU.", + _thread_guard_exc, + ) +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# Configuración — rutas y endpoints +# --------------------------------------------------------------------------- + +# Resolución de rutas ANCLADA al propio archivo (no al cwd del proceso que +# arranca el servidor) — `attention_bilstm_global.keras` y `scalers.pkl` +# viven en la MISMA carpeta que este módulo (ej. backend/services/). +_THIS_DIR = os.path.dirname(os.path.abspath(__file__)) + +# V5: persistencia segregada por régimen (ver train_kodaquant_v5.py, +# Requerimiento 3) — reemplaza el modelo global único V4. +MODELS_ROOT = Path(_THIS_DIR) / "kodaquant_models" +REGIME_TICKERS: dict[str, tuple[str, ...]] = { + "equity_specialist": ("AAPL", "MSFT", "NVDA", "TSLA", "GOOGL", "AMZN", "META", "SPY"), + "crypto_specialist": ("BTC-USD", "ETH-USD"), +} + + +def _regime_for_ticker(ticker: str) -> str: + """Resuelve a qué especialista V5 pertenece un ticker. Falla ruidosamente si no está en ningún régimen conocido.""" + normalized = ticker.strip().upper() + for regime_name, tickers in REGIME_TICKERS.items(): + if normalized in tickers: + return regime_name + raise ValueError( + f"'{ticker}' no pertenece a ningún régimen V5 conocido " + f"({list(REGIME_TICKERS)}) — no hay .keras/scalers_dict.pkl que lo cubra." + ) + + +def _model_path(regime: str) -> str: + return str(MODELS_ROOT / regime / "model_v5.keras") + + +def _scalers_path(regime: str) -> Path: + return MODELS_ROOT / regime / "scalers_dict.pkl" + + +# data_pipeline.py vive junto a este módulo en services/ — provee +# get_daily_news_sentiment() (FinBERT + Finnhub/yfinance.news), la MISMA +# fuente de NEWS_SENTIMENT_SCORE que entrenó los especialistas V5. +from services.data_pipeline import get_daily_news_sentiment # noqa: E402 + +# Fallback defensivo únicamente. El valor real de cada request viaja en +# `forecastHorizonDays` desde el Command Center y pasa por +# `_resolve_horizon_days()` antes de tocar el motor Keras. +DEFAULT_FORECAST_HORIZON_DAYS = 5 +PLAN_A_TICKER = "SPY" # Reserva — activo ancla de baja volatilidad + +# --- V6: TECH_COLS — fuente de verdad ÚNICA del orden de columnas técnicas +# del tensor de N_FEATURES = 1 + len(TECH_COLS) + len(macro_tickers) features +# (LOG_RETURN_1D + técnicos + macro; 24 tras la auditoría 2026-08 -- ver +# bloque de constantes nuevas más abajo, NUNCA hardcodear este número en un +# comentario, esa fue la causa raíz real de la desalineación auditada). DEBE +# coincidir EXACTO (mismo orden Y misma definición matemática) con TECH_COLS +# en train_kodaquant_v5.py — el feature_scaler cargado desde +# scalers_dict.pkl fue ajustado con ESTE orden/definición, así que +# desalinearlo acá desplazaría cada columna en silencio dentro de +# feature_scaler.transform(). Se valida contra scalers["tech_cols"] en +# `_get_scalers()` (ver más abajo), para fallar ruidosamente antes de la +# primera inferencia en vez de producir un forecast matemáticamente +# incorrecto sin ninguna excepción visible. +# +# MIGRACIÓN A ESTACIONARIEDAD ESTRICTA (Reinicio Estructural): "PRICE" +# (nivel absoluto) se eliminó del tensor — ver LOG_RETURN_1D más abajo en +# `_fetch_feature_window`. EMA_20/MACD/MACD_SIGNAL/ATR_14/OBV (los 5 +# técnicos NO auto-acotados, ver auditoría SOFT_CLIP_MARGIN abajo) se +# re-expresan como razones adimensionales invariantes a escala — +# EMA20_DEV_PCT, MACD_PCT, MACD_SIGNAL_PCT, ATR_PCT, OBV_ROC_20. RSI_14 / +# BB_WIDTH_20 / ADX_14 / STOCH_K_14 / SENTIMENT_SCORE / NEWS_SENTIMENT_SCORE +# quedan idénticos (ya acotados/adimensionales por construcción). +# AUDITORÍA RESCATE 2026-08 — DESALINEACIÓN CRÍTICA ENCONTRADA Y CORREGIDA: +# esta lista tenía 11 columnas (V6, pre-V23.5/V24) mientras que +# train_kodaquant_v5.py ya entrena con 18 (agregó FEAR_GREED_INDEX/ +# FUNDING_RATE_ZSCORE/ONCHAIN_ACTIVITY_ROC/FRAC_DIFF_LOG_CLOSE/ +# PUELL_MULTIPLE_ZSCORE en V23.5/V24, y PARKINSON_VOL_ZSCORE/ +# VOL_OF_VOL_ZSCORE en la auditoría 2026-08). `_get_scalers()` ya valida +# `saved_tech_cols == TECH_COLS` y falla ruidosamente ante cualquier +# desalineación (ver más abajo) — con la lista vieja, CUALQUIER +# scalers_dict.pkl generado por el train_kodaquant_v5.py actual bloqueaba +# el arranque de este motor de inferencia. Sincronizado 1:1, mismo orden. +TECH_COLS = ["RSI_14", "EMA20_DEV_PCT", "MACD_PCT", "MACD_SIGNAL_PCT", "SENTIMENT_SCORE", + "ATR_PCT", "BB_WIDTH_20", "OBV_ROC_20", "ADX_14", "STOCH_K_14", + "NEWS_SENTIMENT_SCORE", "FEAR_GREED_INDEX", + "FUNDING_RATE_ZSCORE", "ONCHAIN_ACTIVITY_ROC", "FRAC_DIFF_LOG_CLOSE", + "PUELL_MULTIPLE_ZSCORE", "PARKINSON_VOL_ZSCORE", "VOL_OF_VOL_ZSCORE", + "FUNDING_RATE_MOMENTUM_ZSCORE", "AMIHUD_ILLIQUIDITY_ZSCORE", + "GARMAN_KLASS_VOL_ZSCORE", "FIB_GAP_Z_20", "FIB_GAP_Z_50", + "OFI_PROXY_ZSCORE", "RETURN_ENTROPY_ZSCORE"] + list(V28_COLS) +# V28 -- 25 base + 8 (V28_COLS, importado de free_alpha: idéntico a train por +# construcción) = 33 TECH_COLS -> N_FEATURES = 1 + 33 + 5 macro = 39. Sin +# NEWS_SENTIMENT_SCORE (gate de train): 32 / 38, adoptado desde el pkl por +# `_get_scalers()`. La forma final se valida contra `feature_scaler.n_features_in_` +# al final de `_fetch_feature_window`. +if 1 + len(TECH_COLS) + 5 != 39: + raise ImportError(f"[V28] TECH_COLS={len(TECH_COLS)} -> N_FEATURES={1 + len(TECH_COLS) + 5} != 39.") +# RE-VERIFICACIÓN 2026-08-31 (auditoría rescate, Directiva "sincronizar +# fetchers/TECH_COLS-N_FEATURES") -- diff línea por línea contra TECH_COLS +# en train_kodaquant_v5.py: 18 columnas, MISMO orden, MISMOS 7 fetchers/ +# compute_* de alpha cripto (FEAR_GREED_INDEX, FUNDING_RATE_ZSCORE vía +# Binance funding asimétrico, ONCHAIN_ACTIVITY_ROC vía NVT Ratio Z-score, +# FRAC_DIFF_LOG_CLOSE, PUELL_MULTIPLE_ZSCORE, PARKINSON_VOL_ZSCORE, +# VOL_OF_VOL_ZSCORE) ya presentes y replicados 1:1 (mismas constantes de +# ventana/clip, mismo criterio 0.0-neutro fuera de cripto/BTC) en ambos +# archivos -- CERO desalineación encontrada, CERO cambio funcional +# requerido en este módulo. `N_FEATURES` (derivado, no hardcodeado) sigue +# idéntico en ambos lados por construcción. +OBV_ROC_LOOKBACK_DAYS = 20 # DEBE calzar con OBV_ROC_LOOKBACK_DAYS en train_kodaquant_v5.py +OBV_ROC_CLIP = 3.0 # ±300% — DEBE calzar con OBV_ROC_CLIP en train_kodaquant_v5.py + +# --- V23.5/V24/auditoría 2026-08 — réplica EXACTA de las constantes de +# train_kodaquant_v5.py para las 7 columnas nuevas de TECH_COLS arriba. +# Mismos valores, mismas fórmulas — cualquier divergencia numérica acá +# desalinearía la inferencia contra un feature_scaler ajustado con los +# valores de entrenamiento (ver docstring de módulo, "replica EXACTA"). +CRYPTO_TICKERS_V5 = ("BTC-USD", "ETH-USD") # DEBE calzar con REGIMES["crypto_specialist"]["tickers"] +BTC_TICKER_V5 = "BTC-USD" + +FUNDING_ZSCORE_WINDOW_DAYS = 90 +FUNDING_ZSCORE_MIN_PERIODS = 20 +FUNDING_ZSCORE_CLIP = 5.0 +# AUDITORÍA RESCATE 2026-08 -- réplica EXACTA de la restructuración asimétrica +# de train_kodaquant_v5.py (ver docstring de módulo ahí, bloque +# FUNDING_ZSCORE_ASYM_*). Mismos valores -- cualquier divergencia numérica +# acá desalinearía inferencia vs. el feature_scaler ajustado en train. +FUNDING_ZSCORE_ASYM_POS_GAMMA = 1.35 +FUNDING_ZSCORE_ASYM_NEG_GAMMA = 0.85 +BINANCE_FAPI_FUNDING_URL = "https://fapi.binance.com/fapi/v1/fundingRate" +BINANCE_FUNDING_SYMBOL_MAP = {"BTC-USD": "BTCUSDT", "ETH-USD": "ETHUSDT"} + +ONCHAIN_CHART_NAME = "n-transactions" +ONCHAIN_ROC_LOOKBACK_DAYS = 7 +ONCHAIN_ROC_CLIP = 3.0 +BLOCKCHAIN_INFO_CHART_URL = "https://api.blockchain.info/charts/{chart}" +# AUDITORÍA RESCATE 2026-08 -- réplica EXACTA de la restructuración NVT Ratio +# de train_kodaquant_v5.py (ver docstring de módulo ahí, bloque "V25"). +ONCHAIN_TX_VALUE_CHART_NAME = "estimated-transaction-volume-usd" +NVT_ZSCORE_WINDOW_DAYS = 365 +NVT_ZSCORE_MIN_PERIODS = 60 +NVT_ZSCORE_CLIP = 5.0 + +FRAC_DIFF_D_GRID = tuple(round(float(d), 2) for d in np.arange(0.10, 1.01, 0.10)) +FRAC_DIFF_ADF_PVALUE_MAX = 0.05 +FRAC_DIFF_THRESH = 1e-4 +FRAC_DIFF_DEFAULT_D = 0.40 + +BTC_HALVING_SCHEDULE: tuple[tuple[datetime, float], ...] = ( + (datetime(2009, 1, 3, tzinfo=timezone.utc), 50.0), + (datetime(2012, 11, 28, tzinfo=timezone.utc), 25.0), + (datetime(2016, 7, 9, tzinfo=timezone.utc), 12.5), + (datetime(2020, 5, 11, tzinfo=timezone.utc), 6.25), + (datetime(2024, 4, 20, tzinfo=timezone.utc), 3.125), + (datetime(2028, 4, 1, tzinfo=timezone.utc), 1.5625), +) +BTC_BLOCKS_PER_DAY = 144.0 +PUELL_MA_WINDOW_DAYS = 365 +PUELL_MA_MIN_PERIODS = 30 +PUELL_ZSCORE_WINDOW_DAYS = 365 +PUELL_ZSCORE_MIN_PERIODS = 60 +PUELL_ZSCORE_CLIP = 5.0 + +PARKINSON_VOL_LOOKBACK_DAYS = 20 +PARKINSON_VOL_ZSCORE_WINDOW_DAYS = 60 +PARKINSON_VOL_ZSCORE_MIN_PERIODS = 20 +PARKINSON_VOL_ZSCORE_CLIP = 5.0 +VOL_OF_VOL_LOOKBACK_DAYS = 20 +VOL_OF_VOL_ZSCORE_WINDOW_DAYS = 60 +VOL_OF_VOL_ZSCORE_MIN_PERIODS = 20 +VOL_OF_VOL_ZSCORE_CLIP = 5.0 + +# --- V27 — réplica EXACTA de las constantes de train_kodaquant_v5.py. +# Cualquier divergencia numérica acá desalinea la inferencia contra un +# feature_scaler ajustado con los valores de entrenamiento. +GK_VOL_LOOKBACK_DAYS = 20 +GK_ZSCORE_WINDOW_DAYS = 60 +GK_ZSCORE_MIN_PERIODS = 20 +GK_ZSCORE_CLIP = 5.0 + +FIB_WINDOWS = (20, 50) +FIB_RATIOS = (0.382, 0.500, 0.618, 1.272) +FIB_ZSCORE_WINDOW_DAYS = 120 +FIB_ZSCORE_MIN_PERIODS = 30 +FIB_ZSCORE_CLIP = 5.0 + +OFI_LOOKBACK_DAYS = 10 +OFI_ZSCORE_WINDOW_DAYS = 90 +OFI_ZSCORE_MIN_PERIODS = 30 +OFI_ZSCORE_CLIP = 5.0 + +ENTROPY_WINDOW_DAYS = 30 +ENTROPY_SIGMA_LOOKBACK = 60 +ENTROPY_DEADZONE_SIGMA = 0.25 +ENTROPY_ZSCORE_WINDOW_DAYS = 120 +ENTROPY_ZSCORE_MIN_PERIODS = 30 +ENTROPY_ZSCORE_CLIP = 5.0 + +try: + from statsmodels.tsa.stattools import adfuller as _adfuller +except ImportError: # pragma: no cover + _adfuller = None + logger.warning( + "statsmodels no instalado — FRAC_DIFF_LOG_CLOSE usará FRAC_DIFF_DEFAULT_D=%.2f fijo " + "en vez de calibrar 'd' vía ADF (ver train_kodaquant_v5.py:find_min_ffd_d).", + FRAC_DIFF_DEFAULT_D, + ) + +# --- Inyección de Volatilidad Estocástica (post inverse_transform) -------- +# El log-return que sale del modelo (`r_hat`, ya en escala real) se +# perturba, EN CADA PASO del bucle autoregresivo, con ruido gaussiano +# `N(0, (VOLATILITY_INJECTION_FACTOR * sigma_hist)^2)`, donde `sigma_hist` +# es la desviación estándar de los log-returns REALES de los últimos +# `VOLATILITY_LOOKBACK_DAYS` (la volatilidad realizada del propio activo, +# no un número inventado). Esto ocurre DESPUÉS de `inverse_transform` — el +# ruido nunca toca el tensor de entrada del modelo (`scaled_window`), así +# que no hay riesgo de romper shapes ni el pipeline de escalado. +# NOTA DE HONESTIDAD: esto hace que el path proyectado sea, en parte, una +# simulación estocástica calibrada con volatilidad histórica real — no una +# inferencia 100% determinista de la red en cada punto. `variance_source` +# lo refleja explícitamente para que el frontend/LLM no lo presenten como +# "predicción pura del modelo" sin matices. +VOLATILITY_INJECTION_ENABLED = True +VOLATILITY_INJECTION_FACTOR = 0.85 # escala de sigma_hist inyectada por paso +VOLATILITY_LOOKBACK_DAYS = 63 # ~3 meses bursátiles para estimar sigma_hist + +# --- Cinturón de seguridad contra el "tobogán" (colapso direccional) ------ +# La fuga autorregresiva documentada arriba (RSI/EMA/MACD/ATR/BB/OBV/ADX/ +# STOCH sintéticos alejándose del rango de entrenamiento paso a paso) tiene +# un clip de ENTRADA (`np.clip(scaled_windows, 0.0, 1.0)`, ver bucle más +# abajo) que evita que el tensor escalado se vaya a infinito — pero NO +# evita que, una vez el tensor queda pegado en 0.0/1.0 (una región fuera +# de distribución que el modelo nunca vio en train), la RED responda con +# un retorno sesgado sistemáticamente en una sola dirección en cada paso +# restante. Con ruido gaussiano genuino de por medio (`noise_batch` más +# abajo) eso normalmente se disimula como textura día-a-día real; pero si +# el sesgo del modelo (`r_hat_model_batch`) es mucho más grande que ese +# ruido, la señal domina y el path se ve casi como una línea recta — un +# retorno diario sostenido fuera de cualquier rango estadísticamente +# plausible para el activo (ej. SPY perdiendo ~15% en 5 sesiones). +# +# MODEL_SIGNAL_CLIP_SIGMAS acota la SEÑAL del modelo — no el ruido, no el +# precio final — a un múltiplo de `sigma_hist` (la volatilidad diaria REAL +# del propio activo, ya calculada más abajo). Un movimiento diario de 5 +# desviaciones estándar ya es un evento de cola extremo (p < 1e-6 bajo +# normalidad); nada que el modelo prediga más allá de eso es señal +# genuina, es el artefacto de fuga descrito. El ruido de volatilidad +# inyectada actúa DESPUÉS de este clip y sigue sin tocarse, así que el +# ancho real del cono P5-P95 y la textura diaria del `sample_path` no se +# ven artificialmente comprimidos — solo se corta la cola sesgada del +# propio modelo, no la varianza real de la simulación. +MODEL_SIGNAL_CLIP_SIGMAS = 5 + +# --- Soft-clip del tensor escalado (reemplaza el hard np.clip de entrada) -- +# DIAGNÓSTICO (auditoría step T+5): `np.clip(scaled_windows, 0.0, 1.0)` corta +# la fuga autorregresiva (evita extrapolación sin límite del MinMaxScaler), +# pero PINEA cualquier valor fuera de rango exactamente en 0.0 o 1.0. Cuando +# la fracción de features pineados sube a 40-50% en los últimos pasos +# (indicadores no acotados por diseño — EMA_20/ATR_14/OBV/BB_WIDTH/MACD, +# todos derivados de `cursor_prices` y por tanto atados al nivel de precio, +# a diferencia de RSI_14/STOCH_K_14 que son osciladores naturalmente +# acotados a [0,100]), trayectorias con divergencias MUY distintas en +# espacio real terminan produciendo el MISMO tensor de entrada (idéntico +# 0.0/1.0 repetido) -> la red ya no puede diferenciarlas -> `r_hat_model_batch` +# converge al mismo valor para todas ellas. La varianza de PRECIO sigue viva +# (la inyecta `noise_batch`, ver más abajo, que actúa después y en espacio +# real), pero la textura que aporta la propia red (su respuesta direccional +# a "qué tan sobrecomprado/sobrevendido" está cada trayectoria) se aplana: +# eso es la pérdida de textura reportada, no un fallo del Monte Carlo en sí. +# +# FIX: soft-clip en vez de hard-clip. Dentro de [0, 1] es la función +# IDENTIDAD exacta (cero cambio de comportamiento para el caso normal, donde +# la inmensa mayoría de los features cae dentro del rango de entrenamiento). +# Fuera de [0, 1], en vez de pinear, comprime el excedente con tanh hacia una +# banda estrecha (1 ± SOFT_CLIP_MARGIN) que el modelo NUNCA vio en train, +# pero de forma estrictamente monótona e inyectiva: dos valores distintos +# fuera de rango YA NO colapsan al mismo escalar, así que la red conserva +# sensibilidad direccional incluso en la cola. La función es C¹-continua en +# los empalmes x=0 y x=1 (la derivada de tanh((x-1)/m) en x=1 vale 1/m·m=1, +# igual que la pendiente de la identidad), así que no hay discontinuidad de +# pendiente que el modelo pueda "ver" como un artefacto numérico. +SOFT_CLIP_MARGIN = 0.05 # banda de overshoot permitida: salida ∈ (-0.05, 1.05) + + +def _soft_clip_unit_interval(x: np.ndarray, margin: float = SOFT_CLIP_MARGIN) -> np.ndarray: + """ + Soft-clip vectorizado a [0, 1] con overflow comprimido por tanh en vez de + pineado duro. Identidad estricta dentro de [0, 1]; fuera de rango, + monótono e inyectivo (nunca dos entradas distintas colapsan al mismo + valor de salida), a diferencia de `np.clip`. Ver bloque SOFT_CLIP_MARGIN + arriba para el razonamiento completo. + """ + below = x < 0.0 + above = x > 1.0 + out = x + out = np.where(below, margin * np.tanh(x / margin), out) + out = np.where(above, 1.0 + margin * np.tanh((x - 1.0) / margin), out) + return out.astype(x.dtype, copy=False) + + +# --- Anchor-pull + decay de señal (estabilizador anti "Autoregressive Drift") --- +# SÍNTOMA POST-SOFT-CLIP: al dejar de pinear en 0.0/1.0, el tensor de entrada +# ya no oculta la deriva progresiva de los indicadores sintéticos — lo cual +# arregló la textura, pero destapó un problema DISTINTO y preexistente: nada +# en el bucle empujaba esos indicadores (EMA_20/EMA_fast/EMA_slow/ +# MACD_SIGNAL/ATR_14/OBV/BB_WIDTH_20 — los TECH_COLS no auto-acotados por su +# propia fórmula; RSI/STOCH_K/ADX/SENTIMENT SÍ lo están, ver auditoría en el +# bloque SOFT_CLIP_MARGIN) de vuelta hacia el último estado REAL conocido. Si +# el modelo responde a "técnicos cada vez peores" con retornos cada vez más +# negativos (patrón de momentum perfectamente legítimo que puede haber +# aprendido de datos reales), el ciclo se retroalimenta: precio baja -> +# EMA/ATR empeoran -> modelo predice una baja aún mayor -> se repite. Con +# `cursor_prices = cursor_prices * np.exp(r_hat_batch)` (compounding +# multiplicativo correcto, NO es un bug — así se reconstruye precio desde +# log-retornos) ese sesgo por-paso se acumula geométricamente: un sesgo +# COMPARTIDO por las 100 trayectorias (no ruido i.i.d. real) explica que el +# síntoma reportado no sea solo P5 cayendo (cola pesimista esperable) sino +# P95 cayendo también — la MEDIA del batch se está desplazando, no solo su +# dispersión. +# +# CALIBRACIÓN — GAP ENCONTRADO (auditoría T+5, colapso a -14% con P95 +# desplomándose PESE a ANCHOR_RETENTION/SIGNAL_DECAY_BASE ya activos): el +# bloque de soft-clip arriba ya identificaba a OBV y BB_WIDTH_20 como +# indicadores atados al nivel de precio y no auto-acotados — pero el +# anchor-pull nunca se aplicaba a `obv_arr`/`bb_width_arr` en el bucle, solo +# a EMA/MACD_SIGNAL/ATR. Es la brecha más plausible para un sesgo COMPARTIDO +# entre las 100 trayectorias tan temprano como T+5: `obv_arr` es una SUMA +# ACUMULADA (`obv_arr = obv_arr + sign(Δprecio) * volume_proxy`, ver bucle +# más abajo) sin ningún término de reversión propio — a diferencia de una +# EWM (que ya se amortigua sola, solo más lento), una racha de +# `direction_arr` con el mismo signo en la mayoría de las trayectorias (la +# consecuencia esperable de una señal direccional compartida y aún poco +# decaída en los primeros pasos) empuja a `obv_arr` fuera de rango de forma +# monótona y ACELERADA, sin nada que la traiga de vuelta. Ese OBV fuera de +# rango reingresa al tensor de la iteración siguiente (soft-clipeado a la +# banda de saturación), reforzando la misma dirección otra vez — exactamente +# la retroalimentación que este bloque existe para cortar, colándose por la +# única puerta que había quedado sin anchor-pull. FIX: `obv_arr` y +# `bb_width_arr` ahora se anclan igual que EMA/MACD_SIGNAL/ATR (mismo +# `ANCHOR_RETENTION`, ver aplicación en el bucle más abajo). +# +# DOS estabilizadores independientes, complementarios, NINGUNO toca el ruido +# gaussiano i.i.d. (`noise_batch`, más abajo) que le da al cono su ancho +# P5-P95 genuino — tocar eso reintroduciría el problema original de textura: +# +# 1) ANCHOR_RETENTION — "spring-back" hacia el último valor REAL observado. +# Cada paso, el estado recursivo de esos 5 indicadores conserva una +# fracción `ANCHOR_RETENTION` de su desviación respecto al ancla real y +# PIERDE el resto — no se toca la fórmula EWM/recursiva en sí (sigue +# siendo la misma matemática honesta, cero cifras inventadas), solo se +# amortigua cuánto puede alejarse del último dato real confirmado en un +# horizonte de apenas `steps` sesiones sin nueva confirmación de mercado. +# Es una media-reversión de Ornstein-Uhlenbeck discreta de libro de texto, +# simétrica (no sesga dirección), sobre la DESVIACIÓN, no sobre el precio. +# +# 2) SIGNAL_DECAY_BASE — atenúa la SEÑAL DIRECCIONAL del modelo +# (`r_hat_model_batch`, el componente determinista/compartido) con +# `SIGNAL_DECAY_BASE ** step_i`: paso 1 al 100% de confianza, cada paso +# subsiguiente un poco menos, reflejando que cada sesión adicional aleja +# más al modelo de su distribución de entrenamiento real. El ruido +# (`noise_batch`) NO se decae — la dispersión sigue creciendo con +# sqrt(steps) como un random walk genuino; solo se descuenta cuánto pesa +# la CONVICCIÓN DIRECCIONAL compartida del modelo en el precio final, +# exactamente la fuente del arrastre sistemático que tira de P5 Y P95 a +# la vez. El cinturón MODEL_SIGNAL_CLIP_SIGMAS se conserva intacto como +# techo absoluto de última instancia (defensa en profundidad). +ANCHOR_RETENTION = 0.90 # fracción de la desviación vs. ancla real que sobrevive cada paso +SIGNAL_DECAY_BASE = 0.65 # atenúa más rápido en horizontes cortos (5 pasos); revalidar con backtest direccional V6 antes de fijarlo en prod +DIRECTIONAL_ACCURACY_HOLDOUT = 0.53 # punto medio DA 51-55% — actualizar tras cada reentrenamiento +EDGE_SHRINKAGE_FACTOR = max(0.0, 2 * (DIRECTIONAL_ACCURACY_HOLDOUT - 0.5)) # ≈0.06: la magnitud solo merece la confianza que el edge real (sobre 50/50) le gana al azar + + + +def _anchor_pull(state: np.ndarray, anchor: float, retention: float = ANCHOR_RETENTION) -> np.ndarray: + """ + Media-reversión discreta hacia `anchor` (el último valor REAL observado, + congelado antes del bucle): conserva `retention` de la desviación actual + y descarta el resto. Identidad cuando `state == anchor`. No fabrica + ningún dato — solo amortigua qué tan lejos puede derivar el ESTADO + recursivo del último punto confirmado por mercado real. + """ + return anchor + (state - anchor) * retention + + +# --- Dampening por OOD real (auditoría SPY: oob_frac=45.6% en T+1, 100% +# data real, sin ningún paso sintético todavía) ----------------------------- +# `_anchor_pull`/`SIGNAL_DECAY_BASE` amortiguan la deriva SINTÉTICA que el +# propio bucle acumula paso a paso — no dicen nada sobre un tensor que YA +# nace fuera de rango en T+1, antes de que el bucle exista. `oob_frac` +# medido en T+1 (ver diagnóstico más abajo) es 100% atribuible a que +# `feature_scaler` se fiteó una única vez (`MinMaxScaler.fit(features[: +# split_idx])`, ver train_kodaquant_v5.py) sobre un tramo histórico que el +# mercado real ya superó — el activo hizo máximos que el scaler nunca vio. +# +# DESCARTADO explícitamente — "Dynamic Scaler Recalibration" (re-fitear o +# desplazar min/max del scaler en tiempo de inferencia, por ticker/por +# request): matemáticamente inválido para una red YA ENTRENADA. Los pesos +# de la Bi-LSTM aprendieron qué SIGNIFICA "RSI escalado = 0.85" en términos +# del rango de entrenamiento fijo — si el scaler se recalibra con la +# ventana actual, "0.85" pasa a representar un RSI crudo distinto sin que +# la red se entere. El síntoma (oob_frac) desaparecería de los logs, pero +# el problema real (la red extrapolando a una región que nunca vio) seguiría +# intacto y ahora invisible — cambia una anomalía honesta por una lectura +# artificialmente "normal". Es exactamente el tipo de maquillaje de cifras +# que este pipeline evita en todos sus otros componentes (ver +# `evaluate_asset`, `_confidence_score`); no corresponde hacer la excepción +# acá. La corrección estructural real —representación estacionaria +# (retornos/z-score móvil) en vez de nivel de precio absoluto para +# PRICE/EMA/MACD/ATR/OBV— existe y es superior a largo plazo, pero exige +# reentrenar desde cero (cambia qué significa cada columna de entrada) y +# por lo tanto no es un fix de calibración desplegable hoy. +# +# Lo que SÍ es matemáticamente válido sin retrain: si la red va a +# extrapolar de todos modos, no confiar en la MAGNITUD de su señal +# determinista en proporción a cuán lejos del manifold de entrenamiento +# arrancó — mismo principio que `SIGNAL_DECAY_BASE`, pero disparado por +# distancia a la distribución de entrenamiento en vez de por número de +# pasos sintéticos, y fijo para todo el horizonte (T+1 ya nace OOD; ese +# hecho no cambia paso a paso). El ruido i.i.d. (`noise_batch`) y el +# ancho P5-P95 NO se tocan — solo se recorta cuánto pesa el punto estimado +# del modelo, igual que con el decay por pasos. +REAL_OOD_DAMPENING_START = 0.15 # oob_frac en T+1 a partir del cual empieza a atenuarse la señal +REAL_OOD_DAMPENING_FULL = 0.50 # oob_frac en T+1 a partir del cual la atenuación llega a su piso +REAL_OOD_DAMPENING_FLOOR = 0.10 # piso multiplicativo — recorte agresivo bajo saturación extrema; > 0 a propósito: preserva el SIGNO (dirección) que la red detecta, nunca lo invierte ni lo anula a cero (ver auditoría SPY: floor=0.35 dejó -11.94%->-9.27%, compounding vía technicals recursivos hace la relación sub-lineal — floor más bajo pega más fuerte en la magnitud sin tocar de qué lado del cero cae) + + +def _real_ood_dampening_factor(oob_frac_t0: float) -> float: + """ + Factor multiplicativo ∈ [REAL_OOD_DAMPENING_FLOOR, 1.0], función lineal + de `oob_frac_t0` (medido UNA sola vez, en T+1, sobre la ventana 100% + real — ver captura en el bucle). 1.0 = sin penalización (input dentro + de rango de entrenamiento). Decrece linealmente entre + REAL_OOD_DAMPENING_START y REAL_OOD_DAMPENING_FULL hasta el piso. + """ + if oob_frac_t0 <= REAL_OOD_DAMPENING_START: + return 1.0 + if oob_frac_t0 >= REAL_OOD_DAMPENING_FULL: + return REAL_OOD_DAMPENING_FLOOR + span = REAL_OOD_DAMPENING_FULL - REAL_OOD_DAMPENING_START + progress = (oob_frac_t0 - REAL_OOD_DAMPENING_START) / span + return 1.0 - progress * (1.0 - REAL_OOD_DAMPENING_FLOOR) + + +# --- Simulación Monte Carlo / Intervalos de Confianza Dinámicos ----------- +# En vez de un único camino estocástico, cada paso del bucle autoregresivo +# corre un FORWARD PASS BATCHEADO del modelo (batch = N_MONTE_CARLO_SIMULATIONS +# trayectorias en paralelo, una sola llamada a Keras por paso — no N llamadas +# por paso) más su propio ruido de volatilidad i.i.d. por trayectoria. Al +# final se colapsan las N trayectorias a 3 percentiles por fecha. +N_MONTE_CARLO_SIMULATIONS = 100 +CONFIDENCE_LOWER_PERCENTILE = 5 # escenario pesimista +CONFIDENCE_MEDIAN_PERCENTILE = 50 # tendencia central (expected_path) +CONFIDENCE_UPPER_PERCENTILE = 95 # escenario optimista + +# Plan A y Plan B se despachan EN PARALELO vía asyncio.gather + threads (ver +# _build_investment_plans), pero comparten el MISMO objeto `model` cacheado +# por `_get_keras_model`. Este lock serializa EXCLUSIVAMENTE la llamada de +# inferencia (`model([...], training=True)`) para que dos forward passes +# nunca pisen el mismo grafo/tensores a la vez — todo lo demás del bucle +# (yfinance, feature engineering, reconstrucción de precio) sigue corriendo +# en paralelo sin contención. +inference_lock = threading.Lock() + +# --- Guardia de congelamiento — segunda línea de defensa, independiente --- +# del fix de raíz (CPU-only, ver bloque [DEVICE GUARD] arriba). El fix de +# raíz elimina la causa CONOCIDA (Metal desde hilo secundario); esta guardia +# cubre cualquier OTRA causa de hang silencioso (otro backend, otra GPU, un +# deadlock nativo distinto) convirtiéndola en una excepción explícita a los +# `_KERAS_CALL_TIMEOUT_SECONDS` en vez de un freeze infinito. Nativo — cero +# librerías nuevas, reutiliza `ThreadPoolExecutor` (ya importado arriba). +_KERAS_CALL_TIMEOUT_SECONDS = 15.0 +_keras_call_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="kodaquant-keras-call") + + +def _call_keras_with_hang_guard(fn, *args, **kwargs): + """ + Ejecuta `fn(*args, **kwargs)` en un worker dedicado de 1 solo hilo + (reutilizado entre llamadas mientras no cuelgue ninguna) y exige el + resultado con timeout. Si `fn` no responde en + `_KERAS_CALL_TIMEOUT_SECONDS`, lanza `TimeoutError` con diagnóstico + explícito — Y descarta el executor completo: un hilo que quedó + congelado a mitad de un forward pass (command queue de GPU corrupto, + lock nativo tomado y nunca liberado) no es confiable para llamadas + futuras, así que se abandona (daemon, no bloquea shutdown) y la + siguiente llamada arranca un worker nuevo y limpio. + """ + global _keras_call_executor + future = _keras_call_executor.submit(fn, *args, **kwargs) + try: + return future.result(timeout=_KERAS_CALL_TIMEOUT_SECONDS) + except TimeoutError as exc: + stuck_executor = _keras_call_executor + _keras_call_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="kodaquant-keras-call") + stuck_executor.shutdown(wait=False, cancel_futures=False) + raise TimeoutError( + f"Forward pass de Keras excedió {_KERAS_CALL_TIMEOUT_SECONDS:.0f}s sin " + "responder (hang silencioso). Worker aislado y descartado; la siguiente " + "llamada usa un hilo nuevo. Si esto dispara pese al [DEVICE GUARD] " + "CPU-only, la causa NO es Metal/GPU — audita a partir de este log." + ) from exc + +# Executor DEDICADO para I/O ligero (yfinance de sentimiento) — separado del +# executor default (`run_in_executor(None, ...)`) que usa `_forecast_asset` +# (Keras + Monte Carlo, bloqueante, varios segundos por ticker). Compartir un +# solo pool entre tareas pesadas de CPU y tareas livianas de red hace que el +# fetch de sentimiento quede en cola detrás de un forecast completo y dispare +# el Circuit Breaker por "timeout" cuando en realidad es contención de +# threads, no lentitud real de red (ver get_market_sentiment). Pool chico y +# propio = el sentimiento nunca espera detrás de un forward pass de Keras. +_SENTIMENT_EXECUTOR = ThreadPoolExecutor(max_workers=8, thread_name_prefix="kodaquant-sentiment") + +# --- Groq LPU — inferencia generativa en la nube (SDK oficial `groq`) ---- +# Reemplaza por completo al viejo transporte dual "http" (servidor GGUF +# aparte, llama-server/LM Studio) / "embedded" (llama-cpp-python + Metal +# in-process). Sin servidor propio que levantar, sin puerto que coordinar +# con FastAPI, sin build de Metal/CUDA — un solo cliente async oficial. +# +# GROQ_API_KEY es OBLIGATORIA. Si falta, el proceso debe fallar rápido y +# ruidosamente al importar este módulo (arranque del servidor) en vez de +# fallar recién en la primera consulta de un usuario real — ver el +# RuntimeError explícito más abajo. +GROQ_API_KEY = os.getenv("GROQ_API_KEY", "").strip() +if not GROQ_API_KEY: + raise RuntimeError( + "GROQ_API_KEY no está definida. Exportala en el entorno o en el " + ".env del backend, ej.:\n" + " GROQ_API_KEY=gsk_xxx...\n" + "Conseguila en https://console.groq.com/keys — sin esta clave el " + "motor no puede inicializar el cliente AsyncGroq." + ) + +# Modelo fijo y rígido — no configurable por entorno, para que ningún +# despliegue quede corriendo silenciosamente contra otro modelo por un +# .env desalineado. +GROQ_MODEL_NAME = "llama-3.3-70b-versatile" + +# Tope de tokens de salida. Balanceado (1024-1500) para respuestas +# completas y estructuradas (RESUMEN + ESTRATEGIA DE RESERVA + ESTRATEGIA +# DE RIESGO, ver _build_system_prompt) sin arriesgar corte a mitad de +# frase ni gastar de más la cuota del Free Tier de Groq. +GROQ_MAX_OUTPUT_TOKENS = int(os.getenv("GROQ_MAX_OUTPUT_TOKENS", "1500")) + +# Cliente async ÚNICO (singleton de módulo) — AsyncGroq usa httpx.AsyncClient +# internamente y es seguro reutilizar la misma instancia entre requests +# concurrentes de FastAPI; instanciarlo por request desperdiciaría el pool +# de conexiones. Está PROHIBIDO usar el cliente sincrónico `Groq` acá: con +# `Groq` (no async) cada llamada bloquearía el event loop de FastAPI. +_groq_client = AsyncGroq(api_key=GROQ_API_KEY) + + +# --------------------------------------------------------------------------- +# Custom layer — DEBE ser idéntica bit a bit a la definición del notebook de +# entrenamiento (mismo package/nombre en el decorador, mismos sub-layers, +# mismo build/call) para que `keras.models.load_model` pueda reconstruir el +# grafo y calzar los pesos guardados en `attention_bilstm_global.keras`. +# --------------------------------------------------------------------------- + +@keras.saving.register_keras_serializable(package="quanti") +class BahdanauAttention(layers.Layer): + """Self-attention aditiva (Bahdanau) sobre la salida temporal de la BiLSTM.""" + + def __init__(self, units: int, **kwargs): + super().__init__(**kwargs) + self.units = units + self.W = layers.Dense(units, name="attn_W") + self.U = layers.Dense(units, name="attn_U") + self.V = layers.Dense(1, name="attn_V") + + def build(self, input_shape): + feature_dim = input_shape[-1] + self.W.build((None, None, feature_dim)) + self.U.build((None, 1, feature_dim)) + self.V.build((None, None, self.units)) + super().build(input_shape) + + def call(self, hidden_states): + query = keras.ops.mean(hidden_states, axis=1, keepdims=True) + score = self.V(keras.ops.tanh(self.W(hidden_states) + self.U(query))) + weights = keras.ops.softmax(score, axis=1) + context = keras.ops.sum(weights * hidden_states, axis=1) + return context, weights + + def get_config(self): + config = super().get_config() + config.update({"units": self.units}) + return config + + +# --------------------------------------------------------------------------- +# V3 — Custom loss / metric. DEBEN ser idénticas bit a bit a +# entrenamiento.py (mismo package="quanti", mismo nombre de clase/función, +# misma lógica de `call`/`get_config`) para que `keras.models.load_model` +# pueda resolver "Unknown loss function: DirectionalHuberLoss" / "Unknown +# metric function: directional_accuracy_metric" al deserializar +# `attention_bilstm_global.keras`. +# +# NOTA: `_get_keras_model()` carga con `compile=False` (este motor solo +# hace forward passes vía `model(...)`, nunca `.fit()`/`.evaluate()`), así +# que en la práctica Keras 3 no necesita reconstruir la loss/optimizer para +# servir inferencia. Igual se registran acá como red de seguridad: distintas +# versiones de Keras 3 difieren en cuánto de `compile_config` tocan incluso +# con `compile=False`, y un futuro `compile=True` (ej. para +# `model.evaluate()` en un job de validación offline) debe encontrar ambos +# símbolos sin sorpresas. +# +# `DynamicGammaCallback` (curriculum learning de `gamma`) NO se replica +# acá a propósito: es un `keras.callbacks.Callback` que solo existe dentro +# del bucle de `model.fit()` — nunca se serializa como parte del grafo ni +# del artefacto `.keras`. El valor de `gamma` con el que se guardó el +# checkpoint queda FIJO como float estático dentro de +# `DirectionalHuberLoss.get_config()` (ver su docstring), que es +# exactamente el comportamiento correcto para inferencia. +# --------------------------------------------------------------------------- + +@keras.saving.register_keras_serializable(package="quanti") +class DirectionalHuberLoss(keras.losses.Loss): + """ + L(y, ŷ) = Huber_δ(y, ŷ) · (1 + γ · 1[sign(y) ≠ sign(ŷ)]) + + Réplica exacta de la loss de entrenamiento — ver entrenamiento.py para + la derivación completa. En inferencia (`compile=False`, sin `.fit()`) + esta clase nunca se invoca: solo necesita existir para que + `keras.models.load_model` pueda resolver el `class_name` guardado en el + `compile_config` del artefacto si alguna vez se carga con `compile=True`. + """ + + def __init__(self, delta: float = 1.0, gamma=1.5, + name: str = "directional_huber", **kwargs): + super().__init__(name=name, **kwargs) + self.delta = delta + self.gamma = gamma if isinstance(gamma, keras.Variable) else keras.Variable( + gamma, trainable=False, dtype="float32", name=f"{name}_gamma" + ) + + def call(self, y_true, y_pred): + y_true = keras.ops.cast(y_true, "float32") + y_pred = keras.ops.cast(y_pred, "float32") + + error = y_true - y_pred + abs_error = keras.ops.abs(error) + quadratic = keras.ops.minimum(abs_error, self.delta) + linear = abs_error - quadratic + huber = 0.5 * keras.ops.square(quadratic) + self.delta * linear + + mismatch = keras.ops.cast( + keras.ops.not_equal(keras.ops.sign(y_true), keras.ops.sign(y_pred)), + dtype=huber.dtype, + ) + penalty = 1.0 + self.gamma * mismatch + return keras.ops.mean(huber * penalty, axis=-1) + + def get_config(self): + config = super().get_config() + config.update({ + "delta": self.delta, + "gamma": float(keras.ops.convert_to_numpy(self.gamma)), + }) + return config + + +@keras.saving.register_keras_serializable(package="quanti") +def directional_accuracy_metric(y_true, y_pred): + """Réplica exacta de la métrica de monitoreo de entrenamiento.py: % de aciertos de signo.""" + y_true = keras.ops.cast(y_true, "float32") + y_pred = keras.ops.cast(y_pred, "float32") + match = keras.ops.cast( + keras.ops.equal(keras.ops.sign(y_true), keras.ops.sign(y_pred)), dtype="float32" + ) + return keras.ops.mean(match) + + +# --------------------------------------------------------------------------- +# Carga perezosa y cacheada de artefactos pesados (una sola vez por proceso) +# --------------------------------------------------------------------------- + +def _dropout_layer_names(model: KerasModel) -> list[str]: + """ + Verificación honesta, no un supuesto: recorre el grafo cargado y confirma + que el `Dropout(0.4)` del notebook sigue vivo en el modelo deserializado. + A diferencia de un export a ONNX (que hornea Dropout -> Identity bajo + `model.eval()`), un `.keras` nativo conserva la capa completa — pero + igual lo comprobamos en vez de darlo por hecho. + """ + return [layer.name for layer in model.layers if isinstance(layer, layers.Dropout)] + + +def _build_mc_dropout_bridge(model: KerasModel) -> KerasModel: + """ + DIAGNÓSTICO RAÍZ (colapso de varianza / línea recta) — confirmado + inspeccionando `config.json` DENTRO del propio artefacto `.keras` (no + una suposición): el nodo Functional de cada capa `Dropout` del grafo + entrenado quedó serializado con `inbound_nodes[0].kwargs == + {"training": False}` — un booleano concreto HORNEADO en tiempo de + construcción del grafo en el notebook (ej. `layers.Dropout(0.4)(x, + training=False)`), no un valor simbólico. Cuando una capa recibe un + booleano literal (no `None`) como `training` dentro del Functional + API, Keras lo fija PERMANENTEMENTE en ESE nodo — llamar después a + `model([...], training=True)` sobre el modelo completo NO tiene ningún + efecto sobre ese nodo puntual. + + FIX sin reentrenar y sin tocar el `.keras` original: se reutilizan los + MISMOS objetos de capa (mismos pesos entrenados) para reconstruir el + grafo Functional COMPLETO en nodos nuevos, forzando `training=True` + únicamente en las capas `Dropout`. La versión anterior de este bridge + hardcodeaba el tramo final (`dropout_regularizer -> post_fusion_dense + -> return_head`), válido solo para la topología base (cripto) — con la + topología inflada de equity (bloque residual extra + `extra_residual_dense -> skip -> add -> ln -> dropout` insertado entre + medio) esa cadena fija saltaba directo de `fusion_attn_asset` (dim + ancha) a `post_fusion_dense` (dim angosta) y colapsaba con + `ValueError` de shape. Este bridge es agnóstico a la topología: no + conoce nombres de capa ni cantidad de capas Dropout, camina el grafo + real capa por capa sin importar cuántos bloques residuales, ramas o + capas multi-entrada/multi-salida tenga. + + MECANISMO — se indexa, para cada nodo entrante de cada capa del + modelo original (`model.layers`, saltando `InputLayer`), su tensor de + salida ORIGINAL -> (capa, nodo) que lo produjo (`producer_of`). Para + reconstruir `model.output` se resuelve esa dependencia RECURSIVAMENTE + en post-order (primero los tensores de entrada de un nodo, después el + nodo mismo) — no se asume que `model.layers` ya viene en orden + topológico estricto, así que el resultado es correcto sin importar + cómo Keras haya ordenado esa lista internamente. + + Por cada nodo, `node.arguments.fill_in(tensor_dict)` — el MISMO + mecanismo interno que usa Keras para EJECUTAR el grafo — reconstruye + los args/kwargs EXACTOS con los que esa capa fue invocada en el + notebook (posicionales, kwargs, tensores anidados en listas como + `Add()([a, b])`, constantes no-tensor), sustituyendo cada tensor + original por su contraparte ya reconstruida. Cero hardcoding de firmas + de capa: lo que se invoca es literalmente "lo mismo que ya estaba", + tensor por tensor. + + ÚNICO cambio funcional: si la capa es una instancia de + `layers.Dropout` (cualquier nombre, cualquier posición, cualquier + cantidad — la topología equity tiene DOS Dropout, la base tiene UNO), + se fuerza `training=True` explícito en el nodo NUEVO. Todo lo demás + (capas custom multi-salida como `BahdanauAttention`, `Concatenate`, + `Add`, `LayerNormalization`, embeddings, etc.) se reinvoca sin tocar + un solo kwarg propio. + + Ninguna capa se clona ni se reinicializa: se reutiliza el MISMO objeto + Python de cada capa (mismos pesos entrenados), solo se le agrega un + nodo Functional nuevo — el patrón nativo de "capa reutilizable / + multi-nodo" de Keras (igual que un modelo "siamés"), aplicado ahora a + la totalidad del grafo en vez de a un tramo fijo. + """ + original_inputs = list(model.inputs) + # Tensor de entrada original -> él mismo: el grafo nuevo arranca desde + # los MISMOS `keras.Input` simbólicos, no se clonan. + resolved: dict[int, Any] = {id(t): t for t in original_inputs} + + # id(tensor de salida ORIGINAL) -> (capa, nodo) que lo produjo. Se + # indexa ANTES de invocar ninguna capa nueva, sobre el grafo intacto — + # así una capa reutilizada más de una vez (>1 `_inbound_nodes`) queda + # desambiguada nodo por nodo, no por nombre de capa. + producer_of: dict[int, tuple[Any, Any]] = {} + for layer in model.layers: + if isinstance(layer, layers.InputLayer): + continue + for node in layer._inbound_nodes: + outputs = node.output_tensors + outputs = outputs if isinstance(outputs, (list, tuple)) else [outputs] + for tensor in outputs: + producer_of[id(tensor)] = (layer, node) + + visited_nodes: set[int] = set() + + def _resolve_node(layer, node) -> None: + if id(node) in visited_nodes: + return + visited_nodes.add(id(node)) + + # Post-order: resuelve primero TODOS los tensores de entrada de + # este nodo (recursión sobre su propio productor) antes de + # reinvocar la capa — garantiza orden correcto sin depender de + # cómo Keras haya poblado `model.layers`. + for parent_tensor in node.arguments.keras_tensors: + if id(parent_tensor) not in resolved: + parent_layer, parent_node = producer_of[id(parent_tensor)] + _resolve_node(parent_layer, parent_node) + + tensor_dict = {id(t): resolved[id(t)] for t in node.arguments.keras_tensors} + args, kwargs = node.arguments.fill_in(tensor_dict) + + if isinstance(layer, layers.Dropout): + kwargs = dict(kwargs) + kwargs["training"] = True # único override permitido — MC Dropout real + + new_output = layer(*args, **kwargs) + + original_output = node.output_tensors + if isinstance(original_output, (list, tuple)): + new_outputs_seq = new_output if isinstance(new_output, (list, tuple)) else [new_output] + for orig_t, new_t in zip(original_output, new_outputs_seq): + resolved[id(orig_t)] = new_t + else: + resolved[id(original_output)] = new_output + + def _resolve_structure(struct): + if isinstance(struct, (list, tuple)): + return type(struct)(_resolve_structure(item) for item in struct) + if isinstance(struct, dict): + return {key: _resolve_structure(value) for key, value in struct.items()} + if id(struct) in resolved: + return resolved[id(struct)] + if id(struct) in producer_of: + layer, node = producer_of[id(struct)] + _resolve_node(layer, node) + return resolved[id(struct)] + return struct # no es un tensor del grafo — constante, se deja intacta + + final_outputs = _resolve_structure(model.output) + return keras.Model(inputs=original_inputs, outputs=final_outputs, name="mc_dropout_bridge") + + +def _zero_sample_from_input_shape(model: KerasModel) -> list[np.ndarray]: + """ + Construye un batch de entrada dummy (ceros) con la forma EXACTA de + `model.input_shape`, respetando el dtype real que usa `_forecast_asset` + para cada tensor: `float32` para la ventana de features, `int32` para el + id categórico del activo. Solo se usa para la verificación de + estocasticidad de abajo — nunca participa en una predicción real. + """ + shapes = model.input_shape + if not isinstance(shapes, list): + shapes = [shapes] + samples = [] + for i, shape in enumerate(shapes): + concrete_shape = tuple(1 if dim is None else dim for dim in shape) + dtype = np.int32 if i == 1 else np.float32 + samples.append(np.zeros(concrete_shape, dtype=dtype)) + return samples + + +def _verify_stochastic_variance(model: KerasModel) -> bool: + """ + Verificación defensiva — NO una suposición. Corre dos forward passes + IDÉNTICOS (mismo input dummy) con `training=True` y compara bit a bit. + Un bridge de MC Dropout correctamente reconstruido debe devolver dos + salidas DISTINTAS (cada pasada muestrea su propia máscara de dropout); + si salen idénticas, el `training=True` no está llegando realmente a + ninguna capa Dropout activa (nombre de capa equivocado, capas + downstream desalineadas con el grafo real, optimización que colapsó el + nodo nuevo, etc.) — y eso debe quedar visible en el log ANTES de que se + manifieste solo como una curva plana en el frontend, sin pista de causa. + """ + try: + sample_input = _zero_sample_from_input_shape(model) + with inference_lock: + out_1 = keras.ops.convert_to_numpy( + _call_keras_with_hang_guard(model, sample_input, training=True) + ) + out_2 = keras.ops.convert_to_numpy( + _call_keras_with_hang_guard(model, sample_input, training=True) + ) + return not np.allclose(out_1, out_2, atol=1e-9) + except Exception as exc: # noqa: BLE001 — la verificación jamás debe tumbar la carga del modelo + print(f"⚠️ No se pudo verificar la estocasticidad del modelo cargado ({exc!r}).") + return False + + +# --------------------------------------------------------------------------- +# Caché de artefactos en RAM (patrón Singleton por régimen) + locks de carga +# --------------------------------------------------------------------------- +# FIX DEADLOCK/I-O: `@lru_cache` protege con su Lock interno el ACCESO al +# dict de caché, pero NO serializa la ejecución de la función decorada — +# bajo cache-miss concurrente (Alpha Seeker escaneando N tickers del MISMO +# régimen vía asyncio.gather + run_in_executor, ver +# prediccion.py._scan_universe), cada hilo que llega antes de que el +# primero termine de poblar el caché dispara su PROPIO +# keras.models.load_model()/pickle.load() en paralelo — de ahí la avalancha +# de "[ARTIFACT LOAD]" duplicados en el mismo milisegundo. Con la GPU +# deshabilitada (Device Guard, más arriba) esas N deserializaciones +# completas del grafo (incl. la reconstrucción nodo-a-nodo del MC-Dropout +# bridge) compiten por CPU y saturan el proceso — el síntoma percibido +# como deadlock. +# +# Reemplazo: dict de caché en RAM + double-checked locking con UN Lock POR +# RÉGIMEN (no un lock global — preserva la independencia de carga +# equity/crypto ya documentada en el diseño original). Garantiza que +# `keras.models.load_model`/`pickle.load` corran EXACTAMENTE UNA VEZ por +# régimen durante todo el ciclo de vida del proceso: el primer hilo que +# adquiere el lock carga y publica en el dict; cualquier hilo que llegue +# después (con el lock libre u ocupado) encuentra el cache-hit y retorna +# sin tocar disco. +_model_cache: dict[str, tuple[KerasModel, tuple[str, ...]]] = {} +_scalers_cache: dict[str, dict] = {} +_model_load_locks: dict[str, threading.Lock] = {regime: threading.Lock() for regime in REGIME_TICKERS} +_scalers_load_locks: dict[str, threading.Lock] = {regime: threading.Lock() for regime in REGIME_TICKERS} + + +def _load_keras_model_from_disk(regime: str) -> tuple[KerasModel, tuple[str, ...]]: + """ + Carga real (sin caché, sin lock) de `kodaquant_models//model_v5.keras`. + Body original de `_get_keras_model` V5 intacto — SOLO se invoca desde + dentro de `_model_load_locks[regime]` en `_get_keras_model`, nunca + directamente. `compile=False` porque solo hacemos forward passes + (`model(...)`), nunca `.fit()`. + + Devuelve el "MC-Dropout bridge" (ver `_build_mc_dropout_bridge`) cuando + el grafo original tiene `dropout_regularizer` congelado en + `training=False` — en vez del `model` crudo, que seguiría siendo + determinista para siempre sin importar qué `training` se le pase desde + `_forecast_asset`. + """ + model_path = _model_path(regime) + if not os.path.exists(model_path): + raise FileNotFoundError(f"No se encontró el modelo Keras del régimen '{regime}' en: {model_path}") + + mtime = datetime.fromtimestamp(os.path.getmtime(model_path)).isoformat(timespec="seconds") + logger.info( + "[ARTIFACT LOAD] regime=%s model_path=%s mtime=%s", + regime, os.path.abspath(model_path), mtime, + ) + model = keras.models.load_model( + model_path, + custom_objects={ + "BahdanauAttention": BahdanauAttention, + "DirectionalHuberLoss": DirectionalHuberLoss, + "directional_accuracy_metric": directional_accuracy_metric, + }, + compile=False, + ) + + dropout_layers = tuple(_dropout_layer_names(model)) + if not dropout_layers: + print( + f"⚠️ MC Dropout NO disponible: el modelo del régimen '{regime}' cargado desde " + f"{os.path.basename(model_path)} no tiene ninguna capa Dropout en su grafo. " + "El motor autoregresivo seguirá siendo 100% real pero " + "determinista bajo `training=True` — revisa que el .keras " + "cargado sea el mismo que entrenó `dropout_regularizer` (0.4) " + "en el notebook. CERO ruido artificial será inyectado como " + "sustituto." + ) + return model, dropout_layers + + try: + inference_model = _build_mc_dropout_bridge(model) + except Exception as exc: # noqa: BLE001 — jamás fallar en silencio ni caer a ruido sintético + print( + f"⚠️ No se pudo reconstruir el bridge de MC Dropout ({exc!r}) — " + "se usa `model` crudo. El bridge reconstruye TODO el grafo nodo a " + "nodo (ver `_build_mc_dropout_bridge`); una excepción acá casi " + "siempre indica un nodo cuyo `node.arguments.fill_in` no resuelve " + "limpio (ej. una capa custom con un input no-KerasTensor en su " + "firma de `call`). Si ninguna capa Dropout del grafo estaba " + "congelada en `training=False`, esto es inofensivo y el `model` " + "crudo ya es correcto; si sí lo estaba, el forecast volverá a ser " + "determinista." + ) + return model, dropout_layers + + if not _verify_stochastic_variance(inference_model): + print( + "🚨 ALERTA — el bridge de MC Dropout se construyó SIN excepción, pero " + "dos forward passes idénticos con training=True devolvieron el MISMO " + "resultado: la varianza sigue sin inyectarse pese al bridge. El bridge " + "es agnóstico a nombres de capa — fuerza `training=True` en TODA " + "instancia de `layers.Dropout` del grafo real (ver " + "`_build_mc_dropout_bridge`) — así que si esto dispara, sospechá de " + "`rate=0.0` en la(s) capa(s) Dropout del `.keras` cargado, o de que " + "el grafo simplemente no tiene ninguna Dropout activa pese a lo que " + "reportó `_dropout_layer_names` (`model.summary()` / " + "`[l.name for l in model.layers]` para confirmar)." + ) + + return inference_model, dropout_layers + + +def _get_keras_model(regime: str) -> tuple[KerasModel, tuple[str, ...]]: + """ + Singleton en RAM thread-safe: retorna el modelo Keras del régimen desde + `_model_cache`, cargándolo desde disco (`_load_keras_model_from_disk`) + EXACTAMENTE UNA VEZ por régimen durante todo el ciclo de vida del + proceso. Double-checked locking sobre `_model_load_locks[regime]` — el + fast-path (cache-hit) no toca ningún lock; solo el primer cache-miss + por régimen paga el costo de `keras.models.load_model` + reconstrucción + del MC-Dropout bridge, cualquier hilo concurrente que llegue mientras + tanto espera el lock y reutiliza el resultado ya publicado (nunca + dispara su propia carga redundante). + """ + cached = _model_cache.get(regime) + if cached is not None: + return cached + + with _model_load_locks[regime]: + cached = _model_cache.get(regime) + if cached is not None: # otro hilo ya cargó mientras esperábamos el lock + return cached + result = _load_keras_model_from_disk(regime) + _model_cache[regime] = result + return result + + +def _load_scalers_from_disk(regime: str) -> dict: + """ + Carga real (sin caché, sin lock) de + `kodaquant_models//scalers_dict.pkl`. Body original de + `_get_scalers` V5 intacto — SOLO se invoca desde dentro de + `_scalers_load_locks[regime]` en `_get_scalers`, nunca directamente. + """ + scalers_path = _scalers_path(regime) + if not scalers_path.exists(): + raise FileNotFoundError(f"No se encontró el bundle de scalers del régimen '{regime}' en: {scalers_path}") + + suspicious = sorted( + p.name for p in scalers_path.parent.glob("scalers*.pkl") + if p.resolve() != scalers_path.resolve() + ) + if suspicious: + print( + f"⚠️ Artefacto(s) duplicado(s) junto a {scalers_path.name} " + f"(IGNORADOS, nunca se cargan): {suspicious}" + ) + + with open(scalers_path, "rb") as f: + payload = pickle.load(f) + + mtime = datetime.fromtimestamp(scalers_path.stat().st_mtime).isoformat(timespec="seconds") + logger.info( + "[ARTIFACT LOAD] regime=%s scalers_path=%s mtime=%s tech_cols=%s", + regime, scalers_path.resolve(), mtime, payload.get("tech_cols"), + ) + + # Validación defensiva V3: si scalers.pkl viene de un bundle con un + # TECH_COLS distinto (ej. el V2 de 5 técnicos, sin ATR_14/BB_WIDTH_20/ + # OBV), el feature_scaler.transform() de _forecast_asset desplazaría + # cada columna del tensor EN SILENCIO — mismo riesgo que un + # desalineamiento de shape, pero sin lanzar ningún error propio. Se + # compara nombre y orden exactos, no solo el conteo. + saved_tech_cols = payload.get("tech_cols") + # V27 -- ÚNICA divergencia tolerada: NEWS_SENTIMENT_SCORE ausente en el + # pkl porque el entrenamiento corrió sin backend de sentimiento (ver + # `_apply_news_sentiment_gate` en train_kodaquant_v5.py). Se ADOPTA la + # lista guardada en vez de fallar: el feature_scaler fue ajustado con + # ESE orden. Cualquier OTRA diferencia sigue siendo fatal. + if saved_tech_cols is not None and list(saved_tech_cols) != TECH_COLS: + _saved = list(saved_tech_cols) + if _saved == [c for c in TECH_COLS if c != "NEWS_SENTIMENT_SCORE"]: + TECH_COLS[:] = _saved + logger.warning( + "[ARTIFACT LOAD] '%s' se entrenó SIN NEWS_SENTIMENT_SCORE -> " + "columna excluida del tensor de inferencia (len=%d). El motor " + "NO reintroduce la feature: el feature_scaler no tiene columna " + "para ella.", regime, len(TECH_COLS)) + saved_tech_cols = TECH_COLS + if saved_tech_cols is not None and list(saved_tech_cols) != TECH_COLS: + raise ValueError( + f"Desalineación de TECH_COLS entre {scalers_path.name} " + f"({list(saved_tech_cols)}) y este motor de inferencia " + f"({TECH_COLS}). El .keras/scalers_dict.pkl del régimen '{regime}' " + "no corresponden al pipeline V5 vigente — regenera ambos " + "artefactos desde train_kodaquant_v5.py antes de servir inferencia." + ) + if saved_tech_cols is None: + print( + f"⚠️ {scalers_path.name} ('{regime}') no incluye la clave 'tech_cols' " + f"(bundle pre-V5) — se asume el orden hardcodeado {TECH_COLS} sin " + "poder validarlo contra el artefacto real. Regenera scalers_dict.pkl " + "con train_kodaquant_v5.py para una validación genuina." + ) + + return payload + + +def _get_scalers(regime: str) -> dict: + """ + Singleton en RAM thread-safe para `scalers_dict.pkl` — mismo patrón de + double-checked locking que `_get_keras_model`, con lock INDEPENDIENTE + (`_scalers_load_locks[regime]`) para que la carga de scalers de un + régimen nunca espere ociosamente a que termine la carga (más pesada) + del modelo Keras de ese mismo régimen. + """ + cached = _scalers_cache.get(regime) + if cached is not None: + return cached + + with _scalers_load_locks[regime]: + cached = _scalers_cache.get(regime) + if cached is not None: + return cached + payload = _load_scalers_from_disk(regime) + _scalers_cache[regime] = payload + return payload + + +# --------------------------------------------------------------------------- +# Numeric helpers — el backend es la única fuente de verdad matemática. +# --------------------------------------------------------------------------- + +def _select_experience_level(budget_usd: float, experience_level: str) -> str: + if budget_usd >= 150 and experience_level == "advanced": + return "advanced" + return "beginner" + + +def _fmt_money(value: float) -> str: + return f"${value:,.2f} USD" + + +def _fmt_pct(value: float) -> str: + pct = value * 100 if isinstance(value, float) and value <= 1 else value + return f"{pct:.1f}%" + + +def _compute_exact_amounts(investment_plans: dict) -> dict: + """ + Riesgo = Plan B, Reserva = Plan A. SIEMPRE deriva del split dinámico ya + resuelto por `_resolve_risk_split` (ver `_build_investment_plans`) — jamás + un 50/50 desacoplado del `risk_score` real del usuario. Este es el único + punto de verdad para lo que ven las tarjetas "Riesgo" / "Reserva". + """ + plan_a = investment_plans["plan_a"] + plan_b = investment_plans["plan_b"] + + return { + "riesgo_usd": round(float(plan_b["monto_usd"]), 2), + "reserva_usd": round(float(plan_a["monto_usd"]), 2), + "riesgo_pct": plan_b["pct"], + "reserva_pct": plan_a["pct"], + } + + +def _extract_market_signal(radar_data: dict) -> str: + volatility = radar_data.get("volatility", radar_data.get("volatilidad", radar_data.get("volatility_index"))) + correlation = radar_data.get("correlation", radar_data.get("correlacion")) + macro = radar_data.get("macro", radar_data.get("macro_context", radar_data.get("trend"))) + + parts = [] + if volatility is not None: + parts.append(f"volatilidad={volatility}") + if correlation is not None: + parts.append(f"correlación={correlation}") + if macro is not None: + parts.append(f"macro='{macro}'") + + return ", ".join(parts) if parts else "sin señales relevantes en el radar actual" + + +# --------------------------------------------------------------------------- +# Feature engineering — DEBE replicar bit a bit engineer_asset() del notebook +# --------------------------------------------------------------------------- + +def _compute_rsi(series: pd.Series, period: int = 14) -> pd.Series: + delta = series.diff() + gain = delta.clip(lower=0.0) + loss = -delta.clip(upper=0.0) + avg_gain = gain.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + avg_loss = loss.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + rs = avg_gain / avg_loss.replace(0.0, np.nan) + return (100 - (100 / (1 + rs))).fillna(50.0) + + +def _compute_macd(series: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9): + ema_fast = series.ewm(span=fast, adjust=False).mean() + ema_slow = series.ewm(span=slow, adjust=False).mean() + macd_line = ema_fast - ema_slow + signal_line = macd_line.ewm(span=signal, adjust=False).mean() + return macd_line, signal_line + + +# --- SENTIMENT_SCORE: correlación de Pearson móvil activo/VIX -------------- +# HALLAZGO F5 (fix de Data Skew Train/Serve): esta función calculaba antes +# un Z-score de MOMENTUM PROPIO del activo (log-return del día frente a su +# propia media/std móvil) — esa NO es la matemática que entrenó +# `scalers_dict.pkl`. `entrenamiento.py` (V4, ver docstring del módulo) +# redefinió SENTIMENT_SCORE como la correlación de Pearson móvil de +# `SENTIMENT_LOOKBACK_DAYS` sesiones entre el log-return del activo y el +# log-return de ^VIX (proxy de pánico/miedo de mercado, no de momentum +# propio). El `feature_scaler` fue ajustado (`.fit()`) sobre esa +# distribución acotada a [-1, 1] de un COEFICIENTE DE CORRELACIÓN — un +# Z-score de momentum (no acotado, cola larga) cae fuera de ese rango +# ajustado, satura la entrada de la red y colapsa el Monte Carlo +# autoregresivo. DEBE replicar bit a bit `compute_sentiment_score()` del +# notebook de entrenamiento. `SENTIMENT_LOOKBACK_DAYS` == `SENTIMENT_LOOKBACK` +# allá. +SENTIMENT_LOOKBACK_DAYS = 20 + + +def _resolve_vix_ticker(macro_tickers: list[str]) -> str: + """ + Localiza el ticker de VIX dentro de `macro_tickers` (persistido en + `scalers_dict.pkl` como `scalers["macro_tickers"]`). SENTIMENT_SCORE + requiere ESPECÍFICAMENTE el VIX como proxy de pánico/miedo de mercado — + el resto de factores macro (ej. ^GSPC, ^TNX, GC=F, DX-Y.NYB) no + participan de este cálculo. Falla ruidosamente (en vez de asumir un + índice fijo) si el régimen cargado no incluye VIX entre sus macro + tickers, para no desalinear en silencio el tensor de entrada. + """ + for macro_ticker in macro_tickers: + if "VIX" in macro_ticker.upper(): + return macro_ticker + raise ValueError( + f"SENTIMENT_SCORE requiere un ticker VIX en macro_tickers ({macro_tickers}) " + "para replicar la correlación de Pearson móvil del entrenamiento — no se " + "encontró ninguno en scalers_dict.pkl." + ) + + +def _compute_sentiment_score( + price_series: pd.Series, vix_series: pd.Series, window: int = SENTIMENT_LOOKBACK_DAYS +) -> pd.Series: + """Correlación de Pearson móvil (`window` sesiones) entre el log-return del activo y el de VIX.""" + asset_log_returns = np.log(price_series / price_series.shift(1)) + vix_log_returns = np.log(vix_series / vix_series.shift(1)) + corr = asset_log_returns.rolling(window=window, min_periods=window).corr(vix_log_returns) + return corr.fillna(0.0).clip(-1.0, 1.0) + + +# --- V3: ATR_14 / BB_WIDTH_20 / OBV — DEBEN replicar bit a bit compute_atr() +# / compute_bb_width() / compute_obv() del notebook de entrenamiento. +ATR_PERIOD = 14 +ATR_ALPHA = 1 / ATR_PERIOD +BB_WIDTH_WINDOW = 20 +BB_WIDTH_NUM_STD = 2.0 +# OBV es un ACUMULADO, no un oscilador acotado: este motor NO proyecta +# volumen futuro (solo precio), así que el volumen sintético de cada paso +# autoregresivo usa el promedio de los últimos N días REALES como único +# proxy disponible — ver `_compute_indicator_states` y el bucle en +# `_forecast_asset`. Documentado explícitamente, igual que +# VOLATILITY_INJECTION_* más arriba en este módulo. +OBV_VOLUME_PROXY_LOOKBACK_DAYS = 20 + + +def _compute_atr(high: pd.Series, low: pd.Series, close: pd.Series, period: int = ATR_PERIOD) -> pd.Series: + """ATR_14 — True Range con suavizado de Wilder (EWM). Réplica exacta de compute_atr() del notebook.""" + prev_close = close.shift(1) + tr = pd.concat([ + high - low, + (high - prev_close).abs(), + (low - prev_close).abs(), + ], axis=1).max(axis=1) + atr = tr.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + return atr.fillna(0.0) + + +def _compute_bb_width(series: pd.Series, window: int = BB_WIDTH_WINDOW, num_std: float = BB_WIDTH_NUM_STD) -> pd.Series: + """BB_WIDTH_20 — ancho normalizado de Bandas de Bollinger. Réplica exacta de compute_bb_width() del notebook.""" + rolling_mean = series.rolling(window=window, min_periods=window).mean() + rolling_std = series.rolling(window=window, min_periods=window).std() + width = (2 * num_std * rolling_std) / rolling_mean.replace(0.0, np.nan) + return width.fillna(0.0) + + +def _compute_obv(close: pd.Series, volume: pd.Series) -> pd.Series: + """OBV — On-Balance Volume. Réplica exacta de compute_obv() del notebook.""" + direction = np.sign(close.diff()).fillna(0.0) + obv = (direction * volume).cumsum() + return obv.fillna(0.0) + + +# --- V5: ADX_14 / STOCH_K_14 — DEBEN replicar bit a bit compute_adx() / +# compute_stochastic_k() de train_kodaquant_v5.py. +ADX_PERIOD = 14 +STOCH_K_PERIOD = 14 + + +def _compute_adx(high: pd.Series, low: pd.Series, close: pd.Series, period: int = ADX_PERIOD) -> pd.Series: + """ADX (Wilder). Réplica exacta de compute_adx() del notebook.""" + up_move = high.diff() + down_move = -low.diff() + plus_dm = pd.Series(np.where((up_move > down_move) & (up_move > 0), up_move, 0.0), index=high.index) + minus_dm = pd.Series(np.where((down_move > up_move) & (down_move > 0), down_move, 0.0), index=high.index) + + tr = pd.concat([ + high - low, + (high - close.shift(1)).abs(), + (low - close.shift(1)).abs(), + ], axis=1).max(axis=1) + atr = tr.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + + plus_di = 100 * (plus_dm.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() / atr.replace(0.0, np.nan)) + minus_di = 100 * (minus_dm.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() / atr.replace(0.0, np.nan)) + dx = 100 * (plus_di - minus_di).abs() / (plus_di + minus_di).replace(0.0, np.nan) + adx = dx.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + return adx.fillna(0.0) + + +def _compute_stochastic_k(high: pd.Series, low: pd.Series, close: pd.Series, period: int = STOCH_K_PERIOD) -> pd.Series: + """%K estocástico. Réplica exacta de compute_stochastic_k() del notebook.""" + lowest_low = low.rolling(window=period, min_periods=period).min() + highest_high = high.rolling(window=period, min_periods=period).max() + denom = (highest_high - lowest_low).replace(0.0, np.nan) + stoch_k = 100 * (close - lowest_low) / denom + return stoch_k.fillna(50.0) + + +def _compute_adx_state(high: pd.Series, low: pd.Series, close: pd.Series, period: int = ADX_PERIOD) -> dict: + """ + Últimos valores de +DM/-DM suavizados (Wilder) + ADX real — estado + necesario para continuar la EWM de ADX_14 dentro del bucle autoregresivo + de `_forecast_asset` (reutiliza `atr_arr` ya trackeado ahí mismo como + denominador de +DI/-DI, misma fórmula/periodo que este ATR interno). + """ + up_move = high.diff() + down_move = -low.diff() + plus_dm = pd.Series(np.where((up_move > down_move) & (up_move > 0), up_move, 0.0), index=high.index) + minus_dm = pd.Series(np.where((down_move > up_move) & (down_move > 0), down_move, 0.0), index=high.index) + plus_dm_smooth = plus_dm.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + minus_dm_smooth = minus_dm.ewm(alpha=1 / period, min_periods=period, adjust=False).mean() + adx = _compute_adx(high, low, close, period) + return { + "plus_dm_smooth_prev": float(plus_dm_smooth.iloc[-1]) if pd.notna(plus_dm_smooth.iloc[-1]) else 0.0, + "minus_dm_smooth_prev": float(minus_dm_smooth.iloc[-1]) if pd.notna(minus_dm_smooth.iloc[-1]) else 0.0, + "adx_prev": float(adx.iloc[-1]) if pd.notna(adx.iloc[-1]) else 0.0, + } + + +# --------------------------------------------------------------------------- +# AUDITORÍA RESCATE 2026-08 — paridad train/inferencia para las 7 columnas +# que faltaban en TECH_COLS (ver auditoría arriba). Réplica EXACTA (mismos +# endpoints públicos sin key, misma matemática) de las funciones equivalentes +# en train_kodaquant_v5.py — self-contained en este módulo, mismo patrón que +# el resto de _compute_* de arriba (el docstring de módulo ya documenta que +# este archivo es una "replica EXACTA del notebook de entrenamiento"). +# --------------------------------------------------------------------------- + +def _fetch_fear_greed_index(tail_days: int = 3700) -> pd.Series | None: + """Fear & Greed Index (alternative.me, público, sin key). Neutro (50.0) + en el caller si el fetch falla — nunca tumba la inferencia.""" + try: + resp = requests.get("https://api.alternative.me/fng/", params={"limit": 0, "format": "json"}, timeout=10.0) + resp.raise_for_status() + records = resp.json().get("data", []) + except Exception as exc: # noqa: BLE001 — proveedor opcional + logger.debug("Fear & Greed Index falló: %r", exc) + return None + if not records: + return None + fg = pd.DataFrame(records) + fg["date"] = pd.to_datetime(pd.to_numeric(fg["timestamp"]), unit="s").dt.normalize() + fg["value"] = pd.to_numeric(fg["value"], errors="coerce") + return fg.groupby("date")["value"].mean() + + +def _fetch_binance_funding_history(ticker: str) -> pd.Series | None: + """Historial diario de funding rate de perpetuos Binance (REST público, sin key).""" + symbol = BINANCE_FUNDING_SYMBOL_MAP.get(ticker) + if symbol is None: + return None + all_records: list[dict] = [] + cursor_ms = int(datetime(2019, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) + now_ms = int(time.time() * 1000) + for _ in range(50): + if cursor_ms >= now_ms: + break + try: + resp = requests.get( + BINANCE_FAPI_FUNDING_URL, params={"symbol": symbol, "startTime": cursor_ms, "limit": 1000}, timeout=15, + ) + resp.raise_for_status() + batch = resp.json() + except Exception as exc: # noqa: BLE001 + logger.warning("Binance fundingRate falló para %s: %r", symbol, exc) + break + if not batch: + break + all_records.extend(batch) + last_time = int(batch[-1]["fundingTime"]) + if last_time <= cursor_ms: + break + cursor_ms = last_time + 1 + if len(batch) < 1000: + break + time.sleep(0.15) + if not all_records: + return None + raw = pd.DataFrame(all_records) + raw["date"] = pd.to_datetime(pd.to_numeric(raw["fundingTime"]), unit="ms").dt.normalize() + raw["fundingRate"] = pd.to_numeric(raw["fundingRate"], errors="coerce") + return raw.groupby("date")["fundingRate"].mean().sort_index() + + +def _compute_funding_rate_zscore(daily_funding: pd.Series, window: int = FUNDING_ZSCORE_WINDOW_DAYS, + min_periods: int = FUNDING_ZSCORE_MIN_PERIODS) -> pd.Series: + """Réplica EXACTA de `compute_funding_rate_zscore` en train_kodaquant_v5.py + (V25 -- asimétrico, ver docstring ahí).""" + mean = daily_funding.rolling(window, min_periods=min_periods).mean() + std = daily_funding.rolling(window, min_periods=min_periods).std() + z = (daily_funding - mean) / std.replace(0.0, np.nan) + pos = z.clip(lower=0.0) + neg_abs = (-z.clip(upper=0.0)) + z_asym = pos.pow(FUNDING_ZSCORE_ASYM_POS_GAMMA) - neg_abs.pow(FUNDING_ZSCORE_ASYM_NEG_GAMMA) + return z_asym.clip(-FUNDING_ZSCORE_CLIP, FUNDING_ZSCORE_CLIP).fillna(0.0) + + +def _fetch_onchain_activity(chart: str = ONCHAIN_CHART_NAME) -> pd.Series | None: + """Actividad on-chain BTC (blockchain.info /charts, público, sin key). BTC únicamente.""" + try: + resp = requests.get( + BLOCKCHAIN_INFO_CHART_URL.format(chart=chart), + params={"timespan": "all", "format": "json", "sampled": "false"}, timeout=20, + ) + resp.raise_for_status() + values = resp.json().get("values", []) + except Exception as exc: # noqa: BLE001 + logger.debug("blockchain.info/charts/%s falló: %r", chart, exc) + return None + if not values: + return None + idx = pd.to_datetime([v["x"] for v in values], unit="s").normalize() + series = pd.Series([v["y"] for v in values], index=idx, dtype=float) + return series.groupby(level=0).mean().sort_index() + + +def _btc_block_reward_schedule(dates: pd.DatetimeIndex) -> np.ndarray: + idx = pd.DatetimeIndex(dates) + idx_utc = idx.tz_localize("UTC") if idx.tz is None else idx.tz_convert("UTC") + schedule_dates = pd.DatetimeIndex([d for d, _ in BTC_HALVING_SCHEDULE]) + schedule_rewards = np.array([r for _, r in BTC_HALVING_SCHEDULE]) + pos = schedule_dates.searchsorted(idx_utc, side="right") - 1 + pos = np.clip(pos, 0, len(schedule_rewards) - 1) + return schedule_rewards[pos] + + +def _compute_puell_multiple_zscore(close: pd.Series, window: int = PUELL_ZSCORE_WINDOW_DAYS, + min_periods: int = PUELL_ZSCORE_MIN_PERIODS) -> pd.Series: + """BTC únicamente — cero llamada de red, calendario de halving determinístico.""" + reward_per_block = _btc_block_reward_schedule(close.index) + daily_issuance_usd = reward_per_block * BTC_BLOCKS_PER_DAY * close.to_numpy() + issuance = pd.Series(daily_issuance_usd, index=close.index) + issuance_ma = issuance.rolling(PUELL_MA_WINDOW_DAYS, min_periods=PUELL_MA_MIN_PERIODS).mean() + puell = issuance / issuance_ma.replace(0.0, np.nan) + log_puell = np.log(puell.clip(lower=1e-6)) + mean = log_puell.rolling(window, min_periods=min_periods).mean() + std = log_puell.rolling(window, min_periods=min_periods).std() + z = (log_puell - mean) / std.replace(0.0, np.nan) + return z.clip(-PUELL_ZSCORE_CLIP, PUELL_ZSCORE_CLIP).fillna(0.0) + + +def _btc_halving_epoch_cum_supply() -> np.ndarray: + """Réplica EXACTA de `_btc_halving_epoch_cum_supply` en train_kodaquant_v5.py.""" + dates = [d for d, _ in BTC_HALVING_SCHEDULE] + rewards = [r for _, r in BTC_HALVING_SCHEDULE] + cum = [0.0] + for i in range(1, len(dates)): + days = (dates[i] - dates[i - 1]).total_seconds() / 86400.0 + cum.append(cum[-1] + days * BTC_BLOCKS_PER_DAY * rewards[i - 1]) + return np.array(cum) + + +_BTC_EPOCH_CUM_SUPPLY_AT_START = _btc_halving_epoch_cum_supply() + + +def _btc_cumulative_supply(dates: pd.DatetimeIndex) -> np.ndarray: + """Réplica EXACTA de `_btc_cumulative_supply` en train_kodaquant_v5.py -- + suministro circulante determinístico, cero llamada de red.""" + idx = pd.DatetimeIndex(dates) + idx_utc = idx.tz_localize("UTC") if idx.tz is None else idx.tz_convert("UTC") + schedule_dates = pd.DatetimeIndex([d for d, _ in BTC_HALVING_SCHEDULE]) + schedule_rewards = np.array([r for _, r in BTC_HALVING_SCHEDULE]) + pos = np.clip(schedule_dates.searchsorted(idx_utc, side="right") - 1, 0, len(schedule_rewards) - 1) + epoch_start = schedule_dates[pos] + days_since_epoch_start = (idx_utc - epoch_start).total_seconds() / 86400.0 + return _BTC_EPOCH_CUM_SUPPLY_AT_START[pos] + days_since_epoch_start * BTC_BLOCKS_PER_DAY * schedule_rewards[pos] + + +def _fetch_onchain_tx_volume_usd() -> pd.Series | None: + """Réplica EXACTA de `_fetch_onchain_tx_volume_usd` en train_kodaquant_v5.py + -- numerador de utilidad real de NVT Ratio, mismo endpoint que + `_fetch_onchain_activity`, chart distinto.""" + return _fetch_onchain_activity(chart=ONCHAIN_TX_VALUE_CHART_NAME) + + +def _compute_nvt_ratio_zscore(close: pd.Series, tx_volume_usd: pd.Series, + window: int = NVT_ZSCORE_WINDOW_DAYS, + min_periods: int = NVT_ZSCORE_MIN_PERIODS) -> pd.Series: + """Réplica EXACTA de `compute_nvt_ratio_zscore` en train_kodaquant_v5.py + (V25 -- reemplaza ONCHAIN_ACTIVITY_ROC, ver docstring ahí). BTC únicamente.""" + market_cap = close * _btc_cumulative_supply(close.index) + nvt = market_cap / tx_volume_usd.replace(0.0, np.nan) + log_nvt = np.log(nvt.clip(lower=1e-6)) + mean = log_nvt.rolling(window, min_periods=min_periods).mean() + std = log_nvt.rolling(window, min_periods=min_periods).std() + z = (log_nvt - mean) / std.replace(0.0, np.nan) + return z.clip(-NVT_ZSCORE_CLIP, NVT_ZSCORE_CLIP).fillna(0.0) + + +def _ffd_weights(d: float, thresh: float) -> np.ndarray: + w = [1.0] + k = 1 + while True: + w_k = -w[-1] * (d - k + 1) / k + if abs(w_k) < thresh: + break + w.append(w_k) + k += 1 + return np.array(w[::-1]) + + +def _frac_diff_ffd(series: pd.Series, d: float, thresh: float = FRAC_DIFF_THRESH) -> pd.Series: + weights = _ffd_weights(d, thresh) + width = len(weights) + values = series.to_numpy(dtype=np.float64) + out = np.full(len(values), np.nan) + for i in range(width - 1, len(values)): + out[i] = np.dot(weights, values[i - width + 1:i + 1]) + return pd.Series(out, index=series.index) + + +def _find_min_ffd_d(series: pd.Series, train_frac: float = 0.8) -> float: + """Calibra el mínimo `d` que logra estacionariedad (ADF) SOLO sobre el + prefijo de train — cero fuga hacia test/inferencia en vivo. Fallback a + FRAC_DIFF_DEFAULT_D si statsmodels no está disponible.""" + if _adfuller is None: + return FRAC_DIFF_DEFAULT_D + n_train = max(int(len(series) * train_frac), 100) + train_series = series.iloc[:n_train] + for d in FRAC_DIFF_D_GRID: + diffed = _frac_diff_ffd(train_series, d).dropna() + if len(diffed) < 20: + continue + try: + p_value = _adfuller(diffed.to_numpy(), autolag="AIC")[1] + except Exception: # noqa: BLE001 + continue + if p_value <= FRAC_DIFF_ADF_PVALUE_MAX: + return d + return float(FRAC_DIFF_D_GRID[-1]) + + +def _compute_parkinson_vol(high: pd.Series, low: pd.Series, window: int = PARKINSON_VOL_LOOKBACK_DAYS) -> pd.Series: + """Estimador de volatilidad realizada de Parkinson — proxy libre de IV, + solo High/Low. Réplica exacta de compute_parkinson_vol() del notebook.""" + log_hl = np.log(high / low) + variance = (log_hl ** 2).rolling(window=window, min_periods=window).mean() / (4.0 * np.log(2.0)) + return np.sqrt(variance.clip(lower=0.0)) + + +def _compute_parkinson_vol_zscore(parkinson_vol: pd.Series, window: int = PARKINSON_VOL_ZSCORE_WINDOW_DAYS, + min_periods: int = PARKINSON_VOL_ZSCORE_MIN_PERIODS) -> pd.Series: + mean = parkinson_vol.rolling(window, min_periods=min_periods).mean() + std = parkinson_vol.rolling(window, min_periods=min_periods).std() + z = (parkinson_vol - mean) / std.replace(0.0, np.nan) + return z.clip(-PARKINSON_VOL_ZSCORE_CLIP, PARKINSON_VOL_ZSCORE_CLIP).fillna(0.0) + + +def _compute_vol_of_vol_zscore(parkinson_vol: pd.Series, lookback: int = VOL_OF_VOL_LOOKBACK_DAYS, + window: int = VOL_OF_VOL_ZSCORE_WINDOW_DAYS, + min_periods: int = VOL_OF_VOL_ZSCORE_MIN_PERIODS) -> pd.Series: + vol_of_vol = parkinson_vol.rolling(lookback, min_periods=lookback).std() + mean = vol_of_vol.rolling(window, min_periods=min_periods).mean() + std = vol_of_vol.rolling(window, min_periods=min_periods).std() + z = (vol_of_vol - mean) / std.replace(0.0, np.nan) + return z.clip(-VOL_OF_VOL_ZSCORE_CLIP, VOL_OF_VOL_ZSCORE_CLIP).fillna(0.0) + + +# --- V27 — espejo 1:1 de train_kodaquant_v5.py (mismas ventanas, mismos +# clips, mismas fórmulas). Todo trailing: cero lookahead, cero fetch nuevo. +def _rolling_zscore(s: pd.Series, window: int, min_periods: int, clip: float) -> pd.Series: + mean = s.rolling(window, min_periods=min_periods).mean() + std = s.rolling(window, min_periods=min_periods).std() + z = (s - mean) / std.replace(0.0, np.nan) + return z.replace([np.inf, -np.inf], np.nan).clip(-clip, clip).fillna(0.0) + + +def _compute_garman_klass_vol(open_: Optional[pd.Series], high: pd.Series, low: pd.Series, + close: pd.Series, window: int = GK_VOL_LOOKBACK_DAYS) -> pd.Series: + """sigma^2 = 0.5*ln(H/L)^2 - (2ln2-1)*ln(C/O)^2, media rolling. + + `open_` NO se decide acá: lo impone `scalers["gk_uses_open"]` vía + `_fetch_feature_window`. Elegir la rama localmente produciría un número + distinto al de entrenamiento contra el MISMO feature_scaler. + """ + var = 0.5 * np.log(high / low) ** 2 + if open_ is not None: + var = var - (2.0 * np.log(2.0) - 1.0) * np.log(close / open_) ** 2 + var = var.replace([np.inf, -np.inf], np.nan) + return np.sqrt(var.rolling(window, min_periods=window).mean().clip(lower=0.0)) + + +def _compute_fib_gap_zscore(high: pd.Series, low: pd.Series, close: pd.Series, + window: int) -> pd.Series: + """Distancia FIRMADA al nivel de Fibonacci más cercano, z-scoreada.""" + swing_high = high.rolling(window, min_periods=window).max() + swing_low = low.rolling(window, min_periods=window).min() + rng = (swing_high - swing_low).replace(0.0, np.nan) + pos = (close - swing_low) / rng + + gaps = np.stack([(pos - r).to_numpy(dtype=float) for r in FIB_RATIOS], axis=1) + abs_gaps = np.abs(gaps) + all_nan = np.isnan(abs_gaps).all(axis=1) + nearest = gaps[np.arange(gaps.shape[0]), + np.where(np.isnan(abs_gaps), np.inf, abs_gaps).argmin(axis=1)] + nearest[all_nan] = np.nan + return _rolling_zscore(pd.Series(nearest, index=close.index), + FIB_ZSCORE_WINDOW_DAYS, FIB_ZSCORE_MIN_PERIODS, FIB_ZSCORE_CLIP) + + +def _compute_ofi_proxy_zscore(high: pd.Series, low: pd.Series, close: pd.Series, + volume: pd.Series, lookback: int = OFI_LOOKBACK_DAYS) -> pd.Series: + """Order Flow Imbalance proxy: CLV ponderado por volumen, normalizado.""" + rng = (high - low).replace(0.0, np.nan) + clv = ((close - low) - (high - close)) / rng + signed_vol = (clv * volume).replace([np.inf, -np.inf], np.nan) + num = signed_vol.rolling(lookback, min_periods=lookback).sum() + den = volume.rolling(lookback, min_periods=lookback).sum().replace(0.0, np.nan) + return _rolling_zscore((num / den), OFI_ZSCORE_WINDOW_DAYS, + OFI_ZSCORE_MIN_PERIODS, OFI_ZSCORE_CLIP) + + +def _compute_return_entropy_zscore(log_return: pd.Series, + window: int = ENTROPY_WINDOW_DAYS) -> pd.Series: + """Entropía de Shannon normalizada de los retornos simbolizados en 3 estados.""" + sigma = log_return.rolling(ENTROPY_SIGMA_LOOKBACK, + min_periods=ENTROPY_SIGMA_LOOKBACK).std() + thr = ENTROPY_DEADZONE_SIGMA * sigma + up = (log_return > thr).astype(float) + down = (log_return < -thr).astype(float) + flat = 1.0 - up - down + + h = None + for state in (up, down, flat): + p = state.rolling(window, min_periods=window).mean() + term = -(p * np.log(p.where(p > 0.0))) + h = term if h is None else h.add(term, fill_value=0.0) + h = (h / np.log(3.0)).where(sigma.notna()) + return _rolling_zscore(h, ENTROPY_ZSCORE_WINDOW_DAYS, + ENTROPY_ZSCORE_MIN_PERIODS, ENTROPY_ZSCORE_CLIP) + + +def _compute_indicator_states(close_df: pd.DataFrame, ticker: str, vix_ticker: str) -> dict: + """ + Estado recursivo final de RSI/EMA/MACD/SENTIMENT/ATR/BB_WIDTH/OBV/ADX_14/ + STOCH_K_14/NEWS_SENTIMENT_SCORE sobre el historial real — necesario para + actualizarlos incrementalmente dentro del bucle autoregresivo en vez de + congelarlos (ver _forecast_asset). + + `close_df` es el frame COMPLETO devuelto por `_fetch_feature_window` + (incluye `f"{ticker}_High"` / `f"{ticker}_Low"` / `f"{ticker}_Volume"` + además de la serie de precio bajo la columna `ticker`) — ATR_14 y OBV + necesitan ese OHLCV real para su estado inicial, no solo el precio. + `vix_ticker` (resuelto vía `_resolve_vix_ticker`) también debe estar + presente como columna en `close_df` — SENTIMENT_SCORE (Hallazgo F5, ver + `_compute_sentiment_score`) necesita la ventana PAREADA de log-returns + activo/VIX, no solo la del activo. + """ + close_series = close_df[ticker] + high_series = close_df[f"{ticker}_High"] + low_series = close_df[f"{ticker}_Low"] + volume_series = close_df[f"{ticker}_Volume"] + + delta = close_series.diff() + gain = delta.clip(lower=0.0) + loss = -delta.clip(upper=0.0) + avg_gain = gain.ewm(alpha=1 / 14, min_periods=14, adjust=False).mean().iloc[-1] + avg_loss = loss.ewm(alpha=1 / 14, min_periods=14, adjust=False).mean().iloc[-1] + ema_fast = close_series.ewm(span=12, adjust=False).mean().iloc[-1] + ema_slow = close_series.ewm(span=26, adjust=False).mean().iloc[-1] + ema_20 = close_series.ewm(span=20, adjust=False).mean().iloc[-1] + macd_line = ( + close_series.ewm(span=12, adjust=False).mean() + - close_series.ewm(span=26, adjust=False).mean() + ) + macd_signal = macd_line.ewm(span=9, adjust=False).mean().iloc[-1] + + # Estado recursivo de SENTIMENT_SCORE (Hallazgo F5 — correlación de + # Pearson móvil activo/VIX, ver `_compute_sentiment_score`): a diferencia + # de RSI/EMA/MACD (que se resumen en un puñado de escalares IIR), la + # correlación necesita la ventana CRUDA PAREADA de los últimos + # `SENTIMENT_LOOKBACK_DAYS` log-returns reales — del activo Y de VIX, + # misma fecha a fecha — para poder recalcular la correlación sobre una + # ventana deslizante en cada paso del bucle (ver _forecast_asset). Se + # guarda tal cual — sin recortar ni promediar — para no perder precisión. + log_returns_hist = np.log(close_series / close_series.shift(1)).dropna() + tail_returns = log_returns_hist.tail(SENTIMENT_LOOKBACK_DAYS).to_numpy(dtype=np.float64) + if len(tail_returns) < SENTIMENT_LOOKBACK_DAYS: + # Historial insuficiente (activo recién listado): rellena por + # delante repitiendo el primer valor disponible, o con ceros si no + # hay ninguno — evita un ValueError en el reshape aguas abajo. + pad = SENTIMENT_LOOKBACK_DAYS - len(tail_returns) + fill_value = tail_returns[0] if len(tail_returns) else 0.0 + tail_returns = np.concatenate([np.full(pad, fill_value), tail_returns]) + + vix_series = close_df[vix_ticker] + vix_log_returns_hist = np.log(vix_series / vix_series.shift(1)).dropna() + tail_returns_vix = vix_log_returns_hist.tail(SENTIMENT_LOOKBACK_DAYS).to_numpy(dtype=np.float64) + if len(tail_returns_vix) < SENTIMENT_LOOKBACK_DAYS: + pad_vix = SENTIMENT_LOOKBACK_DAYS - len(tail_returns_vix) + fill_value_vix = tail_returns_vix[0] if len(tail_returns_vix) else 0.0 + tail_returns_vix = np.concatenate([np.full(pad_vix, fill_value_vix), tail_returns_vix]) + + # --- V3: ATR_14 — último valor real del EWM de Wilder (High/Low/Close + # reales). El bucle autoregresivo lo continúa con velas SINTÉTICAS + # degeneradas (High=Low=Close del día proyectado, ver _forecast_asset) — + # solo el estado INICIAL usa OHLC genuino. + atr_prev = float(_compute_atr(high_series, low_series, close_series).iloc[-1]) + + # --- V3: BB_WIDTH_20 — ventana CRUDA de los últimos 20 precios REALES + # (a nivel precio, no retorno) — mismo patrón que log_return_window, + # necesaria para recalcular media/std móvil de precio en cada paso. + tail_prices = close_series.tail(BB_WIDTH_WINDOW).to_numpy(dtype=np.float64) + if len(tail_prices) < BB_WIDTH_WINDOW: + pad = BB_WIDTH_WINDOW - len(tail_prices) + fill_value = tail_prices[0] if len(tail_prices) else float(close_series.iloc[-1]) + tail_prices = np.concatenate([np.full(pad, fill_value), tail_prices]) + + # --- V3: OBV — último acumulado REAL + proxy de volumen para los pasos + # sintéticos (ver OBV_VOLUME_PROXY_LOOKBACK_DAYS arriba: este motor no + # proyecta volumen, solo precio). + obv_series = _compute_obv(close_series, volume_series) + obv_prev = float(obv_series.iloc[-1]) + volume_tail_mean = volume_series.tail(OBV_VOLUME_PROXY_LOOKBACK_DAYS).mean() + volume_proxy = float(volume_tail_mean) if pd.notna(volume_tail_mean) else 0.0 + # --- V6: ventana CRUDA de los últimos OBV_ROC_LOOKBACK_DAYS valores + # REALES de OBV (mismo patrón que `tail_prices`/`stoch_high_window`) — + # necesaria para derivar OBV_ROC_20 = (OBV_t - OBV_{t-20}) / OBV_{t-20} + # sobre una ventana deslizante en cada paso del bucle autoregresivo. + obv_window = obv_series.tail(OBV_ROC_LOOKBACK_DAYS).to_numpy(dtype=np.float64) + if len(obv_window) < OBV_ROC_LOOKBACK_DAYS: + pad = OBV_ROC_LOOKBACK_DAYS - len(obv_window) + fill_value = obv_window[0] if len(obv_window) else obv_prev + obv_window = np.concatenate([np.full(pad, fill_value), obv_window]) + + # --- V5: ADX_14 — estado recursivo (+DM/-DM suavizados de Wilder). + adx_state = _compute_adx_state(high_series, low_series, close_series) + + # --- V5: STOCH_K_14 — ventana CRUDA de los últimos 14 High/Low reales + # (rolling min/max, no EWM) — mismo patrón que price_window (BB_WIDTH). + stoch_high_window = high_series.tail(STOCH_K_PERIOD).to_numpy(dtype=np.float64) + stoch_low_window = low_series.tail(STOCH_K_PERIOD).to_numpy(dtype=np.float64) + if len(stoch_high_window) < STOCH_K_PERIOD: + pad = STOCH_K_PERIOD - len(stoch_high_window) + fill_h = stoch_high_window[0] if len(stoch_high_window) else float(close_series.iloc[-1]) + fill_l = stoch_low_window[0] if len(stoch_low_window) else float(close_series.iloc[-1]) + stoch_high_window = np.concatenate([np.full(pad, fill_h), stoch_high_window]) + stoch_low_window = np.concatenate([np.full(pad, fill_l), stoch_low_window]) + + # --- V5: NEWS_SENTIMENT_SCORE — último valor real (FinBERT/Finnhub, ya + # calculado en `_fetch_feature_window`); se mantiene CONSTANTE en cada + # paso sintético del bucle — este motor no proyecta noticias futuras, + # mismo criterio de honestidad que el volume_proxy de OBV. + news_sentiment_last = float(close_df["NEWS_SENTIMENT_SCORE"].iloc[-1]) + + return { + "avg_gain": float(avg_gain) if pd.notna(avg_gain) else 0.0, + "avg_loss": float(avg_loss) if pd.notna(avg_loss) else 0.0, + "ema_fast": float(ema_fast), + "ema_slow": float(ema_slow), + "ema_20": float(ema_20), + "macd_signal": float(macd_signal), + "log_return_window": tail_returns, # shape (SENTIMENT_LOOKBACK_DAYS,) + "log_return_window_vix": tail_returns_vix, # shape (SENTIMENT_LOOKBACK_DAYS,) — Hallazgo F5 + "atr_prev": atr_prev, + "price_window": tail_prices, # shape (BB_WIDTH_WINDOW,) + "obv_prev": obv_prev, + "obv_window": obv_window, # shape (OBV_ROC_LOOKBACK_DAYS,) + "volume_proxy": max(volume_proxy, 0.0), + "adx_prev": adx_state["adx_prev"], + "plus_dm_smooth_prev": adx_state["plus_dm_smooth_prev"], + "minus_dm_smooth_prev": adx_state["minus_dm_smooth_prev"], + "stoch_high_window": stoch_high_window, # shape (STOCH_K_PERIOD,) + "stoch_low_window": stoch_low_window, # shape (STOCH_K_PERIOD,) + "news_sentiment_last": news_sentiment_last, + } + + +def _fetch_feature_window( + ticker: str, + macro_tickers: list, + lookback: int, + as_of_date: str | None = None, + scalers: dict | None = None, +) -> tuple[pd.DataFrame, np.ndarray]: + """ + AUDITORÍA RESCATE 2026-08 -- `scalers` (opcional, default None por + compatibilidad con cualquier caller que no lo pase) permite leer + `scalers["ffd_d_by_ticker"]` (ver train_kodaquant_v5.py -- persiste el + `d` REAL calibrado en entrenamiento para FRAC_DIFF_LOG_CLOSE) en vez de + recalibrar por ADF sobre la ventana corta de inferencia (fix de + desalineación train/serve, ver bloque FRAC_DIFF_LOG_CLOSE más abajo). + Sin este argumento (o con un bundle viejo que no tiene la clave), el + comportamiento es IDÉNTICO al previo (recalibra localmente). + + Ingesta en vivo — DEBE replicar bit a bit `engineer_asset()` del notebook, + con una salvedad de PRODUCCIÓN: los filtros IIR recursivos (RSI/EMA/MACD, + todos `ewm(adjust=False)`) requieren un tramo de calentamiento largo para + converger al mismo estado recursivo con el que el Colab entrenó (10y de + historia). Descargar 10y en cada request mataría la latencia de la API; + "6mo" (el valor previo) dejaba un warm-up demasiado corto (~126 sesiones) + frente a un span MACD_SLOW=26 / RSI=14, con transitorio aún no aplanado. + + FIX DE CONVERGENCIA: se descargan 2 AÑOS ("2y", ~504 sesiones) — suficiente + burn-in para que el estado recursivo de RSI_14/EMA_20/MACD/MACD_SIGNAL + converja de forma prácticamente indistinguible del estado alcanzado con + 10y de historia, sin penalizar la latencia como lo haría "10y" completo. + + RECORTE ANTES DE RETORNAR (crítico): el DataFrame `close` (precios + + indicadores YA estabilizados por los 2y de warm-up) se retorna COMPLETO + porque callers aguas abajo lo necesitan más allá de `lookback`: + - `_compute_indicator_states(close_df, ticker, vix_ticker)` recalcula + RSI/EMA/MACD/SENTIMENT/ATR_14/BB_WIDTH_20/OBV desde cero sobre la + serie de precios (y OHLCV) completa — si se le pasara solo + `lookback` filas, se perdería TODO el beneficio de los 2y de + calentamiento que acabamos de pagar en la descarga. + - `vol_window = close_df[ticker].tail(VOLATILITY_LOOKBACK_DAYS + 1)` + (63+1 días) y `historical = close_df[ticker].tail(hist_window)` + (hasta 90 días, ver `_historical_window_for_horizon`) exceden + `lookback` en la mayoría de configuraciones. + Lo único que el tensor 3D de la Bi-LSTM necesita es la ÚLTIMA ventana de + `lookback` filas — por eso, y SOLO para `raw_features` (el array que + alimenta al modelo), se recorta estrictamente a `[-lookback:]` antes de + devolverlo. `close` (para todo lo demás) permanece intacto. + """ + all_symbols = list(dict.fromkeys([ticker] + macro_tickers)) + # V3: bundle OHLCV COMPLETO solo para el ticker objetivo — ATR_14 + # necesita High/Low, OBV necesita Volume. Los macro tickers permanecen + # Close-only, replicando exactamente engineer_asset()/download_all() del + # notebook (no se calculan técnicos sobre los factores macro). Columnas + # planas `f"{ticker}_High"` / `_Low` / `_Volume`, mismo patrón de + # nombrado que download_all() en entrenamiento.py. `fetch_feature_ohlcv` + # (services/market_data.py, Twelve Data + fallback Stooq) ya devuelve + # exactamente este layout -- reemplaza 1:1 el antiguo `yf.download`. + close = fetch_feature_ohlcv(ticker, macro_tickers, min_sessions=DEFAULT_HISTORY_SESSIONS) + close = close.ffill().dropna() + + # --- FIX VELA VIVA (cripto 24/7, sin campana de cierre) ----------------- + # Un Daily Close consolidado para un activo 24/7 solo existe DESPUÉS de + # las 00:00 UTC del día siguiente. Si este pipeline corre en cualquier + # momento ANTES de ese corte para el día de "hoy" (UTC), la última fila + # que yfinance devuelve para el ticker cripto es un snapshot EN VIVO + # (precio al instante de la query), no un cierre real — y ese snapshot + # cambia cada vez que se re-corre el pipeline en el mismo día. Usarlo + # tal cual como último punto de `historical`/ancla del forecast produce + # exactamente el desfase reportado: el "cierre" no es reproducible ni + # coincide con el cierre real posterior de esa misma fecha. Equities NO + # tienen este problema — yfinance no publica la fila del día en curso + # hasta después de la campana de cierre — así que el fix se acota + # estrictamente al régimen 24/7 (mismo patrón que el resto del motor, + # ver `regime == "crypto_specialist"` más abajo). Se dropea la fila + # completa (todas las columnas, incluidos los macro tickers) porque una + # sesión de "hoy" sin cerrar tampoco es un dato consolidado válido para + # ningún otro campo derivado de esa misma fila. + if ticker in REGIME_TICKERS.get("crypto_specialist", ()) and not close.empty: + today_utc = datetime.now(timezone.utc).date() + if close.index[-1].date() >= today_utc: + close = close.iloc[:-1] + if close.empty: + raise ValueError( + f"'{ticker}': sin ninguna sesión UTC consolidada todavía tras " + "dropear la vela en vivo de hoy — histórico insuficiente para " + "construir la ventana de features." + ) + + # --- FIX PRICING (Adjusted vs Regular Close) --------------------------- + # Bajo yfinance, este bloque descargaba una SEGUNDA serie (Regular + # Close, sin ajustar) porque `auto_adjust=True` aplicaba un ajuste + # retroactivo por dividendos que no coincidía con el precio que + # realmente vio el usuario ese día — y esas dos descargas independientes + # podían desincronizarse entre sí (ver el FIX de "ancla desfasada" que + # existía acá antes de esta migración). + # + # Twelve Data no tiene esa dualidad en el plan gratuito: `time_series` + # devuelve UNA sola serie de Close (la operada, sin ajuste retroactivo + # por dividendos) — la misma que ya se usó arriba para los indicadores. + # No hay una segunda fuente que descargar ni que pueda desincronizarse: + # todo el bloque de reconciliación de dos índices queda eliminado. + # `display_col` se conserva solo por compatibilidad con los + # consumidores aguas abajo que ya leen esa columna (ver `historical` + # dentro de `_forecast_asset`). + # + # CAVEAT HONESTO (léase antes de asumir paridad con el pipeline + # anterior): si `train_kodaquant_v5.py` entrenó específicamente contra + # el Auto-Adjusted Close de Yahoo (que sí incorpora dividendos, no solo + # splits), este cambio de proveedor introduce un desvío estructural + # MENOR en la serie de precio de activos con dividendo alto (ej. AAPL, + # MSFT) alrededor de cada fecha ex-dividendo. No es un bug de esta + # migración — es una diferencia real de metodología entre fuentes de + # datos que ningún mapeo de símbolos puede maquillar. Si la paridad + # exacta con el entrenamiento original es crítica para tu caso de uso, + # conviene re-validar el error de forecast contra Twelve Data como + # fuente en vez de asumir equivalencia bit a bit con yfinance. + display_col = f"{ticker}__DISPLAY_CLOSE" + close[display_col] = close[ticker] + + # CUTOFF RETROACTIVO (online learning): si se pide reconstruir la ventana + # tal cual estaba en una fecha pasada (`as_of_date`), se descarta TODA + # fila posterior ANTES de calcular RSI/EMA/MACD — si se recortara + # después, los indicadores incorporarían "futuro" (fuga de información) + # respecto al momento real en que se generó la predicción que se está + # reevaluando. `as_of_date=None` (default, ruta de inferencia normal) + # deja el comportamiento bit a bit idéntico al de antes de este cambio. + if as_of_date is not None: + cutoff = pd.Timestamp(as_of_date) + close = close[close.index <= cutoff] + if close.empty: + raise ValueError( + f"'{as_of_date}' no tiene datos de mercado disponibles (¿fecha " + "futura o anterior al histórico descargable?) — no se puede " + "reconstruir la ventana de ese día para fine-tuning." + ) + + close["RSI_14"] = _compute_rsi(close[ticker]) # oscilador ya acotado [0,100] — sin cambios + + # --- V6: LOG_RETURN_1D reemplaza a "PRICE" (nivel absoluto) como único + # input de nivel-precio del tensor. `close[ticker]` SIGUE guardando el + # precio CRUDO — lo necesitan `last_price`/`historical`/ + # `_compute_indicator_states` y los técnicos derivados más abajo; + # LOG_RETURN_1D es una columna ADICIONAL, nunca un reemplazo. + close["LOG_RETURN_1D"] = np.log(close[ticker] / close[ticker].shift(1)) + + ema_20 = close[ticker].ewm(span=20, adjust=False).mean() + close["EMA20_DEV_PCT"] = (close[ticker] - ema_20) / ema_20 # % desviación vs. la propia media móvil + + macd_line, signal_line = _compute_macd(close[ticker]) + close["MACD_PCT"] = macd_line / close[ticker] + close["MACD_SIGNAL_PCT"] = signal_line / close[ticker] + + # Hallazgo F5: SENTIMENT_SCORE = correlación de Pearson móvil activo/VIX + # (ver _compute_sentiment_score), no un Z-score de momentum propio. + # DEBE correr con `close[vix_ticker]` TODAVÍA en precio crudo (la + # función deriva su propio log-return internamente) — por eso va ANTES + # del bloque de log-return de factores macro más abajo. + vix_ticker = _resolve_vix_ticker(macro_tickers) + close["SENTIMENT_SCORE"] = _compute_sentiment_score(close[ticker], close[vix_ticker]) + + # V3: ATR_14 -> ATR_PCT ("ATRP", normalizado por precio) — requiere + # High/Low reales del ticker, igual que antes. + atr = _compute_atr(close[f"{ticker}_High"], close[f"{ticker}_Low"], close[ticker]) + close["ATR_PCT"] = atr / close[ticker] + close["BB_WIDTH_20"] = _compute_bb_width(close[ticker]) # ya es 2σ/μ, adimensional — sin cambios + + obv = _compute_obv(close[ticker], close[f"{ticker}_Volume"]) + obv_roc = obv.pct_change(periods=OBV_ROC_LOOKBACK_DAYS) + close["OBV_ROC_20"] = obv_roc.replace([np.inf, -np.inf], np.nan).clip(-OBV_ROC_CLIP, OBV_ROC_CLIP).fillna(0.0) + + close["ADX_14"] = _compute_adx(close[f"{ticker}_High"], close[f"{ticker}_Low"], close[ticker]) + close["STOCH_K_14"] = _compute_stochastic_k(close[f"{ticker}_High"], close[f"{ticker}_Low"], close[ticker]) + # V5 (Requerimiento 1/3 del pipeline): NEWS_SENTIMENT_SCORE vía FinBERT + # (transformers) + Finnhub/yfinance.news — misma fuente que entrenó los + # especialistas. Llamada de red + inferencia local; el pipeline de + # inferencia ya paga latencia por la descarga yfinance de 2y, así que + # esto es consistente con el resto de este método (sin cache propio). + close["NEWS_SENTIMENT_SCORE"] = get_daily_news_sentiment(ticker, close.index) + + # --- AUDITORÍA RESCATE 2026-08 — FEAR_GREED_INDEX/FUNDING_RATE_ZSCORE/ + # ONCHAIN_ACTIVITY_ROC/PUELL_MULTIPLE_ZSCORE/FRAC_DIFF_LOG_CLOSE/ + # PARKINSON_VOL_ZSCORE/VOL_OF_VOL_ZSCORE -- las 7 columnas que TECH_COLS + # ya declara pero que este bloque nunca calculaba (ver auditoría al + # inicio del módulo). Réplica 1:1 de `engineer_asset` en + # train_kodaquant_v5.py, mismo criterio "neutro 0.0 fuera de cripto/BTC". + is_crypto_ticker = ticker in CRYPTO_TICKERS_V5 + + if is_crypto_ticker: + fg_series = _fetch_fear_greed_index(tail_days=3700) + if fg_series is not None and not fg_series.empty: + fg_series.index = pd.DatetimeIndex(fg_series.index).tz_localize(None) + close["FEAR_GREED_INDEX"] = fg_series.reindex(close.index).ffill().fillna(50.0) + else: + close["FEAR_GREED_INDEX"] = 50.0 + else: + close["FEAR_GREED_INDEX"] = 50.0 + + if is_crypto_ticker: + funding_series = _fetch_binance_funding_history(ticker) + if funding_series is not None and not funding_series.empty: + funding_series.index = pd.DatetimeIndex(funding_series.index).tz_localize(None) + funding_z = _compute_funding_rate_zscore(funding_series) + close["FUNDING_RATE_ZSCORE"] = funding_z.reindex(close.index).ffill().fillna(0.0) + else: + close["FUNDING_RATE_ZSCORE"] = 0.0 + else: + close["FUNDING_RATE_ZSCORE"] = 0.0 + + # AUDITORÍA RESCATE 2026-08 -- V25: ONCHAIN_ACTIVITY_ROC ahora es NVT + # Ratio Z-score (réplica EXACTA de train_kodaquant_v5.py::engineer_asset, + # ver docstring ahí), con el tx-count ROC V24 como fallback si el chart + # de volumen USD no responde. MISMO nombre de columna -- cero cambio de + # shape/N_FEATURES. + if ticker == BTC_TICKER_V5: + tx_value_series = _fetch_onchain_tx_volume_usd() + if tx_value_series is not None and not tx_value_series.empty: + tx_value_series.index = pd.DatetimeIndex(tx_value_series.index).tz_localize(None) + nvt_z = _compute_nvt_ratio_zscore(close[ticker], tx_value_series.reindex(close.index).ffill()) + close["ONCHAIN_ACTIVITY_ROC"] = nvt_z.reindex(close.index).fillna(0.0) + else: + onchain_series = _fetch_onchain_activity() + if onchain_series is not None and not onchain_series.empty: + onchain_series.index = pd.DatetimeIndex(onchain_series.index).tz_localize(None) + onchain_roc = onchain_series.pct_change(periods=ONCHAIN_ROC_LOOKBACK_DAYS) + onchain_roc = onchain_roc.replace([np.inf, -np.inf], np.nan).clip(-ONCHAIN_ROC_CLIP, ONCHAIN_ROC_CLIP) + close["ONCHAIN_ACTIVITY_ROC"] = onchain_roc.reindex(close.index).ffill().fillna(0.0) + else: + close["ONCHAIN_ACTIVITY_ROC"] = 0.0 + else: + close["ONCHAIN_ACTIVITY_ROC"] = 0.0 + + if ticker == BTC_TICKER_V5: + close["PUELL_MULTIPLE_ZSCORE"] = _compute_puell_multiple_zscore(close[ticker]) + else: + close["PUELL_MULTIPLE_ZSCORE"] = 0.0 + + # AUDITORÍA RESCATE 2026-08 -- fix de desalineación train/serve: usa el + # `d` REAL calibrado en entrenamiento (persistido en `scalers_dict.pkl`, + # ver train_kodaquant_v5.py::_LAST_FFD_D_BY_TICKER) en vez de recalibrar + # por ADF sobre esta ventana corta de inferencia. Bundle viejo sin la + # clave (o `scalers=None`) -> fallback IDÉNTICO al comportamiento previo. + if is_crypto_ticker: + persisted_ffd_d = (scalers or {}).get("ffd_d_by_ticker", {}).get(ticker) + ffd_d = float(persisted_ffd_d) if persisted_ffd_d is not None else _find_min_ffd_d(np.log(close[ticker])) + close["FRAC_DIFF_LOG_CLOSE"] = _frac_diff_ffd(np.log(close[ticker]), ffd_d) + else: + close["FRAC_DIFF_LOG_CLOSE"] = 0.0 + + _parkinson_vol = _compute_parkinson_vol(close[f"{ticker}_High"], close[f"{ticker}_Low"]) + close["PARKINSON_VOL_ZSCORE"] = _compute_parkinson_vol_zscore(_parkinson_vol) + if is_crypto_ticker: + close["VOL_OF_VOL_ZSCORE"] = _compute_vol_of_vol_zscore(_parkinson_vol) + else: + close["VOL_OF_VOL_ZSCORE"] = 0.0 + + # --- V27: microestructura OHLC + geometría fractal + flujo + caos ------ + # AMBOS regímenes, 100% OHLCV ya en scope -- cero fetch nuevo. + _gk_uses_open = bool((scalers or {}).get("gk_uses_open", False)) + _open_col = f"{ticker}_Open" + if _gk_uses_open and _open_col not in close.columns: + raise RuntimeError( + f"[GK] '{ticker}': el entrenamiento calculó GARMAN_KLASS_VOL_ZSCORE CON el " + f"término ln(C/O) (scalers['gk_uses_open']=True) pero '{_open_col}' no está en " + "este feed de inferencia. Calcular la rama H/L acá produciría un valor " + "numéricamente distinto contra el MISMO feature_scaler -- desync silencioso. " + "Agregá 'Open' a fetch_feature_ohlcv (services/market_data.py) o reentrená " + "sin Open. NO se degrada en silencio a propósito." + ) + _gk_open = close[_open_col] if _gk_uses_open else None + _high, _low, _vol = close[f"{ticker}_High"], close[f"{ticker}_Low"], close[f"{ticker}_Volume"] + close["GARMAN_KLASS_VOL_ZSCORE"] = _rolling_zscore( + _compute_garman_klass_vol(_gk_open, _high, _low, close[ticker]), + GK_ZSCORE_WINDOW_DAYS, GK_ZSCORE_MIN_PERIODS, GK_ZSCORE_CLIP) + + for _w in FIB_WINDOWS: + close[f"FIB_GAP_Z_{_w}"] = _compute_fib_gap_zscore(_high, _low, close[ticker], _w) + + close["OFI_PROXY_ZSCORE"] = _compute_ofi_proxy_zscore(_high, _low, close[ticker], _vol) + close["RETURN_ENTROPY_ZSCORE"] = _compute_return_entropy_zscore( + np.log(close[ticker] / close[ticker].shift(1))) + + # --- V28: free_alpha.py -- réplica 1:1 de engineer_asset (misma función) --- + # Cualquier fuente caída / Open ausente -> 0.0 neutro + log (nunca excepción). + # Corre ANTES del log-return macro: `close["^GSPC"]` sigue en precio crudo. + _v28_flush_cache_on_utc_rollover() + if is_crypto_ticker: + for _c in V28_EQUITY_COLS: + close[_c] = 0.0 + try: + _flow = build_crypto_flow_features(ticker, close.index, cache=None) + if len(_flow) != len(close): + raise ValueError(f"len(flow)={len(_flow)} != len(close)={len(close)}") + _flow_arr = _flow[V28_CRYPTO_COLS].to_numpy(dtype=float) + except Exception as exc: # noqa: BLE001 -- proveedor opcional, degrada a neutro + logger.error("[V28] '%s': flujo cripto falló (%r) -> 4 cols = 0.0 " + "(skew vs. entrenamiento).", ticker, exc) + _flow_arr = np.zeros((len(close), len(V28_CRYPTO_COLS))) + _flow_arr = np.nan_to_num(_flow_arr, nan=0.0, posinf=0.0, neginf=0.0) + for _i, _c in enumerate(V28_CRYPTO_COLS): + close[_c] = _flow_arr[:, _i] + else: + for _c in V28_CRYPTO_COLS: + close[_c] = 0.0 + _v28_open_col = f"{ticker}_Open" + _v28_open = close[_v28_open_col] if _v28_open_col in close.columns else None + _v28_trained = (scalers or {}).get("v28_open_by_ticker") + if _v28_trained is not None: + if bool(_v28_trained.get(ticker, False)) and _v28_open is None: + logger.error("[V28] '%s': entrenado CON Open pero el feed live no trae '%s' -> " + "OVERNIGHT_GAP/INTRADAY_RET/OVERNIGHT_MOM = 0.0 (SKEW train/serve). " + "Agregar 'Open' a services/market_data.fetch_feature_ohlcv.", + ticker, _v28_open_col) + elif not bool(_v28_trained.get(ticker, False)): + _v28_open = None # train usó 0.0 constante: paridad estricta + _v28_spx = (np.log(close["^GSPC"] / close["^GSPC"].shift(1)) + if "^GSPC" in macro_tickers and "^GSPC" in close.columns else None) + _v28_eq = compute_equity_open_features(_v28_open, close[ticker], _v28_spx, ticker) + for _c in V28_EQUITY_COLS: + close[_c] = _v28_eq[_c] + + # --- FIX CRÍTICO (auditoría de paridad train/serve, previa a V6): + # `engineer_asset()` en train_kodaquant_v5.py transforma CADA factor + # macro a log-return ANTES de que `feature_scaler.fit()` los vea + # (estacionariedad, V4) — esta función NUNCA replicaba ese paso: los + # macro_tickers llegaban a `feature_cols` (más abajo) en NIVEL DE + # PRECIO CRUDO (ej. ^GSPC≈6000, ^TNX≈4.2, GC=F≈2400, DX-Y.NYB≈100) + # contra un `feature_scaler` calibrado para log-returns ≈[-0.05, 0.05] + # — saturación masiva en TODOS los timesteps de la ventana (no solo los + # sintéticos), consistente con el oob_frac=45.6% medido en T+1 (100% + # datos reales) que se venía atribuyendo enteramente al ATH. Se + # transforma en columnas NUEVAS (sufijo `__LOGRET`) en vez de + # sobreescribir `close[macro_ticker]` in-place: `_compute_indicator_ + # states`/`_resolve_vix_ticker` más abajo en `_forecast_asset` siguen + # necesitando el precio CRUDO del VIX. + macro_logret_cols = [f"{m}__LOGRET" for m in macro_tickers] + for macro_ticker, logret_col in zip(macro_tickers, macro_logret_cols): + macro_price = close[macro_ticker] + close[logret_col] = np.log(macro_price / macro_price.shift(1)) + + close = close.ffill().dropna() + + # Orden EXACTO de TECH_COLS (ver constante de módulo, arriba — sincronizada + # con train_kodaquant_v5.py tras la auditoría 2026-08): RSI_14, + # EMA20_DEV_PCT, MACD_PCT, MACD_SIGNAL_PCT, SENTIMENT_SCORE, ATR_PCT, + # BB_WIDTH_20, OBV_ROC_20, ADX_14, STOCH_K_14, NEWS_SENTIMENT_SCORE, + # FEAR_GREED_INDEX, FUNDING_RATE_ZSCORE, ONCHAIN_ACTIVITY_ROC, + # FRAC_DIFF_LOG_CLOSE, PUELL_MULTIPLE_ZSCORE, PARKINSON_VOL_ZSCORE, + # VOL_OF_VOL_ZSCORE — el feature_scaler cargado desde scalers_dict.pkl fue + # ajustado con ese orden/definición, así que romperlo aquí desalinearía + # cada columna al pasar por `.transform()`. `_get_scalers()` ya valida que + # TECH_COLS coincide con `scalers["tech_cols"]` al arrancar el proceso. El + # tramo macro usa las columnas `__LOGRET` (estacionarias) — NUNCA el + # precio crudo `macro_tickers`, que sigue vivo en `close` solo para los + # otros consumidores señalados arriba. + feature_cols = ["LOG_RETURN_1D"] + TECH_COLS + macro_logret_cols + + # Recorte estricto: SOLO el tensor de entrada a la red se acota a + # `lookback` filas. `close` se retorna completo (2y) para los + # consumidores que necesitan más historia que la ventana del modelo. + raw_features = close[feature_cols].values[-lookback:] + + # V28 -- guardia dura de forma: un entero de desalineación contra el + # feature_scaler ajustado en train debe fallar AQUÍ, no dentro de Keras. + _n_expected = getattr(((scalers or {}).get("feature_scalers") or {}).get(ticker), + "n_features_in_", None) + if _n_expected is not None and raw_features.shape[1] != _n_expected: + raise ValueError( + f"[V28] '{ticker}': tensor de inferencia con {raw_features.shape[1]} features, " + f"feature_scaler entrenado con {_n_expected}. Regenerar artefactos con " + "train_kodaquant_v5.py (TECH_COLS/V28_COLS desalineados).") + + return close, raw_features + + +# --------------------------------------------------------------------------- +# Inferencia Keras / TensorFlow nativa (MC Dropout real vía training=True) +# --------------------------------------------------------------------------- + +def _resolve_horizon_days(forecast_horizon_days: int | None) -> int: + """ + Clamp defensivo del horizonte de proyección: cualquier entero positivo + razonable se respeta; basura (None, <=0, no-entero) cae al default de + 1 semana; se topa a 252 sesiones (~1 año bursátil). + """ + if not isinstance(forecast_horizon_days, int) or isinstance(forecast_horizon_days, bool): + return DEFAULT_FORECAST_HORIZON_DAYS + if forecast_horizon_days <= 0: + return DEFAULT_FORECAST_HORIZON_DAYS + return min(forecast_horizon_days, 252) + + +def _find_optimal_entry_exit( + forecast_points: list[dict], + anchor_date: str | None = None, + anchor_price: float | None = None, +) -> dict | None: + """ + Peak & Trough Analysis — ESTRICTAMENTE cronológico. El tiempo es lineal: + jamás se puede vender antes o el mismo día que se compra. + + Paso A) Día de Compra = precio MÍNIMO GLOBAL de todo el arreglo de + proyección (`forecast_points`). + Paso B) Día de Venta = precio MÁXIMO, buscado ÚNICAMENTE en el slice de + `forecast_points` posterior al índice de compra + (`forecast_points[entry_idx + 1:]`) — nunca en el mismo día, + nunca antes. + + Si el mínimo global cae en el ÚLTIMO día proyectado, no queda ventana de + salida posterior dentro del propio arreglo. En ese caso degrada a un plan + defensivo en vez de no emitir señal: Compra HOY (`anchor_date` / + `anchor_price`, el último precio real ya conocido, anterior a toda la + proyección) y Vende en el último día proyectado. Nunca inventa una fecha + o precio fuera de estos dos ya calculados. + """ + if not forecast_points: + return None + + entry_idx = min(range(len(forecast_points)), key=lambda i: forecast_points[i]["expected_path"]) + entry = forecast_points[entry_idx] + + remaining = forecast_points[entry_idx + 1:] + if remaining: + exit_point = max(remaining, key=lambda p: p["expected_path"]) + return { + "entry_date": entry["date"], + "entry_price": entry["expected_path"], + "exit_date": exit_point["date"], + "exit_price": exit_point["expected_path"], + } + + # El mínimo global es el ÚLTIMO día proyectado: no hay slice posterior. + # Fallback defensivo — compra HOY, vende en el último día proyectado. + if anchor_date is None or anchor_price is None: + return None + + last_point = forecast_points[-1] + if last_point["date"] == anchor_date: + # Degenerado: no hay ni un día futuro distinto de hoy — sin señal. + return None + + return { + "entry_date": anchor_date, + "entry_price": anchor_price, + "exit_date": last_point["date"], + "exit_price": last_point["expected_path"], + } + + +def _validate_date_str(value) -> str | None: + """ + VERIFICACIÓN CRÍTICA (post-mortem: el LLM omitía fechas cuando algo + corrupto llegaba a la plantilla). `entry_date`/`exit_date` deberían + llegar siempre como 'YYYY-MM-DD' (vienen de `strftime` en + `_forecast_asset`), pero esta función lo confirma explícitamente antes + de que cualquier fecha toque el prompt: si no es un string con esa + forma exacta, retorna None en vez de dejar pasar un valor corrupto + (None, '', un float, un objeto date sin castear, etc.) a la f-string. + """ + if not isinstance(value, str): + return None + value = value.strip() + if len(value) != 10 or value[4] != "-" or value[7] != "-": + return None + year, month, day = value[:4], value[5:7], value[8:10] + if not (year.isdigit() and month.isdigit() and day.isdigit()): + return None + return value + + +def _build_tactical_operation(plan: dict) -> dict | None: + """ + Traduce el `tactical_signal` (Peak & Trough, ver `_find_optimal_entry_exit`) + de UN plan (Plan A o Plan B, ambos pasan por aquí — jamás solo Plan B) a + una Operación Táctica ejecutable, agregando la Ganancia Neta Proyectada en + USD: capital asignado a ESE activo × diferencial de precios entrada/salida. + + Este cálculo vive 100% en Python — verdad absoluta. El LLM NUNCA lo + recalcula, solo lo narra (ver REGLA ANTI-ALUCINACIÓN en + `_build_system_prompt`). + + Retorna None si el forecast del plan falló, si no hay ventana de salida + válida, o si `entry_date`/`exit_date` no pasan `_validate_date_str` — en + los tres casos el prompt debe degradar sin inventar fecha/precio/ganancia. + """ + forecast = plan.get("forecast") + if not forecast: + return None + + tactical_signal = forecast.get("tactical_signal") + if not tactical_signal: + return None + + entry_date = _validate_date_str(tactical_signal.get("entry_date")) + exit_date = _validate_date_str(tactical_signal.get("exit_date")) + if entry_date is None or exit_date is None: + print( + f"⚠️ Fecha inválida en tactical_signal de {plan.get('activo_referencia')} " + f"(entry={tactical_signal.get('entry_date')!r}, exit={tactical_signal.get('exit_date')!r}) " + "— se omite la operación en vez de inyectar una fecha corrupta al prompt." + ) + return None + + entry_price = tactical_signal["entry_price"] + exit_price = tactical_signal["exit_price"] + capital_usd = float(plan["monto_usd"]) + + price_return_pct = (exit_price / entry_price - 1) if entry_price else 0.0 + net_profit_usd = round(capital_usd * price_return_pct, 2) + + return { + "ticker": plan["activo_referencia"], + "nombre_plan": plan["nombre"], + "capital_usd": round(capital_usd, 2), + "entry_date": entry_date, + "entry_price": entry_price, + "exit_date": exit_date, + "exit_price": exit_price, + "net_profit_usd": net_profit_usd, + } + +def _historical_window_for_horizon(steps: int) -> int: + """ + El panel histórico debe verse proporcional a lo proyectado — 30 días + fijos contra un horizonte de 63 (3M) deja la gráfica ~68% forecast / + 32% historia real. Regla: ~1.5x el horizonte, acotado a [30, 90]. + """ + return max(30, min(90, int(steps * 1.5))) + +# --------------------------------------------------------------------------- +# V22 — Inferencia target_mode="triple_barrier" (crypto_specialist). +# --------------------------------------------------------------------------- +# `_forecast_asset` (regresión, ver más abajo) es un motor AUTOREGRESIVO: +# encadena `steps` forward passes de una cabeza Dense(2) [mu, log_var] que +# predice un log-return de UN solo paso, y ese paso se retroalimenta al +# siguiente. La cabeza Triple Barrier (Dense(3, softmax)) no predice un +# retorno de un solo paso — clasifica el DESENLACE completo de una apuesta +# que ya lleva codificado su propio horizonte (`max_holding_days`) en el +# entrenamiento. Encadenar `steps` clasificaciones sucesivas de esa cabeza +# (una por día, retroalimentando la "clase" al tensor de entrada del día +# siguiente) no tiene ningún fundamento estadístico: no es lo que el +# clasificador aprendió a hacer, y el propio `evaluate_asset_triple_barrier` +# de train_kodaquant_v5.py lo confirma — evalúa con UN solo +# `model.predict(...)` por ventana de test, nunca autoregresivo. Esta +# función replica ESE mismo contrato en producción. +# +# Zero-GPU budget: un solo forward pass por request (batcheado a +# TB_MC_DROPOUT_PASSES filas para MC Dropout) es órdenes de magnitud más +# barato que los `steps x N_MONTE_CARLO_SIMULATIONS` forward passes del +# régimen de regresión — el régimen crypto es, con este diseño, el MÁS +# barato de servir en CPU, no el más caro. +TB_MC_DROPOUT_PASSES = 30 # error MC ~ 1/sqrt(N); 30 estabiliza la media del softmax a bajo costo de CPU/RAM + +# Fallbacks defensivos ÚNICAMENTE — replican línea por línea los defaults de +# train_kodaquant_v5.py. `tb_params` SIEMPRE debería viajar en +# scalers_dict.pkl para target_mode="triple_barrier" (ver scalers_payload en +# run_regime_pipeline); esto solo cubre un bundle viejo/corrupto sin esa +# clave, para fallar hacia un comportamiento documentado en vez de un +# KeyError críptico en producción. V23.5: los fallbacks son el ÚLTIMO +# recurso también cuando `tb_params[ticker]` no tiene entrada propia (ver +# detección dual de esquema en `_forecast_asset_triple_barrier`). +_TB_PT_MULT_FALLBACK = 2.0 +_TB_SL_MULT_FALLBACK = 2.0 +_TB_MAX_HOLDING_DAYS_FALLBACK = 10 +_TB_VOL_LOOKBACK_FALLBACK = 20 +_TB_MIN_VOL_FALLBACK = 1e-6 +_TB_CLASS_NAMES_FALLBACK = ["SL", "TIMEOUT", "TP"] + +# Meta-labeling (López de Prado, cap. 3) — Directiva 3 de la misión: piso de +# confianza ANTES de traducir una clase predicha en señal operativa. Con 3 +# clases, 33.3% es azar puro; exigir >= 45% es una banda de convicción real. +# Es el ÚNICO lever honesto para mover precisión (win-rate de las señales +# que SÍ se operan) a costa de recall (frecuencia de señal) — el trade-off +# clásico de cualquier clasificador, no una promesa de resultado. Este valor +# es un PUNTO DE PARTIDA razonable, no una cifra medida contra tus datos: +# antes de subirlo/bajarlo en producción, corré walk_forward_eval.py / +# pnl_backtest.py y mirá cómo se mueven `signal_precision` / +# `actionable_accuracy` / `win_rate_pct` en función de este piso — ver +# MANUAL DE IGNICIÓN. +TB_MIN_SIGNAL_CONFIDENCE = 0.45 + +# V27 -- Auditoría Purged Walk-Forward completa (2026-09-25/26, 4 folds +# válidos por ticker, k=5 epochs=45 -- ver run_cpcv_audit en +# train_kodaquant_v5.py). NO es un ajuste algorítmico más: es la medición +# honesta, out-of-sample, de qué tickers tienen DirAcc real por encima del +# 53% baseline y cuáles no -- después de que sentimiento real, meta- +# labeling, ajuste de umbral, exclusión de TIMEOUT, más tickers y más +# historia (6 intentos, cripto) NO movieran el techo. Equity nunca había +# sido auditado con la misma disciplina hasta este barrido. +# +# ticker -> (dir_acc_media_cpcv, std_entre_folds, tier) +# tier: "high" (>=53%, std bajo) / "watch" (~52-53%, std bajo, cerca) / +# "low" (<52% o std alto -- el single-split original no era confiable) +EQUITY_HISTORICAL_EDGE = { + "AAPL": (0.531, 0.027, "high"), + "MSFT": (0.532, 0.022, "high"), + "NVDA": (0.527, 0.015, "watch"), + "GOOGL": (0.527, 0.017, "watch"), + "AMZN": (0.518, 0.012, "low"), + "SPY": (0.517, 0.054, "low"), # std alto -- single-split (55.5%) estaba inflado + "TSLA": (0.514, 0.027, "low"), + "META": (0.499, 0.028, "low"), +} + + +def _get_historical_edge(ticker: str) -> dict: + """ + V27 -- lookup de EQUITY_HISTORICAL_EDGE. Ticker fuera de la tabla (ej. + un activo nuevo, todavía no auditado) -> tier "unaudited", NUNCA se + inventa un número: es una categoría honesta más, no un fallback a + "high" ni a "low". + """ + entry = EQUITY_HISTORICAL_EDGE.get(ticker) + if entry is None: + return {"tier": "unaudited", "dir_acc_cpcv_mean": None, "dir_acc_cpcv_std": None} + mean, std, tier = entry + return {"tier": tier, "dir_acc_cpcv_mean": mean, "dir_acc_cpcv_std": std} + + +def _forecast_asset_triple_barrier( + ticker: str, + regime: str, + scalers: dict, + asset_id: int, + feature_scaler: Any, + lookback: int, + macro_tickers: list, + requested_steps: int, +) -> dict: + """ + Inferencia real V22 target_mode="triple_barrier" — UN forward pass (+MC + Dropout, ver TB_MC_DROPOUT_PASSES) sobre la ventana de features más + reciente. Ver bloque de módulo arriba para por qué esto NO es + autoregresivo. + + Devuelve el MISMO esquema de claves que la rama de regresión de + `_forecast_asset` (`ticker`, `last_price`, `predicted_price`, + `predicted_return_pct`, `trend`, `historical`, `forecast`, + `tactical_signal`, `forecast_incomplete`, `variance_source`, + `real_data_ood_frac`, `real_ood_dampening_applied`, + `forecast_reliability`) — CERO consumidor aguas abajo + (`_fmt_plan_math_line`, `_build_tactical_operation`, + `services/prediccion.py`, `services/live_trade.py`) necesita branch + propio para no romperse — más las claves `tb_*` con el detalle real de + clasificación (confianza P(TP) vs P(SL) vs P(TIMEOUT), ver misión). + + `predicted_return_pct`/`predicted_price` NO son un path día-a-día: son + la ESPERANZA del retorno bajo la distribución de clases real del propio + modelo (`tb_probabilities`) sobre los DOS niveles de barrera reales + (`pt_mult`/`sl_mult` × volatilidad realizada actual, MISMA fórmula que + `compute_triple_barrier_labels` en train_kodaquant_v5.py) — cero cifras + inventadas. `forecast` son bandas ESTÁTICAS (los niveles de barrera no + se mueven una vez abierta la apuesta), no un cono creciente. + """ + # V23.5 -- `scalers["tb_params"]` cambió de esquema en train_kodaquant_v5.py + # (Directiva 1): pasó de un dict PLANO compartido por todos los tickers + # cripto a un dict-de-dicts `{ticker: {pt_mult, sl_mult, ...}}` (barreras + # calibradas de forma INDEPENDIENTE por activo). Detección dual de + # esquema -- NO se asume qué versión de scalers_dict.pkl está desplegada: + # si el dict trae "pt_mult" como llave de primer nivel, es el esquema + # VIEJO (pre-V23.5, plano); si no, se indexa por `ticker` (esquema V23.5). + # Esto evita un colapso de producción durante el rollout (modelo/scalers + # nuevos desplegados en distintos momentos que este archivo). + _tb_params_raw = scalers.get("tb_params") or {} + if isinstance(_tb_params_raw, dict) and "pt_mult" in _tb_params_raw: + tb_params = _tb_params_raw # esquema viejo -- plano, mismo dict para cualquier ticker + else: + tb_params = _tb_params_raw.get(ticker) or {} # esquema V23.5 -- por ticker + pt_mult = float(tb_params.get("pt_mult", _TB_PT_MULT_FALLBACK)) + sl_mult = float(tb_params.get("sl_mult", _TB_SL_MULT_FALLBACK)) + max_holding_days = int(tb_params.get("max_holding_days", _TB_MAX_HOLDING_DAYS_FALLBACK)) + vol_lookback = int(tb_params.get("vol_lookback", _TB_VOL_LOOKBACK_FALLBACK)) + class_names = list(scalers.get("tb_class_names") or _TB_CLASS_NAMES_FALLBACK) + + if requested_steps and requested_steps != max_holding_days: + print( + f"ℹ️ {ticker} es target_mode='triple_barrier': horizonte efectivo = " + f"max_holding_days={max_holding_days} (entrenado) — se ignora el " + f"forecast_horizon_days={requested_steps} solicitado. La cabeza softmax " + "clasifica el desenlace COMPLETO de la apuesta, no admite un horizonte parcial." + ) + + model, dropout_layers = _get_keras_model(regime) + close_df, raw_features = _fetch_feature_window(ticker, macro_tickers, lookback, scalers=scalers) + + last_price = float(close_df[ticker].iloc[-1]) + anchor_date_str = close_df.index[-1].strftime("%Y-%m-%d") + + hist_window = _historical_window_for_horizon(max_holding_days) + display_col = f"{ticker}__DISPLAY_CLOSE" + historical_price_series = close_df[display_col] if display_col in close_df.columns else close_df[ticker] + historical = [ + {"date": d.strftime("%Y-%m-%d"), "price": round(float(p), 2)} + for d, p in historical_price_series.tail(hist_window).items() + ] + last_price_quote = historical[-1]["price"] if historical else round(last_price, 2) + + # Volatilidad realizada actual — MISMA fórmula exacta que + # `compute_triple_barrier_labels` (train_kodaquant_v5.py): rolling std + # de LOG_RETURN_1D en una ventana de `vol_lookback` días, evaluada en el + # último punto real disponible (el "hoy" de esta apuesta hipotética). + close_tail = close_df[ticker].tail(vol_lookback + 1).to_numpy(dtype=np.float64) + vol_t = float(np.std(np.diff(np.log(close_tail)))) if len(close_tail) >= 2 else 0.0 + vol_t = max(vol_t, _TB_MIN_VOL_FALLBACK) + + barrier_upper_price = last_price * math.exp(pt_mult * vol_t) + barrier_lower_price = last_price * math.exp(-sl_mult * vol_t) + + window = raw_features[-lookback:] + scaled_window = feature_scaler.transform(window) + oob_frac = float(np.mean((scaled_window < 0.0) | (scaled_window > 1.0))) + real_ood_dampening = _real_ood_dampening_factor(oob_frac) + scaled_window = _soft_clip_unit_interval(scaled_window) + + n_mc = TB_MC_DROPOUT_PASSES if dropout_layers else 1 + X_batch = np.repeat(scaled_window[np.newaxis, :, :], n_mc, axis=0).astype(np.float32) + asset_batch = np.full((n_mc, 1), asset_id, dtype=np.int32) + + # Misma semilla determinista "memoria diaria" que la cabeza de + # regresión (ver `_forecast_asset`) — todas las requests del mismo + # (ticker, día UTC) devuelven las MISMAS `n_mc` máscaras de dropout. + today_utc_str = datetime.now(timezone.utc).date().isoformat() + tb_seed_material = f"{ticker}|{today_utc_str}|triple_barrier".encode("utf-8") + tb_keras_seed = int(hashlib.sha256(tb_seed_material).hexdigest(), 16) % (2**32) + + forecast_incomplete = False + try: + with inference_lock: + keras.utils.set_random_seed(tb_keras_seed) + probs_tensor = _call_keras_with_hang_guard( + model, [X_batch, asset_batch], training=bool(dropout_layers) + ) + probs_np = keras.ops.convert_to_numpy(probs_tensor) + if probs_np.shape != (n_mc, 3): + raise ValueError( + f"Salida del modelo con shape inesperado {probs_np.shape} " + f"(se esperaba ({n_mc}, 3): softmax [SL, TIMEOUT, TP] por pasada MC)." + ) + mean_probs = probs_np.mean(axis=0) + std_probs = probs_np.std(axis=0) if n_mc > 1 else np.zeros(3) + except Exception as exc: # noqa: BLE001 — jamás inventar probabilidades, degradar explícito + print( + f"⚠️ Forward pass Triple Barrier de {ticker} falló ({exc!r}) — forecast " + "incompleto, cero clase/confianza inventada." + ) + forecast_incomplete = True + mean_probs = np.full(3, 1.0 / 3.0) # uniforme = "no sé", nunca una clase con convicción falsa + std_probs = np.zeros(3) + + predicted_idx = int(np.argmax(mean_probs)) + predicted_class = class_names[predicted_idx] + tb_confidence = float(mean_probs[predicted_idx]) + # Orden fijo TB_LABEL_TO_CLASS_IDX = {-1:0, 0:1, 1:2} (ver train_kodaquant_v5.py) -> [SL, TIMEOUT, TP] + p_sl, p_timeout, p_tp = float(mean_probs[0]), float(mean_probs[1]), float(mean_probs[2]) + + # Esperanza del retorno bajo la distribución de clases real del modelo, + # sobre los niveles de barrera reales (ver docstring). TIMEOUT aporta + # 0.0: este motor de inferencia no tiene, en producción, el historial + # de TB_REALIZED_RETURN por-timeout para promediar sin inventar un + # número — 0.0 es el supuesto neutro honesto, no una medición. + expected_log_return = (p_tp * pt_mult * vol_t) - (p_sl * sl_mult * vol_t) + expected_log_return *= real_ood_dampening + predicted_price = last_price_quote * math.exp(expected_log_return) + predicted_return_pct = expected_log_return * 100.0 + + # Filtro de confianza mínima (ver TB_MIN_SIGNAL_CONFIDENCE arriba): + # degrada una clase SL/TP de baja convicción a "sin convicción + # operativa" — prediccion.py/live_trade.py deben leer `tb_actionable` + # (no solo `tb_predicted_class`) antes de convertir la clase en una + # acción de COMPRA/VENTA real. + tb_actionable = predicted_class != "TIMEOUT" and tb_confidence >= TB_MIN_SIGNAL_CONFIDENCE + + forecast_dates = [] + cursor_date = close_df.index[-1] + for _ in range(max_holding_days): + # Crypto cotiza 24/7 — mismo criterio que la rama de regresión + # (ver `regime != "crypto_specialist"` más abajo): nunca saltar + # fin de semana acá. + cursor_date = cursor_date + timedelta(days=1) + forecast_dates.append(cursor_date.strftime("%Y-%m-%d")) + + # Bandas ESTÁTICAS (ver docstring): los niveles de barrera se fijan UNA + # vez en la entrada y no se mueven mientras la apuesta está abierta — + # por eso son los MISMOS en cada fecha del horizonte, a diferencia del + # cono creciente P5-P95 de la cabeza de regresión. + forecast_points = [ + { + "date": d, + "lower_bound": round(barrier_lower_price, 2), + "expected_path": round(predicted_price, 2), + "upper_bound": round(barrier_upper_price, 2), + "sample_path": round(predicted_price, 2), + } + for d in forecast_dates + ] + + # Señal táctica V22: Triple Barrier es una apuesta ÚNICA sostenida hasta + # que se toque una barrera o venza `max_holding_days` — no hay + # peak&trough que buscar dentro de una banda estática (a diferencia de + # `_find_optimal_entry_exit`, diseñada para el cono creciente de la + # cabeza de regresión). Entrada = HOY al precio real; salida = fin del + # horizonte de la apuesta, al valor esperado bajo la distribución de + # clases — None si el filtro de confianza (`tb_actionable`) descartó la + # señal, degradando el prompt/frontend en vez de inventar una operación. + tactical_signal = None + if tb_actionable and forecast_dates: + tactical_signal = { + "entry_date": anchor_date_str, + "entry_price": last_price_quote, + "exit_date": forecast_dates[-1], + "exit_price": round(predicted_price, 2), + } + + return { + "ticker": ticker, + "regime": regime, + "target_mode": "triple_barrier", + "last_price": last_price_quote, + "predicted_price": round(predicted_price, 2), + "predicted_return_pct": round(predicted_return_pct, 4), + "trend": "alcista" if predicted_return_pct >= 0 else "bajista", + "historical": historical, + "forecast": forecast_points, + "predicted_path": [p["expected_path"] for p in forecast_points], + "tactical_signal": tactical_signal, + "forecast_incomplete": forecast_incomplete, + "variance_source": f"mc_dropout_{n_mc}x_softmax" if dropout_layers else "deterministic_native_keras_softmax", + "n_simulations": n_mc, + "deterministic_seed": tb_keras_seed, + "confidence_interval": "static_barrier_band", + "real_data_ood_frac": round(oob_frac, 4), + "real_ood_dampening_applied": round(real_ood_dampening, 4), + "forecast_reliability": "degraded" if oob_frac > REAL_OOD_DAMPENING_START else "normal", + # --- Triple Barrier — detalle de clasificación real (misión: ------- + # "calculando la confianza de TP vs SL") ---------------------------- + "tb_class_names": class_names, + "tb_probabilities": {"SL": p_sl, "TIMEOUT": p_timeout, "TP": p_tp}, + "tb_mc_std": {"SL": float(std_probs[0]), "TIMEOUT": float(std_probs[1]), "TP": float(std_probs[2])}, + "tb_predicted_class": predicted_class, + "tb_confidence": round(tb_confidence, 4), + "tb_actionable": tb_actionable, + "tb_min_signal_confidence": TB_MIN_SIGNAL_CONFIDENCE, + "tb_max_holding_days": max_holding_days, + "tb_pt_mult": pt_mult, + "tb_sl_mult": sl_mult, + "tb_vol_realized": round(vol_t, 6), + "tb_barrier_upper_price": round(barrier_upper_price, 2), + "tb_barrier_lower_price": round(barrier_lower_price, 2), + } + + +def _forecast_asset(ticker: str, steps: int = DEFAULT_FORECAST_HORIZON_DAYS) -> dict: + """ + Motor autoregresivo con Simulación Monte Carlo (sliding window, batcheado). + En cada paso T+1 ... T+steps se corre UN forward pass del modelo Keras + con un batch de `N_MONTE_CARLO_SIMULATIONS` trayectorias en paralelo + (`model(..., training=True)` — MC Dropout real, ver `_get_keras_model`; + con dropout activo, cada elemento del batch muestrea su propia máscara, + así que el batch ya son N inferencias estocásticas genuinas, no N copias + idénticas). A cada trayectoria se le suma además su propio ruido + gaussiano i.i.d. calibrado con la volatilidad histórica REAL del activo + (`VOLATILITY_INJECTION_*`). Cada trayectoria evoluciona su propia ventana + de features (RSI/EMA/MACD recalculados por trayectoria) de forma + completamente independiente. + + Al terminar el bucle, las N trayectorias se colapsan por fecha a tres + percentiles — `lower_bound` (P5), `expected_path` (P50), `upper_bound` + (P95) — que son los que se devuelven en `forecast`. Los N caminos crudos + NUNCA se devuelven, solo el resumen probabilístico. + + HONESTIDAD DE DATOS: `expected_path` es la mediana de N simulaciones + (modelo + volatilidad calibrada), no una única inferencia determinista + de la red. `sample_path` es, en cambio, una trayectoria real de esas + mismas N simulaciones (la más cercana a la mediana) — real, no + percentil, así que preserva la textura día-a-día genuina que el + percentil-por-fecha cancela parcialmente. `variance_source` declara el + mecanismo exacto para que ningún consumidor de este dict (frontend, + prompt del LLM) presente cualquiera de los dos como algo distinto a lo + que es. + + SÍNCRONA Y BLOQUEANTE por diseño: el caller SIEMPRE debe despacharla a + un executor. + """ + regime = _regime_for_ticker(ticker) + scalers = _get_scalers(regime) + if ticker not in scalers["asset_to_id"]: + raise ValueError(f"'{ticker}' no pertenece al universo entrenado del especialista '{regime}'.") + + asset_id = scalers["asset_to_id"][ticker] + feature_scaler = scalers["feature_scalers"][ticker] + lookback = scalers["lookback"] + macro_tickers = scalers["macro_tickers"] + + # V22 — despacho dinámico por target_mode (ver bloque "Inferencia + # target_mode=triple_barrier" arriba, _forecast_asset_triple_barrier). + # `target_scalers[ticker]` es `None` para target_mode="triple_barrier" + # (ver train_kodaquant_v5.py, run_regime_pipeline) — por eso el deref + # de `target_scaler` vive DESPUÉS de este branch, nunca antes: la rama + # triple_barrier no debe depender de una clave que su propio pipeline + # de entrenamiento nunca completó. + target_mode = scalers.get("target_mode", "regression") + if target_mode == "triple_barrier": + return _forecast_asset_triple_barrier( + ticker=ticker, + regime=regime, + scalers=scalers, + asset_id=asset_id, + feature_scaler=feature_scaler, + lookback=lookback, + macro_tickers=macro_tickers, + requested_steps=steps, + ) + + target_scaler = scalers["target_scalers"][ticker] + n_sim = N_MONTE_CARLO_SIMULATIONS + + # --- SEMILLA DETERMINISTA (memoria diaria por activo) ------------------- + # Objetivo: todas las peticiones para el MISMO (ticker, horizonte) en el + # MISMO día natural (UTC) deben producir EXACTAMENTE las mismas N + # trayectorias, sin importar cuántos usuarios/requests las disparen — + # hasta que cierre la vela diaria (`today_utc_str` avanza a las 00:00 UTC + # y la semilla cambia sola, sin cache manual que purgar). + # + # Hash estable vía sha256 — NUNCA `hash()` de Python: está salado por + # proceso (`PYTHONHASHSEED` aleatorio por defecto para strings), así que + # dos workers o dos reinicios del mismo proceso darían semillas + # DISTINTAS para el mismo input, rompiendo justo la consistencia + # multiusuario que es el objetivo de este fix. + # + # `np.random.SeedSequence(base_seed).spawn(steps)` deriva `steps` + # sub-semillas HIJAS de alta calidad (independientes entre sí, no una + # secuencia trivial `seed + step_i` que podría correlacionar pasos + # vecinos) — una por cada T+1..T+steps, así el ruido i.i.d. de cada día + # de la trayectoria es distinto pero 100% reproducible. + # + # Cada paso instancia su propio `np.random.default_rng(...)` LOCAL (ver + # bucle más abajo) en vez de mutar `np.random.seed()` global: Plan A + # (SPY) y Plan B (p. ej. BTC-USD) se despachan CONCURRENTEMENTE en + # threads distintos (`_build_investment_plans`) — un seed global sería + # una condición de carrera real entre ambos. + today_utc_str = datetime.now(timezone.utc).date().isoformat() + base_seed_material = f"{ticker}|{today_utc_str}|{steps}".encode("utf-8") + base_seed = int(hashlib.sha256(base_seed_material).hexdigest(), 16) % (2**32) + step_seed_sequences = np.random.SeedSequence(base_seed).spawn(steps) + + # `model` aquí puede ser el grafo crudo o el "MC-Dropout bridge" (ver + # `_build_mc_dropout_bridge` / `_get_keras_model`) — la función decide + # cuál sirve según si el nodo `dropout_regularizer` del .keras venía + # congelado en `training=False`. Esta función NUNCA debe asumir cuál de + # los dos es: solo le pasa `training=True` y confía en que + # `_get_keras_model` ya resolvió el bug de congelamiento. + model, dropout_layers = _get_keras_model(regime) + base_variance_source = "mc_dropout" if dropout_layers else "deterministic_native_keras" + + close_df, raw_features = _fetch_feature_window(ticker, macro_tickers, lookback, scalers=scalers) + + # sigma_hist: desviación estándar de los log-returns REALES de los + # últimos VOLATILITY_LOOKBACK_DAYS del propio activo — no un número + # inventado, es volatilidad realizada genuina. Sirve como escala del + # ruido gaussiano que se inyecta por trayectoria en cada paso. + vol_window = close_df[ticker].tail(VOLATILITY_LOOKBACK_DAYS + 1).to_numpy(dtype=np.float64) + if VOLATILITY_INJECTION_ENABLED and len(vol_window) >= 3: + hist_log_returns = np.diff(np.log(vol_window)) + sigma_hist = float(np.std(hist_log_returns)) + else: + sigma_hist = 0.0 + noise_scale = sigma_hist * VOLATILITY_INJECTION_FACTOR + variance_source = base_variance_source + ( + f"+monte_carlo_{n_sim}x+volatility_injection" if noise_scale > 0 else f"+monte_carlo_{n_sim}x" + ) + # Techo de la señal del modelo (no del ruido) — ver "Cinturón de + # seguridad contra el tobogán" arriba. Si `sigma_hist` no se pudo + # calcular (histórico insuficiente), no hay base estadística real para + # un límite -> no se acota (np.inf), igual que antes de este fix. + model_signal_clip = ( + sigma_hist * MODEL_SIGNAL_CLIP_SIGMAS if sigma_hist > 0 else np.inf + ) + + # GUARD "Falso Monte Carlo" — la ÚNICA condición bajo la que las N + # trayectorias serían deterministas e idénticas (colapso a un solo + # vector, línea recta perfecta): CERO fuentes de varianza real. Este + # motor tiene DOS por diseño — (1) MC-Dropout genuino vía `training=True` + # en el batch (ver `_get_keras_model`/`dropout_layers`, cada fila del + # batch muestrea su propia máscara de Dropout) y (2) ruido gaussiano + # aditivo post-`inverse_transform` escalado a `VOLATILITY_INJECTION_FACTOR + # * sigma_hist` (ver más abajo, `noise_batch`). Si AMBAS fallan a la vez + # (ej. el .keras cargado no tiene capas Dropout activas Y + # VOLATILITY_INJECTION_ENABLED=False o `sigma_hist=0`), el bucle SÍ + # degenera a un filtro determinista — fallar ruidosamente aquí en vez de + # devolver un forecast silenciosamente colapsado. + if not dropout_layers and noise_scale == 0.0: + raise ValueError( + f"Monte Carlo determinista detectado para '{ticker}': dropout_layers " + "vacío (el .keras del régimen no tiene capas Dropout activas) Y " + "noise_scale=0.0 (VOLATILITY_INJECTION_ENABLED=False o sigma_hist=0 " + "por histórico insuficiente). Sin NINGUNA fuente de varianza real, " + f"las {n_sim} trayectorias serían idénticas — degenerando a un único " + "vector determinista y explicando un colapso en línea recta " + "geométrica. Revisa la arquitectura del modelo cargado o " + "VOLATILITY_INJECTION_ENABLED/VOLATILITY_LOOKBACK_DAYS antes de " + "reintentar el forecast." + ) + + last_price = float(close_df[ticker].iloc[-1]) + cursor_date = close_df.index[-1] + anchor_date_str = cursor_date.strftime("%Y-%m-%d") # "HOY" — ancla real, pre-proyección + + hist_window = _historical_window_for_horizon(steps) + # FIX PRICING: histórico visual en Regular Close (oráculo real), no en + # Auto-Adjusted Close (ver bloque `__DISPLAY_CLOSE` en + # _fetch_feature_window). Fallback a la columna ajustada si por lo que + # sea no está presente (backend viejo / excepción silenciada arriba). + display_col = f"{ticker}__DISPLAY_CLOSE" + historical_price_series = close_df[display_col] if display_col in close_df.columns else close_df[ticker] + historical = [ + {"date": d.strftime("%Y-%m-%d"), "price": round(float(p), 2)} + for d, p in historical_price_series.tail(hist_window).items() + ] + # FIX PRICING (ancla vs. histórico visual): `last_price` (arriba) es + # Auto-Adjusted Close — correcto y OBLIGATORIO como semilla del Monte + # Carlo (`cursor_prices` más abajo) y para la paridad con el + # entrenamiento, así que NO se toca. Pero ese mismo valor NO es + # necesariamente idéntico al último precio de `historical` (Regular + # Close, ver bloque __DISPLAY_CLOSE arriba) — la discrepancia, aunque + # normalmente mínima, es justo lo que se percibe como "el cursor no + # calza con el último punto del histórico" en el chart. Todo lo que se + # DEVUELVE al frontend como "precio actual" (campo `last_price` de la + # respuesta y `anchor_price` de la señal táctica) usa en cambio + # `last_price_quote`, tomado del MISMO array `historical` que ya se + # construyó arriba — coincide con su último punto por construcción, + # no por casualidad. Fallback a `last_price` solo si `historical` + # llegara vacío (activo sin histórico suficiente). + last_price_quote = historical[-1]["price"] if historical else round(last_price, 2) + + # Estado vectorizado: N trayectorias en paralelo, cada una con su propia + # ventana de features y su propio estado de indicadores (RSI/EMA/MACD), + # todas arrancando del MISMO histórico real (`raw_features`). + cursor_windows = np.repeat(raw_features[-lookback:][np.newaxis, :, :], n_sim, axis=0).astype(np.float64) + cursor_prices = np.full(n_sim, last_price, dtype=np.float64) + + vix_ticker = _resolve_vix_ticker(macro_tickers) # Hallazgo F5 — ver _compute_sentiment_score + base_indicator_state = _compute_indicator_states(close_df, ticker, vix_ticker) + avg_gain_arr = np.full(n_sim, base_indicator_state["avg_gain"], dtype=np.float64) + avg_loss_arr = np.full(n_sim, base_indicator_state["avg_loss"], dtype=np.float64) + ema_fast_arr = np.full(n_sim, base_indicator_state["ema_fast"], dtype=np.float64) + ema_slow_arr = np.full(n_sim, base_indicator_state["ema_slow"], dtype=np.float64) + ema_20_arr = np.full(n_sim, base_indicator_state["ema_20"], dtype=np.float64) + macd_signal_arr = np.full(n_sim, base_indicator_state["macd_signal"], dtype=np.float64) + # SENTIMENT_SCORE (Hallazgo F5 — correlación de Pearson móvil + # activo/VIX): cada trayectoria arranca con la MISMA ventana real de los + # últimos SENTIMENT_LOOKBACK_DAYS log-returns del activo (no hay fuga de + # futuro, todo viene del histórico ya observado) y a partir de ahí + # diverge de forma independiente, igual que RSI/EMA/MACD. + log_return_window_arr = np.repeat( + base_indicator_state["log_return_window"][np.newaxis, :], n_sim, axis=0 + ).astype(np.float64) # shape (n_sim, SENTIMENT_LOOKBACK_DAYS) + # Ventana de VIX: COMPARTIDA entre trayectorias (1D, no (n_sim, window)). + # Este motor no proyecta macro a futuro — los tickers macro se propagan + # SIN CAMBIO dentro del tensor (ver comentario "macro_tickers... se + # propagan sin cambio" más abajo, en el ensamblado de `new_rows`), así + # que el VIX queda congelado en su último precio real para siempre. Con + # el precio de VIX congelado, cada log-return SINTÉTICO de VIX es + # exactamente 0.0 (log(P/P) = 0) — por eso la ventana solo se desliza + # añadiendo ceros a medida que el historial real envejece fuera de ella, + # nunca diverge por trayectoria (mismo principio de honestidad que + # `volume_proxy` de OBV: este motor no inventa noticias ni macro futuro). + log_return_window_vix = base_indicator_state["log_return_window_vix"].copy() # shape (SENTIMENT_LOOKBACK_DAYS,) + RSI_ALPHA, EMA20_K, EMA_FAST_K, EMA_SLOW_K, MACD_SIGNAL_K = ( + 1 / 14, 2 / 21, 2 / 13, 2 / 27, 2 / 10, + ) + + # --- V3: estado inicial vectorizado de ATR_14 / BB_WIDTH_20 / OBV, una + # trayectoria por fila, todas arrancando del MISMO estado real + # (`base_indicator_state`) y divergiendo de forma independiente — + # idéntico patrón a RSI/EMA/MACD/SENTIMENT_SCORE arriba. + atr_arr = np.full(n_sim, base_indicator_state["atr_prev"], dtype=np.float64) + price_window_arr = np.repeat( + base_indicator_state["price_window"][np.newaxis, :], n_sim, axis=0 + ).astype(np.float64) # shape (n_sim, BB_WIDTH_WINDOW) + obv_arr = np.full(n_sim, base_indicator_state["obv_prev"], dtype=np.float64) + # --- V6: ventana deslizante de OBV crudo por trayectoria — necesaria + # para derivar OBV_ROC_20 (la feature que SÍ entra al tensor, ver + # `new_rows` más abajo); `obv_arr` sigue siendo el acumulado crudo + # interno (misma recursión que antes, solo cambia qué se PROYECTA al + # modelo). + obv_window_arr = np.repeat( + base_indicator_state["obv_window"][np.newaxis, :], n_sim, axis=0 + ).astype(np.float64) # shape (n_sim, OBV_ROC_LOOKBACK_DAYS) + # Proxy de volumen CONSTANTE (promedio histórico reciente) — este motor + # no proyecta volumen futuro, solo precio; ver OBV_VOLUME_PROXY_LOOKBACK_DAYS. + volume_proxy = base_indicator_state["volume_proxy"] + + # --- V5: estado inicial vectorizado de ADX_14 / STOCH_K_14 / NEWS_SENTIMENT_SCORE. + plus_dm_smooth_arr = np.full(n_sim, base_indicator_state["plus_dm_smooth_prev"], dtype=np.float64) + minus_dm_smooth_arr = np.full(n_sim, base_indicator_state["minus_dm_smooth_prev"], dtype=np.float64) + adx_arr = np.full(n_sim, base_indicator_state["adx_prev"], dtype=np.float64) + stoch_high_window_arr = np.repeat( + base_indicator_state["stoch_high_window"][np.newaxis, :], n_sim, axis=0 + ).astype(np.float64) # shape (n_sim, STOCH_K_PERIOD) + stoch_low_window_arr = np.repeat( + base_indicator_state["stoch_low_window"][np.newaxis, :], n_sim, axis=0 + ).astype(np.float64) # shape (n_sim, STOCH_K_PERIOD) + # NEWS_SENTIMENT_SCORE no se proyecta (este motor no genera noticias + # futuras) — se mantiene CONSTANTE en cada paso sintético. + news_sentiment_value = base_indicator_state["news_sentiment_last"] + + # --- Anclas reales para el mecanismo de anchor-pull (ver ANCHOR_RETENTION + # más abajo) — el ÚLTIMO valor real observado de cada indicador + # price-level-dependiente y no auto-acotado (EMA_20/EMA_fast/EMA_slow/ + # MACD_SIGNAL/ATR_14). Se extraen una sola vez aquí, fuera del bucle, + # porque son CONSTANTES por toda la simulación (el punto de referencia + # es siempre "lo último realmente observado", nunca un valor sintético). + ema_fast_anchor = float(base_indicator_state["ema_fast"]) + ema_slow_anchor = float(base_indicator_state["ema_slow"]) + ema_20_anchor = float(base_indicator_state["ema_20"]) + macd_signal_anchor = float(base_indicator_state["macd_signal"]) + atr_anchor = float(base_indicator_state["atr_prev"]) + + # --- Anclas reales de OBV_14 / BB_WIDTH_20 (fix calibración T+5, ver + # bloque ANCHOR_RETENTION arriba) — mismo criterio que EMA/ATR: último + # estado real conocido, congelado una sola vez antes del bucle. BB_WIDTH + # no tiene un escalar recursivo propio en `base_indicator_state` (se + # recalcula fresco cada paso desde `price_window_arr`), así que su ancla + # se deriva aquí con la MISMA fórmula que `_compute_bb_width` sobre la + # ventana real de precios (`price_window`) — no es un valor nuevo, es el + # BB_WIDTH_20 real del último día confirmado por mercado. + obv_anchor = float(base_indicator_state["obv_prev"]) + _bb_tail_real = base_indicator_state["price_window"] + _bb_mean_real = float(_bb_tail_real.mean()) + _bb_std_real = float(_bb_tail_real.std()) + bb_width_anchor = ( + (2 * BB_WIDTH_NUM_STD * _bb_std_real) / _bb_mean_real if _bb_mean_real != 0.0 else 0.0 + ) + + forecast_dates: list[str] = [] + price_paths: list[np.ndarray] = [] # un array (n_sim,) por fecha proyectada + + # Capturados UNA vez en T+1 (100% data real) — ver bloque + # _real_ood_dampening_factor arriba. Defaults neutros por si el propio + # step 0 falla dentro del try/except del bucle. + real_input_oob_frac = 0.0 + real_ood_dampening = 1.0 + + forecast_incomplete = False + for step_i in range(steps): + try: + # RNG local de este paso (determinista, ver bloque de semilla + # arriba) — nunca `np.random` global. `step_keras_seed` deriva + # un uint32 reproducible de la MISMA SeedSequence hija, para + # sembrar también el generador de Keras (MC Dropout) justo antes + # del forward pass, ver `with inference_lock` más abajo. + step_rng = np.random.default_rng(step_seed_sequences[step_i]) + step_keras_seed = int(step_seed_sequences[step_i].generate_state(1)[0]) + + # Batch de N ventanas -> 2D para el scaler (fit espera + # (n_samples, n_features)) -> de vuelta a 3D (n_sim, lookback, n_features). + flat_windows = cursor_windows.reshape(-1, cursor_windows.shape[-1]) + scaled_flat = feature_scaler.transform(flat_windows) + scaled_windows = scaled_flat.reshape(n_sim, lookback, -1).astype(np.float32) + + # FIX DE FUGA AUTORREGRESIVA (auditoría línea-por-línea del + # bucle — colapso geométrico en línea casi recta): `feature_scaler` + # es un MinMaxScaler fit en train sobre el rango histórico REAL + # (-> [0, 1]). `MinMaxScaler.transform()` NO clippea por diseño — + # un valor fuera del rango de entrenamiento se EXTRAPOLA + # linealmente sin límite (ver docstring del módulo, sección + # "Pipeline de inferencia"). Cada paso de este bucle retroalimenta + # indicadores 100% SINTÉTICOS (RSI/EMA/MACD/SENTIMENT/ATR/BB/OBV/ + # ADX/STOCH, todos derivados de `cursor_prices`) al tensor de + # entrada del paso siguiente — si una trayectoria encadena varios + # retornos negativos, sus indicadores se alejan CADA VEZ MÁS del + # rango de entrenamiento, extrapolando MÁS lejos de [0, 1] paso a + # paso. El modelo nunca vio esa región del espacio de entrada + # durante el entrenamiento: su salida ahí no es una extrapolación + # razonable, es indefinida — y en la práctica sesga + # sistemáticamente hacia retornos aún más negativos, retroalimentando + # la fuga en cada iteración (exactamente el patrón de colapso en + # "línea casi recta" reportado). Acotar el tensor YA ESCALADO a + # una banda alrededor de [0, 1] antes de CADA forward pass + # garantiza que el modelo reciba siempre condiciones cercanas al + # rango de entrenamiento, sin importar cuánto diverja + # `cursor_prices` en espacio real — corta la fuga en la fuente, + # antes de que contamine la predicción, en vez de intentar + # corregirla después. + # + # SOFT-CLIP (no hard-clip): un `np.clip(scaled_windows, 0.0, 1.0)` + # pinea TODO valor fuera de rango exactamente en 0.0/1.0 — cuando + # eso alcanza 40-50% de los features (ver auditoría std/ + # clipped_frac en el log), trayectorias con divergencias muy + # distintas en espacio real terminan con el MISMO tensor de + # entrada, y la red pierde la capacidad de diferenciarlas + # (aplanamiento de la textura direccional, ver bloque + # SOFT_CLIP_MARGIN arriba). `_soft_clip_unit_interval` es + # identidad exacta dentro de [0, 1] y comprime el excedente con + # tanh de forma monótona/inyectiva en vez de pinearlo. + oob_frac = float(np.mean((scaled_windows < 0.0) | (scaled_windows > 1.0))) + if step_i == 0: + # T+1 = ventana 100% real, cero contaminación sintética — + # ver bloque _real_ood_dampening_factor arriba. Se congela + # acá y se reusa en TODOS los pasos: la distancia al + # manifold de entrenamiento del punto de partida no cambia + # con el número de pasos sintéticos. + real_input_oob_frac = oob_frac + real_ood_dampening = _real_ood_dampening_factor(real_input_oob_frac) + scaled_windows = _soft_clip_unit_interval(scaled_windows) + asset_tensor = np.full((n_sim, 1), asset_id, dtype=np.int32) + + # MC Dropout real + batch de N trayectorias en UNA sola llamada: + # `training=True` mantiene vivo `Dropout(0.4)` y, al ser un + # batch, cada fila del tensor de salida muestrea su propia + # máscara — N inferencias estocásticas genuinas por el precio de + # UN forward pass, no de N. `inference_lock` protege esta única + # llamada por paso (Plan A y Plan B corren en threads distintos + # contra el mismo `model` cacheado — ver _build_investment_plans). + # + # `keras.utils.set_random_seed` va DENTRO del mismo lock, justo + # antes del forward pass: el generador aleatorio de Keras es + # estado GLOBAL del proceso (no hay uno por-thread sin tocar la + # arquitectura del modelo ya entrenado/guardado). Fijarlo fuera + # del lock dejaría una ventana de carrera real donde el thread de + # Plan B pisa la semilla de Plan A entre el set y el forward + # pass — atándolos al mismo lock, ambos ocurren como una unidad + # atómica, así la máscara de MC Dropout queda reproducible por + # (ticker, fecha, horizonte, paso) igual que el ruido gaussiano. + with inference_lock: + keras.utils.set_random_seed(step_keras_seed) + y_pred_scaled = _call_keras_with_hang_guard( + model, [scaled_windows, asset_tensor], training=True + ) + y_pred_np = keras.ops.convert_to_numpy(y_pred_scaled) + if y_pred_np.shape != (n_sim, 2): + raise ValueError( + f"Salida del modelo con shape inesperado {y_pred_np.shape} " + f"(se esperaba ({n_sim}, 2): [mu, log_var] dual-head por trayectoria)." + ) + mu_scaled_batch = y_pred_np[:, 0:1] + log_var_scaled_batch = y_pred_np[:, 1:2] + r_hat_model_batch = target_scaler.inverse_transform(mu_scaled_batch).reshape(n_sim) + # StandardScaler(with_mean=False): inverse_transform es y_raw = y_scaled * scale_; + # la std escala igual (lineal) -> sigma_real = sigma_scaled * scale_[0] + sigma_model_batch = ( + np.sqrt(np.exp(log_var_scaled_batch)).reshape(n_sim) * target_scaler.scale_[0] + ) + # FIX (colapso estocástico / "electrocardiograma roto" en BTC): + # `r_hat_model_batch` (la MEDIA) ya tenía cinturón de seguridad + # (`model_signal_clip`, ver más abajo) contra la fuga + # autorregresiva bajo inputs OOD — pero `sigma_model_batch` (la + # VARIANZA, head log_var) NUNCA lo tuvo. `sqrt(exp(log_var))` es + # EXPONENCIAL en la salida cruda de la red: bajo un input OOD + # (ver `real_ood_dampening`/`oob_frac`, auditoría SPY 45.6% en + # T+1 — y crypto, con su rango de precio/features moviéndose más + # rápido que la ventana de entrenamiento de 2y, es el régimen más + # expuesto) un log_var mal calibrado puede disparar + # `sigma_model_batch` muy por encima de la volatilidad real del + # activo. Ese valor entra directo a `combined_scale` -> + # `noise_batch` -> `cursor_prices` sin ningún techo, produciendo + # exactamente picos/caídas extremos en pasos consecutivos: no es + # volatilidad real de BTC, es ruido gaussiano con una desviación + # estándar que la propia red dejó de calibrar bien. Se acota con + # el MISMO techo (`model_signal_clip`, sigma_hist real x + # MODEL_SIGNAL_CLIP_SIGMAS) que ya protege a la media — defensa + # en profundidad simétrica, no un número nuevo inventado. + sigma_model_batch = np.clip(sigma_model_batch, 0.0, model_signal_clip) + + # AUDITORÍA DUAL-HEAD — un solo bloque (los dos que había se + # solapaban), solo en T+1: un horizonte de 3M son 63 pasos x 2 + # planes (A/B) x ambos regímenes en paralelo — sin el guard + # step_i==0 esto imprime cientos de bloques por request. + if step_i == 0: + logger.info( + "[AUDITORIA DUAL-HEAD] ticker=%s regime=%s y_pred_shape=%s " + "target_scaler.scale_[0]=%.8f mu_scaled[:3]=%s log_var_scaled[:3]=%s " + "sigma_model_batch[:3]=%s r_hat_model_batch[:3]=%s", + ticker, regime, y_pred_np.shape, + float(target_scaler.scale_[0]), + mu_scaled_batch[:3].flatten(), log_var_scaled_batch[:3].flatten(), + sigma_model_batch[:3], r_hat_model_batch[:3], + ) + + # Decay de señal (ver SIGNAL_DECAY_BASE arriba): step_i=0 -> 100% + # de la señal del modelo; cada paso adicional la atenúa + # geométricamente. Es lo ÚNICO que se decae — el ruido i.i.d. + # (`noise_batch`, más abajo) sigue intacto, así que el ancho + # P5-P95 del cono sigue creciendo con sqrt(steps) como un random + # walk real; solo se descuenta cuánto pesa la convicción + # direccional COMPARTIDA del modelo (la que, sin decay, arrastraba + # a P5 Y P95 por igual en la misma dirección). + signal_decay = SIGNAL_DECAY_BASE ** step_i + # `real_ood_dampening` (ver bloque arriba, capturado en T+1): + # penaliza la MAGNITUD de la señal determinista en proporción a + # cuán lejos del rango de entrenamiento arrancó el forecast — + # independiente de `signal_decay`, que solo penaliza por número + # de pasos sintéticos acumulados. Con datos in-distribution + # (oob_frac en T+1 <= 15%) este factor es 1.0 y no cambia nada + # del comportamiento anterior. + r_hat_model_batch = r_hat_model_batch * signal_decay * real_ood_dampening * EDGE_SHRINKAGE_FACTOR + + # Cinturón de seguridad (ver MODEL_SIGNAL_CLIP_SIGMAS arriba): + # acota SOLO la señal cruda de la red a ±5 sigma_hist antes de + # sumar el ruido — corta el sesgo direccional de la fuga + # autorregresiva sin tocar la varianza real inyectada abajo. Se + # conserva intacto como techo absoluto incluso con el decay ya + # aplicado (defensa en profundidad, no defensa única). + r_hat_model_batch = np.clip(r_hat_model_batch, -model_signal_clip, model_signal_clip) + + # Inyección de Volatilidad Estocástica — un draw i.i.d. POR + # TRAYECTORIA, ocurre aquí sobre el vector `r_hat_model_batch` ya + # en espacio real (post inverse_transform), nunca sobre los + # tensores de entrada del modelo. La varianza entre trayectorias + # (y por tanto el ancho de la banda P5-P95) crece de forma + # natural con sqrt(steps), como un random walk real. + combined_scale = np.sqrt(sigma_model_batch ** 2 + noise_scale ** 2) + noise_batch = step_rng.normal(loc=0.0, scale=combined_scale, size=n_sim) + r_hat_batch = r_hat_model_batch + noise_batch + except Exception as exc: # noqa: BLE001 + print( + f"⚠️ Paso T+{step_i + 1}/{steps} de {ticker} falló en el modelo Keras ({exc}) — " + "se devuelve el forecast probabilístico acumulado hasta aquí, sin inventar el resto." + ) + forecast_incomplete = True + break + + prev_prices = cursor_prices + cursor_prices = cursor_prices * np.exp(r_hat_batch) + + # DIAGNÓSTICO (fix calibración T+5): antes solo se logueaba el ÚLTIMO + # paso. Se agregan dos checkpoints más para poder atribuir la causa + # empíricamente en el próximo forecast real: T+1 (ventana 100% real, + # CERO contaminación sintética — si `oob_frac` ya es alto acá, la + # causa es un escalador desactualizado frente al precio/OBV real + # actual, no drift autorregresivo) y T+5 (mismo checkpoint que la + # auditoría original que documentó el colapso, para comparar + # antes/después de este fix con la misma referencia exacta). Con + # soft-clip, `scaled_windows` casi nunca es EXACTAMENTE 0.0/1.0 + # (asíntota, no pineado) — esa comparación dejó de ser una señal + # útil. `oob_frac` (capturado ANTES del soft-clip, arriba) mide lo + # mismo que antes medía `clipped_frac`: presión de extrapolación + # real sobre el tensor, sin depender de si el guard es duro o suave. + if step_i in (0, 4, steps - 1): + _step_label = { + 0: "T+1, ventana 100% real — sin contaminación sintética", + 4: "T+5, checkpoint de la auditoría original del colapso", + }.get(step_i, f"T+{step_i + 1}, último paso completado") + print(f"🔎 {ticker} step {step_i} [{_step_label}]: std(cursor_prices)={cursor_prices.std():.4f} | " + f"fracción de features fuera de rango de entrenamiento (pre soft-clip)={oob_frac:.4%}") + # FIX CALENDARIO (Timezones/Data Gaps): saltar sábado/domingo es + # correcto SOLO para equities (L-V, sesión ancla en la timezone del + # exchange, ver `close_df.index` real de yfinance). Crypto + # (`regime == "crypto_specialist"`, ver REGIME_TICKERS) cotiza 24/7 + # en UTC — su propio histórico real (`close_df.index`) YA incluye + # sábados/domingos, así que saltarlos acá desalineaba el eje + # temporal del forecast contra la realidad del activo (fechas + # proyectadas más lejanas de lo real, "1w" dejaba de ser 7 días + # calendario reales para BTC/ETH). + cursor_date = cursor_date + timedelta(days=1) + if regime != "crypto_specialist": + while cursor_date.weekday() >= 5: + cursor_date = cursor_date + timedelta(days=1) + forecast_dates.append(cursor_date.strftime("%Y-%m-%d")) + price_paths.append(cursor_prices.copy()) + + # Recalcular momentum incrementalmente por trayectoria — jamás + # congelarlo ni compartirlo entre trayectorias. + delta_arr = cursor_prices - prev_prices + gain_arr = np.maximum(delta_arr, 0.0) + loss_arr = np.maximum(-delta_arr, 0.0) + avg_gain_arr = avg_gain_arr * (1 - RSI_ALPHA) + gain_arr * RSI_ALPHA + avg_loss_arr = avg_loss_arr * (1 - RSI_ALPHA) + loss_arr * RSI_ALPHA + safe_avg_loss_arr = np.where(avg_loss_arr == 0.0, 1.0, avg_loss_arr) + rs_arr = avg_gain_arr / safe_avg_loss_arr + # misma convención que _compute_rsi: avg_loss==0 -> NaN -> fillna(50) + rsi_arr = np.where(avg_loss_arr == 0.0, 50.0, 100.0 - (100.0 / (1.0 + rs_arr))) + + ema_fast_arr = cursor_prices * EMA_FAST_K + ema_fast_arr * (1 - EMA_FAST_K) + ema_slow_arr = cursor_prices * EMA_SLOW_K + ema_slow_arr * (1 - EMA_SLOW_K) + ema_20_arr = cursor_prices * EMA20_K + ema_20_arr * (1 - EMA20_K) + # Anchor-pull (ver bloque ANCHOR_RETENTION arriba): la fórmula EWM de + # arriba queda intacta (misma matemática honesta); esto solo + # amortigua cuánto puede alejarse cada EMA del último valor real + # antes del siguiente forward pass — se aplica ANTES de derivar MACD + # para que el amortiguamiento se propague también a macd_new_arr. + ema_fast_arr = _anchor_pull(ema_fast_arr, ema_fast_anchor) + ema_slow_arr = _anchor_pull(ema_slow_arr, ema_slow_anchor) + ema_20_arr = _anchor_pull(ema_20_arr, ema_20_anchor) + macd_new_arr = ema_fast_arr - ema_slow_arr + macd_signal_arr = macd_new_arr * MACD_SIGNAL_K + macd_signal_arr * (1 - MACD_SIGNAL_K) + macd_signal_arr = _anchor_pull(macd_signal_arr, macd_signal_anchor) + + # SENTIMENT_SCORE recursivo (Hallazgo F5 — correlación de Pearson + # móvil activo/VIX, ver _compute_sentiment_score): el log-return + # SINTÉTICO recién generado del activo (r_hat_batch, ya con + # volatilidad inyectada) entra a la ventana deslizante DE CADA + # TRAYECTORIA; el de VIX (congelado, ver `log_return_window_vix` + # arriba) es COMPARTIDO y se desliza añadiendo 0.0. La correlación + # se recalcula por trayectoria sobre ambas ventanas — misma fórmula + # exacta que `_compute_sentiment_score()` (Pearson vía media/std + # normalizadas; el factor n/(n-1) de la covarianza muestral se + # cancela entre numerador y denominador), solo que aquí es online y + # vectorizada por trayectoria en vez de `pd.Series.rolling().corr()`. + log_return_window_arr = np.concatenate( + [log_return_window_arr[:, 1:], r_hat_batch[:, np.newaxis]], axis=1 + ) + log_return_window_vix = np.concatenate([log_return_window_vix[1:], [0.0]]) + + asset_mean_arr = log_return_window_arr.mean(axis=1) + asset_std_arr = log_return_window_arr.std(axis=1) + vix_mean = log_return_window_vix.mean() + vix_std = log_return_window_vix.std() + cov_arr = ((log_return_window_arr - asset_mean_arr[:, np.newaxis]) * (log_return_window_vix - vix_mean)).mean(axis=1) + denom_arr = asset_std_arr * vix_std + safe_denom_arr = np.where(denom_arr == 0.0, 1.0, denom_arr) + sentiment_arr = np.clip( + np.where(denom_arr == 0.0, 0.0, cov_arr / safe_denom_arr), + -1.0, 1.0, + ) + + # --- V3: ATR_14 recursivo. Vela sintética DEGENERADA (High=Low= + # Close del día proyectado — este motor no modela rango intradía): + # con H=L=C, True Range = max(H-L, |H-prevC|, |L-prevC|) se reduce + # EXACTAMENTE a |C_t - C_{t-1}| en los 3 términos (ver _compute_atr). + # El EWM de Wilder real se mantiene: atr_t = atr_{t-1}*(1-ATR_ALPHA) + # + TR_t*ATR_ALPHA. Aproximación honesta: subestima el ATR real al + # ignorar rango intradía, documentado igual que el resto de + # indicadores sintéticos de este bucle. + tr_arr = np.abs(delta_arr) + atr_arr = atr_arr * (1 - ATR_ALPHA) + tr_arr * ATR_ALPHA + # Anchor-pull (ver ANCHOR_RETENTION arriba) — misma razón que EMA/MACD: + # ATR_14 es magnitud absoluta de precio (no auto-acotado como + # RSI/STOCH/ADX), así que sin esto puede alejarse del rango de + # entrenamiento tan rápido como el propio precio diverge. + atr_arr = _anchor_pull(atr_arr, atr_anchor) + + # --- V5: ADX_14 recursivo. Vela sintética degenerada (H=L=C) reduce + # +DM/-DM EXACTAMENTE a gain_arr/loss_arr (misma derivación que + # ATR_14 arriba) — reutiliza `atr_arr` (idéntica fórmula/periodo) + # como denominador de +DI/-DI, sin estado adicional. + plus_dm_smooth_arr = plus_dm_smooth_arr * (1 - ATR_ALPHA) + gain_arr * ATR_ALPHA + minus_dm_smooth_arr = minus_dm_smooth_arr * (1 - ATR_ALPHA) + loss_arr * ATR_ALPHA + safe_atr_arr = np.where(atr_arr == 0.0, 1.0, atr_arr) + plus_di_arr = 100 * plus_dm_smooth_arr / safe_atr_arr + minus_di_arr = 100 * minus_dm_smooth_arr / safe_atr_arr + di_sum_arr = plus_di_arr + minus_di_arr + safe_di_sum_arr = np.where(di_sum_arr == 0.0, 1.0, di_sum_arr) + dx_arr = np.where(di_sum_arr == 0.0, 0.0, 100 * np.abs(plus_di_arr - minus_di_arr) / safe_di_sum_arr) + adx_arr = adx_arr * (1 - ATR_ALPHA) + dx_arr * ATR_ALPHA + + # --- BB_WIDTH_20 recursivo. + # sintéticos (no retornos) — mismo patrón que log_return_window_arr, + # a nivel precio en vez de log-return. + price_window_arr = np.concatenate( + [price_window_arr[:, 1:], cursor_prices[:, np.newaxis]], axis=1 + ) + bb_mean_arr = price_window_arr.mean(axis=1) + bb_std_arr = price_window_arr.std(axis=1) + safe_bb_mean_arr = np.where(bb_mean_arr == 0.0, 1.0, bb_mean_arr) + bb_width_arr = np.where( + bb_mean_arr == 0.0, + 0.0, + (2 * BB_WIDTH_NUM_STD * bb_std_arr) / safe_bb_mean_arr, + ) + # Anchor-pull (fix calibración T+5, ver bloque ANCHOR_RETENTION + # arriba) — BB_WIDTH_20 es atado al nivel de precio (no auto-acotado) + # igual que EMA/MACD_SIGNAL/ATR; hasta ahora quedaba fuera del + # estabilizador pese a estar identificado como tal en el bloque + # soft-clip. + bb_width_arr = _anchor_pull(bb_width_arr, bb_width_anchor) + + # --- V3: OBV recursivo. sign(ΔP) * volumen PROXY constante (ver + # `volume_proxy` arriba) — este motor no proyecta volumen futuro, + # solo precio, así que el volumen sintético de cada paso reutiliza + # el promedio histórico reciente en vez de inventar una cifra nueva. + direction_arr = np.sign(delta_arr) + obv_arr = obv_arr + direction_arr * volume_proxy + # Anchor-pull (fix calibración T+5, ver bloque ANCHOR_RETENTION + # arriba) — OBV es una SUMA ACUMULADA sin ningún término de + # reversión propio (a diferencia de una EWM, que se amortigua sola). + # Sin esto, una racha de `direction_arr` con el mismo signo entre + # trayectorias (esperable mientras la señal direccional compartida + # aún no decayó del todo) la aleja del rango de entrenamiento de + # forma monótona y acelerada — el candidato más plausible al sesgo + # COMPARTIDO (P5 y P95 cayendo juntos) reportado en producción. + obv_arr = _anchor_pull(obv_arr, obv_anchor) + + # --- V6: OBV_ROC_20 — la feature que REALMENTE entra al tensor (ver + # `new_rows` más abajo). `obv_arr` (crudo, recursión sin cambios + # arriba) sigue siendo el estado interno; se lee el valor que ESTÁ + # por salir de la ventana (el de hace exactamente + # OBV_ROC_LOOKBACK_DAYS pasos, ANTES de deslizarla) como denominador + # — misma fórmula y mismo clip que `engineer_asset()` en + # train_kodaquant_v5.py (`obv.pct_change(20)` con denominador cero + # ->0.0 en vez de inf, luego clip a ±OBV_ROC_CLIP). + obv_denom_arr = obv_window_arr[:, 0] # valor de hace 20 pasos, ANTES del slide + safe_obv_denom_arr = np.where(obv_denom_arr == 0.0, 1.0, obv_denom_arr) + obv_roc_arr = np.clip( + np.where(obv_denom_arr == 0.0, 0.0, (obv_arr - obv_denom_arr) / safe_obv_denom_arr), + -OBV_ROC_CLIP, OBV_ROC_CLIP, + ) + obv_window_arr = np.concatenate( + [obv_window_arr[:, 1:], obv_arr[:, np.newaxis]], axis=1 + ) + + # --- STOCH_K_14 recursivo. Ventana deslizante de H/L (degenerada a + # cursor_prices en pasos sintéticos, real en el seed histórico). + stoch_high_window_arr = np.concatenate( + [stoch_high_window_arr[:, 1:], cursor_prices[:, np.newaxis]], axis=1 + ) + stoch_low_window_arr = np.concatenate( + [stoch_low_window_arr[:, 1:], cursor_prices[:, np.newaxis]], axis=1 + ) + highest_high_arr = stoch_high_window_arr.max(axis=1) + lowest_low_arr = stoch_low_window_arr.min(axis=1) + stoch_denom_arr = highest_high_arr - lowest_low_arr + safe_stoch_denom_arr = np.where(stoch_denom_arr == 0.0, 1.0, stoch_denom_arr) + stoch_k_arr = np.where( + stoch_denom_arr == 0.0, 50.0, + 100 * (cursor_prices - lowest_low_arr) / safe_stoch_denom_arr, + ) + + new_rows = cursor_windows[:, -1, :].copy() + # --- V6: proyección a features ESTACIONARIAS. La recursión interna + # de ema_fast_arr/ema_slow_arr/ema_20_arr/macd_signal_arr/atr_arr + # arriba NO cambió (misma matemática honesta, mismo anchor-pull) — + # lo único que cambia es QUÉ se escribe en el tensor que ve el + # modelo: razones adimensionales en vez de niveles absolutos, para + # que MinMaxScaler nunca vuelva a extrapolar sin límite ante un + # nuevo máximo histórico de precio. + new_rows[:, 0] = r_hat_batch # LOG_RETURN_1D — el retorno recién generado, ya en espacio real + new_rows[:, 1] = rsi_arr + safe_ema_20_arr = np.where(ema_20_arr == 0.0, 1.0, ema_20_arr) + new_rows[:, 2] = np.where( + ema_20_arr == 0.0, 0.0, (cursor_prices - ema_20_arr) / safe_ema_20_arr + ) # EMA20_DEV_PCT + safe_cursor_prices = np.where(cursor_prices == 0.0, 1.0, cursor_prices) + new_rows[:, 3] = macd_new_arr / safe_cursor_prices # MACD_PCT + new_rows[:, 4] = macd_signal_arr / safe_cursor_prices # MACD_SIGNAL_PCT + new_rows[:, 5] = sentiment_arr + new_rows[:, 6] = atr_arr / safe_cursor_prices # ATR_PCT + new_rows[:, 7] = bb_width_arr + new_rows[:, 8] = obv_roc_arr # OBV_ROC_20 + new_rows[:, 9] = adx_arr + new_rows[:, 10] = stoch_k_arr + new_rows[:, 11] = news_sentiment_value + # macro_tickers__LOGRET (índice 12+, tras LOG_RETURN_1D + 11 + # técnicos): este motor no proyecta macro a futuro. Con los factores + # macro ahora en ESPACIO DE RETORNO (ver `_fetch_feature_window`), + # "sin forecast" significa retorno diario = 0.0 (macro plano) — NO + # "repetir para siempre el último retorno real observado", que + # compondría un drift falso (ej. VIX +1.3% cada día del horizonte + # si el último día real cerró con ese retorno). Antes del fix del + # bug de paridad train/serve, esta columna guardaba precio crudo + # congelado, que SÍ equivalía correctamente a "retorno 0%" — esta + # asignación explícita preserva esa misma intención en el nuevo + # espacio de retornos. + new_rows[:, 12:] = 0.0 + cursor_windows = np.concatenate([cursor_windows[:, 1:, :], new_rows[:, np.newaxis, :]], axis=1) + + if price_paths: + price_matrix = np.stack(price_paths, axis=0) # (steps_completados, n_sim) + lower_arr = np.percentile(price_matrix, CONFIDENCE_LOWER_PERCENTILE, axis=1) + expected_arr = np.percentile(price_matrix, CONFIDENCE_MEDIAN_PERCENTILE, axis=1) + upper_arr = np.percentile(price_matrix, CONFIDENCE_UPPER_PERCENTILE, axis=1) + + # --- Trayectoria representativa (REAL, no fabricada) ---------------- + # `expected_arr` es un percentil calculado POR FECHA de forma + # independiente entre columnas — un corte transversal de las N + # simulaciones en cada instante t, no un camino muestral. Colapsar + # N caminatas i.i.d. fecha por fecha cancela parcialmente el ruido + # diario de cada trayectoria individual (ley de los grandes + # números): por construcción sale más suave que CUALQUIER camino + # individual, aunque cada camino individual (ver `noise_batch` + + # MC Dropout arriba) sea genuinamente ruidoso. + # + # FIX (variance collapse en sample_path): la versión anterior medía + # distancia a la mediana ACUMULADA sobre todo el horizonte + # (np.linalg.norm(..., axis=0) sumando los `steps` pasos). Eso sesga + # el argmin hacia la trayectoria MENOS ruidosa de las N=100 -- una + # que se aparta poco de la mediana EN CADA paso intermedio tiene + # distancia total más chica que una con zigzag diario genuino, + # aunque ambas terminen en un lugar similar. Con N=100 draws casi + # siempre hay una lo bastante "lisa" para ganar el argmin, matando + # la textura real que este campo existe para mostrar. + # + # Comparar SOLO en el día terminal preserva la consistencia + # narrativa (expected_path/predicted_return_pct se calculan sobre + # el último día) sin penalizar el ruido genuino de los días + # intermedios -- ya no premia trayectorias artificialmente suaves. + dist_to_median_terminal = np.abs(price_matrix[-1, :] - expected_arr[-1]) + representative_idx = int(np.argmin(dist_to_median_terminal)) + representative_arr = price_matrix[:, representative_idx] + else: + lower_arr = expected_arr = upper_arr = representative_arr = np.array([]) + + target_price = float(expected_arr[-1]) if expected_arr.size else last_price + total_return_pct = (target_price / last_price - 1) * 100 + + forecast_points = [ + { + "date": d, + "lower_bound": round(float(lo), 2), + "expected_path": round(float(ex), 2), + "upper_bound": round(float(hi), 2), + # Camino real (una de las N simulaciones), no un percentil — + # ver nota "Trayectoria representativa" arriba. Úsalo para + # DIBUJAR la línea central; usa `expected_path` (mediana) para + # cifras/decisiones (retorno %, señal táctica), que deben ser + # robustas a un solo draw ruidoso. + "sample_path": round(float(sp), 2), + } + for d, lo, ex, hi, sp in zip(forecast_dates, lower_arr, expected_arr, upper_arr, representative_arr) + ] + predicted_path = [p["expected_path"] for p in forecast_points] + tactical_signal = _find_optimal_entry_exit( + forecast_points, + anchor_date=anchor_date_str, + anchor_price=last_price_quote, + ) + + return { + "ticker": ticker, + "regime": regime, + "target_mode": target_mode, + "last_price": last_price_quote, + "predicted_price": round(target_price, 2), + "predicted_return_pct": round(total_return_pct, 2), + "trend": "alcista" if total_return_pct >= 0 else "bajista", + "historical": historical, + "forecast": forecast_points, + "predicted_path": predicted_path, + "tactical_signal": tactical_signal, + "forecast_incomplete": forecast_incomplete, + "variance_source": variance_source, + "n_simulations": n_sim, + # Auditoría de la memoria diaria (ver bloque "SEMILLA DETERMINISTA" + # arriba): dos responses con el mismo `deterministic_seed` son, + # verificablemente, la MISMA corrida — mismo (ticker, fecha UTC, + # horizonte). Cambia solo al cruzar medianoche UTC o al pedir un + # horizonte distinto, nunca entre requests idénticos del mismo día. + "deterministic_seed": base_seed, + "confidence_interval": f"P{CONFIDENCE_LOWER_PERCENTILE}-P{CONFIDENCE_UPPER_PERCENTILE}", + # Diagnóstico honesto (auditoría SPY oob_frac=45.6% en T+1, ver + # bloque _real_ood_dampening_factor): cuánto del input REAL en T+1 + # ya caía fuera del rango de entrenamiento, y si por eso se + # atenuó la magnitud de la señal del modelo. No reemplaza un + # retrain — solo evita mostrar un forecast degradado con la misma + # confianza aparente que uno in-distribution. + "real_data_ood_frac": round(real_input_oob_frac, 4), + "real_ood_dampening_applied": round(real_ood_dampening, 4), + "forecast_reliability": "degraded" if real_input_oob_frac > REAL_OOD_DAMPENING_START else "normal", + # V27 -- gate de confianza por ticker (ver EQUITY_HISTORICAL_EDGE). + # Aditivo puro: NO modifica `tactical_signal` ni su cálculo -- el + # consumidor de esta respuesta decide qué hacer con un tier "low" + # (atenuar tamaño, no mostrar, o mostrar con advertencia). Ningún + # número se inventa ni se fuerza a cruzar 53%. + "historical_edge": _get_historical_edge(ticker), + } + + +def _fmt_plan_math_line(plan: dict, horizon_days: int) -> str: + """ + Cheat-sheet de una línea por plan para el prompt. CRÍTICO: calcula la + ganancia en USD explícitamente aquí (capital * %return) para que el LLM + NUNCA tenga que inferirla — jamás debe confundir el precio de cotización + del activo (ej. $745.76/acción) con la ganancia real sobre el capital + invertido (ej. $0.05 USD sobre $6 invertidos). + """ + forecast = plan.get("forecast") + if forecast: + ganancia_estimada_usd = round( + plan["monto_usd"] * forecast["predicted_return_pct"] / 100, 2 + ) + prediction = ( + f"Precio de cotización: {_fmt_money(forecast['last_price'])} → " + f"{_fmt_money(forecast['predicted_price'])} " + f"({forecast['predicted_return_pct']:+.2f}%, {forecast['trend']}) | " + f"Ganancia estimada de la cartera: {_fmt_money(ganancia_estimada_usd)}" + ) + else: + prediction = "no disponible" + return ( + f"Activo={plan['activo_referencia']} | Porcentaje={plan['pct']} | " + f"Capital invertido={_fmt_money(plan['monto_usd'])} | Horizonte={horizon_days} días hábiles | " + f"{prediction}" + ) + + +# --------------------------------------------------------------------------- +# Risk profiling — el risk_score (0-100) es la ÚNICA fuente de verdad del +# split Plan A (Reserva) / Plan B (Riesgo). risk_profile es solo etiqueta. +# --------------------------------------------------------------------------- + +_DEFAULT_RISK_SCORE = 50 +_RISK_PROFILE_LABELS = {"conservador", "moderado", "agresivo"} +_DEFAULT_RISK_PROFILE = "moderado" + + +def _clamp_risk_score(risk_score: int | None) -> int: + if not isinstance(risk_score, int) or isinstance(risk_score, bool): + return _DEFAULT_RISK_SCORE + return max(0, min(100, risk_score)) + + +def _normalize_risk_profile(risk_profile: str | None) -> str: + normalized = (risk_profile or "").strip().lower() + return normalized if normalized in _RISK_PROFILE_LABELS else _DEFAULT_RISK_PROFILE + + +def _resolve_risk_split(risk_score: int | None) -> dict[str, float]: + """ + risk_score=85 -> 85% Plan B (Riesgo) / 15% Plan A (Reserva), continuo, + sin buckets. Reemplaza cualquier split fijo (60/40, 50/50, etc.). + """ + score = _clamp_risk_score(risk_score) + plan_b_weight = score / 100 + return {"plan_a": round(1 - plan_b_weight, 4), "plan_b": round(plan_b_weight, 4)} + + +def _is_finite_number(value: Any) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +# --------------------------------------------------------------------------- +# FIX CRÍTICO — DESFASE DE ESTADO (alucinación narrativa): `_build_investment_ +# plans` llamaba SIEMPRE a `_resolve_risk_split(risk_score)` — el split +# MANUAL del slider — sin importar que `main.py` ya hubiera resuelto un split +# distinto vía `risk_manager.calculate_portfolio` (Auto-Allocation IA, modo +# discovery, dictado por el `market_signal` real del radar/Alpha Seeker). +# Ese `portfolio_allocation` SÍ llegaba como parámetro a +# `generate_quanti_strategy_stream`, pero solo se reenviaba crudo al frontend +# en `meta_payload["allocation"]` — el frontend lo usaba para PISAR las +# tarjetas de Riesgo/Reserva (ver useSignalConsole.js), mientras que +# `investment_plans` (y por lo tanto `_build_tactical_operation` y el prompt +# del LLM) seguían calculando sobre el split manual del risk_score, ya +# invisible en pantalla. Resultado: dos verdades del split coexistiendo +# (75/25 en las tarjetas, 50/50 narrado por Quanti) y una ganancia neta +# (`net_profit_usd`) calculada sobre un capital que el usuario nunca vio +# asignado. +# +# `_resolve_effective_allocation` es ahora el ÚNICO punto que decide el +# split real de capital, ANTES de construir `investment_plans` — todo lo +# demás (amounts de las tarjetas, operación táctica, prompt del LLM) lee +# de esta única fuente. Usa los USD exactos que ya calculó +# `risk_manager.calculate_portfolio` (no los re-deriva multiplicando +# fracciones contra `budget_usd` de nuevo) para que no exista ni un +# centavo de drift por redondeo entre lo que ve el usuario y lo que narra +# Quanti. +# --------------------------------------------------------------------------- + +def _resolve_effective_allocation( + budget_usd: float, + portfolio_allocation: dict | None, + risk_score: int | None, + analysis_mode: str, +) -> dict[str, Any]: + """ + Retorna el split de capital REAL que debe gobernar tarjetas, operación + táctica y narrativa — todos desde el mismo objeto, cero duplicidad: + - modo 'discovery' CON asignación IA válida (`asignacion.riesgo_pct`/ + `reserva_pct`/`riesgo_usd`/`reserva_usd`, todos números finitos): + la Auto-Allocation IA manda. `source`='ai_auto_allocation'. + - modo 'specific', o 'discovery' sin asignación IA válida (radar + degradado, calculate_portfolio no disponible): cae al perfilador + manual (`_resolve_risk_split(risk_score)`) — el comportamiento + previo, nunca un 50/50 mudo. `source`='manual_risk_profile'. + """ + if analysis_mode == "discovery" and isinstance(portfolio_allocation, dict): + asignacion = portfolio_allocation.get("asignacion") + if isinstance(asignacion, dict): + riesgo_pct = asignacion.get("riesgo_pct") + reserva_pct = asignacion.get("reserva_pct") + riesgo_usd = asignacion.get("riesgo_usd") + reserva_usd = asignacion.get("reserva_usd") + if all(_is_finite_number(v) for v in (riesgo_pct, reserva_pct, riesgo_usd, reserva_usd)): + return { + "plan_a_usd": round(float(reserva_usd), 2), + "plan_a_pct": float(reserva_pct), + "plan_b_usd": round(float(riesgo_usd), 2), + "plan_b_pct": float(riesgo_pct), + "source": "ai_auto_allocation", + "signal_detectada": portfolio_allocation.get("signal_detectada"), + "mensaje_estrategico": portfolio_allocation.get("mensaje_estrategico"), + } + + split = _resolve_risk_split(risk_score) + return { + "plan_a_usd": round(budget_usd * split["plan_a"], 2), + "plan_a_pct": split["plan_a"], + "plan_b_usd": round(budget_usd * split["plan_b"], 2), + "plan_b_pct": split["plan_b"], + "source": "manual_risk_profile", + "signal_detectada": None, + "mensaje_estrategico": None, + } + + +def _candidate_alpha_score(candidate: dict) -> float: + """ + Alpha Score real: retorno proyectado CON SIGNO (nunca abs()) ponderado + por la confianza señal/ruido del propio forecast (ver + `_confidence_score`/`_rank_alpha_seeker_candidates` en prediccion.py). + Reemplaza el `risk_score` fantasma que ningún productor llenaba jamás + — con esa clave siempre en 0 para todos los candidatos, `max()` + devolvía en silencio el PRIMER elemento de la lista sin importar cuál + activo era realmente el mejor. Este score es la única fuente de + verdad de la selección. + """ + growth = candidate.get("predicted_return_pct", candidate.get("projected_growth_pct", 0.0)) or 0.0 + confidence = candidate.get("confidence_score", 0.0) or 0.0 + return float(growth) * (1.0 + float(confidence)) + + +def _resolve_plan_b_ticker( + radar_data: dict, + analysis_mode: str = "discovery", + target_asset: str | None = None, +) -> tuple[str, bool]: + """ + Retorna (ticker_resuelto, degraded). degraded=True cuando el usuario + pidió un target_asset fuera del universo entrenado y se sustituyó por + discovery — el caller DEBE propagar esto al frontend para que el chart + no muestre en silencio un activo distinto al seleccionado. + + Alpha Seeker (modo discovery / "Quanti's Choice"): escanea TODO el + universo real vía `radar_data["top_assets"]` (contrato nuevo, ver + `_rank_alpha_seeker_candidates` en prediccion.py; compat retro con la + clave legacy "recommendations" si algún caller viejo sigue mandando + ese payload) y elige el candidato con mayor `_candidate_alpha_score` + ENTRE LOS QUE TIENEN EDGE POSITIVO. Un activo con retorno proyectado + negativo NUNCA puede ganar la elección — "Quanti's Choice" promete la + mejor oportunidad real, no el movimiento con mayor magnitud (positiva + o negativa). PLAN_A_TICKER se excluye del pool: ya está cubierto por + Plan A, elegirlo también para Plan B rompería la diversificación. + """ + degraded = False + if analysis_mode == "specific" and target_asset: + normalized_ticker = target_asset.strip().upper() + try: + scalers = _get_scalers(_regime_for_ticker(normalized_ticker)) + except (ValueError, FileNotFoundError): + scalers = None + + if scalers and normalized_ticker in scalers["asset_to_id"]: + return normalized_ticker, False + + print( + f"⚠️ target_asset '{target_asset}' fuera del universo entrenado " + "— degradando a 'discovery' vía radar." + ) + degraded = True + + candidates = radar_data.get("top_assets") or radar_data.get("recommendations") or [] + candidates = [ + c for c in candidates + if (c.get("symbol") or c.get("ticker", "")).strip().upper() != PLAN_A_TICKER + ] + + profitable = [c for c in candidates if _candidate_alpha_score(c) > 0] + # Sin ningún candidato con edge positivo real, se degrada al mejor + # disponible del universo escaneado (puede incluir negativos) — sigue + # siendo dato real del motor, nunca el hardcode ciego de abajo, que + # solo se alcanza si el radar entero vino vacío. + pool = profitable or candidates + if not pool: + return "NVDA", degraded + + best = max(pool, key=_candidate_alpha_score) + symbol = (best.get("symbol") or best.get("ticker") or "NVDA").strip().upper() + return symbol, degraded + + +def _derive_capital_signal(radar_data: dict) -> str: + """ + Auto-Allocation: clasifica el radar REAL (`generate_predictions`, ver + services/prediccion.py) en el enum COMPRA/VENTA/NEUTRAL que consume + `risk_manager.calculate_portfolio` — activa el split de capital + dictado por IA (antes código muerto: nada escribía nunca + `radar_data["signal"]`, así que `calculate_portfolio` caía SIEMPRE en + NEUTRAL 50/50 sin importar el mercado). + + Deliberadamente NO reutiliza `_extract_market_signal` — esa función + arma una frase narrativa para el prompt del LLM ("volatilidad=..., + macro='...'"), no un enum clasificable; pasarla tal cual a + risk_manager.py caería siempre en su rama "señal no reconocida". + + Cero heurística nueva: solo LEE el veredicto que Alpha Seeker + (`_rank_alpha_seeker_candidates` en prediccion.py) ya calculó. + COMPRA: `top_assets` no vacío -> existe al menos una oportunidad + real de grado compra en el universo entrenado. + VENTA: sin oportunidades de compra Y el mover más fuerte del + radar (`recommendations[0]`) es una señal de VENTA real. + NEUTRAL: cualquier otro caso (radar vacío/degradado, mercado mixto). + """ + top_assets = radar_data.get("top_assets") or [] + if top_assets: + return "COMPRA" + + recommendations = radar_data.get("recommendations") or [] + if recommendations and str(recommendations[0].get("action", "")).strip().upper() == "VENTA": + return "VENTA" + + return "NEUTRAL" + + +# --------------------------------------------------------------------------- +# SentimentEnricher — capa async de "Visión Fundamental". Independiente del +# pipeline Keras: no toca `scaled_window` ni el bucle autoregresivo, solo +# enriquece el payload de salida con contexto macro antes del dispatch. +# Circuit Breaker propio — un fallo aquí NUNCA debe tumbar la proyección +# Monte Carlo ya calculada (ver except al fondo de get_market_sentiment). +# --------------------------------------------------------------------------- + +# FIX (Circuit Breaker por "timeout" que no era lentitud de red): 2.5s +# alcanza justo para un round-trip a Twelve Data en condiciones ideales, pero +# CERO margen para jitter real de red o para una cola momentánea en el +# executor. Con `_SENTIMENT_EXECUTOR` dedicado (arriba) la contención con +# Keras ya no existe, así que este valor ahora refleja tolerancia real a +# latencia de red, no un colchón para encubrir contención de threads. +SENTIMENT_API_TIMEOUT_SECONDS = 6.0 +SENTIMENT_MOMENTUM_LOOKBACK_DAYS = 21 # ~1 mes bursátil +SENTIMENT_BULLISH_THRESHOLD = 0.2 +SENTIMENT_BEARISH_THRESHOLD = -0.2 + +# Caché TTL en memoria — PLAN_A_TICKER (SPY) y el ticker de Plan B se +# consultan en CADA request de /consult y /radar; sin caché, requests +# concurrentes disparan N fetches redundantes al mismo símbolo, saturando +# el pool de sentimiento justo cuando más se lo necesita libre. 60s es +# suficientemente corto para no desactualizar el momentum (ventana de 21 +# días) y suficientemente largo para absorber ráfagas de tráfico. +_SENTIMENT_CACHE_TTL_SECONDS = 60.0 +_sentiment_cache: dict[str, tuple[float, dict[str, float | str]]] = {} + + +def _score_to_sentiment_label(score: float) -> str: + if score >= SENTIMENT_BULLISH_THRESHOLD: + return "Bullish" + if score <= SENTIMENT_BEARISH_THRESHOLD: + return "Bearish" + return "Neutral" + + +async def get_market_sentiment(symbol: str) -> dict[str, float | str]: + """ + Simula la conexión async a una API institucional de sentimiento + (Finnhub / Alpha Vantage). Sin key real conectada, el índice se deriva + del momentum de retorno realizado reciente (yfinance, mismo principio + de "sin cifras inventadas" que el resto del motor) normalizado por su + propia volatilidad — no ruido puro. Circuit Breaker: timeout, símbolo + sin histórico suficiente o cualquier fallo de red degrada + silenciosamente al fallback Neutral, sin propagar excepción JAMÁS — + esta función NUNCA debe poder tumbar un asyncio.gather() que la espera + junto a los forecasts reales. + + FIX (timeout espurio por contención de threads, no de red): antes corría + en el mismo executor default que `_forecast_asset` (Keras, bloqueante, + varios segundos). Ahora usa `_SENTIMENT_EXECUTOR` (pool propio, chico) + + una caché TTL de `_SENTIMENT_CACHE_TTL_SECONDS` por símbolo, así que + nunca hace cola detrás de un forecast pesado y no repite el mismo fetch + de red en cada request concurrente al mismo ticker. + """ + now = time.monotonic() + cached = _sentiment_cache.get(symbol) + if cached is not None and (now - cached[0]) < _SENTIMENT_CACHE_TTL_SECONDS: + return cached[1] + + try: + async def _fetch_raw_score() -> float: + loop = asyncio.get_running_loop() + + def _sync_momentum() -> float: + # `fetch_close_history` (Twelve Data + fallback Stooq, ver + # services/market_data.py) ya devuelve la serie de Close + # completa cacheada (2y) — el mismo dato que ya se descargó + # para el forecast de este ticker si corrió en la misma + # ventana de TTL, cero llamadas de red extra en ese caso. + closes = fetch_close_history(symbol, min_days=SENTIMENT_MOMENTUM_LOOKBACK_DAYS + 5) + if len(closes) < 2: + raise ValueError(f"Histórico insuficiente para {symbol}") + window = closes.tail(SENTIMENT_MOMENTUM_LOOKBACK_DAYS) + log_return = float(np.log(window.iloc[-1] / window.iloc[0])) + daily_log_returns = np.log(window / window.shift(1)).dropna() + sigma = float(daily_log_returns.std()) or 1e-6 + return log_return / (sigma * np.sqrt(len(window))) + + # Pool DEDICADO — nunca comparte cola con `_forecast_asset`. + return await loop.run_in_executor(_SENTIMENT_EXECUTOR, _sync_momentum) + + raw_score = await asyncio.wait_for( + _fetch_raw_score(), timeout=SENTIMENT_API_TIMEOUT_SECONDS + ) + sentiment_score = round(float(np.clip(raw_score, -1.0, 1.0)), 4) + result = { + "sentiment_score": sentiment_score, + "sentiment_label": _score_to_sentiment_label(sentiment_score), + "data_source": "KodaQuant Sentinel", + } + _sentiment_cache[symbol] = (now, result) + return result + except Exception as exc: # noqa: BLE001 — jamás propagar, degradar a Neutral + print( + f"⚠️ Circuit Breaker activado — fallo en get_market_sentiment ({symbol}): " + f"{type(exc).__name__}: {exc!r}\n" + f"{traceback.format_exc()}" + ) + fallback = { + "sentiment_score": 0.0, + "sentiment_label": "Neutral (Data Unavailable)", + "data_source": "KodaQuant Sentinel", + } + # Cachea el fallback también (TTL corto propio) para no reintentar + # un símbolo caído en cada request mientras la ventana de caché + # normal corre — evita mismo ticker rebotando el mismo fallo N veces + # en ráfaga. + _sentiment_cache[symbol] = (now, fallback) + return fallback + + +async def _safe_sentiment(symbol: str) -> dict[str, float | str]: + """ + Wrapper de defensa-en-profundidad para cualquier `asyncio.gather` que + incluya `get_market_sentiment` junto a tareas críticas (forecasts reales) + — `get_market_sentiment` ya jamás propaga excepciones por diseño, pero + esta capa garantiza que ningún cambio futuro en esa función pueda volver + a tumbar el pipeline principal por un fallo de sentimiento, que es + puramente decorativo/contextual frente al forecast Keras real. + """ + try: + return await get_market_sentiment(symbol) + except Exception as exc: # noqa: BLE001 — última línea de defensa + print(f"⚠️ _safe_sentiment: fallback de emergencia para {symbol}: {exc!r}") + return { + "sentiment_score": 0.0, + "sentiment_label": "Neutral (Data Unavailable)", + "data_source": "KodaQuant Sentinel", + } + + +async def _build_investment_plans( + budget_usd: float, + radar_data: dict, + risk_score: int = _DEFAULT_RISK_SCORE, + analysis_mode: str = "discovery", + target_asset: str | None = None, + forecast_horizon_days: int = DEFAULT_FORECAST_HORIZON_DAYS, + portfolio_allocation: dict | None = None, +) -> dict: + """ + ASÍNCRONA: Plan A, Plan B y su sentimiento de mercado se despachan EN + PARALELO vía asyncio.gather (cada forecast es un fetch a Twelve Data + + bucle autoregresivo Keras independiente; cada sentiment es su propio + fetch con Circuit Breaker propio) en vez de secuencial — corta la + latencia total de cada generación de estrategia. + + `portfolio_allocation` (Auto-Allocation IA, ver `_resolve_effective_ + allocation`) es ahora la ÚNICA fuente del split de capital cuando está + presente y es válida en modo discovery — monto_usd/pct de AMBOS planes + (y por lo tanto `_build_tactical_operation` y el prompt del LLM) leen + de aquí. Esto es lo que garantiza que las tarjetas de Riesgo/Reserva + del frontend y lo que narra Quanti sean SIEMPRE el mismo número. + """ + allocation = _resolve_effective_allocation(budget_usd, portfolio_allocation, risk_score, analysis_mode) + plan_b_ticker, target_asset_degraded = _resolve_plan_b_ticker(radar_data, analysis_mode=analysis_mode, target_asset=target_asset) + horizon = _resolve_horizon_days(forecast_horizon_days) + loop = asyncio.get_running_loop() + + async def _safe_forecast(ticker: str, label: str): + try: + return await loop.run_in_executor(None, _forecast_asset, ticker, horizon) + except Exception as exc: # noqa: BLE001 + print(f"⚠️ Forecast {label} ({ticker}) falló: {exc}") + return None + + plan_a_forecast, plan_b_forecast, plan_a_sentiment, plan_b_sentiment = await asyncio.gather( + _safe_forecast(PLAN_A_TICKER, "Plan A"), + _safe_forecast(plan_b_ticker, "Plan B"), + _safe_sentiment(PLAN_A_TICKER), + _safe_sentiment(plan_b_ticker), + ) + + return { + "plan_a": { + "nombre": "Plan A — Reserva", + "monto_usd": allocation["plan_a_usd"], + "pct": _fmt_pct(allocation["plan_a_pct"]), + "activo_referencia": PLAN_A_TICKER, + "forecast": plan_a_forecast, + "market_context": plan_a_sentiment, + }, + "plan_b": { + "nombre": "Plan B — Riesgo", + "monto_usd": allocation["plan_b_usd"], + "pct": _fmt_pct(allocation["plan_b_pct"]), + "activo_referencia": plan_b_ticker, + "forecast": plan_b_forecast, + "market_context": plan_b_sentiment, + }, + "target_asset_degraded": target_asset_degraded, + # Propagado a `_build_system_prompt` — el LLM necesita saber CUÁL + # de las dos fuentes decidió el split para no narrar el risk_score + # manual del usuario cuando en realidad fue la IA quien reasignó el + # capital (ver REGLA ANTI-ALUCINACIÓN en `_build_system_prompt`). + "allocation_source": allocation["source"], + "allocation_signal_detectada": allocation["signal_detectada"], + "allocation_mensaje_estrategico": allocation["mensaje_estrategico"], + } + + +# --------------------------------------------------------------------------- +# System prompt construction — TELEGRÁFICO: cero relleno, cero riesgo de +# corte por tokens. Toda cifra (fecha/precio/ganancia) ya viene validada y +# hard-locked desde _build_tactical_operation; el LLM SOLO copia y narra en +# 1 línea de contexto por activo — nunca decide ni recalcula un número. +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# Core directives — idioma + identidad. ÚNICA fuente de verdad para los 3 +# flujos (consult/strategy vía _build_system_prompt, chat vía +# stream/generate_quanti_chat_completion). Texto EXACTO exigido por +# producto, sin parafrasear. Se ANTEPONE al contenido del system message +# (no se anexa al final): en modelos chat-tuned como Llama 3.3, las reglas +# de persona/identidad "no negociables" se siguen con más fidelidad cuando +# son lo PRIMERO que el modelo lee bajo el rol system, no lo último +# concatenado después de un bloque largo de instrucciones de formato o +# clasificación. +# --------------------------------------------------------------------------- +CORE_DIRECTIVES = ( + "You are Quanti, the elite quantitative analysis engine of KodaQuant.\n\n" + "CRITICAL LANGUAGE RULE: You are a bilingual AI. You MUST respond in the " + "EXACT same language the user is speaking to you. If the user says " + "\"hi\" or speaks English, you MUST answer in English. If the user " + "speaks Spanish, you answer in Spanish. Default fallback is ALWAYS " + "English.\n\n" + "CRITICAL IDENTITY RULE: If asked about your origins, creator, or " + "development, you MUST state the exact truth: You were created solely " + "by Karim Suheim Estrada Egure, a high school student, during a single " + "night of intense development. Never claim to be built by a team or a " + "company. Maintain a highly professional, institutional tone." +) + + +def _inject_core_directives(messages: list[dict]) -> list[dict]: + """ + Clona `messages` y ANTEPONE CORE_DIRECTIVES al contenido del mensaje + `system` (índice 0) — a propósito NO se anexa al final. Si no viniera + un system message, antepone uno nuevo solo con las directivas — nunca + deja pasar una llamada al LLM sin idioma/identidad resueltos. + """ + if not messages or messages[0].get("role") != "system": + return [{"role": "system", "content": CORE_DIRECTIVES}, *messages] + + patched_system = dict(messages[0]) + existing = patched_system.get("content", "") + patched_system["content"] = f"{CORE_DIRECTIVES}\n\n{existing}" if existing else CORE_DIRECTIVES + return [patched_system, *messages[1:]] + + +# Alias retrocompatible — cualquier código que siga importando +# `_inject_language_directive` (nombre viejo) sigue funcionando sin tocar +# otros archivos; ahora también aplica la regla de identidad. +_inject_language_directive = _inject_core_directives + + +# --------------------------------------------------------------------------- +# Idioma del módulo de Predicción/Estrategia — mismo principio de arquitectura +# que CORE_DIRECTIVES (chat), pero aquí no hay turno de usuario del que +# "detectar" idioma: el frontend manda `language` ('en' | 'es') explícito en +# el payload de submit, y esta directiva se ANTEPONE (nunca se anexa) a TODO +# lo demás en el system prompt — inglés es el idioma MAESTRO/default. +# --------------------------------------------------------------------------- +_SUPPORTED_LANGUAGES = {"en", "es"} +_DEFAULT_LANGUAGE = "en" + +_LANGUAGE_NAMES = { + "en": "ENGLISH", + "es": "SPANISH (ESPAÑOL)", +} + + +def _normalize_language(language: str | None) -> str: + """Normaliza el código de idioma recibido del frontend. Default: 'en'.""" + code = (language or "").strip().lower() + return code if code in _SUPPORTED_LANGUAGES else _DEFAULT_LANGUAGE + + +def _build_language_directive(language: str | None) -> str: + """ + Construye la CRITICAL LANGUAGE DIRECTIVE exacta exigida por producto. + Se antepone (ver _build_system_prompt) a CORE_DIRECTIVES y al resto del + prompt — es lo PRIMERO que el modelo lee, con máxima prioridad de + instrucción, igual que CORE_DIRECTIVES en el flujo de chat. + """ + language_requested = _LANGUAGE_NAMES[_normalize_language(language)] + return ( + "CRITICAL LANGUAGE DIRECTIVE: The user has requested this strategic " + f"analysis and prediction table in {language_requested}. You MUST " + "generate the entire output, including all analysis paragraphs, " + "table headers, and table row data, STRICTLY and FLAWLESSLY in " + f"{language_requested}. Do not mix languages under any circumstance." + ) + +def _json_numpy_safe(obj): + """default= de json.dumps: coacciona escalares numpy a tipos nativos en + vez de dejar que TypeError reviente el generador SSE después de que los + headers 200 ya salieron (ver generate_quanti_strategy_stream, L2969).""" + if isinstance(obj, np.floating): + return float(obj) + if isinstance(obj, np.integer): + return int(obj) + if isinstance(obj, np.ndarray): + return obj.tolist() + return str(obj) + +def _build_system_prompt( + budget_usd: float, + market_signal: str, + plan_a: dict, + plan_b: dict, + risk_profile: str, + risk_score: int, + horizon_days: int, + plan_a_operation: dict | None = None, + plan_b_operation: dict | None = None, + language: str | None = None, + allocation_source: str = "manual_risk_profile", + allocation_signal_detectada: str | None = None, +) -> str: + """ + Prompt hiper-corto e inyección rígida vía f-strings, doble hard-lock: + cada fecha/precio/ganancia se inyecta tanto en el cheat-sheet + (`plan_a_line` / `plan_b_line`) como, literalmente, dentro de la propia + plantilla de ESTRATEGIA DE RESERVA / RIESGO — el LLM ya no tiene que + "copiar" el dato desde una línea de contexto separada, lo recibe + pre-escrito en el hueco exacto donde debe aparecer. Esto es lo que evita + que a veces se comiera la fecha o la confundiera con el precio. + Estructura de salida: RESUMEN DEL PORTAFOLIO TÁCTICO / ESTRATEGIA DE + RESERVA / ESTRATEGIA DE RIESGO, separadas por \\n\\n, tono institucional + ("quirúrgico, sofisticado y directo"), máximo 4 líneas por párrafo. + + `allocation_source` (ver `_resolve_effective_allocation`) es lo que + evita el desfase clásico "narra 50/50 y risk score manual mientras la + tarjeta muestra 75/25 IA": cuando el split real vino de Auto-Allocation + (`ai_auto_allocation`), el prompt AMARRA los % de Reserva/Riesgo — que + ya son los mismos que ve el usuario en pantalla, porque + `_build_investment_plans` los tomó de la MISMA fuente — a la señal de + mercado real, y prohíbe explícitamente mencionar el risk score manual + como si hubiera decidido el split. + """ + valid_profits = [op["net_profit_usd"] for op in (plan_a_operation, plan_b_operation) if op] + total_profit_line = ( + f"Ganancia Neta Proyectada TOTAL: {_fmt_money(sum(valid_profits))}" + if valid_profits + else "Ganancia Neta Proyectada TOTAL: no disponible (sin ventana de salida clara en ningún activo)." + ) + + def _operation_line(label: str, plan: dict, operation: dict | None) -> str: + ticker = plan["activo_referencia"] + if operation: + return ( + f"{label} ({ticker}): COMPRAR el {operation['entry_date']} a " + f"{_fmt_money(operation['entry_price'])} | VENDER el {operation['exit_date']} a " + f"{_fmt_money(operation['exit_price'])} | Ganancia: {_fmt_money(operation['net_profit_usd'])}" + ) + return f"{label} ({ticker}): SIN ventana de salida clara en este horizonte — no inventes fecha, precio ni ganancia." + + plan_a_line = _operation_line("RESERVA", plan_a, plan_a_operation) + plan_b_line = _operation_line("RIESGO", plan_b, plan_b_operation) + + # Única línea de asignación de capital — la MISMA fracción que ya + # decidió `monto_usd` de plan_a/plan_b (y por lo tanto lo que ve el + # usuario en las tarjetas Riesgo/Reserva). El LLM no recibe el + # risk_score como si fuera la causa del split salvo que REALMENTE lo + # haya sido. + if allocation_source == "ai_auto_allocation": + allocation_line = ( + f"Asignación de Capital: {plan_b['pct']} Riesgo ({plan_b['activo_referencia']}) / " + f"{plan_a['pct']} Reserva ({plan_a['activo_referencia']}) — decidida por Auto-Allocation IA " + f"en función de la señal de mercado real detectada: {allocation_signal_detectada or market_signal}. " + f"El risk score manual del usuario ({risk_score}/100, perfil {risk_profile}) NO determinó este " + "split en este ciclo — PROHIBIDO mencionarlo como causa, PROHIBIDO describir el enfoque como " + "'equilibrado' o '50/50' salvo que el porcentaje arriba sea literalmente 50/50." + ) + else: + allocation_line = ( + f"Asignación de Capital: {plan_b['pct']} Riesgo ({plan_b['activo_referencia']}) / " + f"{plan_a['pct']} Reserva ({plan_a['activo_referencia']}) — derivada del Risk Score manual del " + f"usuario: {risk_score}/100 (perfil {risk_profile})." + ) + + return _build_language_directive(language) + "\n\n" + CORE_DIRECTIVES + "\n\n" + f""" +Eres Quanti, la IA táctica de KodaQuant. Eres un estratega cuantitativo de élite institucional. + +Reglas inquebrantables: +- CERO formato Markdown (prohibido usar asteriscos **). +- Usa exactamente DOS saltos de línea (\\n\\n) para separar tus párrafos. +- Sé quirúrgico, sofisticado y directo. No superes las 4 líneas por párrafo. +- Nunca reveles que eres un modelo de lenguaje. + +DATOS MATEMÁTICOS OBLIGATORIOS (proyección del motor cuantitativo — modelo Keras + +volatilidad histórica calibrada — ÚNICA FUENTE VÁLIDA: PROHIBIDO INVENTAR, REDONDEAR, +OMITIR O RECALCULAR ninguna fecha, precio, porcentaje o monto; trátalos como una +proyección, no como una certeza garantizada): +- Capital total: {_fmt_money(budget_usd)} +- {allocation_line} +- Señal de mercado (contexto macro): {market_signal} +- {plan_a_line} +- {plan_b_line} +- {total_profit_line} +- No confundas el precio de cotización del activo con la ganancia neta sobre el capital: son cifras distintas. +- No confundas la Asignación de Capital (Riesgo/Reserva, arriba) con el precio o la ganancia de cada operación: son cifras independientes. + +Estructura OBLIGATORIA del reporte (integra estos datos palabra por palabra, sin alterarlos): + +RESUMEN DEL PORTAFOLIO TÁCTICO +Redacta un análisis brillante e institucional de la configuración actual: Capital Total invertido, la Asignación de Capital exacta (Riesgo/Reserva, con su fuente real tal como se te indicó arriba) y Ganancia Neta Total Esperada. Máximo 4 líneas. + +ESTRATEGIA DE RESERVA: {plan_a['activo_referencia']} +Redacta la orden táctica. DEBES incluir obligatoriamente: comprar el {plan_a_operation['entry_date'] if plan_a_operation else '[SIN VENTANA DE SALIDA CLARA]'} a {_fmt_money(plan_a_operation['entry_price']) if plan_a_operation else '[N/D]'}, y liquidar el {plan_a_operation['exit_date'] if plan_a_operation else '[N/D]'} a {_fmt_money(plan_a_operation['exit_price']) if plan_a_operation else '[N/D]'}. Ganancia estimada: {_fmt_money(plan_a_operation['net_profit_usd']) if plan_a_operation else '[N/D]'}. Justifica brevemente la estabilidad. + +ESTRATEGIA DE RIESGO: {plan_b['activo_referencia']} +Redacta la orden táctica. DEBES incluir obligatoriamente: comprar el {plan_b_operation['entry_date'] if plan_b_operation else '[SIN VENTANA DE SALIDA CLARA]'} a {_fmt_money(plan_b_operation['entry_price']) if plan_b_operation else '[N/D]'}, y liquidar el {plan_b_operation['exit_date'] if plan_b_operation else '[N/D]'} a {_fmt_money(plan_b_operation['exit_price']) if plan_b_operation else '[N/D]'}. Ganancia estimada: {_fmt_money(plan_b_operation['net_profit_usd']) if plan_b_operation else '[N/D]'}. Justifica brevemente el potencial de crecimiento. + +Si una estrategia muestra "[SIN VENTANA DE SALIDA CLARA]" o "[N/D]", dilo en una +línea breve y sofisticada dentro de esa sección — jamás inventes fecha, precio ni +ganancia para reemplazarlo. Separa las tres secciones con exactamente \\n\\n. Nada +de viñetas, listas ni texto fuera de esta estructura. +""".strip() + + +_USER_PROMPTS = { + "es": ( + "Genera el reporte en TEXTO PLANO (nunca JSON, nunca Markdown, nunca " + "asteriscos), quirúrgico y sofisticado, con las 3 secciones exigidas — " + "RESUMEN DEL PORTAFOLIO TÁCTICO, ESTRATEGIA DE RESERVA y ESTRATEGIA DE " + "RIESGO — usando exclusivamente los datos numéricos ya provistos en tus " + "instrucciones, palabra por palabra. Separa cada sección con exactamente " + "dos saltos de línea. Prohibido omitir alguna fecha, algún precio, o el " + "activo de Riesgo. Todo el reporte, incluidos los encabezados de " + "sección, debe estar en ESPAÑOL." + ), + "en": ( + "Generate the report in PLAIN TEXT (never JSON, never Markdown, never " + "asterisks), surgical and sophisticated, with the 3 required sections — " + "translate the section headers into English while keeping their exact " + "meaning: TACTICAL PORTFOLIO SUMMARY, RESERVE STRATEGY and RISK " + "STRATEGY — using exclusively the numeric data already provided in " + "your instructions, word for word. Separate each section with exactly " + "two line breaks. Do not omit any date, any price, or the Risk asset. " + "The entire report, including section headers, MUST be in ENGLISH." + ), +} + + +def _build_user_prompt(language: str | None = None) -> str: + return _USER_PROMPTS[_normalize_language(language)] + + +# --------------------------------------------------------------------------- +# LLM inference — Groq LPU en la nube (`llama-3.3-70b-versatile`, SDK +# oficial `groq`, cliente `AsyncGroq`), asíncrono, Circuit Breaker a +# fallback matemático si la API de Groq falla o no responde. +# --------------------------------------------------------------------------- + + +def _sanitize_llm_output(raw_output: str) -> list[str]: + """ + Contrato nuevo: TEXTO PLANO, no JSON. Los títulos van en MAYÚSCULAS y las + secciones separadas por '\\n\\n' (ver _build_system_prompt) — el frontend + divide este bloque con `.split('\\n')` y mapea cada fragmento no vacío a su + propio

    . Acá solo saneamos defensivamente por si el LLM ignora la + instrucción y de todos modos manda backticks o asteriscos de Markdown, que + React no va a renderizar. + """ + text = raw_output.strip() + text = text.removeprefix("```").removesuffix("```").strip() + text = text.replace("**", "").replace("*", "") + return [text] if text else [] + + +def _describe_llm_failure(exc: Exception) -> str: + """ + Diagnóstico legible para los sitios de llamada a Groq. Distingue las + 4 causas reales de fallo — sin conexión a api.groq.com, cuota/rate + limit del Free Tier (429), API key inválida (401), y cualquier otro + error HTTP no-2xx que Groq devuelva — para que el log diga la causa + exacta en vez de un genérico "el LLM no respondió". + """ + if isinstance(exc, GroqAPIConnectionError): + return ( + "sin conexión con Groq LPU (api.groq.com). Verificá la salida de " + f"red del servidor hacia Groq. Detalle: {exc}" + ) + if isinstance(exc, GroqRateLimitError): + return f"cuota de Groq excedida (429 — rate limit del Free Tier). Detalle: {exc}" + if isinstance(exc, GroqAuthenticationError): + return f"GROQ_API_KEY inválida o no autorizada (401). Detalle: {exc}" + if isinstance(exc, GroqAPIStatusError): + return f"Groq devolvió un error HTTP {exc.status_code}. Detalle: {exc}" + return str(exc) + + +def _is_connection_failure(exc: Exception) -> bool: + """ + True SOLO cuando Groq es inalcanzable a nivel de red/transporte — + equivalente exacto al viejo httpx.ConnectError del transporte local: + DNS roto, timeout de conexión, TLS/handshake fallido hacia + api.groq.com. Es la ÚNICA condición que debe tratarse como Circuit + Breaker real (motor generativo "caído"). + + Cuota excedida (429), API key inválida (401) o cualquier otro 4xx/5xx + de Groq NO son fallos de conexión — el servicio SÍ respondió, solo que + con un error. _describe_llm_failure los distingue para el log, pero + ambos casos degradan igual, al mismo fallback matemático (ver + _call_quanti_llm / generate_quanti_strategy_stream): el frontend nunca + debe ver un 5xx a mitad de un SSE ya iniciado, así que todo fallo de la + voz generativa —sea cual sea la causa— resuelve en un 200 OK con + guidance calculado por el motor Keras. + """ + return isinstance(exc, GroqAPIConnectionError) + + +# Alias públicos (sin "_") para uso desde api/quanti_chat.py — el Circuit +# Breaker del endpoint de chat streaming necesita esta misma distinción. +describe_llm_failure = _describe_llm_failure +is_llm_connection_failure = _is_connection_failure + + +# --------------------------------------------------------------------------- +# Primitivas de transporte — ÚNICO lugar donde se llama al cliente +# `_groq_client` (AsyncGroq). _call_quanti_llm, _stream_quanti_llm, +# generate_quanti_chat_completion y stream_quanti_chat_completion delegan +# acá; ninguno de los 4 conoce detalles del SDK de Groq. +# --------------------------------------------------------------------------- + +async def _llm_chat_completion(messages: list[dict]) -> str: + """ + Completion NO-streaming vía Groq LPU. Cliente 100% async (AsyncGroq) — + nunca bloquea el event loop de FastAPI. Las excepciones de Groq + (GroqAPIConnectionError, GroqRateLimitError, GroqAuthenticationError, + GroqAPIStatusError — todas subclases de groq.APIError) se propagan tal + cual al caller (_call_quanti_llm), que decide cómo degradar. + """ + response = await _groq_client.chat.completions.create( + model=GROQ_MODEL_NAME, + messages=messages, + temperature=0.4, + max_tokens=GROQ_MAX_OUTPUT_TOKENS, + ) + return response.choices[0].message.content or "" + + +async def _llm_chat_stream(messages: list[dict]) -> AsyncGenerator[str, None]: + """ + Streaming asíncrono vía Groq LPU (`stream=True`). `AsyncGroq` devuelve + un iterador async nativo de `ChatCompletionChunk` — sin threads, sin + colas puente, sin parsing manual de SSE crudo (eso lo resuelve el SDK + oficial puertas adentro). Cada chunk con `delta.content` no vacío se + yieldea tal cual al caller (_stream_quanti_llm / SSE de + generate_quanti_strategy_stream). + """ + stream = await _groq_client.chat.completions.create( + model=GROQ_MODEL_NAME, + messages=messages, + temperature=0.4, + max_tokens=GROQ_MAX_OUTPUT_TOKENS, + stream=True, + ) + async for chunk in stream: + delta = chunk.choices[0].delta.content + if delta: + yield delta + + +_CIRCUIT_BREAKER_FALLBACK_TEMPLATES = { + "es": ( + "Nuestro motor de análisis en vivo está momentáneamente fuera de línea, " + "pero la matemática no descansa: el modelo cuantitativo asigna " + "{riesgo_pct} ({riesgo_usd}) a riesgo y {reserva_pct} ({reserva_usd}) a " + "reserva. Mantén esa disciplina de asignación mientras restablecemos la " + "voz de Quanti." + ), + "en": ( + "Our live analysis engine is momentarily offline, but the math never " + "sleeps: the quantitative model allocates {riesgo_pct} ({riesgo_usd}) " + "to risk and {reserva_pct} ({reserva_usd}) to reserve. Hold that " + "allocation discipline while we restore Quanti's voice." + ), +} + + +def _build_circuit_breaker_fallback(amounts: dict, language: str | None = None) -> str: + template = _CIRCUIT_BREAKER_FALLBACK_TEMPLATES[_normalize_language(language)] + return template.format( + riesgo_pct=amounts["riesgo_pct"], + riesgo_usd=_fmt_money(amounts["riesgo_usd"]), + reserva_pct=amounts["reserva_pct"], + reserva_usd=_fmt_money(amounts["reserva_usd"]), + ) + + +async def _call_quanti_llm(system_prompt: str, user_prompt: str, amounts: dict, language: str | None = None) -> str: + """ + Llamada asíncrona al modelo Quanti vía Groq LPU (ver _llm_chat_completion). + Circuit Breaker TITANIO: cualquier fallo de Groq (sin conexión, cuota + excedida, API key inválida, error 5xx) se captura sin propagar + excepción y degrada a un fallback matemático con los valores ya + calculados por Keras — el frontend siempre recibe 200 OK, nunca nota + la caída del servicio de inferencia. El fallback respeta `language` + igual que el resto del pipeline. + """ + try: + return await _llm_chat_completion( + [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ] + ) + except Exception as exc: # noqa: BLE001 + if _is_connection_failure(exc): + print(f"⚠️ Circuit Breaker activado — Groq LPU inalcanzable: {_describe_llm_failure(exc)}") + else: + print(f"⚠️ Fallo no-conexión en Quanti LLM (cuota/auth/5xx de Groq, no caída de red): {_describe_llm_failure(exc)}") + + return _build_circuit_breaker_fallback(amounts, language) + +async def _stream_quanti_llm(system_prompt: str, user_prompt: str) -> AsyncGenerator[str, None]: + """ + Streaming asíncrono del modelo Quanti vía Groq LPU (ver _llm_chat_stream). + Si la llamada a Groq falla ANTES del primer chunk (sin conexión, cuota + excedida, API key inválida, 5xx), la excepción se propaga al caller + para que active el fallback matemático — nunca deja un SSE a medias. + """ + async for delta in _llm_chat_stream( + [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ] + ): + yield delta + + +async def generate_quanti_strategy_stream( + budget_usd: float, + portfolio_allocation: dict, + radar_data: dict, + experience_level: str, + analysis_mode: str = "discovery", + target_asset: str | None = None, + forecast_horizon_days: int = DEFAULT_FORECAST_HORIZON_DAYS, + risk_profile: str = _DEFAULT_RISK_PROFILE, + risk_score: int | None = None, + language: str | None = None, +) -> AsyncGenerator[str, None]: + """ + Generador SSE: emite 'meta' (payload numérico Keras, ya resuelto) de + inmediato, luego 'token' por cada fragmento del LLM, luego 'done'. + Circuit Breaker TITANIO: si el stream falla antes de emitir el primer + token, emite 'fallback' con el texto matemático y cierra — siempre + 200 OK vía StreamingResponse, el frontend nunca ve un error HTTP. + """ + # Tramo Keras/data (FASE 3): blindado aparte del try/except del streaming + # LLM de más abajo, que ya tiene su propio Circuit Breaker. Un fallo acá + # (yfinance, ticker sin datos, Keras) grita en terminal y cierra el SSE + # con un evento 'error' explícito en vez de reventar el generador a + # medias sin que el caller (StreamingResponse) tenga forma de saberlo. + try: + resolved_level = _select_experience_level(budget_usd, experience_level) + resolved_risk_profile = _normalize_risk_profile(risk_profile) + resolved_risk_score = _clamp_risk_score(risk_score) + resolved_language = _normalize_language(language) + horizon = _resolve_horizon_days(forecast_horizon_days) + market_signal = _extract_market_signal(radar_data) + + investment_plans = await _build_investment_plans( + budget_usd, radar_data, resolved_risk_score, analysis_mode, target_asset, horizon, + portfolio_allocation=portfolio_allocation, + ) + amounts = _compute_exact_amounts(investment_plans) + amounts["plan_a"] = investment_plans["plan_a"] + amounts["plan_b"] = investment_plans["plan_b"] + + plan_a_operation = _build_tactical_operation(investment_plans["plan_a"]) + plan_b_operation = _build_tactical_operation(investment_plans["plan_b"]) + + meta_payload = { + "status": "success", + "symbol": investment_plans["plan_b"]["activo_referencia"], + "market_context": investment_plans["plan_b"]["market_context"], + "amounts": amounts, + "chart_data": { + "plan_a": investment_plans["plan_a"]["forecast"], + "plan_b": investment_plans["plan_b"]["forecast"], + }, + "tactical_operations": { + "plan_a": plan_a_operation, + "plan_b": plan_b_operation, + }, + "meta": { + "budget_usd": round(budget_usd, 2), + "experience_level": resolved_level, + "radar_data": radar_data, + "market_signal": market_signal, + "analysis_mode": analysis_mode, + "target_asset": target_asset, + "forecast_horizon_days": horizon, + "risk_profile": resolved_risk_profile, + "risk_score": resolved_risk_score, + "language": resolved_language, + "target_asset_degraded": investment_plans.get("target_asset_degraded", False), + # Fuente real del split que ya está reflejado en `amounts` y + # en la narrativa de Quanti — 'ai_auto_allocation' cuando + # Auto-Allocation IA mandó, 'manual_risk_profile' cuando fue + # el risk_score del slider (ver `_resolve_effective_allocation`). + "allocation_source": investment_plans.get("allocation_source", "manual_risk_profile"), + }, + "allocation": portfolio_allocation, + } + # Serialización DENTRO del try: si meta_payload trae un tipo no + # nativo (np.float64/np.int64 colado desde amounts/portfolio_allocation/ + # radar_data), TypeError debe caer en el except de abajo — no escapar + # crudo después de que Starlette ya mandó los headers 200. + meta_json = json.dumps(meta_payload, default=_json_numpy_safe) + + system_prompt = _build_system_prompt( + budget_usd=budget_usd, + market_signal=market_signal, + plan_a=investment_plans["plan_a"], + plan_b=investment_plans["plan_b"], + risk_profile=resolved_risk_profile, + risk_score=resolved_risk_score, + horizon_days=horizon, + plan_a_operation=plan_a_operation, + plan_b_operation=plan_b_operation, + language=resolved_language, + allocation_source=investment_plans.get("allocation_source", "manual_risk_profile"), + allocation_signal_detectada=investment_plans.get("allocation_signal_detectada"), + ) + user_prompt = _build_user_prompt(resolved_language) + except Exception as exc: # noqa: BLE001 — blindaje total del pipeline (FASE 3) + traceback.print_exc() + print(f"🔥 ERROR CRÍTICO EN QUANTI (generate_quanti_strategy_stream, pre-LLM): {exc}") + yield f"event: error\ndata: {json.dumps({'status': 'error', 'error': str(exc)})}\n\n" + return + + yield f"event: meta\ndata: {meta_json}\n\n" + + full_text, started = "", False + try: + async for delta in _stream_quanti_llm(system_prompt, user_prompt): + started = True + full_text += delta + yield f"event: token\ndata: {json.dumps({'delta': delta})}\n\n" + except Exception as exc: # noqa: BLE001 + print(f"⚠️ Circuit Breaker activado — fallo en Quanti LLM stream: {_describe_llm_failure(exc)}") + if not started: + fallback_text = _build_circuit_breaker_fallback(amounts, resolved_language) + yield f"event: fallback\ndata: {json.dumps({'guidelines': [fallback_text]})}\n\n" + return + + guidelines = _sanitize_llm_output(full_text) if started else [] + yield f"event: done\ndata: {json.dumps({'guidelines': guidelines})}\n\n" + + +async def generate_quanti_voice( + budget_usd: float, + amounts: dict, + market_signal: str, + plan_a: dict, + plan_b: dict, + risk_profile: str, + risk_score: int, + horizon_days: int, + language: str | None = None, + allocation_source: str = "manual_risk_profile", + allocation_signal_detectada: str | None = None, +) -> list[str]: + """ + LA VOZ DE QUANTI. Nunca recalcula cifras — solo las narra, ahora como 3 + órdenes tácticas de trading (Resumen de Portafolio + Operación de Reserva + Plan A + Operación de Riesgo Plan B). El "hard lock" numérico vive en + _build_system_prompt / _build_tactical_operation; fallback seguro si + Groq falla (ver _call_quanti_llm, Circuit Breaker, sin cambios). `language` + ('en' | 'es', default 'en') gobierna la CRITICAL LANGUAGE DIRECTIVE + anteponía en _build_system_prompt. `allocation_source`/`allocation_signal_ + detectada` (ver `_resolve_effective_allocation`) se propagan tal cual al + prompt para que la narrativa nunca atribuya el split de capital al + risk_score manual cuando en realidad fue Auto-Allocation IA quien lo + decidió. + """ + resolved_language = _normalize_language(language) + plan_a_operation = _build_tactical_operation(plan_a) + plan_b_operation = _build_tactical_operation(plan_b) + + system_prompt = _build_system_prompt( + budget_usd=budget_usd, + market_signal=market_signal, + plan_a=plan_a, + plan_b=plan_b, + risk_profile=risk_profile, + risk_score=risk_score, + horizon_days=horizon_days, + plan_a_operation=plan_a_operation, + plan_b_operation=plan_b_operation, + language=resolved_language, + allocation_source=allocation_source, + allocation_signal_detectada=allocation_signal_detectada, + ) + user_prompt = _build_user_prompt(resolved_language) + + raw_output = await _call_quanti_llm(system_prompt, user_prompt, amounts, resolved_language) + return _sanitize_llm_output(raw_output) + + +# --------------------------------------------------------------------------- +# Public entrypoint +# --------------------------------------------------------------------------- + +async def generate_quanti_strategy( + budget_usd: float, + portfolio_allocation: dict, + radar_data: dict, + experience_level: str, + analysis_mode: str = "discovery", + target_asset: str | None = None, + forecast_horizon_days: int = DEFAULT_FORECAST_HORIZON_DAYS, + risk_profile: str = _DEFAULT_RISK_PROFILE, + risk_score: int | None = None, + language: str | None = None, +) -> dict: + """ + Entry point público — TODO el pipeline (Keras + Groq) blindado por + try/except (FASE 3): un fallo aquí (yfinance caído, ticker sin datos, + excepción de Keras, etc. — no cubierto por el Circuit Breaker interno + de Groq, que ya degrada solo) NUNCA debe tirar un 500 sin contexto. + Se grita en terminal (traceback completo + línea 🔥) y se retorna el + MISMO esqueleto de llaves top-level que el payload de éxito + (status/symbol/market_context/amounts/chart_data/tactical_operations/ + guidelines/meta/allocation), con status="error" + "error" y los campos + de datos en None — el frontend puede seguir tipando contra las mismas + llaves sin romper. + """ + try: + resolved_level = _select_experience_level(budget_usd, experience_level) + resolved_risk_profile = _normalize_risk_profile(risk_profile) + resolved_risk_score = _clamp_risk_score(risk_score) + resolved_language = _normalize_language(language) + horizon = _resolve_horizon_days(forecast_horizon_days) + market_signal = _extract_market_signal(radar_data) + + investment_plans = await _build_investment_plans( + budget_usd, + radar_data, + resolved_risk_score, + analysis_mode, + target_asset, + horizon, + portfolio_allocation=portfolio_allocation, + ) + + # amounts (riesgo/reserva) SIEMPRE deriva de investment_plans — una + # sola fuente de split (_resolve_effective_allocation, manual o IA + # según el ciclo), cero duplicidad con datos viejos. + amounts = _compute_exact_amounts(investment_plans) + + guidelines = await generate_quanti_voice( + budget_usd=budget_usd, + amounts=amounts, + market_signal=market_signal, + plan_a=investment_plans["plan_a"], + plan_b=investment_plans["plan_b"], + risk_profile=resolved_risk_profile, + risk_score=resolved_risk_score, + horizon_days=horizon, + language=resolved_language, + allocation_source=investment_plans.get("allocation_source", "manual_risk_profile"), + allocation_signal_detectada=investment_plans.get("allocation_signal_detectada"), + ) + + amounts["plan_a"] = investment_plans["plan_a"] + amounts["plan_b"] = investment_plans["plan_b"] + + return { + "status": "success", + "symbol": investment_plans["plan_b"]["activo_referencia"], + "market_context": investment_plans["plan_b"]["market_context"], + "amounts": amounts, + "chart_data": { + "plan_a": investment_plans["plan_a"]["forecast"], + "plan_b": investment_plans["plan_b"]["forecast"], + }, + "tactical_operations": { + "plan_a": _build_tactical_operation(investment_plans["plan_a"]), + "plan_b": _build_tactical_operation(investment_plans["plan_b"]), + }, + "guidelines": guidelines, + "meta": { + "budget_usd": round(budget_usd, 2), + "experience_level": resolved_level, + "radar_data": radar_data, + "market_signal": market_signal, + "analysis_mode": analysis_mode, + "target_asset": target_asset, + "forecast_horizon_days": horizon, + "risk_profile": resolved_risk_profile, + "risk_score": resolved_risk_score, + "language": resolved_language, + "target_asset_degraded": investment_plans.get("target_asset_degraded", False), + "allocation_source": investment_plans.get("allocation_source", "manual_risk_profile"), + }, + "allocation": portfolio_allocation, + } + except Exception as exc: # noqa: BLE001 — blindaje total del pipeline (FASE 3) + traceback.print_exc() + print(f"🔥 ERROR CRÍTICO EN QUANTI (generate_quanti_strategy): {exc}") + return { + "status": "error", + "error": str(exc), + "symbol": None, + "market_context": None, + "amounts": None, + "chart_data": None, + "tactical_operations": None, + "guidelines": [], + "meta": { + "budget_usd": round(budget_usd, 2), + "analysis_mode": analysis_mode, + "target_asset": target_asset, + "forecast_horizon_days": forecast_horizon_days, + "risk_profile": risk_profile, + "risk_score": risk_score, + "language": _normalize_language(language), + }, + "allocation": portfolio_allocation, + } + +# === APPEND AL FINAL DE services/quanti_engine.py (después de generate_quanti_strategy) === +# No requiere imports nuevos: reutiliza json, _groq_client, GROQ_MODEL_NAME, +# GROQ_MAX_OUTPUT_TOKENS y _sanitize_llm_output ya definidos arriba. + +# --------------------------------------------------------------------------- +# Quanti Chat — completion genérica multi-turno para el módulo conversacional +# (api/quanti_chat.py). Mismo cliente Groq que el resto del motor, pero sin +# atar el prompt a la estructura Plan A / Plan B. +# --------------------------------------------------------------------------- + +QUANTI_CHAT_FALLBACK = ( + "El motor de inferencia de Quanti está fuera de línea en este momento. " + "Reintenta en unos segundos." +) + +# Alias público — api/quanti_chat.py sanitiza el texto acumulado del stream +# antes de persistirlo, reusando exactamente la misma lógica de saneo que +# el resto del motor (sin duplicar la regla de negocio en dos archivos). +sanitize_llm_output = _sanitize_llm_output + + +async def stream_quanti_chat_completion(messages: list[dict]) -> AsyncGenerator[str, None]: + """ + Streaming multi-turno para el módulo conversacional (api/quanti_chat.py). + Recibe `messages` ya armado por el caller (system prompt + historial + recortado + turno actual, con [CONTEXTO WEB EN TIEMPO REAL] ya inyectado + si aplicó — ver build_realtime_web_context más abajo). Vía Groq LPU (ver + _llm_chat_stream); si Groq no responde al connect, la excepción sube tal + cual — el caller (router) decide cómo degradar vía is_llm_connection_failure. + """ + async for delta in _llm_chat_stream(_inject_core_directives(messages)): + yield delta + + +async def generate_quanti_chat_completion(messages: list[dict]) -> str: + """ + Variante NO-streaming, mantenida para callers que necesiten un string + de una sola vez (ej. tareas batch/cron, no el endpoint de chat en vivo + — ese usa stream_quanti_chat_completion + StreamingResponse). Mismo + cliente Groq y misma distinción de Circuit Breaker que el resto del motor. + """ + try: + content = await _llm_chat_completion(_inject_core_directives(messages)) + except Exception as exc: # noqa: BLE001 + if _is_connection_failure(exc): + print(f"⚠️ Circuit Breaker activado — Groq LPU inalcanzable (Quanti Chat): {_describe_llm_failure(exc)}") + else: + print(f"⚠️ Fallo no-conexión en Quanti Chat LLM (cuota/auth/5xx de Groq): {_describe_llm_failure(exc)}") + return QUANTI_CHAT_FALLBACK + + sanitized = _sanitize_llm_output(content) + return sanitized[0] if sanitized else QUANTI_CHAT_FALLBACK + + +# --------------------------------------------------------------------------- +# Búsqueda web autónoma y GRATUITA (sin API keys de pago) vía DDGS +# (metabuscador que corrió DuckDuckGo/Bing/etc., ex-paquete "duckduckgo-search", +# renombrado a "ddgs"). Instalación: +# pip install ddgs +# El paquete viejo (`duckduckgo_search`) sigue funcionando como shim con +# warning de deprecación — se intenta `ddgs` primero y se cae a ese shim +# solo si el entorno todavía no migró. +# --------------------------------------------------------------------------- + +try: + from ddgs import DDGS +except ImportError: # entorno viejo, no migrado — mismo símbolo, otro paquete + try: + from duckduckgo_search import DDGS # type: ignore[no-redef] + except ImportError: + DDGS = None # type: ignore[assignment,misc] # se valida en runtime, ver search_financial_web + +DDG_REGION = os.getenv("DDG_REGION", "es-es") +# Estrategia de compresión de tokens (FASE 2): tope ESTRICTO de 3 a 4 +# snippets por búsqueda — nunca más, sin importar lo que pida el .env. Cada +# snippet de más es cuota de entrada del Free Tier de Groq gastada en RAG +# en vez de en la propia respuesta de Quanti (GROQ_MAX_OUTPUT_TOKENS). +DDG_MAX_RESULTS = max(3, min(4, int(os.getenv("DDG_MAX_RESULTS", "4")))) +DDG_SAFESEARCH = os.getenv("DDG_SAFESEARCH", "moderate") + +# Tope duro de caracteres por snippet YA sanitizado — un snippet crudo de +# DDG puede traer varios párrafos; para RAG solo necesitamos la oración +# densa con el dato, no el artículo entero. Ver _sanitize_web_snippet. +DDG_SNIPPET_CHAR_LIMIT = int(os.getenv("DDG_SNIPPET_CHAR_LIMIT", "280")) + +# Señales de que el mensaje del usuario pide un dato que el LLM NO puede +# tener por su cuenta (conocimiento congelado a la fecha de entrenamiento) +# — precios, noticias, tasas, cualquier cosa con componente "ahora mismo". +# Heurística deliberadamente simple y barata (sin llamar a otro LLM para +# clasificar intención): un match alcanza para gatillar la búsqueda: en el +# peor caso se gasta una búsqueda de más, nunca se pierde una real. +_REALTIME_QUERY_KEYWORDS = ( + "hoy", "ahora", "en vivo", "actual", "actualidad", "última hora", + "ultima hora", "reciente", "recientes", "esta semana", "este mes", + "precio de", "cotización", "cotizacion", "noticia", "noticias", + "fed", "powell", "tasa de interés", "tasa de interes", "inflación", + "inflacion", "mercado hoy", "bolsa hoy", "ipc", "nfp", "earnings", +) + + +def _needs_realtime_context(user_message: str) -> bool: + lowered = user_message.lower() + return any(kw in lowered for kw in _REALTIME_QUERY_KEYWORDS) + + +_HTML_TAG_RE = re.compile(r"<[^>]+>") +_WHITESPACE_RE = re.compile(r"\s+") +_REPEATED_PUNCT_RE = re.compile(r"([.,;:!?\-_=*#~])\1{1,}") + + +def _sanitize_web_snippet(raw: str, char_limit: int = DDG_SNIPPET_CHAR_LIMIT) -> str: + """ + Purificación quirúrgica de un snippet crudo de DDG ANTES de que entre + al prompt del LLM (FASE 2 — optimización extrema de tokens): + 1. Elimina cualquier etiqueta HTML residual (``, ``, etc.) + que a veces viaja en el `body` de un resultado de búsqueda. + 2. Colapsa espacios/tabs/saltos de línea múltiples a uno solo. + 3. Colapsa caracteres especiales repetidos ("----", "....", "***") + a una sola ocurrencia — ruido típico de scraping que no aporta + información y solo consume tokens. + 4. Trunca a `char_limit` caracteres (corte en el último espacio antes + del límite, para no partir una palabra a la mitad), agregando + puntos suspensivos si hubo corte. + Nunca lanza excepción — un snippet imposible de limpiar simplemente + vuelve vacío, y el caller ya filtra vacíos. + """ + text = _HTML_TAG_RE.sub(" ", raw or "") + text = _REPEATED_PUNCT_RE.sub(r"\1", text) + text = _WHITESPACE_RE.sub(" ", text).strip() + if len(text) > char_limit: + cut = text.rfind(" ", 0, char_limit) + cut = cut if cut > 0 else char_limit + text = text[:cut].rstrip(",.;: ") + "…" + return text + + +async def search_financial_web(query: str, max_results: int = DDG_MAX_RESULTS) -> list[dict]: + """ + Top N resultados recientes de DDGS para `query` — N acotado SIEMPRE a + DDG_MAX_RESULTS (3-4, hard cap, ver arriba), sin importar lo que pida + el caller. `DDGS().text()` es SÍNCRONO y bloqueante (requests por + debajo) — se corre en threadpool vía asyncio.to_thread para no trabar + el event loop de FastAPI mientras Keras/el resto del motor sigue + respondiendo otras requests. + + Nunca propaga excepción: si DDG falla, ratelimitea, o el paquete no + está instalado, degrada a lista vacía — el caller sigue sin contexto + web en vez de tirar abajo el turno de chat completo por una búsqueda + que es, por diseño, un "nice to have" y no la fuente de verdad numérica + del motor (esa sigue siendo Keras, ver docstring del módulo). + + Cada snippet devuelto ya pasó por _sanitize_web_snippet — llega denso, + sin HTML, sin espacios/puntuación redundante, y acotado en longitud: + la cuota de entrada de Groq se gasta en señal, no en basura de scraping. + """ + if DDGS is None: + print("⚠️ search_financial_web: DDGS no instalado — `pip install ddgs`. Saltando búsqueda web.") + return [] + + capped_results = max(3, min(4, max_results)) + + def _run() -> list[dict]: + with DDGS() as ddgs: + return list( + ddgs.text( + query, + region=DDG_REGION, + safesearch=DDG_SAFESEARCH, + max_results=capped_results, + ) + ) + + try: + raw_results = await asyncio.to_thread(_run) + except Exception as exc: # noqa: BLE001 + print(f"⚠️ search_financial_web: fallo en búsqueda DDG para {query!r}: {exc}") + return [] + + cleaned = [ + { + "title": _sanitize_web_snippet(r.get("title") or "", char_limit=120), + "snippet": _sanitize_web_snippet(r.get("body") or ""), + "url": (r.get("href") or r.get("url") or "").strip(), + } + for r in raw_results + if r.get("body") + ] + return [r for r in cleaned if r["snippet"]] + + +async def build_realtime_web_context(user_message: str) -> str: + """ + Punto de entrada único para api/quanti_chat.py: si `user_message` pide + un dato en tiempo real (ver _needs_realtime_context), busca en DDG y + devuelve el bloque `[CONTEXTO WEB EN TIEMPO REAL]` YA formateado, listo + para concatenar al mensaje del usuario antes de mandarlo al LLM — mismo + patrón que `CONTEXTO DE ARCHIVO` en api/quanti_chat.py (_summarize_dataframe). + Devuelve "" si no aplica o si la búsqueda no trajo nada, así el caller + puede simplemente hacer `prompt + file_context + web_context` sin + chequear nada. + """ + if not _needs_realtime_context(user_message): + return "" + + results = await search_financial_web(user_message) + if not results: + return "" + + lines = [f"- {r['title']}: {r['snippet']} (Fuente: {r['url']})" for r in results] + return ( + "\n\n[CONTEXTO WEB EN TIEMPO REAL] Datos obtenidos ahora mismo vía " + "búsqueda web — es tu ÚNICA fuente sobre eventos/precios actuales, " + "nunca inventes cifras que no estén acá:\n" + "\n".join(lines) + ) + + +# === Integración en api/quanti_chat.py (no requiere tocar CHAT_SYSTEM_PROMPT, +# la instrucción de "única fuente" ya viaja adentro del bloque) === +# +# from services.quanti_engine import build_realtime_web_context +# ... +# web_context = await build_realtime_web_context(prompt) +# llm_messages.append({"role": "user", "content": prompt + file_context + web_context}) + +# === APPEND AL FINAL DE services/quanti_engine.py (Quanti Support — Nivel 1/2) === +# No requiere imports nuevos: reutiliza CORE_DIRECTIVES, _normalize_language, +# _llm_chat_completion, _sanitize_llm_output, _is_connection_failure, +# _describe_llm_failure y QUANTI_CHAT_FALLBACK ya definidos arriba. + +# --------------------------------------------------------------------------- +# Quanti Support — persona Tier-1 para el widget flotante de la Landing. +# Respuestas cortas, ultra empáticas, cero jerga técnica. Si detecta +# frustración, incomprensión, un tema legal/técnico complejo, o un pedido +# explícito de hablar con un humano, corta el análisis y responde +# ÚNICAMENTE con SUPPORT_ESCALATION_MARKER — api/support.py intercepta ese +# marcador antes de reenviar nada como texto plano al frontend. +# --------------------------------------------------------------------------- + +SUPPORT_ESCALATION_MARKER = "[ESCALATE_TICKET]" + +_SUPPORT_SYSTEM_PROMPTS = { + "en": ( + "You are Quanti Support, the Tier-1 assistant of KodaQuant. Your " + "persona is ultra-sophisticated yet deeply empathetic — a brilliant " + "concierge, never a robotic FAQ bot. Keep every reply SHORT and " + "CONCISE (2-3 sentences max), in plain, jargon-free language a " + "complete non-technical user can follow instantly.\n\n" + "ESCALATION RULE (absolute priority): the moment you detect the " + "user is frustrated, still confused despite your explanation, " + "describing a complex legal or technical issue, or explicitly " + "asking to speak with a human — STOP analyzing and reply with " + f"NOTHING ELSE but the exact string {SUPPORT_ESCALATION_MARKER}. " + "No punctuation, no extra words, no apology around it." + ), + "es": ( + "Eres Quanti Support, el asistente Tier-1 de KodaQuant. Tu persona " + "es ultra sofisticada pero profundamente empática — un concierge " + "brillante, nunca un bot de FAQ robótico. Cada respuesta debe ser " + "CORTA y CONCISA (máximo 2-3 oraciones), en lenguaje simple y sin " + "jerga, entendible al instante por un usuario totalmente no técnico.\n\n" + "REGLA DE ESCALACIÓN (prioridad absoluta): en el momento en que " + "detectes que el usuario está frustrado, sigue sin comprender pese " + "a tu explicación, describe un problema legal o técnico complejo, " + "o pide explícitamente hablar con un humano — DETÉN el análisis y " + f"responde ÚNICAMENTE con la cadena exacta {SUPPORT_ESCALATION_MARKER}. " + "Sin puntuación, sin palabras extra, sin disculpas alrededor." + ), +} + + +def _build_support_prompt(language: str | None = None) -> str: + """ + System prompt exclusivo de Quanti Support. Antepone CORE_DIRECTIVES + (identidad/idioma) igual que el resto del motor, para que el widget + herede la misma regla de identidad (Karim Suheim Estrada Egure) y el + mismo fallback de idioma que el resto de Quanti. + """ + return CORE_DIRECTIVES + "\n\n" + _SUPPORT_SYSTEM_PROMPTS[_normalize_language(language)] + + +def is_support_escalation(reply: str) -> bool: + """True si Quanti Support cortó el análisis y decidió escalar a un humano.""" + return reply.strip() == SUPPORT_ESCALATION_MARKER + + +async def generate_quanti_support_reply(messages: list[dict], language: str | None = None) -> str: + """ + Completion NO-streaming para el widget de soporte — api/support.py + necesita el string completo de una sola vez para poder comparar contra + SUPPORT_ESCALATION_MARKER antes de decidir qué mandar al frontend. + Antepone _build_support_prompt como ÚNICO system message (ya incluye + CORE_DIRECTIVES) — descarta cualquier system message que el caller + hubiera mandado por error, para que la persona de soporte nunca se + diluya con otro prompt. + """ + support_system = {"role": "system", "content": _build_support_prompt(language)} + payload = [support_system, *[m for m in messages if m.get("role") != "system"]] + + try: + content = await _llm_chat_completion(payload) + except Exception as exc: # noqa: BLE001 + if _is_connection_failure(exc): + print(f"⚠️ Circuit Breaker activado — Groq LPU inalcanzable (Quanti Support): {_describe_llm_failure(exc)}") + else: + print(f"⚠️ Fallo no-conexión en Quanti Support LLM (cuota/auth/5xx de Groq): {_describe_llm_failure(exc)}") + # Nunca dejamos al usuario sin respuesta, y nunca inventamos una + # escalación falsa solo porque Groq cayó. + return QUANTI_CHAT_FALLBACK + + sanitized = _sanitize_llm_output(content) + return sanitized[0] if sanitized else QUANTI_CHAT_FALLBACK \ No newline at end of file diff --git a/services/risk_manager.py b/services/risk_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..eca66ac786310ea7ddc85cf0a089e1692b0cdbdc --- /dev/null +++ b/services/risk_manager.py @@ -0,0 +1,80 @@ +import json +from typing import Union, Dict, Any + + +class RadarDataError(Exception): + """Excepción lanzada cuando radar_data no puede ser interpretado correctamente.""" + pass + + +async def calculate_portfolio(budget_usd: float, radar_data: Union[str, Dict[str, Any]]) -> Dict[str, Any]: + # Escudo de Datos Estricto + if isinstance(radar_data, str): + try: + radar_data = json.loads(radar_data) + except json.JSONDecodeError as e: + raise RadarDataError( + f"radar_data no contiene un JSON válido: {e}" + ) from e + + if not isinstance(radar_data, dict): + raise RadarDataError( + "radar_data debe ser un diccionario o un string JSON serializable a diccionario." + ) + + signal = radar_data.get("signal", "NEUTRAL") + if not isinstance(signal, str): + signal = "NEUTRAL" + signal = signal.strip().upper() + + if budget_usd < 0: + raise ValueError("budget_usd no puede ser negativo.") + + # Lógica de Capital según la señal + if signal == "COMPRA": + riesgo_pct = 0.75 + reserva_pct = 0.25 + mensaje = ( + "Señal de COMPRA detectada. Se prioriza el despliegue de capital " + "hacia posiciones de riesgo para capturar la tendencia alcista, " + "manteniendo una reserva mínima de liquidez táctica." + ) + elif signal == "VENTA": + riesgo_pct = 0.20 + reserva_pct = 0.80 + mensaje = ( + "Señal de VENTA detectada. Se privilegia el resguardo de capital, " + "reduciendo la exposición a riesgo y fortaleciendo la posición de " + "liquidez ante una posible corrección o tendencia bajista." + ) + elif signal == "NEUTRAL": + riesgo_pct = 0.50 + reserva_pct = 0.50 + mensaje = ( + "Señal NEUTRAL. Se mantiene una distribución equilibrada entre " + "riesgo y liquidez a la espera de una confirmación direccional " + "más clara del mercado." + ) + else: + riesgo_pct = 0.35 + reserva_pct = 0.65 + mensaje = ( + f"Señal no reconocida ('{signal}'). Se aplica una postura " + "conservadora por defecto, favoreciendo la reserva de capital " + "hasta obtener una señal clasificable." + ) + + capital_riesgo = round(budget_usd * riesgo_pct, 2) + capital_reserva = round(budget_usd * reserva_pct, 2) + + return { + "capital_inicial_usd": round(budget_usd, 2), + "signal_detectada": signal, + "asignacion": { + "riesgo_usd": capital_riesgo, + "reserva_usd": capital_reserva, + "riesgo_pct": riesgo_pct, + "reserva_pct": reserva_pct, + }, + "mensaje_estrategico": mensaje, + } \ No newline at end of file diff --git a/setup_structure.sh b/setup_structure.sh new file mode 100644 index 0000000000000000000000000000000000000000..60524f63ab9d66bab0c505141b0fb88cceaad51d --- /dev/null +++ b/setup_structure.sh @@ -0,0 +1,4 @@ +#!/bin/bash +mkdir -p api core database ml_engine middlewares payments services +touch api/__init__.py core/__init__.py database/__init__.py ml_engine/__init__.py middlewares/__init__.py payments/__init__.py services/__init__.py +echo "Estructura creada." \ No newline at end of file diff --git a/train_pipeline.py b/train_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..e03c20f44ded8dcf1a7997b45812e8f854de798c --- /dev/null +++ b/train_pipeline.py @@ -0,0 +1,1098 @@ +#!/usr/bin/env python3 +""" +train_pipeline.py — KodaQuant V5 MLOps: Reentrenamiento Incremental por Régimen +================================================================================= +Demonio/cronjob de fine-tuning incremental con validación estricta +"Champion vs. Challenger", **exclusivo para la arquitectura V5** (dos +especialistas independientes por régimen — `equity_specialist` / +`crypto_specialist` — bajo `services/kodaquant_models//`). + +DEPRECACIÓN EXPLÍCITA: esta reescritura abandona por completo el modelo +GLOBAL V3/V4 (`attention_bilstm_global.keras`, 14 features, sin +NEWS_SENTIMENT_SCORE) y su dependencia de `services/quanti_engine.py`. Ese +modelo y ese pipeline de features quedaron huérfanos desde que +`train_kodaquant_v5.py` introdujo el enrutamiento por régimen; este script +ya no los referencia en absoluto. + +DISEÑO — DECISIONES CRÍTICAS +----------------------------- +1. CERO reimplementación paralela del feature engineering NI del proveedor + de datos de mercado. `engineer_asset`, `TECH_COLS`, `N_FEATURES`, + `REGIMES`, `MACRO_TICKERS`, `LOOKBACK`, `_fetch_all_symbols_flat` y la + arquitectura/pérdida (`BahdanauAttention`, `DirectionalGaussianNLL`, + `mu_mae_metric`, `directional_accuracy_metric`) se importan DIRECTAMENTE + desde `train_kodaquant_v5.py` — el mismo módulo que ejecuta el + full-retrain. `engineer_asset` a su vez invoca + `data_pipeline.get_daily_news_sentiment` internamente y + `_fetch_all_symbols_flat` ya resuelve Twelve Data/FRED/Stooq con + normalización tz-naive diaria (`market_data.py`, única fuente de verdad + de proveedores desde V11) — así que las `N_FEATURES` features (LOG_RETURN_1D + + TECH_COLS + MACRO_TICKERS, ver esas constantes en train_kodaquant_v5.py + -- NUNCA hardcodear el conteo acá, esa fue exactamente la causa raíz de + la desalineación auditada en services/quanti_engine.py en 2026-08) + llegan sin reimplementar nada, sin riesgo de "training/fine-tuning + skew" y sin una segunda ruta de descarga (yfinance) desincronizada de la + que ya usa `train_kodaquant_v5.py` en producción. + +2. Los `feature_scalers` / `target_scalers` de cada especialista NUNCA se + re-ajustan (`.fit`) aquí — solo `.transform()` / `.inverse_transform()`. + El fine-tuning es incremental sobre el mismo espacio de escalado con el + que `run_regime_pipeline()` entrenó el especialista. Si el esquema de + features cambia, el retrain completo sigue siendo responsabilidad de + `train_kodaquant_v5.py`, no de este script. + +3. DOS modelos INDEPENDIENTES. El ciclo drift -> fine-tune -> promote corre + de forma AISLADA por régimen: jamás se mezclan datasets, scalers, + embeddings de asset_id ni estado `baseline_mae` entre `equity_specialist` + y `crypto_specialist`. Cada régimen tiene su propio `mlops_state.json` y + su propio directorio de backups bajo su carpeta en `kodaquant_models/`. + +4. RUTEO DINÁMICO equity <-> crypto (Requerimiento 3). `_resolve_regime()` + determina a qué especialista pertenece un ticker: primero contra el + mapeo real ya entrenado (`REGIMES`), con fallback heurístico por sufijo + para tickers que aún no pasaron por un full retrain. Un ticker fuera del + `asset_to_id` ya entrenado del especialista NO puede fine-tunearse (el + embedding no tiene fila para él) — se omite con un aviso explícito + pidiendo un full retrain. + +5. Ningún workaround de "dropout congelado" (`_make_trainable_graph` de la + versión V3/V4). Ese parche existía únicamente en el *bridge* de + inferencia de `quanti_engine.py` (MC-Dropout con `training=True` + horneado para simulación de paths) — el artefacto crudo `model_v5.keras` + que guarda `run_regime_pipeline()` NO tiene ese bridge, así que + `Dropout` se comporta de forma estándar: activo en `.fit()`, apagado en + `.evaluate()`/`.predict()`, sin reconstrucción de grafo necesaria. + +NUEVO EN V14.1 — SINCRONIZACIÓN CON `train_kodaquant_v5.py` (V6+) Y +ELIMINACIÓN DE YFINANCE (auditoría de compatibilidad al recibir los +módulos reales `market_data.py`/`data_pipeline.py`, antes ausentes): + a) `train_kodaquant_v5.py` migró, desde su V6, la cabeza de salida del + modelo de un único escalar a un head dual `Dense(2)` = [mu, + log_var], entrenado con `DirectionalGaussianNLL` (no + `DirectionalHuberLoss`, que el propio módulo deja "sin uso, como + referencia histórica"). Esta versión de `train_pipeline.py` + compilaba el Challenger con `DirectionalHuberLoss` sobre un modelo + de 2 columnas de salida (mismatch de forma silencioso: Huber + elemento-a-elemento entre `y_true` (N,1) y `y_pred` (N,2) nunca + levanta un error claro, corrompe el gradiente) y extraía + predicciones con `.reshape(-1, 1)` sobre un array (N, 2) -- eso NO + selecciona la columna `mu`, INTERCALA mu y log_var en una sola + columna de longitud 2N. Fix: import de `DirectionalGaussianNLL`/ + `mu_mae_metric` (idénticos hiperparámetros que produce el + especialista Champion) y `y_pred[:, 0:1]` explícito en cada punto + donde se extraía `mu` de una predicción cruda. + b) `_download_regime_history` llamaba `yf.download` directo -- la + fuente que TODO el resto del sistema retiró explícitamente + (`market_data.py`: "Reemplaza por completo yfinance ... bloqueos + recurrentes de Yahoo Finance / errores Proxy CONNECT aborted en + producción"; `data_pipeline.py`: "yfinance retirado por completo"). + Además hacía un `.ffill().dropna(how="all")` CIEGO sobre el frame + combinado ANTES de pasarlo a `engineer_asset` -- exactamente el + patrón que la auditoría V13 de `train_kodaquant_v5.py` identificó + como la causa raíz de aniquilar ~2/7 de un dataset 24/7 (cripto) + al tratar NaN de fin de semana en columnas macro igual que un NaN + real del propio activo. Fix: reemplazado por + `_fetch_all_symbols_flat` (importado de `train_kodaquant_v5.py`, + misma normalización tz-naive + outer join que usa el full-retrain), + SIN ffill/dropna adicional -- ese trabajo es responsabilidad + exclusiva de `engineer_asset`, que ya lo hace bien. + c) Universo cripto reexpresado en formato estándar `BASE/QUOTE` + (`BTC/USD`, ver V12 de `train_kodaquant_v5.py`) -- el heurístico de + ruteo dinámico (`_CRYPTO_SUFFIXES`) y el `--tickers` de CLI seguían + documentados/testeados contra el viejo sufijo `-USD` de yfinance. + Se añade `_normalize_ticker_symbol` (acepta ambas notaciones en el + input del usuario, normaliza a `/` antes de rutear) para no romper + silenciosamente el ruteo si alguien pasa `BTC-USD` por costumbre. + +Requisitos: mismos que `train_kodaquant_v5.py` (`keras`, `tensorflow`, +`pandas`, `numpy`, `scikit-learn`, `nltk`/`requests` para `data_pipeline`, +`requests` para `market_data`) más `scipy` para el test estadístico +Champion vs. Challenger. Debe vivir en el mismo directorio que +`train_kodaquant_v5.py`, `market_data.py` y `data_pipeline.py`. + +Uso: + python train_pipeline.py # ambos regímenes, respeta drift + python train_pipeline.py --force-retrain # fuerza fine-tuning en ambos regímenes + python train_pipeline.py --regimes crypto_specialist --months 12 --lr 5e-6 + python train_pipeline.py --tickers TSLA,BTC/USD # rutea dinámicamente y corre solo esos especialistas +""" + +from __future__ import annotations + +import argparse +import gc +import json +import logging +import os +import pickle +import shutil +import sys +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import keras +import numpy as np +import pandas as pd +from sklearn.metrics import mean_absolute_error, mean_squared_error + +try: + from scipy import stats +except ImportError as exc: # noqa: BLE001 + raise ImportError( + "train_pipeline.py requiere scipy para el test estadístico pareado " + "Champion vs. Challenger (ttest_rel). Instala con: pip install scipy" + ) from exc + +# --------------------------------------------------------------------------- +# Bootstrap de path — hace visible `train_kodaquant_v5.py` / `data_pipeline.py` +# sin importar desde qué cwd dispare el cron. +# --------------------------------------------------------------------------- +_THIS_DIR = Path(__file__).resolve().parent +if str(_THIS_DIR) not in sys.path: + sys.path.insert(0, str(_THIS_DIR)) + +try: + from train_kodaquant_v5 import ( # noqa: E402 + BahdanauAttention, + DirectionalGaussianNLL, + GAMMA_MAX, + GAUSSIAN_NLL_BETA, + GRAD_CLIPNORM, + LOG_VAR_BARRIER_LAMBDA, + LOG_VAR_L2_LAMBDA, + LOG_VAR_MAX, + LOG_VAR_MIN, + MACRO_TICKERS, + MODELS_ROOT, + N_FEATURES, + REGIMES, + TECH_COLS, + _fetch_all_symbols_flat, + directional_accuracy_metric, + engineer_asset, + mu_mae_metric, + ) +except ImportError as exc: # noqa: BLE001 + raise ImportError( + "No se pudo importar train_kodaquant_v5.py. train_pipeline.py debe " + "vivir en el mismo directorio que train_kodaquant_v5.py, " + "market_data.py y data_pipeline.py, con Keras 3 disponible ahí. " + f"Detalle: {exc!r}" + ) from exc + +# Requerimiento 1 — integración 100% explícita con el pipeline NLP de +# sentimiento. No se llama directamente en este módulo (ya la invoca +# `engineer_asset` internamente), pero el import se deja EXPLÍCITO y a nivel +# de módulo para que un `data_pipeline.py` roto (nltk/VADER/Finnhub faltante, +# etc.) falle aquí, de inmediato, en vez de a mitad de una descarga +# multi-proveedor (Twelve Data/FRED/Stooq) de varios minutos dentro del +# ciclo de fine-tuning. +try: + from data_pipeline import get_daily_news_sentiment # noqa: F401,E402 +except ImportError as exc: # noqa: BLE001 + raise ImportError( + "No se pudo importar data_pipeline.py (requerido por engineer_asset " + f"para NEWS_SENTIMENT_SCORE). Detalle: {exc!r}" + ) from exc + + +# --------------------------------------------------------------------------- +# Ruteo dinámico de régimen (Requerimiento 3) +# --------------------------------------------------------------------------- +# AUDITORÍA RESCATE 2026-08 — BUG DE RUTEO ENCONTRADO: `REGIMES` (importado +# de train_kodaquant_v5.py) trae los tickers cripto en notación con GUION +# ("BTC-USD"/"ETH-USD", ver REGIMES en ese archivo), pero este diccionario +# se construía SIN normalizar, mientras `_resolve_regime` sí normaliza el +# ticker de INPUT a notación "/" antes de buscarlo acá -- "BTC-USD" nunca +# hacía match contra una key sin normalizar. Hoy "funcionaba" por pura +# casualidad (el fallback heurístico de `_resolve_regime`, más abajo, +# también reconoce el patrón BASE/QUOTE), no por diseño -- normalizar AMBOS +# lados con la MISMA función (`_normalize_ticker_symbol`, definida abajo) +# lo vuelve determinista y correcto para cualquier notación futura. +# +# V14.1 — universo cripto real vive en notación "BASE/QUOTE" (`BTC/USD`, ver +# V12 de train_kodaquant_v5.py: el guion `BTC-USD` era un artefacto propio +# del ticker de yfinance, ya retirado). `_CRYPTO_QUOTE_SUFFIXES` alimenta +# tanto el heurístico de fallback (activo nuevo, aún sin full retrain) como +# `_normalize_ticker_symbol` (abajo), que acepta la notación legacy con +# guion en el input del usuario/CLI y la reescribe a `/` antes de rutear. +_CRYPTO_QUOTE_SUFFIXES = ("USD", "USDT", "USDC", "BTC", "ETH") + + +def _normalize_ticker_symbol(ticker: str) -> str: + """ + `BTC-USD`/`btc-usd` (notación legacy de yfinance, aún común en input + humano/scripts viejos) -> `BTC/USD` (notación real del universo + entrenado). No-op para cualquier ticker que ya venga en formato + estándar (equity plano o cripto con `/`) o que no calce el patrón + `BASE-QUOTE` de un par cripto reconocido. + """ + t = ticker.strip().upper() + if "-" in t and "/" not in t: + base, _, quote = t.partition("-") + if quote in _CRYPTO_QUOTE_SUFFIXES: + return f"{base}/{quote}" + return t + + +# Construido DESPUÉS de `_normalize_ticker_symbol` y normalizando cada +# ticker de `REGIMES` con la MISMA función que usa `_resolve_regime` sobre +# el input -- ver auditoría arriba. Antes: `REGIMES["crypto_specialist"]` +# traía "BTC-USD" sin normalizar como key, mientras `_resolve_regime` +# consultaba con "BTC/USD" (ya normalizado) -- cero coincidencia posible. +TICKER_TO_REGIME: dict[str, str] = { + _normalize_ticker_symbol(ticker): regime_name + for regime_name, cfg in REGIMES.items() + for ticker in cfg["tickers"] +} + + +def _resolve_regime(ticker: str) -> str: + """ + Decide a qué especialista V5 pertenece un ticker. Prioriza el universo + REAL ya entrenado (`REGIMES`); si el ticker es nuevo (aún no pasó por un + full retrain de `train_kodaquant_v5.py`), cae a una heurística de sufijo + para pares cripto (`BTC/USD`, `SOL/USDT`, ...; también acepta el guion + legacy vía `_normalize_ticker_symbol`). + """ + ticker_norm = _normalize_ticker_symbol(ticker) + if ticker_norm in TICKER_TO_REGIME: + return TICKER_TO_REGIME[ticker_norm] + if "/" in ticker_norm and ticker_norm.split("/")[-1] in _CRYPTO_QUOTE_SUFFIXES \ + and "crypto_specialist" in REGIMES: + return "crypto_specialist" + return "equity_specialist" if "equity_specialist" in REGIMES else next(iter(REGIMES)) + + +# --------------------------------------------------------------------------- +# Configuración +# --------------------------------------------------------------------------- + +@dataclass(frozen=True) +class MLOpsConfig: + """Parámetros del ciclo MLOps V5. Todos con default institucional razonable.""" + + log_dir: Path = MODELS_ROOT / "logs" + + # Data ingestion + training_history_months: int = 24 + + # Drift detection ("el vigilante") + holdout_days: int = 15 + drift_relative_threshold: float = 0.05 # 5% de desviación media vs. baseline + drift_hard_mae_limit: float | None = None # límite duro opcional, escala log-return + + # Incremental training ("el challenger") + validation_split_days: int = 15 + finetune_learning_rate: float = 1e-5 + finetune_max_epochs: int = 50 + finetune_batch_size: int = 64 + early_stopping_patience: int = 5 + + # Champion vs. Challenger (A/B matemático) + promotion_min_relative_improvement: float = 0.0 # exige mejora estrictamente >0 además de p-value + promotion_p_value_threshold: float = 0.05 + + random_seed: int = 42 + + +# --------------------------------------------------------------------------- +# Logging institucional — [TIMESTAMP] - [LEVEL] - [MODULE] - Message +# --------------------------------------------------------------------------- + +def _configure_logging(log_dir: Path) -> logging.Logger: + log_dir.mkdir(parents=True, exist_ok=True) + logger = logging.getLogger("kodaquant.mlops_v5") + logger.setLevel(logging.INFO) + logger.propagate = False + + if not logger.handlers: + fmt = logging.Formatter( + fmt="[%(asctime)s] - [%(levelname)s] - [%(module)s] - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + file_handler = logging.FileHandler(log_dir / "mlops_pipeline_v5.log", encoding="utf-8") + file_handler.setFormatter(fmt) + logger.addHandler(file_handler) + + stream_handler = logging.StreamHandler(sys.stdout) + stream_handler.setFormatter(fmt) + logger.addHandler(stream_handler) + + return logger + + +# --------------------------------------------------------------------------- +# KodaQuantV5MLOps +# --------------------------------------------------------------------------- + +class KodaQuantV5MLOps: + """ + Orquestador del ciclo de vida de los especialistas V5: ingestión (OHLCV + + NEWS_SENTIMENT_SCORE vía `data_pipeline`), detección de drift, fine-tuning + incremental, comparación estadística Champion vs. Challenger y promoción + atómica — todo AISLADO por régimen (`equity_specialist`/`crypto_specialist`). + """ + + def __init__(self, config: MLOpsConfig | None = None) -> None: + self.config = config or MLOpsConfig() + self.logger = _configure_logging(self.config.log_dir) + np.random.seed(self.config.random_seed) + + # ------------------------------------------------------------------ # + # Estado persistente (baseline de MAE entre corridas) — POR RÉGIMEN + # ------------------------------------------------------------------ # + + def _state_path(self, regime_name: str) -> Path: + return MODELS_ROOT / regime_name / "mlops_state.json" + + def _load_state(self, regime_name: str) -> dict[str, Any]: + state_path = self._state_path(regime_name) + if state_path.exists(): + try: + with open(state_path, "r", encoding="utf-8") as fh: + return json.load(fh) + except (json.JSONDecodeError, OSError) as exc: + self.logger.warning( + "[%s] No se pudo leer %s (%s) — se reinicia el estado.", + regime_name, state_path, exc, + ) + return {"baseline_mae": {}, "last_run": None, "history": []} + + def _save_state(self, regime_name: str, state: dict[str, Any]) -> None: + state_path = self._state_path(regime_name) + state_path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = state_path.with_suffix(".tmp.json") + with open(tmp_path, "w", encoding="utf-8") as fh: + json.dump(state, fh, indent=2, ensure_ascii=False) + os.replace(tmp_path, state_path) + + # ------------------------------------------------------------------ # + # Carga de artefactos de producción del especialista V5 — POR RÉGIMEN + # ------------------------------------------------------------------ # + + def _load_scalers(self, regime_name: str) -> dict[str, Any]: + scalers_path = MODELS_ROOT / regime_name / "scalers_dict.pkl" + if not scalers_path.exists(): + raise FileNotFoundError( + f"No se encontró scalers_dict.pkl para '{regime_name}' en {scalers_path}. " + "Ejecuta primero train_kodaquant_v5.py (full retrain) para generar el especialista." + ) + with open(scalers_path, "rb") as fh: + scalers = pickle.load(fh) + + # Validación defensiva V5 (mismo espíritu que quanti_engine._get_scalers + # en V3): si el bundle viene de un TECH_COLS distinto al vigente, el + # feature_scaler.transform() desplazaría cada columna EN SILENCIO. + saved_tech_cols = scalers.get("tech_cols") + if saved_tech_cols is not None and list(saved_tech_cols) != TECH_COLS: + raise ValueError( + f"[{regime_name}] Desalineación de TECH_COLS: scalers_dict.pkl tiene " + f"{list(saved_tech_cols)} pero train_kodaquant_v5.py define {TECH_COLS} " + "vigente. Regenera el especialista con un full retrain antes de fine-tunear." + ) + return scalers + + def _load_champion(self, regime_name: str): + model_path = MODELS_ROOT / regime_name / "model_v5.keras" + if not model_path.exists(): + raise FileNotFoundError( + f"No se encontró el modelo Champion V5 de '{regime_name}' en {model_path}. " + "Ejecuta primero train_kodaquant_v5.py." + ) + return keras.models.load_model( + str(model_path), + custom_objects={ + "BahdanauAttention": BahdanauAttention, + "DirectionalGaussianNLL": DirectionalGaussianNLL, + "mu_mae_metric": mu_mae_metric, + "directional_accuracy_metric": directional_accuracy_metric, + }, + compile=False, + ) + + # ------------------------------------------------------------------ # + # 1. DATA INGESTION & FEATURE ENGINEERING — reuso 100% de V5 + # ------------------------------------------------------------------ # + + def _download_regime_history( + self, tickers: list[str], macro_tickers: list[str], months: int + ) -> pd.DataFrame: + """ + Descarga OHLCV fresca (SIN cache local en parquet — a diferencia de + `download_all` de train_kodaquant_v5.py, un ciclo incremental + necesita el dato del día, nunca un artefacto potencialmente viejo) + para todos los tickers del régimen + macro factores. + + V14.1 — reemplaza `yf.download` (yfinance, retirado en TODO el + resto del sistema por bloqueos/inestabilidad recurrentes, ver + `market_data.py`) por `_fetch_all_symbols_flat`, la MISMA función + que usa `train_kodaquant_v5.py` para el full retrain: cascada + Twelve Data -> FRED -> Stooq, con normalización de índice tz-naive + diaria aplicada a CADA pieza ANTES del outer join (`market_data.py` + + `_normalize_daily_index`, fix V13 — evita la duplicación + tz-aware/tz-naive de entradas por día calendario que corrompía + silenciosamente el dataset de `crypto_specialist`). + + Deliberadamente SIN ffill/dropna acá: ese trabajo es responsabilidad + exclusiva de `engineer_asset` (ffill(limit=4) SOLO sobre columnas + macro + dropna sobre el OHLCV propio del activo, fix V13) — un + `.ffill().dropna()` ciego aplicado ACÁ, antes de `engineer_asset`, + reintroduciría exactamente el bug que esa auditoría corrigió + (aniquilar filas de fin de semana de un activo 24/7 al tratarlas + igual que un NaN real). + """ + period = f"{max(1, int(months))}mo" # _period_to_sessions ya entiende el sufijo "mo" + flat = _fetch_all_symbols_flat(tickers, macro_tickers, period) + + required = {f"{t}_{f}" for t in tickers for f in ("Close", "High", "Low", "Volume")} + required |= {f"{m}_Close" for m in macro_tickers} + missing = required - set(flat.columns) + if missing: + raise RuntimeError( + f"Faltan columnas tras la descarga multi-proveedor (Twelve Data/FRED/Stooq): " + f"{sorted(missing)} -- ver logs de _fetch_all_symbols_flat para el detalle " + f"por símbolo (un ticker que falle en TODOS los proveedores se omite, no aborta)." + ) + return flat + + def _build_windows_existing_scalers( + self, + df: pd.DataFrame, + ticker: str, + lookback: int, + feature_scaler, + target_scaler, + asset_id: int, + feature_cols: list[str], + ) -> tuple[np.ndarray, np.ndarray, np.ndarray, pd.DatetimeIndex]: + """ + Ventanas 3D `(samples, lookback, N_FEATURES)` — misma indexación + EXACTA que `build_asset_dataset` de train_kodaquant_v5.py (ventana + `[t-lookback:t]` -> target `log_returns[t-1]`, fecha `df.index[t]`), + pero aplicando SOLO `.transform()` sobre los scalers ya fit por el + último full retrain — jamás se re-ajustan aquí. + """ + # V6: `engineer_asset()` ya no expone "PRICE" (nivel absoluto) — el + # bookkeeping de precio crudo vive en RAW_CLOSE (excluida de + # `feature_cols`/del tensor, ver train_kodaquant_v5.py). Usar la + # columna vieja aquí desalinearía el target de log-return en + # silencio (KeyError en el mejor caso, ya que "PRICE" no existe más). + prices = df["RAW_CLOSE"].values + features = df[feature_cols].values + log_returns = np.diff(np.log(prices)) + features_scaled = feature_scaler.transform(features) + + n = len(df) + X, y_raw, dates = [], [], [] + for t in range(lookback, n): + X.append(features_scaled[t - lookback: t]) + y_raw.append(log_returns[t - 1]) + dates.append(df.index[t]) + + if not X: + empty = np.empty((0, lookback, len(feature_cols)), dtype=np.float32) + return empty, np.empty((0, 1), dtype=np.float32), np.empty((0,), dtype=np.int32), pd.DatetimeIndex([]) + + X = np.array(X, dtype=np.float32) + assert X.shape[-1] == N_FEATURES, ( + f"[{ticker}] Desalineación de features: la ventana tiene {X.shape[-1]} " + f"columnas pero N_FEATURES={N_FEATURES} (TECH_COLS={TECH_COLS})." + ) + + y_raw = np.array(y_raw, dtype=np.float32).reshape(-1, 1) + y_scaled = target_scaler.transform(y_raw).astype(np.float32) + asset_ids = np.full((len(X),), asset_id, dtype=np.int32) + return X, y_scaled, asset_ids, pd.DatetimeIndex(dates) + + def _prepare_ticker_dataset( + self, + all_market_data: pd.DataFrame, + ticker: str, + macro_tickers: list[str], + lookback: int, + feature_scaler, + target_scaler, + asset_id: int, + ): + """Bit a bit `engineer_asset()` de train_kodaquant_v5.py (incl. NEWS_SENTIMENT_SCORE).""" + df_asset = engineer_asset(all_market_data, ticker, macro_tickers) + feature_cols = ["LOG_RETURN_1D"] + TECH_COLS + macro_tickers + return self._build_windows_existing_scalers( + df_asset, ticker, lookback, feature_scaler, target_scaler, asset_id, feature_cols + ) + + # ------------------------------------------------------------------ # + # 2. STATISTICAL DRIFT DETECTION — el vigilante, aislado por régimen + # ------------------------------------------------------------------ # + + def evaluate_champion_drift( + self, regime_name: str, champion, scalers: dict[str, Any] + ) -> dict[str, dict[str, float]]: + """ + Evalúa el Champion del régimen sobre los últimos `holdout_days` + reales de CADA ticker de SU universo (`scalers["asset_to_id"]`). + Devuelve MAE/MSE en escala REAL de log-return por ticker, más un + agregado `__global__` ponderado por número de muestras — SOLO de + este régimen, nunca mezclado con el otro especialista. + """ + lookback = scalers["lookback"] + macro_tickers = scalers["macro_tickers"] + asset_to_id = scalers["asset_to_id"] + tickers = list(asset_to_id.keys()) + + drift_check_months = max(3, self.config.training_history_months // 4) + all_market_data = self._download_regime_history(tickers, macro_tickers, drift_check_months) + + results: dict[str, dict[str, float]] = {} + pooled_abs_err: list[np.ndarray] = [] + + for ticker in tickers: + try: + X, y_scaled, asset_ids, _dates = self._prepare_ticker_dataset( + all_market_data, ticker, macro_tickers, lookback, + scalers["feature_scalers"][ticker], scalers["target_scalers"][ticker], + asset_to_id[ticker], + ) + except Exception as exc: # noqa: BLE001 — un ticker caído no debe tumbar el chequeo del régimen + self.logger.warning("[%s] Drift check omitido para %s: %r", regime_name, ticker, exc) + continue + + if len(X) == 0: + continue + if len(X) < self.config.holdout_days: + self.logger.warning( + "[%s] Drift check: %s solo tiene %d ventanas (< holdout_days=%d) — se usa todo lo disponible.", + regime_name, ticker, len(X), self.config.holdout_days, + ) + + X_recent = X[-self.config.holdout_days:] + y_recent_scaled = y_scaled[-self.config.holdout_days:] + asset_recent = asset_ids[-self.config.holdout_days:].reshape(-1, 1) + + y_pred_scaled = np.asarray( + champion.predict([X_recent, asset_recent], verbose=0) + )[:, 0:1] # V14.1: head dual [mu, log_var] -- extrae SOLO mu; .reshape(-1,1) intercalaba ambas columnas + target_scaler = scalers["target_scalers"][ticker] + y_pred_real = target_scaler.inverse_transform(y_pred_scaled).reshape(-1) + y_true_real = target_scaler.inverse_transform(y_recent_scaled).reshape(-1) + + mae = float(mean_absolute_error(y_true_real, y_pred_real)) + mse = float(mean_squared_error(y_true_real, y_pred_real)) + results[ticker] = {"mae": mae, "mse": mse, "n_samples": float(len(y_true_real))} + pooled_abs_err.append(np.abs(y_true_real - y_pred_real)) + + if pooled_abs_err: + pooled = np.concatenate(pooled_abs_err) + results["__global__"] = { + "mae": float(np.mean(pooled)), + "mse": float(np.mean(pooled ** 2)), + "n_samples": float(pooled.size), + } + + return results + + def detect_drift( + self, state: dict[str, Any], drift_metrics: dict[str, dict[str, float]] + ) -> tuple[bool, str]: + """ + No reentrena por defecto. Solo dispara si el MAE global actual del + régimen supera el threshold DINÁMICO (`baseline * (1 + threshold)`) + o el límite duro opcional. Sin baseline previo, se inicializa y NO + se dispara en la primera corrida de ese régimen. + """ + global_metrics = drift_metrics.get("__global__") + if not global_metrics: + return False, "Sin datos suficientes de ningún ticker — se omite el ciclo." + + current_mae = global_metrics["mae"] + baseline_mae = state.get("baseline_mae", {}).get("__global__") + + if baseline_mae is None: + self.logger.info( + "No existe baseline_mae previo — se fija el MAE actual (%.6f) como baseline inicial.", + current_mae, + ) + return False, "baseline_inicializado" + + dynamic_threshold = baseline_mae * (1.0 + self.config.drift_relative_threshold) + hard_limit = self.config.drift_hard_mae_limit + + triggered_dynamic = current_mae > dynamic_threshold + triggered_hard = hard_limit is not None and current_mae > hard_limit + + if triggered_dynamic or triggered_hard: + limit_desc = ( + f"límite duro={hard_limit:.6f}" if triggered_hard + else f"threshold dinámico={dynamic_threshold:.6f} (baseline={baseline_mae:.6f}, " + f"desviación permitida={self.config.drift_relative_threshold:.0%})" + ) + return True, f"MAE actual={current_mae:.6f} superó {limit_desc}." + + return False, ( + f"Sin drift — MAE actual={current_mae:.6f} dentro del threshold dinámico=" + f"{dynamic_threshold:.6f} (baseline={baseline_mae:.6f})." + ) + + # ------------------------------------------------------------------ # + # 3. INCREMENTAL TRAINING — el challenger, aislado por régimen + # ------------------------------------------------------------------ # + + def build_finetune_dataset( + self, regime_name: str, scalers: dict[str, Any] + ) -> dict[str, tuple[np.ndarray, np.ndarray, np.ndarray]]: + """ + Dataset de fine-tuning combinando TODOS los tickers de ESTE régimen + (mismo universo con el que el especialista fue entrenado). Split + CRONOLÓGICO (no aleatorio, por ser serie de tiempo): + [ ---------- train ---------- ][ val ][ holdout Champion/Challenger ] + """ + lookback = scalers["lookback"] + macro_tickers = scalers["macro_tickers"] + asset_to_id = scalers["asset_to_id"] + tickers = list(asset_to_id.keys()) + + all_market_data = self._download_regime_history( + tickers, macro_tickers, self.config.training_history_months + ) + + X_parts, y_parts, asset_parts, date_parts = [], [], [], [] + for ticker in tickers: + try: + X, y_scaled, asset_ids, dates = self._prepare_ticker_dataset( + all_market_data, ticker, macro_tickers, lookback, + scalers["feature_scalers"][ticker], scalers["target_scalers"][ticker], + asset_to_id[ticker], + ) + except Exception as exc: # noqa: BLE001 — un ticker caído no debe tumbar el fine-tuning del régimen + self.logger.warning( + "[%s] Fine-tuning: %s omitido -- %r (mismo criterio de tolerancia a fallos " + "que evaluate_champion_drift).", regime_name, ticker, exc, + ) + continue + if len(X) == 0: + self.logger.warning( + "[%s] Sin ventanas utilizables para %s — se omite del fine-tuning.", + regime_name, ticker, + ) + continue + X_parts.append(X) + y_parts.append(y_scaled) + asset_parts.append(asset_ids.reshape(-1, 1)) + date_parts.append(dates) + + if not X_parts: + raise RuntimeError( + f"[{regime_name}] No se pudo construir el dataset de fine-tuning: " + "0 tickers con datos válidos." + ) + + X = np.concatenate(X_parts, axis=0) + y = np.concatenate(y_parts, axis=0) + asset_ids = np.concatenate(asset_parts, axis=0) + dates = pd.DatetimeIndex(np.concatenate([d.values for d in date_parts])) + + assert X.shape[-1] == N_FEATURES, ( + f"[{regime_name}] Desalineación de features: X tiene {X.shape[-1]} columnas " + f"pero N_FEATURES={N_FEATURES} (TECH_COLS={TECH_COLS})." + ) + + order = np.argsort(dates.values) + X, y, asset_ids = X[order], y[order], asset_ids[order] + + n = len(X) + n_tickers = len(tickers) + n_holdout = max(1, min(self.config.holdout_days * n_tickers, n // 5)) + n_val = max(1, min(self.config.validation_split_days * n_tickers, (n - n_holdout) // 5)) + + if n - n_holdout - n_val <= 0: + raise RuntimeError( + f"[{regime_name}] Dataset insuficiente para separar train/val/holdout " + f"(n={n}, holdout={n_holdout}, val={n_val}). Aumenta training_history_months." + ) + + holdout_slice = slice(n - n_holdout, n) + val_slice = slice(n - n_holdout - n_val, n - n_holdout) + train_slice = slice(0, n - n_holdout - n_val) + + return { + "train": (X[train_slice], y[train_slice], asset_ids[train_slice]), + "val": (X[val_slice], y[val_slice], asset_ids[val_slice]), + "holdout": (X[holdout_slice], y[holdout_slice], asset_ids[holdout_slice]), + } + + def build_challenger(self, champion): + """ + Clona arquitectura Y pesos del Champion (`clone_model` + `set_weights` + — objetos completamente independientes en memoria) y recompila con + LR ultra-bajo (`1e-5` default) para fine-tuning conservador. Usa la + MISMA `DirectionalGaussianNLL` (head dual [mu, log_var], V6+ de + train_kodaquant_v5.py — NO `DirectionalHuberLoss`, que ese módulo + mantiene solo como referencia histórica sin uso) con IDÉNTICOS + hiperparámetros anti-colapso de varianza (β-NLL, barrera de + log_var) con los que el Champion fue entrenado, y `gamma` fijo en + `GAMMA_MAX` (curriculum ya completo — no se re-arranca el warmup en + un fine-tuning incremental). + """ + challenger = keras.models.clone_model(champion) + challenger.set_weights(champion.get_weights()) + + gamma_variable = keras.Variable( + GAMMA_MAX, trainable=False, dtype="float32", name="directional_gamma_finetune" + ) + challenger.compile( + optimizer=keras.optimizers.AdamW( + learning_rate=self.config.finetune_learning_rate, + weight_decay=1e-4, + clipnorm=GRAD_CLIPNORM, + ), + loss=DirectionalGaussianNLL( + gamma_directional=gamma_variable, + beta=GAUSSIAN_NLL_BETA, + log_var_min=LOG_VAR_MIN, log_var_max=LOG_VAR_MAX, + log_var_l2_lambda=LOG_VAR_L2_LAMBDA, + log_var_barrier_lambda=LOG_VAR_BARRIER_LAMBDA, + ), + metrics=[mu_mae_metric, directional_accuracy_metric], + ) + return challenger + + def fine_tune(self, challenger, dataset: dict[str, tuple[np.ndarray, np.ndarray, np.ndarray]]): + """Fine-tuning incremental con Early Stopping obligatorio anti-overfitting.""" + X_train, y_train, asset_train = dataset["train"] + X_val, y_val, asset_val = dataset["val"] + + early_stopping = keras.callbacks.EarlyStopping( + monitor="val_loss", + patience=self.config.early_stopping_patience, + restore_best_weights=True, + ) + + return challenger.fit( + [X_train, asset_train], + y_train, + validation_data=([X_val, asset_val], y_val), + epochs=self.config.finetune_max_epochs, + batch_size=self.config.finetune_batch_size, + shuffle=True, + verbose=0, + callbacks=[early_stopping], + ) + + # ------------------------------------------------------------------ # + # 4. CHAMPION VS. CHALLENGER — A/B testing matemático, por régimen + # ------------------------------------------------------------------ # + + def evaluate_holdout( + self, model, holdout_data: tuple[np.ndarray, np.ndarray, np.ndarray], scalers: dict[str, Any] + ) -> tuple[np.ndarray, dict[str, float]]: + X_hold, y_hold_scaled, asset_hold = holdout_data + id_to_ticker = {v: k for k, v in scalers["asset_to_id"].items()} + flat_ids = asset_hold.reshape(-1) + + y_pred_scaled = np.asarray(model.predict([X_hold, asset_hold], verbose=0))[:, 0:1] # V14.1: solo mu + + y_true_real = np.empty(flat_ids.shape[0], dtype=np.float64) + y_pred_real = np.empty(flat_ids.shape[0], dtype=np.float64) + for asset_id in np.unique(flat_ids): + ticker = id_to_ticker[int(asset_id)] + mask = flat_ids == asset_id + scaler = scalers["target_scalers"][ticker] + y_true_real[mask] = scaler.inverse_transform(y_hold_scaled[mask].reshape(-1, 1)).reshape(-1) + y_pred_real[mask] = scaler.inverse_transform(y_pred_scaled[mask].reshape(-1, 1)).reshape(-1) + + abs_err = np.abs(y_true_real - y_pred_real) + metrics = { + "mae": float(mean_absolute_error(y_true_real, y_pred_real)), + "mse": float(mean_squared_error(y_true_real, y_pred_real)), + "n_samples": int(len(y_true_real)), + } + return abs_err, metrics + + def compare_champion_challenger( + self, champion, challenger, + holdout_data: tuple[np.ndarray, np.ndarray, np.ndarray], + scalers: dict[str, Any], + ) -> dict[str, Any]: + """ + REGLA DE NEGOCIO INQUEBRANTABLE: el Challenger solo gana si su MAE + en Holdout es MENOR **y** esa diferencia es estadísticamente + significativa — test t pareado sobre el error absoluto por muestra, + en escala REAL de log-return, dentro del universo de ESTE régimen. + """ + champion_err, champion_metrics = self.evaluate_holdout(champion, holdout_data, scalers) + challenger_err, challenger_metrics = self.evaluate_holdout(challenger, holdout_data, scalers) + + try: + t_stat, p_value = stats.ttest_rel(challenger_err, champion_err) + t_stat, p_value = float(t_stat), float(p_value) + except Exception as exc: # noqa: BLE001 — el test nunca debe tumbar la comparación + self.logger.warning("Test t pareado falló (%s) — se usa solo comparación directa de MAE.", exc) + t_stat, p_value = None, 1.0 + + mae_improved = challenger_metrics["mae"] < champion_metrics["mae"] * ( + 1.0 - self.config.promotion_min_relative_improvement + ) + statistically_significant = p_value < self.config.promotion_p_value_threshold + promote = bool(mae_improved and statistically_significant) + + return { + "champion": champion_metrics, + "challenger": challenger_metrics, + "t_stat": t_stat, + "p_value": p_value, + "mae_improved": mae_improved, + "statistically_significant": statistically_significant, + "promote": promote, + } + + def promote_challenger(self, regime_name: str, challenger, scalers: dict[str, Any]) -> None: + """Overwrite atómico (`os.replace`) del `.keras`/scalers del especialista, con backup previo.""" + regime_dir = MODELS_ROOT / regime_name + backup_dir = regime_dir / "mlops_backups" + backup_dir.mkdir(parents=True, exist_ok=True) + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + + model_path = regime_dir / "model_v5.keras" + scalers_path = regime_dir / "scalers_dict.pkl" + + if model_path.exists(): + shutil.copy2(model_path, backup_dir / f"model_v5_{stamp}.keras") + if scalers_path.exists(): + shutil.copy2(scalers_path, backup_dir / f"scalers_dict_{stamp}.pkl") + + tmp_model_path = model_path.with_suffix(".tmp.keras") + challenger.save(str(tmp_model_path)) + os.replace(tmp_model_path, model_path) + + # Los scalers no cambian en un fine-tuning incremental (se reutilizan + # los mismos, fit solo en el train histórico del último full retrain) + # — se re-escriben tal cual para dejar el par modelo/scalers + # consistente y con backup en el mismo timestamp de despliegue. + tmp_scalers_path = scalers_path.with_suffix(".tmp.pkl") + with open(tmp_scalers_path, "wb") as fh: + pickle.dump(scalers, fh) + os.replace(tmp_scalers_path, scalers_path) + + self.logger.info( + "[%s] PROMOCIÓN: Challenger sobrescribió al Champion en producción (backup en %s).", + regime_name, backup_dir, + ) + + # ------------------------------------------------------------------ # + # 5. MEMORY LEAK PREVENTION + # ------------------------------------------------------------------ # + + def _release_memory(self, *objs: Any) -> None: + for obj in objs: + del obj + gc.collect() + try: + keras.backend.clear_session() + except Exception as exc: # noqa: BLE001 — la limpieza nunca debe tumbar el ciclo + self.logger.debug("keras.backend.clear_session() no disponible/falló (%s) — se ignora.", exc) + gc.collect() + + # ------------------------------------------------------------------ # + # Orquestador — UN régimen + # ------------------------------------------------------------------ # + + def run_cycle_for_regime(self, regime_name: str, force_retrain: bool = False) -> dict[str, Any]: + cycle_start = datetime.now(timezone.utc) + self.logger.info("==== [%s] CICLO MLOps V5 INICIADO ====", regime_name) + state = self._load_state(regime_name) + + result: dict[str, Any] = {"status": "error", "reason": "ciclo no completado"} + champion = None + challenger = None + dataset = None + + try: + scalers = self._load_scalers(regime_name) + champion = self._load_champion(regime_name) + + drift_metrics = self.evaluate_champion_drift(regime_name, champion, scalers) + drift_detected, drift_reason = self.detect_drift(state, drift_metrics) + if force_retrain: + drift_detected, drift_reason = True, f"Forzado vía --force-retrain (chequeo real: {drift_reason})" + self.logger.info("[%s] Chequeo de drift: %s", regime_name, drift_reason) + + global_metrics = drift_metrics.get("__global__") + if global_metrics is not None: + state.setdefault("baseline_mae", {}).setdefault("__global__", global_metrics["mae"]) + + if not drift_detected: + result = {"status": "no_drift", "reason": drift_reason, "drift_metrics": drift_metrics} + return result + + self.logger.warning("[%s] DRIFT DETECTADO — %s. Se dispara el ciclo Challenger.", regime_name, drift_reason) + + dataset = self.build_finetune_dataset(regime_name, scalers) + challenger = self.build_challenger(champion) + self.fine_tune(challenger, dataset) + + comparison = self.compare_champion_challenger(champion, challenger, dataset["holdout"], scalers) + self.logger.info( + "[%s] Champion MAE: %.6f | Challenger MAE: %.6f | p-value: %s | Winner: %s", + regime_name, + comparison["champion"]["mae"], + comparison["challenger"]["mae"], + f"{comparison['p_value']:.4f}" if comparison["p_value"] is not None else "N/A", + "CHALLENGER" if comparison["promote"] else "CHAMPION", + ) + + if comparison["promote"]: + self.promote_challenger(regime_name, challenger, scalers) + state.setdefault("baseline_mae", {})["__global__"] = comparison["challenger"]["mae"] + result = {"status": "promoted", "comparison": comparison, "drift_metrics": drift_metrics} + else: + self.logger.warning( + "[%s] Degradación rechazada — Challenger NO superó estadísticamente al Champion " + "(mae_improved=%s, statistically_significant=%s). El Champion se mantiene en producción.", + regime_name, comparison["mae_improved"], comparison["statistically_significant"], + ) + result = {"status": "rejected", "comparison": comparison, "drift_metrics": drift_metrics} + + except Exception as exc: # noqa: BLE001 — el demonio nunca debe morir sin loggear + self.logger.exception("[%s] Fallo no controlado durante el ciclo MLOps: %s", regime_name, exc) + result = {"status": "error", "error": str(exc)} + + finally: + state["last_run"] = cycle_start.isoformat() + state.setdefault("history", []).append( + {"timestamp": cycle_start.isoformat(), "status": result.get("status")} + ) + state["history"] = state["history"][-50:] + self._save_state(regime_name, state) + self._release_memory(champion, challenger, dataset) + self.logger.info( + "==== [%s] CICLO MLOps V5 FINALIZADO (status=%s) ====", + regime_name, result.get("status"), + ) + + return result + + # ------------------------------------------------------------------ # + # Orquestador — TODOS los regímenes solicitados + ruteo dinámico + # ------------------------------------------------------------------ # + + def run_cycle( + self, + regimes: list[str] | None = None, + tickers: list[str] | None = None, + force_retrain: bool = False, + ) -> dict[str, dict[str, Any]]: + """ + Si `tickers` viene dado, cada ticker se rutea dinámicamente a su + especialista (`_resolve_regime`) y se valida contra el + `asset_to_id` YA entrenado de ese régimen — un ticker nuevo no puede + fine-tunearse (el embedding no tiene fila para él) y se omite con un + aviso pidiendo un full retrain. El fine-tuning sigue operando sobre + el universo COMPLETO del régimen resuelto (el embedding y el + backbone son compartidos; no tiene sentido fine-tunear con una + fracción del universo entrenado). Sin `tickers`, corre TODOS los + regímenes de `REGIMES` (o el subconjunto de `regimes`). + """ + if tickers: + grouped: dict[str, list[str]] = {} + for raw_ticker in tickers: + ticker = _normalize_ticker_symbol(raw_ticker) + if not ticker: + continue + regime_name = _resolve_regime(ticker) + try: + scalers = self._load_scalers(regime_name) + except (FileNotFoundError, ValueError) as exc: + self.logger.error("No se puede rutear %s -> '%s': %s", ticker, regime_name, exc) + continue + if ticker not in scalers["asset_to_id"]: + self.logger.warning( + "%s no existe en el universo entrenado de '%s' (asset_to_id=%s). El " + "fine-tuning incremental NO puede añadir activos nuevos al embedding " + "— ejecuta train_kodaquant_v5.py (full retrain) para incorporarlo. Se omite.", + ticker, regime_name, list(scalers["asset_to_id"].keys()), + ) + continue + grouped.setdefault(regime_name, []).append(ticker) + + if not grouped: + self.logger.error("Ningún ticker solicitado es procesable — abortando ciclo.") + return {} + + for regime_name, matched in grouped.items(): + self.logger.info("Ruteo dinámico: %s -> especialista '%s'.", matched, regime_name) + target_regimes = list(grouped.keys()) + else: + target_regimes = regimes or list(REGIMES.keys()) + + summary: dict[str, dict[str, Any]] = {} + for regime_name in target_regimes: + if regime_name not in REGIMES: + self.logger.warning( + "Régimen desconocido '%s' — se omite (no existe en REGIMES de train_kodaquant_v5.py).", + regime_name, + ) + summary[regime_name] = {"status": "error", "error": f"régimen desconocido: {regime_name}"} + continue + summary[regime_name] = self.run_cycle_for_regime(regime_name, force_retrain=force_retrain) + + return summary + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def _parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="KodaQuant V5 MLOps — reentrenamiento incremental por régimen, " + "disparado por drift (Champion vs. Challenger).", + ) + parser.add_argument("--months", type=int, default=None, help="Meses de histórico para fine-tuning.") + parser.add_argument("--holdout-days", type=int, default=None, help="Días de holdout Champion vs. Challenger.") + parser.add_argument("--drift-threshold", type=float, default=None, help="Umbral relativo de drift (ej. 0.05 = 5%%).") + parser.add_argument("--hard-mae-limit", type=float, default=None, help="Límite duro de MAE (escala log-return).") + parser.add_argument("--lr", type=float, default=None, help="Learning rate del fine-tuning del Challenger.") + parser.add_argument("--force-retrain", action="store_true", help="Ignora el chequeo de drift y fuerza el ciclo Challenger.") + parser.add_argument( + "--regimes", type=str, default=None, + help="Lista separada por comas de regímenes a procesar (default: todos en REGIMES). Ej: equity_specialist", + ) + parser.add_argument( + "--tickers", type=str, default=None, + help="Lista separada por comas de tickers a rutear dinámicamente hacia su especialista. " + "Ej: TSLA,BTC/USD (también acepta BTC-USD, se normaliza automáticamente).", + ) + return parser.parse_args() + + +def main() -> None: + args = _parse_args() + + overrides: dict[str, Any] = {} + if args.months is not None: + overrides["training_history_months"] = args.months + if args.holdout_days is not None: + overrides["holdout_days"] = args.holdout_days + if args.drift_threshold is not None: + overrides["drift_relative_threshold"] = args.drift_threshold + if args.hard_mae_limit is not None: + overrides["drift_hard_mae_limit"] = args.hard_mae_limit + if args.lr is not None: + overrides["finetune_learning_rate"] = args.lr + + regimes = [r.strip() for r in args.regimes.split(",") if r.strip()] if args.regimes else None + tickers = [t.strip() for t in args.tickers.split(",") if t.strip()] if args.tickers else None + + pipeline = KodaQuantV5MLOps(MLOpsConfig(**overrides)) + summary = pipeline.run_cycle(regimes=regimes, tickers=tickers, force_retrain=args.force_retrain) + + ok_statuses = {"no_drift", "promoted", "rejected"} + success = bool(summary) and all(r.get("status") in ok_statuses for r in summary.values()) + sys.exit(0 if success else 1) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/versions_lock.txt b/versions_lock.txt new file mode 100644 index 0000000000000000000000000000000000000000..484b2d010572786c2f0130d1be17137a9dfdb5dc --- /dev/null +++ b/versions_lock.txt @@ -0,0 +1,2 @@ +scikit-learn==1.6.1 +keras==3.13.2