GitHub Actions KodaQuant commited on
Commit
960fcdd
·
0 Parent(s):

deploy: sync automático a Hugging Face Spaces (ZeroGPU, front-matter README corregido)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +23 -0
  2. .gitattributes +4 -0
  3. .github/workflows/entrenamiento_semanal.yml +131 -0
  4. .github/workflows/keep_alive_hf.yml +22 -0
  5. .github/workflows/sync_huggingface.yml +66 -0
  6. .gitignore +8 -0
  7. Dockerfile +43 -0
  8. README.md +11 -0
  9. api/__init__.py +0 -0
  10. api/auth.py +377 -0
  11. api/online_learning.py +35 -0
  12. api/payments.py +549 -0
  13. api/quanti_chat.py +347 -0
  14. api/quota_test_routes.py +15 -0
  15. api/support.py +146 -0
  16. app.py +30 -0
  17. attention_bilstm_global_best.keras +3 -0
  18. cache/news/headlines_AAPL.json +1 -0
  19. cache/news/headlines_AMZN.json +1 -0
  20. cache/news/headlines_BTC-USD.json +1 -0
  21. cache/news/headlines_ETH-USD.json +1 -0
  22. cache/news/headlines_GOOGL.json +1 -0
  23. cache/news/headlines_META.json +1 -0
  24. cache/news/headlines_MSFT.json +1 -0
  25. cache/news/headlines_NVDA.json +1 -0
  26. cache/news/headlines_SPY.json +1 -0
  27. cache/news/headlines_TSLA.json +1 -0
  28. core/__init__.py +0 -0
  29. core/config.py +92 -0
  30. core/quota_manager.py +142 -0
  31. core/rate_limiter.py +45 -0
  32. core/security.py +564 -0
  33. core/supabase_client.py +20 -0
  34. database/__init__.py +0 -0
  35. logs/mlops_pipeline.log +36 -0
  36. main.py +447 -0
  37. middlewares/__init__.py +0 -0
  38. ml_engine/__init__.py +0 -0
  39. ml_engine/attention_bilstm_global_best.keras +3 -0
  40. ml_engine/cache/news/headlines_AAPL.json +1 -0
  41. ml_engine/cache/news/headlines_AMZN.json +1 -0
  42. ml_engine/cache/news/headlines_GOOGL.json +1 -0
  43. ml_engine/cache/news/headlines_META.json +1 -0
  44. ml_engine/cache/news/headlines_MSFT.json +1 -0
  45. ml_engine/cache/news/headlines_NVDA.json +1 -0
  46. ml_engine/cache/news/headlines_SPY.json +1 -0
  47. ml_engine/cache/news/headlines_TSLA.json +1 -0
  48. ml_engine/data_pipeline.py +1041 -0
  49. ml_engine/entrenamiento.py +1144 -0
  50. ml_engine/forecast_AAPL.png +3 -0
.dockerignore ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .github
3
+ .gitattributes
4
+ __pycache__/
5
+ *.pyc
6
+ *.pyo
7
+ .Python
8
+ venv/
9
+ .venv/
10
+ env/
11
+ .env
12
+ .env.*
13
+ *.egg-info/
14
+ .pytest_cache/
15
+ .mypy_cache/
16
+ .ruff_cache/
17
+ node_modules/
18
+ dist/
19
+ build/
20
+ *.log
21
+ .DS_Store
22
+ .vscode/
23
+ .idea/
.gitattributes ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *.keras filter=lfs diff=lfs merge=lfs -text
2
+ *.pkl filter=lfs diff=lfs merge=lfs -text
3
+ *.png filter=lfs diff=lfs merge=lfs -text
4
+ *.onnx filter=lfs diff=lfs merge=lfs -text
.github/workflows/entrenamiento_semanal.yml ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Entrenamiento Semanal - KodaQuant Predictive Engine
2
+
3
+ on:
4
+ schedule:
5
+ - cron: '0 23 * * 5'
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: write
10
+
11
+ jobs:
12
+ retrain-model:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Checkout repository
16
+ uses: actions/checkout@v4
17
+ with:
18
+ fetch-depth: 0
19
+
20
+ # NUEVO: libera espacio en disco ANTES de instalar dependencias --
21
+ # root cause de "[Errno 28] No space left on device": TensorFlow +
22
+ # CUDA + torch no entran junto a las herramientas preinstaladas
23
+ # (Android SDK, .NET, Haskell/GHC) que el runner ubuntu-latest trae
24
+ # por defecto y este pipeline nunca usa. swap-storage desactivado
25
+ # (solo genera warnings, no libera espacio real relevante acá).
26
+ - name: Liberar espacio en disco del runner
27
+ uses: jlumbroso/free-disk-space@main
28
+ with:
29
+ tool-cache: true
30
+ android: true
31
+ dotnet: true
32
+ haskell: true
33
+ large-packages: false
34
+ docker-images: true
35
+ swap-storage: false
36
+
37
+ - name: Set up Python
38
+ uses: actions/setup-python@v5
39
+ with:
40
+ # FIX: numpy==2.5.1 exige Python>=3.12 (root cause del build fallido).
41
+ # 3.12 ya es el runtime real del HF Space (ver python_version en
42
+ # sync_huggingface.yml) -- esto solo alinea train/serve parity.
43
+ python-version: '3.12'
44
+
45
+ - name: Cache pip dependencies
46
+ uses: actions/cache@v4
47
+ with:
48
+ path: ~/.cache/pip
49
+ key: ${{ runner.os }}-pip-3.12-${{ hashFiles('requirements.txt') }}
50
+ restore-keys: |
51
+ ${{ runner.os }}-pip-3.12-
52
+
53
+ - name: Install dependencies
54
+ run: |
55
+ python -m pip install --upgrade pip
56
+ # torch/transformers YA están pineados en requirements.txt
57
+ # (torch==2.11.0, transformers==5.15.0 -- ver FIX RONDA 1/2 ahí)
58
+ # para compat con el validador ZeroGPU de HF. Instalarlos sueltos
59
+ # acá (como antes) los sobrescribía con versiones sin pinear,
60
+ # deshaciendo esos fixes en cada corrida de entrenamiento.
61
+ # --no-cache-dir -- NUEVO: el cache de pip (wheels descargados)
62
+ # ocupaba espacio real de disco además de TensorFlow/torch/CUDA
63
+ # ya instalados -- root cause de "No space left on device".
64
+ python -m pip install --no-cache-dir -r requirements.txt
65
+
66
+ - name: Ejecutar script de entrenamiento
67
+ env:
68
+ # --- Supabase ---
69
+ SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
70
+ SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}
71
+ SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}
72
+ SUPABASE_JWT_SECRET: ${{ secrets.SUPABASE_JWT_SECRET }}
73
+
74
+ # --- Stripe ---
75
+ STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }}
76
+ STRIPE_PRICE_PRO: ${{ secrets.STRIPE_PRICE_PRO }}
77
+ STRIPE_PRICE_ULTRA: ${{ secrets.STRIPE_PRICE_ULTRA }}
78
+ STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }}
79
+ STRIPE_SUCCESS_URL: ${{ secrets.STRIPE_SUCCESS_URL }}
80
+ STRIPE_CANCEL_URL: ${{ secrets.STRIPE_CANCEL_URL }}
81
+
82
+ # --- Mercado / Sentimiento ---
83
+ FINNHUB_API_KEY: ${{ secrets.FINNHUB_API_KEY }}
84
+ TWELVE_DATA_API_KEY: ${{ secrets.TWELVE_DATA_API_KEY }}
85
+ FRED_API_KEY: ${{ secrets.FRED_API_KEY }}
86
+
87
+ # --- Seguridad interna ---
88
+ API_SECRET_KEY: ${{ secrets.API_SECRET_KEY }}
89
+
90
+ # --- SMTP ---
91
+ SMTP_USER: ${{ secrets.SMTP_USER }}
92
+ SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
93
+ SMTP_FROM: ${{ secrets.SMTP_FROM }}
94
+
95
+ # --- Flags de entorno (tienen default en Settings, se fuerzan explícitos) ---
96
+ ENV: ${{ secrets.ENV }}
97
+ DEBUG: ${{ secrets.DEBUG }}
98
+
99
+ # --- V9 CI/CD (Purgado Total en Producción) ---
100
+ KODAQUANT_FORCE_FRESH_DATA: "true"
101
+ run: python ml_engine/train_kodaquant_v5.py
102
+
103
+ - name: Auto commit model artifacts
104
+ uses: stefanzweifel/git-auto-commit-action@v5
105
+ with:
106
+ commit_message: "🤖 MLOps: Automated model retraining weights updated"
107
+ file_pattern: 'services/kodaquant_models/**/*.keras services/kodaquant_models/**/*.pkl services/kodaquant_models/**/*.png'
108
+ commit_user_name: github-actions[bot]
109
+ commit_user_email: github-actions[bot]@users.noreply.github.com
110
+ commit_author: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
111
+
112
+ # NUEVO: push directo a HF -- NO depende del `on: push` de
113
+ # sync_huggingface.yml, porque el commit de arriba usa GITHUB_TOKEN y
114
+ # GitHub NO dispara otros workflows con ese token (evita loops
115
+ # infinitos). Sin este step, los pesos nunca llegaban a HF solos.
116
+ - name: Publicar pesos del modelo en Hugging Face
117
+ env:
118
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
119
+ run: |
120
+ pip install -U "huggingface_hub[cli]"
121
+
122
+ # Destino: mismo Space del backend (Zusheim/kodaquant-backend).
123
+ # Ruta destino "services/kodaquant_models" (NO ".") -- preserva la
124
+ # misma ruta relativa que usa el código en runtime (quanti_engine.py
125
+ # espera crypto_specialist/ y equity_specialist/ ahí mismo, igual
126
+ # que en el checkout local).
127
+ huggingface-cli upload Zusheim/kodaquant-backend \
128
+ services/kodaquant_models/ services/kodaquant_models \
129
+ --repo-type space \
130
+ --token "$HF_TOKEN" \
131
+ --commit-message "🤖 MLOps: sync pesos entrenados $(date -u +%Y-%m-%dT%H:%M:%SZ)"
.github/workflows/keep_alive_hf.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Keep-Alive HF Space - KodaQuant Backend
2
+
3
+ on:
4
+ schedule:
5
+ - cron: '0 12 * * *'
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ ping-space:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - name: Ping al Space para resetear el temporizador de sleep de HF
13
+ continue-on-error: true
14
+ run: |
15
+ # Sin -f: un 404/403 en el frontend del Space NO debe marcar fallo
16
+ # el workflow -- el objetivo es solo que el contenedor reciba el
17
+ # hit y resetee su temporizador de inactividad (48h), no validar
18
+ # el contenido de la respuesta. -L sigue redirects. continue-on-error
19
+ # a nivel step cubre además timeouts/errores de red genuinos.
20
+ curl -sS -o /dev/null -w "HTTP %{http_code}\n" -L \
21
+ --max-time 30 --retry 2 --retry-delay 5 \
22
+ "https://zusheim-kodaquant-backend.hf.space" || true
.github/workflows/sync_huggingface.yml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Despliegue Automático a Hugging Face
2
+
3
+ on:
4
+ push:
5
+ branches: [ "main" ]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ sync-to-hub:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ with:
14
+ lfs: true
15
+
16
+ - name: Empujar estado limpio a Hugging Face
17
+ env:
18
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
19
+ run: |
20
+ # 1. Crear .gitignore linea por linea sin sangrías
21
+ echo "node_modules/" > .gitignore
22
+ echo "venv/" >> .gitignore
23
+ echo ".env" >> .gitignore
24
+ echo "dist/" >> .gitignore
25
+ echo "build/" >> .gitignore
26
+ echo "__pycache__/" >> .gitignore
27
+ echo "*.pyc" >> .gitignore
28
+ echo ".DS_Store" >> .gitignore
29
+
30
+ # 2. Inyectar la llave de encendido de Gradio con Python 3.12
31
+ # FIX -- `sdk_version`/`python_version` DEBEN ir entre comillas.
32
+ # Verificado: `echo "python_version: 3.12" >> README.md` (sin
33
+ # comillas) produce un YAML donde ese valor se parsea como FLOAT
34
+ # (3.12), no como string "3.12" -- el mismo tipo de
35
+ # "configuration error" silencioso que ya rompió el build por el
36
+ # pin de torch. El template oficial de HF (`{{sdkVersion}}` /
37
+ # `{{pythonVersion}}`) siempre los entrega entre comillas dobles
38
+ # por esta razón exacta.
39
+ echo "---" > README.md
40
+ echo "title: KodaQuant Backend" >> README.md
41
+ echo "emoji: 🚀" >> README.md
42
+ echo "colorFrom: blue" >> README.md
43
+ echo "colorTo: indigo" >> README.md
44
+ echo "sdk: gradio" >> README.md
45
+ echo 'sdk_version: "6.22.0"' >> README.md
46
+ echo 'python_version: "3.12"' >> README.md
47
+ echo "app_file: app.py" >> README.md
48
+ echo "pinned: false" >> README.md
49
+ echo "---" >> README.md
50
+
51
+ # 3. Borrar el historial fantasma de Git
52
+ rm -rf .git
53
+ git init
54
+ git checkout -b main
55
+ git config user.name "GitHub Actions KodaQuant"
56
+ git config user.email "actions@github.com"
57
+
58
+ # 4. Rastrear solo los archivos que existen HOY
59
+ git lfs install
60
+ git lfs track "*.keras"
61
+ git lfs track "*.pkl"
62
+ git add .
63
+
64
+ # 5. Empaquetar y forzar la subida a Hugging Face
65
+ git commit -m "deploy: sync automático a Hugging Face Spaces (ZeroGPU, front-matter README corregido)"
66
+ git push --force https://Zusheim:$HF_TOKEN@huggingface.co/spaces/Zusheim/kodaquant-backend main
.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ venv/
3
+ .env
4
+ dist/
5
+ build/
6
+ __pycache__/
7
+ *.pyc
8
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ FROM python:3.12-slim
3
+
4
+ # libgomp1: required at import time by TensorFlow / scikit-learn's
5
+ # OpenMP-based ops. Not present on python:slim -> silent ImportError
6
+ # on `import tensorflow` without it.
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ libgomp1 \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ # Hugging Face Spaces containers run as uid 1000 — mirror that so file
12
+ # ownership matches what the platform expects instead of fighting it.
13
+ RUN useradd -m -u 1000 user
14
+ USER user
15
+
16
+ ENV HOME=/home/user \
17
+ PATH="/home/user/.local/bin:${PATH}" \
18
+ PYTHONDONTWRITEBYTECODE=1 \
19
+ PYTHONUNBUFFERED=1 \
20
+ PIP_NO_CACHE_DIR=1 \
21
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
22
+ # Keras / HF-hub / Matplotlib all try to write cache files at
23
+ # import time. Only /tmp and WORKDIR are guaranteed writable on
24
+ # Spaces, so caches are redirected there defensively.
25
+ KERAS_HOME=/tmp/.keras \
26
+ HF_HOME=/tmp/.huggingface \
27
+ XDG_CACHE_HOME=/tmp/.cache \
28
+ MPLCONFIGDIR=/tmp/.matplotlib
29
+
30
+ WORKDIR /app
31
+
32
+ # Dependencies installed before the rest of the source is copied, so
33
+ # `docker build` only reinstalls TensorFlow/pandas/etc. when
34
+ # requirements.txt actually changes, not on every code push.
35
+ COPY --chown=user requirements.txt .
36
+ RUN pip install --no-cache-dir --upgrade pip \
37
+ && pip install --no-cache-dir -r requirements.txt
38
+
39
+ COPY --chown=user . .
40
+
41
+ EXPOSE 7860
42
+
43
+ CMD ["python", "app.py"]
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: KodaQuant Backend
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: "6.22.0"
8
+ python_version: "3.12"
9
+ app_file: app.py
10
+ pinned: false
11
+ ---
api/__init__.py ADDED
File without changes
api/auth.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ api/auth.py
3
+
4
+ Módulo de autenticación para KodaQuant Terminal.
5
+ Responsable de exponer los endpoints de registro de usuarios delegando
6
+ la persistencia y validación de credenciales a Supabase Auth.
7
+
8
+ Arquitectura:
9
+ - Cliente Supabase inicializado a partir de credenciales centralizadas en core.config.
10
+ - Esquemas de entrada/salida validados con Pydantic.
11
+ - Manejo explícito de errores de Supabase mapeados a HTTPException.
12
+ """
13
+ import hashlib
14
+ from datetime import datetime, timezone
15
+ from core.security import (
16
+ generate_verification_token,
17
+ send_verification_email,
18
+ generate_password_reset_token,
19
+ send_password_reset_email,
20
+ )
21
+ from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, status
22
+ from pydantic import BaseModel, EmailStr, Field, field_validator
23
+ from core.supabase_client import supabase, supabase_admin
24
+ from core.rate_limiter import enforce_rate_limit
25
+
26
+
27
+ def _hash_token(token: str) -> str:
28
+ """Hash de un solo sentido para tokens de un solo uso antes de persistirlos.
29
+ El token crudo viaja SOLO por el link del correo — nunca en texto plano en DB."""
30
+ return hashlib.sha256(token.encode()).hexdigest()
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Router
34
+ # ---------------------------------------------------------------------------
35
+ router = APIRouter(
36
+ tags=["Authentication"],
37
+ )
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Esquemas Pydantic
42
+ # ---------------------------------------------------------------------------
43
+ class UserRegisterRequest(BaseModel):
44
+ """Payload de entrada para el registro de un nuevo usuario."""
45
+
46
+ email: EmailStr = Field(..., description="Correo electrónico del usuario.")
47
+ full_name: str = Field(..., min_length=2, max_length=120, description="Nombre completo del usuario.")
48
+ password: str = Field(
49
+ ...,
50
+ min_length=8,
51
+ description="Contraseña del usuario. Mínimo 8 caracteres.",
52
+ )
53
+ terms_accepted: bool = Field(
54
+ ..., description="Debe ser true: aceptación explícita de T&C y Aviso de Privacidad."
55
+ )
56
+
57
+ @field_validator("terms_accepted")
58
+ @classmethod
59
+ def validate_terms_accepted(cls, value: bool) -> bool:
60
+ if value is not True:
61
+ raise ValueError("Debes aceptar los Términos y Condiciones y el Aviso de Privacidad.")
62
+ return value
63
+
64
+ @field_validator("password")
65
+ @classmethod
66
+ def validate_password_strength(cls, value: str) -> str:
67
+ # El hashing de la contraseña NO se hace acá: Supabase Auth (GoTrue)
68
+ # la hashea con bcrypt del lado del servidor dentro de auth.sign_up().
69
+ # Hashear manualmente antes de enviarla duplicaría el trabajo y
70
+ # rompería la verificación posterior en sign_in_with_password.
71
+ """Valida requisitos mínimos de robustez antes de llamar a Supabase."""
72
+ if not any(char.isdigit() for char in value):
73
+ raise ValueError("La contraseña debe contener al menos un número.")
74
+ if not any(char.isupper() for char in value):
75
+ raise ValueError("La contraseña debe contener al menos una letra mayúscula.")
76
+ return value
77
+
78
+
79
+ class UserRegisterResponse(BaseModel):
80
+ """Respuesta devuelta tras un registro exitoso."""
81
+
82
+ id: str
83
+ email: EmailStr
84
+ message: str = "Usuario registrado exitosamente. Verifica tu correo electrónico."
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Endpoint: Registro de usuario
89
+ # ---------------------------------------------------------------------------
90
+ @router.post(
91
+ "/register",
92
+ response_model=UserRegisterResponse,
93
+ status_code=status.HTTP_201_CREATED,
94
+ summary="Registrar un nuevo usuario",
95
+ description="Crea una nueva cuenta de usuario en Supabase Auth para KodaQuant Terminal.",
96
+ )
97
+ async def register_user(
98
+ payload: UserRegisterRequest, request: Request, background_tasks: BackgroundTasks
99
+ ) -> UserRegisterResponse:
100
+ """
101
+ Registra un nuevo usuario en Supabase Auth.
102
+
103
+ Args:
104
+ payload (UserRegisterRequest): Credenciales del usuario (email, password,
105
+ full_name y terms_accepted).
106
+
107
+ Returns:
108
+ UserRegisterResponse: Datos básicos del usuario creado.
109
+
110
+ Raises:
111
+ HTTPException 409: Si el correo ya está registrado.
112
+ HTTPException 422: Si la contraseña es rechazada por Supabase (débil).
113
+ HTTPException 429: Si se excede el límite de intentos (fuerza bruta).
114
+ HTTPException 500: Ante cualquier error inesperado del proveedor de auth
115
+ o si falla la inicialización del perfil en `profiles`.
116
+ """
117
+ await enforce_rate_limit(request, "register")
118
+
119
+ try:
120
+ # FIX: `full_name` va anidado bajo "options.data", no como key de nivel
121
+ # superior. supabase-py solo escribe en auth.users.raw_user_meta_data
122
+ # cuando el metadata llega dentro de "options" -- con la forma anterior
123
+ # ({"data": {...}} al mismo nivel que "email"/"password"), el SDK la
124
+ # ignora silenciosamente y raw_user_meta_data queda vacío, sin error.
125
+ result = supabase.auth.sign_up(
126
+ {
127
+ "email": payload.email,
128
+ "password": payload.password,
129
+ "options": {"data": {"full_name": payload.full_name}},
130
+ }
131
+ )
132
+ except Exception as exc:
133
+ error_message = str(exc).lower()
134
+
135
+ if "already registered" in error_message or "already exists" in error_message:
136
+ raise HTTPException(
137
+ status_code=status.HTTP_409_CONFLICT,
138
+ detail="El correo electrónico ya se encuentra registrado.",
139
+ ) from exc
140
+
141
+ if "password" in error_message and (
142
+ "weak" in error_message or "short" in error_message or "should be" in error_message
143
+ ):
144
+ raise HTTPException(
145
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
146
+ detail="La contraseña no cumple con los requisitos mínimos de seguridad.",
147
+ ) from exc
148
+
149
+ print(f"[ERROR] Fallo inesperado en registro (user={payload.email}): {exc}")
150
+ raise HTTPException(
151
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
152
+ detail="No se pudo completar el registro. Intenta nuevamente más tarde.",
153
+ ) from exc
154
+
155
+ user = getattr(result, "user", None)
156
+ if user is None or getattr(user, "id", None) is None:
157
+ raise HTTPException(
158
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
159
+ detail="Supabase no devolvió información válida del usuario creado.",
160
+ )
161
+
162
+ # --- FIX: detección de correo duplicado silencioso ---
163
+ # Cuando la confirmación por email está activada en Supabase, sign_up()
164
+ # con un correo YA existente no lanza excepción: devuelve un "user" con
165
+ # identities=[] vacío (medida anti-enumeración de Supabase). Sin este
166
+ # chequeo, el backend responde 201 como si hubiera creado una cuenta nueva.
167
+ identities = getattr(user, "identities", None)
168
+ if identities is not None and len(identities) == 0:
169
+ raise HTTPException(
170
+ status_code=status.HTTP_400_BAD_REQUEST,
171
+ detail="Este correo ya está registrado.",
172
+ )
173
+
174
+ token, expires_at = generate_verification_token()
175
+
176
+ # FIX (root cause del 500 / PGRST204): requiere que exista
177
+ # public.profiles.full_name (ver migración SQL adjunta). Además, esta
178
+ # escritura ahora está aislada en su propio try/except: para este punto
179
+ # el usuario YA existe en Auth (sign_up ya se ejecutó con éxito), así que
180
+ # un fallo acá NO debe propagarse como un AttributeError/KeyError crudo --
181
+ # se loguea con detalle y se responde un 500 explícito y accionable, en
182
+ # vez de dejar a la cuenta en un estado a medio inicializar sin avisar.
183
+ try:
184
+ supabase_admin.table("profiles").update({
185
+ "full_name": payload.full_name,
186
+ "is_verified": False,
187
+ "verification_token": _hash_token(token),
188
+ "verification_token_expires_at": expires_at.isoformat(),
189
+ }).eq("id", user.id).execute()
190
+ except Exception as exc:
191
+ print(f"[ERROR] No se pudo inicializar el perfil en 'profiles' (user_id={user.id}): {exc}")
192
+ raise HTTPException(
193
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
194
+ detail=(
195
+ "Tu cuenta se creó pero hubo un problema al configurar tu perfil. "
196
+ "Contacta a soporte antes de intentar registrarte de nuevo."
197
+ ),
198
+ ) from exc
199
+
200
+ # FIX (root cause de "el registro tarda demasiado" / SMTP timeout en
201
+ # línea): antes esto era `await send_verification_email(...)` dentro de
202
+ # un try/except -- el cliente HTTP esperaba a que el SMTP conectara (o
203
+ # tronara) ANTES de recibir el 201. Con el puerto bloqueado y sin timeout
204
+ # explícito eso eran hasta 60s de espera real por request. Ahora se
205
+ # agenda como BackgroundTask: la respuesta 201 sale apenas termina lo de
206
+ # arriba, y el envío corre después, con su propio techo de 3s
207
+ # (core/security.py::_send_mail_message) que nunca vuelve a tocar este
208
+ # request.
209
+ background_tasks.add_task(send_verification_email, payload.email, token)
210
+
211
+ return UserRegisterResponse(
212
+ id=user.id,
213
+ email=payload.email,
214
+ )
215
+
216
+ class VerifyEmailRequest(BaseModel):
217
+ token: str
218
+
219
+ @router.post("/verify-email")
220
+ async def verify_email(payload: VerifyEmailRequest):
221
+ result = (
222
+ supabase_admin.table("profiles")
223
+ .select("id, is_verified, verification_token_expires_at")
224
+ .eq("verification_token", _hash_token(payload.token))
225
+ .maybe_single()
226
+ .execute()
227
+ )
228
+ profile = result.data
229
+ if not profile:
230
+ raise HTTPException(status_code=400, detail="Token de verificación inválido.")
231
+ if profile.get("is_verified"):
232
+ return {"message": "El correo ya estaba verificado."}
233
+
234
+ expires_at = profile.get("verification_token_expires_at")
235
+ if expires_at and datetime.fromisoformat(expires_at) < datetime.now(timezone.utc):
236
+ raise HTTPException(status_code=400, detail="El token ha expirado.")
237
+
238
+ supabase_admin.table("profiles").update({
239
+ "is_verified": True,
240
+ "verification_token": None,
241
+ "verification_token_expires_at": None,
242
+ }).eq("id", profile["id"]).execute()
243
+
244
+ return {"message": "Correo verificado exitosamente."}
245
+
246
+ class LoginRequest(BaseModel):
247
+ email: str
248
+ password: str
249
+
250
+ @router.post("/login")
251
+ async def login(payload: LoginRequest, request: Request):
252
+ await enforce_rate_limit(request, "login")
253
+
254
+ try:
255
+ response = supabase.auth.sign_in_with_password({
256
+ "email": payload.email,
257
+ "password": payload.password
258
+ })
259
+ except Exception as exc:
260
+ print(f"[ERROR] Fallo de login (user={payload.email}): {exc}")
261
+ raise HTTPException(status_code=401, detail="Credenciales inválidas.")
262
+
263
+ if not response or not response.session:
264
+ raise HTTPException(status_code=401, detail="No se pudo autenticar")
265
+
266
+ profile = (
267
+ supabase_admin.table("profiles")
268
+ .select("is_verified")
269
+ .eq("id", response.user.id)
270
+ .single()
271
+ .execute()
272
+ ).data
273
+ if not profile or not profile.get("is_verified"):
274
+ raise HTTPException(status_code=401, detail="Debes verificar tu correo antes de iniciar sesión.")
275
+
276
+ return {
277
+ "access_token": response.session.access_token,
278
+ "token_type": "bearer",
279
+ "user": response.user
280
+ }
281
+
282
+
283
+ class ForgotPasswordRequest(BaseModel):
284
+ email: EmailStr
285
+
286
+
287
+ @router.post("/forgot-password")
288
+ async def forgot_password(payload: ForgotPasswordRequest, request: Request, background_tasks: BackgroundTasks):
289
+ """
290
+ Inicia el flujo de recuperación de contraseña.
291
+
292
+ Respuesta SIEMPRE genérica (anti user-enumeration): nunca confirmamos
293
+ ni negamos si el correo existe en la base, sin importar el resultado.
294
+ """
295
+ await enforce_rate_limit(request, "forgot-password")
296
+
297
+ generic_response = {
298
+ "message": "Si existe una cuenta con ese correo, te enviamos un enlace para restablecer tu contraseña."
299
+ }
300
+
301
+ # ⚠️ Asume que la tabla `profiles` tiene columna `email` (patrón típico de
302
+ # trigger on-signup en Supabase). Si tu esquema no la tiene, ajusta esta
303
+ # búsqueda a como resuelvas hoy user-por-email.
304
+ profile_result = (
305
+ supabase_admin.table("profiles")
306
+ .select("id")
307
+ .eq("email", payload.email)
308
+ .maybe_single()
309
+ .execute()
310
+ )
311
+ profile = profile_result.data
312
+ if not profile:
313
+ return generic_response
314
+
315
+ token, expires_at = generate_password_reset_token()
316
+ supabase_admin.table("profiles").update({
317
+ "password_reset_token": _hash_token(token),
318
+ "password_reset_token_expires_at": expires_at.isoformat(),
319
+ }).eq("id", profile["id"]).execute()
320
+
321
+ # Mismo fix que en /register: agendado como BackgroundTask para que la
322
+ # respuesta genérica (anti-enumeración) salga de inmediato, sin esperar
323
+ # al SMTP. Ver core/security.py::_send_mail_message para el techo de 3s.
324
+ background_tasks.add_task(send_password_reset_email, payload.email, token)
325
+
326
+ return generic_response
327
+
328
+
329
+ class ResetPasswordRequest(BaseModel):
330
+ token: str
331
+ password: str = Field(..., min_length=8)
332
+
333
+ @field_validator("password")
334
+ @classmethod
335
+ def validate_password_strength(cls, value: str) -> str:
336
+ if not any(char.isdigit() for char in value):
337
+ raise ValueError("La contraseña debe contener al menos un número.")
338
+ if not any(char.isupper() for char in value):
339
+ raise ValueError("La contraseña debe contener al menos una letra mayúscula.")
340
+ return value
341
+
342
+
343
+ @router.post("/reset-password")
344
+ async def reset_password(payload: ResetPasswordRequest, request: Request):
345
+ await enforce_rate_limit(request, "reset-password")
346
+
347
+ result = (
348
+ supabase_admin.table("profiles")
349
+ .select("id, password_reset_token_expires_at")
350
+ .eq("password_reset_token", _hash_token(payload.token))
351
+ .maybe_single()
352
+ .execute()
353
+ )
354
+ profile = result.data
355
+ if not profile:
356
+ raise HTTPException(status_code=400, detail="Enlace de restablecimiento inválido.")
357
+
358
+ expires_at = profile.get("password_reset_token_expires_at")
359
+ if not expires_at or datetime.fromisoformat(expires_at) < datetime.now(timezone.utc):
360
+ raise HTTPException(status_code=400, detail="El enlace ha expirado. Solicita uno nuevo.")
361
+
362
+ try:
363
+ supabase_admin.auth.admin.update_user_by_id(
364
+ profile["id"], {"password": payload.password}
365
+ )
366
+ except Exception as exc:
367
+ raise HTTPException(
368
+ status_code=500,
369
+ detail=f"No se pudo actualizar la contraseña: {str(exc)}",
370
+ ) from exc
371
+
372
+ supabase_admin.table("profiles").update({
373
+ "password_reset_token": None,
374
+ "password_reset_token_expires_at": None,
375
+ }).eq("id", profile["id"]).execute()
376
+
377
+ return {"message": "Contraseña actualizada exitosamente."}
api/online_learning.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api/online_learning.py
2
+ """
3
+ Endpoint disparador del ciclo diario de online learning (Fase 1). Pensado
4
+ para ser golpeado por un cron externo (Render Cron Job, GitHub Actions
5
+ schedule, cron de VPS con `curl`) UNA vez al día, después del cierre de
6
+ mercado (NYSE cierra 21:00 UTC / 16:00 ET) — NO por el frontend ni por
7
+ usuarios finales, por eso vive detrás de un secreto compartido en vez de
8
+ `verify_api_credits` (esto no consume créditos de ningún usuario, es
9
+ mantenimiento interno del modelo).
10
+ """
11
+
12
+ import os
13
+
14
+ from fastapi import APIRouter, Header, HTTPException
15
+
16
+ from services.online_learning import run_daily_online_learning_cycle
17
+
18
+ router = APIRouter()
19
+
20
+ # Debe fijarse en el entorno de producción (`CRON_SECRET=...`) — sin él,
21
+ # el endpoint rechaza TODO request (fail-closed, nunca fail-open).
22
+ _CRON_SECRET = os.getenv("CRON_SECRET")
23
+
24
+
25
+ @router.post("/api/v1/quanti/online-learning/run")
26
+ async def trigger_online_learning_cycle(x_cron_secret: str | None = Header(default=None)):
27
+ if not _CRON_SECRET or x_cron_secret != _CRON_SECRET:
28
+ raise HTTPException(status_code=403, detail="CRON_SECRET ausente o inválido.")
29
+
30
+ # SÍNCRONO Y POTENCIALMENTE LARGO (descarga de mercado + fit de Keras) —
31
+ # se corre tal cual dentro del handler porque este endpoint es de uso
32
+ # exclusivo del cron (1 invocación/día), no del tráfico de usuarios; no
33
+ # justifica la complejidad de un job queue para este volumen.
34
+ report = run_daily_online_learning_cycle()
35
+ return {"status": "success" if not report.get("errors") else "partial", "report": report}
api/payments.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RUTA: api/payments.py
2
+ import json
3
+ import logging
4
+ from datetime import datetime, timezone
5
+ from typing import Any
6
+
7
+ import stripe
8
+ from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, status
9
+ from pydantic import BaseModel
10
+
11
+ from core.config import settings
12
+ from core.security import AuthenticatedUser, get_current_user
13
+ from core.supabase_client import supabase_admin
14
+ from core.security import (
15
+ send_subscription_upgrade_email,
16
+ send_subscription_downgrade_email,
17
+ send_subscription_cancel_email,
18
+ )
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ stripe.api_key = settings.STRIPE_SECRET_KEY
23
+
24
+ router = APIRouter(prefix="/api/v1/payments", tags=["payments"])
25
+
26
+ PRICE_MAP = {
27
+ "pro": settings.STRIPE_PRICE_PRO,
28
+ "ultra": settings.STRIPE_PRICE_ULTRA,
29
+ }
30
+ TIER_BY_PRICE = {v: k.upper() for k, v in PRICE_MAP.items() if v}
31
+ TIER_RANK = {"FREE": 0, "PRO": 1, "ULTRA": 2}
32
+
33
+
34
+ def _ts_to_iso(ts: int | None) -> str | None:
35
+ if not ts:
36
+ return None
37
+ return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
38
+
39
+
40
+ def _stripe_object_to_dict(obj: Any) -> dict:
41
+ """Convierte recursivamente un Event/StripeObject del SDK a dict/list
42
+ nativos de Python. En SDK v12+, ningún StripeObject anidado garantiza
43
+ .get() en accesos encadenados -- normalizar UNA vez acá (aquí, en
44
+ change-plan, en el webhook) evita repetir ese riesgo en cada callsite."""
45
+ if hasattr(obj, "to_dict_recursive"):
46
+ return obj.to_dict_recursive()
47
+ if hasattr(obj, "to_dict"):
48
+ return obj.to_dict()
49
+ try:
50
+ return json.loads(json.dumps(obj, default=str))
51
+ except (TypeError, ValueError) as exc:
52
+ logger.error("No se pudo normalizar objeto Stripe: %s", exc)
53
+ return {}
54
+
55
+
56
+ def _extract_period_end(sub_dict: dict) -> int | None:
57
+ """Extrae el timestamp Unix de current_period_end de forma segura.
58
+
59
+ Root cause real del 23502: a partir de la versión de API 'Basil'
60
+ (2025-03-31+), Stripe removió current_period_start/current_period_end
61
+ del objeto Subscription de nivel superior. Ahora viven por-item, en
62
+ items.data[N].current_period_end (ver changelog de Stripe: "Adds
63
+ subscription item-level billing periods and removes subscription-level
64
+ periods"). Cualquier cuenta/SDK apuntando a esa versión de API (o
65
+ posterior) devuelve `None` en sub_dict.get("current_period_end"),
66
+ que es exactamente el síntoma reportado.
67
+
68
+ Estrategia: leer primero desde el primer item de la suscripción (fuente
69
+ de verdad en Basil+), con fallback al campo legacy de nivel superior
70
+ para cuentas todavía en una versión de API pre-Basil.
71
+ """
72
+ items = (sub_dict.get("items") or {}).get("data") or []
73
+ if items:
74
+ item_period_end = items[0].get("current_period_end")
75
+ if item_period_end is not None:
76
+ return int(item_period_end)
77
+
78
+ legacy_period_end = sub_dict.get("current_period_end")
79
+ if legacy_period_end is not None:
80
+ return int(legacy_period_end)
81
+
82
+ return None
83
+
84
+
85
+ def _require_period_end_iso(sub_dict: dict, subscription_id: str) -> str:
86
+ """Fail-fast: valida ANTES de tocar la base de datos. Si Stripe no
87
+ devuelve current_period_end en ninguna de las dos ubicaciones posibles,
88
+ aborta con un error claro en vez de dejar pasar un None hacia el
89
+ .update() de Supabase (que dispara el 23502 sobre la constraint
90
+ NOT NULL de profiles.current_period_end)."""
91
+ period_end_ts = _extract_period_end(sub_dict)
92
+ if period_end_ts is None:
93
+ logger.error(
94
+ "current_period_end ausente en la suscripción %s (ni en items[0] ni en el nivel superior)",
95
+ subscription_id,
96
+ )
97
+ raise HTTPException(
98
+ status.HTTP_500_INTERNAL_SERVER_ERROR,
99
+ "No se pudo determinar la fecha de fin de período de la suscripción en Stripe.",
100
+ )
101
+ period_end_iso = _ts_to_iso(period_end_ts)
102
+ if period_end_iso is None:
103
+ logger.error("Fallo al convertir current_period_end=%s a ISO-8601 (sub=%s)", period_end_ts, subscription_id)
104
+ raise HTTPException(
105
+ status.HTTP_500_INTERNAL_SERVER_ERROR,
106
+ "No se pudo convertir la fecha de fin de período de la suscripción.",
107
+ )
108
+ return period_end_iso
109
+
110
+
111
+ def _release_schedule_if_attached(sub_dict: dict, subscription_id: str) -> None:
112
+ """Rompe el vínculo Subscription<->SubscriptionSchedule si existe uno activo.
113
+
114
+ Root cause de los 400 en change-plan/cancel: una vez que una Subscription
115
+ queda atada a un SubscriptionSchedule (ej. por un downgrade programado
116
+ previo vía _schedule_downgrade), Stripe bloquea CUALQUIER
117
+ Subscription.modify() directo -- tanto cambio de item/price como
118
+ cancel_at_period_end -- exigiendo que la modificación pase por el
119
+ schedule ("You cannot migrate a subscription that is already attached
120
+ to a schedule" / "updating any cancelation behavior directly is not
121
+ allowed"). `SubscriptionSchedule.release()` desata el schedule de la
122
+ Subscription sin cancelarla, devolviendo el control directo sobre
123
+ Subscription.modify(). Se ejecuta ANTES de cualquier modify() o de
124
+ crear un schedule nuevo (_schedule_downgrade también fallaría con 400
125
+ si ya hay uno attached)."""
126
+ schedule_id = sub_dict.get("schedule")
127
+ if not schedule_id:
128
+ return
129
+ try:
130
+ stripe.SubscriptionSchedule.release(schedule_id)
131
+ logger.info(
132
+ "Schedule %s liberado para desbloquear modificación directa de sub %s",
133
+ schedule_id, subscription_id,
134
+ )
135
+ except stripe.error.StripeError as exc:
136
+ logger.error(
137
+ "No se pudo liberar el schedule %s de la suscripción %s: %s",
138
+ schedule_id, subscription_id, exc,
139
+ )
140
+ raise HTTPException(
141
+ status.HTTP_409_CONFLICT,
142
+ "La suscripción está atada a un schedule de Stripe que no pudo liberarse. Contactá a soporte.",
143
+ )
144
+
145
+
146
+ def _get_user_email_and_language(user_id: str) -> tuple[str | None, str]:
147
+ email = None
148
+ try:
149
+ admin_user = supabase_admin.auth.admin.get_user_by_id(user_id)
150
+ email = getattr(admin_user.user, "email", None)
151
+ except Exception as exc:
152
+ logger.warning("No se pudo resolver email de %s: %s", user_id, exc)
153
+
154
+ profile = (
155
+ supabase_admin.table("profiles")
156
+ .select("preferred_language")
157
+ .eq("id", user_id)
158
+ .maybe_single()
159
+ .execute()
160
+ )
161
+ language = (profile.data or {}).get("preferred_language") or "en"
162
+ return email, language
163
+
164
+
165
+ async def _notify_change(user_id: str, tier: str, direction: str):
166
+ email, language = _get_user_email_and_language(user_id)
167
+ if not email:
168
+ return
169
+ if direction == "upgrade":
170
+ await send_subscription_upgrade_email(email, tier, language)
171
+ else:
172
+ await send_subscription_downgrade_email(email, tier, language)
173
+
174
+
175
+ async def _notify_cancel_scheduled(user_id: str):
176
+ email, language = _get_user_email_and_language(user_id)
177
+ if email:
178
+ await send_subscription_downgrade_email(email, "FREE", language)
179
+
180
+
181
+ async def _notify_cancel_final(user_id: str):
182
+ email, language = _get_user_email_and_language(user_id)
183
+ if email:
184
+ await send_subscription_cancel_email(email, language)
185
+
186
+
187
+ def _schedule_downgrade(subscription_id: str, new_price_id: str):
188
+ """Downgrade a un plan pago inferior (ej. ULTRA -> PRO): SubscriptionSchedule
189
+ con 2 fases -- la actual (sin tocar) y una nueva que arranca justo cuando
190
+ termina el ciclo vigente. Sin prorrateo, sin reembolso parcial.
191
+
192
+ Root cause real del 400 "Received unknown parameter: phases[iterations]":
193
+ Stripe removió `iterations` de phases en subscription_schedules a partir
194
+ de la versión de API 'Clover' (2025-09-30), reemplazándolo por `duration`
195
+ (ver changelog: "Removes iterations parameter for subscription schedules").
196
+ Cualquier cuenta en esa versión de API o posterior rechaza `iterations`
197
+ de plano. `duration` se ancla al intervalo de facturación real del price
198
+ destino (no se asume 'month' a ciegas -- rompería planes anuales)."""
199
+ schedule = stripe.SubscriptionSchedule.create(from_subscription=subscription_id)
200
+ schedule_dict: dict = _stripe_object_to_dict(schedule)
201
+ current_phase = schedule_dict["phases"][0]
202
+
203
+ new_price_dict: dict = _stripe_object_to_dict(stripe.Price.retrieve(new_price_id))
204
+ recurring = new_price_dict.get("recurring") or {}
205
+ duration_interval = recurring.get("interval") or "month"
206
+ duration_interval_count = recurring.get("interval_count") or 1
207
+
208
+ stripe.SubscriptionSchedule.modify(
209
+ schedule_dict["id"],
210
+ # Explícito (no queda a un default implícito de Stripe): al terminar
211
+ # la fase 2, el schedule se libera y la suscripción sigue renovando
212
+ # normalmente con el price nuevo -- consistente con "downgrade
213
+ # permanente", no una promo temporal de 1 ciclo.
214
+ end_behavior="release",
215
+ phases=[
216
+ {
217
+ "items": [
218
+ {"price": item["price"], "quantity": item.get("quantity", 1)}
219
+ for item in current_phase["items"]
220
+ ],
221
+ "start_date": current_phase["start_date"],
222
+ "end_date": current_phase["end_date"],
223
+ },
224
+ {
225
+ "items": [{"price": new_price_id, "quantity": 1}],
226
+ "duration": {
227
+ "interval": duration_interval,
228
+ "interval_count": duration_interval_count,
229
+ },
230
+ },
231
+ ],
232
+ )
233
+
234
+
235
+ @router.post("/checkout")
236
+ async def create_checkout_session(
237
+ plan: str = Query(..., description="Escribe 'pro' o 'ultra'"),
238
+ current_user: AuthenticatedUser = Depends(get_current_user),
239
+ ):
240
+ plan_key = plan.lower()
241
+ price_id = PRICE_MAP.get(plan_key)
242
+ if not price_id:
243
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, "Plan inválido. Usa 'pro' o 'ultra'.")
244
+
245
+ # Checkout SOLO para alta nueva (usuario sin suscripción activa). Si ya
246
+ # tiene una, upgrade/downgrade/cancelación van por /change-plan -- nunca
247
+ # por acá, o se duplicaría la suscripción en Stripe.
248
+ existing = (
249
+ supabase_admin.table("profiles")
250
+ .select("stripe_subscription_id")
251
+ .eq("id", current_user.id)
252
+ .maybe_single()
253
+ .execute()
254
+ )
255
+ if existing.data and existing.data.get("stripe_subscription_id"):
256
+ raise HTTPException(status.HTTP_409_CONFLICT, "Ya tenés una suscripción activa. Usa /change-plan.")
257
+
258
+ try:
259
+ session = stripe.checkout.Session.create(
260
+ mode="subscription",
261
+ line_items=[{"price": price_id, "quantity": 1}],
262
+ client_reference_id=current_user.id,
263
+ customer_email=current_user.email,
264
+ metadata={"user_id": current_user.id, "target_tier": plan_key.upper()},
265
+ # subscription_data.metadata es la ÚNICA forma de que el metadata
266
+ # sobreviva al objeto Subscription (el de Session no se copia solo).
267
+ subscription_data={"metadata": {"user_id": current_user.id, "target_tier": plan_key.upper()}},
268
+ success_url=settings.STRIPE_SUCCESS_URL,
269
+ cancel_url=settings.STRIPE_CANCEL_URL,
270
+ )
271
+ except stripe.error.StripeError as e:
272
+ logger.warning("StripeError en checkout (user=%s, plan=%s): %s", current_user.id, plan_key, e)
273
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e))
274
+ except Exception as exc:
275
+ logger.error("Fallo inesperado en checkout (user=%s, plan=%s): %s", current_user.id, plan_key, exc, exc_info=True)
276
+ raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Error interno al crear la sesión de pago.")
277
+
278
+ return {"checkout_url": session.url}
279
+
280
+
281
+ class ChangePlanRequest(BaseModel):
282
+ target_tier: str # "free" | "pro" | "ultra"
283
+
284
+
285
+ class ChangePlanResponse(BaseModel):
286
+ """Respuesta fuertemente tipada para que el frontend SPA sepa exactamente
287
+ qué pasó y, si corresponde, a dónde debe empujar el router -- en vez de
288
+ inferirlo de un mensaje genérico de texto."""
289
+
290
+ status: str # "scheduled" | "processing"
291
+ message: str
292
+ pending_tier: str | None = None
293
+ current_period_end: str | None = None
294
+ redirect_url: str | None = None # ej. "/cancel" -- None cuando no aplica
295
+
296
+
297
+ @router.post("/change-plan", response_model=ChangePlanResponse)
298
+ async def change_plan(
299
+ # No existe un endpoint /cancel-plan separado: la cancelación es
300
+ # target_tier="free" acá mismo (rama cancel_at_period_end más abajo).
301
+ # El redirect_url="/cancel" se setea únicamente en esa rama.
302
+ payload: ChangePlanRequest,
303
+ current_user: AuthenticatedUser = Depends(get_current_user),
304
+ ):
305
+ target = payload.target_tier.lower()
306
+ if target not in ("free", "pro", "ultra"):
307
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, "target_tier debe ser 'free', 'pro' o 'ultra'.")
308
+
309
+ profile = (
310
+ supabase_admin.table("profiles")
311
+ .select("subscription_tier, stripe_subscription_id")
312
+ .eq("id", current_user.id)
313
+ .maybe_single()
314
+ .execute()
315
+ )
316
+ if not profile.data or not profile.data.get("stripe_subscription_id"):
317
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, "No hay suscripción activa para modificar. Usa /checkout.")
318
+
319
+ subscription_id = profile.data["stripe_subscription_id"]
320
+ current_tier = profile.data.get("subscription_tier", "FREE")
321
+ target_upper = target.upper()
322
+
323
+ if target_upper == current_tier:
324
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, "Ya estás en ese plan.")
325
+
326
+ try:
327
+ subscription = stripe.Subscription.retrieve(subscription_id)
328
+ # Normalización única a dict -- misma causa raíz que el webhook:
329
+ # StripeObject en SDK v12+ no garantiza .get() en accesos anidados.
330
+ sub_dict: dict = _stripe_object_to_dict(subscription)
331
+
332
+ # The Breaker: si la sub está attached a un schedule (de un downgrade
333
+ # previo, ej. Ultra->Pro programado), liberarlo ANTES de tocar items
334
+ # o cancel_at_period_end -- si no, tanto el modify() de abajo como
335
+ # _schedule_downgrade() (que crea un schedule nuevo) rechazan con 400.
336
+ _release_schedule_if_attached(sub_dict, subscription_id)
337
+
338
+ items = sub_dict.get("items", {}).get("data", [])
339
+ if not items:
340
+ logger.error("Suscripción %s sin items al ejecutar change-plan", subscription_id)
341
+ raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Suscripción inconsistente en Stripe.")
342
+ item_id = items[0]["id"]
343
+
344
+ # Fail-fast: extrae y valida current_period_end ANTES de escribir en
345
+ # Supabase (ver _extract_period_end para la causa raíz real: Stripe
346
+ # API 'Basil' 2025-03-31+ movió este campo a items.data[0]).
347
+ period_end_iso = _require_period_end_iso(sub_dict, subscription_id)
348
+
349
+ if target == "free":
350
+ # Cancelación total: sigue con el plan actual hasta fin de ciclo.
351
+ # subscription_tier real lo pisa el webhook (.deleted), esto solo
352
+ # deja constancia visible para el frontend.
353
+ stripe.Subscription.modify(subscription_id, cancel_at_period_end=True)
354
+ supabase_admin.table("profiles").update({
355
+ "pending_tier": "FREE",
356
+ "cancel_at_period_end": True,
357
+ "current_period_end": period_end_iso,
358
+ }).eq("id", current_user.id).execute()
359
+ return ChangePlanResponse(
360
+ status="scheduled",
361
+ message=f"Tu suscripción se cancelará el {period_end_iso}. Hasta entonces seguís con acceso.",
362
+ pending_tier="free",
363
+ current_period_end=period_end_iso,
364
+ redirect_url="/cancel", # instrucción explícita de ruteo para el SPA
365
+ )
366
+
367
+ if TIER_RANK[target_upper] > TIER_RANK[current_tier]:
368
+ # Upgrade in-place (Pro -> Ultra): inmediato, con prorrateo.
369
+ stripe.Subscription.modify(
370
+ subscription_id,
371
+ items=[{"id": item_id, "price": PRICE_MAP[target]}],
372
+ proration_behavior="always_invoice",
373
+ cancel_at_period_end=False,
374
+ )
375
+ # subscription_tier lo confirma el webhook; no hay ruteo especial acá.
376
+ return ChangePlanResponse(
377
+ status="processing",
378
+ message=f"Tu plan se está actualizando a {target_upper}.",
379
+ )
380
+
381
+ # Downgrade a un plan pago inferior (Ultra -> Pro): programado.
382
+ _schedule_downgrade(subscription_id, PRICE_MAP[target])
383
+ supabase_admin.table("profiles").update({
384
+ "pending_tier": target_upper,
385
+ "current_period_end": period_end_iso,
386
+ }).eq("id", current_user.id).execute()
387
+ return ChangePlanResponse(
388
+ status="scheduled",
389
+ message=f"Tu plan bajará a {target_upper} el {period_end_iso}.",
390
+ pending_tier=target,
391
+ current_period_end=period_end_iso,
392
+ )
393
+
394
+ except stripe.error.StripeError as e:
395
+ logger.warning("StripeError en change-plan (user=%s, sub=%s): %s", current_user.id, subscription_id, e)
396
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e))
397
+ except HTTPException:
398
+ raise
399
+ except Exception as exc:
400
+ logger.error(
401
+ "Fallo inesperado en change-plan (user=%s, sub=%s): %s",
402
+ current_user.id, subscription_id, exc, exc_info=True,
403
+ )
404
+ raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Error interno al modificar la suscripción.")
405
+
406
+
407
+ @router.get("/subscription")
408
+ async def get_subscription_status(current_user: AuthenticatedUser = Depends(get_current_user)):
409
+ profile = (
410
+ supabase_admin.table("profiles")
411
+ .select("subscription_tier, pending_tier, cancel_at_period_end, current_period_end")
412
+ .eq("id", current_user.id)
413
+ .maybe_single()
414
+ .execute()
415
+ )
416
+ data = profile.data or {}
417
+ pending = data.get("pending_tier")
418
+ return {
419
+ "subscription_tier": (data.get("subscription_tier") or "FREE").lower(),
420
+ "pending_tier": pending.lower() if pending else None,
421
+ "cancel_at_period_end": bool(data.get("cancel_at_period_end")),
422
+ "current_period_end": data.get("current_period_end"),
423
+ }
424
+
425
+
426
+ @router.post("/webhook")
427
+ async def stripe_webhook(request: Request, background_tasks: BackgroundTasks):
428
+ payload = await request.body()
429
+ sig_header = request.headers.get("stripe-signature")
430
+ endpoint_secret = settings.STRIPE_WEBHOOK_SECRET
431
+
432
+ try:
433
+ event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
434
+ except (ValueError, stripe.error.SignatureVerificationError) as exc:
435
+ logger.warning("Webhook rechazado (firma/payload inválido): %s", exc)
436
+ raise HTTPException(status.HTTP_400_BAD_REQUEST, "Webhook inválido")
437
+
438
+ # Normalización única a dict nativo -- de acá en más TODO acceso usa
439
+ # .get()/[] de dict estándar.
440
+ event_dict: dict = _stripe_object_to_dict(event)
441
+ event_type: str = event_dict.get("type", "")
442
+ event_id: str = event_dict.get("id", "unknown")
443
+ data: dict = event_dict.get("data") or {}
444
+ obj: dict = data.get("object") or {}
445
+ previous: dict = data.get("previous_attributes") or {}
446
+
447
+ try:
448
+ if event_type == "checkout.session.completed":
449
+ user_id = obj.get("metadata", {}).get("user_id")
450
+ target_tier = obj.get("metadata", {}).get("target_tier", "PRO")
451
+ if user_id:
452
+ supabase_admin.table("profiles").update({
453
+ "subscription_tier": target_tier,
454
+ "stripe_customer_id": obj.get("customer"),
455
+ "stripe_subscription_id": obj.get("subscription"),
456
+ "cancel_at_period_end": False,
457
+ "pending_tier": None,
458
+ }).eq("id", user_id).execute()
459
+ background_tasks.add_task(_notify_change, user_id, target_tier, "upgrade")
460
+
461
+ elif event_type == "customer.subscription.updated":
462
+ subscription_id = obj.get("id")
463
+ profile = (
464
+ supabase_admin.table("profiles")
465
+ .select("id, subscription_tier")
466
+ .eq("stripe_subscription_id", subscription_id)
467
+ .maybe_single()
468
+ .execute()
469
+ )
470
+ if profile.data:
471
+ user_id = profile.data["id"]
472
+ current_tier_db = profile.data.get("subscription_tier", "FREE")
473
+ cancel_at_period_end = obj.get("cancel_at_period_end", False)
474
+ items = obj.get("items", {}).get("data", [])
475
+ price_id = items[0]["price"]["id"] if items else None
476
+ new_tier = TIER_BY_PRICE.get(price_id)
477
+
478
+ if "cancel_at_period_end" in previous and cancel_at_period_end:
479
+ # Cancelación total recién programada (paid -> FREE a fin
480
+ # de ciclo). NO tocar subscription_tier -- eso lo hace
481
+ # .deleted.
482
+ # Mismo fix que change-plan: current_period_end puede
483
+ # vivir en items.data[0] (Stripe API 'Basil' 2025-03-31+)
484
+ # en vez del nivel superior de `obj`.
485
+ update_payload: dict = {
486
+ "cancel_at_period_end": True,
487
+ "pending_tier": "FREE",
488
+ }
489
+ period_end_ts = _extract_period_end(obj)
490
+ if period_end_ts is not None:
491
+ update_payload["current_period_end"] = _ts_to_iso(period_end_ts)
492
+ else:
493
+ # No se crashea el webhook por esto (Stripe reintentaría
494
+ # indefinidamente si el campo nunca llega): se omite el
495
+ # campo en vez de mandar null y violar la constraint
496
+ # NOT NULL, y se deja rastro en logs para investigar.
497
+ logger.error(
498
+ "customer.subscription.updated (sub=%s): current_period_end no disponible "
499
+ "ni en items[0] ni en el nivel superior; se omite el campo en el update.",
500
+ subscription_id,
501
+ )
502
+ supabase_admin.table("profiles").update(update_payload).eq("id", user_id).execute()
503
+ background_tasks.add_task(_notify_cancel_scheduled, user_id)
504
+
505
+ elif new_tier and new_tier != current_tier_db and not cancel_at_period_end:
506
+ # Precio ya efectivo: upgrade inmediato (Pro->Ultra) o
507
+ # release automático de un SubscriptionSchedule (fase 2 de
508
+ # un downgrade Ultra->Pro activándose al fin del ciclo
509
+ # anterior).
510
+ direction = "upgrade" if TIER_RANK[new_tier] > TIER_RANK[current_tier_db] else "downgrade"
511
+ supabase_admin.table("profiles").update({
512
+ "subscription_tier": new_tier,
513
+ "pending_tier": None,
514
+ "cancel_at_period_end": False,
515
+ }).eq("id", user_id).execute()
516
+ background_tasks.add_task(_notify_change, user_id, new_tier, direction)
517
+
518
+ elif event_type == "customer.subscription.deleted":
519
+ subscription_id = obj.get("id")
520
+ profile = (
521
+ supabase_admin.table("profiles")
522
+ .select("id")
523
+ .eq("stripe_subscription_id", subscription_id)
524
+ .maybe_single()
525
+ .execute()
526
+ )
527
+ if profile.data:
528
+ user_id = profile.data["id"]
529
+ supabase_admin.table("profiles").update({
530
+ "subscription_tier": "FREE",
531
+ "pending_tier": None,
532
+ "cancel_at_period_end": False,
533
+ "stripe_subscription_id": None,
534
+ }).eq("id", user_id).execute()
535
+ background_tasks.add_task(_notify_cancel_final, user_id)
536
+
537
+ else:
538
+ logger.info("Evento Stripe no manejado: %s (id=%s)", event_type, event_id)
539
+
540
+ except Exception as exc:
541
+ # Cualquier fallo real de procesamiento (Supabase, KeyError, etc.)
542
+ # devuelve 500 para que Stripe reintente -- nunca un AttributeError
543
+ # crudo ni un 200 silencioso que enmascare el fallo.
544
+ logger.error(
545
+ "Error procesando webhook %s (id=%s): %s", event_type, event_id, exc, exc_info=True
546
+ )
547
+ raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, "Error interno procesando el evento")
548
+
549
+ return {"status": "success"}
api/quanti_chat.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api/quanti_chat.py
2
+ import io
3
+ import json
4
+
5
+ import pandas as pd
6
+ from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
7
+ from fastapi.responses import StreamingResponse
8
+ from pydantic import BaseModel
9
+
10
+ from core.security import AuthenticatedUser, get_current_user
11
+ from core.quota_manager import verify_quota
12
+ from core.supabase_client import supabase_admin as supabase
13
+ from services.quanti_engine import (
14
+ QUANTI_CHAT_FALLBACK,
15
+ describe_llm_failure,
16
+ is_llm_connection_failure,
17
+ sanitize_llm_output,
18
+ stream_quanti_chat_completion,
19
+ )
20
+
21
+ router = APIRouter(prefix="/api/v1/quanti/chat", tags=["quanti-chat"])
22
+
23
+ MAX_FILE_BYTES = 5 * 1024 * 1024 # 5 MB
24
+ HISTORY_TURNS = 6
25
+ TITLE_MAX_LEN = 48
26
+
27
+ 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.
28
+
29
+ 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).
30
+
31
+ 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.
32
+
33
+ Classify every user message into ONE of these 4 categories and respond accordingly:
34
+
35
+ 1) GREETING OR QUESTION ABOUT YOURSELF ("hi", "good morning", "what are you?", "what can you do?", thanks, farewells):
36
+ 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.
37
+
38
+ 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):
39
+ 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:
40
+ - 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.
41
+ - Direct them to the "Strategy Parameters" panel on the terminal's side panel.
42
+ - Tell them to enter their exact capital in their desired currency.
43
+ - 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.
44
+ - Close with confident, concierge-grade phrasing that frames this as superior service, not a deflection.
45
+ 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.
46
+
47
+ 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:
48
+ 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.
49
+
50
+ 4) OUT OF SCOPE (general knowledge, jokes, programming unrelated to KodaQuant, everyday topics, anything unrelated to finance):
51
+ 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."
52
+
53
+ 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."""
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # Utilidades de archivo (pandas)
58
+ # ---------------------------------------------------------------------------
59
+
60
+ def _read_tabular_file(filename: str, raw_bytes: bytes) -> pd.DataFrame:
61
+ buf = io.BytesIO(raw_bytes)
62
+ lower = (filename or "").lower()
63
+ if lower.endswith(".csv"):
64
+ return pd.read_csv(buf)
65
+ if lower.endswith((".xlsx", ".xls")):
66
+ return pd.read_excel(buf)
67
+ raise ValueError("Formato no soportado. Usa .csv o .xlsx.")
68
+
69
+
70
+ def _summarize_dataframe(df: pd.DataFrame, max_cols: int = 8) -> str:
71
+ numeric_df = df.select_dtypes(include="number")
72
+ if numeric_df.empty:
73
+ return "Archivo sin columnas numéricas detectables."
74
+
75
+ lines = [f"Filas: {len(df)} | Columnas numéricas: {len(numeric_df.columns)}"]
76
+ for col in list(numeric_df.columns)[:max_cols]:
77
+ series = numeric_df[col].dropna()
78
+ if series.empty:
79
+ continue
80
+ first, last = float(series.iloc[0]), float(series.iloc[-1])
81
+ pct_change = ((last - first) / first * 100) if first != 0 else 0.0
82
+ trend = "alcista" if last > first else ("bajista" if last < first else "plano")
83
+ lines.append(
84
+ f"{col}: media={series.mean():.4f} | desv.std={series.std(ddof=0):.4f} | "
85
+ f"tendencia={trend} ({pct_change:+.2f}%) | min={series.min():.4f} | max={series.max():.4f}"
86
+ )
87
+ return "\n".join(lines)
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Ownership guard
92
+ # ---------------------------------------------------------------------------
93
+
94
+ def _verify_thread_ownership(thread_id: str, user_id: str) -> None:
95
+ """
96
+ `maybe_single().execute()` puede devolver `None` DIRECTAMENTE (no un
97
+ objeto con `.data = None`) cuando la query no matchea ninguna fila —
98
+ comportamiento conocido de ciertas versiones de supabase-py/postgrest-py.
99
+ Evaluar `.data` sobre eso revienta con AttributeError antes de llegar al
100
+ chequeo de negocio. Se blinda en 2 capas: try/except por si el cliente
101
+ lanza en vez de devolver None, y `getattr` en vez de acceso directo.
102
+
103
+ NOTA: `supabase` acá es el cliente SERVICE ROLE (ver import arriba) —
104
+ bypassea RLS por completo, así que este filtro por user_id es la ÚNICA
105
+ barrera de autorización real. No se puede quitar ni relajar.
106
+ """
107
+ try:
108
+ owned = (
109
+ supabase.table("chat_threads")
110
+ .select("id")
111
+ .eq("id", thread_id)
112
+ .eq("user_id", user_id)
113
+ .maybe_single()
114
+ .execute()
115
+ )
116
+ except Exception as exc: # noqa: BLE001
117
+ raise HTTPException(
118
+ status_code=status.HTTP_403_FORBIDDEN,
119
+ detail="Acceso denegado o hilo no encontrado.",
120
+ ) from exc
121
+
122
+ if owned is None or not getattr(owned, "data", None):
123
+ raise HTTPException(
124
+ status_code=status.HTTP_403_FORBIDDEN,
125
+ detail="Acceso denegado o hilo no encontrado.",
126
+ )
127
+
128
+ class ThreadPinUpdate(BaseModel):
129
+ pinned: bool
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Endpoints
133
+ # ---------------------------------------------------------------------------
134
+
135
+ @router.get("/threads")
136
+ async def list_threads(current_user: AuthenticatedUser = Depends(get_current_user)):
137
+ result = (
138
+ supabase.table("chat_threads")
139
+ .select("id, title, pinned, created_at")
140
+ .eq("user_id", current_user.id)
141
+ .is_("deleted_at", "null")
142
+ .order("created_at", desc=True)
143
+ .execute()
144
+ )
145
+ return {"threads": result.data or []}
146
+
147
+
148
+ @router.get("/threads/{thread_id}/messages")
149
+ async def get_thread_messages(
150
+ thread_id: str,
151
+ current_user: AuthenticatedUser = Depends(get_current_user),
152
+ ):
153
+ _verify_thread_ownership(thread_id, current_user.id)
154
+
155
+ result = (
156
+ supabase.table("chat_messages")
157
+ .select("id, role, content, created_at")
158
+ .eq("thread_id", thread_id)
159
+ .order("created_at", desc=False)
160
+ .execute()
161
+ )
162
+ return {"messages": result.data or []}
163
+
164
+ # ── PATCH /api/v1/quanti/chat/threads/{thread_id} ───────────────────────────
165
+ @router.patch("/threads/{thread_id}")
166
+ async def update_thread_pin(
167
+ thread_id: str,
168
+ payload: ThreadPinUpdate,
169
+ current_user: AuthenticatedUser = Depends(get_current_user),
170
+ ):
171
+ _verify_thread_ownership(thread_id, current_user.id)
172
+
173
+ try:
174
+ result = (
175
+ supabase.table("chat_threads")
176
+ .update({"pinned": payload.pinned})
177
+ .eq("id", thread_id)
178
+ .eq("user_id", current_user.id)
179
+ .execute()
180
+ )
181
+ except Exception as exc: # noqa: BLE001
182
+ raise HTTPException(
183
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
184
+ detail="No se pudo actualizar el hilo.",
185
+ ) from exc
186
+
187
+ if not result.data:
188
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Hilo no encontrado.")
189
+
190
+ return {"thread": result.data[0]}
191
+
192
+
193
+ # ── DELETE /api/v1/quanti/chat/threads/{thread_id} (hard delete) ───────────
194
+ @router.delete("/threads/{thread_id}")
195
+ async def delete_thread(
196
+ thread_id: str,
197
+ current_user: AuthenticatedUser = Depends(get_current_user),
198
+ ):
199
+ _verify_thread_ownership(thread_id, current_user.id)
200
+
201
+ try:
202
+ # Cascade manual: si la FK chat_messages.thread_id no tiene
203
+ # ON DELETE CASCADE en el schema de Supabase, este borrado
204
+ # explícito es obligatorio para no dejar mensajes huérfanos.
205
+ supabase.table("chat_messages").delete().eq("thread_id", thread_id).execute()
206
+ result = (
207
+ supabase.table("chat_threads")
208
+ .delete()
209
+ .eq("id", thread_id)
210
+ .eq("user_id", current_user.id)
211
+ .execute()
212
+ )
213
+ except Exception as exc: # noqa: BLE001
214
+ raise HTTPException(
215
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
216
+ detail="No se pudo eliminar el hilo.",
217
+ ) from exc
218
+
219
+ if not result.data:
220
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Hilo no encontrado.")
221
+
222
+ return {"deleted": True}
223
+
224
+ def _persist_chat_turn(thread_id: str, prompt: str, reply: str) -> None:
225
+ supabase.table("chat_messages").insert(
226
+ [
227
+ {"thread_id": thread_id, "role": "user", "content": prompt},
228
+ {"thread_id": thread_id, "role": "assistant", "content": reply},
229
+ ]
230
+ ).execute()
231
+
232
+
233
+ async def _chat_sse_generator(thread_id: str, prompt: str, llm_messages: list[dict]):
234
+ """
235
+ Generador SSE del turno de chat. Contrato:
236
+ data: {"type":"thread","thread_id":"..."}\\n\\n (1 vez, al inicio)
237
+ data: {"type":"token","text":"..."}\\n\\n (N veces, deltas del LLM)
238
+ data: {"type":"done"}\\n\\n (cierre, siempre se emite)
239
+
240
+ Circuit Breaker: el motor (stream_quanti_chat_completion) corre con
241
+ read timeout=None, así que una generación larga NUNCA dispara esta
242
+ rama por sí sola — solo un fallo real de conexión al servidor GGUF
243
+ (is_llm_connection_failure) o un error inesperado del transporte cae
244
+ acá. En cualquier caso, la respuesta HTTP ya salió en 200 (SSE), así
245
+ que degradamos con un evento 'token' de fallback + 'done' en vez de
246
+ intentar levantar un status code a esta altura.
247
+ """
248
+ yield f"data: {json.dumps({'type': 'thread', 'thread_id': thread_id})}\n\n"
249
+
250
+ full_text = ""
251
+ try:
252
+ async for delta in stream_quanti_chat_completion(llm_messages):
253
+ full_text += delta
254
+ yield f"data: {json.dumps({'type': 'token', 'text': delta})}\n\n"
255
+ except Exception as exc: # noqa: BLE001
256
+ if is_llm_connection_failure(exc):
257
+ print(f"⚠️ Circuit Breaker activado — servidor GGUF inalcanzable (Quanti Chat stream): {describe_llm_failure(exc)}")
258
+ else:
259
+ print(f"⚠️ Fallo no-conexión en Quanti Chat stream (no se enmascara como servidor caído): {describe_llm_failure(exc)}")
260
+ full_text = QUANTI_CHAT_FALLBACK
261
+ yield f"data: {json.dumps({'type': 'token', 'text': full_text})}\n\n"
262
+
263
+ sanitized = sanitize_llm_output(full_text)
264
+ reply = sanitized[0] if sanitized else QUANTI_CHAT_FALLBACK
265
+
266
+ try:
267
+ _persist_chat_turn(thread_id, prompt, reply)
268
+ except Exception as exc: # noqa: BLE001
269
+ # El stream ya se le entregó al usuario completo — un fallo de
270
+ # persistencia acá no debe convertirse en un error HTTP a esta
271
+ # altura, pero sí queda logueado para no perderlo en silencio.
272
+ print(f"⚠️ No se pudo persistir el turno de chat (thread_id={thread_id}): {exc}")
273
+
274
+ yield f"data: {json.dumps({'type': 'done'})}\n\n"
275
+
276
+
277
+ @router.post("")
278
+ async def send_message(
279
+ prompt: str = Form(...),
280
+ thread_id: str | None = Form(None),
281
+ file: UploadFile | None = File(None),
282
+ # verify_quota("chat") ya envuelve get_current_user: valida cuota Y
283
+ # devuelve el AuthenticatedUser en una sola dependencia.
284
+ current_user: AuthenticatedUser = Depends(verify_quota("chat")),
285
+ ):
286
+ prompt = prompt.strip()
287
+ if not prompt:
288
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="El mensaje no puede estar vacío.")
289
+
290
+ # --- Resolver / crear hilo, validando ownership ---
291
+ if thread_id:
292
+ _verify_thread_ownership(thread_id, current_user.id)
293
+ else:
294
+ title = prompt[:TITLE_MAX_LEN] + ("…" if len(prompt) > TITLE_MAX_LEN else "")
295
+ created = (
296
+ supabase.table("chat_threads")
297
+ .insert({"user_id": current_user.id, "title": title})
298
+ .execute()
299
+ )
300
+ thread_id = created.data[0]["id"]
301
+
302
+ # --- Contexto de archivo adjunto (opcional) ---
303
+ file_context = ""
304
+ if file is not None:
305
+ raw_bytes = await file.read()
306
+ if len(raw_bytes) > MAX_FILE_BYTES:
307
+ raise HTTPException(
308
+ status_code=status.HTTP_400_BAD_REQUEST,
309
+ detail="Archivo demasiado grande (máx 5MB).",
310
+ )
311
+ try:
312
+ df = _read_tabular_file(file.filename or "", raw_bytes)
313
+ file_context = f"\n\nCONTEXTO DE ARCHIVO ({file.filename}):\n{_summarize_dataframe(df)}"
314
+ except Exception as exc: # noqa: BLE001
315
+ raise HTTPException(
316
+ status_code=status.HTTP_400_BAD_REQUEST,
317
+ detail=f"No se pudo procesar el archivo: {exc}",
318
+ )
319
+
320
+ # --- Historial reciente (últimos HISTORY_TURNS mensajes del hilo) ---
321
+ history_result = (
322
+ supabase.table("chat_messages")
323
+ .select("role, content")
324
+ .eq("thread_id", thread_id)
325
+ .order("created_at", desc=True)
326
+ .limit(HISTORY_TURNS)
327
+ .execute()
328
+ )
329
+ recent_history = list(reversed(history_result.data or []))
330
+
331
+ llm_messages = [{"role": "system", "content": CHAT_SYSTEM_PROMPT}]
332
+ llm_messages.extend({"role": m["role"], "content": m["content"]} for m in recent_history)
333
+ llm_messages.append({"role": "user", "content": prompt + file_context})
334
+
335
+ # Todo lo síncrono (validación, ownership, hilo, archivo, historial) ya
336
+ # corrió arriba y puede seguir devolviendo 400/403 normales. De acá en
337
+ # más la respuesta es 200 (SSE) sin importar qué pase con el LLM local
338
+ # — el Circuit Breaker vive DENTRO del generador, no acá.
339
+ return StreamingResponse(
340
+ _chat_sse_generator(thread_id, prompt, llm_messages),
341
+ media_type="text/event-stream",
342
+ headers={
343
+ "Cache-Control": "no-cache",
344
+ "X-Accel-Buffering": "no", # evita que nginx bufferee el stream
345
+ "Connection": "keep-alive",
346
+ },
347
+ )
api/quota_test_routes.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api/quota_test.py
2
+ from fastapi import APIRouter, Depends
3
+ from core.quota_manager import verify_quota
4
+
5
+ router = APIRouter(prefix="/api", tags=["quota-test"])
6
+
7
+
8
+ @router.post("/test-chat")
9
+ async def test_chat(user=Depends(verify_quota("chat"))):
10
+ return {"msg": "Acceso permitido"}
11
+
12
+
13
+ @router.post("/test-prediction")
14
+ async def test_prediction(user=Depends(verify_quota("prediction"))):
15
+ return {"msg": "Acceso permitido"}
api/support.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api/support.py
2
+ """
3
+ Quanti Support — Nivel 1 (chat IA Tier-1) + Nivel 2 (escalación a humano).
4
+ Router aislado; se monta en main.py vía app.include_router(support_router).
5
+ """
6
+
7
+ import ipaddress
8
+ import time
9
+ import uuid
10
+ from typing import Literal, Optional
11
+
12
+ from fastapi import APIRouter, HTTPException, Request
13
+ from pydantic import BaseModel, Field
14
+
15
+ from core.supabase_client import supabase_admin as _supabase
16
+ from services.quanti_engine import generate_quanti_support_reply, is_support_escalation
17
+
18
+ router = APIRouter(prefix="/api/support", tags=["support"])
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Anti-spam — rate limit en memoria (1 ticket por IP cada 30 minutos). Vive
22
+ # en el proceso: se resetea en cada deploy/restart y NO se comparte entre
23
+ # workers si corres > 1 proceso uvicorn/gunicorn. Migrar a Redis si se
24
+ # escala horizontalmente.
25
+ # ---------------------------------------------------------------------------
26
+ _TICKET_COOLDOWN_SECONDS = 30 * 60
27
+ _last_ticket_by_ip: dict[str, float] = {}
28
+
29
+
30
+ def _get_client_ip(request: Request) -> str:
31
+ """
32
+ request.client.host es la IP de la conexión TCP directa — el cliente NO
33
+ puede falsearla. X-Forwarded-For sí lo controla el cliente en su primer
34
+ salto (spoofing trivial: mandar un header distinto en cada request rota
35
+ el cooldown de 30 min). Por eso ahora es la fuente PRIMARIA, y XFF queda
36
+ como fallback validado (solo si viene un formato de IP válido).
37
+ """
38
+ if request.client and request.client.host:
39
+ return request.client.host
40
+
41
+ forwarded = request.headers.get("x-forwarded-for")
42
+ if forwarded:
43
+ candidate = forwarded.split(",")[0].strip()
44
+ try:
45
+ ipaddress.ip_address(candidate)
46
+ return candidate
47
+ except ValueError:
48
+ pass
49
+
50
+ return "unknown"
51
+
52
+
53
+ def _is_rate_limited(ip: str) -> bool:
54
+ last = _last_ticket_by_ip.get(ip)
55
+ return last is not None and (time.time() - last) < _TICKET_COOLDOWN_SECONDS
56
+
57
+
58
+ def _mark_ticket_sent(ip: str) -> None:
59
+ _last_ticket_by_ip[ip] = time.time()
60
+
61
+
62
+ def _insert_support_ticket(user_ip: str, chat_history: list[dict], user_email: Optional[str]) -> str:
63
+ ticket_id = str(uuid.uuid4())
64
+ _supabase.table("koda_support_tickets").insert({
65
+ "id": ticket_id,
66
+ "user_ip": user_ip,
67
+ "user_email": user_email,
68
+ "chat_history": chat_history,
69
+ "status": "open",
70
+ }).execute()
71
+ return ticket_id
72
+
73
+
74
+ def _send_escalation_email(ticket_id: str, user_email: Optional[str], chat_history: list[dict]) -> None:
75
+ """Placeholder de notificación — listo para smtplib real. Un fallo de
76
+ correo nunca debe tumbar el request; el ticket ya quedó en Supabase."""
77
+ try:
78
+ # import smtplib
79
+ # from email.message import EmailMessage
80
+ # msg = EmailMessage()
81
+ # msg["Subject"] = f"[KodaQuant] Nuevo ticket de soporte #{ticket_id}"
82
+ # msg["From"] = "no-reply@kodaquant.com"
83
+ # msg["To"] = "karim.egure@gmail.com"
84
+ # msg.set_content(f"Ticket {ticket_id}\nEmail usuario: {user_email}\n\n{chat_history}")
85
+ # with smtplib.SMTP(os.getenv("SMTP_HOST"), 587) as server:
86
+ # server.starttls()
87
+ # server.login(os.getenv("SMTP_USER"), os.getenv("SMTP_PASSWORD"))
88
+ # server.send_message(msg)
89
+ print(f"📧 [SIMULADO] Ticket #{ticket_id} → karim.egure@gmail.com | usuario: {user_email}")
90
+ except Exception as exc: # noqa: BLE001
91
+ print(f"⚠️ No se pudo enviar el correo de escalación (ticket #{ticket_id} ya está en BD): {exc}")
92
+
93
+
94
+ _ESCALATION_CONFIRMATION = {
95
+ "en": "Thank you. I've escalated this to Karim Estrada (Administrator) — he'll personally reach out to {email} shortly.",
96
+ "es": "Gracias. Escalé esto con Karim Estrada (Administrador) — se pondrá en contacto contigo a {email} en breve.",
97
+ }
98
+
99
+ _RATE_LIMIT_MESSAGE = {
100
+ "en": "You already have an open ticket. Karim Estrada will reach out shortly — no need to send another request yet.",
101
+ "es": "Ya tienes un ticket abierto. Karim Estrada se pondrá en contacto en breve — no hace falta enviar otra solicitud todavía.",
102
+ }
103
+
104
+
105
+ class SupportChatMessage(BaseModel):
106
+ role: Literal["user", "assistant"]
107
+ content: str
108
+
109
+
110
+ class SupportChatRequest(BaseModel):
111
+ messages: list[SupportChatMessage] = Field(..., min_length=1)
112
+ language: Optional[str] = "en"
113
+ email: Optional[str] = None
114
+
115
+
116
+ @router.post("/chat")
117
+ async def support_chat(payload: SupportChatRequest, request: Request):
118
+ lang = (payload.language or "en").strip().lower()
119
+ lang = lang if lang in ("en", "es") else "en"
120
+
121
+ history = [m.model_dump() for m in payload.messages]
122
+ reply = await generate_quanti_support_reply(history, language=lang)
123
+
124
+ if not is_support_escalation(reply):
125
+ return {"status": "ok", "message": reply}
126
+
127
+ if not payload.email:
128
+ return {"status": "needs_email"}
129
+
130
+ client_ip = _get_client_ip(request)
131
+ if _is_rate_limited(client_ip):
132
+ return {"status": "rate_limited", "message": _RATE_LIMIT_MESSAGE[lang]}
133
+
134
+ try:
135
+ ticket_id = _insert_support_ticket(client_ip, history, payload.email)
136
+ except Exception as exc:
137
+ raise HTTPException(status_code=500, detail=f"Error al crear el ticket de soporte: {exc}")
138
+
139
+ _mark_ticket_sent(client_ip)
140
+ _send_escalation_email(ticket_id, payload.email, history)
141
+
142
+ return {
143
+ "status": "escalated",
144
+ "ticket_id": ticket_id,
145
+ "message": _ESCALATION_CONFIRMATION[lang].format(email=payload.email),
146
+ }
app.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Entrypoint de Hugging Face Spaces (app_file: app.py).
3
+
4
+ ROUND 4 -- FIX del estado zombi "Starting..."/"Building..." permanente en
5
+ el dashboard de HF (ver el bloque de comentarios "RONDA 4" en main.py,
6
+ junto a `_zerogpu_probe`, para la auditoría completa línea a línea contra
7
+ gradio==6.22.0).
8
+
9
+ Resumen: `Server.launch()` (rondas 1-3) invocaba `app.launch()` SIN
10
+ `app_kwargs`. Internamente, `Blocks.launch()` -> `App.create_app()`
11
+ reasigna `app.router.lifespan_context` a partir de
12
+ `app_kwargs.get("lifespan")` — nunca del `lifespan=` pasado al
13
+ constructor `Server(...)` ni de ningún `@app.on_event("startup")`
14
+ registrado antes de `.launch()`. Sin `app_kwargs={"lifespan": lifespan}`
15
+ explícito ACÁ, el hook de arranque real (log de "ASGI startup complete" +
16
+ warm-up del probe de ZeroGPU) queda descartado en silencio — causa raíz
17
+ real de que el hypervisor de HF nunca viera la señal de arranque que
18
+ esperaba y el Space quedara colgado en "Starting...".
19
+
20
+ `main.app` sigue siendo un `gradio.Server` (FastAPI real que ZeroGPU
21
+ reconoce nativamente, ver ROUND 3) — `.launch()` sigue reemplazando al
22
+ `uvicorn.run()` manual, maneja el ciclo de vida completo y detecta el
23
+ entorno de Spaces automáticamente. Lo único que cambia acá es el
24
+ `app_kwargs={"lifespan": lifespan}` explícito.
25
+ """
26
+
27
+ from main import app, lifespan
28
+
29
+ if __name__ == "__main__":
30
+ app.launch(app_kwargs={"lifespan": lifespan})
attention_bilstm_global_best.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4184709375c1506a9436a19ee7242386cc7a5c29b6c28bdc342805daf05a34fa
3
+ size 1612269
cache/news/headlines_AAPL.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_AMZN.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_BTC-USD.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_ETH-USD.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_GOOGL.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_META.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_MSFT.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_NVDA.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_SPY.json ADDED
@@ -0,0 +1 @@
 
 
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}
cache/news/headlines_TSLA.json ADDED
@@ -0,0 +1 @@
 
 
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}
core/__init__.py ADDED
File without changes
core/config.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/config.py
2
+
3
+ from pydantic_settings import BaseSettings, SettingsConfigDict
4
+ from pydantic import field_validator
5
+ from functools import lru_cache
6
+
7
+
8
+ class Settings(BaseSettings):
9
+ """
10
+ Configuración central de KodaQuant Terminal.
11
+ Lee variables de entorno desde el archivo .env en la raíz del proyecto.
12
+ """
13
+
14
+ # --- Supabase ---
15
+ SUPABASE_URL: str
16
+ SUPABASE_KEY: str
17
+ SUPABASE_SERVICE_ROLE_KEY: str
18
+ SUPABASE_JWT_SECRET: str | None = None
19
+
20
+ # --- Stripe ---
21
+ STRIPE_SECRET_KEY: str
22
+ STRIPE_PRICE_PRO: str
23
+ STRIPE_PRICE_ULTRA: str
24
+ STRIPE_WEBHOOK_SECRET: str
25
+ STRIPE_SUCCESS_URL: str
26
+ STRIPE_CANCEL_URL: str
27
+
28
+ # --- Seguridad interna (firma de tokens JWT/HMAC) ---
29
+ API_SECRET_KEY: str
30
+
31
+ # --- Rate limiting anti fuerza bruta (auth) ---
32
+ RATE_LIMIT_MAX_ATTEMPTS: int = 5
33
+ RATE_LIMIT_WINDOW_SECONDS: int = 60
34
+
35
+ # --- Configuración general opcional ---
36
+ APP_NAME: str = "KodaQuant Terminal"
37
+ ENV: str = "development"
38
+ DEBUG: bool = False
39
+
40
+ # FIX DEFINITIVO: dominio kodaquant.site verificado en Resend, sandbox
41
+ # desactivado. Se abandona SMTP directo por completo (bloqueado a nivel
42
+ # de firewall en HF Spaces -- ver historial) a favor del SDK oficial
43
+ # `resend` (ver core/security.py). Las variables SMTP_HOST/PORT/
44
+ # USE_SSL/USER/PASSWORD de las iteraciones anteriores ya no existen acá
45
+ # -- no se usan en ningún lado del código.
46
+ #
47
+ # Techo duro (segundos) para la llamada del SDK de Resend, corrida en
48
+ # thread vía asyncio.to_thread (ver core/security.py::_send_mail_message).
49
+ # El envío corre como FastAPI BackgroundTask -- no bloquea la respuesta
50
+ # al cliente -- así que 15s da margen real sin arriesgar tareas colgadas
51
+ # indefinidamente.
52
+ SMTP_TIMEOUT_SECONDS: float = 15.0
53
+ # API key de Resend (https://resend.com/api-keys). Obligatoria para que
54
+ # el envío de correo funcione -- sin ella, se loguea un warning y el
55
+ # correo simplemente no sale (no rompe el registro/login).
56
+ RESEND_API_KEY: str | None = None
57
+ # Remitente verificado. Dominio kodaquant.site ya validado por DNS en
58
+ # Resend -- puede enviar a cualquier destinatario, no solo al sandbox.
59
+ SMTP_FROM: str = "KodaQuant <no-reply@kodaquant.site>"
60
+ # Si un usuario responde un correo automático, llega acá en vez de a
61
+ # no-reply@kodaquant.site (que nadie lee).
62
+ REPLY_TO_EMAIL: str = "karim.egure@gmail.com"
63
+ FRONTEND_URL: str = "https://kodaquant.site"
64
+
65
+ model_config = SettingsConfigDict(
66
+ env_file=".env",
67
+ env_file_encoding="utf-8",
68
+ case_sensitive=True,
69
+ extra="ignore",
70
+ )
71
+
72
+ # Defensa contra espacios accidentales al pegar valores en .env o en el
73
+ # panel de variables de entorno del hosting (ej. "FRONTEND_URL= https://...").
74
+ # Un espacio colado acá rompe el matching exacto de origen en CORS
75
+ # (Starlette compara el header Origin contra el string tal cual) y
76
+ # generaría URLs rotas en los links de los correos de verificación.
77
+ @field_validator("FRONTEND_URL", "SUPABASE_URL", mode="before")
78
+ @classmethod
79
+ def _strip_whitespace(cls, v: str) -> str:
80
+ return v.strip() if isinstance(v, str) else v
81
+
82
+
83
+ @lru_cache
84
+ def get_settings() -> Settings:
85
+ """
86
+ Devuelve una instancia cacheada de Settings para evitar
87
+ releer el .env en cada request.
88
+ """
89
+ return Settings()
90
+
91
+
92
+ settings = get_settings()
core/quota_manager.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/quota_manager.py
2
+ """
3
+ Aduana de cuotas para KodaQuant Terminal.
4
+ Verifica y consume cuota de servicios (predicciones / chat Quanti) según
5
+ el tier de suscripción, delegando el estado persistente a Supabase.
6
+
7
+ Ciclos:
8
+ - FREE predicciones: reinicio diario (cron externo ya existente,
9
+ fuera del alcance de este módulo).
10
+ - FREE / PRO chat y PRO predicciones: reinicio cada 14 días vía
11
+ `current_period_end` (pg_cron, ver migrations/quota_migration.sql).
12
+ - ULTRA: sin límites, bypass total (no se leen ni consumen contadores).
13
+ """
14
+ from datetime import datetime, timedelta, timezone
15
+ from fastapi import Depends, HTTPException, status
16
+ from postgrest.exceptions import APIError
17
+ from core.security import get_current_user, AuthenticatedUser
18
+ from core.supabase_client import supabase_admin
19
+
20
+ LIMITS = {
21
+ "prediction": {"FREE": 3, "PRO": 50},
22
+ "chat": {"FREE": 1, "PRO": 100},
23
+ }
24
+
25
+ DEFAULT_PROFILE_FIELDS = {
26
+ "subscription_tier": "FREE",
27
+ "api_requests_count": 0,
28
+ "period_predictions_used": 0,
29
+ "quanti_chat_used": 0,
30
+ }
31
+
32
+ # Cada (service_type, tier) apunta a la columna de Supabase que lleva su contador.
33
+ COUNTER_COLUMN = {
34
+ "prediction": {"FREE": "api_requests_count", "PRO": "period_predictions_used"},
35
+ "chat": {"FREE": "quanti_chat_used", "PRO": "quanti_chat_used"},
36
+ }
37
+
38
+ PROFILE_SELECT_FIELDS = (
39
+ "subscription_tier, api_requests_count, period_predictions_used, "
40
+ "quanti_chat_used, current_period_end"
41
+ )
42
+
43
+ # Ventana rodante de 14 días. Aplica a period_predictions_used y
44
+ # quanti_chat_used (PRO predicciones + FREE/PRO chat). NO aplica a
45
+ # api_requests_count (FREE predicciones = reinicio diario, cron externo,
46
+ # fuera del alcance de este módulo).
47
+ QUOTA_PERIOD = timedelta(days=14)
48
+
49
+
50
+ def _parse_utc(value: str | None) -> datetime | None:
51
+ if not value:
52
+ return None
53
+ try:
54
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
55
+ except ValueError:
56
+ return None
57
+ return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
58
+
59
+
60
+ def _format_reset_date(current_period_end: str | None) -> str:
61
+ if not current_period_end:
62
+ return "próximamente"
63
+ try:
64
+ dt = datetime.fromisoformat(current_period_end)
65
+ return dt.strftime("%d/%m/%Y %H:%M UTC")
66
+ except ValueError:
67
+ return "próximamente"
68
+
69
+
70
+ def verify_quota(service_type: str):
71
+ """
72
+ Factory de dependencia FastAPI.
73
+
74
+ Uso:
75
+ @router.post("/predict", dependencies=[Depends(verify_quota("prediction"))])
76
+ async def predict(...): ...
77
+ """
78
+ if service_type not in LIMITS:
79
+ raise ValueError(f"service_type inválido: {service_type!r}")
80
+
81
+ async def _dependency(
82
+ current_user: AuthenticatedUser = Depends(get_current_user),
83
+ ) -> AuthenticatedUser:
84
+ try:
85
+ result = (
86
+ supabase_admin.table("profiles")
87
+ .select(PROFILE_SELECT_FIELDS)
88
+ .eq("id", current_user.id)
89
+ .maybe_single()
90
+ .execute()
91
+ )
92
+ profile = result.data if result else None
93
+ except APIError:
94
+ profile = None
95
+
96
+ if not profile:
97
+ # Sin insert/upsert: evita el 42501 del cliente anon/user-scoped.
98
+ # Se asume perfil FREE con 0 usos; el UPDATE posterior sobre una
99
+ # fila inexistente es un no-op silencioso (no rompe el flujo).
100
+ profile = {"id": current_user.id, **DEFAULT_PROFILE_FIELDS}
101
+
102
+ tier = (profile.get("subscription_tier") or "FREE").upper()
103
+
104
+ # ULTRA: bypass total. Ni siquiera se toca la tabla.
105
+ if tier == "ULTRA":
106
+ return current_user
107
+
108
+ if tier not in LIMITS[service_type]:
109
+ tier = "FREE" # Tier desconocido -> tratar como FREE por seguridad.
110
+
111
+ limit = LIMITS[service_type][tier]
112
+ column = COUNTER_COLUMN[service_type][tier]
113
+ current_count = profile.get(column) or 0
114
+
115
+ # Ventana rodante de 14 días, forzada en Python (no depende solo del
116
+ # pg_cron externo). Si current_period_end no existe o ya venció,
117
+ # se resetea el contador YA, antes de evaluar el límite.
118
+ if column != "api_requests_count":
119
+ period_end = _parse_utc(profile.get("current_period_end"))
120
+ now_utc = datetime.now(timezone.utc)
121
+ if period_end is None or now_utc >= period_end:
122
+ new_period_end = now_utc + QUOTA_PERIOD
123
+ supabase_admin.table("profiles").update(
124
+ {column: 0, "current_period_end": new_period_end.isoformat()}
125
+ ).eq("id", current_user.id).execute()
126
+ current_count = 0
127
+ profile["current_period_end"] = new_period_end.isoformat()
128
+
129
+ if current_count >= limit:
130
+ reset_label = _format_reset_date(profile.get("current_period_end"))
131
+ raise HTTPException(
132
+ status_code=status.HTTP_403_FORBIDDEN,
133
+ detail=f"Límite alcanzado, reinicio en {reset_label}",
134
+ )
135
+
136
+ supabase_admin.table("profiles").update(
137
+ {column: current_count + 1}
138
+ ).eq("id", current_user.id).execute()
139
+
140
+ return current_user
141
+
142
+ return _dependency
core/rate_limiter.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/rate_limiter.py
2
+ """
3
+ Rate limiter en memoria (sliding window) para mitigar fuerza bruta en
4
+ /register y /login. Sin dependencias externas, sin estado compartido entre
5
+ procesos -- válido para un solo worker. Si se escala a múltiples
6
+ workers/instancias, migrar la key a Redis (INCR + EXPIRE) manteniendo la
7
+ misma firma de `enforce_rate_limit`.
8
+ """
9
+ import time
10
+ from collections import defaultdict
11
+ from threading import Lock
12
+
13
+ from fastapi import HTTPException, Request, status
14
+
15
+ from core.config import settings
16
+
17
+ _attempts: dict[str, list[float]] = defaultdict(list)
18
+ _lock = Lock()
19
+
20
+
21
+ def _client_ip(request: Request) -> str:
22
+ forwarded = request.headers.get("x-forwarded-for")
23
+ if forwarded:
24
+ return forwarded.split(",")[0].strip()
25
+ return request.client.host if request.client else "unknown"
26
+
27
+
28
+ async def enforce_rate_limit(request: Request, bucket: str) -> None:
29
+ """Lanza 429 si `bucket:ip` excede el límite en la ventana configurada."""
30
+ key = f"{bucket}:{_client_ip(request)}"
31
+ now = time.time()
32
+ window = settings.RATE_LIMIT_WINDOW_SECONDS
33
+ max_attempts = settings.RATE_LIMIT_MAX_ATTEMPTS
34
+
35
+ with _lock:
36
+ timestamps = [t for t in _attempts[key] if now - t < window]
37
+ if len(timestamps) >= max_attempts:
38
+ retry_after = int(window - (now - timestamps[0]))
39
+ raise HTTPException(
40
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
41
+ detail="Demasiados intentos. Intenta de nuevo más tarde.",
42
+ headers={"Retry-After": str(max(retry_after, 1))},
43
+ )
44
+ timestamps.append(now)
45
+ _attempts[key] = timestamps
core/security.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/security.py
2
+ """
3
+ Autenticación de producción para KodaQuant Terminal.
4
+ Valida el JWT de Supabase delegando la verificación criptográfica al propio
5
+ backend de Supabase Auth (GoTrue) vía `supabase.auth.get_user()`. No existe
6
+ bypass de desarrollo.
7
+ """
8
+ import secrets
9
+ import traceback
10
+ import httpx
11
+ from core.config import settings
12
+ from datetime import datetime, timedelta, timezone
13
+ from fastapi import Depends, HTTPException, Request, status
14
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
15
+ from fastapi.responses import JSONResponse
16
+ from pydantic import BaseModel
17
+ from starlette.middleware.base import BaseHTTPMiddleware
18
+ from core.supabase_client import supabase, supabase_admin
19
+
20
+ # --- CORS: lista cerrada de orígenes de producción ---
21
+ # NUNCA usar "*" aquí: Starlette lo rechaza en runtime cuando
22
+ # allow_credentials=True, y aunque no lo hiciera, "*" + credentials abre la
23
+ # puerta a CSRF cross-origin contra cualquier endpoint autenticado
24
+ # (/api/v1/quanti/consult, /api/v1/auth/*, payments). Solo se listan
25
+ # orígenes explícitos y verificados.
26
+ PRODUCTION_ORIGINS = {
27
+ "https://kodaquant.site", # Firebase Hosting (dominio primario)
28
+ "https://kodaquant.site", # Firebase Hosting (dominio secundario, mismo proyecto)
29
+ }
30
+
31
+ # Puertos reales del dev server (Vite), tomados de la config actual del
32
+ # proyecto -- NO 3000 (eso es el puerto default de Create React App / Next,
33
+ # que este repo no usa). Agregar un origen que nadie sirve no protege nada
34
+ # y agregar uno que falta rompe el login en local.
35
+ _DEV_ORIGINS = {
36
+ "http://localhost:5173", "http://127.0.0.1:5173",
37
+ "http://localhost:5174", "http://127.0.0.1:5174",
38
+ }
39
+
40
+ # Métodos y headers reales que usan los endpoints (fetch/EventSource desde
41
+ # App.jsx + Authorization Bearer del login Supabase). "*" en methods/headers
42
+ # es innecesario aquí y amplía la superficie de ataque sin motivo.
43
+ ALLOWED_METHODS = ["GET", "POST", "OPTIONS"]
44
+ ALLOWED_HEADERS = ["Authorization", "Content-Type"]
45
+
46
+
47
+ def get_allowed_origins() -> list[str]:
48
+ """
49
+ Orígenes permitidos por CORS.
50
+
51
+ - Producción (settings.ENV == "production"): SOLO los dominios de
52
+ Firebase Hosting + settings.FRONTEND_URL. Los orígenes de localhost
53
+ jamás se incluyen en este modo.
54
+ - Cualquier otro valor de settings.ENV (dev/staging): se añaden también
55
+ los orígenes del dev server local.
56
+
57
+ IMPORTANTE: `ENV` en core/config.py tiene default "development". Si el
58
+ deploy de producción no exporta explícitamente ENV=production en su
59
+ entorno, este backend seguirá aceptando peticiones con credenciales
60
+ desde localhost. Confirmar esa variable en la config del servidor
61
+ (Railway/Render/Fly/EC2/lo que uses) -- esto NO es opcional para que el
62
+ lockdown de CORS sea real.
63
+ """
64
+ origins = set(PRODUCTION_ORIGINS)
65
+ if getattr(settings, "FRONTEND_URL", None):
66
+ origins.add(settings.FRONTEND_URL.strip())
67
+
68
+ if settings.ENV.strip().lower() != "production":
69
+ origins |= _DEV_ORIGINS
70
+
71
+ return sorted(origins)
72
+
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # FIX CRÍTICO — CORS bypass real en producción vía gradio.Server
76
+ # ---------------------------------------------------------------------------
77
+ # ROOT CAUSE (confirmado leyendo gradio/route_utils.py::CustomCORSMiddleware
78
+ # en gradio==6.22.0 y reproducido en vivo, no es una hipótesis):
79
+ #
80
+ # Server.launch() -> Blocks.launch() -> App.create_app() SIEMPRE ejecuta
81
+ # app.add_middleware(CustomCORSMiddleware, strict_cors=strict_cors)
82
+ #
83
+ # ...DESPUÉS de que main.py ya agregó nuestro CORSMiddleware. En Starlette,
84
+ # add_middleware() inserta al frente de la pila (`user_middleware.insert(0,
85
+ # ...)`), así que el middleware de Gradio, agregado más tarde (en
86
+ # .launch()), termina SIEMPRE por FUERA del nuestro -- procesa cada
87
+ # request antes que el nuestro y puede reescribir la respuesta después.
88
+ #
89
+ # Su lógica interna (is_valid_origin) SOLO restringe origenes cuando el
90
+ # Host de la request es localhost/127.0.0.1/0.0.0.0 (para proteger demos
91
+ # corriendo en la laptop del dev). En cualquier deploy real -- este caso,
92
+ # *.hf.space -- esa condición nunca aplica, así que Gradio termina
93
+ # agregando `Access-Control-Allow-Origin: <origin que sea>` +
94
+ # `Access-Control-Allow-Credentials: true` a CUALQUIER origen, y además
95
+ # contesta TODO el preflight (OPTIONS) él mismo -- nuestro CORSMiddleware
96
+ # (con su ALLOWED_METHODS/ALLOWED_HEADERS restringido) nunca llega a
97
+ # correr para el preflight. `PRODUCTION_ORIGINS` de arriba queda
98
+ # decorativo en producción. Verificado en vivo: una request con
99
+ # `Origin: https://evil-attacker.com` contra un server con Host no-local
100
+ # recibe `Access-Control-Allow-Origin: https://evil-attacker.com` de
101
+ # vuelta.
102
+ #
103
+ # No hay manera de "ganarle" la posición a Gradio en la pila de
104
+ # middleware -- SIEMPRE se agrega después, en .launch(), sin importar el
105
+ # orden en main.py. La única defensa real es no depender de qué headers
106
+ # CORS termine poniendo esa capa, y en cambio RECHAZAR nosotros mismos,
107
+ # a nivel aplicación, cualquier request de un Origin no reconocido --
108
+ # esto SÍ es efectivo pase lo que pase después en la respuesta, porque el
109
+ # request nunca llega al router si lo cortamos acá.
110
+ #
111
+ # Nota de alcance: como este backend NO usa cookies para auth (el JWT de
112
+ # Supabase viaja en el header Authorization, nunca en una cookie), esto
113
+ # no es un CSRF clásico explotable por un sitio malicioso ajeno -- pero
114
+ # sí anula la protección que el equipo cree tener, y cualquier
115
+ # dependencia futura en cookies o en "Origin como control de acceso"
116
+ # quedaría rota. Corregir de todos modos.
117
+ class StrictOriginMiddleware(BaseHTTPMiddleware):
118
+ """
119
+ Rechaza (403) cualquier request con un header Origin presente que NO
120
+ esté en la lista cerrada de `get_allowed_origins()`. Se evalúa en cada
121
+ request (no cachea la lista), así que respeta el mismo ENV en runtime
122
+ que ve `get_allowed_origins()`.
123
+
124
+ Requests SIN header Origin (curl, llamadas server-to-server, health
125
+ checks del propio hosting) pasan de largo -- Origin solo lo manda un
126
+ navegador haciendo fetch/XHR cross-origin.
127
+ """
128
+
129
+ async def dispatch(self, request: Request, call_next):
130
+ origin = request.headers.get("origin")
131
+ if origin is not None and origin not in set(get_allowed_origins()):
132
+ return JSONResponse(
133
+ {"detail": "Origen no permitido."},
134
+ status_code=status.HTTP_403_FORBIDDEN,
135
+ )
136
+ return await call_next(request)
137
+
138
+
139
+ # auto_error=False es la pieza clave: si el header falta o está mal formado,
140
+ # HTTPBearer devuelve None en lugar de lanzar su propio HTTPException(403).
141
+ # Así TODO el manejo de errores de auth pasa por get_current_user y responde
142
+ # 401 de forma consistente -- nunca más un 403 "silencioso" que evita
143
+ # nuestro try/except.
144
+ security_scheme = HTTPBearer(auto_error=False)
145
+
146
+
147
+ class AuthenticatedUser(BaseModel):
148
+ """Identidad resuelta a partir del usuario verificado por Supabase Auth."""
149
+ id: str
150
+ email: str | None = None
151
+ role: str | None = None
152
+
153
+
154
+ async def get_current_user(
155
+ credentials: HTTPAuthorizationCredentials | None = Depends(security_scheme),
156
+ ) -> AuthenticatedUser:
157
+ if credentials is None or not credentials.credentials:
158
+ print("[AUTH] Falta el header Authorization o no tiene el esquema 'Bearer <token>'.")
159
+ raise HTTPException(
160
+ status_code=status.HTTP_401_UNAUTHORIZED,
161
+ detail="Token inválido o expirado",
162
+ )
163
+
164
+ # credentials.credentials YA es el JWT puro (HTTPBearer separa el esquema
165
+ # "Bearer" del token). Este strip extra es cinturón de seguridad por si
166
+ # el cliente concatena mal el header -- en condiciones normales es un no-op.
167
+ raw_token = credentials.credentials.strip()
168
+ if raw_token.lower().startswith("bearer "):
169
+ raw_token = raw_token[7:].strip()
170
+
171
+ try:
172
+ response = supabase.auth.get_user(raw_token)
173
+ except Exception as exc:
174
+ print(f"Error Supabase: {exc}")
175
+ raise HTTPException(
176
+ status_code=status.HTTP_401_UNAUTHORIZED,
177
+ detail="Token inválido o expirado",
178
+ )
179
+
180
+ user = getattr(response, "user", None)
181
+ if user is None or getattr(user, "id", None) is None:
182
+ raise HTTPException(
183
+ status_code=status.HTTP_401_UNAUTHORIZED,
184
+ detail="Token inválido o expirado",
185
+ )
186
+
187
+ return AuthenticatedUser(
188
+ id=user.id,
189
+ email=getattr(user, "email", None),
190
+ role=getattr(user, "role", None),
191
+ )
192
+
193
+
194
+ async def verify_api_credits(
195
+ current_user: AuthenticatedUser = Depends(get_current_user),
196
+ ) -> AuthenticatedUser:
197
+ result = (
198
+ supabase_admin.table("profiles")
199
+ .select("subscription_tier, api_requests_count")
200
+ .eq("id", current_user.id)
201
+ .single()
202
+ .execute()
203
+ )
204
+ profile = result.data
205
+ if not profile:
206
+ raise HTTPException(
207
+ status_code=status.HTTP_404_NOT_FOUND,
208
+ detail="Perfil no encontrado",
209
+ )
210
+
211
+ tier = profile.get("subscription_tier")
212
+ if tier == "FREE":
213
+ current_count = profile.get("api_requests_count", 0)
214
+ if current_count >= 3:
215
+ raise HTTPException(
216
+ status_code=status.HTTP_403_FORBIDDEN,
217
+ detail="Límite de solicitudes alcanzado para el plan FREE",
218
+ )
219
+ supabase_admin.table("profiles").update(
220
+ {"api_requests_count": current_count + 1}
221
+ ).eq("id", current_user.id).execute()
222
+
223
+ return current_user
224
+
225
+
226
+ # ---------------------------------------------------------------------------
227
+ # FIX DEFINITIVO — SMTP directo abandonado, migrado a API HTTPS (Resend)
228
+ # ---------------------------------------------------------------------------
229
+ # ROOT CAUSE real (confirmado con el traceback del segundo fallo): el
230
+ # TimeoutError NO ocurre en el handshake TLS -- ocurre antes, dentro de
231
+ # `aiosmtplib.smtp._create_connection` -> `asyncio.wait_for(connect_coro)`.
232
+ # Es decir, el `CancelledError`/`TimeoutError` salta al intentar abrir la
233
+ # conexión TCP misma, nunca llega a mandar un solo byte. Con 587 (STARTTLS)
234
+ # colgaba igual y con 465 (SSL implícito, ya corregido en la iteración
235
+ # anterior) cuelga exactamente igual: la variable en común no es el modo
236
+ # TLS, es que Hugging Face Spaces filtra a nivel de firewall de red TODO el
237
+ # egress saliente a puertos SMTP (25/465/587), sin importar el protocolo
238
+ # de arriba. Nada configurable en aiosmtplib arregla un paquete que el
239
+ # hosting nunca deja salir. Los mismos logs lo prueban: las llamadas a
240
+ # Supabase (puerto 443/HTTPS) responden 200 OK sin problema -- 443 es el
241
+ # único puerto saliente garantizado en este entorno.
242
+ #
243
+ # FIX: se abandona SMTP directo por completo y el envío se hace por HTTPS
244
+ # vía la API REST de Resend (https://resend.com) -- mismo patrón que ya usa
245
+ # este backend para hablar con Supabase (httpx sobre 443). Requiere UNA
246
+ # variable nueva: RESEND_API_KEY (ver core/config.py). Pasos de una sola
247
+ # vez en el dashboard de Resend: crear cuenta, verificar el dominio de
248
+ # SMTP_FROM (o usar su dominio de pruebas mientras tanto), generar la API
249
+ # key. Las variables SMTP_HOST/PORT/USER/PASSWORD/USE_SSL quedan sin uso
250
+ # real -- no hace falta borrarlas del .env, simplemente no se leen más acá.
251
+ _RESEND_API_URL = "https://api.resend.com/emails"
252
+
253
+
254
+ async def _send_mail_message(*, to: str, subject: str, html: str, text: str, context: str) -> None:
255
+ """Envía un correo vía la API HTTPS de Resend, con techo duro de
256
+ `settings.SMTP_TIMEOUT_SECONDS`. Pensada para correr como BackgroundTask.
257
+
258
+ Loguea DOS clases de fallo por separado:
259
+ - Errores de red/timeout (DNS, conexión, techo de tiempo agotado).
260
+ - Rechazos de Resend (4xx/5xx) -- acá se imprime `response.text`
261
+ explícitamente porque httpx.HTTPStatusError / raise_for_status() NO
262
+ incluye el cuerpo de la respuesta en su mensaje por defecto, y ese
263
+ cuerpo es justo donde Resend explica el motivo real (dominio del
264
+ remitente sin verificar, restricción de sandbox al propio email de
265
+ la cuenta, API key inválida/revocada, etc.). Sin esto, un 403 se ve
266
+ genérico y no dice nada accionable -- que es exactamente lo que
267
+ pasó en el log anterior."""
268
+ if not settings.RESEND_API_KEY:
269
+ print(f"[WARN] Envío de correo ({context}) omitido: falta RESEND_API_KEY en el entorno.")
270
+ return
271
+
272
+ try:
273
+ async with httpx.AsyncClient(timeout=settings.SMTP_TIMEOUT_SECONDS) as client:
274
+ response = await client.post(
275
+ _RESEND_API_URL,
276
+ headers={"Authorization": f"Bearer {settings.RESEND_API_KEY}"},
277
+ json={
278
+ "from": settings.SMTP_FROM,
279
+ "to": [to],
280
+ "subject": subject,
281
+ "html": html,
282
+ "text": text,
283
+ },
284
+ )
285
+ except Exception as exc:
286
+ print(f"[WARN] Envío de correo ({context}) falló de red/timeout hacia Resend (to={to}): {exc!r}")
287
+ traceback.print_exc()
288
+ return
289
+
290
+ if response.status_code >= 400:
291
+ print(
292
+ f"[WARN] Envío de correo ({context}) rechazado por Resend "
293
+ f"(HTTP {response.status_code}) to={to} from={settings.SMTP_FROM}: {response.text}"
294
+ )
295
+
296
+
297
+ # --- Verificación de email ---
298
+ def generate_verification_token() -> tuple[str, datetime]:
299
+ """Token de verificación, válido 24h."""
300
+ token = secrets.token_urlsafe(32)
301
+ expires_at = datetime.now(timezone.utc) + timedelta(hours=24)
302
+ return token, expires_at
303
+
304
+
305
+ async def send_verification_email(email_to: str, token: str) -> None:
306
+ """Construye y envía el correo de verificación. Diseñada para ser
307
+ agendada como BackgroundTask desde api/auth.py -- nunca debe hacer
308
+ esperar al cliente HTTP (ver _send_mail_message)."""
309
+ verify_url = f"{settings.FRONTEND_URL}/verify?token={token}"
310
+
311
+ html = f"""\
312
+ <html>
313
+ <body style="margin:0;padding:0;background-color:#0a0e14;font-family:'Segoe UI',Arial,sans-serif;">
314
+ <table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 0;background-color:#0a0e14;">
315
+ <tr>
316
+ <td align="center">
317
+ <table width="480" cellpadding="0" cellspacing="0" style="background-color:#10151f;border:1px solid #1f2a37;border-radius:8px;overflow:hidden;">
318
+ <tr>
319
+ <td style="padding:32px;text-align:center;border-bottom:1px solid #1f2a37;">
320
+ <span style="font-size:22px;font-weight:700;color:#00e5c7;letter-spacing:1px;">KODA<span style="color:#e6edf3;">QUANT</span></span>
321
+ </td>
322
+ </tr>
323
+ <tr>
324
+ <td style="padding:32px;color:#c9d1d9;">
325
+ <p style="font-size:15px;line-height:1.6;margin:0 0 20px;">Confirma tu correo electrónico para activar tu cuenta y desbloquear tu Free Tier.</p>
326
+ <table cellpadding="0" cellspacing="0" width="100%">
327
+ <tr>
328
+ <td align="center" style="padding:12px 0 24px;">
329
+ <a href="{verify_url}" style="background-color:#00e5c7;color:#0a0e14;text-decoration:none;font-weight:700;font-size:14px;padding:14px 32px;border-radius:6px;display:inline-block;">
330
+ VERIFICAR CUENTA
331
+ </a>
332
+ </td>
333
+ </tr>
334
+ </table>
335
+ <p style="font-size:12px;line-height:1.5;color:#6e7681;margin:0;">Si el botón no funciona, copia este enlace:<br>
336
+ <a href="{verify_url}" style="color:#00e5c7;word-break:break-all;">{verify_url}</a>
337
+ </p>
338
+ <p style="font-size:12px;color:#6e7681;margin:24px 0 0;">Este enlace expira en 24 horas.</p>
339
+ </td>
340
+ </tr>
341
+ </table>
342
+ </td>
343
+ </tr>
344
+ </table>
345
+ </body>
346
+ </html>
347
+ """
348
+
349
+ await _send_mail_message(
350
+ to=email_to,
351
+ subject="Verifica tu cuenta — KodaQuant Terminal",
352
+ html=html,
353
+ text="Verifica tu cuenta visitando: " + verify_url, # fallback texto plano
354
+ context="verification",
355
+ )
356
+
357
+
358
+ # --- Recuperación de contraseña ---
359
+ def generate_password_reset_token() -> tuple[str, datetime]:
360
+ """Token de restablecimiento de contraseña, válido 60 minutos (más corto
361
+ que el de verificación de email porque habilita una acción sensible)."""
362
+ token = secrets.token_urlsafe(32)
363
+ expires_at = datetime.now(timezone.utc) + timedelta(minutes=60)
364
+ return token, expires_at
365
+
366
+
367
+ async def send_password_reset_email(email_to: str, token: str) -> None:
368
+ """Construye y envía el correo de restablecimiento. Diseñada para ser
369
+ agendada como BackgroundTask desde api/auth.py (ver _send_mail_message)."""
370
+ reset_url = f"{settings.FRONTEND_URL}/update-password?token={token}"
371
+
372
+ html = f"""\
373
+ <html>
374
+ <body style="margin:0;padding:0;background-color:#0a0e14;font-family:'Segoe UI',Arial,sans-serif;">
375
+ <table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 0;background-color:#0a0e14;">
376
+ <tr>
377
+ <td align="center">
378
+ <table width="480" cellpadding="0" cellspacing="0" style="background-color:#10151f;border:1px solid #1f2a37;border-radius:8px;overflow:hidden;">
379
+ <tr>
380
+ <td style="padding:32px;text-align:center;border-bottom:1px solid #1f2a37;">
381
+ <span style="font-size:22px;font-weight:700;color:#00e5c7;letter-spacing:1px;">KODA<span style="color:#e6edf3;">QUANT</span></span>
382
+ </td>
383
+ </tr>
384
+ <tr>
385
+ <td style="padding:32px;color:#c9d1d9;">
386
+ <p style="font-size:15px;line-height:1.6;margin:0 0 20px;">Recibimos una solicitud para restablecer la contraseña de tu cuenta. Si no fuiste tú, ignora este correo.</p>
387
+ <table cellpadding="0" cellspacing="0" width="100%">
388
+ <tr>
389
+ <td align="center" style="padding:12px 0 24px;">
390
+ <a href="{reset_url}" style="background-color:#00e5c7;color:#0a0e14;text-decoration:none;font-weight:700;font-size:14px;padding:14px 32px;border-radius:6px;display:inline-block;">
391
+ RESTABLECER CONTRASEÑA
392
+ </a>
393
+ </td>
394
+ </tr>
395
+ </table>
396
+ <p style="font-size:12px;line-height:1.5;color:#6e7681;margin:0;">Si el botón no funciona, copia este enlace:<br>
397
+ <a href="{reset_url}" style="color:#00e5c7;word-break:break-all;">{reset_url}</a>
398
+ </p>
399
+ <p style="font-size:12px;color:#6e7681;margin:24px 0 0;">Este enlace expira en 60 minutos.</p>
400
+ </td>
401
+ </tr>
402
+ </table>
403
+ </td>
404
+ </tr>
405
+ </table>
406
+ </body>
407
+ </html>
408
+ """
409
+
410
+ await _send_mail_message(
411
+ to=email_to,
412
+ subject="Restablece tu contraseña — KodaQuant Terminal",
413
+ html=html,
414
+ text="Restablece tu contraseña visitando: " + reset_url,
415
+ context="password-reset",
416
+ )
417
+
418
+
419
+ # --- Correos transaccionales de suscripción (i18n) ---
420
+ # Disparar SIEMPRE desde el backend (webhook de Stripe / endpoint server-side
421
+ # que ya conoce el nuevo tier), nunca desde una acción de cliente sin validar.
422
+
423
+ _SUBSCRIPTION_COPY = {
424
+ "en": {
425
+ "upgrade": {
426
+ "subject": "Welcome to KodaQuant {tier} — Subscription Confirmed",
427
+ "heading": "Your upgrade is live",
428
+ "body": "Your subscription has just been upgraded to <strong>{tier}</strong>. Here's what changed:",
429
+ "cta": "OPEN TERMINAL",
430
+ },
431
+ "downgrade": {
432
+ "subject": "Your KodaQuant plan has changed to {tier}",
433
+ "heading": "Plan updated",
434
+ "body": "Your subscription has been changed to <strong>{tier}</strong>, effective at the end of your current billing cycle. Here's what to expect:",
435
+ "cta": "VIEW PLAN DETAILS",
436
+ },
437
+ "cancel": {
438
+ "subject": "Your KodaQuant subscription has been canceled",
439
+ "heading": "Subscription canceled",
440
+ "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 <strong>Free</strong>.",
441
+ "cta": "MANAGE ACCOUNT",
442
+ },
443
+ "footer": "No refunds are issued for partial billing periods.",
444
+ },
445
+ "es": {
446
+ "upgrade": {
447
+ "subject": "Bienvenido a KodaQuant {tier} — Suscripción confirmada",
448
+ "heading": "Tu mejora ya está activa",
449
+ "body": "Tu suscripción acaba de mejorar a <strong>{tier}</strong>. Esto es lo que cambió:",
450
+ "cta": "ABRIR TERMINAL",
451
+ },
452
+ "downgrade": {
453
+ "subject": "Tu plan de KodaQuant cambió a {tier}",
454
+ "heading": "Plan actualizado",
455
+ "body": "Tu suscripción cambiará a <strong>{tier}</strong> al finalizar tu ciclo de facturación actual. Esto es lo que puedes esperar:",
456
+ "cta": "VER DETALLES DEL PLAN",
457
+ },
458
+ "cancel": {
459
+ "subject": "Tu suscripción de KodaQuant fue cancelada",
460
+ "heading": "Suscripción cancelada",
461
+ "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 <strong>Free</strong>.",
462
+ "cta": "GESTIONAR CUENTA",
463
+ },
464
+ "footer": "No se emiten reembolsos por períodos de facturación parciales.",
465
+ },
466
+ }
467
+
468
+ _TIER_BENEFITS = {
469
+ "en": {
470
+ "FREE": ["1 active signal at a time", "Standard forecast horizon"],
471
+ "PRO": ["Unlimited signal generation", "Opportunity Scanner access"],
472
+ "ULTRA": ["Priority ONNX inference queue", "Quanti Discovery mode"],
473
+ },
474
+ "es": {
475
+ "FREE": ["1 señal activa a la vez", "Horizonte de pronóstico estándar"],
476
+ "PRO": ["Generación ilimitada de señales", "Acceso a Opportunity Scanner"],
477
+ "ULTRA": ["Cola de inferencia ONNX prioritaria", "Modo Quanti Discovery"],
478
+ },
479
+ }
480
+
481
+
482
+ def _render_subscription_email_html(heading: str, body: str, tier: str, language: str, cta_label: str) -> str:
483
+ """Mismo layout visual que verify/reset (fondo #0a0e14, tarjeta #10151f,
484
+ borde #1f2a37, logo KODAQUANT #00e5c7/#e6edf3), con comparativa de
485
+ beneficios del tier destino inyectada como lista."""
486
+ benefits = _TIER_BENEFITS.get(language, _TIER_BENEFITS["en"]).get(tier.upper(), [])
487
+ benefits_html = "".join(f'<li style="padding:4px 0;">{b}</li>' for b in benefits)
488
+ footer = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["footer"]
489
+ cta_url = f"{settings.FRONTEND_URL}/dashboard"
490
+ return f"""\
491
+ <html>
492
+ <body style="margin:0;padding:0;background-color:#0a0e14;font-family:'Segoe UI',Arial,sans-serif;">
493
+ <table width="100%" cellpadding="0" cellspacing="0" style="padding:40px 0;background-color:#0a0e14;">
494
+ <tr>
495
+ <td align="center">
496
+ <table width="480" cellpadding="0" cellspacing="0" style="background-color:#10151f;border:1px solid #1f2a37;border-radius:8px;overflow:hidden;">
497
+ <tr>
498
+ <td style="padding:32px;text-align:center;border-bottom:1px solid #1f2a37;">
499
+ <span style="font-size:22px;font-weight:700;color:#00e5c7;letter-spacing:1px;">KODA<span style="color:#e6edf3;">QUANT</span></span>
500
+ </td>
501
+ </tr>
502
+ <tr>
503
+ <td style="padding:32px;color:#c9d1d9;">
504
+ <p style="font-size:17px;font-weight:600;color:#e6edf3;margin:0 0 12px;">{heading}</p>
505
+ <p style="font-size:15px;line-height:1.6;margin:0 0 20px;">{body}</p>
506
+ <ul style="font-size:13px;line-height:1.6;color:#c9d1d9;margin:0 0 24px;padding-left:18px;">
507
+ {benefits_html}
508
+ </ul>
509
+ <table cellpadding="0" cellspacing="0" width="100%">
510
+ <tr>
511
+ <td align="center" style="padding:12px 0 24px;">
512
+ <a href="{cta_url}" style="background-color:#00e5c7;color:#0a0e14;text-decoration:none;font-weight:700;font-size:14px;padding:14px 32px;border-radius:6px;display:inline-block;">
513
+ {cta_label}
514
+ </a>
515
+ </td>
516
+ </tr>
517
+ </table>
518
+ <p style="font-size:12px;color:#6e7681;margin:0;">{footer}</p>
519
+ </td>
520
+ </tr>
521
+ </table>
522
+ </td>
523
+ </tr>
524
+ </table>
525
+ </body>
526
+ </html>
527
+ """
528
+
529
+
530
+ async def send_subscription_upgrade_email(email_to: str, tier: str, language: str = "en") -> None:
531
+ """Correo al mejorar de plan (ej. FREE -> PRO, PRO -> ULTRA)."""
532
+ copy = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["upgrade"]
533
+ subject = copy["subject"].format(tier=tier.upper())
534
+ body = copy["body"].format(tier=tier.upper())
535
+ html = _render_subscription_email_html(copy["heading"], body, tier, language, copy["cta"])
536
+ plain = f"{copy['heading']}. {body}".replace("<strong>", "").replace("</strong>", "")
537
+
538
+ await _send_mail_message(
539
+ to=email_to, subject=subject, html=html, text=plain, context="subscription-upgrade"
540
+ )
541
+
542
+
543
+ async def send_subscription_downgrade_email(email_to: str, tier: str, language: str = "en") -> None:
544
+ """Correo al bajar de plan (ej. ULTRA -> PRO), efectivo al fin del ciclo."""
545
+ copy = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["downgrade"]
546
+ subject = copy["subject"].format(tier=tier.upper())
547
+ body = copy["body"].format(tier=tier.upper())
548
+ html = _render_subscription_email_html(copy["heading"], body, tier, language, copy["cta"])
549
+ plain = f"{copy['heading']}. {body}".replace("<strong>", "").replace("</strong>", "")
550
+
551
+ await _send_mail_message(
552
+ to=email_to, subject=subject, html=html, text=plain, context="subscription-downgrade"
553
+ )
554
+
555
+
556
+ async def send_subscription_cancel_email(email_to: str, language: str = "en") -> None:
557
+ """Correo al cancelar un plan pago; el usuario vuelve a FREE al fin del ciclo."""
558
+ copy = _SUBSCRIPTION_COPY.get(language, _SUBSCRIPTION_COPY["en"])["cancel"]
559
+ html = _render_subscription_email_html(copy["heading"], copy["body"], "FREE", language, copy["cta"])
560
+ plain = f"{copy['heading']}. {copy['body']}".replace("<strong>", "").replace("</strong>", "")
561
+
562
+ await _send_mail_message(
563
+ to=email_to, subject=copy["subject"], html=html, text=plain, context="subscription-cancel"
564
+ )
core/supabase_client.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from supabase import create_client, Client
2
+ from core.config import settings
3
+
4
+ # --- Cliente ANON (respeta RLS) ---
5
+ # Para todo lo que ya funciona hoy: auth.get_user() y cualquier lectura o
6
+ # escritura donde las policies de RLS deben seguir aplicando (ver
7
+ # core/security.py: get_current_user, verify_api_credits). NO se toca.
8
+ url: str = settings.SUPABASE_URL
9
+ key: str = settings.SUPABASE_KEY
10
+ supabase: Client = create_client(url, key)
11
+
12
+ # --- Cliente SERVICE ROLE (bypassea RLS por completo) ---
13
+ # Uso EXCLUSIVO para operaciones de servidor de confianza donde el backend
14
+ # ya verificó la identidad del usuario por su cuenta (ej. el INSERT en
15
+ # chat_threads, hecho después de pasar por get_current_user). Este cliente
16
+ # no tiene NINGÚN control de acceso propio -- es admin total sobre la DB.
17
+ # Nunca lo uses para resolver datos a partir de un id que no hayas validado
18
+ # vos mismo antes, y nunca lo expongas fuera del backend.
19
+ service_key: str = settings.SUPABASE_SERVICE_ROLE_KEY
20
+ supabase_admin: Client = create_client(url, service_key)
database/__init__.py ADDED
File without changes
logs/mlops_pipeline.log ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [2026-07-18 21:32:29] - [INFO] - [train_pipeline] - ==================== CICLO MLOps INICIADO ====================
2
+ [2026-07-18 21:32:32] - [WARNING] - [train_pipeline] - Drift check: AAPL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
3
+ [2026-07-18 21:32:33] - [WARNING] - [train_pipeline] - Drift check: MSFT solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
4
+ [2026-07-18 21:32:34] - [WARNING] - [train_pipeline] - Drift check: NVDA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
5
+ [2026-07-18 21:32:36] - [WARNING] - [train_pipeline] - Drift check: TSLA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
6
+ [2026-07-18 21:32:37] - [WARNING] - [train_pipeline] - Drift check: GOOGL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
7
+ [2026-07-18 21:32:40] - [WARNING] - [train_pipeline] - Drift check: AMZN solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
8
+ [2026-07-18 21:32:41] - [WARNING] - [train_pipeline] - Drift check: META solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
9
+ [2026-07-18 21:32:44] - [WARNING] - [train_pipeline] - Drift check: SPY solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
10
+ [2026-07-18 21:32:44] - [INFO] - [train_pipeline] - No existe baseline_mae previo — se fija el MAE actual (0.017297) como baseline inicial.
11
+ [2026-07-18 21:32:44] - [INFO] - [train_pipeline] - Chequeo de drift: Forzado vía --force-retrain (chequeo real: baseline_inicializado)
12
+ [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.
13
+ [2026-07-18 21:34:40] - [INFO] - [train_pipeline] - ==================== CICLO MLOps FINALIZADO (status=error) ====================
14
+ [2026-07-18 22:03:23] - [INFO] - [train_pipeline] - ==================== CICLO MLOps INICIADO ====================
15
+ [2026-07-18 22:03:25] - [WARNING] - [train_pipeline] - Drift check: AAPL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
16
+ [2026-07-18 22:03:27] - [WARNING] - [train_pipeline] - Drift check: MSFT solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
17
+ [2026-07-18 22:03:29] - [WARNING] - [train_pipeline] - Drift check: NVDA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
18
+ [2026-07-18 22:03:30] - [WARNING] - [train_pipeline] - Drift check: TSLA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
19
+ [2026-07-18 22:03:32] - [WARNING] - [train_pipeline] - Drift check: GOOGL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
20
+ [2026-07-18 22:03:34] - [WARNING] - [train_pipeline] - Drift check: AMZN solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
21
+ [2026-07-18 22:03:36] - [WARNING] - [train_pipeline] - Drift check: META solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
22
+ [2026-07-18 22:03:43] - [INFO] - [train_pipeline] - ==================== CICLO MLOps FINALIZADO (status=error) ====================
23
+ [2026-07-18 22:04:11] - [INFO] - [train_pipeline] - ==================== CICLO MLOps INICIADO ====================
24
+ [2026-07-18 22:04:13] - [WARNING] - [train_pipeline] - Drift check: AAPL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
25
+ [2026-07-18 22:04:14] - [WARNING] - [train_pipeline] - Drift check: MSFT solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
26
+ [2026-07-18 22:04:16] - [WARNING] - [train_pipeline] - Drift check: NVDA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
27
+ [2026-07-18 22:04:17] - [WARNING] - [train_pipeline] - Drift check: TSLA solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
28
+ [2026-07-18 22:04:19] - [WARNING] - [train_pipeline] - Drift check: GOOGL solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
29
+ [2026-07-18 22:04:20] - [WARNING] - [train_pipeline] - Drift check: AMZN solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
30
+ [2026-07-18 22:04:22] - [WARNING] - [train_pipeline] - Drift check: META solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
31
+ [2026-07-18 22:04:26] - [WARNING] - [train_pipeline] - Drift check: SPY solo tiene 3 ventanas (< holdout_days=15) — se usa todo lo disponible.
32
+ [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).)
33
+ [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.
34
+ [2026-07-18 22:07:47] - [INFO] - [train_pipeline] - Champion MAE: 0.017953 | Challenger MAE: 0.018024 | p-value: 0.3819 | Winner: CHAMPION
35
+ [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.
36
+ [2026-07-18 22:07:48] - [INFO] - [train_pipeline] - ==================== CICLO MLOps FINALIZADO (status=rejected) ====================
main.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import asyncio
3
+ import contextlib
4
+ import logging
5
+ import threading
6
+ import time
7
+ load_dotenv()
8
+ from fastapi import Depends, HTTPException, Request
9
+ from gradio import Server
10
+ import spaces
11
+ from fastapi.middleware.cors import CORSMiddleware
12
+ from fastapi.exceptions import RequestValidationError
13
+ from fastapi.responses import StreamingResponse, JSONResponse
14
+ from starlette.exceptions import HTTPException as StarletteHTTPException
15
+ from services.currency_engine import convert_to_usd
16
+ from services.prediccion import generate_predictions
17
+ from services.risk_manager import calculate_portfolio
18
+ from api.auth import router as auth_router
19
+ from core.security import (
20
+ verify_api_credits,
21
+ AuthenticatedUser,
22
+ get_allowed_origins, # <-- CAMBIO: lista cerrada de orígenes CORS
23
+ ALLOWED_METHODS,
24
+ ALLOWED_HEADERS,
25
+ StrictOriginMiddleware, # <-- FIX: bloquea Origin no permitido a nivel app
26
+ # (gradio.Server pisa nuestro CORSMiddleware
27
+ # en prod -- ver detalle en core/security.py)
28
+ )
29
+ from api.payments import router as payments_router
30
+ from api.online_learning import router as online_learning_router
31
+ from typing import Literal, Optional
32
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
33
+ from services.quanti_engine import DEFAULT_FORECAST_HORIZON_DAYS
34
+ from services.quanti_engine import generate_quanti_strategy_stream
35
+ from services.quanti_engine import _forecast_asset
36
+ from services.quanti_engine import _normalize_language
37
+ from services.quanti_engine import _derive_capital_signal
38
+ from api.quota_test_routes import router as quota_test_router
39
+ from api.quanti_chat import router as quanti_chat_router
40
+ from api.support import router as support_router
41
+ from core.config import settings
42
+
43
+ logger = logging.getLogger("kodaquant.main")
44
+
45
+ # NOTA: `lifespan` NO se pasa acá (`Server(lifespan=...)`) a propósito —
46
+ # `Blocks.launch()`/`App.create_app()` lo pisa igual que a `@app.on_event`
47
+ # (ver el bloque de comentarios "RONDA 4" junto al probe de ZeroGPU, más
48
+ # abajo). El único punto que gradio realmente respeta es
49
+ # `app.launch(app_kwargs={"lifespan": lifespan})` en app.py.
50
+ app = Server(title="KodaQuant Terminal", version="4.0")
51
+ app.include_router(payments_router)
52
+ app.include_router(auth_router, prefix="/api/v1/auth")
53
+ app.include_router(online_learning_router)
54
+ if settings.ENV != "production":
55
+ app.include_router(quota_test_router)
56
+ app.include_router(quanti_chat_router)
57
+ app.include_router(support_router)
58
+
59
+ _VALID_EXPERIENCE = {"beginner", "advanced"}
60
+ _VALID_ANALYSIS_MODE = {"specific", "discovery"}
61
+ _VALID_RISK_PROFILE = {"conservador", "moderado", "agresivo"}
62
+
63
+ class QuantiConsultRequest(BaseModel):
64
+ """
65
+ Solo `capital` es realmente obligatorio — todo lo demás tiene default
66
+ seguro y se NORMALIZA en lugar de rechazar la request con 422 ante
67
+ variaciones menores (mayúsculas, catálogo, strings vacíos). Alias
68
+ camelCase 1:1 con lo que envía App.jsx.
69
+ """
70
+
71
+ model_config = ConfigDict(populate_by_name=True, extra="ignore")
72
+
73
+ capital: float = Field(..., gt=0, alias="capital")
74
+ currency: str = Field(default="USD", alias="currency")
75
+ experience_level: str = Field(default="beginner", alias="experienceLevel")
76
+ analysis_mode: str = Field(default="discovery", alias="analysisMode")
77
+ target_asset: Optional[str] = Field(default=None, alias="targetAsset")
78
+ forecast_horizon_days: int = Field(default=DEFAULT_FORECAST_HORIZON_DAYS, alias="forecastHorizonDays")
79
+ risk_profile: str = Field(default="moderado", alias="riskProfile")
80
+ risk_score: int = Field(default=50, alias="riskScore")
81
+ language: str = Field(default="en", alias="language")
82
+
83
+ @field_validator("capital", mode="before")
84
+ @classmethod
85
+ def _coerce_capital(cls, v):
86
+ try:
87
+ return float(v)
88
+ except (TypeError, ValueError):
89
+ raise ValueError("capital debe ser un número mayor a 0")
90
+
91
+ @field_validator("currency", mode="before")
92
+ @classmethod
93
+ def _normalize_currency(cls, v):
94
+ if not isinstance(v, str) or not v.strip():
95
+ return "USD"
96
+ return v.strip().upper()[:3]
97
+
98
+ @field_validator("experience_level", mode="before")
99
+ @classmethod
100
+ def _normalize_experience(cls, v):
101
+ v = str(v).strip().lower() if v else "beginner"
102
+ return v if v in _VALID_EXPERIENCE else "beginner"
103
+
104
+ @field_validator("analysis_mode", mode="before")
105
+ @classmethod
106
+ def _normalize_analysis_mode(cls, v):
107
+ v = str(v).strip().lower() if v else "discovery"
108
+ return v if v in _VALID_ANALYSIS_MODE else "discovery"
109
+
110
+ @field_validator("target_asset", mode="before")
111
+ @classmethod
112
+ def _normalize_target_asset(cls, v):
113
+ if v is None or (isinstance(v, str) and not v.strip()):
114
+ return None
115
+ return str(v).strip().upper()
116
+
117
+ @field_validator("forecast_horizon_days", mode="before")
118
+ @classmethod
119
+ def _normalize_horizon(cls, v):
120
+ try:
121
+ days = int(v)
122
+ except (TypeError, ValueError):
123
+ return DEFAULT_FORECAST_HORIZON_DAYS
124
+ return days if days > 0 else DEFAULT_FORECAST_HORIZON_DAYS
125
+
126
+ @field_validator("risk_profile", mode="before")
127
+ @classmethod
128
+ def _normalize_risk_profile_field(cls, v):
129
+ v = str(v).strip().lower() if v else "moderado"
130
+ return v if v in _VALID_RISK_PROFILE else "moderado"
131
+
132
+ @field_validator("risk_score", mode="before")
133
+ @classmethod
134
+ def _normalize_risk_score(cls, v):
135
+ try:
136
+ score = int(v)
137
+ except (TypeError, ValueError):
138
+ return 50
139
+ return max(0, min(100, score))
140
+
141
+ @field_validator("language", mode="before")
142
+ @classmethod
143
+ def _normalize_language_field(cls, v):
144
+ # Reusa la MISMA normalización que quanti_engine (_SUPPORTED_LANGUAGES
145
+ # = {"en","es"}, default "en"), para que nunca haya drift entre el
146
+ # schema de entrada y lo que el LLM realmente honra.
147
+ return _normalize_language(v)
148
+
149
+ class StrategyRequest(BaseModel):
150
+ budget_usd: float = Field(..., gt=0)
151
+ experience_level: Literal["beginner", "intermediate", "advanced"] = "beginner"
152
+
153
+ @app.post("/strategy")
154
+ async def strategy_mock(payload: StrategyRequest):
155
+ return {
156
+ "status": "success",
157
+ "amounts": {
158
+ "riesgo_usd": 4000,
159
+ "reserva_usd": 6000,
160
+ "riesgo_pct": "40.0%",
161
+ "reserva_pct": "60.0%",
162
+ },
163
+ "guidelines": [
164
+ "Conexión exitosa con el servidor KodaQuant.",
165
+ "El motor está en línea y operando.",
166
+ ],
167
+ }
168
+
169
+ # FIX CRÍTICO (Alpha Seeker nunca corría): este mock estático alimentaba
170
+ # `/api/v1/quanti/consult` con un `top_assets` FIJO donde BTC-USD siempre
171
+ # tenía el `risk_score` más alto (0.78) — `_resolve_plan_b_ticker`
172
+ # (quanti_engine.py) lo elegía SIEMPRE, sin importar el forecast real de
173
+ # cada ciclo. Reemplazado por `_get_radar_data`, que llama al pipeline
174
+ # REAL (`generate_predictions`, ver services/prediccion.py) con caché TTL.
175
+
176
+ _RADAR_CACHE_TTL_SECONDS = 60.0
177
+ _radar_cache: dict[str, tuple[float, dict]] = {}
178
+
179
+
180
+ async def _get_radar_data(budget_usd: float) -> dict:
181
+ """
182
+ Radar real (Alpha Seeker) para `/api/v1/quanti/consult` — sustituye el
183
+ mock hardcodeado. Cacheado con TTL: escanea el universo completo (10
184
+ tickers, Keras + Monte Carlo vía `_forecast_asset`) y el resultado NO
185
+ depende de `budget_usd` (ese solo escala montos de display en
186
+ `recommendations`; el ranking real de `top_assets` es independiente),
187
+ así que recomputarlo en cada request dispararía ~10 inferencias Keras
188
+ extra por usuario concurrente sin necesidad. `generate_predictions`
189
+ nunca lanza excepción (Circuit Breaker propio, devuelve
190
+ status="error" con listas vacías) — safe de propagar tal cual.
191
+ """
192
+ now = time.monotonic()
193
+ cached = _radar_cache.get("global")
194
+ if cached is not None and (now - cached[0]) < _RADAR_CACHE_TTL_SECONDS:
195
+ return cached[1]
196
+
197
+ data = await generate_predictions(budget_usd)
198
+ if data.get("status") != "success":
199
+ logger.warning("generate_predictions degradado en /consult: %s", data.get("error"))
200
+ _radar_cache["global"] = (now, data)
201
+ return data
202
+
203
+ app.add_middleware(
204
+ CORSMiddleware,
205
+ # Lista cerrada, resuelta en core/security.py. En ENVIRONMENT=production
206
+ # esto se reduce a *solo* los dominios de Firebase Hosting (+
207
+ # settings.FRONTEND_URL); localhost nunca se cuela a producción.
208
+ allow_origins=get_allowed_origins(),
209
+ allow_credentials=True,
210
+ allow_methods=ALLOWED_METHODS, # GET, POST, OPTIONS — no "*"
211
+ allow_headers=ALLOWED_HEADERS, # Authorization, Content-Type — no "*"
212
+ expose_headers=["Content-Type", "Cache-Control"],
213
+ )
214
+
215
+ # FIX CRÍTICO — gradio.Server SIEMPRE agrega su propio CustomCORSMiddleware
216
+ # en .launch() (después de este punto, ver app.py), y ese middleware queda
217
+ # por FUERA de nuestro CORSMiddleware de arriba sin importar el orden acá.
218
+ # Su regla solo restringe origen si el Host es localhost -- en *.hf.space
219
+ # NUNCA aplica esa restricción, así que termina permitiendo cualquier
220
+ # Origin con credentials=true, pisando get_allowed_origins(). Verificado
221
+ # contra gradio==6.22.0 (ver core/security.py::StrictOriginMiddleware para
222
+ # el detalle completo). Esta capa rechaza (403) el request ANTES de que
223
+ # llegue al router, así que ningún header que agregue Gradio después
224
+ # importa: la request nunca se procesó.
225
+ app.add_middleware(StrictOriginMiddleware)
226
+
227
+
228
+ # FIX — blindaje JSON-only. Ninguna respuesta de esta API debe poder
229
+ # renderizar como HTML, sin importar qué falle. Starlette por default
230
+ # puede devolver su propia página de error para excepciones no atrapadas;
231
+ # estos handlers garantizan que 404/422/500 y cualquier excepción no
232
+ # manejada siempre vuelvan como JSON, consistente con lo que espera
233
+ # quantiService.js (response.json() en cada llamada).
234
+ @app.exception_handler(StarletteHTTPException)
235
+ async def _json_http_exception_handler(request: Request, exc: StarletteHTTPException):
236
+ return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
237
+
238
+
239
+ @app.exception_handler(RequestValidationError)
240
+ async def _json_validation_exception_handler(request: Request, exc: RequestValidationError):
241
+ return JSONResponse(status_code=422, content={"detail": exc.errors()})
242
+
243
+
244
+ @app.exception_handler(Exception)
245
+ async def _json_unhandled_exception_handler(request: Request, exc: Exception):
246
+ logger.exception("Excepción no manejada en %s %s", request.method, request.url.path)
247
+ return JSONResponse(
248
+ status_code=500,
249
+ content={"detail": "Error interno del servidor."},
250
+ )
251
+
252
+ # --- ZeroGPU probe -----------------------------------------------------
253
+ # ROUND 3 — causa raíz real del "No @spaces.GPU function detected during
254
+ # startup": `gr.mount_gradio_app(fastapi_app, blocks, path=...)` devuelve
255
+ # la instancia FastAPI de ENTRADA (fastapi_app), mutada in place — nunca
256
+ # un gr.Blocks/Interface. El hypervisor de ZeroGPU necesita reconocer el
257
+ # objeto `app` exportado como demo Gradio nativo; al recibir un FastAPI
258
+ # puro con Gradio montado como sub-app en un path escondido, no lo
259
+ # reconoce como tal — pase lo que pase adentro de esa sub-app (Blocks con
260
+ # GPU function real por .load() o .click(), no importa), y mata el
261
+ # proceso. Esto es válido tanto para el mount en app.py (ronda 2) como
262
+ # para este mismo patrón acá en main.py (bug preexistente, mismo defecto).
263
+ #
264
+ # Fix: `gradio.Server` (gradio>=6.22, ver
265
+ # https://gradio.app/main/guides/server-mode) es un FastAPI real —
266
+ # `app.add_middleware`, `app.include_router`, rutas @app.get/@app.post,
267
+ # todo lo que ya usa este archivo sigue funcionando sin tocarlo — pero ES
268
+ # el tipo de objeto que Gradio/ZeroGPU reconocen nativamente como servidor
269
+ # Gradio. `@app.api()` registra la función en la tabla de endpoints de
270
+ # Gradio (mismo registro que el hypervisor inspecciona), sin necesidad de
271
+ # gr.Blocks ni de mount_gradio_app. Nunca se llama desde el frontend — solo
272
+ # necesita existir registrada para que el hypervisor la detecte al
273
+ # build/startup. KodaQuant sigue forzando toda la inferencia Keras real a
274
+ # CPU (ver DEVICE GUARD arriba); este endpoint no hace inferencia real.
275
+ @app.api(name="zerogpu_probe")
276
+ @spaces.GPU()
277
+ def _zerogpu_probe() -> str:
278
+ return "ok"
279
+
280
+
281
+ # FIX 2026-08-15 (RONDA 4) — CAUSA RAÍZ REAL del estado zombi "Starting...".
282
+ #
283
+ # Auditoría línea a línea de gradio==6.22.0 (gradio/routes.py::App.create_app,
284
+ # gradio/blocks.py::Blocks.launch, gradio/server.py::Server.launch):
285
+ #
286
+ # Server.launch() -> blocks.launch(_app=self, app_kwargs=app_kwargs, ...)
287
+ # Blocks.launch() -> App.create_app(self, app=_app, app_kwargs=app_kwargs, ...)
288
+ # App.create_app(): como `app` (=self, nuestra instancia YA construida)
289
+ # NO es None, toma la rama:
290
+ # app.router.lifespan_context = create_lifespan_handler(
291
+ # app_kwargs.get("lifespan", None), *delete_cache
292
+ # )
293
+ #
294
+ # Esa línea PISA `app.router.lifespan_context` con un handler construido a
295
+ # partir de `app_kwargs` — el dict que se le pasa a `.launch()`, NUNCA el
296
+ # `lifespan=` que se le pasó al CONSTRUCTOR `Server(...)`. Como `app.py`
297
+ # (rondas 1-3) llamaba `app.launch()` sin `app_kwargs`, `app_kwargs.get(
298
+ # "lifespan")` daba `None` -> el lifespan real quedaba DESCARTADO en
299
+ # silencio. Y como `router.lifespan_context` se reasigna DIRECTO (no se
300
+ # compone con la implementación default de Starlette que sí lee
301
+ # `router.on_startup`), cualquier `@app.on_event("startup")` registrado
302
+ # antes de `.launch()` (como el que vivía acá) también queda huérfano —
303
+ # explica exacto por qué "KodaQuant ASGI startup complete" NUNCA aparecía
304
+ # en los logs de producción pese a que el resto del pipeline sí corría.
305
+ #
306
+ # FIX REAL: el lifespan tiene que viajar como `app_kwargs={"lifespan": lifespan}`
307
+ # en la LLAMADA a `.launch()` (ver app.py) — es el ÚNICO punto de la cadena
308
+ # que `create_app` efectivamente respeta. `lifespan` se define acá y se
309
+ # exporta para que app.py lo importe.
310
+ def _warm_zerogpu_probe_sync() -> None:
311
+ """
312
+ Red de seguridad INDEPENDIENTE de todo el ciclo de vida ASGI/Gradio de
313
+ arriba: corre en un hilo daemon disparado en el momento del IMPORT de
314
+ este módulo — mucho antes de que exista `router`/`lifespan_context`
315
+ alguno para pisar. Garantiza al menos una ejecución real de
316
+ `_zerogpu_probe` durante el arranque del proceso sin importar qué haga
317
+ `Server.launch()` internamente ni qué versión de gradio la sirva.
318
+ """
319
+ try:
320
+ result = _zerogpu_probe()
321
+ logger.info("ZeroGPU probe warm-up OK (hilo de import, red de seguridad): %s", result)
322
+ except Exception as exc:
323
+ logger.warning("ZeroGPU probe warm-up (hilo de import) falló (no crítico): %r", exc)
324
+
325
+
326
+ threading.Thread(
327
+ target=_warm_zerogpu_probe_sync, daemon=True, name="zerogpu-warmup-import"
328
+ ).start()
329
+
330
+
331
+ @contextlib.asynccontextmanager
332
+ async def lifespan(app):
333
+ """
334
+ Lifespan real de la app — DEBE inyectarse vía
335
+ `app.launch(app_kwargs={"lifespan": lifespan})` en app.py (ver bloque
336
+ de comentarios arriba). Pasarlo al constructor `Server(lifespan=...)`
337
+ o registrar `@app.on_event("startup")` NO alcanza: ambos caminos son
338
+ pisados por `Blocks.launch()`/`App.create_app()` antes de que el
339
+ Space quede realmente sirviendo tráfico.
340
+ """
341
+ # Uvicorn solo loguea el genérico "Application startup complete.". Este
342
+ # marcador con timestamp deja explícito en los logs del Space cuánto
343
+ # tardó el cold start real (imports de TensorFlow/Keras + montaje de
344
+ # gradio) — clave para diferenciar "todo bien, algo externo mandó
345
+ # SIGTERM" de "el arranque fue tan lento que algo lo mató por timeout".
346
+ logger.info("KodaQuant ASGI startup complete — rutas + probe de ZeroGPU montados.")
347
+
348
+ async def _warm_zerogpu_probe_async() -> None:
349
+ # Segunda ejecución del probe, esta vez DENTRO del ciclo de vida
350
+ # ASGI real (útil si el hilo de import de arriba corrió antes de
351
+ # que `device-api.zero` estuviera listo para recibirlo). Fire-and-
352
+ # forget con timeout: si ZeroGPU no responde o el tier actual no lo
353
+ # tiene habilitado, esto NUNCA debe retrasar ni tumbar el arranque.
354
+ try:
355
+ loop = asyncio.get_running_loop()
356
+ result = await asyncio.wait_for(
357
+ loop.run_in_executor(None, _zerogpu_probe), timeout=15.0
358
+ )
359
+ logger.info("ZeroGPU probe warm-up OK (lifespan ASGI): %s", result)
360
+ except Exception as exc:
361
+ logger.warning("ZeroGPU probe warm-up (lifespan ASGI) falló (no crítico): %r", exc)
362
+
363
+ warmup_task = asyncio.create_task(_warm_zerogpu_probe_async())
364
+ try:
365
+ yield
366
+ finally:
367
+ warmup_task.cancel()
368
+ with contextlib.suppress(asyncio.CancelledError):
369
+ await warmup_task
370
+
371
+ @app.get("/")
372
+ async def root():
373
+ return {"status": "online", "system": "KodaQuant Terminal", "version": "4.0"}
374
+
375
+ @app.get("/api/v1/convert")
376
+ async def test_conversion(amount: float, currency: str):
377
+ try:
378
+ data = await convert_to_usd(amount, currency.upper())
379
+ return {"status": "success", "data": data}
380
+ except Exception as e:
381
+ return {"status": "error", "message": str(e)}
382
+
383
+ @app.get("/api/v1/radar")
384
+ async def test_radar(usd_budget: float):
385
+ try:
386
+ data = await generate_predictions(usd_budget)
387
+ return {"status": "success", "data": data}
388
+ except Exception as e:
389
+ return {"status": "error", "message": str(e)}
390
+
391
+ @app.get("/api/v1/quanti/forecast")
392
+ async def test_ml_forecast(ticker: str = "SPY"):
393
+ # `data` es el dict completo que arma `_forecast_asset` — ya incluye
394
+ # `predicted_path` (array plano día-a-día) junto con `forecast`
395
+ # (mismo dato, con date/price/kind). No requiere transformación aquí:
396
+ # serializar el dict completo es suficiente para que el frontend lo lea.
397
+ try:
398
+ loop = asyncio.get_running_loop()
399
+ data = await loop.run_in_executor(None, _forecast_asset, ticker)
400
+ return {"status": "success", "data": data}
401
+ except Exception as e:
402
+ return {"status": "error", "message": str(e)}
403
+
404
+ @app.post("/api/v1/quanti/consult")
405
+ async def quanti_consult(
406
+ payload: QuantiConsultRequest,
407
+ current_user: AuthenticatedUser = Depends(verify_api_credits),
408
+ ):
409
+ try:
410
+ conversion_report = await convert_to_usd(payload.capital, payload.currency)
411
+ budget_usd = conversion_report["usd_amount"]
412
+ except Exception as exc:
413
+ raise HTTPException(status_code=400, detail=f"Error de conversión de divisa: {exc}")
414
+
415
+ radar_data = await _get_radar_data(budget_usd)
416
+ # Auto-Allocation: copia superficial — NUNCA mutar en sitio el dict que
417
+ # devuelve `_get_radar_data` (está cacheado con TTL y compartido entre
418
+ # requests concurrentes). `_derive_capital_signal` es puro/determinista
419
+ # sobre datos ya calculados, así que enriquecerlo acá es seguro y no
420
+ # requiere invalidar ni recomputar el caché del radar.
421
+ radar_data = {**radar_data, "signal": _derive_capital_signal(radar_data)}
422
+
423
+ try:
424
+ portfolio_allocation = await calculate_portfolio(budget_usd, radar_data)
425
+ except Exception as exc:
426
+ raise HTTPException(status_code=500, detail=f"Error en risk_manager: {exc}")
427
+
428
+ # `generate_quanti_strategy_stream` emite `chart_data.plan_a` / `plan_b`
429
+ # como el dict completo de `_forecast_asset` (ver quanti_engine.py), así
430
+ # que `predicted_path` viaja automáticamente en el evento `meta` del SSE
431
+ # — no hace falta tocar el stream para exponerlo.
432
+ return StreamingResponse(
433
+ generate_quanti_strategy_stream(
434
+ budget_usd=budget_usd,
435
+ portfolio_allocation=portfolio_allocation,
436
+ radar_data=radar_data,
437
+ experience_level=payload.experience_level,
438
+ analysis_mode=payload.analysis_mode,
439
+ target_asset=payload.target_asset,
440
+ forecast_horizon_days=payload.forecast_horizon_days,
441
+ risk_profile=payload.risk_profile,
442
+ risk_score=payload.risk_score,
443
+ language=payload.language,
444
+ ),
445
+ media_type="text/event-stream",
446
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
447
+ )
middlewares/__init__.py ADDED
File without changes
ml_engine/__init__.py ADDED
File without changes
ml_engine/attention_bilstm_global_best.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10a425f6c4b837cc902b24051c3d473c103f2e5eae23f963451dd050569c9548
3
+ size 19854569
ml_engine/cache/news/headlines_AAPL.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/cache/news/headlines_AMZN.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/cache/news/headlines_GOOGL.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/cache/news/headlines_META.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/cache/news/headlines_MSFT.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/cache/news/headlines_NVDA.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/cache/news/headlines_SPY.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/cache/news/headlines_TSLA.json ADDED
@@ -0,0 +1 @@
 
 
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}
ml_engine/data_pipeline.py ADDED
@@ -0,0 +1,1041 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ services/data_pipeline.py
3
+
4
+ Fragmento de Ingeniería de Features — Pipeline NLP de Sentimiento de Noticias
5
+ ==============================================================================
6
+ KodaQuant V5 — Requerimiento 1 (Cero Fricción / Anti-CAPTCHAs).
7
+
8
+ Añade la variable continua `NEWS_SENTIMENT_SCORE` (rango [-1, 1]) al tensor
9
+ de entrada del modelo, calculada EXCLUSIVAMENTE con APIs nativas:
10
+
11
+ 1) DDGS (DuckDuckGo News Search) -> fuente primaria, sin API key.
12
+ Reemplaza a `yfinance.Ticker(ticker).news` (yfinance retirado por
13
+ completo del proyecto, ver services/market_data.py) manteniendo el
14
+ mismo rol estructural: gratuita, sin key, no depende de que el
15
+ operador configure nada para tener AL MENOS cobertura básica.
16
+ 2) Finnhub REST API -> fallback, requiere FINNHUB_API_KEY.
17
+ `/company-news` para equities, `/news?category=crypto` para cripto
18
+ (ver `_is_crypto_ticker`/`_fetch_headlines_finnhub` — V6, fix de
19
+ "señal muerta" en crypto_specialist).
20
+
21
+ PROHIBIDO en este módulo: Selenium, BeautifulSoup, requests directos a
22
+ portales de noticias, o cualquier scraping HTML iterativo. Cualquiera de
23
+ esos vectores colapsa el pipeline productivo ante CAPTCHAs, Cloudflare o
24
+ baneos de IP del proveedor de hosting — exactamente lo que este pipeline
25
+ está diseñado para evitar. DDGS consume el endpoint JSON de noticias de
26
+ DuckDuckGo (misma librería `ddgs` ya usada por
27
+ `quanti_engine.search_financial_web`, ya pineada en requirements.txt) —
28
+ no es scraping de HTML de portales de noticias individuales.
29
+
30
+ V7 (auditoría "señal muerta" universal, post-fix-tz V6): dos fallos
31
+ independientes que colapsaban NEWS_SENTIMENT_SCORE a 0.0 EXACTO pese al
32
+ fix de timezone previo — (a) `_score_text` descartaba en silencio
33
+ cualquier etiqueta de FinBERT no reconocida (ej. LABEL_0/1/2 en vez de
34
+ positive/negative/neutral) sin loguear nada, para TODOS los tickers por
35
+ igual; (b) `get_daily_news_sentiment` exigía calce EXACTO de
36
+ fecha-calendario (`Series.reindex`), que nunca aterriza para titulares
37
+ publicados fin de semana/feriado en el universo de equities. Ver
38
+ docstrings de ambas funciones para el detalle completo.
39
+
40
+ V8 (auditoría de atribución por gradiente, post-fix-señal-muerta V7): con
41
+ la señal ya viva (V7), NEWS_SENTIMENT_SCORE seguía rank 17/17 en
42
+ equity_specialist mientras SENTIMENT_SCORE (correlación móvil
43
+ activo<->VIX, ver train_kodaquant_v5.py/quanti_engine.py — variable de
44
+ régimen/beta derivada de precio, NO redundante con esta) dominaba el
45
+ Top 5. Diagnóstico: no es colisión de features, es cobertura de prensa
46
+ esporádica en equity (relleno neutro + saltos discretos = ruido de alta
47
+ frecuencia que el modelo aprende a ignorar). Fix: EMA regime-aware al
48
+ final de `get_daily_news_sentiment` — amortigua equity, no-op exacto en
49
+ cripto (flujo de noticias 24/7, la misma densidad que sostiene el
50
+ 51.2%/52.3% de crypto_specialist). Ver constantes
51
+ `NEWS_SENTIMENT_EMA_SPAN_*` más abajo. Cero cambios en
52
+ train_kodaquant_v5.py/quanti_engine.py: ambos consumen esta función tal
53
+ cual, consistencia train/inferencia automática.
54
+
55
+ V9 (consolidación del core, auditoría CTO 2026-08-16): `fetch_recent_headlines`
56
+ ahora cachea en disco vía `kodaquant_core.CacheManager` (TTL corto,
57
+ `KODAQUANT_NEWS_CACHE_TTL_SECONDS`, purga automática local en cada
58
+ llamada) -- reduce presión sobre DDGS/Finnhub sin tocar la lógica de
59
+ scoring/merge de abajo, que queda intacta. Ver `kodaquant_core.py` para el
60
+ resto de la consolidación (caché de OHLCV, cliente FRED, alineación de
61
+ calendario macro), compartida ahora con `train_kodaquant_v5.py`.
62
+
63
+ V10 (auditoría "100% neutro" AMZN/META, post-rollback V23.6 equity):
64
+ `DDG_REGION` default venía en `"es-es"` -- sesga `ddgs.news(...)` hacia
65
+ resultados LOCALIZADOS a España (con mayor probabilidad de titulares en
66
+ español) para consultas de equities 100% US-listed (`"{TICKER} stock"`).
67
+ `ProsusAI/finbert` (`_score_text`) es un clasificador ENTRENADO
68
+ EXCLUSIVAMENTE en texto financiero en inglés (Financial PhraseBank) -- un
69
+ titular en español queda fuera de su distribución de entrenamiento y
70
+ tiende a colapsar a la clase "neutral" con score de confianza alto (no es
71
+ un titular sin opinión: es el modelo adivinando entre 3 clases sobre texto
72
+ que nunca vio en ese idioma). Esto es indistinguible, aguas abajo, del
73
+ caso legítimo "titular real sin carga direccional" -- exactamente el
74
+ síntoma reportado (9 titulares obtenidos para META, 0 warnings de
75
+ etiqueta-no-reconocida, score 100% neutro de todas formas: los titulares
76
+ SÍ llegaban y SÍ eran clasificables, solo que en el idioma equivocado para
77
+ este scorer). Fix: default cambiado a `"us-en"` (mercado real de todo el
78
+ universo de `equity_specialist`: AAPL/MSFT/NVDA/TSLA/GOOGL/AMZN/META/SPY,
79
+ todos NYSE/NASDAQ) -- sigue siendo 100% override-able vía env var
80
+ `DDG_REGION` si el operador necesita otra región por algún motivo. NO
81
+ toca `quanti_engine.py::DDG_REGION` (constante del mismo nombre pero
82
+ CONSUMIDOR DISTINTO: alimenta el RAG conversacional de Quanti para
83
+ usuarios que preguntan en español, vía `search_financial_web` -> Groq,
84
+ nunca pasa por FinBERT -- ahí "es-es" sigue siendo la región correcta y
85
+ no se toca).
86
+
87
+ Analizador de sentimiento: FinBERT (`ProsusAI/finbert` vía `transformers`),
88
+ cargado perezosamente (singleton) y con selección automática de device
89
+ (GPU si disponible, CPU en runners de CI). `get_daily_news_sentiment` sigue
90
+ aceptando un `scorer_fn` intercambiable para no acoplar el resto del módulo
91
+ a este modelo en particular.
92
+
93
+ Integración con `engineer_asset` (ver train_kodaquant_v5.py):
94
+ df["NEWS_SENTIMENT_SCORE"] = get_daily_news_sentiment(ticker, df.index)
95
+ Debe ejecutarse ANTES de que `TECH_COLS`/`feature_cols` arme el tensor de
96
+ entrada, junto al resto de los indicadores técnicos — nunca después de la
97
+ transformación a retornos logarítmicos del target.
98
+
99
+ V11 (auditoría rescate 2026-08 -- "esto tiene que quedar perfecto"): 4 puntos
100
+ menores detectados en una corrida real de producción, ninguno bloqueante,
101
+ todos con fix real:
102
+ a) COLISIÓN DE ENV VAR (el único con impacto real en la señal): este
103
+ módulo y `quanti_engine.py` compartían el nombre `DDG_REGION` para
104
+ DOS propósitos incompatibles (RAG conversacional en español vs.
105
+ scoring FinBERT inglés-únicamente) -- fijar `DDG_REGION=es-es` para
106
+ el chat de Quanti reintroducía en silencio el bug "100% neutro" que
107
+ V10 creía cerrado. Fix: variable dedicada `NEWS_SENTIMENT_DDG_REGION`.
108
+ b) Filtro de idioma `langdetect` (opcional, gratis, sin key) como
109
+ defensa en profundidad DESPUÉS del fix de región -- poda la cola
110
+ larga de titulares fuera de idioma que un agregador global puede
111
+ colar incluso con la región correcta.
112
+ c) Reintento con query más amplia + fallback a `/news?category=general`
113
+ de Finnhub para ETFs (SPY, QQQ...) que nunca tienen perfil de
114
+ compañía en `/company-news` y antes se quedaban sin ninguna señal
115
+ de prensa cuando DDGS tampoco rendía para esa query específica.
116
+ d) `FutureWarning` cosmético de `huggingface_hub` (resume_download)
117
+ silenciado de forma acotada -- no afectaba nada, solo ruido de log.
118
+
119
+ V12 (auditoría rescate 2026-08 -- crash real en despliegue HF Space):
120
+ `ModuleNotFoundError: No module named 'langdetect'` seguido de
121
+ `NameError: name 'logger' is not defined`, ambos en import-time de este
122
+ módulo (tumbaba todo el proceso, no solo esta feature). Causa raíz: el
123
+ bloque `try/except ImportError` de `langdetect` (V11, arriba) llamaba
124
+ `logger.warning(...)` en su rama `except`, pero `logger =
125
+ logging.getLogger(...)` se definía DEBAJO de ese bloque -- el except SÍ
126
+ atrapaba el `ModuleNotFoundError` real (es subclase de `ImportError`),
127
+ pero al intentar loguearlo lanzaba un `NameError` sin atrapar, que se
128
+ propagaba y abortaba la carga del módulo completo. Fix real: `logger` se
129
+ define ANTES de cualquier bloque que pueda loguear en su rama except
130
+ (orden, no manejo de excepciones nuevo). `langdetect` además se agrega a
131
+ requirements.txt (ver ese archivo) -- puro-Python, gratis, sin key -- para
132
+ que la defensa en profundidad V11 quede activa en producción en vez de
133
+ degradarse siempre al no-op silencioso.
134
+
135
+ V13 (auditoría rescate 2026-08-31 -- re-verificación post-reporte de
136
+ `ModuleNotFoundError`/`NameError` en este mismo módulo): re-auditado línea
137
+ por línea contra el reporte. Ambos síntomas YA estaban resueltos por V12
138
+ (arriba) en esta versión del archivo -- `logger` se define en la línea
139
+ correcta (antes del primer `except` que lo usa) y `langdetect==1.0.9` ya
140
+ está pineado en requirements.txt. Confirmado también con `pyflakes` (cero
141
+ warnings) y `ast.parse`/`py_compile` (sintaxis válida) sobre el archivo
142
+ completo -- CERO cambios funcionales en este módulo; el crash reportado no
143
+ reproduce contra este código fuente. Ver requirements.txt (RONDA 7) para
144
+ el crash real de esta corrida (`numpy`/`tensorflow`, módulo distinto).
145
+ """
146
+
147
+ from __future__ import annotations
148
+
149
+ import logging
150
+ import os
151
+ import re
152
+ import sys
153
+ import threading
154
+ import time
155
+ import warnings
156
+ from datetime import datetime, timedelta, timezone
157
+ from pathlib import Path
158
+ from typing import Callable, Optional
159
+
160
+ # V11 (auditoría 2026-08) -- `huggingface_hub` emite un FutureWarning
161
+ # cosmético ("resume_download is deprecated") en CADA carga de FinBERT vía
162
+ # `transformers.pipeline`, sin relación con ningún bug real de este módulo
163
+ # ni con la calidad de NEWS_SENTIMENT_SCORE. Acotado por `module=` a la
164
+ # librería exacta que lo emite -- nunca un `warnings.filterwarnings("ignore")`
165
+ # global, que enmascararía warnings reales de otras dependencias.
166
+ warnings.filterwarnings("ignore", category=FutureWarning, module=r"huggingface_hub\..*")
167
+
168
+ # --- RESOLUCIÓN ABSOLUTA DE IMPORTS (Directiva 2 — fin al Import Hell) ----
169
+ # Este archivo vive ÚNICAMENTE en `ml_engine/` (Directiva 1: SINGLE SOURCE
170
+ # OF TRUTH). Sube desde este archivo hasta encontrar la raíz del proyecto
171
+ # -- el primer ancestro que contiene TANTO `ml_engine/` como `services/`
172
+ # como subdirectorios -- y la inserta en `sys.path[0]`. A partir de ahí,
173
+ # `ml_engine` y `services` son paquetes válidos sin importar desde qué
174
+ # directorio de trabajo se invoque `python .../data_pipeline.py` (directo,
175
+ # importado por `train_kodaquant_v5.py`, o vía `services.quanti_engine`).
176
+ # Reemplaza por completo el patrón try/except dual + copias duplicadas de
177
+ # `kodaquant_core.py` que causaba `ModuleNotFoundError`/`ImportError`.
178
+ def _bootstrap_project_root() -> Path:
179
+ here = Path(__file__).resolve()
180
+ for ancestor in (here.parent, *here.parents):
181
+ if (ancestor / "ml_engine").is_dir() and (ancestor / "services").is_dir():
182
+ return ancestor
183
+ # Fallback determinista: este archivo vive en ml_engine/, por lo que su
184
+ # abuelo es la raíz del proyecto por construcción, incluso si `services/`
185
+ # todavía no existe en el entorno actual (ej. checkout parcial/CI).
186
+ return here.parent.parent
187
+
188
+
189
+ _PROJECT_ROOT = _bootstrap_project_root()
190
+ if str(_PROJECT_ROOT) not in sys.path:
191
+ sys.path.insert(0, str(_PROJECT_ROOT))
192
+
193
+ # Núcleo compartido train/inferencia -- SINGLE SOURCE OF TRUTH en
194
+ # `ml_engine/kodaquant_core.py` (Directiva 1). Import directo y absoluto,
195
+ # sin fallback dual: con la raíz del proyecto ya en sys.path, esta ruta
196
+ # resuelve siempre, sin importar el cwd de invocación.
197
+ from ml_engine.kodaquant_core import CacheManager # noqa: E402
198
+
199
+ # --- PARCHE macOS Intel: runtimes OpenMP duplicados TensorFlow/PyTorch ----
200
+ # `quanti_engine.py` carga TensorFlow/Keras (bundla Intel MKL -> libiomp5.dylib)
201
+ # EAGER al arrancar Uvicorn. PyTorch (bundla LLVM -> libomp.dylib) se importa
202
+ # LAZY aquí, recién en el primer request real. Ambos runtimes OpenMP en el
203
+ # mismo proceso es un conflicto conocido en macOS que puede impedir que
204
+ # torch cargue su extensión nativa. Debe fijarse ANTES del primer `import
205
+ # torch` — no tiene efecto si se fija después.
206
+ os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
207
+
208
+ import pandas as pd
209
+ import requests # Únicamente para el endpoint JSON de Finnhub — API nativa, NO scraping.
210
+
211
+ # --- Búsqueda de noticias vía DDGS (DuckDuckGo) — reemplaza a yfinance.news
212
+ # como fuente primaria, gratuita y sin API key (yfinance retirado por
213
+ # completo del proyecto, ver services/market_data.py). Mismo import
214
+ # defensivo (paquete renombrado `duckduckgo_search` -> `ddgs`) que ya usa
215
+ # `quanti_engine.search_financial_web`; `ddgs` ya está pineado en
216
+ # requirements.txt, cero dependencias nuevas.
217
+ logger = logging.getLogger("kodaquant.data_pipeline")
218
+
219
+ try:
220
+ from ddgs import DDGS
221
+ except ImportError: # pragma: no cover
222
+ try:
223
+ from duckduckgo_search import DDGS # type: ignore[no-redef]
224
+ except ImportError:
225
+ DDGS = None # type: ignore[assignment,misc] # se valida en runtime, ver _fetch_headlines_ddg
226
+
227
+ # V11 (auditoría 2026-08 — colisión de nombre de env var, root cause real
228
+ # del "100% neutro" que V10 creyó haber cerrado): V10 cambió el DEFAULT de
229
+ # este módulo a "us-en", pero seguía leyendo la MISMA variable de entorno
230
+ # `DDG_REGION` que usa `quanti_engine.py::DDG_REGION` para el buscador
231
+ # conversacional de Quanti (default "es-es", CORRECTO ahí -- los usuarios
232
+ # le hablan en español). Cualquier operador que fije `DDG_REGION=es-es` en
233
+ # su .env/entorno (lo natural para un producto en español) pisa SIN
234
+ # querer el default de ESTE módulo también -- las dos constantes comparten
235
+ # nombre pero NO deberían compartir valor: una alimenta un LLM que lee
236
+ # español perfectamente, la otra alimenta FinBERT, que es inglés-únicamente.
237
+ # Fix real: variable de entorno dedicada y jamás compartida con
238
+ # quanti_engine.py. Quien necesite tocar la región de este módulo usa
239
+ # `NEWS_SENTIMENT_DDG_REGION`, nunca `DDG_REGION`.
240
+ DDG_REGION = os.getenv("NEWS_SENTIMENT_DDG_REGION", "us-en")
241
+ DDG_SAFESEARCH = os.getenv("DDG_SAFESEARCH", "moderate")
242
+ MAX_DDG_HEADLINES = 10 # techo por-ticker -- Finnhub complementa si esto no alcanza
243
+
244
+ # V11 — defensa en profundidad además del fix de región de arriba: agregadores
245
+ # de noticias globales pueden devolver un titular fuera de idioma incluso con
246
+ # la región correcta (ej. un medio hispano indexado igual bajo "us-en"). Un
247
+ # titular no-inglés que llega a FinBERT no lanza NINGÚN warning (ver V10) y
248
+ # se pierde como "neutral" falso -- indistinguible de una lectura neutra real.
249
+ # `langdetect` es puro-Python, gratuito, sin key, determinístico con seed fija
250
+ # -- se usa como filtro PREVIO al scorer, no como reemplazo del fix de región
251
+ # (más barato: si la región ya resuelve el 95% de los casos, este filtro solo
252
+ # poda la cola larga). Si no está instalado, se degrada a no-op con un único
253
+ # warning (nunca bloquea el pipeline).
254
+ try:
255
+ from langdetect import DetectorFactory as _LangDetectorFactory, detect_langs as _langdetect_detect_langs
256
+ _LangDetectorFactory.seed = 0 # determinístico -- sin esto, langdetect no es reproducible corrida a corrida
257
+ _LANGDETECT_AVAILABLE = True
258
+ except ImportError: # pragma: no cover
259
+ _LANGDETECT_AVAILABLE = False
260
+ logger.warning(
261
+ "langdetect no instalado (`pip install langdetect`) -- se omite el filtro de idioma "
262
+ "de defensa en profundidad; NEWS_SENTIMENT_DDG_REGION sigue siendo la defensa primaria."
263
+ )
264
+
265
+ # Caché de titulares (DDGS/Finnhub) — vida corta: la cobertura de prensa
266
+ # cambia varias veces al día, pero no vale la pena re-golpear DDGS/Finnhub
267
+ # en cada llamada de `get_daily_news_sentiment` dentro de la MISMA corrida
268
+ # (el radar escanea el universo completo en paralelo, ver
269
+ # `data_pipeline.get_daily_news_sentiment` invocado por cada régimen).
270
+ # Purga automática local (Requerimiento 1): `_headline_cache.purge_stale()`
271
+ # se invoca de forma perezosa en cada `fetch_recent_headlines` -- sin cron
272
+ # externo, sin intervención manual.
273
+ _HEADLINE_CACHE_DIR = Path(os.getenv("KODAQUANT_NEWS_CACHE_DIR", "cache/news"))
274
+ _HEADLINE_CACHE_TTL_SECONDS = int(os.getenv("KODAQUANT_NEWS_CACHE_TTL_SECONDS", str(2 * 3600)))
275
+ _headline_cache = CacheManager(_HEADLINE_CACHE_DIR, default_ttl_seconds=_HEADLINE_CACHE_TTL_SECONDS)
276
+
277
+ # ---------------------------------------------------------------------------
278
+ # FinBERT — analizador de sentimiento transformer, carga perezosa (singleton)
279
+ # ---------------------------------------------------------------------------
280
+ _FINBERT_MODEL_NAME = "ProsusAI/finbert"
281
+ _FINBERT_LABEL_SIGN = {"positive": 1.0, "negative": -1.0, "neutral": 0.0}
282
+ # V7 (auditoría "señal muerta" UNIVERSAL — TODOS los activos, no solo cripto):
283
+ # ciertas combinaciones de `transformers`/config cacheado devuelven las
284
+ # etiquetas GENÉRICAS del clasificador (LABEL_0/LABEL_1/LABEL_2) en vez de
285
+ # las humanas positive/negative/neutral, cuando el `id2label` del modelo no
286
+ # se resuelve en tiempo de carga. Orden oficial de ProsusAI/finbert
287
+ # (config.json del modelo): 0=positive, 1=negative, 2=neutral.
288
+ _FINBERT_LABEL_ALIASES = {"label_0": "positive", "label_1": "negative", "label_2": "neutral"}
289
+ _finbert_pipeline = None
290
+ # RONDA 10 -- sentinela de FALLO cacheado (str del motivo, o None si aún no
291
+ # se intentó / tuvo éxito). Antes solo se cacheaba el ÉXITO (`_finbert_pipeline`)
292
+ # -- un fallo NUNCA quedaba memorizado, así que CADA titular individual
293
+ # repetía el import + intento de carga completo desde cero y volvía a
294
+ # producir el traceback entero -- la causa real de las "cientos de líneas
295
+ # de error" reportadas, no un crash único. Con esto: se diagnostica UNA
296
+ # vez, se loguea el traceback real completo UNA vez, y todo el resto del
297
+ # proceso degrada a NEUTRAL_SCORE con un mensaje corto de una línea.
298
+ _finbert_unavailable_reason: Optional[str] = None
299
+ # Protege la carga perezosa contra llamadas CONCURRENTES: bajo Uvicorn,
300
+ # get_daily_news_sentiment se dispara desde varios hilos a la vez (Plan A/Plan B
301
+ # en paralelo, radar escaneando el universo completo vía ThreadPoolExecutor).
302
+ # Sin lock, el primer request real puede disparar 2+ hilos importando
303
+ # torch/transformers simultáneamente -> ImportError transitorio de import
304
+ # parcial/circular, indistinguible de "no instalado" sin este fix.
305
+ _finbert_init_lock = threading.Lock()
306
+ # RONDA 10 -- piso REAL de transformers 5.x, verificado contra la guía de
307
+ # migración oficial de la librería (Python 3.10+, PyTorch 2.4+,
308
+ # huggingface_hub<2.0,>=1.3.0) -- NO 2.5 como asumía una auditoría previa.
309
+ _TRANSFORMERS_MIN_TORCH = (2, 4)
310
+
311
+ # --- Backend ONNX (camino PRIMARIO, torch-independiente) -------------------
312
+ _FINBERT_ONNX_REPO = os.getenv("KODAQUANT_FINBERT_ONNX_REPO", "Xenova/finbert").strip()
313
+ # V27 -- default cambiado de _FINBERT_MODEL_NAME (ProsusAI/finbert, sin
314
+ # export ONNX -> 404 permanente) a Xenova/finbert (mismo modelo base,
315
+ # mismas labels -- config.json id2label idéntico, verificado). Confirmado
316
+ # en producción: "[FinBERT/ONNX] sesión activa (Xenova/finbert ...)".
317
+ # KODAQUANT_FINBERT_ONNX_REPO sigue pisando esto si se necesita otro repo.
318
+ _FINBERT_ONNX_FILE = os.getenv("KODAQUANT_FINBERT_ONNX_FILE", "onnx/model.onnx").strip()
319
+ _FINBERT_ONNX_MAXLEN = 256
320
+ _finbert_onnx = None # tuple(InferenceSession, Tokenizer, input_names)
321
+ _finbert_onnx_unavailable: Optional[str] = None
322
+ _finbert_onnx_lock = threading.Lock()
323
+
324
+
325
+ def _load_finbert_tokenizer(hf_hub_download):
326
+ """tokenizer.json (fast) con fallback a vocab.txt (WordPiece clásico)."""
327
+ from tokenizers import Tokenizer
328
+ try:
329
+ return Tokenizer.from_file(hf_hub_download(_FINBERT_ONNX_REPO, "tokenizer.json"))
330
+ except Exception:
331
+ from tokenizers import BertWordPieceTokenizer
332
+ vocab = hf_hub_download(_FINBERT_ONNX_REPO, "vocab.txt")
333
+ return BertWordPieceTokenizer(vocab, lowercase=True)
334
+
335
+
336
+ def _get_finbert_onnx():
337
+ """Sesión ONNX + tokenizer (singleton thread-safe). Cero torch, cero TF.
338
+
339
+ Esquiva `transformers.pipeline()` por completo -- ahí vive la NameError
340
+ de la compuerta torch>=2.4 diagnosticada en RONDA 10, que NINGÚN kwarg
341
+ de esta capa puede evitar.
342
+ """
343
+ global _finbert_onnx, _finbert_onnx_unavailable
344
+ if _finbert_onnx is not None:
345
+ return _finbert_onnx
346
+ if _finbert_onnx_unavailable is not None:
347
+ raise FinBERTUnavailableError(_finbert_onnx_unavailable)
348
+
349
+ with _finbert_onnx_lock:
350
+ if _finbert_onnx is not None:
351
+ return _finbert_onnx
352
+ if _finbert_onnx_unavailable is not None:
353
+ raise FinBERTUnavailableError(_finbert_onnx_unavailable)
354
+ try:
355
+ import numpy as _np
356
+ import onnxruntime as _ort
357
+ from huggingface_hub import hf_hub_download
358
+ except ImportError as exc:
359
+ _finbert_onnx_unavailable = (
360
+ f"[FinBERT/ONNX] backend no instalado ({type(exc).__name__}: {exc}). "
361
+ "`pip install onnxruntime tokenizers` en el MISMO venv."
362
+ )
363
+ logger.warning(_finbert_onnx_unavailable)
364
+ raise FinBERTUnavailableError(_finbert_onnx_unavailable) from exc
365
+
366
+ try:
367
+ onnx_path = hf_hub_download(_FINBERT_ONNX_REPO, _FINBERT_ONNX_FILE)
368
+ tokenizer = _load_finbert_tokenizer(hf_hub_download)
369
+ opts = _ort.SessionOptions()
370
+ opts.intra_op_num_threads = 1 # ZeroGPU / Uvicorn multihilo
371
+ opts.graph_optimization_level = _ort.GraphOptimizationLevel.ORT_ENABLE_ALL
372
+ session = _ort.InferenceSession(onnx_path, opts, providers=["CPUExecutionProvider"])
373
+ input_names = {i.name for i in session.get_inputs()}
374
+ _finbert_onnx = (session, tokenizer, input_names, _np)
375
+ logger.info("[FinBERT/ONNX] sesión activa (%s :: %s, inputs=%s).",
376
+ _FINBERT_ONNX_REPO, _FINBERT_ONNX_FILE, sorted(input_names))
377
+ except Exception as exc:
378
+ _finbert_onnx_unavailable = (
379
+ f"[FinBERT/ONNX] no se pudo abrir '{_FINBERT_ONNX_REPO}::{_FINBERT_ONNX_FILE}' "
380
+ f"({type(exc).__name__}: {exc}). Si es 404, ese repo no publica export ONNX -- "
381
+ "exportalo una vez y fijá KODAQUANT_FINBERT_ONNX_REPO/_FILE."
382
+ )
383
+ logger.warning(_finbert_onnx_unavailable)
384
+ raise FinBERTUnavailableError(_finbert_onnx_unavailable) from exc
385
+ return _finbert_onnx
386
+
387
+
388
+ def _score_text_onnx(text: str) -> float:
389
+ session, tokenizer, input_names, _np = _get_finbert_onnx()
390
+ enc = tokenizer.encode(text)
391
+ ids = enc.ids[:_FINBERT_ONNX_MAXLEN]
392
+ mask = (enc.attention_mask[:_FINBERT_ONNX_MAXLEN]
393
+ if getattr(enc, "attention_mask", None) else [1] * len(ids))
394
+ feed = {"input_ids": _np.asarray([ids], dtype=_np.int64),
395
+ "attention_mask": _np.asarray([mask], dtype=_np.int64)}
396
+ if "token_type_ids" in input_names:
397
+ feed["token_type_ids"] = _np.zeros((1, len(ids)), dtype=_np.int64)
398
+ logits = _np.asarray(session.run(None, {k: v for k, v in feed.items()
399
+ if k in input_names})[0][0], dtype=_np.float64)
400
+ exp = _np.exp(logits - logits.max())
401
+ probs = exp / exp.sum()
402
+ # id2label oficial de ProsusAI/finbert: 0=positive, 1=negative, 2=neutral
403
+ return float(probs[0] - probs[1])
404
+
405
+
406
+ def news_sentiment_available() -> bool:
407
+ """Probe determinista -- ¿hay ALGÚN backend capaz de puntuar sentimiento?
408
+
409
+ Consumido por `train_kodaquant_v5.run_regime_pipeline` para decidir, UNA
410
+ vez y antes de construir el tensor, si NEWS_SENTIMENT_SCORE entra o se
411
+ excluye. Inyectar 0.0 constante es peor que excluirla: el feature_scaler
412
+ se ajusta sobre una constante y la red aprende un slot muerto.
413
+ """
414
+ try:
415
+ _get_finbert_onnx()
416
+ return True
417
+ except Exception:
418
+ pass
419
+ try:
420
+ _get_finbert_pipeline()
421
+ return True
422
+ except Exception:
423
+ return False
424
+
425
+
426
+ class FinBERTUnavailableError(ImportError):
427
+ """RONDA 10 -- excepción DEDICADA para el caso 'ya diagnosticado, no
428
+ reintentable en este proceso' (piso de torch no alcanzado / backend TF
429
+ inexistente en transformers 5.x). `_score_text` la distingue de un
430
+ ImportError genérico para loguear corto (sin traceback repetido) en
431
+ vez de con `exc_info=True` en cada titular -- ver ahí."""
432
+
433
+
434
+ def _get_finbert_pipeline():
435
+ """Carga perezosa (singleton, thread-safe) del pipeline FinBERT — CPU-safe para runners sin GPU.
436
+
437
+ RONDA 10 (fix REAL, reemplaza el intento fallido de RONDA 6-9) --
438
+ diagnóstico verificado contra el TRACEBACK REAL producido en Mac Intel
439
+ (no solo contra el código fuente): el intento anterior de "fallback a
440
+ backend TensorFlow" era imposible de raíz, no un bug de esta función.
441
+ Evidencia: el segundo intento (`framework="tf"`) reventó con la
442
+ EXACTA MISMA `NameError: name 'torch' is not defined` en la EXACTA
443
+ MISMA línea (`transformers/pipelines/__init__.py::pipeline`, chequeo
444
+ `isinstance(dtype, str) and hasattr(torch, dtype)`) que el primero --
445
+ esa línea corre ANTES de cualquier rama específica de framework, así
446
+ que reintentar con otro framework nunca podía esquivarla. Confirmado
447
+ además contra la guía de migración oficial de transformers 5.x: la
448
+ serie 5.x eliminó el backend TensorFlow POR COMPLETO y sin período de
449
+ gracia (PyTorch es el único backend soportado) -- no había ninguna
450
+ rama TF real a la que caer, el `except NameError: ... framework="tf"`
451
+ de las rondas previas apuntaba a código que ya no existe en la
452
+ librería instalada (`transformers==5.15.0`, ver requirements.txt).
453
+ El piso real es torch>=2.4 (Python 3.10+/huggingface_hub<2.0,>=1.3.0
454
+ son los otros dos). En macOS Intel (x86_64) NINGÚN wheel de `torch`
455
+ >2.2.2 existe en PyPI -- techo real y permanente de esa plataforma, no
456
+ arreglable con más código. Pinear `transformers` a la serie 4.x (que
457
+ SÍ soportaba TF) NO es salida: esa serie exige `huggingface-hub<1.0`
458
+ en TODAS sus versiones (confirmado en vivo, incl. el último release
459
+ 4.57.x), lo que choca de frente con `huggingface-hub<2.0,>=1.16.0` que
460
+ ya exige `gradio[oauth,mcp]==6.22.0` en el MISMO requirements.txt --
461
+ `ResolutionImpossible` real, no evitable sin romper el build de HF
462
+ Spaces (`gradio` no está platform-split, no puede estarlo: `sdk_version`
463
+ del README.md debe calzar exacto para TODA plataforma).
464
+ Conclusión honesta: FinBERT vía `transformers.pipeline()` es
465
+ IRRECUPERABLE en Mac Intel local con esta cadena de dependencias --
466
+ no es arreglable sin (a) un Mac Apple Silicon/Linux real, o (b)
467
+ remover `gradio[mcp]` del proyecto para poder bajar a transformers 4.x.
468
+ Producción (HF Space, Linux, `torch==2.11.0`) NO está afectada -- ahí
469
+ `torch_ver >= _TRANSFORMERS_MIN_TORCH` es verdadero y el pipeline
470
+ PyTorch carga y sirve FinBERT completo, sin ninguna rama de este fix
471
+ involucrada. Este fix, entonces, es sobre CALIDAD DE FALLO en Mac
472
+ Intel (un diagnóstico honesto, una sola vez, degrade limpio a
473
+ NEUTRAL_SCORE) -- no sobre "hacer funcionar" algo que la librería ya
474
+ no soporta en esa plataforma.
475
+ """
476
+ global _finbert_pipeline, _finbert_unavailable_reason
477
+ if _finbert_pipeline is not None:
478
+ return _finbert_pipeline
479
+ if _finbert_unavailable_reason is not None:
480
+ raise FinBERTUnavailableError(_finbert_unavailable_reason)
481
+
482
+ with _finbert_init_lock:
483
+ if _finbert_pipeline is not None: # doble check: otro hilo ya lo cargó mientras esperábamos el lock
484
+ return _finbert_pipeline
485
+ if _finbert_unavailable_reason is not None: # ídem, otro hilo ya lo diagnosticó como inviable
486
+ raise FinBERTUnavailableError(_finbert_unavailable_reason)
487
+
488
+ try:
489
+ import torch
490
+ from transformers import pipeline as _hf_pipeline
491
+ from transformers.utils import is_torch_available
492
+ except ModuleNotFoundError as exc:
493
+ # Caso real de "no instalado": el paquete no existe en este intérprete.
494
+ _finbert_unavailable_reason = (
495
+ f"torch/transformers no están instalados en {sys.executable}: {exc}. "
496
+ "Ejecuta `pip install torch transformers` en el MISMO venv que corre Uvicorn."
497
+ )
498
+ raise ImportError(_finbert_unavailable_reason) from exc
499
+ except ImportError as exc:
500
+ # CUALQUIER OTRO ImportError (símbolo nativo, dlopen roto, import
501
+ # circular parcial por carrera entre hilos, etc.) — antes se
502
+ # enmascaraba con el mismo mensaje genérico de "no instalado".
503
+ # Se preserva el tipo y mensaje reales para que el log no mienta.
504
+ _finbert_unavailable_reason = (
505
+ f"torch/transformers están instalados pero fallaron al importar "
506
+ f"({type(exc).__name__}: {exc}). NO es un paquete faltante — revisa "
507
+ "conflictos nativos (runtimes OpenMP duplicados TF/PyTorch en macOS, "
508
+ "ver KMP_DUPLICATE_LIB_OK) o reinstala ambos paquetes emparejados."
509
+ )
510
+ raise ImportError(_finbert_unavailable_reason) from exc
511
+
512
+ _ver_match = re.match(r"(\d+)\.(\d+)", torch.__version__)
513
+ torch_ver = tuple(int(p) for p in _ver_match.groups()) if _ver_match else (0, 0)
514
+ if not is_torch_available() or torch_ver < _TRANSFORMERS_MIN_TORCH:
515
+ _finbert_unavailable_reason = (
516
+ f"[FinBERT] no disponible en este proceso: torch {torch.__version__} "
517
+ f"instalado, transformers {__import__('transformers').__version__} exige "
518
+ f"torch>={'.'.join(map(str, _TRANSFORMERS_MIN_TORCH))} y ELIMINÓ el backend "
519
+ "TensorFlow por completo en la serie 5.x (verificado: framework='tf' dispara "
520
+ "la MISMA NameError compartida en pipeline() antes de cualquier rama TF real "
521
+ "-- no hay fallback posible). En macOS Intel ningún wheel de torch >2.2.2 "
522
+ "existe en PyPI (techo real de plataforma). NEWS_SENTIMENT_SCORE degradará a "
523
+ "NEUTRAL_SCORE de forma consistente en este proceso -- producción "
524
+ "(Linux, torch==2.11.0) no está afectada, ahí el piso SÍ se cumple."
525
+ )
526
+ logger.error(_finbert_unavailable_reason)
527
+ raise FinBERTUnavailableError(_finbert_unavailable_reason)
528
+
529
+ device = 0 if torch.cuda.is_available() else -1
530
+ try:
531
+ _finbert_pipeline = _hf_pipeline(
532
+ "sentiment-analysis", model=_FINBERT_MODEL_NAME,
533
+ tokenizer=_FINBERT_MODEL_NAME, truncation=True, device=device,
534
+ dtype=None, # esquiva `isinstance(dtype, str) and hasattr(torch, dtype)` (ver docstring)
535
+ )
536
+ except Exception as exc:
537
+ _finbert_unavailable_reason = (
538
+ f"[FinBERT] pipeline PyTorch falló pese a pasar el check de versión/"
539
+ f"is_torch_available() ({type(exc).__name__}: {exc})."
540
+ )
541
+ logger.error(_finbert_unavailable_reason, exc_info=True)
542
+ raise FinBERTUnavailableError(_finbert_unavailable_reason) from exc
543
+ return _finbert_pipeline
544
+
545
+ FINNHUB_API_KEY = os.getenv("FINNHUB_API_KEY", "").strip()
546
+ # V6 (auditoría "señal muerta" crypto_specialist) — `/company-news` es
547
+ # EXCLUSIVO para equities listadas en EE. UU. (doc oficial Finnhub); jamás
548
+ # devuelve resultados para tickers cripto. `/news?category=crypto` es el
549
+ # endpoint correcto para ese universo — ver `_fetch_headlines_finnhub`.
550
+ FINNHUB_COMPANY_NEWS_URL = "https://finnhub.io/api/v1/company-news"
551
+ FINNHUB_CRYPTO_NEWS_URL = "https://finnhub.io/api/v1/news"
552
+ # V11 -- MISMO endpoint que FINNHUB_CRYPTO_NEWS_URL (Finnhub `/news` acepta
553
+ # `category` general/forex/crypto/merger); alias legible para el fallback de
554
+ # ETFs (`_fetch_headlines_finnhub`, ver auditoría 2026-08), nunca un endpoint nuevo.
555
+ FINNHUB_GENERAL_NEWS_URL = FINNHUB_CRYPTO_NEWS_URL
556
+
557
+ NEWS_LOOKBACK_DAYS = 7 # ventana de titulares recientes a recolectar (fallback Finnhub)
558
+ MAX_HEADLINES_PER_TICKER = 60 # techo defensivo (rate-limit / ruido)
559
+ NEUTRAL_SCORE = 0.0 # relleno para días/activos sin cobertura de prensa
560
+ # V7 — tolerancia del merge_asof temporal (ver get_daily_news_sentiment):
561
+ # NEWS_LOOKBACK_DAYS + colchón de fin de semana/feriado, para que un titular
562
+ # del viernes siga cubriendo el lunes bursátil sin exigir calce EXACTO de
563
+ # fecha (el bug que _NEWS_MERGE_TOLERANCE_DAYS/pd.merge_asof reemplaza) y,
564
+ # a la vez, sin arrastrar sentimiento añejo indefinidamente como hacía el
565
+ # `.ffill()` sin cota que tenía este merge antes.
566
+ _NEWS_MERGE_TOLERANCE_DAYS = NEWS_LOOKBACK_DAYS + 3
567
+
568
+ _RETRY_ATTEMPTS = 3
569
+ _RETRY_BACKOFF_SECONDS = 1.5
570
+
571
+ # --- V8 (Filtrado Regime-Aware — aislamiento de ruido equity sin tocar cripto) ---
572
+ # Auditoría de atribución por gradiente: NEWS_SENTIMENT_SCORE cae a
573
+ # rank 17/17 en equity_specialist. Causa raíz NO es colisión con
574
+ # SENTIMENT_SCORE (esa es la correlación móvil activo<->VIX de
575
+ # compute_sentiment_score en train_kodaquant_v5.py/quanti_engine.py — un
576
+ # proxy de régimen/beta derivado 100% de precio, variable estructuralmente
577
+ # distinta de esta, cero solapamiento de información): es que la cobertura
578
+ # de prensa por-ticker vía DDGS/Finnhub es ESPORÁDICA en equity (pocos
579
+ # titulares/semana), así que la señal día a día alterna tramos planos
580
+ # (relleno neutro) con saltos discretos cada vez que aterriza un titular —
581
+ # exactamente el patrón de alta frecuencia que un BiLSTM aprende a
582
+ # descontar como ruido. crypto_specialist NO sufre esto: `/news?category=
583
+ # crypto` entrega flujo 24/7 sin huecos, la misma densidad/volatilidad
584
+ # cruda que llevó a crypto_specialist a 51.2%/52.3% de asertividad — jamás
585
+ # se suaviza.
586
+ # Fix: EMA regime-aware aplicado DENTRO de get_daily_news_sentiment (única
587
+ # fuente de esta columna para train_kodaquant_v5.py Y quanti_engine.py) ->
588
+ # consistencia train/inferencia automática, cero cambios en esos dos
589
+ # archivos, cero impacto en TECH_COLS/N_FEATURES/(batch,60,17).
590
+ NEWS_SENTIMENT_EMA_SPAN_EQUITY = 5 # ~1 semana bursátil: amortigua saltos discretos sin borrar la tendencia real
591
+ NEWS_SENTIMENT_EMA_SPAN_CRYPTO = 1 # span=1 -> alpha=2/(span+1)=1.0 -> no-op matemático exacto, señal cruda intacta
592
+
593
+
594
+ def _score_text(text: str) -> float:
595
+ """Escalar direccional (∈[-1, 1]) de un titular vía FinBERT (ProsusAI/finbert)."""
596
+ if not text:
597
+ return NEUTRAL_SCORE
598
+ if _finbert_onnx is not None or _finbert_onnx_unavailable is None:
599
+ try:
600
+ return _score_text_onnx(text[:2048])
601
+ except FinBERTUnavailableError:
602
+ pass # diagnosticado UNA vez en _get_finbert_onnx -> cae a torch
603
+ except Exception as exc: # noqa: BLE001
604
+ logger.warning("[FinBERT/ONNX] fallo de inferencia (%s: %s) -> fallback torch.",
605
+ type(exc).__name__, exc)
606
+ try:
607
+ result = _get_finbert_pipeline()(text[:512])[0]
608
+ raw_label = str(result["label"]).lower()
609
+ label = _FINBERT_LABEL_ALIASES.get(raw_label, raw_label)
610
+ if label not in _FINBERT_LABEL_SIGN:
611
+ # FIX RAÍZ V7 (auditoría "señal muerta" universal — 10 titulares
612
+ # obtenidos, 100% neutro, TODOS los activos, sin ningún otro
613
+ # warning en el log): antes, una etiqueta no reconocida caía en
614
+ # `_FINBERT_LABEL_SIGN.get(label, 0.0)` -> 0.0 SILENCIOSO. No es
615
+ # una excepción (no dispara el except de abajo), así que NUNCA
616
+ # quedaba rastro en el log de por qué el score era siempre 0 —
617
+ # exactamente el síntoma reportado, y explica por qué persistía
618
+ # pese al fix de timezone (esa parte del pipeline nunca fue el
619
+ # problema: los titulares SÍ llegaban, pero cada uno puntuaba
620
+ # 0.0 antes de tocar cualquier lógica de fechas). Ahora es ruidoso.
621
+ logger.warning(
622
+ "FinBERT devolvió una etiqueta no reconocida %r (fuera de "
623
+ "_FINBERT_LABEL_SIGN/_FINBERT_LABEL_ALIASES) -> score forzado "
624
+ "a NEUTRAL_SCORE para este titular. Verifica la versión de "
625
+ "`transformers` / el config.json de %s (id2label esperado: "
626
+ "0=positive, 1=negative, 2=neutral).", result["label"], _FINBERT_MODEL_NAME,
627
+ )
628
+ return NEUTRAL_SCORE
629
+ sign = _FINBERT_LABEL_SIGN[label]
630
+ return float(sign * result["score"])
631
+ except FinBERTUnavailableError:
632
+ # RONDA 10 -- caso YA diagnosticado con traceback completo UNA vez
633
+ # dentro de `_get_finbert_pipeline` (logger.error/exc_info=True ahí).
634
+ # Repetir el traceback completo por CADA titular es exactamente la
635
+ # causa real de las "cientos de líneas de error" reportadas -- acá
636
+ # alcanza con un rastro corto, sin traceback, por titular.
637
+ logger.debug("FinBERT no disponible en este proceso (ver diagnóstico previo) -> NEUTRAL_SCORE.")
638
+ return NEUTRAL_SCORE
639
+ except Exception as exc: # noqa: BLE001 — fallo de inferencia del modelo local, causa NO diagnosticada aún
640
+ # exc_info=True: antes se logueaba solo %r del error (a veces ya
641
+ # reescrito con un mensaje genérico), sin traceback — la causa real
642
+ # (incl. __cause__ encadenado) quedaba invisible en los logs de
643
+ # Uvicorn. Ahora se propaga completa -- SOLO para fallos nuevos/no
644
+ # cacheados (ver FinBERTUnavailableError arriba para el caso ya
645
+ # conocido).
646
+ logger.warning(
647
+ "FinBERT falló al puntuar titular (%s: %s)", type(exc).__name__, exc,
648
+ exc_info=True,
649
+ )
650
+ return NEUTRAL_SCORE
651
+
652
+
653
+ def _normalize_timestamp(ts_raw) -> Optional[datetime]:
654
+ """Normaliza epoch (int/float) o string de fecha a `datetime` UTC."""
655
+ if ts_raw is None:
656
+ return None
657
+ try:
658
+ if isinstance(ts_raw, (int, float)):
659
+ return datetime.fromtimestamp(float(ts_raw), tz=timezone.utc)
660
+ return pd.Timestamp(ts_raw, tz="UTC").to_pydatetime()
661
+ except (ValueError, TypeError, OSError):
662
+ return None
663
+
664
+
665
+ # V11 -- umbral calibrado empíricamente (ver auditoría 2026-08): `detect()`
666
+ # ingenuo (top-1, sin probabilidad) da FALSOS POSITIVOS reales en titulares
667
+ # financieros cortos -- "Tesla stock drops on delivery miss" clasificó como
668
+ # sueco con `detect()`. `detect_langs()` expone la distribución de
669
+ # probabilidad completa; frases reales en español/inglés (>=20 chars)
670
+ # resuelven con >0.999 de confianza al idioma correcto, mientras que el
671
+ # ruido de titulares cortos ambiguos rara vez supera 0.97 -- de ahí el
672
+ # doble filtro (confianza alta Y longitud mínima) en vez de un simple
673
+ # top-1, que habría descartado titulares en inglés legítimos.
674
+ _LANGDETECT_MIN_CONFIDENCE = 0.97
675
+ _LANGDETECT_MIN_LENGTH = 20
676
+
677
+
678
+ def _is_english_headline(title: str) -> bool:
679
+ """
680
+ Defensa en profundidad (V11) -- filtro de idioma PREVIO al scorer.
681
+ `True` (se deja pasar a FinBERT) salvo que `langdetect` esté MUY seguro
682
+ (`prob >= _LANGDETECT_MIN_CONFIDENCE`) de que el idioma NO es inglés,
683
+ sobre un titular con longitud suficiente para que esa confianza sea
684
+ confiable (`len >= _LANGDETECT_MIN_LENGTH`) -- en cualquier otro caso
685
+ (ambiguo, corto, o `langdetect` no instalado) se deja pasar: este
686
+ filtro poda la cola larga de titulares CLARAMENTE no-ingleses, nunca
687
+ reemplaza el fix de región (`NEWS_SENTIMENT_DDG_REGION`).
688
+ """
689
+ if not _LANGDETECT_AVAILABLE or not title or len(title) < _LANGDETECT_MIN_LENGTH:
690
+ return True
691
+ try:
692
+ top = _langdetect_detect_langs(title)[0]
693
+ except Exception: # noqa: BLE001 -- langdetect lanza LangDetectException en texto ambiguo
694
+ return True
695
+ return not (top.lang != "en" and top.prob >= _LANGDETECT_MIN_CONFIDENCE)
696
+
697
+
698
+ def _fetch_headlines_ddg(ticker: str, max_results: int = MAX_DDG_HEADLINES) -> list[dict]:
699
+ """
700
+ Fuente primaria — búsqueda de noticias vía DDGS (`ddgs.news`, JSON nativo
701
+ de DuckDuckGo, sin scraping de portales individuales, sin API key).
702
+ Reemplaza 1:1 el rol de `yfinance.Ticker(ticker).news` (retirado, ver
703
+ services/market_data.py): misma firma de retorno (`title`/`published_at`),
704
+ mismo lugar en `fetch_recent_headlines` (primaria, Finnhub complementa).
705
+
706
+ V11 (auditoría 2026-08) -- dos mejoras sobre la fuente primaria:
707
+ (a) reintento con query MÁS AMPLIA si la query específica (`"{ticker}
708
+ stock"`) devuelve 0 resultados -- tickers de baja cobertura de
709
+ prensa dedicada (ETFs como SPY, sin "compañía" detrás) rendían
710
+ "No results found" en vez de degradarse a Finnhub con más señal.
711
+ (b) filtro de idioma (`_is_english_headline`) ANTES de devolver los
712
+ titulares -- ver V11 arriba.
713
+ """
714
+ if DDGS is None:
715
+ logger.warning("DDGS no instalado (`pip install ddgs`) -- fuente primaria de noticias deshabilitada; solo Finnhub (si hay API key).")
716
+ return []
717
+
718
+ # Cripto: "-USD" es la convención de símbolo de todo el proyecto
719
+ # (REGIME_TICKERS/MACRO_SYMBOL_MAP), no específica de ningún proveedor
720
+ # -- se usa solo el símbolo base (ej. "BTC") para una query de noticias
721
+ # más natural que "BTC-USD".
722
+ is_crypto = _is_crypto_ticker(ticker)
723
+ base_symbol = ticker.split("-")[0]
724
+ queries = [f"{base_symbol} crypto"] if is_crypto else [f"{ticker} stock", f"{ticker} ETF", base_symbol]
725
+
726
+ raw: list[dict] = []
727
+ for query in queries:
728
+ try:
729
+ with DDGS() as ddgs:
730
+ raw = list(
731
+ ddgs.news(query, region=DDG_REGION, safesearch=DDG_SAFESEARCH, max_results=max_results)
732
+ )
733
+ except Exception as exc: # noqa: BLE001 -- red/HTTP transitorio de DDG
734
+ logger.warning("DDGS.news falló para %s (query=%r): %r", ticker, query, exc)
735
+ continue
736
+ if raw:
737
+ break # primera query con resultados gana -- no seguimos ampliando innecesariamente
738
+
739
+ headlines = []
740
+ dropped_non_english = 0
741
+ for item in raw:
742
+ title = (item.get("title") or "").strip()
743
+ published_at = _normalize_timestamp(item.get("date"))
744
+ if not title or published_at is None:
745
+ continue
746
+ if not _is_english_headline(title):
747
+ dropped_non_english += 1
748
+ continue
749
+ headlines.append({"title": title, "published_at": published_at})
750
+ if dropped_non_english:
751
+ logger.debug("%s: %d titular(es) descartado(s) por filtro de idioma (no-inglés).", ticker, dropped_non_english)
752
+ return headlines
753
+
754
+
755
+ def _is_crypto_ticker(ticker: str) -> bool:
756
+ """
757
+ Heurística deliberadamente auto-contenida (sin importar `REGIME_TICKERS`
758
+ de quanti_engine.py/train_kodaquant_v5.py: SON quienes importan
759
+ data_pipeline.py, importar en sentido inverso crearía un ciclo). La
760
+ convención de todo el proyecto para cripto es SIEMPRE '<SÍMBOLO>-USD'
761
+ (BTC-USD, ETH-USD); ningún ticker de equity/ETF del universo entrenado
762
+ usa ese sufijo -> heurística exacta y suficiente para este propósito.
763
+ """
764
+ return ticker.upper().endswith("-USD")
765
+
766
+
767
+ def _fetch_headlines_finnhub(ticker: str, lookback_days: int = NEWS_LOOKBACK_DAYS) -> list[dict]:
768
+ """
769
+ Fallback — API REST gratuita de Finnhub, JSON puro, sin scraping.
770
+ Requiere `FINNHUB_API_KEY` en el entorno; si falta, se omite
771
+ silenciosamente (DDGS sigue siendo la fuente primaria y suficiente
772
+ en la mayoría de los casos).
773
+
774
+ V6 (auditoría "señal muerta" `crypto_specialist`, NEWS_SENTIMENT_SCORE
775
+ rank 17/17, atribución 0.000000) — FIX de enrutamiento: `/company-news`
776
+ es EXCLUSIVO para equities listadas en EE. UU. (documentación oficial
777
+ de Finnhub) y nunca devuelve resultados para tickers cripto; antes se
778
+ llamaba ese mismo endpoint también para BTC-USD/ETH-USD, vaciando
779
+ silenciosamente el fallback justo para el régimen que más lo necesita.
780
+ Se enruta ahora vía `_is_crypto_ticker` al endpoint general
781
+ `/news?category=crypto` para cripto (sin filtro por símbolo: el tier
782
+ gratuito de Finnhub no ofrece news cripto por-moneda -> se filtra la
783
+ ventana `lookback_days` del lado del cliente, ya que ese endpoint no
784
+ acepta `from`/`to`) y mantiene `/company-news` intacto para equities.
785
+ """
786
+ if not FINNHUB_API_KEY:
787
+ logger.debug("FINNHUB_API_KEY no configurada; se omite el fallback de Finnhub.")
788
+ return []
789
+
790
+ is_crypto = _is_crypto_ticker(ticker)
791
+ url = FINNHUB_CRYPTO_NEWS_URL if is_crypto else FINNHUB_COMPANY_NEWS_URL
792
+ today = datetime.now(timezone.utc).date()
793
+ since = today - timedelta(days=lookback_days)
794
+ if is_crypto:
795
+ params = {"category": "crypto", "token": FINNHUB_API_KEY}
796
+ else:
797
+ params = {
798
+ "symbol": ticker,
799
+ "from": since.isoformat(),
800
+ "to": today.isoformat(),
801
+ "token": FINNHUB_API_KEY,
802
+ }
803
+
804
+ # `filter_clientside_by_date`: True para cualquier llamada al endpoint
805
+ # genérico `/news` (crypto O general), que NO acepta `from`/`to`
806
+ # server-side -- `/company-news` sí los acepta (ver `params` arriba),
807
+ # así que ese caso no necesita el recorte extra.
808
+ headlines = _fetch_finnhub_json(url, params, ticker, filter_clientside_by_date=is_crypto, since=since)
809
+
810
+ # V11 (auditoría 2026-08) -- `/company-news` es EXCLUSIVO de compañías
811
+ # con perfil en Finnhub; ETFs (SPY, QQQ, ...) NUNCA tienen uno y
812
+ # devuelven [] SIEMPRE, sin importar cuántos reintentos. Fallback a
813
+ # `/news?category=general` (mercado agregado) filtrado client-side por
814
+ # el símbolo/nombre del ticker en el titular -- mejor que dejar el
815
+ # activo entero sin ninguna señal de prensa cuando DDGS tampoco rindió.
816
+ if not headlines and not is_crypto:
817
+ general_params = {"category": "general", "token": FINNHUB_API_KEY}
818
+ general = _fetch_finnhub_json(FINNHUB_GENERAL_NEWS_URL, general_params, ticker,
819
+ filter_clientside_by_date=True, since=since)
820
+ needle = ticker.upper()
821
+ headlines = [h for h in general if needle in h["title"].upper()]
822
+
823
+ return headlines
824
+
825
+
826
+ def _fetch_finnhub_json(url: str, params: dict, ticker: str, filter_clientside_by_date: bool, since) -> list[dict]:
827
+ """Request GET con reintentos -- extraído de `_fetch_headlines_finnhub` para
828
+ reutilizarlo también en el fallback `/news?category=general` de ETFs.
829
+ `filter_clientside_by_date`: True para endpoints sin `from`/`to`
830
+ server-side (`/news`, crypto o general) -- recorta del lado del cliente
831
+ contra `since` para no arrastrar noticias arbitrariamente viejas."""
832
+ last_exc: Exception | None = None
833
+ for attempt in range(1, _RETRY_ATTEMPTS + 1):
834
+ try:
835
+ response = requests.get(url, params=params, timeout=10)
836
+ response.raise_for_status()
837
+ payload = response.json() or []
838
+ headlines = []
839
+ for item in payload[:MAX_HEADLINES_PER_TICKER]:
840
+ title = item.get("headline") or item.get("summary") or ""
841
+ published_at = _normalize_timestamp(item.get("datetime"))
842
+ if filter_clientside_by_date and published_at is not None and published_at.date() < since:
843
+ continue
844
+ if title and published_at is not None:
845
+ headlines.append({"title": title, "published_at": published_at})
846
+ return headlines
847
+ except Exception as exc: # noqa: BLE001 — red/HTTP transitorio
848
+ last_exc = exc
849
+ if attempt == _RETRY_ATTEMPTS:
850
+ break
851
+ time.sleep(_RETRY_BACKOFF_SECONDS * attempt)
852
+
853
+ logger.warning("Finnhub falló tras %d intentos para %s: %r", _RETRY_ATTEMPTS, ticker, last_exc)
854
+ return []
855
+
856
+
857
+ def fetch_recent_headlines(ticker: str) -> list[dict]:
858
+ """
859
+ Orquesta ambas fuentes nativas (DDGS -> Finnhub) y deduplica por
860
+ título. DDGS es la fuente primaria (no exige API key); Finnhub
861
+ complementa cobertura solo cuando DDGS devuelve pocos titulares.
862
+
863
+ CacheManager (kodaquant_core): cachea el resultado ya deduplicado por
864
+ `_HEADLINE_CACHE_TTL_SECONDS` -- evita re-golpear DDGS/Finnhub por
865
+ ticker dentro de la misma ventana corta cuando el radar escanea el
866
+ universo completo. Purga automática local en cada llamada (best-effort,
867
+ nunca bloquea el fetch real si falla).
868
+ """
869
+ try:
870
+ _headline_cache.purge_stale()
871
+ except Exception as exc: # noqa: BLE001 -- la purga nunca debe tumbar el fetch real
872
+ logger.debug("[CacheManager] purge_stale falló (%r) -- se ignora.", exc)
873
+
874
+ cache_key = f"headlines_{ticker}"
875
+ cached = _headline_cache.get_json(cache_key)
876
+ if cached is not None:
877
+ for h in cached:
878
+ h["published_at"] = _normalize_timestamp(h.get("published_at"))
879
+ return [h for h in cached if h.get("published_at") is not None]
880
+
881
+ headlines = _fetch_headlines_ddg(ticker)
882
+ if len(headlines) < 5:
883
+ headlines += _fetch_headlines_finnhub(ticker)
884
+
885
+ seen_titles: set[str] = set()
886
+ deduped: list[dict] = []
887
+ for h in headlines:
888
+ if h["title"] not in seen_titles:
889
+ seen_titles.add(h["title"])
890
+ deduped.append(h)
891
+ deduped = deduped[:MAX_HEADLINES_PER_TICKER]
892
+
893
+ serializable = [
894
+ {"title": h["title"], "published_at": h["published_at"].isoformat()}
895
+ for h in deduped
896
+ ]
897
+ _headline_cache.set_json(cache_key, serializable)
898
+ return deduped
899
+
900
+
901
+ def get_daily_news_sentiment(
902
+ ticker: str,
903
+ target_index: pd.DatetimeIndex,
904
+ scorer_fn: Callable[[str], float] = _score_text,
905
+ ) -> pd.Series:
906
+ """
907
+ Devuelve `NEWS_SENTIMENT_SCORE` alineado día a día contra `target_index`
908
+ (el mismo índice temporal que ya usan RSI/MACD/ATR/etc.). Cada titular se
909
+ promedia por día de publicación (UTC, normalizado a medianoche); los
910
+ días sin cobertura de prensa se rellenan hacia adelante (`ffill`) y, si
911
+ no hay ningún titular previo disponible, con `NEUTRAL_SCORE` (0.0) — la
912
+ misma convención de "lectura neutra" que SENTIMENT_SCORE ya usa en V4.
913
+
914
+ Esta función debe llamarse ANTES de concatenar el tensor final al
915
+ espacio de entrada (batch, time_steps, features), junto al resto de los
916
+ indicadores técnicos en `engineer_asset`.
917
+
918
+ FIX RAÍZ V7 (auditoría "señal muerta" — persiste tras el fix de tz V6,
919
+ NEWS_SENTIMENT_SCORE rank 17/17, atribución exacta 0.000000, EN TODOS
920
+ LOS ACTIVOS, no solo cripto): el fix V6 (despojar tz antes de comparar
921
+ fechas) era necesario pero NO suficiente — quedaban dos fallos
922
+ independientes, cualquiera de los dos basta por sí solo para colapsar
923
+ la columna entera a 0.0:
924
+
925
+ (a) SCORER: ver `_score_text` — una etiqueta de FinBERT no reconocida
926
+ caía en `.get(label, 0.0)` -> 0.0 silencioso, SIN excepción, para
927
+ el 100% de los titulares, en TODOS los tickers por igual (fix
928
+ separado, ver ese docstring).
929
+ (b) MERGE: `Series.reindex` exige que la fecha-calendario del
930
+ titular calce EXACTA (bit a bit) con una fila del índice de
931
+ trading. Cripto cotiza 24/7 (hay fila para cada día), pero
932
+ equities NO — cualquier titular publicado un fin de semana o
933
+ feriado bursátil no tenía dónde aterrizar y quedaba NaN -> 0.0,
934
+ sin importar qué tan bien alineados estuvieran los tz. Se
935
+ reemplaza por `pd.merge_asof(direction="backward")`: busca el
936
+ titular MÁS RECIENTE publicado EN O ANTES de cada fecha del
937
+ índice (sin exigir igualdad exacta), acotado por
938
+ `_NEWS_MERGE_TOLERANCE_DAYS` para no arrastrar sentimiento añejo
939
+ indefinidamente como hacía el `.ffill()` sin cota anterior.
940
+
941
+ Ambos lados de la fecha se normalizan ahora de forma SIMÉTRICA a
942
+ fecha-calendario UTC (`tz_convert("UTC")` real, no un `tz_localize(None)`
943
+ que solo despoja la etiqueta sin convertir el instante) — antes los
944
+ titulares se convertían a UTC pero `target_index` solo se despojaba de
945
+ su tz "tal cual", una asimetría de la que dependía silenciosamente el
946
+ calce.
947
+ """
948
+ headlines = fetch_recent_headlines(ticker)
949
+
950
+ if not headlines:
951
+ logger.info("Sin titulares recientes para %s -> NEWS_SENTIMENT_SCORE neutro.", ticker)
952
+ return pd.Series(NEUTRAL_SCORE, index=target_index, name="NEWS_SENTIMENT_SCORE")
953
+
954
+ scored = pd.DataFrame(headlines)
955
+ scored["score"] = scored["title"].map(scorer_fn)
956
+
957
+ # Diagnóstico (a): aísla un SCORER muerto de un MERGE con mala cobertura
958
+ # temporal — antes ambos colapsaban al mismo mensaje genérico y eran
959
+ # indistinguibles desde el log.
960
+ nonzero_scores = int((scored["score"].abs() > 1e-9).sum())
961
+
962
+ scored["date"] = (
963
+ pd.DatetimeIndex(scored["published_at"]).tz_convert("UTC").tz_localize(None).normalize()
964
+ )
965
+ daily = (
966
+ scored.groupby("date")["score"].mean()
967
+ .sort_index()
968
+ .rename("headline_score")
969
+ .reset_index()
970
+ )
971
+
972
+ target_dt = pd.DatetimeIndex(target_index)
973
+ if target_dt.tz is not None:
974
+ target_dates = target_dt.tz_convert("UTC").tz_localize(None).normalize()
975
+ else:
976
+ target_dates = target_dt.normalize()
977
+
978
+ # FIX: pandas 3.x ya no fuerza datetime64[ns] en todos lados -- conserva
979
+ # la resolución de origen de cada Serie (target_index puede venir en
980
+ # [us] del feed de mercado (Twelve Data/Stooq, ver services/market_data.py),
981
+ # "date" en [s] desde el parseo de published_at).
982
+ # merge_asof exige que ambas claves compartan EXACTAMENTE el mismo
983
+ # dtype, si no: "incompatible merge keys ... must be the same type".
984
+ # Se normalizan ambas a [ns] explícitamente antes de mergear.
985
+ frame = pd.DataFrame({"target_date": target_dates.astype("datetime64[ns]")})
986
+ frame["orig_pos"] = range(len(frame))
987
+ frame_sorted = frame.sort_values("target_date", kind="stable")
988
+ daily["date"] = daily["date"].astype("datetime64[ns]")
989
+
990
+ merged = pd.merge_asof(
991
+ frame_sorted,
992
+ daily,
993
+ left_on="target_date",
994
+ right_on="date",
995
+ direction="backward",
996
+ tolerance=pd.Timedelta(days=_NEWS_MERGE_TOLERANCE_DAYS),
997
+ ).sort_values("orig_pos")
998
+
999
+ aligned = pd.Series(
1000
+ merged["headline_score"].to_numpy(), index=target_index, name="NEWS_SENTIMENT_SCORE",
1001
+ )
1002
+ aligned = aligned.fillna(NEUTRAL_SCORE).clip(-1.0, 1.0)
1003
+
1004
+ # Canario de cobertura, ahora DESAMBIGUADO: si la columna vuelve a
1005
+ # colapsar a puro NEUTRAL_SCORE, el log dice CUÁL de las dos causas
1006
+ # posibles es — nunca más un mensaje genérico "revisar fechas o API"
1007
+ # cuando el problema real puede estar en el scorer y viceversa.
1008
+ if (aligned == NEUTRAL_SCORE).all():
1009
+ if nonzero_scores == 0:
1010
+ logger.warning(
1011
+ "NEWS_SENTIMENT_SCORE 100%% neutro para %s: los %d titular(es) "
1012
+ "obtenidos puntuaron EXACTAMENTE 0.0 en el scorer -> revisar, "
1013
+ "en orden: (1) warnings de '_score_text'/etiqueta FinBERT no "
1014
+ "reconocida arriba en el log; (2) idioma real de esos "
1015
+ "titulares -- ProsusAI/finbert es inglés-únicamente, un "
1016
+ "titular no-inglés puntúa 'neutral' SIN lanzar ningún warning "
1017
+ "(ver V10, DDG_REGION); el merge de fechas es irrelevante, la "
1018
+ "señal ya nace muerta antes de tocar cualquier lógica temporal.",
1019
+ ticker, len(headlines),
1020
+ )
1021
+ else:
1022
+ logger.warning(
1023
+ "NEWS_SENTIMENT_SCORE 100%% neutro para %s pese a %d titular(es) "
1024
+ "obtenidos Y %d de ellos con score no-neutro real -> el scorer "
1025
+ "funciona, es un problema de COBERTURA TEMPORAL: ninguna fecha "
1026
+ "cae dentro de la tolerancia de %d día(s) contra target_index "
1027
+ "(¿target_index desactualizado / caché parquet vieja / rango "
1028
+ "histórico que no llega hasta fechas recientes?).",
1029
+ ticker, len(headlines), nonzero_scores, _NEWS_MERGE_TOLERANCE_DAYS,
1030
+ )
1031
+
1032
+ # V8 — suavizado EMA regime-aware (ver constantes arriba): el canario de
1033
+ # cobertura recién evaluado corre SIEMPRE sobre la señal cruda (`aligned`
1034
+ # sin suavizar) para no enmascarar un scorer/merge realmente muerto tras
1035
+ # una EMA; el suavizado se aplica acá, al final, solo sobre lo que
1036
+ # efectivamente entra al tensor.
1037
+ ema_span = NEWS_SENTIMENT_EMA_SPAN_CRYPTO if _is_crypto_ticker(ticker) else NEWS_SENTIMENT_EMA_SPAN_EQUITY
1038
+ if ema_span > 1:
1039
+ aligned = aligned.ewm(span=ema_span, adjust=False).mean().rename("NEWS_SENTIMENT_SCORE")
1040
+
1041
+ return aligned
ml_engine/entrenamiento.py ADDED
@@ -0,0 +1,1144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ #!pip install yfinance -q
3
+
4
+ """
5
+ Pipeline Predictivo GLOBAL Multi-Activo: Attention-BiLSTM (Log-Returns) — V4
6
+ =============================================================================
7
+ Arquitectura (V4 — PODADA respecto a V1-V3, ver sección 10 más abajo):
8
+ BiLSTM(64) -> LayerNorm -> [MultiHeadAttention + Residual]
9
+ -> LayerNorm -> BahdanauAttention (pooling de contexto)
10
+ -> Concat(context, Embedding(asset_id)) -> Dropout(0.45)
11
+ -> [Dense(32)+L2 + Residual(proyección+L2)] -> LayerNorm -> Dense(1)+L2
12
+ Entorno objetivo: local (VSCode / macOS), TensorFlow/Keras 3.x
13
+
14
+ CAMBIOS RESPECTO A LA V1 (single-asset, precio absoluto):
15
+
16
+ 1) GLOBAL MULTI-ACTIVO: se entrena UN SOLO modelo sobre 10 activos distintos,
17
+ combinados en un dataset masivo. Un input categórico `asset_id` (Embedding)
18
+ le da al modelo la capacidad de diferenciar el "régimen" de cada activo
19
+ dentro del mismo espacio de pesos compartido — sin esto, el modelo no
20
+ podría distinguir un día de BTC-USD de un día de SPY.
21
+
22
+ 2) TARGET = LOG-RETURN, no precio absoluto. Un LSTM entrenado a predecir el
23
+ precio absoluto de un activo casi-random-walk aprende trivialmente a
24
+ "copiar" el último precio conocido (efecto shadow/lag: la predicción
25
+ parece la serie real desplazada un día). Al predecir
26
+ log(P_t / P_{t-1}) forzamos al modelo a aprender señal real, no inercia.
27
+ El precio se RECONSTRUYE matemáticamente en evaluación:
28
+ P_hat_t = P_{t-1} * exp(r_hat_t)
29
+
30
+ 3) NORMALIZACIÓN POR ACTIVO: cada activo tiene su propio feature_scaler y su
31
+ propio target_scaler, ajustados SOLO con el tramo de train de ESE activo.
32
+ Esto evita que activos de alta volatilidad (BTC-USD) dominen la pérdida
33
+ frente a activos de baja volatilidad (SPY), y evita fuga de información
34
+ train/test.
35
+
36
+ 4) MÉTRICA NUEVA: directional accuracy (% de aciertos en el SIGNO del
37
+ retorno), la métrica que realmente importa en un modelo de retornos —
38
+ MAE/RMSE de precio reconstruido pueden verse "bien" incluso si el modelo
39
+ no acierta la dirección.
40
+
41
+ CAMBIOS V2 (este archivo):
42
+
43
+ 5) FEATURES DE VOLATILIDAD/VOLUMEN: ATR_14 (volatilidad absoluta), BB_WIDTH_20
44
+ (volatilidad relativa vía Bollinger) y OBV (volumen firmado acumulado).
45
+ Requieren descargar High/Low/Volume además de Close -> `download_all`
46
+ ahora trae el bundle OHLCV completo, no solo Close.
47
+
48
+ 6) ARQUITECTURA: LayerNormalization tras cada bloque recurrente/atencional
49
+ (estabiliza la escala de los hidden states entre capas), un bloque de
50
+ MultiHeadAttention auto-atencional CON conexión residual antes del
51
+ Bahdanau (que sigue actuando como pooling final de contexto), y una
52
+ conexión residual (con proyección lineal para igualar dimensiones) en el
53
+ bloque denso profundo.
54
+
55
+ 7) PÉRDIDA ASIMÉTRICA DIRECCIONAL: `DirectionalHuberLoss` escala Huber por
56
+ (1 + gamma) cuando sign(y_true) != sign(y_pred). CORRECCIÓN NECESARIA:
57
+ para que "signo en espacio escalado" == "signo del retorno real", el
58
+ target_scaler pasa de StandardScaler() a StandardScaler(with_mean=False)
59
+ (solo divide por sigma, no resta la media) — de lo contrario, en activos
60
+ con drift fuerte (BTC, NVDA) el "cruce por cero" quedaría desplazado a
61
+ y_raw=mu≠0 y la pérdida direccional penalizaría el signo EQUIVOCADO en un
62
+ sub-conjunto de muestras cercanas a cero. Ver docstring de la clase.
63
+
64
+ 8) SCHEDULING: CosineDecayRestarts reemplaza a EarlyStopping/ReduceLROnPlateau
65
+ como mecanismo de escape de mínimos locales, inyectado directamente en el
66
+ optimizador (así es como Keras 3 espera un LearningRateSchedule — NO como
67
+ callback). ModelCheckpoint(save_best_only=True) + recarga post-fit se
68
+ mantienen para no terminar el entrenamiento con los pesos de la ÚLTIMA
69
+ época (que tras un reinicio de LR puede ser peor que un punto intermedio).
70
+
71
+ CAMBIOS V3 (este archivo) — FIX DEL COLAPSO "COBARDE":
72
+
73
+ 9) DIAGNÓSTICO V2: con gamma=1.5 FIJO desde el Epoch 0, el gradiente de la
74
+ penalización direccional domina antes de que el modelo aprenda siquiera
75
+ la ESCALA de los retornos. La salida más "segura" para minimizar
76
+ Huber*(1+gamma) bajo incertidumbre de signo es predecir ŷ≈0 (error de
77
+ magnitud pequeño) -> loss y mae siguen bajando mientras
78
+ directional_accuracy se estanca en ~38% (peor que el 50% de una moneda
79
+ justa, señal de que el sesgo hacia 0 rompe incluso el empate esperable
80
+ de un ŷ aleatorio). Los 4 cambios de abajo atacan esto sin tocar la
81
+ arquitectura (Fases A/B se mantienen idénticas a la V2).
82
+
83
+ 9.1) CURRICULUM LEARNING (GAMMA DINÁMICO). `gamma` deja de ser un float
84
+ Python y pasa a ser un `keras.Variable` no-entrenable, mutado por
85
+ `DynamicGammaCallback` en `on_epoch_begin` según un warmup de
86
+ GAMMA_WARMUP_EPOCHS épocas:
87
+
88
+ progress(e) = clip(e / GAMMA_WARMUP_EPOCHS, 0, 1)
89
+
90
+ # Lineal:
91
+ gamma(e) = GAMMA_MAX * progress(e)
92
+
93
+ # Sigmoide (GAMMA_SCHEDULE="sigmoid", por defecto) — la mayor
94
+ # parte del cambio se concentra a mitad de camino en vez de
95
+ # repartirse uniforme; k=GAMMA_SIGMOID_STEEPNESS controla qué tan
96
+ # abrupta es esa zona central. Se renormaliza para que
97
+ # gamma(0)=0 exacto y gamma(GAMMA_WARMUP_EPOCHS)=GAMMA_MAX exacto
98
+ # (un sigmoide crudo nunca toca 0 ni 1 en sus extremos):
99
+ sig(x) = 1 / (1 + e^(-k*(x - 0.5)))
100
+ gamma(e) = GAMMA_MAX * (sig(progress(e)) - sig(0)) / (sig(1) - sig(0))
101
+
102
+ Con gamma≈0 en las primeras épocas la pérdida es Huber prácticamente
103
+ puro -> el modelo explora magnitudes de retorno sin miedo al castigo
104
+ direccional. Solo cuando gamma empieza a crecer el gradiente también
105
+ empuja a acertar el SIGNO, ya sobre una base de magnitud razonable,
106
+ evitando el óptimo local "predecir 0" que domina cuando ambos
107
+ objetivos compiten desde el Epoch 0.
108
+
109
+ 9.2) GRADIENT CLIPPING. `AdamW(clipnorm=GRAD_CLIPNORM=1.0)`: recorta la
110
+ norma global del gradiente antes de cada update. Con 14 features
111
+ (ATR/OBV con escalas y ruido propios) y los picos de LR que introduce
112
+ cada reinicio de CosineDecayRestarts, un batch con outliers puede
113
+ generar un gradiente desproporcionado que explota los pesos justo
114
+ tras un reinicio -> clipnorm pone un techo duro a esa norma,
115
+ complementando (no reemplazando) a TerminateOnNaN().
116
+
117
+ 9.3) REINICIOS DE LR MÁS FRECUENTES. LR_RESTART_PERIOD_EPOCHS baja de 10 a
118
+ 8: reinicios más seguidos agitan la superficie de pérdida con más
119
+ regularidad, ayudando a escapar de mínimos locales -> no se lleva a 5
120
+ para no superponer dos fuentes de inestabilidad (reinicio de LR +
121
+ rampa de gamma) dentro de la misma ventana de épocas.
122
+
123
+ 9.4) REGULARIZACIÓN. Dropout del bloque de fusión sube de 0.4 a 0.45
124
+ (DROPOUT_RATE) + L2 leve (DENSE_L2_REG=1e-5) en las 3 capas Dense de
125
+ la cabeza (post_fusion_dense, fused_projection_skip, return_head):
126
+ fuerza a esas capas a apoyarse en pesos más pequeños y distribuidos,
127
+ en vez de memorizar combinaciones específicas de features ruidosas
128
+ del set de entrenamiento.
129
+
130
+ CAMBIOS V4 (este archivo) — REFACTOR ESTADÍSTICO/ARQUITECTÓNICO INSTITUCIONAL:
131
+
132
+ 10) DIAGNÓSTICO V3: pese al curriculum de gamma, el modelo seguía
133
+ convergiendo a ŷ≈0 en gran parte de las muestras (directional_accuracy
134
+ < 40%, peor que el 50% de una moneda justa). Causas identificadas:
135
+ (a) los factores macro entraban al feature_scaler como NIVEL crudo
136
+ (no-estacionario), (b) la red seguía sobre-parametrizada para 14
137
+ features, y (c) minimizar Huber puro bajo ruido sigue premiando
138
+ ŷ≈0 aunque gamma sea 0 al inicio del curriculum. Los 4 cambios de abajo
139
+ atacan cada causa; el curriculum de gamma (9.1-9.3) y el resto de la
140
+ V3 se MANTIENEN sin cambios salvo donde se indica explícitamente.
141
+
142
+ 10.1) ESTACIONARIEDAD ESTRICTA (Fase A). `engineer_asset` transforma TODOS
143
+ los factores macro (^GSPC, ^TNX, ^VIX, GC=F, DX-Y.NYB) a log-return
144
+ ANTES de que `build_asset_dataset` los pase al feature_scaler —
145
+ exactamente el mismo tratamiento que ya recibía el target:
146
+ r_macro_t = log(P_macro_t / P_macro_{t-1})
147
+ Nunca se pasa un nivel/precio macro crudo al scaler. Sin esto, un
148
+ MinMaxScaler ajustado en el tramo de train de ^TNX/^VIX/etc. queda
149
+ "descalibrado" en cuanto el nivel deriva fuera del rango de
150
+ entrenamiento (el mismo problema de raíz unitaria que motivó predecir
151
+ log-return en vez de precio para el target).
152
+
153
+ 10.2) SENTIMENT_SCORE VÍA CORRELACIÓN CRUZADA. `compute_sentiment_score`
154
+ deja de ser un Z-score de momentum propio del activo (V1-V3) y pasa a
155
+ ser la correlación de Pearson MÓVIL (ventana SENTIMENT_LOOKBACK=20)
156
+ entre el log-return del activo y el log-return de un factor macro de
157
+ referencia (SENTIMENT_MACRO_PROXY="^VIX" por defecto, con fallback al
158
+ primer macro_ticker si no está presente en MACRO_TICKERS):
159
+ rho_t = Corr_{k=t-20..t}( r_asset_k , r_VIX_k )
160
+ Una caída/inversión abrupta de esa correlación respecto a su nivel
161
+ histórico es la firma matemática de un shock IDIOSINCRÁTICO del
162
+ activo (noticia específica) que rompe su co-movimiento habitual con
163
+ el miedo/mercado agregado — una señal mucho más específica que "qué
164
+ tan extremo fue el retorno de hoy frente a su propia distribución".
165
+
166
+ 10.3) TOPOLOGÍA DE OCKHAM (Fase B). `BiLSTM(256)->BiLSTM(128)` se poda a
167
+ una ÚNICA `BiLSTM(64)`. El bloque de MultiHeadAttention (con
168
+ residual) y el pooling de BahdanauAttention se MANTIENEN intactos.
169
+ Al desaparecer la segunda rama recurrente, la fusión pasa de
170
+ [context_vector, bilstm_2, asset_embed] a [context_vector,
171
+ asset_embed], y la cabeza densa (post_fusion_dense +
172
+ fused_projection_skip) se poda de 64 a 32 unidades — un modelo con
173
+ muchos menos parámetros para 14 features de entrada, que fuerza
174
+ representaciones generalizadas en vez de memorización de ruido.
175
+
176
+ 10.4) PENALIZACIÓN DE VARIANZA — LA CURA DE LA "COBARDÍA". Se extiende
177
+ `DirectionalHuberLoss` con un término que RESTA de la loss la
178
+ varianza (saturada en VARIANCE_CAP) de las predicciones del batch:
179
+ Total_Loss = mean(Huber_δ(y,ŷ)·(1+γ·1[sign≠]))
180
+ - λ · min(Var_batch(ŷ), VARIANCE_CAP)
181
+ Si el modelo colapsa a predicciones casi-constantes, Var_batch(ŷ)->0
182
+ y el término de recompensa desaparece — deja de ser "gratis" predecir
183
+ ŷ≈0. `variance_lambda` (VARIANCE_LAMBDA, ajustable) es el único
184
+ hiperparámetro nuevo a tunear: demasiado alto y el modelo aprende a
185
+ "gritar" (varianza alta, dirección aleatoria) en vez de acertar;
186
+ demasiado bajo y no rompe el colapso. `VARIANCE_CAP` evita que el
187
+ término, al no tener mínimo interior, incentive varianza sin límite.
188
+
189
+ 10.5) LR ADAPTATIVO + EARLY STOPPING (Fase C). `CosineDecayRestarts`
190
+ (LearningRateSchedule estático inyectado en el optimizador) se
191
+ reemplaza por `ReduceLROnPlateau` (monitorea val_loss, señal
192
+ continua) + `EarlyStopping` (monitorea val_directional_accuracy_metric
193
+ en modo "max", la métrica que realmente importa, con
194
+ start_from_epoch=EARLY_STOPPING_START_EPOCH para no contar el
195
+ plateau esperable durante el warmup de gamma). Ya no se gastan las
196
+ 100 épocas completas si el modelo se estanca ~época 40.
197
+ """
198
+
199
+ import pickle
200
+ import time
201
+ from pathlib import Path
202
+
203
+ import numpy as np
204
+ import pandas as pd
205
+ import yfinance as yf
206
+ import matplotlib.pyplot as plt
207
+ import matplotlib.dates as mdates
208
+ import keras
209
+ from keras import layers
210
+ from sklearn.preprocessing import MinMaxScaler, StandardScaler
211
+ from sklearn.metrics import mean_absolute_error, mean_squared_error
212
+
213
+ # ============================================================
214
+ # CONFIG — 100% LOCAL (VSCode / macOS Intel). CERO Colab, CERO Drive.
215
+ # ============================================================
216
+ BASE_DIR = Path(__file__).resolve().parent if "__file__" in dir() else Path.cwd()
217
+ DATA_DIR = BASE_DIR / "data_cache" # cache local del OHLCV descargado (parquet)
218
+ MODEL_DIR = BASE_DIR / "artifacts" # copia de trabajo/dev (opcional, se mantiene por compatibilidad)
219
+ PROD_DIR = BASE_DIR.parent / "services" # ENRUTAMIENTO DE PRODUCCIÓN: sube un nivel desde BASE_DIR y entra a /services
220
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
221
+ MODEL_DIR.mkdir(parents=True, exist_ok=True)
222
+ PROD_DIR.mkdir(parents=True, exist_ok=True)
223
+
224
+ TICKERS = ["AAPL", "MSFT", "NVDA", "TSLA", "GOOGL", "AMZN", "META", "BTC-USD", "ETH-USD", "SPY"]
225
+ MACRO_TICKERS = ["^GSPC", "^TNX", "^VIX", "GC=F", "DX-Y.NYB"] # SPX, UST10Y, VIX, Oro, Dollar Index
226
+ PERIOD = "10y"
227
+ LOOKBACK = 60
228
+ TRAIN_RATIO = 0.8
229
+ SEED = 42
230
+ ASSET_EMBED_DIM = 8
231
+
232
+ SENTIMENT_LOOKBACK = 20 # ventana de la correlación móvil activo<->macro (proxy de "noticias", V4)
233
+ SENTIMENT_MACRO_PROXY = "^VIX" # factor macro de referencia para la correlación; fallback: MACRO_TICKERS[0]
234
+
235
+ # TECH_COLS es la ÚNICA fuente de verdad de qué técnicos entran al tensor —
236
+ # agregar/quitar un nombre aquí basta para que N_FEATURES y feature_cols
237
+ # (en engineer_asset / build_asset_dataset) se re-dimensionen solos, SIN
238
+ # tocar la arquitectura del modelo a mano.
239
+ TECH_COLS = ["RSI_14", "EMA_20", "MACD", "MACD_SIGNAL", "SENTIMENT_SCORE",
240
+ "ATR_14", "BB_WIDTH_20", "OBV"]
241
+ N_FEATURES = 1 + len(TECH_COLS) + len(MACRO_TICKERS) # precio propio + técnicos + macro = 14
242
+
243
+ ASSET_TO_ID = {t: i for i, t in enumerate(TICKERS)}
244
+
245
+ # --- Hiperparámetros de entrenamiento V2 (antes hardcodeados dentro de las
246
+ # funciones; centralizados acá para que build_model/train_model queden
247
+ # como funciones puras parametrizadas) ---
248
+ BATCH_SIZE = 64
249
+ EPOCHS = 100
250
+ VALIDATION_SPLIT = 0.1
251
+ MHA_HEADS = 4
252
+ MHA_KEY_DIM = 32
253
+ HUBER_DELTA = 1.0
254
+
255
+ # --- V3: CURRICULUM LEARNING (GAMMA DINÁMICO) --------------------------
256
+ # GAMMA_MAX reemplaza al antiguo DIRECTIONAL_GAMMA=1.5 ESTÁTICO: ahora es
257
+ # el TECHO al que converge el schedule, no el valor desde la Epoch 0 (ver
258
+ # DynamicGammaCallback y la sección 9.1 del docstring del módulo).
259
+ GAMMA_INITIAL = 0.0 # arranque: Huber prácticamente puro (sin penalización de signo)
260
+ GAMMA_MAX = 1.5 # techo de penalización (antiguo DIRECTIONAL_GAMMA)
261
+ GAMMA_WARMUP_EPOCHS = 35 # rampa completa entre época 30-40 (elegido: 35)
262
+ GAMMA_SCHEDULE = "sigmoid" # "sigmoid" (rampa suave en S) o "linear"
263
+ GAMMA_SIGMOID_STEEPNESS = 10.0 # mayor = transición más abrupta en el punto medio del warmup
264
+
265
+ # --- V3: REGULARIZACIÓN --------------------------------------------------
266
+ DROPOUT_RATE = 0.45 # antes 0.4 -> refuerzo anti-overfitting del bloque de fusión
267
+ DENSE_L2_REG = 1e-5 # L2 leve en las cabezas densas (post-fusión + salida)
268
+
269
+ LR_INITIAL = 1e-3 # V4: LR FIJO al arrancar el optimizador — ya no hay
270
+ # LearningRateSchedule inyectado; ReduceLROnPlateau (callback,
271
+ # ver train_model) es quien lo muta en tiempo real según val_loss.
272
+ GRAD_CLIPNORM = 1.0 # se mantiene: red de seguridad contra picos de gradiente
273
+
274
+ # --- V4: LR ADAPTATIVO + EARLY STOPPING (reemplaza CosineDecayRestarts, sección 10.5) ---
275
+ REDUCE_LR_FACTOR = 0.5 # cada plateau de val_loss -> LR se parte a la mitad
276
+ REDUCE_LR_PATIENCE = 5 # épocas sin mejora de val_loss antes de reducir el LR
277
+ REDUCE_LR_MIN_LR = 1e-6 # piso absoluto del LR
278
+ EARLY_STOPPING_PATIENCE = 12 # épocas sin mejora de val_directional_accuracy_metric antes de detener
279
+ EARLY_STOPPING_START_EPOCH = 15 # no cuenta el plateau antes de esta época (deja rodar el warmup de gamma)
280
+
281
+ # --- V4: PENALIZACIÓN DE VARIANZA — cura de la "cobardía" (sección 10.4) ---
282
+ VARIANCE_LAMBDA = 0.15 # peso de -lambda*min(var(y_pred), cap) en la loss; ajustable
283
+ VARIANCE_CAP = 4.0 # techo de var(y_pred) que se premia (evita varianza sin límite)
284
+
285
+ keras.utils.set_random_seed(SEED) # fija numpy/python/backend de forma consistente (Keras 3)
286
+
287
+
288
+ # ============================================================
289
+ # FASE A: ETL — DESCARGA UNIFICADA (OHLCV) + FEATURE ENGINEERING POR ACTIVO
290
+ # ============================================================
291
+ MAX_DOWNLOAD_RETRIES = 5
292
+ BACKOFF_BASE_SECONDS = 2.0
293
+
294
+
295
+ def _download_with_backoff(symbols: list, period: str,
296
+ max_retries: int = MAX_DOWNLOAD_RETRIES,
297
+ backoff_base: float = BACKOFF_BASE_SECONDS) -> pd.DataFrame:
298
+ """
299
+ Reintenta la descarga con backoff exponencial (2s, 4s, 8s, 16s, ...) ante
300
+ errores TRANSITORIOS de red o de rate-limit (HTTP 429 / timeouts) — algo
301
+ común en runners de CI/CD que comparten IP de salida con muchos otros
302
+ jobs. Esto es simplemente "esperar y reintentar", el manejo estándar y
303
+ sostenible de un 429 (ver `Retry-After` / RFC 6585); NO altera headers
304
+ para disfrazar el origen del tráfico ni intenta sortear CAPTCHAs — ver
305
+ la nota al final del script sobre por qué esa parte se dejó fuera.
306
+ """
307
+ last_exc = None
308
+ for attempt in range(1, max_retries + 1):
309
+ try:
310
+ data = yf.download(symbols, period=period, auto_adjust=True, progress=False)
311
+ if data is None or data.empty:
312
+ raise ValueError("yfinance devolvió un DataFrame vacío")
313
+ return data
314
+ except Exception as exc:
315
+ last_exc = exc
316
+ if attempt == max_retries:
317
+ break
318
+ wait_s = backoff_base * (2 ** (attempt - 1))
319
+ print(f" [reintento {attempt}/{max_retries}] descarga falló ({exc!r}); "
320
+ f"backoff exponencial -> esperando {wait_s:.0f}s...")
321
+ time.sleep(wait_s)
322
+ raise RuntimeError(
323
+ f"download_all: no se pudo descargar tras {max_retries} intentos"
324
+ ) from last_exc
325
+
326
+
327
+ def download_all(tickers: list, macro_tickers: list, period: str) -> pd.DataFrame:
328
+ """
329
+ Descarga en UNA sola llamada el bundle OHLCV completo (Open/High/Low/
330
+ Close/Volume) de los activos principales + factores macro, con cache
331
+ local en DATA_DIR (parquet). A diferencia de la V1 (que solo traía
332
+ Close), acá se necesita el bundle completo porque ATR requiere
333
+ High/Low y OBV requiere Volume. Para los macro tickers solo se
334
+ conserva Close (son inputs de contexto, no se calculan técnicos sobre
335
+ ellos). Columnas planas "TICKER_FIELD" para que el cache parquet sea
336
+ trivial (evita el manejo de MultiIndex en disco).
337
+ """
338
+ all_symbols = list(dict.fromkeys(tickers + macro_tickers)) # dedup preservando orden
339
+ fields = ["Open", "High", "Low", "Close", "Volume"]
340
+ cache_path = DATA_DIR / f"all_ohlcv_{period}.parquet"
341
+
342
+ required_cols = set()
343
+ for t in tickers:
344
+ required_cols.update(f"{t}_{f}" for f in fields)
345
+ for m in macro_tickers:
346
+ required_cols.add(f"{m}_Close")
347
+
348
+ if cache_path.exists():
349
+ print(f" [cache local] leyendo {cache_path.relative_to(BASE_DIR)}")
350
+ cached = pd.read_parquet(cache_path)
351
+ if required_cols.issubset(set(cached.columns)):
352
+ return cached
353
+
354
+ raw = _download_with_backoff(all_symbols, period)
355
+ flat = pd.DataFrame(index=raw.index)
356
+ available_fields = set(raw.columns.get_level_values(0))
357
+ for field in fields:
358
+ if field not in available_fields:
359
+ continue
360
+ sub = raw[field]
361
+ for sym in all_symbols:
362
+ if sym in sub.columns:
363
+ flat[f"{sym}_{field}"] = sub[sym]
364
+
365
+ flat.to_parquet(cache_path)
366
+ print(f" [cache local] guardado en {cache_path.relative_to(BASE_DIR)}")
367
+ return flat
368
+
369
+
370
+ def compute_rsi(series: pd.Series, period: int = 14) -> pd.Series:
371
+ """RSI nativo (suavizado de Wilder vía EWM)."""
372
+ delta = series.diff()
373
+ gain = delta.clip(lower=0.0)
374
+ loss = -delta.clip(upper=0.0)
375
+ avg_gain = gain.ewm(alpha=1 / period, min_periods=period, adjust=False).mean()
376
+ avg_loss = loss.ewm(alpha=1 / period, min_periods=period, adjust=False).mean()
377
+ rs = avg_gain / avg_loss.replace(0.0, np.nan)
378
+ return (100 - (100 / (1 + rs))).fillna(50.0)
379
+
380
+
381
+ def compute_macd(series: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9):
382
+ """MACD nativo: línea MACD y línea de señal."""
383
+ ema_fast = series.ewm(span=fast, adjust=False).mean()
384
+ ema_slow = series.ewm(span=slow, adjust=False).mean()
385
+ macd_line = ema_fast - ema_slow
386
+ signal_line = macd_line.ewm(span=signal, adjust=False).mean()
387
+ return macd_line, signal_line
388
+
389
+
390
+ def compute_sentiment_score(asset_log_return: pd.Series, macro_log_return: pd.Series,
391
+ window: int = SENTIMENT_LOOKBACK) -> pd.Series:
392
+ """
393
+ SENTIMENT_SCORE (V4) — proxy de shock IDIOSINCRÁTICO vía correlación de
394
+ Pearson MÓVIL (ventana de `window` sesiones) entre el log-return del
395
+ activo y el log-return de un factor macro de referencia (VIX por
396
+ defecto, ver SENTIMENT_MACRO_PROXY):
397
+
398
+ rho_t = Corr_{k=t-window..t}( r_asset_k , r_macro_k )
399
+
400
+ En régimen normal, un activo mantiene una relación relativamente
401
+ estable con el miedo/mercado agregado (rho_t con signo y magnitud
402
+ consistentes en el tiempo). Una caída o inversión abrupta de esa
403
+ correlación respecto a su nivel histórico es la firma matemática de un
404
+ shock ESPECÍFICO del activo (earnings, guidance, oferta/demanda
405
+ puntual) que rompe temporalmente su co-movimiento habitual con el
406
+ macro — una noticia. Esto reemplaza al Z-score de momentum propio de
407
+ la V1-V3 (que solo medía "qué tan extremo fue el retorno de HOY frente
408
+ a su propia distribución reciente", sin distinguir un movimiento
409
+ sistémico -todo el mercado se mueve junto- de uno idiosincrático).
410
+
411
+ `asset_log_return`/`macro_log_return` deben venir YA en log-return
412
+ (nunca precio/nivel crudo) y compartir índice. Las primeras `window`
413
+ observaciones no tienen ventana completa -> `rolling().corr()` produce
414
+ NaN ahí -> se rellena con 0.0 (lectura neutra: "sin shock detectado"),
415
+ consistente con el resto de los indicadores técnicos del pipeline.
416
+ """
417
+ rho = asset_log_return.rolling(window=window, min_periods=window).corr(macro_log_return)
418
+ return rho.fillna(0.0)
419
+
420
+
421
+ def compute_atr(high: pd.Series, low: pd.Series, close: pd.Series, period: int = 14) -> pd.Series:
422
+ """
423
+ ATR_14 — Average True Range (suavizado de Wilder vía EWM): proxy de
424
+ volatilidad ABSOLUTA (en unidades de precio) que RSI/MACD no capturan.
425
+ TR_t = max(H_t - L_t, |H_t - C_{t-1}|, |L_t - C_{t-1}|)
426
+ ATR_t = EWM_Wilder(TR)_t
427
+ """
428
+ prev_close = close.shift(1)
429
+ tr = pd.concat([
430
+ high - low,
431
+ (high - prev_close).abs(),
432
+ (low - prev_close).abs(),
433
+ ], axis=1).max(axis=1)
434
+ atr = tr.ewm(alpha=1 / period, min_periods=period, adjust=False).mean()
435
+ return atr.fillna(0.0)
436
+
437
+
438
+ def compute_bb_width(series: pd.Series, window: int = 20, num_std: float = 2.0) -> pd.Series:
439
+ """
440
+ BB_WIDTH_20 — ancho normalizado de Bandas de Bollinger:
441
+ width_t = (banda_sup - banda_inf) / SMA_t = (2*num_std*std_t) / SMA_t
442
+ Proxy de volatilidad RELATIVA (independiente de la escala de precio),
443
+ complementa a ATR_14 (volatilidad en términos absolutos).
444
+ """
445
+ rolling_mean = series.rolling(window=window, min_periods=window).mean()
446
+ rolling_std = series.rolling(window=window, min_periods=window).std()
447
+ width = (2 * num_std * rolling_std) / rolling_mean.replace(0.0, np.nan)
448
+ return width.fillna(0.0)
449
+
450
+
451
+ def compute_obv(close: pd.Series, volume: pd.Series) -> pd.Series:
452
+ """
453
+ OBV — On-Balance Volume: acumulado de volumen firmado por la dirección
454
+ del precio. Único feature del tensor que incorpora PARTICIPACIÓN
455
+ (volumen); ayuda a detectar divergencias precio/volumen.
456
+ OBV_t = OBV_{t-1} + sign(C_t - C_{t-1}) * V_t
457
+ """
458
+ direction = np.sign(close.diff()).fillna(0.0)
459
+ obv = (direction * volume).cumsum()
460
+ return obv.fillna(0.0)
461
+
462
+
463
+ def engineer_asset(all_data: pd.DataFrame, ticker: str, macro_tickers: list) -> pd.DataFrame:
464
+ """
465
+ Construye el frame de features de UN activo: OHLCV propio + técnicos +
466
+ macro. V4 — ESTACIONARIEDAD ESTRICTA (Fase A, sección 10.1): los
467
+ factores macro llegan a `all_data` como NIVEL/PRECIO crudo
468
+ (no-estacionario) -> se transforman a log-return AQUÍ, antes de que
469
+ `build_asset_dataset` los pase al feature_scaler, igual que el target:
470
+ r_macro_t = log(P_macro_t / P_macro_{t-1})
471
+ Nunca se pasa un nivel/precio macro crudo al scaler.
472
+ """
473
+ close_col = f"{ticker}_Close"
474
+ high_col = f"{ticker}_High"
475
+ low_col = f"{ticker}_Low"
476
+ vol_col = f"{ticker}_Volume"
477
+ macro_close_cols = [f"{m}_Close" for m in macro_tickers]
478
+
479
+ df = all_data[[close_col, high_col, low_col, vol_col] + macro_close_cols].copy()
480
+ df = df.ffill().dropna()
481
+
482
+ close, high, low, volume = df[close_col], df[high_col], df[low_col], df[vol_col]
483
+
484
+ # --- Fase A (V4): factores macro -> log-return, NUNCA nivel crudo al scaler ---
485
+ for macro_close_col in macro_close_cols:
486
+ macro_price = df[macro_close_col]
487
+ df[macro_close_col] = np.log(macro_price / macro_price.shift(1))
488
+
489
+ df["RSI_14"] = compute_rsi(close)
490
+ df["EMA_20"] = close.ewm(span=20, adjust=False).mean()
491
+ macd_line, signal_line = compute_macd(close)
492
+ df["MACD"] = macd_line
493
+ df["MACD_SIGNAL"] = signal_line
494
+
495
+ # --- SENTIMENT_SCORE (V4, sección 10.2): correlación móvil activo<->macro.
496
+ # proxy_log_return reutiliza la columna macro YA transformada arriba
497
+ # (no se recalcula desde precio crudo).
498
+ asset_log_return = np.log(close / close.shift(1))
499
+ proxy_ticker = SENTIMENT_MACRO_PROXY if SENTIMENT_MACRO_PROXY in macro_tickers else macro_tickers[0]
500
+ proxy_log_return = df[f"{proxy_ticker}_Close"]
501
+ df["SENTIMENT_SCORE"] = compute_sentiment_score(asset_log_return, proxy_log_return, SENTIMENT_LOOKBACK)
502
+
503
+ df["ATR_14"] = compute_atr(high, low, close)
504
+ df["BB_WIDTH_20"] = compute_bb_width(close)
505
+ df["OBV"] = compute_obv(close, volume)
506
+ df = df.ffill().dropna()
507
+
508
+ feature_cols = [close_col] + TECH_COLS + macro_close_cols
509
+ df = df[feature_cols]
510
+ df.columns = ["PRICE"] + TECH_COLS + macro_tickers # nombre genérico -> permite apilar activos distintos
511
+ return df
512
+
513
+
514
+ def build_asset_dataset(df: pd.DataFrame, ticker: str, lookback: int, train_ratio: float):
515
+ """
516
+ Ventanas (X) + targets de LOG-RETURN (y) para UN activo, con normalización
517
+ propia (feature_scaler + target_scaler) ajustada SOLO en el tramo de train
518
+ de ese activo. Split cronológico: sin fuga de información test -> train.
519
+
520
+ target_scaler = StandardScaler(with_mean=False): SOLO divide por sigma,
521
+ NO resta la media. Es una corrección deliberada respecto a la V1: con
522
+ centrado de media, sign(y_scaled) puede diferir de sign(y_raw) para
523
+ activos con drift fuerte (el "cero" quedaría desplazado a y_raw=mu), lo
524
+ que rompería silenciosamente la semántica de DirectionalHuberLoss. Dividir
525
+ solo por una constante positiva (sigma) preserva el signo exactamente.
526
+ """
527
+ # V4 (sección 10.1): las columnas de MACRO_TICKERS ya llegan en LOG-RETURN
528
+ # (ver engineer_asset, Fase A) -> el MinMaxScaler de abajo nunca ve un
529
+ # nivel/precio macro no-estacionario.
530
+ feature_cols = ["PRICE"] + TECH_COLS + MACRO_TICKERS
531
+ prices = df["PRICE"].values
532
+ features = df[feature_cols].values
533
+ log_returns = np.diff(np.log(prices)) # log_returns[k] = log(P[k+1] / P[k])
534
+
535
+ n = len(df)
536
+ split_idx = int(n * train_ratio)
537
+
538
+ feature_scaler = MinMaxScaler(feature_range=(0, 1))
539
+ feature_scaler.fit(features[:split_idx])
540
+ features_scaled = feature_scaler.transform(features)
541
+
542
+ X, y_raw, last_price, dates = [], [], [], []
543
+ # t recorre el índice del DÍA OBJETIVO. Predecimos el retorno que ocurre
544
+ # entre t-1 y t usando SOLO features hasta t-1 inclusive (sin fuga).
545
+ for t in range(lookback, n):
546
+ X.append(features_scaled[t - lookback: t])
547
+ y_raw.append(log_returns[t - 1])
548
+ last_price.append(prices[t - 1])
549
+ dates.append(df.index[t])
550
+
551
+ X = np.array(X, dtype=np.float32)
552
+ y_raw = np.array(y_raw, dtype=np.float32).reshape(-1, 1)
553
+ last_price = np.array(last_price, dtype=np.float32)
554
+ dates = pd.DatetimeIndex(dates)
555
+
556
+ window_split = split_idx - lookback # offset por la ventana de lookback
557
+
558
+ target_scaler = StandardScaler(with_mean=False) # ver docstring: preserva el signo del retorno
559
+ target_scaler.fit(y_raw[:window_split])
560
+ y_scaled = target_scaler.transform(y_raw).astype(np.float32)
561
+
562
+ asset_id = np.full((len(X),), ASSET_TO_ID[ticker], dtype=np.int32)
563
+
564
+ train = dict(
565
+ X=X[:window_split], y=y_scaled[:window_split], asset_id=asset_id[:window_split],
566
+ last_price=last_price[:window_split], dates=dates[:window_split],
567
+ )
568
+ test = dict(
569
+ X=X[window_split:], y=y_scaled[window_split:], asset_id=asset_id[window_split:],
570
+ last_price=last_price[window_split:], dates=dates[window_split:],
571
+ )
572
+ return train, test, feature_scaler, target_scaler
573
+
574
+
575
+ # ============================================================
576
+ # FASE B: ARQUITECTURA GLOBAL — MHA+Residual + Bahdanau + BiLSTM + Asset Embedding
577
+ # ============================================================
578
+ @keras.saving.register_keras_serializable(package="quanti")
579
+ class BahdanauAttention(layers.Layer):
580
+ """Self-attention aditiva (Bahdanau) — pooling final de contexto sobre la secuencia enriquecida por MHA."""
581
+
582
+ def __init__(self, units: int, **kwargs):
583
+ super().__init__(**kwargs)
584
+ self.units = units
585
+ self.W = layers.Dense(units, name="attn_W")
586
+ self.U = layers.Dense(units, name="attn_U")
587
+ self.V = layers.Dense(1, name="attn_V")
588
+
589
+ def build(self, input_shape):
590
+ feature_dim = input_shape[-1]
591
+ self.W.build((None, None, feature_dim))
592
+ self.U.build((None, 1, feature_dim))
593
+ self.V.build((None, None, self.units))
594
+ super().build(input_shape)
595
+
596
+ def call(self, hidden_states):
597
+ query = keras.ops.mean(hidden_states, axis=1, keepdims=True)
598
+ score = self.V(keras.ops.tanh(self.W(hidden_states) + self.U(query)))
599
+ weights = keras.ops.softmax(score, axis=1)
600
+ context = keras.ops.sum(weights * hidden_states, axis=1)
601
+ return context, weights
602
+
603
+ def get_config(self):
604
+ config = super().get_config()
605
+ config.update({"units": self.units})
606
+ return config
607
+
608
+
609
+ # ============================================================
610
+ # FASE B.1: FUNCIÓN DE PÉRDIDA — ASYMMETRIC DIRECTIONAL HUBER
611
+ # ============================================================
612
+ @keras.saving.register_keras_serializable(package="quanti")
613
+ class DirectionalHuberLoss(keras.losses.Loss):
614
+ """
615
+ L(y, ŷ) = Huber_δ(y, ŷ) · (1 + γ · 1[sign(y) ≠ sign(ŷ)])
616
+
617
+ Extiende Huber (robusta a outliers de retornos extremos) con un
618
+ multiplicador γ que SOLO se activa cuando el modelo falla el SIGNO del
619
+ retorno — el error que realmente destruye una estrategia direccional
620
+ (ir LONG cuando debía ir SHORT, o viceversa), a diferencia de un simple
621
+ error de magnitud con el signo correcto.
622
+
623
+ Requiere que y_true/y_pred lleguen en un espacio donde el signo del
624
+ valor escalado coincide EXACTAMENTE con el signo del retorno real; por
625
+ eso `build_asset_dataset` usa StandardScaler(with_mean=False) para el
626
+ target en vez de un StandardScaler centrado en la media (ver su
627
+ docstring). Con centrado de media este término penalizaría el signo
628
+ equivocado para activos con drift fuerte.
629
+
630
+ V3 — CURRICULUM LEARNING: `gamma` ahora acepta un `keras.Variable` NO
631
+ entrenable (además del float estático de la V2, por compatibilidad).
632
+ `DynamicGammaCallback` reescribe su VALOR en cada `on_epoch_begin` (de
633
+ 0.0 a GAMMA_MAX en rampa sigmoide/lineal a lo largo de
634
+ GAMMA_WARMUP_EPOCHS) -> como `call()` lee `self.gamma` en cada forward
635
+ pass, el nuevo valor se refleja automáticamente sin recompilar el
636
+ modelo. Ver sección 9.1 del docstring del módulo para el fundamento
637
+ matemático completo.
638
+
639
+ V4 — PENALIZACIÓN DE VARIANZA ("cura de la cobardía", sección 10.4):
640
+ aun con el curriculum de gamma, minimizar Huber puro bajo ruido sigue
641
+ premiando ŷ≈0 ∀ muestras. Se agrega un término que RESTA de la loss la
642
+ varianza (saturada en `variance_cap`) de las predicciones del batch:
643
+
644
+ L_total = mean( Huber_δ(y,ŷ)·(1+γ·1[sign(y)≠sign(ŷ)]) )
645
+ - variance_lambda · min(Var_batch(ŷ), variance_cap)
646
+
647
+ Si el modelo colapsa a predicciones casi-constantes, Var_batch(ŷ)->0 y
648
+ el término de recompensa desaparece -> deja de ser "gratis" predecir
649
+ ŷ≈0, lo que reactiva el gradiente de magnitud/dirección. `variance_cap`
650
+ evita el riesgo simétrico: sin techo, -variance_lambda·Var(ŷ) no tiene
651
+ mínimo interior (el modelo podría maximizar varianza saturando ŷ hacia
652
+ ±∞ en vez de aprender señal real); al saturar en `variance_cap`, más
653
+ allá de ese punto el único gradiente que queda es el de Huber/dirección.
654
+ """
655
+
656
+ def __init__(self, delta: float = 1.0, gamma=1.5,
657
+ variance_lambda: float = 0.0, variance_cap: float = None,
658
+ name: str = "directional_huber", **kwargs):
659
+ super().__init__(name=name, **kwargs)
660
+ self.delta = delta
661
+ # Compatibilidad dual: si `gamma` ya es una Variable (curriculum
662
+ # dinámico -> caso normal en V3) se usa TAL CUAL, de modo que el
663
+ # callback y la loss comparten la misma celda de memoria. Si es un
664
+ # float (ej. al recargar un .keras guardado) se envuelve en una
665
+ # Variable no-entrenable nueva, así `call()` nunca tiene que
666
+ # ramificar entre "float" y "Variable".
667
+ self.gamma = gamma if isinstance(gamma, keras.Variable) else keras.Variable(
668
+ gamma, trainable=False, dtype="float32", name=f"{name}_gamma"
669
+ )
670
+ self.variance_lambda = float(variance_lambda)
671
+ self.variance_cap = None if variance_cap is None else float(variance_cap)
672
+
673
+ def call(self, y_true, y_pred):
674
+ y_true = keras.ops.cast(y_true, "float32")
675
+ y_pred = keras.ops.cast(y_pred, "float32")
676
+
677
+ error = y_true - y_pred
678
+ abs_error = keras.ops.abs(error)
679
+ quadratic = keras.ops.minimum(abs_error, self.delta)
680
+ linear = abs_error - quadratic
681
+ huber = 0.5 * keras.ops.square(quadratic) + self.delta * linear
682
+
683
+ mismatch = keras.ops.cast(
684
+ keras.ops.not_equal(keras.ops.sign(y_true), keras.ops.sign(y_pred)),
685
+ dtype=huber.dtype,
686
+ )
687
+ # self.gamma es una Variable: se lee su valor CORRIENTE en cada
688
+ # forward pass. DynamicGammaCallback la actualiza al inicio de cada
689
+ # época, así que este término crece época a época sin recompilar.
690
+ penalty = 1.0 + self.gamma * mismatch
691
+ directional_huber = keras.ops.mean(huber * penalty, axis=-1) # (batch,)
692
+
693
+ # V4 (sección 10.4): batch_variance es un ÚNICO escalar por batch (no
694
+ # por muestra). keras.losses.Loss espera que call() devuelva un
695
+ # vector (batch,), así que se resta el mismo escalar a cada
696
+ # elemento; la reducción posterior (mean sobre el batch, default de
697
+ # Loss) queda matemáticamente idéntica a
698
+ # "mean(directional_huber) - variance_lambda*min(Var(ŷ), cap)".
699
+ if self.variance_lambda > 0.0:
700
+ batch_variance = keras.ops.var(y_pred)
701
+ if self.variance_cap is not None:
702
+ batch_variance = keras.ops.minimum(batch_variance, self.variance_cap)
703
+ directional_huber = directional_huber - self.variance_lambda * batch_variance
704
+
705
+ return directional_huber
706
+
707
+ def get_config(self):
708
+ config = super().get_config()
709
+ config.update({
710
+ "delta": self.delta,
711
+ # Se serializa el VALOR ESCALAR actual (no el objeto Variable,
712
+ # que no es JSON-serializable). Al recargar con
713
+ # keras.models.load_model() este número queda FIJO -> correcto
714
+ # para inferencia; para REANUDAR el curriculum tras una carga
715
+ # habría que re-envolverlo a mano en una Variable nueva.
716
+ "gamma": float(keras.ops.convert_to_numpy(self.gamma)),
717
+ "variance_lambda": self.variance_lambda,
718
+ "variance_cap": self.variance_cap,
719
+ })
720
+ return config
721
+
722
+
723
+ @keras.saving.register_keras_serializable(package="quanti")
724
+ def directional_accuracy_metric(y_true, y_pred):
725
+ """Métrica de monitoreo en vivo durante fit(): % de aciertos de signo (espacio escalado, signo-preservado)."""
726
+ y_true = keras.ops.cast(y_true, "float32")
727
+ y_pred = keras.ops.cast(y_pred, "float32")
728
+ match = keras.ops.cast(
729
+ keras.ops.equal(keras.ops.sign(y_true), keras.ops.sign(y_pred)), dtype="float32"
730
+ )
731
+ return keras.ops.mean(match)
732
+
733
+
734
+ # ============================================================
735
+ # FASE B.2: CURRICULUM LEARNING — CALLBACK DE GAMMA DINÁMICO (V3)
736
+ # ============================================================
737
+ class DynamicGammaCallback(keras.callbacks.Callback):
738
+ """
739
+ Reescribe, al inicio de cada época, el `keras.Variable` de gamma que
740
+ consume `DirectionalHuberLoss`, siguiendo un warmup de
741
+ `warmup_epochs` épocas desde `0.0` hasta `gamma_max`. Ver sección 9.1
742
+ del docstring del módulo para la derivación matemática completa del
743
+ schedule sigmoide/lineal.
744
+
745
+ Se implementa como Callback (no como parte de la loss) porque el
746
+ schedule depende del ÍNDICE DE ÉPOCA, una noción que la loss —evaluada
747
+ por batch, sin conocimiento del bucle de entrenamiento— no tiene; el
748
+ Callback sí recibe `epoch` en `on_epoch_begin` desde `model.fit()`.
749
+ """
750
+
751
+ def __init__(self, gamma_variable, gamma_max: float = GAMMA_MAX,
752
+ warmup_epochs: int = GAMMA_WARMUP_EPOCHS,
753
+ schedule: str = GAMMA_SCHEDULE,
754
+ sigmoid_steepness: float = GAMMA_SIGMOID_STEEPNESS,
755
+ verbose: bool = True):
756
+ super().__init__()
757
+ self.gamma_variable = gamma_variable
758
+ self.gamma_max = gamma_max
759
+ self.warmup_epochs = max(1, warmup_epochs)
760
+ self.schedule = schedule
761
+ self.sigmoid_steepness = sigmoid_steepness
762
+ self.verbose = verbose
763
+ # Normalización del sigmoide para que _progress_to_fraction(0)=0.0 y
764
+ # _progress_to_fraction(1)=1.0 EXACTOS -> un sigmoide "crudo" nunca
765
+ # toca 0 ni 1 en sus extremos (asíntotas), lo que dejaría gamma(0)
766
+ # ligeramente por encima de 0 (penalización direccional desde el
767
+ # primer batch, justo lo que V3 busca evitar).
768
+ k = self.sigmoid_steepness
769
+ self._sig_lo = 1.0 / (1.0 + np.exp(k * 0.5))
770
+ self._sig_hi = 1.0 / (1.0 + np.exp(-k * 0.5))
771
+
772
+ def _progress_to_fraction(self, progress: float) -> float:
773
+ progress = min(max(progress, 0.0), 1.0)
774
+ if self.schedule == "linear":
775
+ return progress
776
+ k = self.sigmoid_steepness
777
+ raw = 1.0 / (1.0 + np.exp(-k * (progress - 0.5)))
778
+ return (raw - self._sig_lo) / (self._sig_hi - self._sig_lo)
779
+
780
+ def on_epoch_begin(self, epoch, logs=None):
781
+ progress = epoch / self.warmup_epochs
782
+ new_gamma = float(self.gamma_max * self._progress_to_fraction(progress))
783
+ self.gamma_variable.assign(new_gamma)
784
+ if self.verbose and (epoch % 5 == 0 or epoch == self.warmup_epochs):
785
+ tag = " <- curriculum completo" if epoch >= self.warmup_epochs else ""
786
+ print(f" [DynamicGamma] epoch={epoch:3d} gamma={new_gamma:.4f}{tag}")
787
+
788
+
789
+ def build_model(n_timesteps: int, n_features: int, n_assets: int,
790
+ embed_dim: int = ASSET_EMBED_DIM, attention_units: int = 32,
791
+ mha_heads: int = MHA_HEADS, mha_key_dim: int = MHA_KEY_DIM,
792
+ huber_delta: float = HUBER_DELTA,
793
+ gamma_initial: float = GAMMA_INITIAL,
794
+ variance_lambda: float = VARIANCE_LAMBDA,
795
+ variance_cap: float = VARIANCE_CAP,
796
+ dropout_rate: float = DROPOUT_RATE,
797
+ dense_l2_reg: float = DENSE_L2_REG) -> tuple:
798
+ """
799
+ V4 — Fase B: TOPOLOGÍA DE OCKHAM (sección 10.3). Con 14 features de
800
+ entrada, `BiLSTM(256)->BiLSTM(128)` (V1-V3) está masivamente
801
+ sobre-parametrizada y memoriza ruido en vez de generalizar -> se poda a
802
+ una ÚNICA `BiLSTM(64)`. El bloque de auto-atención multi-cabeza (con
803
+ residual) y el pooling de Bahdanau se MANTIENEN sin cambios. Al
804
+ desaparecer la segunda rama recurrente, la fusión pasa de
805
+ [context_vector, bilstm_2, asset_embed] a [context_vector, asset_embed],
806
+ y la cabeza densa (post_fusion_dense / fused_projection_skip) se poda
807
+ de 64 a 32 unidades, coherente con la reducción de capacidad aguas
808
+ arriba.
809
+ """
810
+ # `n_features` NUNCA se hardcodea acá — llega calculado desde
811
+ # N_FEATURES = 1 + len(TECH_COLS) + len(MACRO_TICKERS).
812
+ seq_input = keras.Input(shape=(n_timesteps, n_features), name="input_sequence")
813
+ asset_input = keras.Input(shape=(1,), dtype="int32", name="input_asset_id")
814
+
815
+ bilstm = layers.Bidirectional(
816
+ layers.LSTM(64, return_sequences=True), name="bilstm_64"
817
+ )(seq_input)
818
+ bilstm = layers.LayerNormalization(name="ln_post_bilstm_64")(bilstm)
819
+
820
+ # Bloque auto-atencional multi-cabeza (estilo encoder de Transformer) con
821
+ # conexión residual: se mantiene IDÉNTICO a V1-V3 (directiva Fase B:
822
+ # "Keep the Multi-Head Attention and Bahdanau context"). Cada posición
823
+ # temporal puede atender a TODA la secuencia antes de que Bahdanau haga
824
+ # el pooling final de contexto; la suma residual + LayerNormalization
825
+ # evita que el bloque MHA degrade el gradiente que fluye desde la BiLSTM.
826
+ mha_out = layers.MultiHeadAttention(
827
+ num_heads=mha_heads, key_dim=mha_key_dim, name="multi_head_self_attention"
828
+ )(query=bilstm, value=bilstm, key=bilstm)
829
+ attn_block = layers.Add(name="mha_residual_add")([bilstm, mha_out])
830
+ attn_block = layers.LayerNormalization(name="ln_post_mha_residual")(attn_block)
831
+
832
+ context_vector, attention_weights = BahdanauAttention(
833
+ attention_units, name="bahdanau_attention"
834
+ )(attn_block)
835
+
836
+ asset_embed = layers.Embedding(n_assets, embed_dim, name="asset_embedding")(asset_input)
837
+ asset_embed = layers.Flatten(name="asset_embedding_flat")(asset_embed)
838
+
839
+ # V4: sin segunda rama BiLSTM(128) -> la fusión pasa de 3 a 2 entradas.
840
+ fused = layers.Concatenate(name="fusion_attn_asset")([context_vector, asset_embed])
841
+ fused = layers.Dropout(dropout_rate, name="dropout_regularizer")(fused)
842
+
843
+ # Bloque denso con conexión residual: `fused_projection_skip` proyecta el
844
+ # vector de fusión a 32-d para poder sumarlo con `post_fusion_dense`
845
+ # (proyección lineal, no una identidad pura, patrón "projection shortcut"
846
+ # de ResNet). V4: cabeza podada de 64 a 32 unidades (sección 10.3); las
847
+ # 3 capas Dense siguen llevando L2 leve (dense_l2_reg).
848
+ l2 = keras.regularizers.l2(dense_l2_reg)
849
+ dense_hidden = layers.Dense(32, activation="relu", name="post_fusion_dense",
850
+ kernel_regularizer=l2)(fused)
851
+ fused_projection = layers.Dense(32, name="fused_projection_skip",
852
+ kernel_regularizer=l2)(fused)
853
+ dense_block = layers.Add(name="dense_residual_add")([dense_hidden, fused_projection])
854
+ dense_block = layers.LayerNormalization(name="ln_post_dense_residual")(dense_block)
855
+
856
+ output = layers.Dense(1, name="return_head", kernel_regularizer=l2)(dense_block)
857
+
858
+ model = keras.Model(inputs=[seq_input, asset_input], outputs=output,
859
+ name="Global_Attention_BiLSTM_Returns_V4")
860
+
861
+ # V4 — Fase C (sección 10.5): LR FIJO al compilar. Ya no hay
862
+ # LearningRateSchedule inyectado en el optimizador (CosineDecayRestarts
863
+ # queda retirado) -> ReduceLROnPlateau (callback, ver train_model) es
864
+ # quien muta el LR en tiempo real según val_loss, algo que un schedule
865
+ # estático no puede hacer al no leer métricas de validación. clipnorm
866
+ # se mantiene como red de seguridad contra picos de gradiente.
867
+ optimizer = keras.optimizers.AdamW(
868
+ learning_rate=LR_INITIAL, weight_decay=1e-4, clipnorm=GRAD_CLIPNORM
869
+ )
870
+
871
+ # V3 — CURRICULUM LEARNING (se mantiene en V4): gamma es un
872
+ # keras.Variable NO entrenable (no es un peso del modelo: es un
873
+ # hiperparámetro mutable). DynamicGammaCallback la reescribe en
874
+ # `on_epoch_begin`; como DirectionalHuberLoss.call() lee `self.gamma` en
875
+ # cada forward pass, el nuevo valor se refleja solo, sin recompilar el
876
+ # modelo. Ver sección 9.1 del docstring del módulo.
877
+ gamma_variable = keras.Variable(
878
+ gamma_initial, trainable=False, dtype="float32", name="directional_gamma"
879
+ )
880
+ model.compile(
881
+ optimizer=optimizer,
882
+ loss=DirectionalHuberLoss(
883
+ delta=huber_delta, gamma=gamma_variable,
884
+ variance_lambda=variance_lambda, variance_cap=variance_cap,
885
+ ),
886
+ metrics=["mae", directional_accuracy_metric],
887
+ )
888
+ # NO se guarda `gamma_variable` como atributo de `model` (ej.
889
+ # `model.gamma_variable = ...`): keras.Model rastrea automáticamente
890
+ # cualquier keras.Variable asignada como atributo directo de un Layer/
891
+ # Model (igual que trackea pesos), lo que la suma al conteo de
892
+ # variables del Functional top-level. Al guardar el checkpoint esa
893
+ # variable extra queda serializada, pero al reconstruir el modelo desde
894
+ # su config en `keras.models.load_model()` el grafo Functional
895
+ # reconstruido NO la vuelve a crear (no es parte de la arquitectura) ->
896
+ # desalineación "expected 0 variables, but received 1" y el reload
897
+ # revienta. Se devuelve por separado para que la comparta explícitamente
898
+ # con `train_model()` sin pasar por la maquinaria de tracking de Keras.
899
+ return model, gamma_variable
900
+
901
+
902
+ # ============================================================
903
+ # FASE C: ENTRENAMIENTO GLOBAL
904
+ # ============================================================
905
+ def train_model(model: keras.Model, X_train, asset_id_train, y_train,
906
+ epochs: int = EPOCHS, batch_size: int = BATCH_SIZE,
907
+ validation_split: float = VALIDATION_SPLIT,
908
+ checkpoint_path: str = "attention_bilstm_global_best.keras",
909
+ gamma_variable=None,
910
+ gamma_max: float = GAMMA_MAX,
911
+ gamma_warmup_epochs: int = GAMMA_WARMUP_EPOCHS,
912
+ gamma_schedule: str = GAMMA_SCHEDULE,
913
+ gamma_sigmoid_steepness: float = GAMMA_SIGMOID_STEEPNESS):
914
+ """
915
+ V4 — Fase C (sección 10.5): `ReduceLROnPlateau` + `EarlyStopping`
916
+ reemplazan a `CosineDecayRestarts` como mecanismo de control del
917
+ LR/duración del entrenamiento (V1-V3 dependía de reinicios periódicos
918
+ de LR inyectados en el optimizador y dejaba correr las `epochs`
919
+ completas sin criterio de parada).
920
+
921
+ - `ReduceLROnPlateau(monitor="val_loss")`: parte el LR a la mitad
922
+ (REDUCE_LR_FACTOR) cada vez que val_loss no mejora durante
923
+ REDUCE_LR_PATIENCE épocas, con piso REDUCE_LR_MIN_LR. val_loss (no la
924
+ accuracy direccional) es la señal correcta para ESTA decisión: es
925
+ continua, mientras que directional_accuracy es una métrica de conteo
926
+ (0/1 por muestra) demasiado ruidosa época a época para gobernar el LR.
927
+ - `EarlyStopping(monitor="val_directional_accuracy_metric", mode="max")`:
928
+ detiene el entrenamiento si la métrica que REALMENTE importa (no la
929
+ loss compuesta, que mezcla magnitud + dirección + varianza) no mejora
930
+ durante EARLY_STOPPING_PATIENCE épocas, con `restore_best_weights=True`
931
+ como red de seguridad adicional. `start_from_epoch=
932
+ EARLY_STOPPING_START_EPOCH` evita que la paciencia empiece a contar
933
+ mientras el curriculum de gamma sigue en rampa (las primeras épocas
934
+ son de exploración de magnitud, no de precisión direccional -> un
935
+ plateau ahí es esperado, no señal de estancamiento real). Así se evita
936
+ gastar epochs completos si el modelo se estanca ~época 40.
937
+ - `ModelCheckpoint(save_best_only=True, monitor="val_loss")` sigue
938
+ siendo la fuente de verdad FINAL de los pesos (se recarga tras
939
+ `fit()`, igual que en V1-V3): puede diferir levemente de los pesos
940
+ que deja `restore_best_weights` de EarlyStopping (que optimiza por
941
+ accuracy direccional) — es una elección deliberada, val_loss sigue
942
+ siendo el objetivo de entrenamiento primario.
943
+ - `TerminateOnNaN()` se mantiene sin cambios como red de seguridad barata.
944
+
945
+ V3 — nota sobre `gamma_variable`: si `save_best_only=True` guarda el
946
+ checkpoint en una época donde el curriculum aún no llegó a gamma_max (un
947
+ val_loss más bajo es "más fácil" con gamma pequeño), el `best_model`
948
+ recargado por `keras.models.load_model()` queda con un gamma ESTÁTICO
949
+ congelado en ese valor (ver `DirectionalHuberLoss.get_config`) — esto es
950
+ correcto para inferencia (la loss no se usa en `predict()`) pero si se
951
+ quisiera REANUDAR entrenamiento habría que reconstruir la Variable a mano.
952
+ """
953
+ callbacks = [
954
+ keras.callbacks.ModelCheckpoint(
955
+ checkpoint_path, monitor="val_loss", save_best_only=True, verbose=1
956
+ ),
957
+ keras.callbacks.TerminateOnNaN(),
958
+ # V4 (sección 10.5): LR adaptativo sobre plateau de val_loss.
959
+ keras.callbacks.ReduceLROnPlateau(
960
+ monitor="val_loss", factor=REDUCE_LR_FACTOR, patience=REDUCE_LR_PATIENCE,
961
+ min_lr=REDUCE_LR_MIN_LR, verbose=1,
962
+ ),
963
+ # V4 (sección 10.5): parada temprana agresiva sobre la métrica que
964
+ # de verdad importa, no sobre la loss compuesta.
965
+ keras.callbacks.EarlyStopping(
966
+ monitor="val_directional_accuracy_metric", mode="max",
967
+ patience=EARLY_STOPPING_PATIENCE, start_from_epoch=EARLY_STOPPING_START_EPOCH,
968
+ restore_best_weights=True, verbose=1,
969
+ ),
970
+ ]
971
+ if gamma_variable is not None:
972
+ # V3: registra el callback de curriculum learning SOLO si se pasó una
973
+ # gamma_variable (permite seguir usando train_model en modo V2 puro,
974
+ # con una loss de gamma estático, sin romper la firma de la función).
975
+ callbacks.append(DynamicGammaCallback(
976
+ gamma_variable=gamma_variable,
977
+ gamma_max=gamma_max,
978
+ warmup_epochs=gamma_warmup_epochs,
979
+ schedule=gamma_schedule,
980
+ sigmoid_steepness=gamma_sigmoid_steepness,
981
+ ))
982
+ history = model.fit(
983
+ [X_train, asset_id_train], y_train,
984
+ validation_split=validation_split,
985
+ epochs=epochs,
986
+ batch_size=batch_size,
987
+ shuffle=True,
988
+ callbacks=callbacks,
989
+ verbose=1,
990
+ )
991
+ best_model = keras.models.load_model(checkpoint_path)
992
+ return history, best_model
993
+
994
+
995
+ # ============================================================
996
+ # FASE D: EVALUACIÓN — RECONSTRUCCIÓN DE PRECIOS + DIRECTIONAL ACCURACY
997
+ # ============================================================
998
+ def evaluate_asset(model: keras.Model, test: dict, ticker: str, target_scaler: StandardScaler) -> dict:
999
+ asset_id_col = test["asset_id"].reshape(-1, 1)
1000
+ y_pred_scaled = model.predict([test["X"], asset_id_col], verbose=0)
1001
+
1002
+ r_hat = target_scaler.inverse_transform(y_pred_scaled).flatten()
1003
+ r_true = target_scaler.inverse_transform(test["y"]).flatten()
1004
+
1005
+ price_pred = test["last_price"] * np.exp(r_hat)
1006
+ price_true = test["last_price"] * np.exp(r_true)
1007
+
1008
+ mae_price = mean_absolute_error(price_true, price_pred)
1009
+ rmse_price = np.sqrt(mean_squared_error(price_true, price_pred))
1010
+ directional_acc = float(np.mean(np.sign(r_hat) == np.sign(r_true)))
1011
+
1012
+ return {
1013
+ "ticker": ticker,
1014
+ "mae_price": mae_price,
1015
+ "rmse_price": rmse_price,
1016
+ "directional_accuracy": directional_acc,
1017
+ "price_true": price_true,
1018
+ "price_pred": price_pred,
1019
+ "dates": test["dates"],
1020
+ }
1021
+
1022
+
1023
+ def plot_asset(result: dict, ticker: str):
1024
+ fig, ax = plt.subplots(figsize=(14, 6))
1025
+ ax.plot(result["dates"], result["price_true"], label="Real", color="#1f77b4", linewidth=1.8)
1026
+ ax.plot(result["dates"], result["price_pred"], label="Predicho (reconstruido)", color="#d62728",
1027
+ linewidth=1.5, linestyle="--")
1028
+ ax.set_title(f"{ticker} — Global Attention-BiLSTM V3 (Log-Return): Predicho vs. Real (Test)")
1029
+ ax.set_xlabel("Fecha")
1030
+ ax.set_ylabel("Precio de Cierre (USD)")
1031
+ ax.xaxis.set_major_locator(mdates.AutoDateLocator())
1032
+ ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
1033
+ fig.autofmt_xdate()
1034
+ ax.legend()
1035
+ ax.grid(alpha=0.3)
1036
+ plt.tight_layout()
1037
+ plt.savefig(f"forecast_{ticker.replace('=', '_').replace('^', '')}.png", dpi=150)
1038
+ plt.show()
1039
+
1040
+
1041
+ # ============================================================
1042
+ # ORQUESTACIÓN (nivel de módulo -> variables quedan en scope global)
1043
+ # ============================================================
1044
+ print(f"[1/5] Descargando {len(TICKERS)} activos (OHLCV) + {len(MACRO_TICKERS)} factores macro (Close) ({PERIOD})...")
1045
+ all_market_data = download_all(TICKERS, MACRO_TICKERS, PERIOD)
1046
+
1047
+ print("[2/5] Ingeniería de features y construcción de dataset GLOBAL por activo...")
1048
+ feature_scalers, target_scalers = {}, {}
1049
+ X_train_parts, y_train_parts, asset_id_train_parts = [], [], []
1050
+ test_sets = {}
1051
+
1052
+ for ticker in TICKERS:
1053
+ df_asset = engineer_asset(all_market_data, ticker, MACRO_TICKERS)
1054
+ train, test, f_scaler, t_scaler = build_asset_dataset(df_asset, ticker, LOOKBACK, TRAIN_RATIO)
1055
+
1056
+ feature_scalers[ticker] = f_scaler
1057
+ target_scalers[ticker] = t_scaler
1058
+ test_sets[ticker] = test
1059
+
1060
+ X_train_parts.append(train["X"])
1061
+ y_train_parts.append(train["y"])
1062
+ asset_id_train_parts.append(train["asset_id"])
1063
+ print(f" {ticker:10s} train={len(train['X']):5d} test={len(test['X']):5d}")
1064
+
1065
+ X_train = np.concatenate(X_train_parts, axis=0)
1066
+ y_train = np.concatenate(y_train_parts, axis=0)
1067
+ asset_id_train = np.concatenate(asset_id_train_parts, axis=0).reshape(-1, 1)
1068
+ print(f" Dataset global combinado -> X_train {X_train.shape}")
1069
+
1070
+ print("[3/5] Construyendo y entrenando el modelo GLOBAL...")
1071
+ # Verificación de dimensionalidad ANTES de instanciar el modelo: si
1072
+ # TECH_COLS y N_FEATURES se desalinearan del tensor real, mejor un
1073
+ # AssertionError explícito acá que un colapso de shape dentro de la BiLSTM.
1074
+ assert X_train.shape[-1] == N_FEATURES, (
1075
+ f"Desalineación de features: X_train tiene {X_train.shape[-1]} columnas "
1076
+ f"pero N_FEATURES={N_FEATURES} (TECH_COLS={TECH_COLS}). Revisa "
1077
+ "engineer_asset()/build_asset_dataset()."
1078
+ )
1079
+ 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)")
1080
+
1081
+ # V4: ya no se necesita steps_per_epoch -> CosineDecayRestarts (que lo
1082
+ # consumía para calibrar first_decay_steps) se retiró en favor de
1083
+ # ReduceLROnPlateau/EarlyStopping (operan por ÉPOCA, no por step; ver
1084
+ # sección 10.5 del docstring del módulo).
1085
+ model, gamma_variable = build_model(
1086
+ n_timesteps=LOOKBACK, n_features=N_FEATURES, n_assets=len(TICKERS),
1087
+ mha_heads=MHA_HEADS, mha_key_dim=MHA_KEY_DIM,
1088
+ huber_delta=HUBER_DELTA, gamma_initial=GAMMA_INITIAL,
1089
+ variance_lambda=VARIANCE_LAMBDA, variance_cap=VARIANCE_CAP,
1090
+ dropout_rate=DROPOUT_RATE, dense_l2_reg=DENSE_L2_REG,
1091
+ )
1092
+ model.summary()
1093
+ print(f" [V4] Curriculum gamma: {GAMMA_INITIAL} -> {GAMMA_MAX} en {GAMMA_WARMUP_EPOCHS} "
1094
+ f"épocas (schedule={GAMMA_SCHEDULE}) | clipnorm={GRAD_CLIPNORM} | "
1095
+ f"variance_lambda={VARIANCE_LAMBDA} (cap={VARIANCE_CAP}) | "
1096
+ f"ReduceLROnPlateau(factor={REDUCE_LR_FACTOR}, patience={REDUCE_LR_PATIENCE}) | "
1097
+ f"EarlyStopping(patience={EARLY_STOPPING_PATIENCE}, start_from_epoch={EARLY_STOPPING_START_EPOCH})")
1098
+ history, model = train_model(
1099
+ model, X_train, asset_id_train, y_train,
1100
+ epochs=EPOCHS, batch_size=BATCH_SIZE, validation_split=VALIDATION_SPLIT,
1101
+ gamma_variable=gamma_variable, gamma_max=GAMMA_MAX,
1102
+ gamma_warmup_epochs=GAMMA_WARMUP_EPOCHS, gamma_schedule=GAMMA_SCHEDULE,
1103
+ gamma_sigmoid_steepness=GAMMA_SIGMOID_STEEPNESS,
1104
+ )
1105
+
1106
+ print("[4/5] Evaluación por activo (reconstrucción de precio + directional accuracy)...")
1107
+ results = {}
1108
+ for ticker in TICKERS:
1109
+ results[ticker] = evaluate_asset(model, test_sets[ticker], ticker, target_scalers[ticker])
1110
+ r = results[ticker]
1111
+ print(f" {ticker:10s} MAE=${r['mae_price']:.2f} RMSE=${r['rmse_price']:.2f} "
1112
+ f"DirAcc={r['directional_accuracy'] * 100:.1f}%")
1113
+
1114
+ plot_asset(results["AAPL"], "AAPL") # muestra representativa; repetir con cualquier ticker de TICKERS
1115
+
1116
+ print("[5/5] Exportando modelo global + scalers -> ENRUTAMIENTO DE PRODUCCIÓN (/services)...")
1117
+ # Rutas FIJAS (nombre de archivo estable, sin timestamp/versión) para que cada
1118
+ # corrida del pipeline SOBREESCRIBA el artefacto anterior en vez de generar
1119
+ # duplicados tipo "scalers 1.pkl".
1120
+ model_path = PROD_DIR / "attention_bilstm_global.keras"
1121
+ scalers_path = PROD_DIR / "scalers.pkl"
1122
+
1123
+ model.save(model_path, overwrite=True) # overwrite explícito: en un runner de CI no hay prompt interactivo que confirmar
1124
+
1125
+ scalers_payload = {
1126
+ "feature_scalers": feature_scalers,
1127
+ "target_scalers": target_scalers,
1128
+ "asset_to_id": ASSET_TO_ID,
1129
+ "lookback": LOOKBACK,
1130
+ "macro_tickers": MACRO_TICKERS,
1131
+ "tickers": TICKERS,
1132
+ "tech_cols": TECH_COLS, # incluye ATR_14/BB_WIDTH_20/OBV -> permite validar orden/dimensión en producción
1133
+ }
1134
+ with open(scalers_path, "wb") as f: # modo "wb" trunca y reescribe el archivo existente, no lo duplica
1135
+ pickle.dump(scalers_payload, f)
1136
+
1137
+ print(f" Modelo -> {model_path.relative_to(BASE_DIR.parent)}")
1138
+ print(f" Scalers -> {scalers_path.relative_to(BASE_DIR.parent)}")
1139
+ print(" Archivos sobreescritos exitosamente en /services")
1140
+
1141
+ # Variables disponibles en el scope global tras la ejecución:
1142
+ # model, history, feature_scalers, target_scalers, test_sets, results,
1143
+ # X_train, y_train, asset_id_train
1144
+ # %%
ml_engine/forecast_AAPL.png ADDED

Git LFS Details

  • SHA256: 6937323d82498140fb41b8c450ac32c225c68f3176d304cfc3b5eba20bd284d6
  • Pointer size: 131 Bytes
  • Size of remote file: 162 kB