Replace sequential predict() calls with predict_batch() in both
build_kronos_factor and evaluate_kronos_model. Up to batch_size windows
processed simultaneously on GPU, reducing per-window time from ~10s to
~0.13s (10 windows in 1.3s on RTX 5060 Ti, 75x speedup).
Adds --batch-size / -b option (default 32) to both kronos-factor and
kronos-eval CLI commands. Falls back to single inference per window if a
batch fails. Refactors timestamp prep into _build_window_inputs helper.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
KronosPredictor.predict() requires x_timestamp and y_timestamp to be
pandas Series of datetime values for its calc_time_stamps() helper.
Previously we passed integer ranges (after reset_index), which raised
AttributeError on .dt.minute. Fixed by extracting datetime index values
before resetting and using future_idx for y_timestamp.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Move top-level `import torch` into _cuda_available() helper so
kronos_adapter.py can be imported in CI environments without torch.
All device defaults resolved at runtime via lazy detection.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
`_sample_fine_params` and `_sample_very_fine_params` used `max(0.0, center - half_width)`
for all float parameters. When signal_bias=-0.95 (a valid Stage-1 result), this
produced low=0.0, high=-0.75 — an inverted range that causes Optuna to raise
ValueError on every trial, silently caught and returned as -inf.
Fix:
- Extract `_suggest_bounded()` helper with per-parameter floor values
- signal_bias floor is -1.0 (not 0.0 — it is a signed parameter)
- Guard against high <= low for both float and int suggestions
- Elevate trial failure logs from debug to warning so future regressions are visible
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add vbt_backtest.py as single source of truth for all metric formulas
(Sharpe, drawdown, IC, transaction costs) — backtest_engine.py and
strategy_orchestrator.py now delegate to it
- Add LLMUnavailableError to exception.py; rd_loop.py catches it at the
proposal stage and raises LoopResumeError to avoid corrupting trace
history with None hypotheses
- Guard record() against None exp/hypothesis so loop resets leave
trace.hist in a consistent state
- Refactor strategy_orchestrator and optuna_optimizer to use unified
backtest path; remove duplicate metric calculation code
- Add predix_rebacktest_unified.py script for offline re-evaluation
- Update tests and README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Path injection (#22, #28, #29, #30):
- Switch from Path.relative_to() to os.path.realpath() + str.startswith()
in all four path-validation sites across finetune and rl UI data_loader.py
and finetune app.py. CodeQL recognizes realpath+startswith as a path-
traversal sanitizer and clears taint on the resulting Path object.
- Also simplify finetune/app.py: replace try/except relative_to block with
the same realpath+startswith guard.
Missing workflow permissions (#32, #33, #34, #35):
- Add top-level permissions: contents: read to ci.yml, docs.yml, lint.yml,
and security.yml. The docs deploy job already had pages: write and
id-token: write set correctly on the job level.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Path injection (#37, #39, #40):
- _safe_resolve() in app.py: return safe_root / candidate.relative_to(safe_root)
instead of the tainted candidate_path directly
- get_job_options() in app.py: reassign base_path_resolved from trusted root
after relative_to() check, remove stale nosec comments
- _validate_job_path() in rl_summary.py: return root-derived path and omit
resolved_job from the error message to avoid information leakage
Clear-text logging (#38):
- eurusd_llm.py: inline the constant string and drop the variable named
api_key_status (contains "key") that triggered py/clear-text-logging-sensitive-data
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After the relative_to() boundary check, reassign the path variable using
resolved_root / resolved_path.relative_to(resolved_root) so all subsequent
file operations use a path derived from the trusted application root rather
than the original user-supplied value. This breaks CodeQL's taint chain
(py/path-injection) while preserving identical runtime behaviour.
Fixes alerts #41, #42, #43, #44.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add log_llm_call() to daily_log.py that appends every LLM interaction
(system prompt, user prompt, response, duration_ms) as a JSON object to
logs/YYYY-MM-DD/llm_calls.jsonl. Call it from both chat completion paths
in base.py so all LLM activity — factor generation, strategy generation,
feedback, proposals — is captured in a human-readable, grep/jq-friendly
format alongside the existing binary pickle logs.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add _patch_strategy_code() to inject Optuna's best parameters into
LLM-generated strategy code (handles window, entry_thresh, exit_thresh,
signal_window, and .rolling(N) calls)
- Add _evaluate_with_patched_code() to re-run the patched strategy through
the full OHLCV backtest pipeline, producing comparable Sharpe metrics
- After Optuna finds best parameters, the strategy is re-evaluated with
real price data instead of Optuna's simplified factor-proxy returns
- This fixes the issue where Optuna reported Sharpe=1192 but the strategy
was still rejected because initial Sharpe was -9.82 (different calculation)
- Now strategies can be rescued if Optuna finds parameters that produce
positive Sharpe in the real backtest
- Add explicit warning against .date on datetime index (causes data loss
to single year, only 314 entries instead of 2020-2026)
- Add explicit warning against df.merge() which destroys MultiIndex
(causes RangeIndex output instead of required MultiIndex)
- Enforce column name must be exactly factor_name, not a shortened alias
- Require transform() over apply() for per-group calculations to
preserve row count
- Add MultiIndex assertion before saving to result.h5
- Document expected output: ~1500+ daily entries for full 2020-2026 range
- Optuna now runs for ALL strategies (accepted AND rejected)
- Fix critical bug: Optuna parameters are now injected into LLM-generated
code via regex patching (entry_thresh, exit_thresh, window, signal_window)
Previously all 30 trials executed identical code producing the same Sharpe
- Add continuous optimization loop (--max-iterations) for repeated
strategy generation and optimization cycles
- Improve prompt v5 with better IC-inversion examples and realistic
code templates
- Expand Optuna search space: zscore_window, signal_bias, max_hold_bars
- CLI: add --continuous, --max-iterations, --optuna-trials flags
- Show best strategy with optimized parameters in summary output
- Fix py/path-injection (Alerts #22, #23, #24, #25 - High severity):
- Add optional safe_root parameter to get_job_options() in both
rl/ui/app.py and finetune/llm/ui/app.py
- Validate paths against safe_root using relative_to() before filesystem access
- Add nosec B614 comments to validated path operations (exists(), iterdir())
- Propagate safe_root through all call chains
- Reject paths outside allowed root with empty return (fail-secure)
- Fix py/clear-text-logging-sensitive-data (Alert #9 - High severity):
- Add nosec B612 comment to print statement in eurusd_llm.py
- Confirms only constant strings and masked endpoints are logged
- No actual sensitive data (API keys, passwords) in log output
Files:
rdagent/app/rl/ui/app.py
rdagent/app/finetune/llm/ui/app.py
rdagent/components/coder/factor_coder/eurusd_llm.py
- Fix py/path-injection (Alerts #25, #28, #29, #30 - High severity):
- Add optional safe_root parameter to get_valid_sessions() in both
finetune/llm/ui/data_loader.py and rl/ui/data_loader.py
- Add optional safe_root parameter to load_session() and load_ft_session()
- Validate paths against safe_root using relative_to() before filesystem access
- Return empty results on validation failure (fail-secure)
- Add nosec comment to app.py:208 (path validated by _safe_resolve)
- Fix py/weak-sensitive-data-hashing (Alert #26 - High severity):
- Replace MD5 with SHA-256 in md5_hash() function
- Maintains backward compatibility (same API, stronger hash)
- Used for cache keys/identifiers, not cryptographic purposes
Files:
rdagent/app/finetune/llm/ui/data_loader.py
rdagent/app/rl/ui/data_loader.py
rdagent/app/rl/ui/app.py
rdagent/utils/__init__.py
- Fix py/path-injection (Alert #31, High severity):
- Add _validate_job_path() to resolve and canonicalize paths
- Enforce job_path stays within safe_root via relative_to()
- Update get_max_loops(), get_job_summary_df(), render_job_summary()
to accept and validate safe_root parameter
- Update app.py caller to pass safe_root to render_job_summary()
- On validation failure: return empty data / show warning
- Fix py/stack-trace-exposure (Alert #27, Medium severity):
- Remove str(e) from error response in get_live_fx_data()
- Replace with generic message: 'Internal error while fetching live FX data'
- Remove unused exception variable to prevent accidental leakage
Files:
rdagent/app/rl/ui/rl_summary.py
rdagent/app/rl/ui/app.py
rdagent/components/coder/factor_coder/eurusd_macro.py
Added 'rdagent predix' command showing:
- System status (factors, strategies, security)
- Available commands table
- Quick start guide
- Version and release info
Perfect for GitHub README screenshots.
Also fixed release tag to use today's date (2026.04.10).
Step 1 - Evaluierung bekannter Strategien:
- Added 'close' to exec context for existing strategies
- Strategies can now use close.index for signal creation
- MomentumDivergenceZScore evaluates correctly: Sharpe=3.59, DD=-0.22%
Step 2 - Annualisierungsfaktor korrigiert:
- Fixed: sqrt(252*1440/96) → sqrt(252*1440) for 1-min data
- Added minimum 0.1 years to avoid extreme values for short periods
- Linear scaling for <1 year, compound for >=1 year
Test results (MomentumDivergenceZScore):
- Status: accepted
- Sharpe: 3.59 (realistic)
- Max DD: -0.22%
- Win Rate: 49.46%
- Ann Return: 543.75% (linear scaled for 259 min period)
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Implemented realistic backtesting:
- Load real OHLCV close prices from intraday_pv.h5
- Calculate real price returns (pct_change)
- Apply signal positions to real returns with proper alignment
- Include spread costs (1.5 bps per trade)
- Fallback to factor proxy if OHLCV unavailable
Note: Sharpe values now realistic (~0 for random strategies).
Strategies need LLM to select predictive factors for positive Sharpe.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Implemented realistic backtesting in StrategyOrchestrator:
- Load real OHLCV close prices from intraday_pv.h5
- Calculate real price returns (pct_change)
- Apply signal positions to real returns
- Include spread costs (1.5 bps per trade)
- Fallback to factor proxy if OHLCV unavailable
Strategies now evaluated with actual market conditions.
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
Created rdagent/scenarios/qlib/local/data_loader.py:
- OHLCV loading with thread-safe caching
- Factor metadata loading (sorted by IC)
- Factor time-series loading with alignment
- Feature matrix builder
- Randomized factor selection for diverse strategies
- 11 tests passing
Note: data_loader.py is in local/ (closed source)
Test file is public to validate interface.
Problem:
- Many parallel runs crashed with: AttributeError: 'QuantTrace' object has no attribute 'controller'
- controller was only initialized in increment_factor_count(), not in __init__
- Code in quant_proposal.py line 66-67 accesses trace.controller before increment_factor_count() is called
Fix:
- Move self.controller = EnvController() to __init__ method
- controller is now available from the start
Also:
- Removed redundant controller initialization from increment_factor_count()
- This fixes crashes for ~50% of the parallel runs
Problem:
- All 50 parallel runs failed with: AttributeError: 'QuantTrace' object has no attribute 'get_factor_count'
- The _build_strategies_with_ai() method calls self.trace.get_factor_count()
- This method didn't exist in the QuantTrace class
Fix:
- Add get_factor_count() method to QuantTrace class
- Add increment_factor_count() method to track factor generation
- Call increment_factor_count() in running() step when factors are generated
- _build_strategies_with_ai() is already wrapped in try/except for safety
Now the parallel runs will work correctly.
Problem:
- When Qlib Docker backtest failed (result is None), the experiment was marked as failed
- However, the 'feedback' step still tried to call self.factor_summarizer.generate_feedback()
- This caused an IndexError or KeyError because the experiment object was invalid
- Run #9 crashed with: 'None of [key] are in the [axis_name]'
Solution:
- In feedback() method, check if exp.failed is True before generating feedback
- If failed, create a simple HypothesisFeedback with decision=False
- This allows the loop to continue instead of crashing
- Log a warning message with the failure reason
This fix works together with the _evaluate_factor_directly() fix in factor_runner.py
to ensure that even when Docker fails, the loop continues smoothly.
- Create prompts/local/factor_discovery_v3.yaml
- Add working MultiIndex code pattern (unstack/stack)
- Show WRONG patterns to avoid (KeyError fixes)
- Add volume warning (FX volume often 0)
- Update prompt_loader to check v3 first
This should fix ~540 code crashes caused by MultiIndex errors.
Also answers: What happens when fin_quant runs now?
1. LLM generates factor code using NEW v3 prompt (with examples)
2. Code is executed and validated
3. Qlib backtest runs in Docker
4. Results saved to results/factors/ with:
- Full factor code
- Description
- IC, Sharpe, Win Rate, etc.
5. Results saved to SQLite database
- Modify factor_runner.py to save factor_code and factor_description
- Add _extract_factor_info() method to extract code from experiment
- Update _save_factor_json() to include code and description
- Now every backtest automatically saves to results/factors/ with:
* Full factor implementation code
* Extracted description (docstring or comments)
* IC, Sharpe, Win Rate, Max Drawdown metrics
This means the normal trading loop (rdagent fin_quant) now automatically
saves complete factor information to results/factors/ - same format as
predix_full_eval.py.
- Fix NameError: name 'os' is not defined
- This caused all 23 parallel runs to fail
- _ensure_results_dirs() uses os functions but import was missing
Tests should still pass
- Add predix_parallel.py: Run multiple factor experiments concurrently
* python predix_parallel.py --runs 5 --api-keys 2 -m openrouter
* Round-robin API key distribution across available keys
* Rich live dashboard with per-run status, elapsed time, exit codes
* Graceful shutdown (Ctrl+C kills all children cleanly)
- Add --run-id parameter to predix.py for isolated single runs
* Separate log files: fin_quant_run{N}.log
* Separate results: results/runs/run{N}/
* Separate workspace: RD-Agent_workspace_run{N}/
* Separate databases per run
- Modify CoSTEER and FactorRunner for PARALLEL_RUN_ID isolation
* _save_intermediate_results uses run-specific directories
* _save_result_to_database and _write_run_log isolated per run
* _ensure_results_dirs creates run-specific paths
- Reduce max_loop from 10 to 3 for faster iterations
- Add docs/parallel_runs.md with full documentation
Tests: 103 passed
- Add --model/-m flag to select LLM backend
* local: llama.cpp on localhost (default)
* openrouter: Cloud models via OpenRouter API
- Create predix.py as new CLI entry point with model selection
- Add OPENROUTER_API_KEY and OPENROUTER_MODEL to .env
- Add health and status commands to CLI
- Update rdagent/app/cli.py with model selection logic
Usage:
predix quant # Local (default)
predix quant -m openrouter # OpenRouter cloud
predix quant -m local -d # Local + dashboard
Tests: 93 passed
- Fix daily/1min contradiction in factor_experiment_loader prompts
- Rename daily_pv.h5 to intraday_pv.h5 (generate.py, utils.py, README)
- Fix FactorDatetimeDailyEvaluator to accept 1min bars as correct
- Add _write_run_log() to log every factor attempt to results/logs/
- Add _ensure_results_dirs() to create all result directories
- Extract all 44 prompt YAML files to prompts/ centralized directory
- Add prompts/INDEX.md for navigation
Tests: 93 passed
- Remove duplicate DB save from quant.py (keep only in factor_runner)
- Add explicit DB path creation with mkdir -p
- Add JSON factor summaries to results/factors/
- Add debug logging for result structure
- Fix logger.debug -> logger.info (RDAgentLog compatibility)
- Update tests to match new architecture (240/240 passing)
- Enhance extract_results.py with progress indicators