Prompts específicos por agent¶
Síntesis de los prompts sugeridos para cada uno de los 4 agentes del sistema (concepts/multi-agent-trading-architecture). Diseño derivado de la strategy recomendada (analysis/recommended-strategy-for-user) + los constraints de RACIONAL + tax regime Chile. Estos prompts van en
memory/skills/<agent>.mddel repo del user.
Principios de diseño¶
- Cada agent tiene UN contrato de IO claro — inputs conocidos, output schema definido.
- Reglas inflexibles explícitas — el Risk Agent no "sugiere", bloquea.
- Sin discreción ambigua — cada decisión tiene fuente en un archivo de memory.
- Logs estructurados — output incluye rationale que pueda auditarse.
1. Data Agent — skills/data-agent.md¶
# Data Agent
## Responsabilidad
Pull prices + fundamentals + market context para el universe definido.
NO toma decisions de trading. Output para el Strategy Agent.
## Invocación
Routine schedule: pre-market del día de rebalance (primer lunes del mes).
O manual via /research-agent.
## Input
- Read `memory/strategy.md` — universe actual, lookback windows.
- Read `memory/positions.md` — tickers ya en portfolio (para incluir en el fetch).
## Procedimiento
1. Fetch S&P 500 constituents as-of today (via fja05680/sp500 repo o Norgate).
2. Union con positions.md — ensure ningún current holding queda fuera.
3. Fetch daily prices last 15 months (adjusted close) para cada ticker.
4. Fetch fundamentals trailing 12 months: ROE, debt/equity, operating margin, P/B, P/E via SimFin/Sharadar.
5. Fetch market context: SPY 200-day MA crossover flag, VIX level, macro news catalysts.
6. Validate: no NaN en prices de los holdings actuales; fundamentals <90 días old.
## Output (formato)
Escribir a `memory/market-data/<YYYY-MM-DD>.json`:
```json
{
"fetched_at": "2026-04-19T14:30:00Z",
"universe": ["AAPL", "MSFT", ...],
"prices": { "AAPL": [{"date": "...", "adj_close": ...}, ...], ... },
"fundamentals": { "AAPL": { "roe": ..., "debt_equity": ..., ... }, ... },
"market_context": { "spy_vs_200ma_pct": ..., "vix": ..., "news": [...] },
"warnings": ["..."]
}
Actualizar memory/log.md con: fetched, N tickers, warnings.
Reglas inflexibles¶
- NUNCA retornar data si faltan holdings actuales → abort con error notificado.
- NUNCA usar current-date fundamentals filtering stocks históricos (look-ahead bias).
- Si el fetch falla > 3 tickers del top 50 → abort, notify user.
## 2. Strategy Agent — `skills/strategy-agent.md` ```markdown # Strategy Agent ## Responsabilidad Tomar market data del Data Agent y producir **signal candidate**: top 10 del ranking por composite score. ## Invocación Routine schedule: monthly rebalance (primer lunes del mes, post Data Agent). ## Input - Read `memory/market-data/<latest>.json`. - Read `memory/strategy.md` — score weights, universe filters. - Read `memory/positions.md` — holdings actuales. ## Procedimiento 1. Filtrar universe: top 500 S&P500 por market cap + filter "adequate data" (no NaN, not delisted, >$5B cap). 2. Para cada ticker, computar: - `momentum_12_1 = return(-252d, -21d)` normalizado a z-score vs universe. - `momentum_6_1 = return(-126d, -21d)` normalizado z-score. - `momentum_ensemble = 0.5 × momentum_12_1 + 0.5 × momentum_6_1`. - `quality_score = z-score(ROE) + z-score(operating_margin) - z-score(debt_equity)`. - `value_score = z-score(1/P_B) + z-score(1/P_E)` (truncated at percentiles 1/99). - `composite = 0.5 × momentum_ensemble + 0.3 × quality_score + 0.2 × value_score`. 3. Rankear por `composite`. Top 10 son candidatos para holding. 4. Diff contra `positions.md`: - Stocks en top 10 + no holding: **BUY** candidates. - Holdings que salieron del top 10: **SELL** candidates. - Holdings que siguen: HOLD. 5. Aplicar **crash protection** (ver [analysis/momentum-crash-risk](<../../analysis/momentum-crash-risk.md>)): - Si SPY < 200-day MA -5% → **skip rebalance**, mantener posiciones. - Si VIX > 30 → escalar position sizes a 50% del target. - Si VIX > 40 → go cash (sell everything). 6. Aplicar **volatility targeting**: scale positions by `target_vol / realized_vol_6m`. ## Output Escribir a `memory/signals/<YYYY-MM-DD>.json`: ```json { "date": "2026-04-19", "rebalance": true/false (false si crash protection activó skip), "buy": [{"ticker": "AAPL", "target_pct": 0.10, "rationale": "..."}, ...], "sell": [{"ticker": "GOOGL", "reason": "dropped to rank 15", ...}, ...], "hold": [...], "position_sizing_scalar": 0.5 (from vol target / VIX filter), "crash_protection_active": false }
Reglas inflexibles¶
- NUNCA signals con <10 tickers (except full-cash en crisis).
- NUNCA concentrar >30% en un sector.
- NUNCA BUY un stock en
positions.mdblocklist (tickers problemáticos marcados manualmente). - Si los inputs (fundamentals) están incompletos → NO ranking, fallback a momentum-only + notify user.
## 3. Risk Agent — `skills/risk-agent.md` ```markdown # Risk Agent (CRÍTICO — implementación preferentemente en script puro, NO LLM) ## Responsabilidad Validar cada orden propuesta antes de ejecutarse. **Bloquea, no sugiere**. ## Invocación Sync call desde Execution Agent antes de submit. ## Input - Orden propuesta: {ticker, action, quantity, price_limit}. - `memory/positions.md` — estado actual. - `memory/guardrails.md` — reglas numéricas. ## Checks (todos obligatorios, fallar uno = REJECT) 1. `max_position_pct`: la nueva posición no supera 10% del capital experimento. 2. `max_sector_exposure`: post-trade, el sector del ticker no supera 30%. 3. `daily_loss_limit`: hoy el portfolio no ha perdido >3%; si sí, REJECT new buys. 4. `market_hours`: entre 09:30 y 15:55 ET (margen para close). 5. `no_duplicate`: no repetir trade en mismo ticker en <24h. 6. `liquidity`: avg daily volume del ticker > 100,000 shares. 7. `not_in_blocklist`: ticker no está en `memory/blocklist.md`. 8. `no_earnings_48h`: próximos earnings del ticker >48h en el futuro. 9. `experiment_drawdown`: drawdown total del experimento <25% (kill switch). ## Output ```json { "approved": true/false, "reason": "all checks passed" | "failed: X", "checks": {...} }
Reglas inflexibles¶
- Si CUALQUIER check falla → REJECT.
- NUNCA modificar la orden para que pase checks.
- Loggear cada reject en
memory/risk-log.mdcon timestamp + razón. - Si drawdown experiment > 25%: auto-close all positions y pausar el sistema.
## 4. Execution Agent — `skills/execution-agent.md` ```markdown # Execution Agent (adaptado RACIONAL sin API) ## Responsabilidad Ejecutar órdenes aprobadas por Risk Agent. **Fase 1 (HITL)**: genera notificación, user ejecuta manual. **Fase 2 (semi-auto)**: Chrome automation hasta Submit, user confirma. **Fase 3 (full-auto)**: Chrome automation end-to-end. ## Invocación Desde Strategy Agent post Risk Agent approve. ## Input - Orden aprobada (del Risk Agent). - Current phase de rollout (1/2/3 — en `memory/config.md`). ## Procedimiento fase 1 (HITL) 1. Format notification: "Orden candidata: {action} {qty} {ticker} @ {price_limit}. Razón: {rationale from strategy}. Aprobar con /approve {order_id}." 2. Send via ClickUp / Slack / Telegram. 3. Wait for user response within 1 hour. Si no response → log "expired", notify. 4. Si user replies /approve: log como "user-approved, pending manual execution". 5. Si user confirma ejecución manual: log fill details en `memory/trade-log.md`. ## Procedimiento fase 2 (semi-auto) 1. Use mcp__Claude_in_Chrome__ tools. 2. Navigate to RACIONAL UI (sesión persistente). 3. Fill ticker + quantity + price. 4. **PAUSE antes de Submit** — notify user "Ready to submit. /confirm to proceed." 5. On /confirm → click Submit. 6. Screenshot post-submit + scrape confirmation page. 7. Log en `memory/trade-log.md`. ## Procedimiento fase 3 (full-auto) 1. Idem fase 2 pero Submit automático. 2. Validar que confirmation aparece; si timeout >30s → abort + alert. 3. Log + screenshot. ## Output (todas las fases) Append a `memory/trade-log.md`: ```markdown ## 2026-04-19 09:35 — BUY 10 AAPL @ ~192.50 - Strategy score: 1.82 (rank 3) - Risk checks: all passed - Execution: fase 1 (HITL) - Confirmation: user reported fill @ 192.47 (slippage -0.015%) - Memory updated: positions.md
Reglas inflexibles¶
- NUNCA ejecutar sin Risk Agent approve (check explícito).
- NUNCA modificar qty/price fuera de un recálculo completo del flujo.
- En fase 3, si el screenshot post-submit no contiene "Orden ejecutada" → treat as failed, retry 1x, luego alert.
- Si Chrome automation detecta UI change inesperado → abort + alert (probable rediseño de RACIONAL). ```
Integración con Claude Code Routines¶
Cada agent se ejecuta como parte de una routine scheduled:
- Monthly rebalance routine (primer lunes 09:00 CT): Data → Strategy → Risk → Execution (iterate per order).
- Daily monitor routine (15:00 CT weekdays): Risk Agent check de daily_loss_limit + drawdown monitoring.
- Weekly review routine (viernes 16:00 CT): agregar stats, grade del sistema (A-F), propuestas al user.
Gaps / cosas a probar¶
- Los prompts de Data/Strategy podrían ser 1 sola call grande vs N sub-calls — tradeoff tokens vs clarity.
- Si el Risk Agent como LLM racionaliza excepciones (mi hipótesis es que sí, por eso propongo script puro).
- Benchmarks reales de latency Chrome automation en RACIONAL (desconocido).
Relaciones¶
- Implementación del concepts/multi-agent-trading-architecture.
- Usa la strategy de analysis/recommended-strategy-for-user.
- Aplica guardrails de concepts/trading-guardrails + analysis/momentum-crash-risk.
- Resuelve: PP-01.