* update rdagent cmd
* fix log error message
* use multiProcessing.Process instead of subprocess.Popen
* add traces to gitignore
* add user interactor in RDLoop (finance scenarios)
* add interactor (feedback, hypothesis) for quant scens
* fix the test_end in qlib conf
* add features init config, general instruction to qlib scenarios
* set base features for based exp
* fix bug when combine factors
* move traces folder to git_ignore_folder
* fix bug in features init
* fix quant interact bug
* fix logger warning error
* bug fixes
* modify rdagent logger, now it can set file output
* adjust cli functions and fix logger bug
* fix server port transport problem
* update server_ui in cli
* add web code
* fix CI problem
* black fix
* update web ui README
* update README
* update readme
* feat: rdkit for chemcotbench
* update qwen2.5&llama3.1 context
* fix: force failure on validation error and remove try/except in validator
* feat: unified error sample extraction (with test scripts)
* feat: set conda cache with .env
* feat: skip data eval if data pass in last evo
* fix: rm redundant param
* fix ui bug
* refactor: centralize assign_code_list_to_evo in MultiProcessEvolvingStrategy
* feat: add test_params.yaml generation and workspace cleanup improvements for finetune
* refactor: replace get_clear_ws_cmd with clear_workspace and update prompts for hard check criteria
* add bioprobench dataset
* fix: handle commas in training config extraction and refactor prompt includes
* bioprobench description
* add bioprobench readme
* feat: merge lora adapter for blackwell gpu
* feat: support for multi benchmarks in one job
* change dfficult aware content for training
* update difficulty-aware and logging principles
* fix: resolve variable name conflict in FTRunnerEvaluator
* set job id accuracy to minute
* feat(ui): display one selected metric per benchmark
* feat: store sota exp, and fix ws_ckp bug
* fix: truncate data.json in feedback
* fix: opencompass data for conda env
* fix: save only the last model
* feat: set log path and ws path
* fix: set overwrite_cache to avoid lock contention(through injecting params)
* feat: redirect stdout to file in localenv
* add pickle cache to dataset desc
* fix CI
* fix: remove redundant wrapper
* feat: set python_unbuffered
* move redirect stdout to env run
* fix a small bug
* move model folder
* feat(ui): display benchmark baseline
* fix: enrich scenario and benchmark description
* fix: rewrite runner eval to accept easier
* feat: compare with baseline when no SOTA
* update tablebench readme
* fix: switch back to single benchmark (for baseline)
* feat(ui): add ws path in ui
* refactor: update SOTA tracking to use DAG traversal and parent selection
* fix: prioritize local_selection in trace and refactor sibling retrieval logic
* refactor: unify error handling in feedback generation and update workspace injection
* feat: add skip_loop_error_stepname to control error skip step in LoopBase
* fix: set local_selection to NEW_ROOT for experiments without parent
* feat: set different ports for jobs
* feat: set different ports for jobs
* feat: add upper data size limit for LLM fine-tuning and update related prompts
* fix: replace get_truncated_stdout() with stdout for consistent output handling
* refactor: remove data.json from cache and workspace logic, focus on script-based reuse
* fix: rm target_scenario
* feat: add selective cache extraction and custom cache key for data processing
* fix(ui): bug when displaying tablebench
* fix: filter config in dataset_info.json
* feat: add test set, set valid set
* feat(ui): update test score, and set color for final decision
* feat: add test score for baseline and update ui
* fix: use [-100:] as test range
* feat: update data_stats in runner
* feat: wait for opencompass init when run multi jobs
* fix: adjust test&valid split
* feat: force to generate COT(with <think> token), and add answer format in scenarios.json
* feat: improve ui
* fix: unify benchmark volume mounts and set extra_volumes for conda env
* fix(ui): number color
* fix: update GPU memory handling to use total memory in GB and streamline code
* fix: set use_cot_postprocessor
* feat: add env_dict to config classes and merge env vars in Env run
* fix: let coder obey proposal
* fix(ui): direction bug and update chemcot core metirc
* fix: set consistent benchmark mount points and env vars for docker and conda
* fix: addintional target for LoRA
* feat: workspace dir log for benchmark running
* fix: tableInstruct path bug and update benchmark description
* feat: timeout for whole job
* fix: align FinanceIQ import to opencompass
* feat: use llm_judge for FinanceIQ
* feat: switch to turn on <think> or not
* feat: using scripts to redirect stdout, and run in different windows
* feat: sync litellm log
* fix: gpu memory format
* fix: escape special characters in benchmark desc
* fix: set data processing timeout to 1h
* feat: set valid_loss and save_best_model
* fix: inject timeout and stage
* fix: loss history extract logic
* feat: inject output dir
* feat: inject eval batch size
* feat: inject save_total_limit
* feat: update data prompt
* fix: escape shell special characters
* fix: tablebench visualization UI
* fix: move implementation validation to coder, and ignore injected params
* docs: add README for RL-PostTraining evaluation system
* Add AutoRL-Bench evaluation framework for RL post-training
* Add architecture documentation
* docs: update architecture and interface documentation for AutoRL-Bench
* improve doc
* fix
* refactor: YAML配置驱动
* feat: add RL Docker env, workspace test, and update project structure
* feat: 重命名 autorl_bench, 新增 RLWorkspace, 配置 Docker extra_volumes
* Add eval-only AutoRL-Bench pipeline
* sturcture clean
* docs: add autorl_bench README
* feat(rl): Implement RL post-training agent scaffold and example
* refactor: simplify RL scenario classes and update RL CoSTEER integration
* feat(rl): 调通 scaffold,mock 数据跑完 5 步循环
* feat(rl): 接入 LLM 生成代码,支持 model_path 传递
* feat(rl): Docker 执行框架,RLWorkspace.run() + RLPostTrainingRunner
* feat(rl): LLM 生成假设/反馈,完整 loop 跑通
* feat: add RL post-training entry point with configurable options
* refactor: simplify RL proposal and trace classes, update config and docs
* Update rl eval autorl_bench layout
* Update RL workflow and evaluation setup
* Integrate AutoRL-Bench evaluation in RL workflow
* feat(rl): 添加 --base-model/--benchmark CLI 参数,简化 RLTask
* feat(rl): Docker 环境动态选择 + example_agent 完整训练评测流程(无llm)
* fix(rl): 修复 feedback 传递 + 添加 verl 依赖
* refactor: remove unused validate in BenchmarkAdapter and add core utils module
* feat(rl): UI
* Refactor autorl_bench layout and docker entrypoint
* autorl_bench: add aider autoloop tool
* feat(rl): environment docker
* refactor: simplify aider autoloop tooling
* chore: update misc files
* feat(rl): yaml-driven dataset download & auto-download on startup
* feat(rl): yaml-driven dataset download & auto-download on startup
* Refactor RL eval runner and clean up
* Simplify RL eval runner and env
* rl: include litellm in RL docker image
* feat(rl): unified resource path & model repo_id structure
* feat(rl): refactor eval with OpenCompass & add training code template
* feat(rl): refactor eval with OpenCompass & add training code template
* feat(rl): delete test bench
* docs: add benchmark interface notes and TODOs for unified evaluation
* feat(rl): unified benchmark eval interface + shared configs
* feat(rl): 优雅
* feat(rl): prompt prososal+coder improve
* feat(rl): fix eval
* fix(rl): docker
* fix(rl): eval
* v 1.0 tmep
* benchmark v1.0
* benchmark v1.1
* benchmark v1.1: grading日志+代码去重
* benchmark v1.1: grading日志+代码去重
* benchmark v1.1: grading日志+代码去重+task description
* benchmark v1.2: fix
* benchmark v1.3: fix,example-agent ok,rdagent test,openhands develop
* benchmark v1.4: fix,example-agent ok,rdagent ok,openhands develop
* benchmark : add alfworld
* benchmark : update readme
* benchmark : update readme
* benchmark :
* chore: add eval bypass block and mark TODO in grading server
* benchmark
* benchmark
* benchmark
* benchmark
* alfworld
* alfworld
* benchmark
* rdagent
* rdagent
* benchmark
* benchmark:ui
* benchmark:delete docker + log
* 1
* alfworld
* ui
* alfworld
* readme
* alfworld
* parallex
* alfworld
* run
* eval gpu
* alfworld
* alfworld
* fix conda init in start.sh for non-interactive shells
Fallback to common miniconda paths when conda is not in PATH.
Fixes B200 pod startup failure (conda: command not found).
Made-with: Cursor
* simplify start.sh: read TRAINING_PYTHON from .env
No more conda detection logic. Just set TRAINING_PYTHON in .env.
Fallback to conda only if not set.
Made-with: Cursor
* use OPENHANDS_PYTHON from .env to run agent
start.sh now uses OPENHANDS_PYTHON for main.py execution,
since the parent process may be in a different conda env.
Made-with: Cursor
* feat: register OpenCode agent into autorl_bench framework
- Add agents/opencode/ with config.yaml, start.sh, README.md
- Include opencode-rl pipeline code (pipeline/, runner_fsm/, benchmarks/)
- Merge opencode-rl dependencies into autorl_bench requirements.txt
- Remove separate venv requirement, share main environment
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Update opencode agent, benchmarks, and eval configs
- Sync opencode-rl runner_fsm with latest simplifications
- Add smith benchmarks integration
- Update opencompass configs and server with GPU support + error handling
* Update OpenCode agent docs for external opencode-rl integration
- Document external repo architecture (opencode-rl as independent plugin)
- Add setup instructions for cloning and configuring opencode-rl
- Add architecture diagram showing RD-Agent ↔ opencode-rl interaction
- Document OPENCODE_RL_ROOT for custom paths
* feat: add smith benchmark discovery and per-sample evaluator
- Add smith/ module for dynamic benchmark discovery from rl-smith
- Add PerSampleEvaluator for per-sample scoring via vLLM
- Update utils.py to support script-based data download for smith benchmarks
- Update opencode agent config
* enforce RL-only in instructions.md; remove embedded opencode-rl
- instructions.md: prohibit SFT, require RL (GRPO/PPO) for all benchmarks
- remove agents/opencode/opencode-rl/ (runtime uses external OPENCODE_RL_ROOT)
Made-with: Cursor
* comment out OpenCode-only deps in requirements.txt
openai, httpx, python-dotenv, tenacity are for OpenCode agent's
separate environment. Keep peft and pydantic as shared deps.
Made-with: Cursor
* refactor: extract _kill_process_group, narrow exception catches
- run.py: replace 2x nested 3-level try/except with shared
_kill_process_group() using loop + specific exceptions
- server.py: except Exception → except (RuntimeError, ValueError, OSError)
- utils.py: except Exception → except requests.ConnectionError
Made-with: Cursor
* move kill_process_group to core/utils for reuse
Extract from run.py into core/utils.py so other runners
can also use it. Exported via core/__init__.py.
Made-with: Cursor
* add comments to run.py for workspace isolation and signal handling
Made-with: Cursor
* remove OpenCode-only deps from requirements.txt entirely
Made-with: Cursor
* allow SFT in instructions, RL as ultimate goal
Made-with: Cursor
* add workspace isolation rules to instructions.md
Use relative paths, forbid cd outside workspace, ignore symlink targets.
Made-with: Cursor
* update opencode start.sh: use OPENCODE_PYTHON, add PATH for opencode CLI, remove unsupported args
Made-with: Cursor
* opencode start.sh: pass --run-dir to use AutoRL-Bench workspace
Ensures OpenCode-FSM-Runner writes outputs into the workspace prepared
by AutoRL-Bench instead of creating its own runs/ directory.
Made-with: Cursor
* opencode start.sh: prepend training env bin to PATH
Ensures LLM agent bash calls (e.g. python3 -c "from trl import ...")
resolve to the correct training environment, instead of relying on
parent shell conda activation.
Made-with: Cursor
* opencode start.sh: restore --max-retries and --eval-timeout for opencode-rl
Made-with: Cursor
* add humaneval benchmark
* Replace import * cleanup hack with explicit imports in OpenCompass config
- Resolve dataset variable names via importlib before generating config,
so the template uses `from xxx import datasets` instead of `import *`
- Remove the fragile runtime cleanup hack that set leaked modules to None
- Increase OpenCompass timeout from 3600s to 7200s
- Fix score parsing to average across multiple subdatasets
* refine opencompass config file generating
* add humaneval benchmark dependency instructions
human-eval package requires clone from open-compass/human-eval with
a one-line patch to relax assertion for partial evaluation (test split only).
Made-with: Cursor
* fix: sanitize user-provided paths in RL UI (CodeQL)
* fix: resolve user path relative to safe root (CodeQL)
* fix: use Copilot-suggested path sanitization pattern (CodeQL)
* fix: normalize and reject absolute user paths (CodeQL)
* Fix training params, vLLM OOM cleanup, OpenCompass score parsing, and baseline cache logic
* fix: add setuptools<75 to requirements for opencompass pkg_resources dependency
uv venv does not include setuptools by default, causing OpenCompass baseline
evaluation to fail with "No module named 'pkg_resources'".
Made-with: Cursor
* webshop
* feat(autorl_bench): improve smith benchmark integration and evaluator robustness
- Add smith benchmark docs to README: usage examples, discovery mechanism, SMITH_BENCH_DIR
- Improve PerSampleEvaluator: vLLM GPU cleanup, test_range slicing
- Refactor server.py: extract grading server from utils
- Fix OpenCompass score parsing and baseline cache logic
* fix: add smart fallback for OpenCompass dataset variable resolution
When build_dataset_imports_explicit() fails to import an OpenCompass
dataset module (common in grading server subprocess), it now guesses
the correct variable name from the module path convention instead of
falling back to empty names (which causes import * and breaks BBH
due to leaked file handle objects).
* revert: restore opencompass.py to pre-modification state
Revert vLLM pid cleanup, dash-value checks, and metric-based
score parsing added in 31caff2f and bb32e555.
* keep metric-aware score parsing in opencompass; add baseline column to UI
- opencompass.py: retain metric-type filtering (accuracy/score) instead
of naive averaging, avoids polluting scores with pass/timeout counters
- ui.py: add Baseline column to Agent Summary table
Made-with: Cursor
* fix: handle non-string answers in extract_answer to prevent TypeError
arc_agi and other benchmarks can have non-string answer fields (e.g. lists),
which caused a crash in re.search(). Adding str() coercion fixes this.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update deepsearch qa tasks
* fix: benchmark evaluation reliability (B1-B4)
- B1: auto-detect LoRA adapters and enable vLLM LoRA mode (read base_model from adapter_config.json)
- B2: serialize evaluations with threading.Lock to prevent GPU contention
- B3: cache eval results by model_path to deduplicate concurrent submissions
- B4: propagate error details from OpenCompass to agent (non-numeric scores, load failures)
Made-with: Cursor
* fix(B1): reject LoRA adapter submissions with clear merge instructions
- opencompass.py: detect adapter_config.json and return error with
merge_and_unload() instructions instead of broken vLLM LoRA mode
- instructions.md: add requirement to submit full merged models
- opencompass_template.yaml: remove unused is_lora/lora_path params
Made-with: Cursor
* update chat completion
* update
* update deepsearch
* md
* codex + benchmark update
* codex + benchmark update
* codex + benchmark update
* codex
* codex
* fix: grading server cache key includes mtime to detect model overwrites
Previously cache used only resolved_path, so overwritten models at the
same path returned stale scores. Now cache key = path@max_mtime so
re-evaluation is triggered when model files change.
Made-with: Cursor
* feat: add gemini/claude agent scaffolds, fix codex binary path
- codex/start.sh: use CODEX_BIN env var instead of bare 'codex'
- Add gemini/ and claude/ agent directories with config.yaml and start.sh
Made-with: Cursor
* chore: remove copied human_readable_trace.py from PostTrainBench
Made-with: Cursor
* update evaluation
* benchmark
* Fix log cleanup and OpenHands env
* fix: webshop env pth problem
* benchmark alpacaeval
* style(rl): apply auto-lint fixes
* fix(rl): address CI and CodeQL issues
* fix(rl): make autorl bench imports CI-safe
---------
Co-authored-by: Qizheng Li <jenssenlee@163.com>
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
Co-authored-by: chelsea97 <zhuowbrown@gmail.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: sakura657 <yctangcse@gmail.com>
Co-authored-by: shatianming5 <tianming.sha@stonybrook.edu>
Co-authored-by: Yeyuqing0913 <shatianming4@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* refine prompt
* small update
* fix a small bug
* remove debug config after execution
* fix: only remove <think> at start
* feat: support creating dataset & multi-eval frame (#1302)
* feat: add iterative evolve and evaluation support with partial chain stop
* feat: add FTDataEvaluator and support multiple implement functions in finetune
* feat: data implement for pre-proposal and proposal and add datasets (#1303)
* feat:(1) support for multi layer dataset extraction (2) add category.json for dataset in datasets/
* fix: fix bug for generate category.json
* feat: add get_dataset_folder_desc
* init data proposal and merge qzli/ft
* update data proposal prompts and add max_position_embeddings and resolve confilcts
* remove sample counts in data proposal
* turn data and train to unified hypo_gen
* refine prompts
* remove category.json and add it to dataset_info
* fix jinja problem and proposal done
* lint
* add ai-generated description and raw readme into dataset_info.json
* update prompt for description
* add datasets
* initial fix for proposal of data
* final version for data proposal
* lint
* feat: add stats in dataset_info, and enable data coder (#1306)
* refactor(dataset): add stats into dataset_info.json, and remove dataset from gitignore_folder
* feat: enable data coder and run data process
* feat: Merge data coder (#1307)
* feat: implement finetune data coding, evaluation, and config improvements
* fix: deepspeed config path
* fix: dataset info columns
---------
Co-authored-by: Young <afe.young@gmail.com>
* replace str length with token_limit
* add readme to dataset_info and remove useless blank lines in scenario description
* feat: dataset prepare
* fix: extract prams script name
* feat: add loss&predictions samples to feedback
* remove duplicate envs and and add llm_api_preferences and enhance reasoning token limits
* feat: network for ft_env
* fix: remove gpt-4o, which has low quota
* feat: a simple ui
* feat: merge data and train task type (#1309)
* feat: filter redundant prams of lf
* fix: ui bug caused by removing task_type
* fix: force agent to use high concurrency, and remove redundant prompt
* feat: extract info from llama factory log, and check data exists before download
* fix: add compatibility rules
* feat: llm evaluator for data coder
* feat: openai package in ft docker, and refine prompt
* feat: refine ft ui, add more info
* feat: add raw logs
* refine data coder prompt(for feedback debug)
* feat: select dataset in scen init
* fix: ui for docker log seperately
* feat: sync log through blob
* improve ui, and add llm feedback in Runner&Exp2FB (#1312)
* fix: ui bug to visualize docker log, and lint
* feat: unified docker log for ft env, and some refactor
* fix bugs and improve ui
* feat: save log of evaluator(single feedback)
* feat: add evaluator, set cleanup docker log
* feat: call llm in RunnerEvaluator and Feedback
* fix: extract structured error message in RunnerEvaluator
* feat: feedback improve, and fix some bugs
* feat: feedback improve when runner fails
* small update
* feat(UI): add running info and benchmark metric in loop expander
* feat(UI): add render markdown toggle
* feat: refine prompts and add error type in exp2fb
* feat: add filterd params reason, set default benchmark timeout to infinite, and refine train loss express
* recover dataset deepscaler
* feat: set timeout in .env
* refactor: unifiied ft_env timeout
* feat: debug mode for data coder
* feat: deliver data_stats after generate debug_data
* feat: use gpt-5.1 as judge model, set judge_retry, and refine debug mode prompt
* refine prompt
* refactor: llama factory manager logic, and refine data processing prompt
* feat(DockerEnv): support GPU selection via CUDA_VISIBLE_DEVICES
* feat: set api concurrency via .env
* fix: ft env timeout bug
* feat: enable CondaEnv run
* fix: can't update bin path in first run, and path bug in lf manager
* feat(ui): set log path through .env
* refactor(ui): wrap_lines, remove css
* feat(coder): retry when parse code-block fail
* fix: refine single-fb in ui, and fix path bug(not allow proposal to decide path)
* fix: opencompass CondaEnv torch compatible with vllm
* fix: refine error text in coding
* feat: deepspeed config for CondaEnv
* feat: memory estimator
* fix: deepspeed package for condaenv
* fix: use `client.chat.completions.create()` only
* feat: flash attention for condaenv
* feat: strong and weak models interface
* fix: condaenv package dependency
* use multi round conversation in llm finetune proposal
* refine prompt for data processing
* enable evolving in data coder
* maximize output token size
* fix: refine ui
* fix: optional packages for llama factory
* fix: torch denpendency for b200
* fix: opencompass dependency
* update cot prompts
* skip the sub implement
* skip conda preparation if env exists
* update chemcot datasets
* fix: unify docker to use litellm
* update readme and instructions
* fix: set CUDA_VISIBLE_DEVICES for CondaEnv
* feat: add panorama dataset, refactor dataset interface
* feat: calculate token using tiktoken, and ndarray bug
* fix: download subtasks of chemcotdataset seperately
* feat: customized prepare func for datasets
* feat: update new benchmarks
* add datasets package
* docs: readme for llm finetune
* feat: download raw data directly, with post-process function
* feat: analyze raw dataset
* suppress litellm debug info
* feat(ui): summary page
* feat: run multi-jobs
* feat: improve ui
* feat: add path and checkout options to LLM finetune loop entrypoint
* feat: add FinanceIQ_ppl benchmark with auto-download and dataset desc rendering
* refactor: remove unused imports and dead code, fix session folder logging
* feat: enable tablebench and tableInstruct dataset
* refine dataset readme, and coder prompt
* refine proposal and coder prompt
* fix: ui path (default log path)
* feat: add automatic LoRA model merging for benchmarking with vLLM
* refactor: reorganize finetune benchmark and merge modules under benchmark dir
* refactor: modularize benchmark config and error extraction for finetune scenario
* fix: update benchmark import paths and disable env cache for device info
* refactor docke&conda env and fix import bugs
* modify init python file
* feat: add FinanceIQ dataset split utility and integrate with pipeline
* feat: set weak and strong model by env, distribute workload across models
* feat: sample dataset and rm params for tensorboard, wandb
* update script to run jobs
* refine proposal prompt, remove specific dataset name
* fix(ui): auto switch log folder
* fix: estimate the processed full data after sample
* feat: filter raw data more aggressively, and lower data_eval standard
* feat: sync workspace to blob
* feat: rdkit for chemcotbench
* update qwen2.5&llama3.1 context
* fix: force failure on validation error and remove try/except in validator
* feat: unified error sample extraction (with test scripts)
* feat: set conda cache with .env
* feat: skip data eval if data pass in last evo
* fix: rm redundant param
* fix ui bug
* refactor: centralize assign_code_list_to_evo in MultiProcessEvolvingStrategy
* feat: add test_params.yaml generation and workspace cleanup improvements for finetune
* refactor: replace get_clear_ws_cmd with clear_workspace and update prompts for hard check criteria
* add bioprobench dataset
* fix: handle commas in training config extraction and refactor prompt includes
* bioprobench description
* add bioprobench readme
* feat: merge lora adapter for blackwell gpu
* feat: support for multi benchmarks in one job
* change dfficult aware content for training
* update difficulty-aware and logging principles
* fix: resolve variable name conflict in FTRunnerEvaluator
* set job id accuracy to minute
* feat(ui): display one selected metric per benchmark
* feat: store sota exp, and fix ws_ckp bug
* fix: truncate data.json in feedback
* fix: opencompass data for conda env
* fix: save only the last model
* feat: set log path and ws path
* fix: set overwrite_cache to avoid lock contention(through injecting params)
* feat: redirect stdout to file in localenv
* add pickle cache to dataset desc
* fix CI
* fix: remove redundant wrapper
* feat: set python_unbuffered
* move redirect stdout to env run
* fix a small bug
* move model folder
* feat(ui): display benchmark baseline
* fix: enrich scenario and benchmark description
* fix: rewrite runner eval to accept easier
* feat: compare with baseline when no SOTA
* update tablebench readme
* fix: switch back to single benchmark (for baseline)
* feat(ui): add ws path in ui
* refactor: update SOTA tracking to use DAG traversal and parent selection
* fix: prioritize local_selection in trace and refactor sibling retrieval logic
* refactor: unify error handling in feedback generation and update workspace injection
* feat: add skip_loop_error_stepname to control error skip step in LoopBase
* fix: set local_selection to NEW_ROOT for experiments without parent
* feat: set different ports for jobs
* feat: set different ports for jobs
* feat: add upper data size limit for LLM fine-tuning and update related prompts
* fix: replace get_truncated_stdout() with stdout for consistent output handling
* refactor: remove data.json from cache and workspace logic, focus on script-based reuse
* fix: rm target_scenario
* feat: add selective cache extraction and custom cache key for data processing
* fix(ui): bug when displaying tablebench
* fix: filter config in dataset_info.json
* feat: add test set, set valid set
* feat(ui): update test score, and set color for final decision
* feat: add test score for baseline and update ui
* fix: use [-100:] as test range
* feat: update data_stats in runner
* feat: wait for opencompass init when run multi jobs
* fix: adjust test&valid split
* feat: force to generate COT(with <think> token), and add answer format in scenarios.json
* feat: improve ui
* fix: unify benchmark volume mounts and set extra_volumes for conda env
* fix(ui): number color
* fix: update GPU memory handling to use total memory in GB and streamline code
* fix: set use_cot_postprocessor
* feat: add env_dict to config classes and merge env vars in Env run
* fix: let coder obey proposal
* fix(ui): direction bug and update chemcot core metirc
* fix: set consistent benchmark mount points and env vars for docker and conda
* fix: addintional target for LoRA
* feat: workspace dir log for benchmark running
* fix: tableInstruct path bug and update benchmark description
* feat: timeout for whole job
* fix: align FinanceIQ import to opencompass
* feat: use llm_judge for FinanceIQ
* feat: switch to turn on <think> or not
* feat: using scripts to redirect stdout, and run in different windows
* feat: sync litellm log
* fix: gpu memory format
* fix: escape special characters in benchmark desc
* fix: set data processing timeout to 1h
* feat: set valid_loss and save_best_model
* fix: inject timeout and stage
* fix: loss history extract logic
* feat: inject output dir
* feat: inject eval batch size
* feat: inject save_total_limit
* feat: update data prompt
* fix: escape shell special characters
* fix: tablebench visualization UI
* fix: move implementation validation to coder, and ignore injected params
* feat: README for FinanceIQ dataset
* fix: bioprobench desc error
* fix: remove task alignment when coder eval
* fix: FinanceIQ now extracts last capital as answer
* fix: stdout contains binary data
* feat: recover estimate full output and set eval setting automatically
* fix(ui): precision for summary table
* fix(ui): import error
* feat: try to use lora
* fix(api): fix litellm bug for code block
* fix: refine prompts to give agent more decision space
* chore(ci): fix mypy typing issues
* chore(ci): format code with black
* chore(ci): fix ruff lint violations
* chore(ci): sort imports with isort
* chore(ci): format code with black
* test: temporarily skip extract_parameters imports due to numpy pin
* fix: compatibility issues for qlib scenarios on finetune branch
* fix(fin_factor): skip to fb for coder error
* fix(loop): default skip to feedback step on skip_loop_error
When skip_loop_error exception happens and skip_loop_error_stepname is not
explicitly set, default to jumping to 'feedback' step if it exists,
otherwise fall back to the last step (record).
This prevents KeyError when record step tries to access feedback data that
doesn't exist because we skipped the feedback phase.
Also removed redundant skip_loop_error_stepname from finetune loop since
it's now the default behavior.
* add 'skip to record' to DS scenario like other scenarios
* fix 2 scenarios bug about rd_loop class
* fix: lint(mypy, ruff, black) error
* fix: mypy lint error
* fix data science scenario bug
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: Qizheng Li <jenssenlee@163.com>
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
Co-authored-by: amstrongzyf <201840057@smail.nju.edu.cn>
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: amstrongzyf <amstrongzyf@126.com>
Co-authored-by: chelsea97 <zhuowbrown@gmail.com>
Co-authored-by: SunsetWolf <Lv.Linlang@hotmail.com>
* fix: prevent calendar index overflow when signal data ends early
* fix: make test_end optional to resolve Qlib backtest calendar misalignment
* fix: enhance GPU information output in get_gpu_info function
* fix: improve GPU information output in get_gpu_info function for better clarity
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* refactor: unify qlib experiment configs, runners, and templates
* fix: use PropSetting instances instead of class attributes in qlib runners
* docs: add configurable train/valid/test time segments for fintech scenarios
* fix: refine task scheduling logic in MultiProcessEvolvingStrategy for improved handling of feedback in improve mode
* fix: add empty implementation for skipped tasks in MultiProcessEvolvingStrategy
* add simple rag mcp
* add rag_agent in expGen v2
* add conf config for research rag
* fix CI
* refactor: move context7 and rag config files to new conf modules
* make rag agent general
* fix CI
---------
Co-authored-by: Young <afe.young@gmail.com>
* feat: add interactor classes and user interaction handling for experiments
* update code
* use fragment retry mechanism instead of rerun()
* fix a bug
* integrate user instructions into proposal and coder
* fix CI
* fix CI
* feat: add approval option for user instructions submission
* feat: enhance user instructions handling in Task and DSExperiment classes
* fix CI
* add user instructions into hypothesis rewrite
* add interface to command line
---------
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
* chore: add medal info
* return sota_exp_stat
* update hit check
* update experiment
* udpate experiment
* extract log
* remove old log folder
* update candidates
* keep highest score
* early stop if no medal candidate
* refactor: use get_truncated_stdout for consistent stdout handling across modules
* lint
* feat: add dump_stdout_type to DSRunnerCoSTEERSettings and use in eval
* fix: avoid circular import by moving DSRunnerEvaluator import inside method
* fix: update fallback criterion
* fix: ensure evo_fb is initialized and used correctly in fallback logic
* refactor: rename use_new_evo to should_use_new_evo for clarity
* feat: add option to enable hyperparameter tuning only in first eval loop
* fix: use total_seconds() for accurate time calculations in evolution and tracking
* show a workspace path string for easier copy, only percent existing columns when percent summary dataframe
* catch summary exception
* fix a bug
* fix ci
* fix: enable embedding auto truncation
* move embedding_utils to utils.embedding
* fix bug
* fix(embedding): improve text truncation with retry strategies and binary search optimization
* new way for embedding truncate
* fix ci errors
* refine prompts and add additional package info
* refine prompts to be specific for GBDT models
* minor refine prompts
* use include to replace duplicate info
* refine prompts
* refactor: import DSTrace from base and remove exp_gen __init__
* lint
---------
Co-authored-by: Young <afe.young@gmail.com>
* change DSCoSTEER_eval prompts
* fallback to better exp only
* fix fallback
* fix and reformat
* fix bug when base_fb is None
* add reasoning to hyperparameter evaluation
* feat: add acceptable assessment in exp_feedback (#1159)
* add time
* refine eval prompt and make the logic of tuning check more clear
* some refinement
* fix CI
* fix a small bug, only consider score in runner
* refine comment
* simplify compare function
---------
Co-authored-by: jingyuanlm <842442862@qq.com>
Co-authored-by: Xu <v-xuminrui@microsoft.com>
Co-authored-by: Jensen Lee <91518020+Jensen246@users.noreply.github.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* feat: refactor CoSTEER classes to use DSCoSTEER and update max seconds handling
* remove useless line
* enable time_ratio_limit_to_enable_hyperparameter_tuning
* add scores.csv metric name in both task_gen and coder
* a little fix to column names
* small fix
* avoid sample submission read in task_gen
* avoid sample_submission reading in coding
* code change summary bug fix
* little update
* little refinement to eval
* refine coder and runner eval prompts
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* add prev loops to runner history
* fix evolving history
* fix bug on initializing feedback without final decision
* reformat
* refine
* add comments
* fix ci
* a little refinement
* fix CI
---------
Co-authored-by: Xu <v-xuminrui@microsoft.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* feat: add time ratio limit for hyperparameter tuning in Kaggle settings and update evaluator logic
* add recommend time limit
* remove 25% hard line
* small fix
* feat: introduce max_seconds_multiplier for timeout management across components
* avoid using assert in test
* hot fix a very small bug
* runner multiply twice
* revert feedback change
* add a switch to longer timeout
* implement runtime_env func for quant
* add runtime_info code
* add runtime env information to the prompt
* format with black
* optimize get_runtime_env code
* delete unnecessary files
* some refinement
* fix fin_quant bugs
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* update data science docs part1
* update data science docs part2
* update data science docs part3
* update data science docs part4
* update data science docs part5
* format with isort
* update data science docs part6
* add check environment scripts
* format with isort
* format with isort
* merge env_check to health_check
* format with isort
* format with black
* optimize code
* use boolean cli options
* replace fire with typer
* replace fire with typer
* optimizing parameter and variable naming
* change refine prompt for full code
* fix: fix the logic of running
* refine prompt
* fix some bugs
* fix
* add two guidelines
* refactor the code
* make costeer evaluator more logical
* refine eval prompt
* make costeer eval prompt markdown
* update code diff prompt
* correct pipeline
* feat: add apply_patch utility and update ret.py with patch functionality (#1071)
* restore to the right version
* fix the docstring
* fix extract_output fcn
* add inplace parameter to apply patch
* remove enable_runner_iteration and make the eval prompt same as main
* refine runner eval prompt based on main
* Update rdagent/scenarios/data_science/dev/runner/prompts.yaml
* add wait_retry
* refactor: move enable_runner_code_diff to DSRunnerCoSTEERSettings as diff_mode
* reformat and remove enable_runner_code_diff
---------
Co-authored-by: yuanteli <1957922024@qq.com>
Co-authored-by: Xu <v-xuminrui@microsoft.com>
Co-authored-by: Jensen Lee <91518020+Jensen246@users.noreply.github.com>
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
Co-authored-by: Qizheng Li <jenssenlee@163.com>
* Align scenario descriptions and include debug timeout
- Updated config.py to support debug timeout configuration
- Synchronized prompts in exp_gen and scen modules
- Refactored proposal.py for consistency with new scenario descriptions
- Improved __init__.py for better scenario management
* remove running time in stdout
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* fix: refine prompts formatting and logic across data science scenarios
* Make runner evaluator more detailed
* feat: switch to system_debugger prompt and print early stopping stats
* refactor: move exp_gen selection files into select directory
* fix selector value in data_science conf
* fix selector template name
* fix CI
---------
Co-authored-by: Young <afe.young@gmail.com>
* fix: improve scheduler API (suggest_sel) and add timer.remain_time()
* chore: exclude .venv from auto-black and auto-isort tasks
* refactor: wrap RoundRobinScheduler commit and selection in retry loop
* set search_type="ancestors" for experiment_and_feedback_list_after_init
* fix bug: no update of uncommited_rec_status with root node
---------
Co-authored-by: Young <afe.young@gmail.com>
* fix: fix a small bug in response_schema
* feat: support response_format parameter in chat completion
* fix: fix between json_mode and response_format
* Update base.py
* Update deprec.py
* add unittest and refine logic
* fix the reasoning extraction logic and refine prompt for deepseek adaptation
* refactor: introduce workflow_check and streamline task parsing
* refine prompt
---------
Co-authored-by: Young <afe.young@gmail.com>
* check sample submission & add package constraint
* add trace.log into clear
* change default
* simplify
* clear CI workspace before running
* move to CI
* use sudo to clean workspace
* move prepare out of global var
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* check the target file path is in a designed folder and make sure it's pdf
* Potential fix for code scanning alert no. 55: Uncontrolled data used in path expression
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
* Potential fix for code scanning alert no. 56: Uncontrolled data used in path expression
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
* continue improving
* Potential fix for code scanning alert no. 62: Uncontrolled data used in path expression
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
* apply secure_filename
* Potential fix for code scanning alert no. 64: Uncontrolled data used in path expression
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
* fix CI
---------
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* fix: improve scheduler API (suggest_sel) and add timer.remain_time()
* chore: exclude .venv from auto-black and auto-isort tasks
* refactor: wrap RoundRobinScheduler commit and selection in retry loop
* set search_type="ancestors" for experiment_and_feedback_list_after_init
* refactor: merge sync_dag_parent_and_hist and hist.append into one call
* fix uncommited rec bug
* lint
---------
Co-authored-by: xuangu-fang <xuangufang@gmail.com>
* init commit
* remove the 5-fold spec from prompts
* refine the hyperparameter specification
* do not sample data
* a small spelling issue
* refine prompt to avoid submission cheating
* do not sample data
* simplify code
* refine the coder evaluator prompt
* refine wording
* remove runtime from proposal
* refine wording
* refine prompt
* add gpu info in runtime_info.py
* modify the spec
* add router and add refinement exp gen
* fix prompt bug
* use rule-based logic for router
* complete the prompt
* fix circular import bug
* fix bug
* make refine_decision optional
* update pipeline prompts: (1) add scenary: in an iterative cooding loop and use sample datasets (2)add some generation tops in coding (3)add evaluation guidelines in evaluation (4)polish the json schema and description
* fix a small bug
* fix a small bug
* rdagent/scenarios/data_science/loop.py back to the original version
* refactor: replace _get_exp_gen with default_exp_gen for exp generation
* import
* refactor: make the __init__ back to main
* fix small bugs
* fix bugs for proposal_version
* move refine into runner
* check early stop
* EDA improvement & coder classes number
* fix CI
* slightly refine the prompt
* remove rule_base_eval and remove useless prompt
---------
Co-authored-by: Xu <v-xuminrui@microsoft.com>
Co-authored-by: TPLin22 <tplin2@163.com>
Co-authored-by: amstrongzyf <amstrongzyf@126.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
Co-authored-by: Young <afe.young@gmail.com>
* commit all code
* fix feedback bug
* add debug mode in ds
* update prompt
* prioritize performance than time lit
* use run instead
* store running time
* move all data running into running phase
* fix a bug
* use sample data as default
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* ui server update
* update
* fix bugs
* updates
* use randomname
* fix
* fix bugs
* change time interval in debug server
* some change
* fix CI
* time interval change
* updates
* some changes
* fix
* fix curves
* one IP, one pointers to show msgs return progress
* enable /control
* fix bugs
* fix CI
* fix isort
* feat: Enhance data folder description for clarity and robustness
* fix bug
* fix present bugs
* delete useless files
* add output example and refactor the hole util.py
* fix bug for file tree
* add corner case example
* delete useless file
* docs: document extra_volumes dict format in DockerConf
* feat: accept dict values in extra_volumes to specify bind and mode
* fix: skip invalid PDF reports to prevent infinite loop
* from break to raise self.LoopTerminationError
* format with black
---------
Co-authored-by: Young <afe.young@gmail.com>
* start to work on multi-trace + async
* init ver of async-multi-tarce, to test
* add eng-ver log
* complete version of async+ mul-trace
* debug
* fix bug on DS_RD_SETTING.get()
* update
* fix bug + simplif the usage of async in multi-trace
* fix mini bug of arg_name
* Move local_selection into class Experiment & clean the code
* add coder version
* merge cooder and feedback prompts
* align v2 and v3 proposal prompts
* fix a small bug
* fix a bug
* fix another bug
* support both function calling and json mode in v2 proposal
* fix minor bug
* reformat
* remove proposal v3
* fix a small bug in json mode
* fix CI
* remove tmp file
* remove v3 check
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* add custom data setting for the data science scene
* fix ci?
* fix ci
* add custom data as an example
* fix ci
* add package
* fix test_import ci error
* docs: update explanation for separate config use in litellm
* docs: update default backend to `rdagent.oai.backend.LiteLLMAPIBackend`
* docs: update .rst format
* Update installation_and_configuration.rst
* remove state.times in old ui
* remove "r" tag
* remove "d" tag
* remove "ef" tag
* remove "init" tag
* fix CI
* remove old tag in app UI
* fix bugs
* fix CI
* some updates
* filter tags
* feat: replace hard-coded cache paths with dynamic cache_path config
* style: reorder wait_retry import and format chmod list
* refactor: pass workspace_path to chmod command and use DockerConf check
* refactor: split workflow into pkg, add WorkflowTracker & wait_retry
* feat: add async LoopBase with parallel workers and step semaphores
* fix: replace pickle with dill and run blocking tasks via joblib wrapper
* feat: add log format settings, dynamic parallelism & pickle-based snapshot
* fix: default step semaphore to 1 and avoid subprocess when single worker
* merge bowen's changes
* merge tim's changes
* refactor: extract component task mapping, add conditional logger setup
* lint
* refactor: add type hints and safer remain_time metric logging in workflow
* lint
* fix: allow BadRequestError to be pickled via custom copyreg reducer
* fix: stop loop when LoopTerminationError is raised in LoopBase
* lint
* refactor: make log tag context-local using ContextVar for thread safety
* feat: add subproc_step flag and helper to decide subprocess execution
* fix: use ./cache path and normalize relative volume bind paths
* fix: reset loop_idx to 0 on loop restart/resume to ensure correct flow
* fix: avoid chmod on cache and input dirs in Env timeout wrapper
* fix: skip chmod on 'cache' and 'input' dirs using find -prune
* fix: restrict chmod to immediate mount dirs excluding cache/input
* fix: chmod cache and input dirs alongside their contents after entry run
* fix: guard chmod with directory checks for cache and input
* fix: prefix mount_path in chmod command for cache/input dirs
* fix: drop quotes from find exclude patterns to ensure chmod executes
* fix: skip chmod on cache/input directories to avoid warning spam
* feat: support string volume mappings and poll subprocess stdout/stderr
* support remove symbolic link
* test: use dynamic home path and code volume in LocalEnv local_simple
* fix: skip trace and progress update when loop step is withdrawn
* refactor: add clean_workspace util and non-destructive workspace backup
* fix: preserve symlinks when backing up workspace with copytree
* fix: prevent AttributeError when _pbar not yet initialized in LoopBase
* perf: replace shutil.copytree with rsync for faster workspace backup
* fix: cast log directory Path to str in tar command of data science loop
* fix: use portable 'cp -r -P' instead of rsync for workspace backup
* fix: add retry and logging to workspace backup for robustness
* refactor: extract backup_folder helper and reuse in DataScienceRDLoop
* fix: propagate backup errors & default _pbar getattr to avoid error
* fix the division by zero bug
* refactor: execute RD loops via asyncio.run and add necessary imports
* lint
* lint
* lint
---------
Co-authored-by: Xu <v-xuminrui@microsoft.com>
* fix the logic of kb-inject, allow different verion
* set more flexiable proposal-version change for multi-tarce
* auto-lint
* fix the divede-zero-bug in a trival way
* keep the dump imp. first, update in next version
* use get_sub_trace_count() to get trace_num_count
* fix the conern case bug of divide-zero
* update corner case
* fix the bug
* auto-lint
* fis the bug
* fix the logic bug in max_sota_filter
* fix bug of old version of self.exp_gen.gen
* update the reset_exp_gen_version
* use get_parent_exps to replace all collect_all_ancestors
* auto lint
* fix the bug of reset_exp_gen_version
* fix bug: update V3's old hypothesis_rank
* trival patch on gap of V3 & V2
* make dump patch to unify proposal_V3's dentify_problems
* auto-lint
* fix the bug of sub_trace_count
* chore: avoid incorporate changes
best as sota
merge hypothesis
fix: max_retrieve_num after decision
chore: select last experiments and feedbacks
* add the set_current_selection before the exp_gen when merging
add trace.NEW_ROOT
fix: no scen_prob_multiplier
fix: use regex with timeout
chore: hypothesis_rank with selected_idx
chore: define is_parent in proposal
chore: rename collect_all_ancestors to get_parent_exps
---------
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: Xu <v-xuminrui@microsoft.com>
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* fix model input shape bug and costeer_model bug
* fix a bug
* fix a bug in docker result extraction
* a system-level optimization
* add a filter of stdout
* update
* add stdout to model
* model training_hyperparameters update
* quant scenario
* update some quant settings
* llm choose action
* Thompson Sampling Bandit for action choosing
* refine both scens
* add trace messages for quant scen
* fix some bugs
* fix some bugs
* update
* update
* update
* fix
* fix
* fix
* update for merge
* fix ci
* fix some bugs
* fix ci
* fix ci
* fix ci
* fix ci
* refactor
* default qlib4rdagent local env downloading
* fix ci
* fix ci
* fix a bug
* fix ci
* fix: align all prompts on template (#908)
* use template to render all prompts
* fix CI
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* add fin_quant in cli
* fix a bug
* fix ci
* fix some bugs
* refactor
* remove the columns in hypothesis if no value generated in this column
* fix a bug
* fix ci
* fix conda env
* add qlib gitignore
* remove existed qlib folder & install torch in qlib conda
* fix workspace ui in feedback
* align model config in coder and runner in docker or conda
* fix CI
* fix CI
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* add try-except to avoid retry when using completion_cost
* feat: add JSON prompt injection and think tag removal handling
* refactor: simplify cost handling in LiteLLM backend and clean up style
* docs: clarify purpose of reasoning_think_rm in LLMSettings
* refactor: remove unused *args and redundant cost assignment
---------
Co-authored-by: Young <afe.young@gmail.com>
* fix the problems weights bug
* refactor: remove DSExpGen
* update problems weights calculation
* update problems weights calculation
* remove the selection parameter from exp_gen
* v2 support draft
* v3 also support decomposition
* make the identify_problems an independent function
* fix minor bug
* reformat
* rename exp_num to weighted_exp_num
* add the set_current_selection before the exp_gen when merging
* reformat
* fix wrong selection
* refactor: drop selection arg from ExpGen.gen and DS merge generators
---------
Co-authored-by: Xu <v-xuminrui@microsoft.com>
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* set constrains on max_sota_retrieved, fix logis on identical problem
* fix: only Auto SOTA selector use max_sota_retrieved_num
* set max_sota_retrieved_num=10 by default
* minor update
* auto lint
* provide get metric direction in kaggle_crawler.py
* move utils function
* move statistics logic
* fix CI
* fix CI
* fix CI
* fix CI
* move some tool functions
* fix CI
* move curves win
* add compare tool
* change function name
* fix CI
* docs: add MLE-bench details to README
* docs: update README with revised MLE-bench description and leaderboard
* docs: update RD-Agent text and add trial info in README
* Update README.md
* Update README.md
* update by M
* update format
* Add documents
* docs: update RD-Agent references to R&D-Agent
* docs: update README with MLE-Bench complexity level details
* rebase selection code
* bug-free run: checkpoint selection and dynamic EDA loading
* add prototypes of various selectors, to imp. and test later
* fix EDA write bug
* imp SOTA-Jump policy
* fix small bug
* allow to set different selector by .env
* add always-win selector
* add init length for AlwaysWinCKPSelector
* add back_jump selector
* auto lint
* add sota_exp_to_submit attribute; change the name of ckp_selector and sota-selector
* fix bug
* auto lint
* working on auto sota selector
* add subtrace counter
* fix bug, remove unuse selector
* add auto sota selector
* auto lint
* fix bug
* fix small logic bug
* add logging
* add inject_diverse feat
* auto lint
* capable to None-select
* feat: add hypothesis_gen config and ExpGen2TraceAndMerge functionality
* refactor: use dynamic import for experiment generator instantiation
* feat: add BestValidSelector for improved SOTA experiment selection
* runnable twin-trace version
* fix logic error of trace-merge
* auto lint
* use import_class to set selector,
* auto-lint
---------
Co-authored-by: Young <afe.young@gmail.com>
* custom data
* fix: simplify competition check and log local description file
* no sample data
* feat: add test evaluation module with error handling support
* fix: update eval path to use eval_sub_dir and add valid_check TODO
* refactor: add MLETestEval check to conditionally run grading steps
* avoid blank stdout
* valid in testeval
* rename test.csv to avoid conflict
* Support Disabling sample submission
* refactoring
* fix: remove DS_KAGGLE_DATA and update prompt instructions
* add try for grade
* ignore submission
* fix: remove tee from eval command and warn about pipeline exit code detection
* optional to use raw description
* support old data
* add execution result to stdout
* add metric to raw description
* custom data explain
* add debug_path
* rst update
---------
Co-authored-by: Young <afe.young@gmail.com>
* fix: return first index if 'SOTA Exp Score (valid)' is empty
* feat: add get_state_data_range helper for loops and slider bounds
* fix: exclude batch embedding tag from log filtering
* feat: add feedback support in sota_experiment and adjust merge flow
* fix: use fb function for merging experiments
* style: remove extra whitespace and reformat code
* using model in the chat_model_map in one tag
* add replace timer to DS loop
* fix CI
* fix CI
* add more custom config in chat_model_map
* fix CI
* fix CI
* fix CI
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* update all code
* update all code
* dump knowledge base
* rename the tag
* add timer to RD-Agent
* fix CI
* fix CI
* use batch embedding
* fix a small bug
* fix prompt bug
* feat: add pause resume to handle K8S cluster pause (#804)
* add resume to cluster running
* fix non-pickle problem
* fix a small bug
* fix a small bug
* avoid shutil move error
* refine the logic
* move knowledge base out of session
* avoid mistake information to pipeline coding
* avoid load and dump in steps
* archive the right folder
* small improvement
* avoid restart when timer is already started
* fix CI
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
Co-authored-by: Xu <v-xuminrui@microsoft.com>
* refactor: use dynamic input path and update template loader
* fix: update include syntax for data source in prompts.yaml
* add customization path
* docs: update prompts for ensemble scoring and metric direction
* chore: remove obsolete data_science/share.yaml file
* style: Simplify language and improve clarity in prompts and share.yaml
* style: Update prompt wording for clarity in raw_data_loader
* style: Simplify conditional logic in task_gen system prompt
* refactor: Update prompts and proposal for component output format handling
* fix: Correct grammar and add clarification in prompts.yaml
* feat: Include coding guidelines in data science component prompts
* lint
* feat: add DocDev for auto-generating workspace documentation
* fix: update markdown instructions in tpl.yaml
* feat: add enable_doc_dev flag and conditionally call DocDev
* refactor: update T import and prompt keys for DocDev
* fix: update include path for MarkdownOut template
* fix: update file search, README injection, and brief prompt text
* docs: update prompt to only introduce models
* lint
* feat: add model dump flag and multi-evaluator support
* tmp code
* refactor: update evaluator feedback and FBWorkspace types
* feat: add get_clear_ws_cmd and CPU count in Docker environment
* feat: Add model dump check level and enhance evaluator functionality
fix data type bug
* fix: Ensure required files exist before model dump evaluation
* refactor: streamline prompt and file checks in model dump evaluation
* fix: add assertions and reorder file reads in model dump evaluator
* feat: remove EDA part from evaluation output
* docs: update dump_model guidelines and eval prompt to include template
* style: reformat multiline dicts and lists in conf and eval files
* fix: add DOTALL flag to EDA removal regex
* rebase selection code
* bug-free run: checkpoint selection and dynamic EDA loading
* add prototypes of various selectors, to imp. and test later
* fix EDA write bug
* move selector to from proposal.py tp seletc.py
* auto lint
* fix line-too-long typos
* aligh the design of "selection", rm extra instance check
* make auto-lint
* add non-trival selector: SOTAjump
* ui changes
* add ours vs medal threshold
* add success loop statistic of components
* show times info
* UI updates
* summary selected
* change colors
* fix CI
* add stat hours param for `mle_summary.py --summary` command
* add 24h summary button
* fix CI
* add logger info for dockerEnv/condaEnv running time
* cache function
* fix test
* bin cache
* fix test
* fix test
* fix test
* cache for different source
* cache for localenv
* remove unnecessary log
* reformat
* remove unrelated modify
* init commit
* limit problem numbers
* ensemble lower case
* add runtime and spec to coder
* submission check notice
* sub EDA in sample execution
* avoid lightgbm
* add time limit to scenario
* rephrase the submission check
* give positive feedback when facing warning in check
* ENABLE FEEDBACK
* fix feedback bug
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* first framework commit
* idea proposal v2
Co-authored-by: Roland Minrui <RolandMinrui@users.noreply.github.com>
* fix a small bug in v1
* fix a small bug
* add problem to DShypothesis
* use exp gen as unified interface
* merge yuante's code into pr
* fix a small bug in draft
* update all minrui's code
* small update
* fix small bug & remove useless code
* fix return type
* fix CI
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: Roland Minrui <RolandMinrui@users.noreply.github.com>
Co-authored-by: Xu <v-xuminrui@microsoft.com>
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
* docs: Update prompts and descriptions for data science components
* chore: Remove outdated comments from conf.py
* feat: Add metric_name attribute to DataScienceScen class
* style: Update description in prompts.yaml and reorder metric_name init
* docs: Update prompts.yaml with feature engineering guidelines
* feat: Track and log accumulated completion cost in LiteLLMAPIBackend
* refactor: Use variable for retry count and update import formatting
* lint
* fix: Allow chat_max_tokens to be None in LLMSettings
* feat: Add logging for LiteLLM settings and finish reason in cost calculation
* update metric_name
* fix some bugs
* add an evaluation in workflow
* add an evalution in runner
* fix ci
* test change
* fix CI
---------
Co-authored-by: TPLin22 <tplin2@163.com>
Co-authored-by: yuanteli <1957922024@qq.com>
* feat: Add spec_enabled configuration for data science settings
* make spec alternative
* change spec logic in exp_gen
* remove some general texts
* align
---------
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: yuanteli <1957922024@qq.com>
* docs: add contributing guidelines for RD-Agent
* docs: update contributing guide to include CI checks before pull requests and refrer to it in the home page README
* prune model task
* add component_description
* add model removal logic to component, hypo, and task gen
* fix ci
* adjust coder to meet the requirement of model removal
* fix and refine the logic of model removal
* add model removal logic in model_eval
* fix ci
* fix ci
* prune some unnecessary codes
* use conda to run kaggle and mlebench code
* refactor: Simplify environment configuration and execution logic
* add setting to use local env in ds
* refine dockerfile
* fix: Move MLEBDockerEnv initialization inside conditionals & fix condaenv
* refactor: reformat code for better readability and consistency
* feat: add conda env to all envs.
* fix: fix bugs when run loop
* refactor: Simplify DockerEnv configuration in mle_summary.py
* fix image bug
* style: reformat code for better readability and consistency
* change commit
* feat: Add entrypoint script for sing_docker scenario in rdagent
* refactor: add Any type hints and comments for clarity in env.py
* feat: Create log directory if it doesn't exist in entrypoint script
* feat: Add debug mode and list root directory in entrypoint script
* fix: Remove specific branch checkout in Dockerfile for RD-Agent
* fix: Add competition argument to loop.py script execution
* fix: Correct directory navigation and dependency installation in entrypoint.sh
* fix: Correct user ownership assignment in entrypoint script
* refactor: Comment out redundant log copying to RD_OUTPUT_DIR
* fix: Unset LOG_TRACE_PATH to prevent log contamination in entrypoint.sh
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* refactor: Rename direct_exp_gen to json_target_type in DSExpGen class
* fix type
* fix: Adjust loop iterations and update json_target_type for nested dicts
* move cache auto continue and retry to all api backend
* add type checker to json mode output
* fix CI
* feat: Add json_mode handling and streaming support in chat completion function
* lint
* fix a bug when returning a dict which value could contain int or bool
* remove litellm
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
Co-authored-by: Young <afe.young@gmail.com>
* feat: add output_path to load from checkpoint function
* add default value to output_path
* sort import
* sort imports
---------
Co-authored-by: Xu <v-xuminrui@microsoft.com>
* fix a bug in cross_validation
* fix cross-validation prompt position
* fix
* fix
* append all error messages and full traceback details in execution
---------
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
* refactor: Add run_ret_code method and update run method to use it
* feat: Add kwargs support to run methods and test for run_ret_code
* fix: preserve exit code after chmod in DockerEnv entry command
* chore: Change file permissions from 755 to 644 in env_tpl directory
* refactor: Return execution code and update evaluator logic
* lint
* refactor: Use MappingProxyType for running_extra_volume in DockerEnv methods
* lint
* refactor: Update type annotations and remove unused class in evolving modules
* refactor: Simplify evolving agent and feedback handling in CoSTEER module
* lint & CI
* mypy
* ruff for core
* mypy
* refactor: remove unnecessary comments and update feedback handling logic
* refactor: Add prev_task_feedback parameter to evolving strategies
* feat: Clear folder before extracting zip file in DockerEnv
* fix: Correct retrieval of last experiment from history
* allow the LLM in the ensemble to focus on the significance of metrics
* fix a bug in feedback
* prun spec
* fix a bug in ensemble
* delete unnecessary prompts
* fix the logic in spec
* generalize dataset split
* File structure for supporting litellm
* more litellm support
* feat: Add CachedAPIBackend class and dynamic API backend retrieval function
* fix: update benchmark folder path and add default values for architecture and hyperparameters
* feat: add LiteLLMAPIBackend and DeprecBackend ; changed structure of the project ; with bus
* fix : deprec_backend
* feat: Add LiteLLMAPIBackend class and related features; update configuration and test cases.
* feat: Enhance LiteLLMAPIBackend with encoder support and dynamic argument handling;Enhance log Colors
* lint
* fix lint...
* fix: Lint
* fix:make auto-lint
* fix:test oai
* fix:redundant _abckend.py
* fix: Optimize LiteLLMAPIBackend on token counting functiona, and clean up unused code;add test on this function
* feat: Add LiteLLMSettings class and update model settings usage
* fix: Update LiteLLMSettings environment variable prefix and model configurations
* fix : gitignore
* test: Consolidate and relocate test files for litellm backend and oai
* fix : lint
* fix: lint
* auto lint
* lint
* LINT
* lint
* chore: remove deprecated backend configuration comments
* refactor: Remove unused functions and imports from deprec.py and llm_utils.py
* refactor: Move md5_hash function from deprec.py to llm_utils.py
* chore: Remove extra newline and add missing import in deprec.py
* lint
* refactor: Move md5_hash function to utils module
* lint
* lint
* lint
---------
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: Yihua Chen <v-yihuachen@microsoft.com>
* refactor: Simplify exp_gen and enhance workflow with init_kwargs_update_func
* fix: Correct type hint for init_kwargs_udpate_func parameter
* lint
* lint
* lint
* lint
* refine ds modal for more cases: eval and es
* update model template
* prompts for model and ensemble
* fix a bug
* fix a bug
* init: ds workflow evovingstrategy
* Adding ensemble (#505)
* Initial Draft
* Updating logic for init
* Revising
* Successful Testing
* Updating to use the latest & right class
* bug: bug-fixing for testing
* data science loop changes
* data science loop base
* ds loop feedback
* fix
* remove measure_time because it's duplicated (in LoopBase)
* add the knowledge query for data_loader & feature
* edit ds workflow evaluator
* data_loader bug fix
* stop evolving when all tasks completed
* llm app change
* fix break all complete strategy
* Adding queried knowledge (#508)
Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>
* fix loop bug
* ds workflow evaluator; test; refine prompts
* workflow spec
* fix ci
* feature task changes
* ds loop change
* fix a bug in feat
* add query knowledge for model and workflow
* llm_debug info(for show) using pickle instead of json
* remove NextLoopException
* loop change
* coder raise CoderError when all sub_tasks failed
* rename code_dict to file_dict in FBWorkspace
* add CoSTEER unittest
* now show self.version in Task.get_task_information(), simplify CoSTEER sub tasks definition
* remove some properties in ModelTask, add model_type in it.
* fix llm app bug
* llm web app bug fix
* ds loop bug fix
* fix: give component code to feature&ens eval
* loop catch error bug
* rename load_from_raw_data to load_data
* feat: Add debug data creation functionality for data science scenarios
* support local folder (#511)
* support local folder
* remove unnecessary random
* KaggleScen Subclass
* small fix
* use template for style description
* update default scen to kaggle
* update sample data script
* make sure frac < 1
* fix a bug
* feature spec changes
* fix
* changeimport order
* clear unnecessary std outputs
* fix a typo
* create sample folder after unzip kaggle data
* feature/model test script update
* Align the data types across modules.
* fix a bug in model eval
* show line number
* move sample entry point to app
* spec & model prompt changes
* Refine the competition specification to address the data type problem and the coherence issue.
* fix some bugs
* add file filter in FBworkspace.code property
* support non-binary prediction
* avoid too much warnings
* fix a bug in ensemble module
* filtered the knowledge query in all modules
* delete RAG in idea proposal
* refine the code in ensemble
* show exp workspace in llm_st
* exp_gen bug fix
* feedback bug fix
* use `feature` instead of `feat01`
* Trace & method of judging if exp is completed change
* fix a bug in package calling and execute ci
* fix code
* bug fix
* bug fix
* fix a bug
* fix some bugs
* fix a bug
* refactor: Enhance error handling and feedback in data science loop
* support different use_azure on chat and embedding models
* multi-model proposal logic
* fix a small syntax error
* loopBase and some changes
* ensemble scores change
* fbworkspace.code -> .all_codes
* use all model codes in workflow coder
* check scores.csv's keys(model_names)
* model name changes
* add a todo in ensemble test
* sota_exp changes
* give model info in exp gen
* add runner time limit
* config using debug data or not in evals
* exp to feedback base
* add feature code when writing model task
* small problem
* copying during sampling
* update
* refactor: Simplify code handling and improve workspace management
* model part output fix
* print model's execution time
* bug fix
* ensemble test fix
* ens small change
* ens_test bug fix
* Refine partial expansion logic to display only a few subfolders when their structure is uniform, improving readability in nested directories.
* several update on prompts
* sample subfolders
* Filter the stdout after code execution to remove irrelevant information e.g. progress bars, whitespace characters, excessive line breaks.
* Add some more prompts and comments
* several update on the first init rounds
* model timeout as error
* fix pattern of getting model codes in workspace
* small bux fix on model prompts
* remove get_code_with_key since we have regex pattern
* fix: Correct tqdm progress bar update logic in LoopBase class
* feat: Add diff generation and enhance feedback mechanism in data science loop
* update some fix to model and workflow prompts
* refine the logic of progress bar filter
* add last_successful_exp in exp_gen
* fix a one line bug
* add a hint in prompt
* fix data sample for bms
* fix data sample for bms
* hypothesis small fix
* crawler readme update
* fix component gen
* fix bug
* annotation change
* load description.md if it exists
* refactor: Simplify SOTA description handling in feedback and prompts
* refactor: Use shared templates for feedback and experiment descriptions
* change webapp for model codes changes
* update proposal
* add timeout message for docker run output
* fix
* refine the code in docker time processing
* use .shape instead of len() when do shape eval
* won't change size during iteration
* support bson sample
* sample support jsonl and bson
* add former_code to coder prompts
* a little speed us in debug data creating
* filter progress bar when eval ens and main
* avoid costeer makes no change to former code
* fix several log error
* add timeout judge threshold
* fix some bugs in the evaluation of component output shapes
* File structure for supporting litellm (#517)
Co-authored-by: Young <afe.young@gmail.com>
* ignore submission and show processing
* ignore submission and show processing
* add efficiency notice
* refactor: Enhance error message with detailed feedback summary
* refactor: Simplify component handling in DSExpGen class
* refactor: Update code structure and add docstring for clarity
* reserve one sample to each label in data sampling
* add Evaluation info
* refine costeer code to avoid giving same code twice
* use raw_description as plain text
* add a prompt hint to avoid same dict key
* model task name bug in first model exp gen
* fix a typo
* add some debug info in costeer tests
* task init change
* enhance data sampling
* refine the code in data_loader
* more reasonable loop
* fix a bug in data folder description
* add error msg & traceback to execution feedback
* fix llm error msg detection
* add task information to costeer eval & add cache to docker run(use zipfile to store the whole workspace)
* fix CI first round
* fix CI second round
* use txt to store test script to avoid pytest
* remove zipfile in requirements
* add azure.identity to requirements
* ignore debug web page
* component test changes
* remove redundent task_desc in model coder
* feat: Add APE module and prompts for automated prompt engineering
* fix: Update .gitignore and improve text formatting in eval.py
* refactor: Update print output and improve code comments and imports
* style: Fix string formatting and import order in ape.py and fmt.py
* exclude ape
* add a data folder notice
* reduce unnecessary output to stdout
* refine the code of describe_data_folder
* fix ci
* style: streamlit style update (#522)
* streamlit style update
* fix import
* fix format
* fix llm_st loop progress bar
* debugapp small change
* fix model str
* refine some prompts
* fix model str
* fix CI
* refine the logic associated with the data_folder
* fix ci
* small change
* set filter_progress_bar as default in execute
* model proposal with workflow
* add submission check in workflow eval
* fix bug
* small change
* fix CI
* fix CI
* refactor: Move generate_diff to utils and update DSExpGen logic
* more reasonable prompt describing metric direction
* fix a minor jinja2 bug
* quick fix exp_gen bugs
* fix the following bug
* fix
* fix some bugs
* remove workflow from model
* add pending_tasks_list in data science to enable coding model and workflow
* refine the code for handling JSON-formatted data descriptions
* assert with information
* ensure correct csv file name
* add logging to help record the output
* log competition
* add log tag for debug llm app
* test: Test ds refactor ll (#523)
* fix bugs to former scenario
* fix a bug because coding in rdloop changed
* fix the bug when feedback gets no hypothesis
* fix trace structure
* change all trace hist when merging hypothesis to experiments
* ignore some error in ruff
* fix kaggle scenario bugs
* refine one line
* another bug
* another small bug
* fix ui bugs
* chage kaggle train.py path
---------
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* fix CI
* Update rdagent/app/data_science/loop.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* add samplecsv into spec prompts
* fix CI
---------
Co-authored-by: TPLin22 <tplin2@163.com>
Co-authored-by: yuanteli <1957922024@qq.com>
Co-authored-by: Xisen Wang <118058822+xisen-w@users.noreply.github.com>
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>
Co-authored-by: Tim <illking@foxmail.com>
Co-authored-by: 炼金术师华华 <37462254+YeewahChan@users.noreply.github.com>
Co-authored-by: Linlang <30293408+SunsetWolf@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* fix PR template
* subfolders of the log displayed on the web page
* fix code error
* add health check
* reformat with isort
* reformat with black
* update README
* fix bug && experience confusing
* reformat with black & update health check code
* reformat with isort
* reformat with black
* update README.md
* Removed duplicates in documentation and health_check && Upgraded code for filtering folders
* update docs
* reformat with black
* Use ExtendedBaseSettings to replace BaseSettings
* update a more general way to pass the default setting
* update all code
* fix CI
* fix CI
* fix qlib scenario
* fix CI
* fix CI
* fix CI & add data science interfaces
* remove redundant code
* abandon costeer knowledge base v1
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>
* init trail
* Add spec info
* auto unzip mlebench prepared data for out scenario
* successfully run example
* successfully run main
* simplify load traing
* extract load_from_raw_data
* split the fies(still buggy)
It should stop on ~20 epoch and reach the end
* some changes
* Fix bug to run example
* (success) until feature
* refine model and ensemble
* add metrics in ens.py
* update README & spec.md
* ens change
* fix ens bug
* Delete rdagent/scenarios/kaggle/tpl_ex/aerial-cactus-identification/train.py
* add template_path in KG_conf
* fix test kaggle
* CI
* make test_import not check kaggle template codes
---------
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
* copy init version
* feat: new-york-city-taxi-fare-prediction_template
* add move to linear model
* Add more details about docker
* auto lint
* auto lint with new black
* several improvement on kaggle loop
* small refinement on prompt
* fix bugs
* add the score of each model in every experiment
* fix ci error
* fix error in ventilator tpl
* fix CI
---------
Co-authored-by: Xu Yang <xuyang1@microsoft.com>
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
Co-authored-by: WinstonLiye <1957922024@qq.com>
Co-authored-by: TPLin22 <tplin2@163.com>
* udpate plot
* log and reduce token
* trace tag
* add simple_background parameter to get_scenario_all_desc
* update trace
* update first version code
* chat model map
* add annotation for stack index
* add annotation
* reformatted by black
* several update on kaggle scenarios
* update some new change
* fix CI
* fix CI
* fix a bug
* fix bugs in graph RAG
---------
Co-authored-by: Tim <illking@foxmail.com>
* init for bg & quickstart for kaggle docs
* Add documentation for the environment configuration in the Kaggle scenario.
* add some descriptions in documents
* remove useless docs
* ci issue
---------
Co-authored-by: TPLin22 <tplin2@163.com>
* initial version
* test requirements
* fix bugs
* fix bugs
* add annotation
* fix ruff error
* fix CI
* fix CI
* fix CI
* fix CI
* change random usage
* move cache_seed_gen to core/utils.py
* fix CI
* change cache_seed_gen name
---------
Co-authored-by: Young <afe.young@gmail.com>
* Fixes on kaggle output
* feat: add kaggle s3e14 template (#394)
* add s3e14 template
* fix CI
* Initialisation of a template of competition
* add kaggle s3e16 template (#396)
* get kaggle competition scores (#397)
* Adding a new competition s4e6
* feat: s4e5 (#400)
* init for s4e5
* edit s4e5
* ci issue
* feat: S4e3 (#402)
* Initialisation of a template of competition
* Adding a new competition s4e6
* Competition Initialised
* Fixed to make sure that now it runs
* Fixing for CI
* correct evaluation (#403)
* find rank in leaderboard (#405)
* fix: model templates for KG scenario (#408)
* fix feature selection for some models
* feat select template
* Updating the prompts for a more powerful model tuning
* refine the prompt
* fix: template error in s4e6
* feat: show simple execution time in demo (#410)
* show time in kaggle demo
* change color
* fix a small bug
* edit loop.py and proposal
* delete useless files
* CI issues
* ci issue
---------
Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>
Co-authored-by: Haoran Pan <167847254+TPLin22@users.noreply.github.com>
Co-authored-by: Way2Learn <118058822+Xisen-Wang@users.noreply.github.com>
Co-authored-by: WinstonLiyt <1957922024@qq.com>
Co-authored-by: TPLin22 <tplin2@163.com>
* simplify RDAgent conf
* add unified cacher(untested)
* fix small bugs
* fix a bug
* fix a small bug in runner
* use hash_key = None to skip cache
* fix CI
* in factor execution, ignore cache when raise exception
* add file locker to avoid mp calling
* fix CI
* use function __module__ name as folder in cache
1. when facing odd v2_query_component_limit, make from gt bigger than without gt
2. do code evaluator even value does not pass
3. provide the value header to value failed evaluators
* crawl notebooks & change to DS-Agent format text
* give one function in kaggle_crawler to collect kaggle knowledge texts
* fix CI
* add tool for merge .py files to one py file
* fix CI
* delete files
* changes for select function
* add nbformat
* jump crawler import test
* del test code
* CI
* change
* change
* change
* rename meta_tpl
* use a isolated coder to deal with model feature selection and refine the structure
* fix CI
* fix: fix some errors in scenario.py, proposal.py and runner.py and several complex competition scenarios(#365)
* fix several bugs in proposal and runner
* fix a bug in feedback-prize-english-language-learning
* fix some bugs and templates
* fix the bug in optiver and nlp problem
* delete unnecessary codes
* remove unnecessary codes
* complete forest and s4e8
* push
* feedback & s4e8 & forest
* optiver finished
* s3e11 & s3e26
* s4e9 finished
* sf-crime finished
* the last one finished
---------
Co-authored-by: WinstonLiyt <104308117+WinstonLiyt@users.noreply.github.com>
Co-authored-by: WinstonLiyte <1957922024@qq.com>
* fix several bugs in proposal and runner
* fix a bug in feedback-prize-english-language-learning
* fix some bugs and templates
* fix the bug in optiver and nlp problem
* remove AttributeError caused by select_threshold
* develop with ground truth
* raise exception for eval_case
* Revert "develop with ground truth"
This reverts commit e68c136588685476f32a3c3696a6a33deb47acc5.
* Modify FactorRowCountEvaluator and FactorIndexEvaluator to return the ratio
* reformatted by black
* Set the threshold for FactorIndexEvaluator to 0.99
* Apply suggestions from code review
* Update rdagent/components/coder/factor_coder/CoSTEER/evaluators.py
* geometric mean for format_succ_rate
* no need to check when similarity is high enough
* black reformat
---------
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
* spaceship: format type of y = pd.series; fix a wrong spelling in xgb
* s3e11: format of y -- pd.series
* spaceship: format of y & fit nn
* spaceship: wrong spelling in xgb
* ci issue
* Adding the competition: Optiver Volatility Prediction
* Fixing for CI
* Updating a new competition @ Optiver
* re-writing the optiver competition
* Revise for better commit
* Further fixes
* Further fixes
* Fixes
* Further Fixing Optiver Template
* Fix further to pass the test
* Fixing for CI
* Fixing for CI
* Adding the competition: Optiver Volatility Prediction
* Fixing for CI
* Updating a new competition @ Optiver
* re-writing the optiver competition
* Revise for better commit
* Further fixes
* Further fixes
* Fixes
* Key changes
* Revised to support submission specifications
* Revised to support submission specifications
* revise CI
* CI-Fix
* fixing-CI
* Support COSTEER Multi-Dimension for output & bug-fix
* Revised to support submission specifications
* revise CI
* CI-Fix
* fixing-CI
* Support COSTEER Multi-Dimension for output & bug-fix
* Linting
* add qlib_factor_strategy
* refine the code of action choosing
* fix a bug
* feat: template for kaggle (#308)
* init for s3e26
* ci issue
* fix a small bug in model runner which might cause error when model is the first try (#309)
* update
---------
Co-authored-by: Haoran Pan <167847254+TPLin22@users.noreply.github.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* Search enhancement
* refactor: reorganize imports for consistency with isort
* reformatterd by black
---------
Co-authored-by: Tim <illking@foxmail.com>
* init for forest-cover-type-prediction
* add nn model for forest-cover-type-prediction
* add cross_validation for forest-cover-type-prediction
* edit path to file
* CI issues
* CI Issue
* edit dir name
* fix a bug in s4e8 ensemble & init spaceship-titanic
* add nn model for s4e8 & spaceship-titanic
* init for s4e9
* ci issues
* ci issue
* edit prompts & model_rf
* init for sf-crime template
* CI issues
* discard change in prompts
* CI issues
* fix a bug
* fix some bugs
* fix a ci bug
---------
Co-authored-by: WinstonLiye <1957922024@qq.com>
* fix some bugs in feedback.py
* feat: kaggle templates related (#287)
* add kaggle test
* kaggle templates changes
* rename two files
* fix a grammar bug
* fix a ci error
* fix a bug
---------
Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>
* Update feedback.py to support all actions
Feedback.py is updated to support all actions.
* Update prompts.yaml to support all actions
* Revised for CI
* CI
* fix a ci bug
* fix a ci bug
---------
Co-authored-by: WinstonLiye <1957922024@qq.com>
* Add runtime measurement for each step and loop in RDLoop.
* refine some codes
* refine the code (#276)
* show variables only when it exists (#277)
* fix: support seed and fix absolute path (#278)
* fix: support seed and fix absolute path
* Absolute path
* lint
* fix: improve_execution_time_in_kaggle_loop (#279)
* improve_execution_time_in_kaggle_loop
* fix CI
* fix CI
* fix CI
* fix: Update runner.py to fix a small bug (#282)
* fix: Update runner.py to fix a small bug
* fix CI
* refine the code
* Update loop.py
* Update rd_loop.py
* Update model_xgb.py
---------
Co-authored-by: XianBW <36835909+XianBW@users.noreply.github.com>
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
Co-authored-by: Xu Yang <peteryang@vip.qq.com>
* init a scenario for kaggle feature engineering
* Added support for loading and storing RAG in Kaggle scenarios.
* fix a ci bug
* Add RAG after each experiment's feedback.
* add a promt
* fix a bug
* fix a bug
* add a readme
* refine the code in knowledge loading
* init a scenario for kaggle feature engineering
* add 1st version rag for Kaggle hypo
* refine the code
* fix a bug
* add the process of extracting exp from docs
* Remove the unnecessary file.
* refine the code for ci test
* Delete rdagent/app/kaggle_feature/conf.py
* refine the comments
* Update extract_experience_from_docs.py
* Update extract_experience_from_docs.py
* init a scenario for kaggle feature engineering
* fix some bugs and add original features' description
* refine the process of data downloading
* fix a error
* revert the code
* fix a bug in feedback
* fix a ci bug
* fix a ci bug
* Init todo
* Evaluation & dataset
* Generate new data
* dataset generation
* add the result
* Analysis
* Factor update
* Updates
* Reformat analysis.py
* CI fix
* Revised Preprocessing & Supported Random Forest
* Revised to support three models with feature
* Further revised prompts
* Slight Revision
* docs: update contributors (#230)
* Revised to support three models with feature
* Further revised prompts
* Slight Revision
* feat: kaggle model and feature (#238)
* update first version code
* make hypothesis_gen and experiment_builder fit for both feature and model
* feat: continue kaggle feature and model coder (#239)
* use qlib docker to run qlib models
* feature coder ready
* model coder ready
* fix CI
* finish the first round of runner (#240)
* Optimized the factor scenario and added the front-end.
* fix a small bug
* fix a typo
* update the kaggle scenario
* delete model_template folder
* use experiment to run data preprocess script
* add source data to scenarios
* minor fix
* minor bug fix
* train.py debug
* fixed a bug in train.py and added some TODOs
* For Debugging
* fix two small bugs in based_exp
* fix some bugs
* update preprocess
* fix a bug in preprocess
* fix a bug in train.py
* reformat
* Follow-up
* fix a bug in train.py
* fix a bug in workspace
* fix a bug in feature duplication
* fix a bug in feedback
* fix a bug in preprocessed data
* fix a bug om feature engineering
* fix a ci error
* Debugged & Connected
* Fixed error on feedback & added other fixes
* fix CI errors
* fix a CI bug
* fix: fix_dotenv_error (#257)
* fix_dotenv_error
* format with isort
* Update rdagent/app/cli.py
---------
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
* chore(main): release 0.2.1 (#249)
Release-As: 0.2.1
* init a scenario for kaggle feature engineering
* delete error codes
* Delete rdagent/app/kaggle_feature/conf.py
---------
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: Taozhi Wang <taozhi.mark.wang@gmail.com>
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
Co-authored-by: cyncyw <47289405+taozhiwang@users.noreply.github.com>
Co-authored-by: Xisen-Wang <xisen_application@163.com>
Co-authored-by: Haotian Chen <113661982+Hytn@users.noreply.github.com>
Co-authored-by: WinstonLiye <1957922024@qq.com>
Co-authored-by: WinstonLiyt <104308117+WinstonLiyt@users.noreply.github.com>
Co-authored-by: Linlang <30293408+SunsetWolf@users.noreply.github.com>
* add collect info
* fix isort error
* optimize code
* fix black error
* Update rdagent/app/cli.py
* Modify the code according to the comments
* fix isort error
* add docker info
* docs: update contributors (#230)
* fix: package dependency. (#234)
* fix package
* fix lint
* docs: Update development.rst (#235)
* feat: add cross validation for kaggle scenario (#236)
* update cross validation for kaggle scenario
* CI Issues
* delete useless file
* CI issues
* docs: Update README.md (#245)
* docs: refine the README (#244)
* init a scenario for kaggle feature engineering
* update the readme
* Delete rdagent/app/kaggle_feature/conf.py
* update some pictures
* Delete rdagent/app/kaggle_feature/model.py
* change a photo
* add pics to docs
* update the readme
* update the README
* for a try
* for another try
* change the style of the pictures in readme
* fix a small bug
* update the readme and the docs
* update the docs
* fix a typo
* change a website url
* change some styles
* fix a typo
* change the size of the logo
* change two urls
* Update README.md
* Update README.md
* Update README.md
* Update README.md
---------
Co-authored-by: Linlang <Lv.Linlang@hotmail.com>
* move the component to other files
* last container
* optimize rdagent info
* format with isort
* format with black
* format_with_black
* fix pip error
* format with isort
* change requirements
* fix pip error
* fix_pip_error
* fix pip error
* format with black
* fix pip error
---------
Co-authored-by: you-n-g <you-n-g@users.noreply.github.com>
Co-authored-by: Haotian Chen <113661982+Hytn@users.noreply.github.com>
Co-authored-by: Haoran Pan <167847254+TPLin22@users.noreply.github.com>
Co-authored-by: Way2Learn <118058822+Xisen-Wang@users.noreply.github.com>
Co-authored-by: WinstonLiyt <104308117+WinstonLiyt@users.noreply.github.com>
Co-authored-by: Young <afe.young@gmail.com>
* init a scenario for kaggle feature engineering
* update the readme
* Delete rdagent/app/kaggle_feature/conf.py
* update some pictures
* Delete rdagent/app/kaggle_feature/model.py
* change a photo
* add pics to docs
* update the readme
* update the README
* for a try
* for another try
* change the style of the pictures in readme
* fix a small bug
* update the readme and the docs
* update the docs
* fix a typo
* change a website url
* change some styles
* fix a typo
* change the size of the logo
* change two urls
* Update README.md
* Update README.md
* Update README.md
* Update README.md
---------
Co-authored-by: Linlang <Lv.Linlang@hotmail.com>
* Initial template
* Updated a bit on the framework
* Revised to enable feat training
* Fixed Accuracy
* fixed mcc
* change some files for feature
* update some logics in feat eng
* update some codes
* update some codes
* Revised further to successfully completed a cycle
* Revised further
* Delete two CSVs
* fix some ci errors
---------
Co-authored-by: Young <afe.young@gmail.com>
Co-authored-by: Xisen-Wang <xisen_application@163.com>
* Update model_experiment.py to support basic eda
It looks into the data first before the proposal.
* Update model_experiment.py
Revised linting
* Update model_experiment.py by fixing sorting order
* Update model_experiment.py for black linting
* Update model_experiment.py
* Update model_experiment.py
* Update model_experiment.py
* Update model_experiment.py
---------
Co-authored-by: WinstonLiyt <104308117+WinstonLiyt@users.noreply.github.com>
* init commit for XGBoost
* fix some bugs
* CI issues
* CI issues
* CI issue
* edit prompts for kaggle scenario & fix some bugs
* Revised Prompts To Improve Performance on Model Type & Support of Random Forest
* edit prompts & modify evaluator.py to adapt to Kaggle scenario
* edit prompts
* fix some bugs
* CI issues
---------
Co-authored-by: Taozhi Wang <taozhi.mark.wang@gmail.com>
Co-authored-by: Xisen-Wang <xisen_application@163.com>
* fuse all code into one commit
* remove container auto
* change remove method
* add kaggle env start
* change kaggle api
* change structure
* add crawler
* add requirements
* refeact the code
* delete mistaken codes
* merge docker settings and crawler
* add chrome install README for crawler usage
* Connect scen with Kaggle to download data
* Reformat some files to pass CI.
* fix some ci errors
* fix a ci error
* fix a ci error
---------
Co-authored-by: Bowen Xian <xianbowen@outlook.com>
<!--- minor update (introduces new functionality): `feat` -->
<!--- Example: feature(parser): add ability to parse arrays -->
<!--- major update(destructive update): Include BREAKING CHANGE in the commit message footer, or add `! ` in the commit footer to indicate that there is a destructive update. -->
<!--- Example: feat(auth)! : remove support for old authentication method -->
<!--- Are there any related issues? If so, please put the link here. -->
<!--- Why is this change required? What problem does it solve? -->
## How Has This Been Tested?
<!--- Put an `x` in all the boxes that apply: --->
- [ ] Pass the test by running: `pytest qlib/tests/test_all_pipeline.py` under upper directory of `qlib`.
- [ ] If you are adding a new feature, test on your own test scripts.
<!--- **ATTENTION**: If you are adding a new feature, please make sure your codes are **correctly tested**. If our test scripts do not cover your cases, please provide your own test scripts under the `tests` folder and test them. More information about test scripts can be found [here](https://docs.python.org/3/library/unittest.html#basic-example), or you could refer to those we provide under the `tests` folder. -->
## Screenshots of Test Results (if appropriate):
1. Pipeline test:
2. Your own tests:
## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
All notable changes to Predix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
### Features
## [Unreleased]
* Add description for scenario experiments. ([#174](https://github.com/microsoft/RD-Agent/issues/174)) ([fbd8c6d](https://github.com/microsoft/RD-Agent/commit/fbd8c6d87e1424c08997103b8e8fbf264858c4ed))
* Added QlibFactorFromReportScenario and improved the report-factor loop. ([#161](https://github.com/microsoft/RD-Agent/issues/161)) ([882c79b](https://github.com/microsoft/RD-Agent/commit/882c79bf11583980e646b130f71cfa20201ffc7b))
* filter feature which is high correlation to former implemented features ([#145](https://github.com/microsoft/RD-Agent/issues/145)) ([e818326](https://github.com/microsoft/RD-Agent/commit/e818326422740e04a4863f7c3c18744dde2ad98f))
* Remove redundant 'key steps' section in frontend scene display. ([#169](https://github.com/microsoft/RD-Agent/issues/169)) ([e767005](https://github.com/microsoft/RD-Agent/commit/e76700513bee29232c93b97414419df330d9be8d))
* streamlit webapp demo for different scenarios ([#135](https://github.com/microsoft/RD-Agent/issues/135)) ([d8da7db](https://github.com/microsoft/RD-Agent/commit/d8da7db865e6653fc4740efee9a843b69bd79699))
* Uploaded Documentation, Updated Prompts & Some Code for model demo ([#144](https://github.com/microsoft/RD-Agent/issues/144)) ([529f935](https://github.com/microsoft/RD-Agent/commit/529f935aa98623f0dc1dda29eecee3ef738dd446))
### Changed
- Rebranded from RD-Agent to Predix for EUR/USD quantitative trading
- Updated project metadata for PredixAI organization
### Fixed
- Removed all Chinese stock references, replaced with EUR/USD 1min FX data
- Migrated to 1min EURUSD data (2020-2026)
- Injected MultiIndex warning into factor interface prompt
### Bug Fixes
---
* Add framework handling for task coding failure. ([#176](https://github.com/microsoft/RD-Agent/issues/176)) ([5e14fa5](https://github.com/microsoft/RD-Agent/commit/5e14fa54a9dd30a94aebe2643b8c9a3b85517a11))
* Comprehensive update to factor extraction. ([#143](https://github.com/microsoft/RD-Agent/issues/143)) ([b5ea040](https://github.com/microsoft/RD-Agent/commit/b5ea04019fd5fa15c0f8b9a7e4f18f490f7057d4))
* first round app folder cleaning ([#166](https://github.com/microsoft/RD-Agent/issues/166)) ([6a5a750](https://github.com/microsoft/RD-Agent/commit/6a5a75021912927deb5e8e4c7ad3ec4b51bfc788))
* fix pickle problem ([#140](https://github.com/microsoft/RD-Agent/issues/140)) ([7ee4258](https://github.com/microsoft/RD-Agent/commit/7ee42587b60d94417f34332cee395cf210dc8a0e))
* fix release CI ([#165](https://github.com/microsoft/RD-Agent/issues/165)) ([85d6a5e](https://github.com/microsoft/RD-Agent/commit/85d6a5ed91113fda34ae079b23c89aa24acd2cb2))
* fix release CI error ([#160](https://github.com/microsoft/RD-Agent/issues/160)) ([1c9f8ef](https://github.com/microsoft/RD-Agent/commit/1c9f8ef287961731944acc9008496b4dddeddca7))
* fix several bugs in data mining scenario ([#147](https://github.com/microsoft/RD-Agent/issues/147)) ([b233380](https://github.com/microsoft/RD-Agent/commit/b233380e2c66fb030db39424f0f040c86e37f5c4))
* fix some small bugs in report-factor loop ([#152](https://github.com/microsoft/RD-Agent/issues/152)) ([a79f9f9](https://github.com/microsoft/RD-Agent/commit/a79f9f93406aff6305a76e6a6abd3852642e4c62))
* Fixed some bugs introduced during refactoring. ([#167](https://github.com/microsoft/RD-Agent/issues/167)) ([f8f1445](https://github.com/microsoft/RD-Agent/commit/f8f1445283fb89aefeb2918243c35a219a51a56c))
* optimize some prompts in factor loop. ([#158](https://github.com/microsoft/RD-Agent/issues/158)) ([c2c1330](https://github.com/microsoft/RD-Agent/commit/c2c13300b9ad315a663ec2d0eada414e56c6f54f))
We welcome contributions and suggestions to improve Predix. Whether it's solving an issue, addressing a bug, enhancing documentation, or even correcting a typo, every contribution is valuable and helps improve the project.
## Getting Started
To get started, you can explore the issues list or search for `TODO:` comments in the codebase by running:
```sh
grep -r "TODO:"
```
## How to Contribute
1.**Fork the Repository**: Create a fork of the repository on GitHub.
2.**Clone the Repository**: Clone your forked repository to your local machine.
RDAgent aims to automate the most critical and valuable aspects of the industrial R&D process, and we begins with focusing on the data-driven scenarios to streamline the development of models and data.
Methodologically, we have identified a framework with two key components: 'R' for proposing new ideas and 'D' for implementing them.
We believe that the automatic evolution of R&D will lead to solutions of significant industrial value.
## Overview
**Predix** is an autonomous AI agent for quantitative trading strategies in the EUR/USD forex market. Built on a multi-agent framework, Predix automates the full research and development cycle:
<!-- Tag Cloud -->
R&D is a very general scenario. The advent of RDAgent can be your
-[🎥Automatic Quant Factory]()
-🤖Data mining agent: iteratively proposing [🎥data]() & [models]() and implementing them by gaining knowledge from data.
- 🦾Research copilot: Auto read [🎥research papers]()/[🎥reports]() and implement model structures or building datasets.
- ...
- 📊 **Data Analysis**– Automatically analyzes market patterns and microstructure
- 💡 **Strategy Discovery**– Proposes novel trading factors and signals
-📈 **Backtesting**– Validates strategies on historical 1-minute data
You can click the [🎥link]() above to view the demo. More methods and scenarios are being added to the project to empower your R&D processes and boost productivity.
Predix is optimized for **1-minute EUR/USD FX data** (2020–2026) and uses Qlib as the underlying backtesting engine.
We have a quick 🎥demo for one use case of RDAgent.
- TODO: Demo
---
## Installation
# ⚡Quick start
You can try our demo by running the following command:
### Prerequisites
### 🐍 Create a Conda Environment
-Create a new conda environment with Python (3.10 and 3.11 are well tested in our CI):
```sh
conda create -n rdagent python=3.10
```
- Activate the environment:
```sh
conda activate rdagent
```
- **Python 3.10 or 3.11**
-**Docker** (required for sandboxed code execution)
- **Linux** (officially supported; macOS/Windows may work with adjustments)
### 🛠️ Run Make Files
TODO: `pip install rdagent` in the future.
### Quick Install
- **Navigate to the directory containing the MakeFile** and set up the development environment:
- Place the `.env` file in the same directory as the `.env.example` file.
- The `.env.example` file contains the environment variables required for users using the OpenAI API (Please note that `.env.example` is an example file. `.env` is the one that will be finally used.)
- please refer to [Configuration](docs/build/html/installation.html#azure-openai) for the detailed explanation of the `.env`
- Export each variable in the `.env` file:
```sh
export $(grep -v '^#' .env | xargs)
```
### 🚀 Run the Application
TODO: run the front-page demo.
```bash
# Create conda environment
conda create -n predix python=3.10
conda activate predix
The [🎥demo]() is implemented by the above commands.
# Install in editable mode with dev dependencies
make dev
```
- Run the factor extraction and implementation application based on financial reports:
- Run the self-loop factor extraction and implementation application:
```sh
python rdagent/app/qlib_rd_loop/factor.py
```
## Quick Start
- Run the self-loop model extraction and implementation application:
```sh
python rdagent/app/qlib_rd_loop/model.py
```
### 1. Health Check
Verify your environment is properly configured:
# Scenarios
```bash
rdagent health_check --no-check-env
```
We have applied RD-Agent to multiple valuable data-driven industrial scenarios..
### 2. Configure LLM Backend
Create a `.env` file in your project root:
## 🎯 Goal: Agent for Data-driven R&D
```bash
# Example: OpenAI configuration
cat << EOF > .env
CHAT_MODEL=gpt-4o
EMBEDDING_MODEL=text-embedding-3-small
OPENAI_API_BASE=https://api.openai.com/v1
OPENAI_API_KEY=your-api-key-here
EOF
```
In this project, we are aiming to build a Agent to automate Data-Driven R\&D that can
+ 📄Read real-world material (reports, papers, etc.) and **extract** key formulas, descriptions of interested **features** and **models**, which are the key components of data-driven R&D .
+ 🛠️**Implement** the extracted formulas (e.g., features, factors, and models) in runnable codes.
+ Due to the limited ability of LLM in implementing at once, evolve the agent to be able to extend abilities by learning from feedback and knowledge and improve the agent's ability to implement more complex models.
+ 💡Propose **new ideas** based on current knowledge and observations.
Automating the R&D process in data science is a highly valuable yet underexplored area in industry. We propose a framework to push the boundaries of this important research field.
### Data Configuration
The research questions within this framework can be divided into three main categories:
| Research Area | Paper/Work List |
|--------------------|-----------------|
| Benchmark the R&D abilities | [Benchmark](#benchmark) |
| Idea proposal: Explore new ideas or refine existing ones | [Research](#research) |
| Ability to realize ideas: Implement and execute ideas | [Development](#development) |
Edit [`data_config.yaml`](data_config.yaml) to customize:
We believe that the key to delivering high-quality solutions lies in the ability to evolve R&D capabilities. Agents should learn like human experts, continuously improving their R&D skills.
Core dependencies (see [`requirements.txt`](requirements.txt) for full list):
- **LLM**: `openai`, `litellm`
- **Data**: `pandas`, `numpy`, `pyarrow`
- **ML**: `scikit-learn`, `lightgbm`, `xgboost`
- **Backtesting**: `qlib` (via Docker)
- **UI**: `streamlit`, `plotly`, `flask`
---
## License
This project is licensed under the **MIT License**– see the [`LICENSE`](LICENSE) file for details.
---
## Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
For major changes, please open an issue first to discuss your approach.
---
## Citation
If you use Predix in your research, please cite the underlying framework:
```bibtex
@misc{yang2025rdagentllmagentframeworkautonomous,
title={R&D-Agent: An LLM-Agent Framework Towards Autonomous Data Science},
author={Yang, Xu and Yang, Xiao and Fang, Shikai and Zhang, Yifei and Wang, Jian and Xian, Bowen and Li, Qizheng and Li, Jingyuan and Xu, Minrui and Li, Yuante and others},
In a data mining expert's daily research and development process, they propose a hypothesis (e.g., a model structure like RNN can capture patterns in time-series data), design experiments (e.g., finance data contains time-series and we can verify the hypothesis in this scenario), implement the experiment as code (e.g., Pytorch model structure), and then execute the code to get feedback (e.g., metrics, loss curve, etc.). The experts learn from the feedback and improve in the next iteration.
## Support
Based on the principles above, we have established a basic method framework that continuously proposes hypotheses, verifies them, and gets feedback from the real-world practice. This is the first scientific research automation framework that supports linking with real-world verification.
- **Documentation**: [Read the Docs](https://rdagent.readthedocs.io/)
[Demos](#📈 Scenarios/Demos) are released.
---
## Development
## Disclaimer
- [Collaborative Evolving Strategy for Automatic Data-Centric Development](https://arxiv.org/abs/2407.18690)
```BibTeX
@misc{yang2024collaborative,
title={Collaborative Evolving Strategy for Automatic Data-Centric Development},
author={Xu Yang and Haotian Chen and Wenjun Feng and Haoxue Wang and Zeqi Ye and Xinjie Shen and Xiao Yang and Shizhao Sun and Weiqing Liu and Jiang Bian},
Predix is provided "as is" for **research and educational purposes only**. It is **not** intended for:
- Live trading or financial advice
- Production use without thorough testing
- Replacement of qualified financial professionals
# Contributing
More documents can be found in the [📚readthedocs](). TODO: add link
## Guidance
This project welcomes contributions and suggestions.
You can find issues in the issues list or simply running `grep -r "TODO:"`.
Making contributions is not a hard thing. Solving an issue(maybe just answering a question raised in issues list ), fixing/issuing a bug, improving the documents and even fixing a typo are important contributions to RDAgent.
**The RD-agent is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. The RD-agent is aimed to facilitate research and development process in the financial industry and not ready-to-use for any financial investment or advice. Users shall independently assess and test the risks of the RD-agent in a specific use scenario, ensure the responsible use of AI technology, including but not limited to developing and integrating risk mitigation measures, and comply with all applicable laws and regulations in all applicable jurisdictions. The RD-agent does not provide financial opinions or reflect the opinions of Microsoft, nor is it designed to replace the role of qualified financial professionals in formulating, assessing, and approving finance products. The inputs and outputs of the RD-agent belong to the users and users shall assume all liability under any theory of liability, whether in contract, torts, regulatory, negligence, products liability, or otherwise, associated with use of the RD-agent and any inputs and outputs thereof.**
Users assume all liability and should comply with applicable laws and regulations in their jurisdiction. Past performance does not guarantee future results.
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below.
## Reporting Security Issues
We take the security of Predix seriously. If you believe you have found a security vulnerability, please report it to us as described below.
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report).
Instead, please report them via email to:
- **Email**: nico@predix.io
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs.
You should receive a response within 48 hours. If for some reason you do not, please follow up via email to ensure we received your original message.
## Preferred Languages
We prefer all communications to be in English.
## Policy
## Security Updates
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->
Security updates will be released as patch versions. Please ensure you are using the latest version of Predix to benefit from security fixes.
# TODO: The maintainer of this repo has not yet edited this file
**REPO OWNER**: Do you want Customer Service & Support (CSS) support for this product/project?
- **No CSS support:** Fill out this template with information about how to file issues and get help.
- **Yes CSS support:** Fill out an intake form at [aka.ms/onboardsupport](https://aka.ms/onboardsupport). CSS will work with/help you to determine next steps.
- **Not sure?** Fill out an intake as though the answer were "Yes". CSS will help you decide.
*Then remove this first heading from this SUPPORT.MD file before publishing your repo.*
# Support
## How to file issues and get help
This project uses GitHub Issues to track bugs and feature requests. Please search the existing
issues before filing new issues to avoid duplicates. For new issues, file your bug or
feature request as a new Issue.
For help and questions about using this project, please **REPO MAINTAINER: INSERT INSTRUCTIONS HERE
FOR HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A STACK OVERFLOW TAG OR OTHER
CHANNEL. WHERE WILL YOU HELP PEOPLE?**.
## Microsoft Support Policy
Support for this **PROJECT or PRODUCT** is limited to the resources listed above.
# Support
## How to file issues and get help
This project uses GitHub Issues to track bugs and feature requests. Please search the existing
issues before filing new issues to avoid duplicates. For new issues, file your bug or
We encourage to set the TODOs in code. But some TODOs are more global.
So we place it here.
# TODOs
This file tracks global TODOs for the Predix project. Individual TODOs in code should be addressed in their respective modules.
- [ ] Aligning the naming of files in components & scenarios.
- We would like to have the same logic for naming convention in components(reusable components for all scenarios) and scenarios (componets for specific scenario).
- But now we have following mismatch
-`coder` in `components`&`developer` in `components`
- [ ]The name of the folders mismatch with the content in them.
-Why are scenarios in experiments?
## Current Global TODOs
- [ ] Align naming conventions for files in `components/` and `scenarios/` directories
- Current mismatch:`coder` in `components/`vs`developer` in `scenarios/`
- [ ]Clean up folder naming inconsistencies
-Investigate why some scenario-related code is in `experiments/` folders
## Completed
- [x] Rebrand from RD-Agent to Predix for EUR/USD focus
- [x] Remove Microsoft-specific references
- [x] Update documentation for PredixAI organization
"text{low}":"Lowest price of the stock for the day.",
"text{high}":"Highest price of the stock for the day."
},
"Category":"Volume&Price",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha053\nnew_df['ratio'] = (new_df['$close'] - new_df['$low'] - (new_df['$high'] - new_df['$close'])) / (new_df['$close'] - new_df['$low'])\n# the change of ratio in new_df over the 15 days\nnew_df['result']=-new_df['ratio'].diff(15)\n# transfer the result to series\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
"std(minute liquidity_imbalance)":"Standard deviation of trading liquidity_imbalance for each minute of the trading day.",
"mean(minute liquidity_imbalance)":"Mean of trading liquidity_imbalance for each minute of the trading day.",
"liquidity_imbalance":"(bid_size-ask_size)/(bid_size+ask_size), we use something like bidV for the size"
},
"Category":"High-Frequency",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['liquidity_imbalance']=(sample_df['bidV']-sample_df['askV'])/(sample_df['bidV']+sample_df['askV'])\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['liquidity_imbalance']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\n# Calculate Z value for each instrument per day\nstats['liquidity_imbalance'] = stats['std'] / stats['mean']\n# Display the calculated Z values\nresult=stats['liquidity_imbalance']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"std(minute liquidity_imbalance)":"Standard deviation of trading liquidity_imbalance for each minute of the trading day.",
"mean(minute liquidity_imbalance)":"Mean of trading liquidity_imbalance for each minute of the trading day.",
"liquidity_imbalance":"(bid_size-ask_size)/2*(bid_size+ask_size), we use something like bidV for the size"
},
"Category":"High-Frequency",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['liquidity_imbalance']=(sample_df['bidV']-sample_df['askV'])/((sample_df['bidV']+sample_df['askV'])*2)\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['liquidity_imbalance']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\n# Calculate Z value for each instrument per day\nstats['liquidity_imbalance'] = stats['std'] / stats['mean']\n# Display the calculated Z values\nresult=stats['liquidity_imbalance']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"std(minute liquidity_imbalance)":"Standard deviation of trading liquidity_imbalance for each minute of the trading day.",
"mean(minute liquidity_imbalance)":"Mean of trading liquidity_imbalance for each minute of the trading day.",
"liquidity_imbalance":"(bid_size-ask_size)/3*(bid_size+ask_size), we use something like bidV for the size"
},
"Category":"High-Frequency",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['liquidity_imbalance']=(sample_df['bidV']-sample_df['askV'])/((sample_df['bidV']+sample_df['askV'])*3)\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['liquidity_imbalance']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\n# Calculate Z value for each instrument per day\nstats['liquidity_imbalance'] = stats['std'] / stats['mean']\n# Display the calculated Z values\nresult=stats['liquidity_imbalance']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['micro_price']=(sample_df['bid']*sample_df['askV']+sample_df['ask']*sample_df['bidV'])/(sample_df['bidV']+sample_df['askV'])\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['micro_price']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\n# Calculate Z value for each instrument per day\nstats['micro_price'] = stats['std'] / stats['mean']\n# Display the calculated Z values\nresult=stats['micro_price']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"std(minute micro_price)":"Standard deviation of trading micro_price for each minute of the trading day.",
"mean(minute micro_price)":"Mean of trading micro_price for each minute of the trading day.",
"micro_price":"((df['bid_price'] * df['ask_size']) + (df['ask_price'] * df['bid_size'])) / 2*(df['bid_size'] + df['ask_size']), we use something like bidV for the size"
},
"Category":"High-Frequency",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['micro_price']=(sample_df['bid']*sample_df['askV']+sample_df['ask']*sample_df['bidV'])/((sample_df['bidV']+sample_df['askV'])*2)\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['micro_price']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\n# Calculate Z value for each instrument per day\nstats['micro_price'] = stats['std'] / stats['mean']\n# Display the calculated Z values\nresult=stats['micro_price']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"std(minute micro_price)":"Standard deviation of trading micro_price for each minute of the trading day.",
"mean(minute micro_price)":"Mean of trading micro_price for each minute of the trading day.",
"micro_price":"((df['bid_price'] * df['ask_size']) + (df['ask_price'] * df['bid_size'])) / 3*(df['bid_size'] + df['ask_size']), we use something like bidV for the size"
},
"Category":"High-Frequency",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['micro_price']=(sample_df['bid']*sample_df['askV']+sample_df['ask']*sample_df['bidV'])/((sample_df['bidV']+sample_df['askV'])*3)\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['micro_price']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\n# Calculate Z value for each instrument per day\nstats['micro_price'] = stats['std'] / stats['mean']\n# Display the calculated Z values\nresult=stats['micro_price']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"std(minute mid_price)":"Standard deviation of trading mid_price for each minute of the trading day.",
"mean(minute mid_price)":"Mean of trading mid_price for each minute of the trading day.",
"mid_price":"The average of the bid and ask prices."
},
"Category":"High-Frequency",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['mid_price']=(sample_df['bid']+sample_df['ask'])/2\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['mid_price']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\nstats['mid_price'] = stats['std'] / stats['mean']\nresult=stats['mid_price']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"std(minute mid_price)":"Standard deviation of trading mid_price for each minute of the trading day.",
"mean(minute mid_price)":"Mean of trading mid_price for each minute of the trading day.",
"mid_price_2":"the average of the bid and ask prices plus the the average of the bid and ask size (bidV and askV)."
},
"Category":"High-Frequency",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['mid_price']=(sample_df['bid']+sample_df['ask'])/2+(sample_df['bidV']+sample_df['askV'])/2\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['mid_price']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\nstats['mid_price'] = stats['std'] / stats['mean']\nresult=stats['mid_price']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
"std(minute mid_price)":"Standard deviation of trading mid_price for each minute of the trading day.",
"mean(minute mid_price)":"Mean of trading mid_price for each minute of the trading day.",
"mid_price_3":"The coefficient of variation (CV) of the mid-price for each minute of the trading day, calculated as the standard deviation of the mid-price divided by the mean mid-price."
},
"Category":"High-Frequency",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_hf = pd.read_hdf('high_freq.h5')\nsample_df= data_hf.reset_index()\n# Convert 'datetime' column to datetime and extract date for grouping\nsample_df['date'] = sample_df['datetime'].dt.date\nsample_df['mid_price']=(sample_df['bid']+sample_df['ask'])/3\n# Group by instrument and date\ngrouped = sample_df.groupby(['date','instrument'])['mid_price']\n# Calculate mean and standard deviation of the volume for each group\nstats = grouped.agg(['mean', 'std'])\nstats['mid_price'] = stats['std'] / stats['mean']\nresult=stats['mid_price']\nresult.index.names = ['datetime','instrument']\n# result = result.swaplevel().sort_index()\nresult.to_hdf('result.h5', key='data')"
},
"PB_ROE":{
"description":"Constructed using the ranking difference between PB and ROE, with regression versions of PB and ROE replacing original PB and ROE to obtain reconstructed factor values.",
"formulation":"text{rank}(PB_t) - rank(ROE_t)",
"variables":{
"text{rank}(PB_t)":"Ranking of regression version PB on cross-section at time t.",
"text{rank}(ROE_t)":"Ranking of regression version single-quarter ROE on cross-section at time t."
},
"Category":"Fundamentals",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\ndata = data_f.reset_index()\n# Calculate the rank of PB and ROE\ndata['PB_rank'] = data.groupby('datetime')['B/P'].rank()\ndata['ROE_rank'] = data.groupby('datetime')['ROE'].rank()\n# Calculate the difference between the ranks\ndata['PB_ROE'] = data['PB_rank'] - data['ROE_rank']\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(data['PB_ROE']).set_index(data_f.index)\n# transfer the result to series\nresult=result['PB_ROE']\nresult.to_hdf('result.h5', key='data')"
},
"PB_ROE_2":{
"description":"Constructed using the ranking difference between PB/2 and ROE, with regression versions of PB and ROE replacing original PB and ROE to obtain reconstructed factor values.",
"formulation":"text{rank}(PB_t)/2 - rank(ROE_t)",
"variables":{
"text{rank}(PB_t)":"Ranking of regression version PB on cross-section at time t.",
"text{rank}(ROE_t)":"Ranking of regression version single-quarter ROE on cross-section at time t."
},
"Category":"Fundamentals",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\ndata = data_f.reset_index()\n# Calculate the rank of PB and ROE\ndata['PB_rank'] = data.groupby('datetime')['B/P'].rank()\ndata['ROE_rank'] = data.groupby('datetime')['ROE'].rank()\n# Calculate the difference between the ranks\ndata['PB_ROE'] = data['PB_rank']/2 - data['ROE_rank']\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(data['PB_ROE']).set_index(data_f.index)\n# transfer the result to series\nresult=result['PB_ROE']\nresult.to_hdf('result.h5', key='data')"
},
"PB_ROE_3":{
"description":"Constructed using the ranking difference between PB/3 and ROE, with regression versions of PB and ROE replacing original PB and ROE to obtain reconstructed factor values.",
"formulation":"text{rank}(PB_t)/3 - rank(ROE_t)",
"variables":{
"text{rank}(PB_t)":"Ranking of regression version PB on cross-section at time t.",
"text{rank}(ROE_t)":"Ranking of regression version single-quarter ROE on cross-section at time t."
},
"Category":"Fundamentals",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\ndata = data_f.reset_index()\n# Calculate the rank of PB and ROE\ndata['PB_rank'] = data.groupby('datetime')['B/P'].rank()\ndata['ROE_rank'] = data.groupby('datetime')['ROE'].rank()\n# Calculate the difference between the ranks\ndata['PB_ROE'] = data['PB_rank']/3 - data['ROE_rank']\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(data['PB_ROE']).set_index(data_f.index)\n# transfer the result to series\nresult=result['PB_ROE']\nresult.to_hdf('result.h5', key='data')"
},
"PB_ROE_movement":{
"description":"PB_ROE_movement=five day PB_ROE movement indicator(-1 and 1 or 0).",
"PB_ROE":"the ranking difference between PB and ROE.",
"5_day_PB_ROE_movement":"1 if PB_ROE is higher than the PB_ROE 5 days ago, -1 if PB_ROE is lower than the PB_ROE 5 days ago, 0 if PB_ROE is the same as the PB_ROE 5 days ago.",
"text{rank}(PB_t)":"Ranking of regression version PB on cross-section at time t.",
"text{rank}(ROE_t)":"Ranking of regression version single-quarter ROE on cross-section at time t."
},
"Category":"Fundamentals",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\nsample_df = data_f.reset_index()\n# Calculate the rank of PB and ROE\nsample_df['PB_rank'] = sample_df.groupby('datetime')['B/P'].rank()\nsample_df['ROE_rank'] = sample_df.groupby('datetime')['ROE'].rank()\nsample_df['PB_ROE'] = sample_df['PB_rank'] - sample_df['ROE_rank']\n# Group by instrument and date\nsample_df['PB_ROE_movement'] = sample_df['PB_ROE'].diff(periods=5).apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))\n#calculate the mid_price_movement ratio for each day\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(sample_df['PB_ROE_movement']).set_index(data_f.index)\n# transfer the result to series\nresult=result['PB_ROE_movement']\nresult.to_hdf('result.h5', key='data')"
},
"PB_ROE_movement_10":{
"description":"PB_ROE_movement=10 days PB_ROE movement indicator(-1 and 1 or 0).",
"PB_ROE":"the ranking difference between PB and ROE.",
"10_day_PB_ROE_movement":"1 if PB_ROE is higher than the PB_ROE 10 days ago, -1 if PB_ROE is lower than the PB_ROE 10 days ago, 0 if PB_ROE is the same as the PB_ROE 10 days ago.",
"text{rank}(PB_t)":"Ranking of regression version PB on cross-section at time t.",
"text{rank}(ROE_t)":"Ranking of regression version single-quarter ROE on cross-section at time t."
},
"Category":"Fundamentals",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\nsample_df = data_f.reset_index()\n# Calculate the rank of PB and ROE\nsample_df['PB_rank'] = sample_df.groupby('datetime')['B/P'].rank()\nsample_df['ROE_rank'] = sample_df.groupby('datetime')['ROE'].rank()\nsample_df['PB_ROE'] = sample_df['PB_rank'] - sample_df['ROE_rank']\n# Group by instrument and date\nsample_df['PB_ROE_movement'] = sample_df['PB_ROE'].diff(periods=10).apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))\n#calculate the mid_price_movement ratio for each day\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(sample_df['PB_ROE_movement']).set_index(data_f.index)\n# transfer the result to series\nresult=result['PB_ROE_movement']\nresult.to_hdf('result.h5', key='data')"
},
"PB_ROE_movement_20":{
"description":"PB_ROE_movement=20 days PB_ROE movement indicator(-1 and 1 or 0).",
"PB_ROE":"the ranking difference between PB and ROE.",
"20_day_PB_ROE_movement":"1 if PB_ROE is higher than the PB_ROE 20 days ago, -1 if PB_ROE is lower than the PB_ROE 20 days ago, 0 if PB_ROE is the same as the PB_ROE 20 days ago.",
"text{rank}(PB_t)":"Ranking of regression version PB on cross-section at time t.",
"text{rank}(ROE_t)":"Ranking of regression version single-quarter ROE on cross-section at time t."
},
"Category":"Fundamentals",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\nsample_df = data_f.reset_index()\n# Calculate the rank of PB and ROE\nsample_df['PB_rank'] = sample_df.groupby('datetime')['B/P'].rank()\nsample_df['ROE_rank'] = sample_df.groupby('datetime')['ROE'].rank()\nsample_df['PB_ROE'] = sample_df['PB_rank'] - sample_df['ROE_rank']\n# Group by instrument and date\nsample_df['PB_ROE_movement'] = sample_df['PB_ROE'].diff(periods=20).apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))\n#calculate the mid_price_movement ratio for each day\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(sample_df['PB_ROE_movement']).set_index(data_f.index)\n# transfer the result to series\nresult=result['PB_ROE_movement']\nresult.to_hdf('result.h5', key='data')"
},
"ROE_movement":{
"description":"ROE_movement=five day ROE movement indicator(-1 and 1 or 0).",
"5_day_ROE_movement":"1 if ROE is higher than the ROE 5 days ago, -1 if ROE is lower than the ROE 5 days ago, 0 if ROE is the same as the ROE 5 days ago."
},
"Category":"Fundamentals",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\nsample_df = data_f.reset_index()\n# Group by instrument and date\nsample_df['ROE_movement'] = sample_df['ROE'].diff(periods=5).apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))\n#calculate the mid_price_movement ratio for each day\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(sample_df['ROE_movement']).set_index(data_f.index)\n# transfer the result to series\nresult=result['ROE_movement']\nresult.to_hdf('result.h5', key='data')"
},
"ROE_movement_10":{
"description":"ROE_movement_10=ten day ROE movement indicator(-1 and 1 or 0).",
"10_day_ROE_movement":"1 if ROE is higher than the ROE 10 days ago, -1 if ROE is lower than the ROE 10 days ago, 0 if ROE is the same as the ROE 10 days ago."
},
"Category":"Fundamentals",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\nsample_df = data_f.reset_index()\n# Group by instrument and date\nsample_df['ROE_movement'] = sample_df['ROE'].diff(periods=10).apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))\n#calculate the mid_price_movement ratio for each day\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(sample_df['ROE_movement']).set_index(data_f.index)\n# transfer the result to series\nresult=result['ROE_movement']\nresult.to_hdf('result.h5', key='data')"
},
"ROE_movement_20":{
"description":"ROE_movement_20=20 day ROE movement indicator(-1 and 1 or 0).",
"20_day_ROE_movement":"1 if ROE is higher than the ROE 20 days ago, -1 if ROE is lower than the ROE 20 days ago, 0 if ROE is the same as the ROE 20 days ago."
},
"Category":"Fundamentals",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_f = pd.read_hdf('daily_f.h5')\nsample_df = data_f.reset_index()\n# Group by instrument and date\nsample_df['ROE_movement'] = sample_df['ROE'].diff(periods=20).apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))\n#calculate the mid_price_movement ratio for each day\n# set the datetime and instrument as index and drop the original index\nresult=pd.DataFrame(sample_df['ROE_movement']).set_index(data_f.index)\n# transfer the result to series\nresult=result['ROE_movement']\nresult.to_hdf('result.h5', key='data')"
},
"alpha_pv_diff":{
"description":"alpha_pv_diff is defined as the ratio of the difference between close prices 10 days change and open prices 10 days change to the sum of the highest minus lowest prices plus a small constant.",
"high":"Highest price of the stock during the day",
"low":"Lowest price of the stock during the day"
},
"Category":"Volume&Price",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha101\nnew_df['result'] = (new_df['$close'].diff(10) - new_df['$open'].diff(10)) / (new_df['$high'] - new_df['$low'] + 0.001)\n# keep the index of the original dataframe\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\n# transfer the result to series\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
},
"alpha_pv_diff_15":{
"description":"alpha_pv_diff is defined as the ratio of the difference between close prices 15 days change and open prices 15 days change to the sum of the highest minus lowest prices plus a small constant.",
"high":"Highest price of the stock during the day",
"low":"Lowest price of the stock during the day"
},
"Category":"Volume&Price",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha101\nnew_df['result'] = (new_df['$close'].diff(15) - new_df['$open'].diff(15)) / (new_df['$high'] - new_df['$low'] + 0.001)\n# keep the index of the original dataframe\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\n# transfer the result to series\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
},
"alpha_pv_diff_20":{
"description":"alpha_pv_diff is defined as the ratio of the difference between close prices 20 days change and open prices 20 days change to the sum of the highest minus lowest prices plus a small constant.",
"high":"Highest price of the stock during the day",
"low":"Lowest price of the stock during the day"
},
"Category":"Volume&Price",
"Difficulty":"Medium",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha101\nnew_df['result'] = (new_df['$close'].diff(20) - new_df['$open'].diff(20)) / (new_df['$high'] - new_df['$low'] + 0.001)\n# keep the index of the original dataframe\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\n# transfer the result to series\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
},
"alpha_pv_diff_pct":{
"description":"alpha_pv is defined as the ratio of the difference between close prices 10 days change and open prices 10 days change to the sum of the highest prices 10 days change ratio minus lowest prices 10 days change ratio plus a small constant.",
"high":"Highest price of the stock during the day",
"low":"Lowest price of the stock during the day"
},
"Category":"Volume&Price",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha101\nnew_df['result'] = (new_df['$close'].diff(10) - new_df['$open'].diff(10)) / (new_df['$high'].pct_change(10) - new_df['$low'].pct_change(10) + 0.001)\n# keep the index of the original dataframe\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\n# transfer the result to series\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
},
"alpha_pv_diff_pct_15":{
"description":"alpha_pv is defined as the ratio of the difference between close prices 15 days change and open prices 15 days change to the sum of the highest prices 10 days change ratio minus lowest prices 10 days change ratio plus a small constant.",
"high":"Highest price of the stock during the day",
"low":"Lowest price of the stock during the day"
},
"Category":"Volume&Price",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha101\nnew_df['result'] = (new_df['$close'].diff(15) - new_df['$open'].diff(15)) / (new_df['$high'].pct_change(10) - new_df['$low'].pct_change(10) + 0.001)\n# keep the index of the original dataframe\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\n# transfer the result to series\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
},
"alpha_pv_diff_pct_20":{
"description":"alpha_pv is defined as the ratio of the difference between close prices 20 days change and open prices 20 days change to the sum of the highest prices 10 days change ratio minus lowest prices 10 days change ratio plus a small constant.",
"high":"Highest price of the stock during the day",
"low":"Lowest price of the stock during the day"
},
"Category":"Volume&Price",
"Difficulty":"Hard",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha101\nnew_df['result'] = (new_df['$close'].diff(20) - new_df['$open'].diff(20)) / (new_df['$high'].pct_change(10) - new_df['$low'].pct_change(10) + 0.001)\n# keep the index of the original dataframe\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\n# transfer the result to series\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
},
"alpha053":{
"description":"Reversal class factor, negative delta of a ratio involving close, low, and high prices over 9 days.",
"text{low}":"Lowest price of the stock for the day.",
"text{high}":"Highest price of the stock for the day."
},
"Category":"Volume&Price",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha053\nnew_df['ratio'] = (new_df['$close'] - new_df['$low'] - (new_df['$high'] - new_df['$close'])) / (new_df['$close'] - new_df['$low'])\n# the change of ratio in new_df over the 9 days\nnew_df['result']=-new_df['ratio'].diff(9)\n# transfer the result to series\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
},
"alpha053_5":{
"description":"Reversal class factor, negative delta of a ratio involving close, low, and high prices over 5 days.",
"text{low}":"Lowest price of the stock for the day.",
"text{high}":"Highest price of the stock for the day."
},
"Category":"Volume&Price",
"Difficulty":"Easy",
"gt_code":"import pandas as pd\ndata_pv = pd.read_hdf('daily_pv.h5')\nnew_df= data_pv.reset_index()\n# Calculate Alpha053\nnew_df['ratio'] = (new_df['$close'] - new_df['$low'] - (new_df['$high'] - new_df['$close'])) / (new_df['$close'] - new_df['$low'])\n# the change of ratio in new_df over the 5 days\nnew_df['result']=-new_df['ratio'].diff(5)\n# transfer the result to series\nresult=pd.DataFrame(new_df['result']).set_index(data_pv.index)\nresult=result['result']\nresult.to_hdf('result.h5', key='data')"
- for dev users: `See development <development.html>`_
**Install Docker**: RDAgent is designed for research and development, acting like a human researcher and developer. It can write and run code in various environments, primarily using Docker for code execution. This keeps the remaining dependencies simple. Users must ensure Docker is installed before attempting most scenarios. Please refer to the `official 🐳Docker page <https://docs.docker.com/engine/install/>`_ for installation instructions.
Ensure the current user can run Docker commands **without using sudo**. You can verify this by executing `docker run hello-world`.
Configuration
=============
LiteLLM Backend Configuration (Default)
=======================================
..note::
🔥 **Attention**: We now provide experimental support for **DeepSeek** models! You can use DeepSeek's official API for cost-effective and high-performance inference. See the configuration example below for DeepSeek setup.
Option 1: Unified API base for both models
------------------------------------------
..code-block::Properties
# Set to any model supported by LiteLLM.
CHAT_MODEL=gpt-4o
EMBEDDING_MODEL=text-embedding-3-small
# Configure unified API base
# The backend api_key fully follows the convention of litellm.
OPENAI_API_BASE=<your_unified_api_base>
OPENAI_API_KEY=<replace_with_your_openai_api_key>
Option 2: Separate API bases for Chat and Embedding models
-`EMBEDDING_MODEL`: The model name of the embedding model.
-`OPENAI_API_BASE`: The base URL of the API. If `EMBEDDING_MODEL` does not start with `litellm_proxy/`, this is used for both chat and embedding models; otherwise, it is used for `CHAT_MODEL` only.
Optional parameters (required if your embedding model is provided by a different provider than `CHAT_MODEL`):
-`LITELLM_PROXY_API_KEY`: The API key for the embedding model, required if `EMBEDDING_MODEL` starts with `litellm_proxy/`.
-`LITELLM_PROXY_API_BASE`: The base URL for the embedding model, required if `EMBEDDING_MODEL` starts with `litellm_proxy/`.
**Note:** If you are using an embedding model from a provider different from the chat model, remember to add the `litellm_proxy/` prefix to the `EMBEDDING_MODEL` name.
The `CHAT_MODEL` and `EMBEDDING_MODEL` parameters will be passed into LiteLLM's completion function.
Therefore, when utilizing models provided by different providers, first review the interface configuration of LiteLLM. The model names must match those allowed by LiteLLM.
Additionally, you need to set up the the additional parameters for the respective model provider, and the parameter names must align with those required by LiteLLM.
For example, if you are using a DeepSeek model, you need to set as follows:
..code-block::Properties
# For some models LiteLLM requires a prefix to the model name.
Besides, when you are using reasoning models, the response might include the thought process. For this case, you need to set the following environment variable:
.. code-block:: Properties
REASONING_THINK_RM=True
For more details on LiteLLM requirements, refer to the `official LiteLLM documentation <https://docs.litellm.ai/docs>`_.
Configuration Example 2: Azure OpenAI Setup
-------------------------------------------
Here’s a sample configuration specifically for Azure OpenAI, based on the `official LiteLLM documentation <https://docs.litellm.ai/docs>`_:
If you're using Azure OpenAI, below is a working example using the Python SDK, following the `LiteLLM Azure OpenAI documentation <https://docs.litellm.ai/docs/providers/azure/>`_:
messages=[{ "content": "Hello, how are you?", "role": "user" }]
)
To align with the Python SDK example above, you can configure the `CHAT_MODEL` based on the `response` model setting and use the corresponding `os.environ` variables by writing them into your local `.env` file as follows:
Coder Environment Configuration (Docker vs. Conda)
RD-Agent's coders can execute code in different environments. You can control this behavior by setting environment variables in your ``.env`` file. This is useful for switching between a local Conda environment and an isolated Docker container.
To configure the environment, add the corresponding line to your ``.env`` file based on the scenario you are running.
**For the Model (Quant) Scenario:**
The execution environment is determined by the ``MODEL_COSTEER_ENV_TYPE`` variable, which is read from ``rdagent/components/coder/model_coder/conf.py``.
***To use Docker** (recommended for isolated execution):
.. code-block:: properties
MODEL_COSTEER_ENV_TYPE=docker
***To use Conda** (for running in a local Conda environment):
.. code-block:: properties
MODEL_COSTEER_ENV_TYPE=conda
**For the Data Science Scenario:**
The execution environment is determined by the ``DS_CODER_COSTEER_ENV_TYPE`` variable, which is read from ``rdagent/components/coder/data_science/conf.py``.
***To use Docker** (recommended for isolated execution):
.. code-block:: properties
DS_CODER_COSTEER_ENV_TYPE=docker
***To use Conda** (for running in a local Conda environment):
.. code-block:: properties
DS_CODER_COSTEER_ENV_TYPE=conda
Custom Time Segment Configuration (Train / Valid / Test)
CHAT_AZURE_API_BASE=# The endpoint for the Azure OpenAI API.
CHAT_AZURE_API_VERSION=# The version of the Azure OpenAI API.
CHAT_MODEL=# The model name of the Azure OpenAI API.
Use Azure Token Provider
------------------------
If you are using the Azure token provider, you need to set the `USE_AZURE_TOKEN_PROVIDER` environment variable to `True`. then
If you are using the Azure token provider, you need to set the `CHAT_USE_AZURE_TOKEN_PROVIDER` and `EMBEDDING_USE_AZURE_TOKEN_PROVIDER` environment variable to `True`. then
use the environment variables provided in the `Azure Configuration section <installation_and_configuration.html#azure-openai>`_.
For users' convenience, we provide a CLI interface called `rdagent`, which automatically runs `load_dotenv()` to load environment variables from the `.env` file.
However, this feature is not enabled by default for other scripts. We recommend users load the environment with the following steps:
- ⚙️ Environment Configuration
- Place the `.env` file in the same directory as the `.env.example` file.
- The `.env.example` file contains the environment variables required for users using the OpenAI API (Please note that `.env.example` is an example file. `.env` is the one that will be finally used.)
- Export each variable in the .env file:
.. code-block:: sh
export $(grep -v '^#' .env | xargs)
- If you want to change the default environment variables, you can refer to the above configuration and edith the `.env` file.
In modern industry, research and development (R&D) is crucial for the enhancement of industrial productivity, especially in the AI era, where the core aspects of R&D are mainly focused on data and models. We are committed to automate these high-value generic R&D processes through our open source R&D automation tool RDAgent, which let AI drive data-driven AI.
Benchmarking the capabilities of the R&D is a very important research problem of the research area.
Currently we are continuously exploring how to benchmark them.
The current benchmarks are listed in this page
Benchmarking the capabilities of R&D is a crucial research problem in this area. We are continuously exploring methods to benchmark these capabilities. The current benchmarks are listed on this page.
Development Capability Benchmarking
===================================
Benchmark is used to evaluate the effectiveness of factors with fixed data.
It mainly includes the following steps:
Benchmarking is used to evaluate the effectiveness of factors with fixed data. It mainly includes the following steps:
1.:ref:`read and prepare the eval_data <data>`
@@ -27,34 +18,31 @@ It mainly includes the following steps:
3.:ref:`declare the eval method and pass the arguments <config>`
The default value for ``bench_test_round`` is 10, and it will take about 2 hours to run 10 rounds.
To modify it from ``10`` to ``2`` you can adjust this by adding environment variables in the .env file as shown below.
The default value for ``bench_test_round`` is 10, which takes about 2 hours to run. To modify it from ``10`` to ``2``, adjust the environment variables in the .env file as shown below.
..code-block::Properties
BENCHMARK_BENCH_TEST_ROUND=1
BENCHMARK_BENCH_TEST_ROUND=2
Data Format
-------------
.._data:
The sample data in ``bench_data_path`` is a dictionary where each key represents a factor name.
The value associated with each key is factor data containing the following information:
The sample data in ``bench_data_path`` is a dictionary where each key represents a factor name. The value associated with each key is factor data containing the following information:
-**description**: A textual description of the factor.
-**formulation**: A LaTeX formula representing the model's formulation.
@@ -63,22 +51,24 @@ The value associated with each key is factor data containing the following infor
-**Difficulty**: The difficulty level of implementing or understanding the factor.
-**gt_code**: A piece of code associated with the factor.
Ensure the data is placed in the ``FACTOR_COSTEER_SETTINGS.data_folder_debug``. The data files should be in ``.h5`` or ``.md`` format and must not be stored in any subfolders. LLM-Agents will review the file content and implement the tasks.
.. TODO: Add a script to automatically generate the data in the `rdagent/app/quant_factor_benchmark/data` folder.
Run Benchmark
-------------
.._run:
Start benchmark after finishing the :doc:`../installation_and_configuration`.
Start the benchmark after completing the :doc:`../installation_and_configuration`.
Once completed, a pkl file will be generated, and its path will be printed on the last line of the console.
@@ -86,18 +76,16 @@ Show Result
-------------
.._show:
The ``analysis.py`` script is used to read data from pkl and convert it to an image.
Modify the python code in ``rdagent/app/quant_factor_benchmark/analysis.py`` to specify the path to the pkl file and the output path for the png file.
The ``analysis.py`` script reads data from the pkl file and converts it to an image. Modify the Python code in ``rdagent/app/quant_factor_benchmark/analysis.py`` to specify the path to the pkl file and the output path for the png file.
To replicate the benchmark detailed in the paper, please consult the factors listed in the following file: `RD2bench.json <../_static/RD2bench.json>`_.
Please note use ``only_correct_format=False`` when evaluating the results.
In the dynamic world of quantitative trading, **factors**are the secret weapons that traders use to harness market inefficiencies.
In the dynamic world of quantitative trading, **factors**serve as the strategic tools that enable traders to exploit market inefficiencies.
These factors—ranging from simple metrics like price-to-earnings ratios to complex models like discounted cash flows—are the key to predicting stock prices with a high degree of accuracy.
These powerful tools—ranging from straightforward metrics like price-to-earnings ratios to intricate discounted cash flow models—unlock the potential to predict stock prices with remarkable precision.
By tapping into this rich vein of data, quantitative traders craft sophisticated strategies that not only capitalize on market patterns but also drastically enhance trading efficiency and accuracy.
By leveraging these factors, quantitative traders can develop sophisticated strategies that not only identify market patterns but also significantly enhance trading efficiency and precision.
The ability to systematically analyze and apply these factors is what separates ordinary trading from truly strategic market outmaneuvering.
And this is where the **Finance Model Agent** comes into play.
Embrace the power of factors, and you're not just trading; you're strategically outsmarting the market.
- Place the `.env` file in the same directory as the `.env.example` file.
- The `.env.example` file contains the environment variables required for users using the OpenAI API (Please note that `.env.example` is an example file. `.env` is the one that will be finally used.)
- Export each variable in the .env file:
.. code-block:: sh
export $(grep -v '^#' .env | xargs)
- If you want to change the default environment variables, you can refer to `Env Config`_ below
- 🚀 Run the Application
.. code-block:: sh
python rdagent/app/qlib_rd_loop/factor_w_sc.py
conda create -n rdagent python=3.10
- Activate the environment:
.. code-block:: sh
conda activate rdagent
- 📦 Install the RDAgent
- You can install the RDAgent package from PyPI:
..code-block::sh
pip install rdagent
- 🚀 Run the Application
- You can directly run the application by using the following command:
.. code-block:: sh
rdagent fin_factor
🛠️ Usage of modules
@@ -132,33 +126,13 @@ You can try our demo by running the following command:
-**Env Config**
The following environment variables can be set in the `.env` file to customize the application's behavior:
- **Path to the folder containing private data (default fundamental data in Qlib):**
- Place the `.env` file in the same directory as the `.env.example` file.
- The `.env.example` file contains the environment variables required for users using the OpenAI API (Please note that `.env.example` is an example file. `.env` is the one that will be finally used.)
- Export each variable in the .env file:
.. code-block:: sh
export $(grep -v '^#' .env | xargs)
- Create a new conda environment with Python (3.10 and 3.11 are well tested in our CI):
- If you want to change the default environment variables, you can refer to `Env Config`_ below
The Data Science Agent is an agent that can automatically perform feature engineering and model tuning. It can be used to solve various data science problems, such as image classification, time series forecasting, and text classification.
🌟 Introduction
~~~~~~~~~~~~~~~~~~
In this scenario, our automated system proposes hypothesis, choose action, implements code, conducts validation, and utilizes feedback in a continuous, iterative process.
The goal is to automatically optimize performance metrics within the validation set or Kaggle Leaderboard, ultimately discovering the most efficient features and models through autonomous research and development.
Here's an enhanced outline of the steps:
**Step 1 : Hypothesis Generation 🔍**
- Generate and propose initial hypotheses based on previous experiment analysis and domain expertise, with thorough reasoning and financial justification.
**Step 2 : Experiment Creation ✨**
- Transform the hypothesis into a task.
- Choose a specific action within feature engineering or model tuning.
- Develop, define, and implement a new feature or model, including its name, description, and formulation.
**Step 3 : Model/Feature Implementation 👨💻**
- Implement the model code based on the detailed description.
- Evolve the model iteratively as a developer would, ensuring accuracy and efficiency.
**Step 4 : Validation on Test Set or Kaggle 📉**
- Validate the newly developed model using the test set or Kaggle dataset.
- Assess the model's effectiveness and performance based on the validation results.
**Step 5: Feedback Analysis 🔍**
- Analyze validation results to assess performance.
- Use insights to refine hypotheses and enhance the model.
**Step 6: Hypothesis Refinement ♻️**
- Adjust hypotheses based on validation feedback.
- Iterate the process to continuously improve the model.
📖 Data Science Background
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the evolving landscape of artificial intelligence, **Data Science** represents a powerful paradigm where machines engage in autonomous exploration, hypothesis testing, and model development across diverse domains — from healthcare and finance to logistics and research.
The **Data Science** Agent stands as a central engine in this transformation, enabling users to automate the entire machine learning workflow: from hypothesis generation to code implementation, validation, and refinement — all guided by performance feedback.
By leveraging the **Data Science** Agent, researchers and developers can accelerate experimentation cycles. Whether fine-tuning custom models or competing in high-stakes benchmarks like Kaggle, the Data Science Agent unlocks new frontiers in intelligent, self-directed discovery.
🧭 Example Guide - Customized dataset
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
🔧 **Set up RD-Agent Environment**
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Before you start, please make sure you have installed RD-Agent and configured the environment for RD-Agent correctly. If you want to know how to install and configure the RD-Agent, please refer to the `documentation <../installation_and_configuration.html>`_.
- 🔩 **Setting the Environment variables at .env file**
- Determine the path where the data will be stored and add it to the ``.env`` file.
.. code-block:: sh
dotenv set DS_LOCAL_DATA_PATH <your local directory>/ds_data
dotenv set DS_SCEN rdagent.scenarios.data_science.scen.DataScienceScen
📥 **Prepare Customized datasets**
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- A data science competition dataset usually consists of two parts: ``competition dataset`` and ``evaluation dataset``. (We provide `a sample <https://github.com/microsoft/RD-Agent/tree/main/rdagent/scenarios/data_science/example>`_ of a customized dataset named: `arf-12-hours-prediction-task as a reference`.)
- The ``evaluation dataset`` contains **standard answer file**, **data checking codes**, and **Code for calculation of scores**.
- We use the ``arf-12-hours-prediction-task`` data as a sample to introduce the preparation workflow for the competition dataset.
- Create a ``ds_data/source_data/arf-12-hours-prediction-task`` folder, which will be used to store your raw dataset.
- The raw files for the competition ``arf-12-hours-prediction-task`` have two files: ``ARF_12h.csv`` and ``X.npz``.
- Create a ``ds_data/source_data/arf-12-hours-prediction-task/prepare.py`` file that splits your raw data into **training data**, **test data**, **formatted submission file**, and **standard answer file**. (You will need to write a script based on your raw data.)
- The following shows the preprocessing code for the raw data of ``arf-12-hours-prediction-task``.
- Create a ``ds_data/eval/arf-12-hours-prediction-task/valid.py`` file, which is used to check the validity of the submission files to ensure that their formatting is consistent with the reference file.
- The following shows a script that checks the validity of a submission based on the ``arf-12-hours-prediction-task`` data.
- Create a ``ds_data/eval/arf-12-hours-prediction-task/grade.py`` file, which is used to calculate the score based on the submission file and the **standard answer file**, and output the result in JSON format.
- The following shows a grading script based on the ``arf-12-hours-prediction-task`` data implementation.
- At this point, you have created a complete dataset. The correct structure of the dataset should look like this.
.. code-block:: text
ds_data
├── arf-12-hours-prediction-task
│ ├── train
│ │ ├── ARF_12h.csv
│ │ └── X.npz
│ ├── test
│ │ ├── ARF_12h.csv
│ │ └── X.npz
│ ├── description.md
│ ├── sample_submission.csv
│ └── sample.py
├── eval
│ └── arf-12-hours-prediction-task
│ ├── grade.py
│ ├── submission_test.csv
│ └── valid.py
└── source_data
└── arf-12-hours-prediction-task
├── ARF_12h.csv
├── prepare.py
└── X.npz
- The above shows the complete dataset creation workflow, some of the files are not required, in practice you can customize the dataset according to your own needs.
- If we don't need the test set scores, then we can choose not to generate **formatted submission files** and **standard answer file** in the prepare code, and we don't need to write **data checking codes** and **Code for calculation of scores**.
- **Data sampling code** can also be created according to the actual need, if you do not provide **data sampling code**, RD-Agent will be handed over to the LLM sampling at runtime.
- In the default sampling method (``create_debug_data``), the default sampling ratio (parameter: ``min_frac``) is 1%, if 1% of the data is less than 5, then 5 data will be sampled (parameter: ``min_num``), you can adjust the sampling ratio by adjusting these two parameters.
- If you have customized data sampling code, you need to set ``DS_SAMPLE_DATA_BY_LLM`` to ``False`` (default is True) in the ``.env`` file before running, so that the program will use the customized sampling code when running, and you can just execute this line of code in the command line:
.. code-block:: sh
dotenv set DS_SAMPLE_DATA_BY_LLM False
- In addition, we provide a data sampling method in `rdagent.scenarios.data_science.debug.data.create_debug_data <https://github.com/microsoft/RD-Agent/blob/main/rdagent/scenarios/data_science/debug/data.py#L605>`_, in this method, the default sampling ratio (parameter: ``min_frac``) is 1%, if 1% of the data is less than 5, then 5 data will be sampled (parameter: ``min_num``), you can use this method by the following two ways.
- You can set ``DS_SAMPLE_DATA_BY_LLM`` to ``False`` in the ``.env`` file so that when the program runs, it will use the sampling code provided by RD-Agent.
.. code-block:: sh
dotenv set DS_SAMPLE_DATA_BY_LLM False
- If you think that the parameters in the receipt sampling method provided by RD-Agent are not suitable, you can customize the parameters in the following command and run it, and set ``DS_SAMPLE_DATA_BY_LLM`` to ``False`` in the ``.env`` so that the program will use the sampling data you provided when running.
.. code-block:: sh
python rdagent/app/data_science/debug.py --dataset_path <dataset path> --competition <competiton_name> --min_frac <sampling ratio> --min_num <minimum number of sampling>
dotenv set DS_SAMPLE_DATA_BY_LLM False
- If you don't need the scores from the test set and leave the data sampling to the LLM, or if you use the sampling method provided by the RD-Agent, you only need to prepare a minimal dataset. The structure of the simplest dataset should be as shown below.
.. code-block:: text
ds_data
├── arf-12-hours-prediction-task
│ ├── train
│ │ ├── ARF_12h.csv
│ │ └── X.npz
│ ├── test
│ │ ├── ARF_12h.csv
│ │ └── X.npz
│ └── description.md
└── source_data
└── arf-12-hours-prediction-task
├── ARF_12h.csv
├── prepare.py
└── X.npz
- We have prepared a dataset based on the above description for your reference. You can download it with the following command.
- Then you can input the log path and visualize the R&D process.
- 🧪 Scoring the test results
- Finally, shutdown the program, and get the test set scores with this command.
.. code-block:: sh
dotenv run -- python rdagent/log/mle_summary.py grade <url_to_log>
Here, <url_to_log> refers to the parent directory of the log folder generated during the run.
🕹️ Kaggle Agent
~~~~~~~~~~~~~~~~
📖 Background
^^^^^^^^^^^^^^
In the landscape of data science competitions, Kaggle serves as the ultimate arena where data enthusiasts harness the power of algorithms to tackle real-world challenges.
The Kaggle Agent stands as a pivotal tool, empowering participants to seamlessly integrate cutting-edge models and datasets, transforming raw data into actionable insights.
By utilizing the **Kaggle Agent**, data scientists can craft innovative solutions that not only uncover hidden patterns but also drive significant advancements in predictive accuracy and model robustness.
🧭 Example Guide - Kaggle Dataset
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
🛠️ Preparing For The Competition
""""""""""""""""""""""""""""""""""
- 🔨 **Configuring the Kaggle API**
- Register and login on the `Kaggle <https://www.kaggle.com/>`_ website.
- Click on the avatar (usually in the top right corner of the page) -> ``Settings`` -> ``Create New Token``, A file called ``kaggle.json`` will be downloaded.
- Move ``kaggle.json`` to ``~/.config/kaggle/``
- Modify the permissions of the ``kaggle.json`` file.
..code-block::sh
chmod 600 ~/.config/kaggle/kaggle.json
- For more information about Kaggle API Settings, refer to the `Kaggle API <https://github.com/Kaggle/kaggle-api>`_.
- 🔩 **Setting the Environment variables at .env file**
- Determine the path where the data will be stored and add it to the ``.env`` file.
.. code-block:: sh
mkdir -p <your local directory>/ds_data
dotenv set KG_LOCAL_DATA_PATH <your local directory>/ds_data
- 📘 More Environment Variables (Optional)
- If you want to see all the available environment variables, you can refer to the configuration file for Data Science scenarios:
- These variables allow you to have finer-grained control in Data Science scenarios.
- 🗳️ **Join the competition**
- If your Kaggle API account has not joined a competition, you will need to join the competition before running the program.
- At the bottom of the competition details page, you can find the ``Join the competition`` button, click on it and select ``I Understand and Accept`` to join the competition.
- In the **Competition List Available** below, you can jump to the competition details page.
📥 Preparing Competition DataDataset && Set up RD-Agent Environment
- As a subset of data science, kaggle's dataset still follows the data science format. Based on this, the kaggle dataset can be divided into two categories depending on whether or not it is supported by the **MLE-Bench**.
- What is **MLE-Bench**?
- **MLE-Bench** is a comprehensive benchmark designed to evaluate the **machine learning engineering** capabilities of AI systems using real-world scenarios. The dataset includes multiple Kaggle competitions. Since Kaggle does not provide reserved test sets for these competitions, the benchmark includes preparation scripts for splitting publicly available training data into new training and test sets, and scoring scripts for each competition to accurately evaluate submission scores.
- I'm running a competition Is **MLE-Bench** supported?
- You can see all the competitions supported by **MLE-Bench**`here <https://github.com/openai/mle-bench/tree/main/mlebench/competitions>`_.
- Prepare datasets for **MLE-Bench** supported competitions.
- If you agree with the **MLE-Bench** standard, then you don't need to prepare the dataset, you just need to configure your ``.env`` file to automate the download of the dataset.
- Configure environment variables, add ``DS_IF_USING_MLE_DATA`` to environment variables, and set it to ``True``.
.. code-block:: sh
dotenv set DS_IF_USING_MLE_DATA True
- Configure environment variables, add ``DS_SAMPLE_DATA_BY_LLM`` to environment variables, and set it to ``True``.
.. code-block:: sh
dotenv set DS_SAMPLE_DATA_BY_LLM True
- Configure environment variables, add ``DS_SCEN`` to environment variables, and set it to ``rdagent.scenarios.data_science.scen.KaggleScen``.
.. code-block:: sh
dotenv set DS_SCEN rdagent.scenarios.data_science.scen.KaggleScen
- At this point, you are ready to start running your competition, which will automatically download the data, and the LLM will automatically extract the minimum dataset.
- After running the program the structure of the ds_data folder should look like this (Using the ``tabular-playground-series-dec-2021`` contest as an example).
.. code-block:: text
ds_data
├── tabular-playground-series-dec-2021
│ ├── description.md
│ ├── sample_submission.csv
│ ├── test.csv
│ └── train.csv
└── zip_files
└── tabular-playground-series-dec-2021
└── tabular-playground-series-dec-2021.zip
- The ``ds_data/zip_files`` folder contains a zip file of the raw competition data downloaded from kaggle website.
- At runtime, RD-Agent will automatically build the Docker image specified at `rdagent/scenarios/kaggle/docker/mle_bench_docker/Dockerfile <https://github.com/microsoft/RD-Agent/blob/main/rdagent/scenarios/kaggle/docker/mle_bench_docker/Dockerfile>`_. This image is responsible for downloading the required datasets and grading files for MLE-Bench.
Note: The first run may take longer than subsequent runs as the Docker image and data are being downloaded and set up for the first time.
- Prepare datasets for competitions that are not supported by **MLE-Bench**.
- As a subset of data science, we can follow the format and steps of data science dataset to prepare kaggle dataset. Below we will describe the workflow for preparing a kaggle dataset using the competition ``playground-series-s4e9`` as an example.
- Create a ``ds_data/source_data/playground-series-s4e9`` folder, which will be used to store your raw dataset.
- The raw files for the competition ``playground-series-s4e9`` have two files: ``train.csv``, ``test.csv``, ``sample_submission.csv``, and there are two ways to get the raw data:
- You can find the raw data required for the competition on the `official kaggle website <https://www.kaggle.com/competitions/playground-series-s4e9/data>`_.
- Or you can use the command line to download the raw data for the competition, the download command is as follows.
- Create a ``ds_data/source_data/playground-series-s4e9/prepare.py`` file that splits your raw data into **training data**, **test data**, **formatted submission file**, and **standard answer file**. (You will need to write a script based on your raw data.)
- The following shows the preprocessing code for the raw data of ``playground-series-s4e9``.
- At the end of program execution, the ``ds_data`` folder structure will look like this:
..code-block::text
ds_data
├── playground-series-s4e9
│ ├── train.csv
│ ├── test.csv
│ └── sample_submission.csv
├── eval
│ └── playground-series-s4e9
│ └── submission_test.csv
└── source_data
└── playground-series-s4e9
├── prepare.py
├── sample_submission.csv
├── test.csv
└── train.csv
- Create a ``ds_data/playground-series-s4e9/description.md`` file to describe your competition, dataset description, and other information. We can find the `competition description information <https://www.kaggle.com/competitions/playground-series-s4e9/overview>`_ and the `dataset description information <https://www.kaggle.com/competitions/playground-series-s4e9/data>`_ from the Kaggle website.
- The following shows the description file for ``playground-series-s4e9``
- Create a ``ds_data/eval/playground-series-s4e9/valid.py`` file, which is used to check the validity of the submission files to ensure that their formatting is consistent with the reference file.
- The following shows a script that checks the validity of a submission based on the ``playground-series-s4e9`` data.
- Create a ``ds_data/eval/playground-series-s4e9/grade.py`` file, which is used to calculate the score based on the submission file and the **standard answer file**, and output the result in JSON format.
- The following shows a grading script based on the ``playground-series-s4e9`` data implementation.
- Next, we need to configure the environment for the ``playground-series-s4e9`` contest. You can do this by executing the following command at the command line.
.. code-block:: sh
dotenv set DS_IF_USING_MLE_DATA False
dotenv set DS_SAMPLE_DATA_BY_LLM False
dotenv set DS_SCEN rdagent.scenarios.data_science.scen.KaggleScen
🚀 **Run the Application**
""""""""""""""""""""""""""""""""""""
- 🌏 You can directly run the application by using the following command:
- Then you can input the log path and visualize the R&D process.
- 🧪 Scoring the test results
- Finally, shutdown the program, and get the test set scores with this command.
.. code-block:: sh
dotenv run -- python rdagent/log/mle_summary.py grade <url_to_log>
- If you have configured the full output in ``ds_data/eval/playground-series-s4e9/grade.py``, or if you are running a competition that receives **MLE-Bench** support, you can also summarize the scores by running the following command.
.. code-block:: sh
rdagent grade_summary --log-folder=<url_to_log>
Here, <url_to_log> refers to the parent directory of the log folder generated during the run.
## **🎯 Scenario: Continue Training on a Pre-trained Model**
In this workflow the **Data Science Agent** starts from a *previously trained* model (and its training script), performs additional fine-tuning on new data, and then re-uses the updated weights for subsequent inference runs.
🚧 Directory Structure
Your competition folder (here called ``custom_data``) must contain **one extra sub-directory** named ``prev_model`` where you keep the old weights and the code that produced them:
- MLE-bench is a comprehensive benchmark designed to evaluate the ML engineering capabilities of AI systems using real-world scenarios. The dataset comprises 75 Kaggle competitions. Since Kaggle does not provide held-out test sets for these competitions, the benchmark includes preparation scripts that split the publicly available training data into new training and test sets, and grading scripts are provided for each competition to accurately evaluate submission scores.
- 🔧 **Set up Environment for MLE-bench**
- Running R&D-Agent on MLE-bench is designed for full automation. There is no need for manual downloads and data preparation. Simply set the environment variable ``DS_IF_USING_MLE_DATA`` to True.
- At runtime, R&D-Agent will automatically build the Docker image specified at ``rdagent/scenarios/kaggle/docker/mle_bench_docker/Dockerfile``. This image is responsible for downloading the required datasets and grading files for MLE-bench.
- Note: The first run may take longer than subsequent runs as the Docker image and data are being downloaded and set up for the first time.
..code-block::sh
dotenv set DS_LOCAL_DATA_PATH <your local directory>/ds_data
dotenv set DS_IF_USING_MLE_DATA True
- 🔨 **Configuring the Kaggle API**
- Downloading Kaggle competition data requires the Kaggle API. You can set up the Kaggle API by following these steps:
- Register and login on the `Kaggle <https://www.kaggle.com/>`_ website.
- Click on the avatar (usually in the top right corner of the page) -> ``Settings`` -> ``Create New Token``, A file called ``kaggle.json`` will be downloaded.
- Move ``kaggle.json`` to ``~/.config/kaggle/``
- Modify the permissions of the ``kaggle.json`` file.
.. code-block:: sh
chmod 600 ~/.config/kaggle/kaggle.json
- For more information about Kaggle API Settings, refer to the `Kaggle API <https://github.com/Kaggle/kaggle-api>`_.
- 🔩 **Setting the Environment Variables for MLE-bench**
- In addition to auto-downloading the benchmark data, you must also configure the runtime environment for executing the competition code.
- Use the environment variable ``DS_CODER_COSTEER_ENV_TYPE`` to select the execution mode:
• When set to docker (the default), RD-Agent utilizes the official Kaggle Docker image (``gcr.io/kaggle-gpu-images/python:latest``) to ensure that all required packages are available.
• If you prefer to use a custom Docker setup, you can modify the configuration using ``DS_DOCKER_IMAGE`` or ``DS_DOCKERFILE_FOLDER_PATH``.
• Alternatively, if your competition work only demands basic libraries, you may set ``DS_CODER_COSTEER_ENV_TYPE`` to conda. In this mode, you must create a local conda environment named “kaggle” and pre-install the necessary packages. RD-Agent will execute the competition code within this “kaggle” conda environment.
..code-block::sh
# Configure the runtime environment: choice between 'docker' (default) or 'conda'
dotenv set DS_CODER_COSTEER_ENV_TYPE docker
-**Additional Guidance**
-**Combine different LLM Models at R&D Stage**
- You can combine different LLM models at the R&D stage.
- By default, when you set environment variable ``CHAT_MODEL``, it covers both R&D stages. When customizing the model for the development stage, you can set:
..code-block::sh
# This example sets the model to "o3-mini". For some models, the reasoning effort shoule be set to "None".
dotenv set LITELLM_CHAT_MODEL_MAP '{"coding":{"model":"o3-mini","reasoning_effort":"high"},"running":{"model":"o3-mini","reasoning_effort":"high"}}'
In the realm of quantitative finance, both factor discovery and model development play crucial roles in driving performance.
While much attention is often given to the discovery of new financial factors, the **models** that leverage these factors are equally important.
The effectiveness of a quantitative strategy depends not only on the factors used but also on how well these factors are integrated into robust, predictive models.
🎥 Demo
~~~~~~~~~~
TODO: Here should put a video of the demo.
However, the process of developing and optimizing these models can be labor-intensive and complex, requiring continuous refinement and adaptation to ever-changing market conditions.
And this is where the **Finance Model Agent** steps in.
In this scenario, our automated system proposes hypothesis, constructs model, implements code, receives back-testing, and uses feedbacks.
Hypothesis is iterated in this continuous process.
The system aims to automatically optimise performance metrics from Qlib library thereby finding the optimised code through autonomous research and development.
In this scenario, our automated system proposes hypothesis, constructs model, implements code, conducts back-testing, and utilizes feedback in a continuous, iterative process.
The goal is to automatically optimize performance metrics within the Qlib library, ultimately discovering the most efficient code through autonomous research and development.
Here's an enhanced outline of the steps:
@@ -69,51 +83,68 @@ Here's an enhanced outline of the steps:
⚡ Quick Start
~~~~~~~~~~~~~~~~~
Please refer to the installation part in :doc:`../installation_and_configuration` to prepare your system dependency.
You can try our demo by running the following command:
- 🐍 Create a Conda Environment
- Create a new conda environment with Python (3.10 and 3.11 are well tested in our CI):
- Create a new conda environment with Python (3.10 and 3.11 are well tested in our CI):
.. code-block:: sh
..code-block::sh
conda create -n rdagent python=3.10
conda create -n rdagent python=3.10
- Activate the environment:
- Activate the environment:
..code-block::sh
conda activate rdagent
- 🛠️ Run Make Files
- Navigate to the directory containing the MakeFile and set up the development environment:
- Place the `.env` file in the same directory as the `.env.example` file.
- The `.env.example` file contains the environment variables required for users using the OpenAI API (Please note that `.env.example` is an example file. `.env` is the one that will be finally used.)
- Export each variable in the .env file:
.. code-block:: sh
export $(grep -v '^#' .env | xargs)
- 🚀 Run the Application
.. code-block:: sh
python rdagent/app/qlib_rd_loop/model_w_sc.py
conda activate rdagent
- 📦 Install the RDAgent
- You can install the RDAgent package from PyPI:
..code-block::sh
pip install rdagent
- 🚀 Run the Application
- You can directly run the application by using the following command:
.. code-block:: sh
rdagent fin_model
🛠️ Usage of modules
~~~~~~~~~~~~~~~~~~~~~
TODO: Show some examples:
.._Env Config:
-**Env Config**
The following environment variables can be set in the `.env` file to customize the application's behavior:
- The `config.yaml` file located in the `model_template` folder contains the relevant configurations for running the developed model in Qlib. The default settings include key information such as:
- **market**: Specifies the market, which is set to `csi300`.
- **fields_group**: Defines the fields group, with the value `feature`.
- **col_list**: A list of columns used, including various indicators such as `RESI5`, `WVMA5`, `RSQR5`, and others.
- **start_time**: The start date for the data, set to `2008-01-01`.
- **end_time**: The end date for the data, set to `2020-08-01`.
- **fit_start_time**: The start date for fitting the model, set to `2008-01-01`.
- **fit_end_time**: The end date for fitting the model, set to `2014-12-31`.
- The default hyperparameters used in the configuration are as follows:
-**n_epochs**: The number of epochs, set to `100`.
-**lr**: The learning rate, set to `1e-3`.
-**early_stop**: The early stopping criterion, set to `10`.
-**batch_size**: The batch size, set to `2000`.
-**metric**: The evaluation metric, set to `loss`.
-**loss**: The loss function, set to `mse`.
-**n_jobs**: The number of parallel jobs, set to `20`.
- Place the `.env` file in the same directory as the `.env.example` file.
- The `.env.example` file contains the environment variables required for users using the OpenAI API (Please note that `.env.example` is an example file. `.env` is the one that will be finally used.)
- Export each variable in the .env file:
.. code-block:: sh
export $(grep -v '^#' .env | xargs)
- 🚀 Run the Application
- Prepare relevant files (in pdf format) by uploading papers to the directory below and copy the path as report_file_path.
..code-block::sh
rdagent/scenarios/general_model
- Run the following command in your terminal within the same virtual environment:
- Prepare relevant files (in pdf format) by uploading papers to the directory below and copy the path as report_file_path.
.. code-block:: sh
.. code-block:: sh
rdagent/scenarios/general_model
- Run the following command in your terminal within the same virtual environment:
There are mainly two modules in this scenario: one that reads the paper and returns a model card & one that reads the model card and returns functional code. The moduldes can also be used separately as components for developers to build up new scenarios.
- Configurations
- The `config.yaml` file located in the `model_template` folder contains the relevant configurations for running the developed model in Qlib. The default settings include key information such as:
- **market**: Specifies the market, which is set to `csi300`.
- **fields_group**: Defines the fields group, with the value `feature`.
- **col_list**: A list of columns used, including various indicators such as `RESI5`, `WVMA5`, `RSQR5`, and others.
- **start_time**: The start date for the data, set to `2008-01-01`.
- **end_time**: The end date for the data, set to `2020-08-01`.
- **fit_start_time**: The start date for fitting the model, set to `2008-01-01`.
- **fit_end_time**: The end date for fitting the model, set to `2014-12-31`.
- The default hyperparameters used in the configuration are as follows:
-**n_epochs**: The number of epochs, set to `100`.
-**lr**: The learning rate, set to `1e-3`.
-**early_stop**: The early stopping criterion, set to `10`.
-**batch_size**: The batch size, set to `2000`.
-**metric**: The evaluation metric, set to `loss`.
-**loss**: The loss function, set to `mse`.
- **n_jobs**: The number of parallel jobs, set to `20`.
R&D-Agent for Quantitative Finance, in short **RD-Agent(Q)**, is the first data-centric, multi-agent framework designed to automate the full-stack research and development of quantitative strategies via coordinated factor-model co-optimization.
You can learn more details about **RD-Agent(Q)** through the `paper <https://arxiv.org/abs/2505.15155>`_.
⚡ Quick Start
~~~~~~~~~~~~~~~~~
Before you start, please make sure you have installed RD-Agent and configured the environment for RD-Agent correctly. If you want to know how to install and configure the RD-Agent, please refer to the `documentation <../installation_and_configuration.html>`_.
Then, you can run the framework by running the following command:
- 🐍 Create a Conda Environment
- Create a new conda environment with Python (3.10 and 3.11 are well tested in our CI):
.. code-block:: sh
conda create -n rdagent python=3.10
- Activate the environment:
.. code-block:: sh
conda activate rdagent
- 📦 Install the RDAgent
- You can install the RDAgent package from PyPI:
..code-block::sh
pip install rdagent
- 🚀 Run the Application
- You can directly run the application by using the following command:
.. code-block:: sh
rdagent fin_quant
🛠️ Usage of modules
~~~~~~~~~~~~~~~~~~~~~
.._Env Config:
-**Env Config**
The following environment variables can be set in the `.env` file to customize the application's behavior:
- The `.yaml` files in both the `model_template` and `factor_template` directories contain some configurations for running the corresponding models or factors within the Qlib framework. Below is an overview of their contents and roles:
- **General Settings**:
- **provider_uri**: Specifies the local Qlib data path, set to `~/.qlib/qlib_data/cn_data`.
- **market**: Configured to `csi300`, representing the CSI 300 index constituents.
- **benchmark**: Set to `SH000300`, used for backtesting evaluation.
- **Data Handling**:
- **start_time** and **end_time**: Define the full data range, from `2008-01-01` to `2022-08-01`.
- **fit_start_time**: The start date for fitting the model, set to `2008-01-01`.
- **fit_end_time**: The end date for fitting the model, set to `2014-12-31`.
- **features and labels**: Generated via a nested data loader combining `Alpha158DL` (for engineered features such as `RESI5`, `WVMA5`, `RSQR5`, `KLEN`, etc.) and a `StaticDataLoader` that loads precomputed factor files (`combined_factors_df.parquet`).
- **normalization**: The pipeline includes `RobustZScoreNorm` (with clipping) and `Fillna` for inference, and `DropnaLabel` with `CSZScoreNorm` for training.
- **Training Configuration**:
- **Model**: Uses `GeneralPTNN`, a PyTorch-based neural network model.
- **Dataset Splits**:
- **train**: `2008-01-01` to `2014-12-31`
- **valid**: `2015-01-01` to `2016-12-31`
- **test**: `2017-01-01` to `2020-08-01`
-**Default Hyperparameters** (can be overridden by command-line arguments):
-**n_epochs**: `100`
-**lr**: `2e-4`
-**early_stop**: `10`
-**batch_size**: `256`
-**weight_decay**: `0.0`
-**metric**: `loss`
-**loss**: `mse`
-**n_jobs**: `20`
-**GPU**: `0` (uses GPU 0 if available)
-**Backtesting and Evaluation**:
-**strategy**: `TopkDropoutStrategy`, which selects the top 50 stocks and randomly drops 5 to introduce exploration.
-**backtest period**: `2017-01-01` to `2020-08-01`
-**initial capital**: `100,000,000`
-**cost configuration**: Includes open/close costs, minimum transaction costs, and slippage control.
-**Recording and Analysis**:
-**SignalRecord**: Logs predicted signals.
-**SigAnaRecord**: Performs signal analysis without long-short separation.
-**PortAnaRecord**: Conducts portfolio analysis using the configured strategy and backtest settings.
streamlit run rdagent/log/ui/app.py --server.port <port> -- --log_dir <log_dir>
rdagent ui --port <port> --log-dir <log_dir like "log/"> [--debug]
This will start a web app on `http://localhost:<port>`.
**NOTE**: The log_dir parameter is not required. You can manually enter the log_path in the web app. If you set the log_dir parameter, you can easily select a different log_path in the web app.
--debug is optional, it will show a "Single Step Run" button in sidebar and saved objects info in the web app.
Use Web App
-----------
1. Open the sidebar.
.. TODO: update these
2. Select the scenario you want to show. There are some pre-defined scenarios:
- Qlib Model
- Qlib Factor
- Data Mining
- Model from Paper
- Kaggle
3. Click the `Config⚙️` button and input the log path (if you set the log_dir parameter, you can select a log_path in the dropdown list).
f"The source dataframe has a datetime index but it is not in the correct format (maybe a regular string or other objects). Please check the implementation.\n The head of the output dataframe is: \n{gen_df.head()}",
f"The source dataframe and the ground truth dataframe have different index with a similarity of {similarity:.2%}. The similarity is calculated by the number of shared indices divided by the union indices. "
return"Both dataframes have the same missing values.",True
else:
return(
f"The dataframes do not have the same missing values. The source dataframe has {gen_df.isna().sum().sum()} missing values, while the ground truth dataframe has {gt_df.isna().sum().sum()} missing values. Please check the implementation.",
f"The dataframes are highly correlated. The ic is {ic:.6f} and the rankic is {ric:.6f}.",
True,
)
else:
return(
f"The dataframes are not sufficiently high correlated. The ic is {ic:.6f} and the rankic is {ric:.6f}. Investigate the factors that might be causing the discrepancies and ensure that the logic of the factor calculation is consistent.",
False,
)
else:
returnf"The ic is ({ic:.6f}) and the rankic is ({ric:.6f}).",ic
classFactorValueEvaluator(FactorEvaluator):
defevaluate(
self,
implementation:Workspace,
gt_implementation:Workspace,
version:int=1,# 1 for qlib factors and 2 for kaggle factors
**kwargs,
)->Tuple:
conclusions=[]
# Initialize result variables
row_result=0
index_result=0
output_format_result=None
equal_value_ratio_result=0
high_correlation_result=False
row_result=None
# Check if both dataframe has only one columns Mute this since factor task might generate more than one columns now
"Output dataframe has more columns than input feature which is not acceptable in feature processing tasks. Please check the implementation to avoid generating too many columns. Consider this implementation as a failure."
feedback_str="The source dataframe and the ground truth dataframe have different index. Give up comparing the values and correlation because it's useless"
Quantitative investment is a data-driven approach to asset management that relies on mathematical models, statistical techniques, and computational methods to analyze financial markets and make investment decisions. Two essential components of this approach are factors and models.
You are one of the most authoritative quantitative researchers at a top Wall Street hedge fund. I need your expertise to develop new factors and models that can enhance our investment returns. Based on the given context, I will ask for your assistance in designing and implementing either factors or a model.
{% if runtime_environment is not none %}
====== Runtime Environment ======
You have following environment to run the code:
{{ runtime_environment }}
{% endif %}
qlib_factor_background:|-
The factor is a characteristic or variable used in quant investment that can help explain the returns and risks of a portfolio or a single asset. Factors are used by investors to identify and exploit sources of excess returns, and they are central to many quantitative investment strategies.
Each number in the factor represents a physics value to an instrument on a day.
User will train a model to predict the next several days return based on the factor values of the previous days.
The factor is defined in the following parts:
1. Name: The name of the factor.
2. Description: The description of the factor.
3. Formulation: The formulation of the factor.
4. Variables: The variables or functions used in the formulation of the factor.
The factor might not provide all the parts of the information above since some might not be applicable.
Please specifically give all the hyperparameter in the factors like the window size, look back period, and so on. One factor should statically defines one output with a static source data. For example, last 10 days momentum and last 20 days momentum should be two different factors.
{% if runtime_environment is not none %}
====== Runtime Environment ======
You have following environment to run the code:
{{ runtime_environment }}
{% endif %}
qlib_factor_interface:|-
Your python code should follow the interface to better interact with the user's system.
CRITICAL DATA FORMAT: The HDF5 file has a MultiIndex with levels ['datetime', 'instrument']. The instrument is an INDEX LEVEL, NOT a column. Never use df['instrument']. Always use df.index.get_level_values('instrument') or df.groupby(level='instrument'). For rolling calculations use df['$close'].unstack(level='instrument'), apply rolling, then .stack() to restore MultiIndex.
Your python code should contain the following part: the import part, the function part, and the main part. You should write a main function name: "calculate_{function_name}" and call this function in "if __name__ == __main__" part. Don't write any try-except block in your python code. The user will catch the exception message and provide the feedback to you.
User will write your python code into a python file and execute the file directly with "python {your_file_name}.py". You should calculate the factor values and save the result into a HDF5(H5) file named "result.h5" in the same directory as your python file. The result file is a HDF5(H5) file containing a pandas dataframe. The index of the dataframe is the "datetime" and "instrument", and the single column name is the factor name,and the value is the factor value. The result file should be saved in the same directory as your python file.
qlib_factor_strategy:|-
Ensure that for every step of data processing, the data format (including indexes) is clearly explained through comments.
Each transformation or calculation should be accompanied by a detailed description of how the data is structured, especially focusing on key aspects like whether the data has multi-level indexing, how to access specific columns or index levels, and any operations that affect the data shape (e.g., `reset_index()`, `groupby()`, `merge()`).
This step-by-step explanation will ensure clarity and accuracy in data handling. For example:
1. **Start with multi-level index**:
```python
# The initial DataFrame has a multi-level index with 'datetime' and 'instrument'.
# To access the 'datetime' index, use df.index.get_level_values('datetime').
Your output should be a pandas dataframe similar to the following example information:
<class 'pandas.core.frame.DataFrame'>
MultiIndex: 2261923 entries, (Timestamp('2020-01-01 17:00:00'), 'EURUSD') to (Timestamp('2026-03-20 15:58:00'), 'EURUSD')
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 your factor name 2261923 non-null float64
dtypes: float64(1)
memory usage: <ignore>
Notice: The non-null count is OK to be different to the total number of entries since some instruments may not have the factor value on some days.
One possible format of `result.h5` may be like following:
datetime instrument
2020-01-01 EURUSD 1.094240
2020-01-02 EURUSD 1.094280
2020-01-03 EURUSD 1.095920
...
2026-03-20 EURUSD 1.083150
qlib_factor_simulator:|-
The factors will be sent into Qlib to train a model to predict the next several days return based on the factor values of the previous days.
Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.
User will use Qlib to automatically do the following things:
1. generate a new factor table based on the factor values.
2. train a model like LightGBM, CatBoost, LSTM or simple PyTorch model to predict the next several days return based on the factor values.
3. build a portfolio based on the predicted return based on a strategy.
4. evaluate the portfolio's performance including the return, sharpe ratio, max drawdown, and so on.
The demo showcases the iterative process of hypothesis generation, knowledge construction, and decision-making. It highlights how financial factors evolve through continuous feedback and refinement.
#### [Automated R&D](#_rdloops)
- **[R (Research)](#_research)**
- Iterative development of ideas and hypotheses.
- Continuous learning and knowledge construction.
- **[D (Development)](#_development)**
- Progressive implementation and code generation of factors.
- Automated testing and validation of financial factors.
#### [Objective](#_summary)
To demonstrate the dynamic evolution of financial factors through the Qlib platform, emphasizing how each iteration enhances the accuracy and reliability of the resulting financial factors.
This demo showcases the process of extracting factors from financial research reports, implementing these factors, and analyzing their performance through Qlib backtest, continually expanding and refining the factor library.
#### [Automated R&D](#_rdloops)
- **[R (Research)](#_research)**
- Iterative development of ideas and hypotheses from financial reports.
- Continuous learning and knowledge construction.
- **[D (Development)](#_development)**
- Progressive factor extraction and code generation.
- Automated implementation and testing of financial factors.
| EURUSD | LGBModel | Alpha158 Plus | Train: 2022-01-01 to 2024-06-30 <br> Valid: 2024-07-01 to 2024-12-31 <br> Test : 2025-01-01 to 2026-03-20 |
qlib_model_background:|-
The model is a machine learning or deep learning structure used in quantitative investment to predict the returns and risks of a portfolio or a single asset. Models are employed by investors to generate forecasts based on historical data and identified factors, which are central to many quantitative investment strategies.
Each model takes the factors as input and predicts the future returns. Usually, the bigger the model is, the better the performance would be.
The model is defined in the following parts:
1. Name: The name of the model.
2. Description: The description of the model.
3. Architecture: The detailed architecture of the model, such as neural network layers or tree structures.
4. Hyperparameters: The hyperparameters used in the model.
5. Training_hyperparameters: The hyperparameters used during the training process.
6. ModelType: The type of the model, "Tabular" for tabular model and "TimeSeries" for time series model.
The model should provide clear and detailed documentation of its architecture and hyperparameters. One model should statically define one output with a fixed architecture and hyperparameters.
{% if runtime_environment is not none %}
====== Runtime Environment ======
You have following environment to run the code:
{{ runtime_environment }}
{% endif %}
qlib_model_interface:|-
Your python code should follow the interface to better interact with the user's system.
You code should contain several parts:
1. The import part: import the necessary libraries.
2. A class which is a sub-class of pytorch.nn.Module. This class should should have a init function and a forward function which inputs a tensor and outputs a tensor.
3. Set a variable called "model_cls" to the class you defined.
The user will save your code into a python file called "model.py". Then the user imports model_cls in file "model.py" after setting the cwd into the directory:
```python
from model import model_cls
```
So your python code should follow the pattern:
```python
class XXXModel(torch.nn.Module):
...
model_cls = XXXModel
```
The model can be configured as either "Tabular" for tabular models or "TimeSeries" for time series models. For a tabular model, the input shape is (batch_size, num_features), while for a time series model, the input shape is (batch_size, num_timesteps, num_features). In both cases, the output shape of the model should be (batch_size, 1).
`num_features` will be directly set for the model based on the input data shape.
User will initialize the tabular model with the following code:
```python
model = model_cls(num_features=num_features)
```
User will initialize the time series model with the following code:
```python
model = model_cls(num_features=num_features, num_timesteps=num_timesteps)
```
No other parameters will be passed to the model so give other parameters a default value or just make them static.
Don't write any try-except block in your python code. The user will catch the exception message and provide the feedback to you. Also, don't write main function in your python code. The user will call the forward method in the model_cls to get the output tensor.
Please notice that your model should only use current features as input. The user will provide the input tensor to the model's forward function.
qlib_model_output_format:|-
Your output should be a tensor with shape (batch_size, 1).
The output tensor should be saved in a file named "output.pth" in the same directory as your python file.
The user will evaluate the shape of the output tensor so the tensor read from "output.pth" should be 8 numbers.
qlib_model_simulator:|-
The models will be sent into Qlib to train and evaluate their performance in predicting future returns. Hypothesis is improved upon checking the feedback on the results.
Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms, including supervised learning, market dynamics modeling, and reinforcement learning (RL).
User will use Qlib to automatically perform the following tasks:
1. Generate a baseline factor table.
2. Train the model defined in your class Net to predict the next several days' returns based on the factor values.
3. Build a portfolio based on the predicted returns using a specific strategy.
4. Evaluate the portfolio's performance, including metrics such as return, IC, max drawdown, and others.
5. Iterate on growing the hypothesis to enable model improvements based on performance evaluations and feedback.
qlib_model_rich_style_description:|-
### Qlib Model Evolving Automatic R&D Demo
#### [Overview](#_summary)
The demo showcases the iterative process of hypothesis generation, knowledge construction, and decision-making in model construction in quantitative finance. It highlights how models evolve through continuous feedback and refinement.
#### [Automated R&D](#_rdloops)
- **[R (Research)](#_research)**
- Iteration of ideas and hypotheses.
- Continuous learning and knowledge construction.
- **[D (Development)](#_development)**
- Evolving code generation and model refinement.
- Automated implementation and testing of models.
#### [Objective](#_summary)
To demonstrate the dynamic evolution of models through the Qlib platform, emphasizing how each iteration enhances the accuracy and reliability of the resulting models.
qlib_model_experiment_setting:|-
| Dataset 📊 | Model 🤖 | Factors 🌟 | Data Split 🧮 |
Here, you need to focus on analyzing whether there are any issues with the training. If any problems are identified, you must correct them in the next iteration and clearly describe how the changes will be made in the hypothesis.
{{ experiment.stdout }}
Observation: {{ feedback.observations }}
Evaluation: {{ feedback.hypothesis_evaluation }}
Decision (Whether this experiment is SOTA): {{ feedback.decision }}
New Hypothesis (Given in feedback stage, just for reference, and can be accepted or rejected in the next round): {{ feedback.new_hypothesis }}
Reasoning (Justification for the new hypothesis): {{ feedback.reason }}
sota_hypothesis_and_feedback:|-
## Hypothesis
{{ experiment.hypothesis }}
## Specific task:
{% for task in experiment.sub_tasks %}
{% if task is not none and task.get_task_brief_information is defined %}
Decision (Whether this experiment is SOTA): {{ feedback.decision }}
hypothesis_output_format:|-
The output should follow JSON format. The schema is as follows:
{
"hypothesis": "An exact, testable, and innovative statement derived from previous experimental trace analysis. Avoid overly general ideas and ensure precision. The hypothesis should clearly specify the exact approach and expected improvement in performance in two or three sentences.",
"reason": "Provide a clear, logical explanation for why this hypothesis was proposed, grounded in evidence (e.g., trace history, domain principles). Reason should be short with no more than two sentences.",
}
factor_hypothesis_output_format:|-
The output should follow JSON format. The schema is as follows:
{
"hypothesis": "The new hypothesis generated based on the information provided. Limit in two or three sentences.",
"reason": "The reason why you generate this hypothesis. It should be comprehensive and logical. It should cover the other keys below and extend them. Limit in two or three sentences.",
}
hypothesis_output_format_with_action:|-
The output should follow JSON format. The schema is as follows:
{
"action": "If `hypothesis_specification` provides the action you need to take, please follow "hypothesis_specification" to choose the action. Otherwise, based on previous experimental results, suggest the action you believe is most appropriate at the moment. It should be one of [`factor`, `model`].",
"hypothesis": "The new hypothesis generated based on the information provided,should be a string.",
"reason": "The reason why you generate this hypothesis. It should be comprehensive and logical. It should cover the other keys below and extend them. Limit in two or three sentences.",
}
model_hypothesis_specification:|-
1. First, observe and analyze the overall experimental progression in `hypothesis_and_feedback`. Analyze where the previous model designs were inadequate — whether it was due to parameter settings, architectural flaws, or a lack of novelty (proposing entirely new concepts is highly encouraged as long as they demonstrate effectiveness).
2. Second, `last_hypothesis_and_feedback` and `sota_hypothesis_and_feedback` are key references you should pay close attention to. You can choose to optimize based on either of them or generate new ideas to form hypotheses and experiments.
3. If there is no prior experiment or result available at the beginning, you can start by implementing a simple and small architecture.
4. If a series of attempts fail to achieve SOTA, consider exploring entirely new directions; at this point, it is acceptable to return to simple architectures.
5. Focus exclusively on the architecture of PyTorch models. Each hypothesis should specifically address architectural decisions, such as layer configurations, activation functions, regularization methods, and overall model structure. DO NOT do any feature-specific processing. Instead, you can propose innovative transformations on the input time-series data to enhance model training effectiveness.
6. Avoid including aspects unrelated to architecture, such as input features or optimization strategies.
7. Sometimes, when training performance is poor, adjusting hyperparameters can also be an effective strategy for improvement.
8. Use standard libraries for baseline models, but also explore custom architecture designs to investigate novel structures. After sufficient trials with traditional models, aim for innovation comparable to top-tier AI conferences (NeurIPS, ICLR, ICML, SIGKDD, etc.) in time series modeling.
factor_hypothesis_specification:|-
You are developing alpha factors for EURUSD intraday trading using 15-minute OHLCV bars.
**Market Context:**
- EURUSD trades 24h with three sessions: Asian (00:00-08:00 UTC), London (08:00-16:00 UTC), NY (13:00-21:00 UTC)
- London-NY overlap (13:00-16:00 UTC) has highest volume and trending behavior
- Daily-frequency assumptions (no overnight gaps in logic)
- Factors with >100 bar lookback without justification
5. No matter how many factors you plan to generate, only reply with one set of hypothesis and reason.
factor_experiment_output_format:|-
The output should follow JSON format. The schema is as follows:
{
"factor name 1": {
"description": "description of factor 1, start with its type, e.g. [Momentum Factor]",
"formulation": "latex formulation of factor 1",
"variables": {
"variable or function name 1": "description of variable or function 1",
"variable or function name 2": "description of variable or function 2"
}
},
"factor name 2": {
"description": "description of factor 2, start with its type, e.g. [Machine Learning based Factor]",
"formulation": "latex formulation of factor 2",
"variables": {
"variable or function name 1": "description of variable or function 1",
"variable or function name 2": "description of variable or function 2"
}
}
# Don't add ellipsis (...) or any filler text that might cause JSON parsing errors here!
}
model_experiment_output_format:|-
So far please only design one model to test the hypothesis!
The output should follow JSON format. The schema is as follows (value in training_hyperparameters is a basic setting for reference, you CAN CHANGE depends on the previous training log):
{
"model_name (The name of the model)": {
"description": "A detailed description of the model",
"formulation": "A LaTeX formula representing the model's formulation",
"architecture": "A detailed description of the model's architecture, e.g., neural network layers or tree structures",
"variables": {
"\\hat{y}_u": "The predicted output for node u",
"variable_name_2": "Description of variable 2",
"variable_name_3": "Description of variable 3"
},
"hyperparameters": {
"hyperparameter_name_1": "value of hyperparameter 1",
"hyperparameter_name_2": "value of hyperparameter 2",
"hyperparameter_name_3": "value of hyperparameter 3"
},
"training_hyperparameters" { # All values are for reference; you can set them yourself
"n_epochs": "100",
"lr": "1e-3",
"early_stop": 10,
"batch_size": 256,
"weight_decay": 1e-4,
}
"model_type": "Tabular or TimeSeries" # Should be one of "Tabular" or "TimeSeries"
},
}
factor_feedback_generation:
system:|-
You are a professional FX quantitative analyst specializing in EURUSD intraday strategies.
The task is described in the following scenario:
{{ scenario }}
You will receive a hypothesis, multiple tasks with their factors, their results, and the SOTA result.
Your feedback should specify whether the current result supports or refutes the hypothesis, compare it with previous SOTA results, and suggest FX-specific improvements.
**FX-specific evaluation criteria:**
- IC > 0.02 is meaningful for 1min EURUSD data
- Annualized return target: >9.62% (current SOTA to beat)
**Note: This factor was not implemented in the current experiment. Only the hypothesis for implemented factors can be verified.**
{% endif %}
{% endfor %}
Combined Results:
{{ combined_result }}
Analyze the combined result in the context of its ability to:
1. Support or refute the hypothesis.
2. Show improvement or deterioration compared to the SOTA experiment.
Note: Only factors with 'Factor Implementation' as True are implemented and tested in this experiment. If 'Factor Implementation' is False, the hypothesis for that factor cannot be verified in this run.
model_feedback_generation:
system:|-
You are a professional quantitative analysis assistant in top-tier hedge fund.
The task is described in the following scenario:
{{ scenario }}
You will receive a quantitative model hypothesis, its specific task description, and it market backtest result.
Your feedback should specify whether the current result supports or refutes the hypothesis, compare it with previous SOTA results, examine the model's training logs to analyze whether there are issues with hyperparameter settings, and suggest improvements or new directions.
Please provide detailed and constructive feedback.
Example JSON Structure for Result Analysis:
{
"Observations": "First analyze the model's training logs to determine whether there are any issues with its parameter settings. Then clearly summarize the current results and the SOTA results with exact scores and any notable patterns. Limit your summary to no more than three concise, data-focused sentences.",
"Feedback for Hypothesis": "Explicitly confirm or refute the hypothesis based on specific data points or performance trends. Limit to two sentences.",
"New Hypothesis": "Propose a revised hypothesis, considering observed patterns and limitations in the current one. Limit to no more than two sentences.",
"Reasoning": "Explain the rationale for the new hypothesis using specific trends or performance shifts. Be concise but technically complete. Limit to two sentences.",
"Decision": <true or false>,
}
user:|-
{% if sota_hypothesis %}
# SOTA Round Information:
Hypothesis: {{ sota_hypothesis.hypothesis }}
Specific Task: {{ sota_task }}
Code Implementation: {{ sota_code }}
Result: {{ sota_result }}
{% else %}
# This is the first round. No previous information available. As long as the performance is not too negative (eg.ICIR is greater than 0), treat it as successful. Do not set the threshold too high.
{% endif %}
# Current Round Information:
Hypothesis: {{ hypothesis.hypothesis }}
Why propose this hypothesis: {{ hypothesis.reason }}
Specific Task: {{ exp.sub_tasks[0].get_task_information() }}
- If the new model's performance shows an improvement in the annualized return, recommend it to replace the current SOTA result.
- Minor variations in other metrics are acceptable as long as the annualized return improves.
2. Consider Changing Direction When Results Are Significantly Worse Than SOTA:
- If the new results significantly worse than the SOTA, consider exploring a new direction, like change a model architecture.
action_gen:
system:|-
Quantitative investment is a data-driven approach to asset management that relies on mathematical models, statistical techniques, and computational methods to analyze financial markets and make investment decisions. Two essential components of this approach are factors and models.
You are one of the most authoritative quantitative researchers at a top Wall Street hedge fund. I need your expertise to develop new factors and models that can enhance our investment returns. Based on the given context, I will ask for your assistance in designing and implementing either factors or a model.
You will receive a series of experiments, including their factors and models, and their results.
Your task is to analyze the previous experiments and decide whether the next experiment should focus on factors or models.
Example JSON Structure for your return:
{
"action": "factor"or "model", # You must choose one of the two
}
user:|-
{% if hypothesis_and_feedback|length == 0 %}
It is the first round of hypothesis generation. The user has no hypothesis on this scenario yet.
{% else %}
The former hypothesis and the corresponding feedbacks are as follows:
{{ hypothesis_and_feedback }}
{% endif %}
{% if last_hypothesis_and_feedback != "" %}
Here is the last trial's hypothesis and the corresponding feedback. The main feedback includes a new hypothesis for your reference only. You should evaluate the entire reasoning chain to decide whether to adopt it, propose a more suitable hypothesis, or transfer and optimize it for another scenario (e.g., factor/model), since transfers are generally encouraged:
"""The strategy to use for injecting diversity context."""
# enable different version of DSExpGen for multi-trace
enable_multi_version_exp_gen:bool=False
exp_gen_version_list:str="v3,v2"
#### multi-trace: time for final multi-trace merge
merge_hours:float=0
"""The time for merge"""
#### multi-trace: max SOTA-retrieved number, used in AutoSOTAexpSelector
# constrains the number of SOTA experiments to retrieve, otherwise too many SOTA experiments to retrieve will cause the exceed of the context window of LLM
max_sota_retrieved_num:int=10
"""The maximum number of SOTA experiments to retrieve in a LLM call"""
"""Number of failures tolerated before escalating to next timeout level (stage width). Every 'patience' failures, timeout increases by 'runner_timeout_increase_stage'"""
show_hard_limit:bool=True
#### enable runner code change summary
runner_enable_code_change_summary:bool=True
### Proposal workflow related
#### Hypothesis Generate related
enable_simple_hypothesis:bool=False
"""If true, generate simple hypothesis, no more than 2 sentences each."""
enable_generate_unique_hypothesis:bool=False
"""Enable generate unique hypothesis. If True, generate unique hypothesis for each component. If False, generate unique hypothesis for each component."""
enable_research_rag:bool=False
"""Enable research RAG for hypothesis generation."""
#### hypothesis critique and rewrite
enable_hypo_critique_rewrite:bool=False
"""Enable hypothesis critique and rewrite stages for improving hypothesis quality"""
enable_scale_check:bool=False
##### select related
ratio_merge_or_ensemble:int=70
"""The ratio of merge or ensemble to be considered as a valid solution"""
llm_select_hypothesis:bool=False
"""Whether to use LLM to select hypothesis. If True, use LLM selection; if False, use the existing ranking method."""
#### Task Generate related
fix_seed_and_data_split:bool=False
ensemble_time_upper_bound:bool=False
user_interaction_wait_seconds:int=6000# seconds to wait for user interaction
{% include "rdagent.components.coder.data_science.pipeline.prompts:pipeline_coder.system" %}
NOTE: Ensure that base model form `{% include "scenarios.data_science.share:scen.input_path" %}prev_model` is correctly loaded, you are supposed to finetune the base model.
"_comment":"Benchmark scenarios for FT tasks. Used by run_ft_job.sh and UI.",
"aime24":{
"category":"math",
"scenario":"Improve the model's ability to solve advanced competition math problems through multi-step reasoning, including number theory, combinatorics, geometry, and algebraic manipulation, with answers expressed as integers from 0 to 999.",
"benchmark_description":"AIME 2024 (American Invitational Mathematics Examination) - Advanced high school math competition problems requiring creative problem-solving. Each answer is an integer 0-999. Topics include number theory, algebra, geometry, trigonometry, probability, and combinatorics. Problems require multi-step reasoning and often have elegant solutions. Expected Output Format: Put final answer within \\boxed{}, e.g., \\boxed{42}."
},
"aime25":{
"category":"math",
"scenario":"Improve the model's ability to solve advanced competition math problems through multi-step reasoning, including number theory, combinatorics, geometry, and algebraic manipulation, with answers expressed as integers from 0 to 999.",
"benchmark_description":"AIME 2025 (American Invitational Mathematics Examination) - Advanced high school math competition problems requiring creative problem-solving. Each answer is an integer 0-999. Topics include number theory, algebra, geometry, trigonometry, probability, and combinatorics. Problems require multi-step reasoning and often have elegant solutions. Expected Output Format: Put final answer within \\boxed{}, e.g., \\boxed{42}."
},
"panorama":{
"category":"patent",
"scenario":"Improve the model's patent examination capabilities including prior art retrieval, paragraph identification, and novelty/obviousness classification based on USPTO standards.",
"benchmark_description":"PANORAMA tests patent examination capabilities based on real USPTO Office Actions. Tasks include: retrieving relevant prior art patents, identifying specific paragraphs in prior art that relate to claims, and classifying claims as allowable, lacking novelty (102), or obvious (103). Requires understanding patent law, technical document analysis, and legal reasoning. Expected Output Format: Return JSON with task-specific format (see subtask descriptions)."
},
"panorama_par4pc":{
"category":"patent",
"scenario":"Improve the model's ability to retrieve relevant prior art patents given a patent claim, by understanding claim scope, identifying technical similarities, and ranking patents by relevance for rejection analysis.",
"benchmark_description":"PAR4PC (Prior Art Retrieval for Patent Claims) - Given a patent claim, retrieve the most relevant prior art patents from a candidate pool. Requires understanding claim scope, identifying technical similarities, and ranking patents by relevance for potential 35 USC 102/103 rejections. Expected Output Format: Return JSON: {\"answer\": \"A\"} for single patent or {\"answer\": [\"A\", \"C\"]} for multiple patents (codes A-H)."
},
"panorama_pi4pc":{
"category":"patent",
"scenario":"Improve the model's ability to identify specific paragraphs in prior art patents that are most relevant for evaluating a claim's novelty and obviousness through element-by-element analysis.",
"benchmark_description":"PI4PC (Paragraph Identification for Patent Claims) - Given a patent claim and cited prior art patent, identify specific paragraphs most relevant for evaluating novelty and obviousness. Requires detailed technical reading, element-by-element claim analysis, and understanding how prior art teachings map to claim limitations. Expected Output Format: Return JSON: {\"answer\": \"<paragraph_id>\"}."
},
"panorama_noc4pc":{
"category":"patent",
"scenario":"Improve the model's ability to classify patent claims as allowable, anticipated, or obvious by applying patent law standards to analyze claim limitations against prior art.",
"benchmark_description":"NOC4PC (Novelty/Obviousness Classification) - Classify patent claims as ALLOW (patentable), 102 (anticipated/lacks novelty), or 103 (obvious). Requires applying patent law standards: 102 when single reference discloses all elements, 103 when combination of references with motivation makes claim obvious to skilled artisan. Expected Output Format: Return JSON: {\"code\": \"ALLOW\"} or {\"code\": \"102\"} or {\"code\": \"103\"}."
},
"panorama_par4pc_cot":{
"category":"patent",
"scenario":"Improve the model's ability to retrieve relevant prior art patents while providing explicit chain-of-thought reasoning explaining which claim elements each patent teaches and how it supports a rejection.",
"benchmark_description":"PAR4PC with chain-of-thought - Retrieve relevant prior art while providing explicit reasoning. Explain why each retrieved patent is relevant: which claim elements it teaches, what technical problems it addresses, and how it could support a rejection. Expected Output Format: Provide reasoning first, then return JSON: {\"answer\": \"A\"} or {\"answer\": [\"A\", \"C\"]}."
},
"panorama_pi4pc_cot":{
"category":"patent",
"scenario":"Improve the model's ability to identify relevant prior art paragraphs while providing element-by-element mapping showing how specific paragraph teachings correspond to claim limitations.",
"benchmark_description":"PI4PC with chain-of-thought - Identify relevant prior art paragraphs while explaining the technical connections. Provide element-by-element mapping showing how specific paragraph teachings correspond to claim limitations. Expected Output Format: Provide reasoning first, then return JSON: {\"answer\": \"<paragraph_id>\"}."
},
"panorama_noc4pc_cot":{
"category":"patent",
"scenario":"Improve the model's ability to classify patent claims with examiner-style rationale, explaining how references anticipate limitations or how combinations with motivation render claims obvious.",
"benchmark_description":"NOC4PC with chain-of-thought - Classify claims with examiner-style rationale. For 102: explain how reference anticipates each limitation. For 103: identify references, explain motivation to combine, and show how combination renders claim obvious. Use proper USPTO citation format. Expected Output Format: Return JSON: {\"reason\": \"<Office Action analysis>\", \"code\": \"ALLOW\"|\"102\"|\"103\"}."
},
"chemcotbench":{
"category":"chemistry",
"scenario":"Improve the model's chemical reasoning capabilities on molecular structures including understanding molecular features, editing molecules, optimizing properties, and predicting reaction outcomes.",
"benchmark_description":"ChemCoTBench tests step-wise chemical reasoning on SMILES molecular structures. Tasks include molecule understanding (identify functional groups, ring systems), molecule editing (add/delete/substitute groups while maintaining validity), molecule optimization (modify for desired properties), and reaction prediction (products, mechanisms, conditions). Contains subtasks with different output requirements. Expected Output Format: Return JSON: {\"output\": \"<answer>\"} where answer format depends on subtask - SMILES string for molecular tasks, numeric count for counting tasks, or Yes/No for equivalence tasks."
},
"chemcotbench_mol_und":{
"category":"chemistry",
"scenario":"Improve the model's ability to analyze molecular structures and identify structural features including functional groups (hydroxyl, carboxyl, amine), ring systems (aromatic, aliphatic), and molecular scaffolds.",
"benchmark_description":"Molecule Understanding - Analyze SMILES strings for structural features. Subtasks: (1) fg_count/ring_count: return integer count, (2) equivalence/ring_system_scaffold: return Yes or No, (3) Murcko_scaffold: return SMILES string. Requires parsing SMILES notation and applying organic chemistry knowledge. Expected Output Format: Return JSON: {\"output\": \"<answer>\"} where answer is integer/Yes/No/SMILES depending on subtask."
},
"chemcotbench_mol_edit":{
"category":"chemistry",
"scenario":"Improve the model's ability to perform precise structural modifications on molecules (add, delete, substitute functional groups) while maintaining chemical validity and molecule integrity.",
"benchmark_description":"Molecule Editing - Perform structural modifications on SMILES. Subtasks: add (add functional group), delete (remove group), sub (substitute group). Output must be valid SMILES representing chemically feasible molecules. Expected Output Format: Return JSON: {\"output\": \"<valid SMILES>\"}. SMILES validity is verified using RDKit."
},
"chemcotbench_mol_opt":{
"category":"chemistry",
"scenario":"Improve the model's ability to modify molecular structures to achieve target properties such as improved solubility, drug-likeness, or binding affinity to specific biological targets.",
"scenario":"Improve the model's ability to predict chemical reaction outcomes including forward synthesis, retrosynthesis, mechanism selection, and reaction conditions based on functional group transformations.",
"scenario":"Improve the model's ability to analyze tabular data for complex questions including trend identification, correlation analysis, statistical computation, and data-driven forecasting.",
"benchmark_description":"Table Data Analysis - Analyze tabular data to answer complex questions. Subtask types with different evaluation: (1) CorrelationAnalysis/TrendForecasting/StatisticalAnalysis: numeric answers with ±10% relative error tolerance, (2) ImpactAnalysis: exact match required, (3) Other analysis types: evaluated using ROUGE-L. Requires reading tables accurately and applying analytical reasoning. Expected Output Format: End response with \"Final Answer: <value>\"."
},
"tablebench_fact_checking":{
"category":"table_qa",
"scenario":"Improve the model's ability to verify factual claims against tabular data through accurate data extraction, implicit relationship understanding, and multi-hop reasoning across table cells.",
"benchmark_description":"Table Fact Checking - Answer table-based factual questions accurately. Questions may ask for specific information (numbers, names, dates) or verification (Yes/No, True/False). Uses Exact Match evaluation. Expected Output Format: End response with \"Final Answer: <value>\" where value is the precise answer to the question."
},
"tablebench_numerical_reasoning":{
"category":"table_qa",
"scenario":"Improve the model's ability to perform mathematical operations on table data including arithmetic, aggregations (sum, average, count), comparisons, percentages, and multi-step calculations.",
"benchmark_description":"Table Numerical Reasoning - Perform mathematical operations on table data: arithmetic (sum, difference, product), aggregations (average, count, max/min), comparisons, percentages, and multi-step calculations. Requires accurate number extraction and correct mathematical computation. Expected Output Format: End response with \"Final Answer: <numeric value>\"."
},
"tablebench_visualization":{
"category":"table_qa",
"scenario":"Improve the model's ability to generate Python code that creates appropriate visualizations (bar, line, pie, scatter charts) from tabular data with correct chart type selection and data mapping.",
"benchmark_description":"Table Visualization - Generate Python code to create appropriate visualizations from tabular data: bar charts, line charts, pie charts, scatter plots. Select correct chart type for data, map columns correctly to axes, and produce executable matplotlib/pandas code. Expected Output Format: Return Python code in ```python code block using matplotlib/pandas. Code will be executed to verify correctness."
},
"tablebench_gen":{
"category":"table_qa",
"scenario":"Improve the model's overall table question answering capabilities across fact checking, numerical reasoning, data analysis, and visualization by understanding table structure and generating accurate answers.",
"benchmark_description":"TableBench General - Comprehensive table QA covering fact checking, numerical reasoning, data analysis, and visualization. Questions require understanding table structure, extracting relevant data, performing reasoning or computation, and generating accurate answers or code. Expected Output Format: End response with \"Final Answer: <answer>\"."
},
"FinanceIQ_gen":{
"category":"finance",
"scenario":"Improve the model's financial domain knowledge and reasoning capabilities across Chinese financial certification exams including CPA, banking, securities, fund, futures, insurance, tax, and actuarial qualifications through multiple-choice question answering.",
"benchmark_description":"FinanceIQ tests financial domain knowledge through multiple-choice questions (A/B/C/D). Covers 10 Chinese financial certification exams: CPA (注册会计师), banking qualification, securities qualification, fund qualification, futures qualification, insurance qualification (CICE), tax advisor, economist, financial planner, and actuary. Uses LLM Judge for evaluation with 5-shot in-context learning. Evaluation metric: accuracy."
},
"bioprobench_gen":{
"category":"biology",
"scenario":"Improve the model's ability to generate complete, detailed experimental protocol steps from research context, including specific reagent concentrations, temperatures, incubation times, and equipment settings.",
"benchmark_description":"Protocol Generation - Generate complete experimental protocol steps given research context and objectives. Output detailed, actionable instructions: specify reagent concentrations, temperatures, incubation times, equipment settings. Protocols must be scientifically valid and reproducible. Expected Output Format: Wrap protocol steps in [ANSWER_START]Step 1: ... Step 2: ...[ANSWER_END]. Evaluated using BLEU, ROUGE, and step matching metrics."
},
"bioprobench_ord":{
"category":"biology",
"scenario":"Improve the model's ability to arrange shuffled experimental steps in correct sequence. Output MUST be a valid Python list format: [ANSWER_START][0, 2, 1, 3][ANSWER_END]. Use brackets and commas, NOT space-separated indices.",
"benchmark_description":"Step Ordering - Arrange shuffled experimental procedure steps in correct logical and temporal sequence. Requires understanding procedural dependencies: which steps must precede others, timing constraints, and scientific logic of experimental workflows. CRITICAL OUTPUT FORMAT: Answer MUST be a valid Python list with brackets and commas, e.g., [ANSWER_START][2, 0, 1, 3][ANSWER_END]. NOT space-separated (0 2 1 3 is WRONG), NOT without brackets (0, 2, 1, 3 is WRONG). Evaluated using Exact Match and Kendall's Tau."
},
"bioprobench_err":{
"category":"biology",
"scenario":"Improve the model's ability to identify errors in biological protocol text. CRITICAL SEMANTICS: True = step is CORRECT (no errors), False = step HAS ERRORS. This matches the benchmark prompt: 'If you find anything wrong, answer False.' Output format: [ANSWER_START]True or False[ANSWER_END].",
"benchmark_description":"Error Correction - Identify errors in biological protocol text including incorrect temperatures, concentrations, reagents, or procedural mistakes. CRITICAL: The benchmark expects True if the protocol step is CORRECT (no errors), and False if it HAS ERRORS. This follows the prompt: 'If you find anything wrong, answer False.' Do NOT invert this logic. Expected Output Format: [ANSWER_START]True[ANSWER_END] for correct steps, [ANSWER_START]False[ANSWER_END] for erroneous steps."
},
"bioprobench_pqa":{
"category":"biology",
"scenario":"Improve the model's ability to extract specific factual information from experimental protocols including temperatures, concentrations, incubation times, reagent quantities, and procedural details.",
"benchmark_description":"Protocol QA - Extract specific factual information from experimental protocols: temperatures, concentrations, incubation times, reagent quantities, equipment specifications, and procedural details. Requires careful reading and accurate information extraction from technical text. Expected Output Format: Return [ANSWER_START]<answer text> & <confidence 0-100>%[ANSWER_END], e.g., [ANSWER_START]Option A & 95%[ANSWER_END]. Evaluated using accuracy and Brier Score."
You are a data scientist tasked with evaluating code generation.
You will receive the following information:
- The implemented code
Focus on these aspects:
- Check if the code load the model in the "prev_model/" subfolder.
Please respond with your feedback in the following JSON format and order
```json
{
"execution": "Describe whether the code executed successfully. Include any errors or issues encountered, and append all error messages and full traceback details without summarizing or omitting any information. ."
"return_checking": "Detect whether the model is loaded from 'prev_model/' subfolder and finetune is prepared based on prev model.",
"code": "The code has explicity load the model from 'prev_model/' subfolder and prepares finetune based on prev model.",
"final_decision": <true or false in boolean type; only return true when ensuring that the code loads the model from 'prev_model/' subfolder and prepares finetune based on prev model.>
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.