Files
NexQuant/rdagent/scenarios/qlib/developer/factor_coder.py
T
TPTBusiness 74d5a8234e feat: Integrate critical features into fin_quant workflow (P0+P1)
Connect Protection Manager, Results Database, model_loader, and Technical
Indicators to the main fin_quant trading loop.

P0 - CRITICAL INTEGRATIONS:

1. PROTECTION MANAGER in factor_runner.py
   - Automatic protection check after every backtest
   - Factors with >15% drawdown are rejected
   - Cooldown, stoploss guard, low performance filters active
   - Error handling: workflow continues if protection fails

2. RESULTS DATABASE in quant.py
   - Auto-save experiment results to SQLite after each loop
   - Stores: IC, Sharpe, Max DD, Annualized Return, Win Rate
   - Queryable via ResultsDatabase API
   - Error handling: warning logged, workflow continues

P1 - IMPORTANT INTEGRATIONS:

3. MODEL LOADER in model_coder.py
   - Loads models/local/ as baseline reference for LLM
   - Transformer, TCN, PatchTST, CNN+LSTM now used as starting point
   - LLM can improve upon existing models instead of from scratch

4. TECHNICAL INDICATORS in factor_coder.py
   - RSI, MACD, Bollinger Bands, CCI, ATR available to LLM
   - Import paths and usage examples in prompts
   - Better factor generation with professional indicators

TESTS (32 new, ALL PASS):
- 23 integration tests in test/qlib/test_fin_quant_integration.py
- 9 enhanced integration tests in test/integration/test_all_features.py
- All 183 tests pass (122 backtesting + 29 qlib + 32 new)

Modified files:
- rdagent/app/qlib_rd_loop/quant.py: Results Database integration
- rdagent/scenarios/qlib/developer/factor_runner.py: Protection Manager
- rdagent/scenarios/qlib/developer/model_coder.py: model_loader baseline
- rdagent/scenarios/qlib/developer/factor_coder.py: Technical indicators
- test/qlib/test_fin_quant_integration.py: NEW - 23 integration tests
- test/integration/test_all_features.py: 9 enhanced tests
2026-04-03 14:10:44 +02:00

83 lines
3.0 KiB
Python

"""
Qlib Factor Coder - Generates trading factors using LLM.
Integrates with technical indicators module to provide
available indicator functions for factor implementation.
"""
from rdagent.components.coder.factor_coder import FactorCoSTEER
from rdagent.core.scenario import Scenario
# Technical indicators documentation string for LLM prompts
TECHNICAL_INDICATORS_DOCSTRING = """
## Available Technical Indicator Functions
You can use these pre-implemented technical indicators in your factor implementations:
```python
from rdagent.components.coder.rl.indicators import (
calculate_rsi, # Relative Strength Index (0-100, overbought/oversold)
calculate_macd, # MACD (Moving Average Convergence Divergence)
calculate_bollinger_bands, # Bollinger Bands (upper, middle, lower)
calculate_cci, # Commodity Channel Index
calculate_atr, # Average True Range (volatility)
prepare_features # Combine all indicators
)
# Example usage:
rsi = calculate_rsi(df['close'], period=14)
macd_df = calculate_macd(df['close'])
bb_df = calculate_bollinger_bands(df['close'], period=20, std_dev=2.0)
cci = calculate_cci(df['close'], df['high'], df['low'], period=20)
atr = calculate_atr(df['high'], df['low'], df['close'], period=14)
```
All functions return pandas Series or DataFrames ready to be used as factor values.
### Indicator Descriptions
- **RSI (Relative Strength Index)**: Momentum oscillator, range 0-100.
- Above 70 = overbought (potential reversal down)
- Below 30 = oversold (potential reversal up)
- **MACD (Moving Average Convergence Divergence)**: Trend-following momentum.
- Returns DataFrame with 'macd', 'signal', 'histogram' columns
- Crossovers indicate potential trend changes
- **Bollinger Bands**: Volatility bands around moving average.
- Returns DataFrame with 'upper', 'middle', 'lower' columns
- Price near upper band = potentially overbought
- Price near lower band = potentially oversold
- **CCI (Commodity Channel Index)**: Momentum oscillator.
- Above +100 = overbought
- Below -100 = oversold
- **ATR (Average True Range)**: Volatility measure.
- Higher values = more volatile market
- Useful for dynamic stop-loss placement
"""
class QlibFactorCoSTEER(FactorCoSTEER):
"""
Qlib-specific Factor Coder that includes technical indicators documentation.
Enhances the scenario with available technical indicator functions
so the LLM knows what tools it can use for factor generation.
"""
def __init__(self, scen: Scenario, *args, **kwargs) -> None:
# Add technical indicators documentation to scenario
if hasattr(scen, "factor_knowledge"):
scen.factor_knowledge += TECHNICAL_INDICATORS_DOCSTRING
elif hasattr(scen, "__dict__"):
scen.technical_indicators_doc = TECHNICAL_INDICATORS_DOCSTRING
super().__init__(scen, *args, **kwargs)
# Keep the alias for backward compatibility
QlibFactorCoSTEER = QlibFactorCoSTEER