Skip to content

feat: plataforma completa de análisis de inversiones en tiempo real v2.0.0#3

Open
JairViana-Libertank wants to merge 2 commits into
yennanliu:mainfrom
JairViana-Libertank:claude/gracious-rosalind
Open

feat: plataforma completa de análisis de inversiones en tiempo real v2.0.0#3
JairViana-Libertank wants to merge 2 commits into
yennanliu:mainfrom
JairViana-Libertank:claude/gracious-rosalind

Conversation

@JairViana-Libertank
Copy link
Copy Markdown

@JairViana-Libertank JairViana-Libertank commented Apr 11, 2026

Resumen

Plataforma profesional de análisis de inversiones en español, con datos en tiempo real, inteligencia artificial y múltiples interfaces (web, Telegram, WhatsApp).


Arquitectura

investskill/
├── core/
│   ├── data/
│   │   ├── fetcher.py      # Motor de datos yfinance (US, LatAm, Crypto)
│   │   └── macro.py        # Indicadores FRED (PIB, CPI, Fed Funds, curva)
│   ├── analysis/
│   │   ├── fundamental.py  # Piotroski F-Score, ROIC/WACC/EVA
│   │   ├── valuation.py    # DCF 3 escenarios + tabla sensibilidad + múltiplos
│   │   └── technical.py    # RSI, MACD, Bollinger, ATR, soporte/resistencia
│   └── ai/
│       └── analyst.py      # Claude API → narrativas en español + señal 0-10
├── app/
│   ├── main.py             # Dashboard principal Streamlit
│   └── pages/
│       ├── 1_Fundamental   # Piotroski + ROIC + estados financieros 4 años
│       ├── 2_Valoracion    # DCF + sensitivity table + football field
│       ├── 3_Tecnico       # Velas + indicadores + retornos históricos
│       ├── 4_Macro         # Curva rendimientos + series FRED
│       ├── 5_Portafolio    # P&L tiempo real + sector allocation
│       └── 6_Reporte       # Informe completo + descarga JSON
├── bots/
│   ├── telegram_bot.py     # 8 comandos: /analizar /precio /dcf /tecnico...
│   └── whatsapp_bot.py     # Flask webhook Twilio + alertas proactivas
├── config.py               # Configuración central (mercados, FRED, WACC)
├── requirements.txt        # Todas las dependencias
├── .env.example            # Template de claves API
└── start.sh                # ./start.sh [app|telegram|whatsapp|all]

Características principales

  • Datos reales via yfinance (US stocks, LatAm, crypto, índices)
  • Macroeconomía via FRED (gratuito, sin API key)
  • Piotroski F-Score calculado con datos financieros reales (9 criterios)
  • DCF en 3 escenarios (alcista/base/bajista) + tabla de sensibilidad WACC × g
  • ROIC/WACC/EVA calculados automáticamente
  • Indicadores técnicos reales: RSI, MACD, Bollinger, ATR, Estocástico
  • IA en español via Claude API (opcional) — narrativas, tesis, veredicto
  • Señal de inversión 0-10 consolidando todos los análisis
  • Multi-mercado: NYSE/NASDAQ, BMV (.MX), B3 (.SA), BYMA (.BA), BCS (.SN), Crypto

Inicio rápido

# 1. Instalar dependencias
pip install -r requirements.txt

# 2. Configurar entorno
cp .env.example .env
# (editar .env con tus claves opcionales)

# 3. Lanzar la app web
./start.sh app
# → Abre http://localhost:8501

# 4. (Opcional) Lanzar bot de Telegram
./start.sh telegram

# 5. (Opcional) Lanzar bot de WhatsApp
./start.sh whatsapp

Test plan

  • pip install -r requirements.txt sin errores
  • python3 -c "from core.data.fetcher import FetcherMercado; print(FetcherMercado(AAPL).precio_actual()[precio])" → precio real
  • ./start.sh app abre Streamlit en http://localhost:8501
  • Ingresar ticker IREN → muestra precio, métricas, gráfico
  • Página Valoración → DCF y tabla de sensibilidad se calculan
  • Página Técnico → gráfico de velas + indicadores reales
  • Página Macro → curva de rendimientos desde FRED
  • Página Portafolio → P&L en tiempo real
  • Página Reporte → genera informe completo + descarga JSON

🤖 Generated with Claude Code

- requirements.txt: all dependencies (yfinance, streamlit, anthropic, telegram, twilio, plotly, ta)
- config.py: central config with market settings, FRED indicators, API validation helpers
- .env.example: template for API keys (Claude, Telegram, Twilio)
- start.sh: one-command launcher for web app, Telegram bot, WhatsApp bot, or all
- core/data/fetcher.py: FetcherMercado — universal real-time data engine (US stocks, LatAm, crypto)
  - Price, fundamentals, financial statements, Piotroski raw data, analyst consensus, news, options
- core/data/macro.py: FRED macro dashboard (GDP, CPI, Fed funds, yield curve, unemployment)
- core/analysis/fundamental.py: Piotroski F-Score (all 9 criteria), ROIC/WACC/EVA, earnings quality

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉 Thanks for opening your first pull request in InvestSkill!

We're excited to review your contribution. Please ensure:

  • All CI checks are passing
  • You've filled out the PR template
  • Documentation is updated (if needed)
  • CHANGELOG.md is updated

A maintainer will review your PR shortly. Feel free to ask questions or request feedback!

Check out our Contributing Guide for more information.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements the core infrastructure for InvestSkill, including configuration management, market and macro data fetchers, and a fundamental analysis engine. Feedback highlights a critical invalid AI model name in the configuration, a potential IndexError and performance inefficiency in the financial data parsing logic, and the fact that the startup script references entry-point files not included in this PR. Additionally, improvements regarding virtual environment usage and warning suppression were suggested.

Comment thread config.py

# ── IA ─────────────────────────────────────────────────────
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
CLAUDE_MODEL = "claude-sonnet-4-6"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

El identificador de modelo claude-sonnet-4-6 no es un nombre de modelo válido en la API de Anthropic. Actualmente, los modelos de la serie Sonnet siguen una nomenclatura como claude-3-5-sonnet-20240620. Usar un nombre incorrecto provocará fallos en las peticiones a la IA.

Suggested change
CLAUDE_MODEL = "claude-sonnet-4-6"
CLAUDE_MODEL = "claude-3-5-sonnet-20240620"

Comment thread core/data/fetcher.py
Comment on lines +383 to +388
def get_val(df, keyword, col=0):
for k in df.index:
if keyword.lower() in str(k).lower():
v = df.iloc[df.index.tolist().index(k), col]
return float(v) if pd.notna(v) else None
return None
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

La función get_val tiene dos problemas:

  1. Vulnerabilidad: Lanzará un IndexError si el DataFrame tiene menos columnas de las esperadas (por ejemplo, si yfinance solo devuelve datos del año actual y se solicita col=1).
  2. Eficiencia: df.index.tolist().index(k) es ineficiente ($O(N)$ dentro de un bucle $O(N)$), resultando en una complejidad $O(N^2)$.

Se sugiere validar el número de columnas y usar enumerate para una búsqueda más eficiente.

Suggested change
def get_val(df, keyword, col=0):
for k in df.index:
if keyword.lower() in str(k).lower():
v = df.iloc[df.index.tolist().index(k), col]
return float(v) if pd.notna(v) else None
return None
def get_val(df, keyword, col=0):
if col >= df.shape[1]:
return None
for i, k in enumerate(df.index):
if keyword.lower() in str(k).lower():
v = df.iloc[i, col]
return float(v) if pd.notna(v) else None
return None

Comment thread start.sh

iniciar_app() {
echo -e "\n${VERDE}▶ Iniciando aplicación web en http://localhost:8501${NC}\n"
streamlit run app/main.py \
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

El script intenta ejecutar app/main.py, pero este archivo no está incluido en los cambios de este pull request. Lo mismo sucede con los bots en las líneas 80 y 85. Esto causará que el script falle inmediatamente al intentar iniciar la aplicación. Si estos componentes son parte de fases posteriores, el script debería manejar su ausencia de forma controlada.

Comment thread core/data/fetcher.py
from datetime import datetime, timedelta
from typing import Optional
import warnings
warnings.filterwarnings("ignore")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Suprimir todas las advertencias de forma global (warnings.filterwarnings("ignore")) en un módulo central es una práctica arriesgada. Esto puede ocultar problemas importantes como advertencias de deprecación en pandas o yfinance que podrían romper el código en el futuro. Se recomienda eliminar esta línea o ser más específico con los filtros.

Comment thread start.sh
# Dependencias
if ! python3 -c "import streamlit" &>/dev/null; then
echo -e " ${AMARILLO}⚠ Instalando dependencias...${NC}"
pip3 install -r requirements.txt -q
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instalar dependencias directamente con pip3 sin utilizar un entorno virtual (venv) puede causar conflictos con otros paquetes del sistema o versiones globales. Se recomienda encarecidamente crear y activar un entorno virtual antes de ejecutar la instalación.

…gram & WhatsApp bots

Analysis engines:
- core/analysis/valuation.py: DCF (3 scenarios + sensitivity table), multiples (P/E, EV/EBITDA, P/FCF), Chowder rule, valuation score
- core/analysis/technical.py: RSI, MACD, Bollinger Bands, ATR, Stochastic, support/resistance, trend score 0-10
- core/ai/analyst.py: Claude API integration — Spanish narratives for stock eval, DCF, technical, macro; final investment signal 0-10

Streamlit web app (6 pages):
- app/main.py: main dashboard — real-time index bar, price chart with SMA/volume, key metrics, analyst consensus
- pages/1: Piotroski F-Score (9 criteria), ROIC/WACC/EVA, financial statements charts (4 years)
- pages/2: DCF 3-scenario model, sensitivity table, football field chart, multiples valuation
- pages/3: candlestick chart + Bollinger Bands, all technical indicators, historical returns
- pages/4: FRED macro dashboard — yield curve, time series of any indicator, AI macro narrative
- pages/5: portfolio tracker — real-time P&L, sector allocation, historical performance
- pages/6: full downloadable report — all analysis consolidated + JSON export

Bots:
- bots/telegram_bot.py: /precio /fundamental /dcf /tecnico /analizar /macro + free-text ticker support
- bots/whatsapp_bot.py: Flask webhook via Twilio — same commands, proactive alert function

Verified: all modules import correctly, live AAPL data fetches successfully ($260.48 USD)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@JairViana-Libertank JairViana-Libertank changed the title feat: plataforma de análisis de inversiones en tiempo real v2.0.0 feat: plataforma completa de análisis de inversiones en tiempo real v2.0.0 Apr 11, 2026
@yennanliu
Copy link
Copy Markdown
Owner

Thannks for the PR, please use english in both PR title and descriptions, and fix the git conflicts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants