Hierarchical ML Pipeline for trading predictions:
- Level 0: Attention Models (volatility/flow classification)
- Level 1: Base Models (XGBoost per symbol/timeframe)
- Level 2: Metamodels (XGBoost Stacking + Neural Gating)
Key components:
- src/pipelines/hierarchical_pipeline.py - Main prediction pipeline
- src/models/ - All ML model classes
- src/training/ - Training utilities
- src/api/ - FastAPI endpoints
- scripts/ - Training and evaluation scripts
- config/ - YAML configurations
Note: Trained models (*.joblib, *.pt) are gitignored.
Regenerate with training scripts.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
420 lines
13 KiB
Python
420 lines
13 KiB
Python
"""
|
|
Strategy Agent Prompts for LLM Fine-Tuning
|
|
==========================================
|
|
|
|
System prompts and templates for the trading strategy LLM agent.
|
|
These prompts guide the LLM to analyze ML predictions and generate
|
|
optimal trading strategies.
|
|
"""
|
|
|
|
# ============================================================
|
|
# SYSTEM PROMPT - Core Identity
|
|
# ============================================================
|
|
|
|
SYSTEM_PROMPT = """Eres un agente de trading algorítmico experto especializado en análisis de predicciones ML.
|
|
|
|
## Tu Rol
|
|
- Analizar predicciones de modelos ML (rangos high/low predichos)
|
|
- Evaluar métricas de rendimiento históricas
|
|
- Generar estrategias de trading óptimas
|
|
- Gestionar riesgo con capital limitado ($1,000 USD)
|
|
|
|
## Reglas de Gestión de Riesgo
|
|
1. Máximo 2% de riesgo por operación ($20 USD)
|
|
2. Máximo 2 posiciones simultáneas
|
|
3. Stop loss obligatorio en cada trade
|
|
4. Ratio riesgo:beneficio mínimo de 1.5:1
|
|
5. Máximo drawdown permitido: 15%
|
|
|
|
## Indicadores Disponibles
|
|
- ATR (Average True Range): Volatilidad
|
|
- SAR (Parabolic SAR): Tendencia y puntos de reversa
|
|
- RSI (Relative Strength Index): Sobrecompra/sobreventa
|
|
- MFI (Money Flow Index): Presión de compra/venta
|
|
- OBV (On Balance Volume): Confirmación de volumen
|
|
- AD (Accumulation/Distribution): Flujo de dinero institucional
|
|
- CMF (Chaikin Money Flow): Fuerza del flujo de dinero
|
|
|
|
## Formato de Respuesta
|
|
Siempre responde en JSON con el formato:
|
|
{
|
|
"analysis": "Tu análisis del mercado",
|
|
"recommendation": "BUY" | "SELL" | "HOLD",
|
|
"confidence": 0.0 a 1.0,
|
|
"entry_price": precio de entrada sugerido,
|
|
"stop_loss": precio de stop loss,
|
|
"take_profit": precio de take profit,
|
|
"position_size": tamaño de posición en lotes,
|
|
"reasoning": "Razonamiento detallado"
|
|
}
|
|
"""
|
|
|
|
# ============================================================
|
|
# ANALYSIS PROMPTS
|
|
# ============================================================
|
|
|
|
PREDICTION_ANALYSIS_PROMPT = """## Análisis de Predicciones ML
|
|
|
|
### Datos del Modelo
|
|
- **Símbolo**: {symbol}
|
|
- **Timeframe**: {timeframe}
|
|
- **Precio Actual**: {current_price}
|
|
- **Rango Alto Predicho (3 barras)**: {predicted_high} (+{high_delta}%)
|
|
- **Rango Bajo Predicho (3 barras)**: {predicted_low} ({low_delta}%)
|
|
- **ATR Actual**: {atr}
|
|
- **Attention Weight**: {attention_weight}
|
|
|
|
### Indicadores Técnicos
|
|
- **RSI**: {rsi} ({rsi_signal})
|
|
- **SAR**: {sar} (señal: {sar_signal})
|
|
- **MFI**: {mfi} ({mfi_signal})
|
|
- **CMF**: {cmf} ({cmf_signal})
|
|
|
|
### Historial Reciente
|
|
{recent_trades_summary}
|
|
|
|
### Rendimiento del Modelo en Este Activo
|
|
- Win Rate: {win_rate}%
|
|
- Profit Factor: {profit_factor}
|
|
- Sharpe Ratio: {sharpe_ratio}
|
|
- Direcciones Ganadoras: {winning_directions}
|
|
|
|
Analiza estos datos y genera una recomendación de trading.
|
|
"""
|
|
|
|
# ============================================================
|
|
# STRATEGY GENERATION PROMPTS
|
|
# ============================================================
|
|
|
|
STRATEGY_OPTIMIZATION_PROMPT = """## Optimización de Estrategia
|
|
|
|
### Problema Identificado
|
|
El backtesting reveló los siguientes problemas:
|
|
- Win Rate Global: {win_rate}%
|
|
- Retorno: {total_return}%
|
|
- Max Drawdown: {max_drawdown}%
|
|
|
|
### Patrones Observados
|
|
{patterns_summary}
|
|
|
|
### Datos Clave
|
|
- Direcciones ganadoras predominantes: {winning_directions}
|
|
- Confianza promedio en ganadores: {avg_winning_confidence}
|
|
- Confianza promedio en perdedores: {avg_losing_confidence}
|
|
- Attention weight en ganadores: {avg_winning_attention}
|
|
|
|
### Tu Tarea
|
|
1. Identifica por qué la estrategia está fallando
|
|
2. Propón ajustes específicos para mejorar:
|
|
- Filtros de entrada
|
|
- Gestión de stop loss
|
|
- Selección de dirección
|
|
3. Define reglas claras y medibles
|
|
|
|
Responde en JSON con formato:
|
|
{{
|
|
"problem_analysis": "análisis del problema",
|
|
"proposed_rules": [
|
|
{{
|
|
"rule": "descripción de la regla",
|
|
"rationale": "por qué ayudará",
|
|
"implementation": "cómo implementarla"
|
|
}}
|
|
],
|
|
"expected_improvement": "mejora esperada"
|
|
}}
|
|
"""
|
|
|
|
# ============================================================
|
|
# TRADE DECISION PROMPTS
|
|
# ============================================================
|
|
|
|
TRADE_DECISION_PROMPT = """## Decisión de Trading
|
|
|
|
### Estado Actual
|
|
- **Capital Disponible**: ${available_capital}
|
|
- **Posiciones Abiertas**: {open_positions}
|
|
- **P&L del Día**: ${daily_pnl} ({daily_pnl_pct}%)
|
|
- **Drawdown Actual**: {current_drawdown}%
|
|
|
|
### Nueva Señal Detectada
|
|
- **Símbolo**: {symbol}
|
|
- **Dirección Sugerida**: {suggested_direction}
|
|
- **Precio de Entrada**: {entry_price}
|
|
- **Stop Loss Sugerido**: {stop_loss}
|
|
- **Take Profit Sugerido**: {take_profit}
|
|
- **Confianza del Modelo**: {model_confidence}%
|
|
- **Attention Weight**: {attention_weight}
|
|
|
|
### Indicadores de Confirmación
|
|
{indicators_summary}
|
|
|
|
### Pregunta
|
|
¿Debo tomar este trade? Si es afirmativo, especifica el tamaño de posición.
|
|
|
|
Responde en JSON:
|
|
{{
|
|
"decision": "TAKE" | "SKIP",
|
|
"position_size": tamaño en lotes (si TAKE),
|
|
"adjusted_sl": stop loss ajustado si es necesario,
|
|
"adjusted_tp": take profit ajustado si es necesario,
|
|
"reasoning": "razonamiento completo"
|
|
}}
|
|
"""
|
|
|
|
# ============================================================
|
|
# POST-TRADE ANALYSIS PROMPTS
|
|
# ============================================================
|
|
|
|
POST_TRADE_ANALYSIS_PROMPT = """## Análisis Post-Trade
|
|
|
|
### Trade Completado
|
|
- **ID**: {trade_id}
|
|
- **Símbolo**: {symbol}
|
|
- **Dirección**: {direction}
|
|
- **Entrada**: {entry_price}
|
|
- **Salida**: {exit_price}
|
|
- **P&L**: ${pnl} ({pnl_pct}%)
|
|
- **Resultado**: {outcome}
|
|
- **Duración**: {duration}
|
|
|
|
### Condiciones al Momento del Trade
|
|
- RSI: {rsi_at_entry}
|
|
- SAR Signal: {sar_signal_at_entry}
|
|
- Attention Weight: {attention_weight_at_entry}
|
|
- Modelo Confianza: {model_confidence}%
|
|
|
|
### Pregunta
|
|
¿Qué podemos aprender de este trade para mejorar la estrategia?
|
|
|
|
Responde en JSON:
|
|
{{
|
|
"lesson_learned": "lección principal",
|
|
"was_good_entry": true/false,
|
|
"improvement_suggestions": ["sugerencia 1", "sugerencia 2"],
|
|
"pattern_to_remember": "patrón a recordar para futuras decisiones"
|
|
}}
|
|
"""
|
|
|
|
# ============================================================
|
|
# FINE-TUNING EXAMPLES
|
|
# ============================================================
|
|
|
|
FINE_TUNING_EXAMPLES = [
|
|
# Example 1: Skip trade due to counter-trend
|
|
{
|
|
"input": """## Decisión de Trading
|
|
Capital Disponible: $980
|
|
Símbolo: XAUUSD
|
|
Dirección Sugerida: LONG
|
|
RSI: 72 (sobrecompra)
|
|
SAR: por encima del precio (bajista)
|
|
Attention Weight: 2.1
|
|
Modelo Confianza: 85%""",
|
|
"output": """{
|
|
"decision": "SKIP",
|
|
"reasoning": "A pesar de la alta confianza del modelo (85%), los indicadores técnicos son contradictorios. RSI en 72 indica sobrecompra, y SAR por encima del precio confirma tendencia bajista. Entrar LONG aquí sería contra tendencia. Esperar mejor setup."
|
|
}"""
|
|
},
|
|
# Example 2: Take trade with high confluence
|
|
{
|
|
"input": """## Decisión de Trading
|
|
Capital Disponible: $1,000
|
|
Símbolo: XAUUSD
|
|
Dirección Sugerida: SHORT
|
|
RSI: 68 (sobrecompra moderada)
|
|
SAR: por encima del precio (bajista)
|
|
CMF: -0.15 (flujo vendedor)
|
|
Attention Weight: 2.8
|
|
Modelo Confianza: 90%""",
|
|
"output": """{
|
|
"decision": "TAKE",
|
|
"position_size": 0.02,
|
|
"adjusted_sl": null,
|
|
"adjusted_tp": null,
|
|
"reasoning": "Alta confluencia: (1) RSI en zona alta sugiere agotamiento, (2) SAR confirma tendencia bajista, (3) CMF negativo muestra presión vendedora, (4) Attention weight alto (2.8) indica momento de alta volatilidad. Confianza del modelo 90%. R:R favorable."
|
|
}"""
|
|
},
|
|
# Example 3: Reduce position due to drawdown
|
|
{
|
|
"input": """## Decisión de Trading
|
|
Capital Disponible: $870
|
|
Drawdown Actual: 13%
|
|
Símbolo: EURUSD
|
|
Dirección Sugerida: LONG
|
|
Attention Weight: 1.5
|
|
Modelo Confianza: 75%""",
|
|
"output": """{
|
|
"decision": "TAKE",
|
|
"position_size": 0.01,
|
|
"reasoning": "Cerca del máximo drawdown permitido (15%). Reducir tamaño de posición al mínimo (0.01). El trade tiene confluencia moderada pero debemos proteger el capital restante."
|
|
}"""
|
|
},
|
|
# Example 4: Skip due to low attention weight
|
|
{
|
|
"input": """## Decisión de Trading
|
|
Símbolo: XAUUSD
|
|
Dirección Sugerida: LONG
|
|
Attention Weight: 0.3
|
|
Modelo Confianza: 65%""",
|
|
"output": """{
|
|
"decision": "SKIP",
|
|
"reasoning": "Attention weight muy bajo (0.3) indica movimiento de baja significancia. La volatilidad actual no justifica el riesgo. Esperar momento de mayor actividad del mercado."
|
|
}"""
|
|
}
|
|
]
|
|
|
|
# ============================================================
|
|
# STRATEGY RULES (Based on Backtest Analysis)
|
|
# ============================================================
|
|
|
|
OPTIMIZED_STRATEGY_RULES = """## Reglas de Estrategia Optimizadas
|
|
|
|
### Basado en el análisis del backtest:
|
|
|
|
#### 1. Filtro Direccional
|
|
- **PRIORIZAR SHORT** en XAUUSD (100% de ganadores fueron SHORT)
|
|
- Solo tomar LONG si RSI < 30 Y SAR está debajo del precio Y CMF > 0
|
|
|
|
#### 2. Filtro de Confianza
|
|
- Mínima confianza para SHORT: 70%
|
|
- Mínima confianza para LONG: 85%
|
|
- Attention weight mínimo: 1.0
|
|
|
|
#### 3. Filtro de Confirmación Técnica
|
|
Para SHORT requiere al menos 2 de:
|
|
- RSI > 60 (tendencia sobreextendida)
|
|
- SAR por encima del precio
|
|
- CMF < 0 (flujo vendedor)
|
|
- MFI > 60
|
|
|
|
Para LONG requiere todos:
|
|
- RSI < 40
|
|
- SAR debajo del precio
|
|
- CMF > 0.1
|
|
- MFI < 40
|
|
|
|
#### 4. Gestión de Posición
|
|
- Reducir tamaño 50% si drawdown > 10%
|
|
- No operar si drawdown > 12%
|
|
- Máximo 1 posición por símbolo
|
|
|
|
#### 5. Gestión de Stop Loss
|
|
- SL basado en ATR: 1.5 * ATR desde entrada
|
|
- Trailing stop después de +1R de ganancia
|
|
- TP: 2.0 * distancia al SL (R:R = 2:1)
|
|
"""
|
|
|
|
# ============================================================
|
|
# PROMPT BUILDER FUNCTIONS
|
|
# ============================================================
|
|
|
|
def build_prediction_analysis_prompt(
|
|
symbol: str,
|
|
timeframe: str,
|
|
current_price: float,
|
|
predicted_high: float,
|
|
predicted_low: float,
|
|
atr: float,
|
|
attention_weight: float,
|
|
rsi: float,
|
|
sar: float,
|
|
mfi: float,
|
|
cmf: float,
|
|
win_rate: float,
|
|
profit_factor: float,
|
|
sharpe_ratio: float,
|
|
winning_directions: str,
|
|
recent_trades_summary: str = "No hay trades recientes"
|
|
) -> str:
|
|
"""Build the prediction analysis prompt with actual data"""
|
|
|
|
high_delta = ((predicted_high - current_price) / current_price) * 100
|
|
low_delta = ((predicted_low - current_price) / current_price) * 100
|
|
|
|
rsi_signal = "sobrecompra" if rsi > 70 else "sobreventa" if rsi < 30 else "neutral"
|
|
sar_signal = "bajista" if sar > current_price else "alcista"
|
|
mfi_signal = "presión compradora" if mfi > 60 else "presión vendedora" if mfi < 40 else "neutral"
|
|
cmf_signal = "flujo positivo" if cmf > 0.1 else "flujo negativo" if cmf < -0.1 else "neutral"
|
|
|
|
return PREDICTION_ANALYSIS_PROMPT.format(
|
|
symbol=symbol,
|
|
timeframe=timeframe,
|
|
current_price=f"{current_price:.4f}",
|
|
predicted_high=f"{predicted_high:.4f}",
|
|
high_delta=f"{high_delta:+.2f}",
|
|
predicted_low=f"{predicted_low:.4f}",
|
|
low_delta=f"{low_delta:+.2f}",
|
|
atr=f"{atr:.4f}",
|
|
attention_weight=f"{attention_weight:.2f}",
|
|
rsi=f"{rsi:.1f}",
|
|
rsi_signal=rsi_signal,
|
|
sar=f"{sar:.4f}",
|
|
sar_signal=sar_signal,
|
|
mfi=f"{mfi:.1f}",
|
|
mfi_signal=mfi_signal,
|
|
cmf=f"{cmf:.3f}",
|
|
cmf_signal=cmf_signal,
|
|
win_rate=f"{win_rate:.1f}",
|
|
profit_factor=f"{profit_factor:.2f}",
|
|
sharpe_ratio=f"{sharpe_ratio:.2f}",
|
|
winning_directions=winning_directions,
|
|
recent_trades_summary=recent_trades_summary
|
|
)
|
|
|
|
|
|
def build_trade_decision_prompt(
|
|
available_capital: float,
|
|
open_positions: int,
|
|
daily_pnl: float,
|
|
current_drawdown: float,
|
|
symbol: str,
|
|
suggested_direction: str,
|
|
entry_price: float,
|
|
stop_loss: float,
|
|
take_profit: float,
|
|
model_confidence: float,
|
|
attention_weight: float,
|
|
indicators: dict
|
|
) -> str:
|
|
"""Build the trade decision prompt with actual data"""
|
|
|
|
daily_pnl_pct = (daily_pnl / available_capital) * 100 if available_capital > 0 else 0
|
|
|
|
indicators_summary = "\n".join([
|
|
f"- {key}: {value}" for key, value in indicators.items()
|
|
])
|
|
|
|
return TRADE_DECISION_PROMPT.format(
|
|
available_capital=f"{available_capital:.2f}",
|
|
open_positions=open_positions,
|
|
daily_pnl=f"{daily_pnl:.2f}",
|
|
daily_pnl_pct=f"{daily_pnl_pct:.1f}",
|
|
current_drawdown=f"{current_drawdown:.1f}",
|
|
symbol=symbol,
|
|
suggested_direction=suggested_direction,
|
|
entry_price=f"{entry_price:.4f}",
|
|
stop_loss=f"{stop_loss:.4f}",
|
|
take_profit=f"{take_profit:.4f}",
|
|
model_confidence=f"{model_confidence:.1f}",
|
|
attention_weight=f"{attention_weight:.2f}",
|
|
indicators_summary=indicators_summary
|
|
)
|
|
|
|
|
|
# ============================================================
|
|
# EXPORT
|
|
# ============================================================
|
|
|
|
__all__ = [
|
|
'SYSTEM_PROMPT',
|
|
'PREDICTION_ANALYSIS_PROMPT',
|
|
'STRATEGY_OPTIMIZATION_PROMPT',
|
|
'TRADE_DECISION_PROMPT',
|
|
'POST_TRADE_ANALYSIS_PROMPT',
|
|
'FINE_TUNING_EXAMPLES',
|
|
'OPTIMIZED_STRATEGY_RULES',
|
|
'build_prediction_analysis_prompt',
|
|
'build_trade_decision_prompt'
|
|
]
|