An Open-Source Recursive Self-Improvement (RSI) Agent for Stock Strategy Research
Diagnose, mutate, falsify, and shadow-verify equity strategies with a full evidence trail
Overview · Core Capabilities · Quick Start · Architecture · Validation · CLI
AlphaEvo is a self-evolving stock strategy research agent. It turns a readable YAML strategy into a disciplined recursive self-improvement (RSI) loop: backtest, diagnose failure, propose a controlled mutation or new factor, stress-test against overfitting, and keep the full evidence trail.
To keep self-evolution honest on noisy equity data, AlphaEvo separates fast offline hypothesis search from slow forward promotion: historical backtests can only veto weak candidates, while a bitemporal forward shadow ledger tracks out-of-sample commitments (T+5 / T+10 / T+20) before any promotion.
Bundled frozen yfinance snapshot, US tech basket, 2025-02-11 to 2026-04-10:
| Strategy | Signals | Win Rate | Avg Return | Max DD | Score |
|---|---|---|---|---|---|
rsi_reversion_v1 baseline |
0 | 0.0% | 0.00% | 0.0% | 8.1% |
rsi_reversion_v7 champion |
37 | 48.6% | 2.94% | 23.6% | 68.7% |
What happened: the deterministic research committee flagged an over-confirmed entry stack, unlocked enough signals, widened the stop, extended holding, raised the payoff target, switched support context to MA60, then tightened volume confirmation. Each change was accepted only after retest. The champion keeps train-val and val-test gaps at 7.1% / 7.1% on this snapshot. See showcase_rsi_reversion_real_snapshot.md.
Live yfinance data, configured external LLM provider, alphaevo evolve rsi_reversion_v1 --method llm, April 10, 2026:
| Strategy | Signals | Win Rate | Avg Return | Score |
|---|---|---|---|---|
rsi_reversion_v1 baseline |
0 | 0.0% | 0.00% | 8.1% |
rsi_reversion_v3 LLM champion |
498 | 52.6% | 1.22% | 56.3% |
Different data windows and protocols should not be ranked directly; the snapshot showcase is the stable no-key first run, while this path demonstrates the LLM research loop on live market data.
- Backtesting and evaluation: run strategies on real data with regime sampling, multi-metric scoring, and walk-forward anti-overfitting checks.
- Recursive self-improvement (
alphaevo rsi): driveprogram.md-steered L1 strategy mutations, L2 Co-STEER factor synthesis,(regime × style × horizon)MAP-Elites archives, executable reflection scars, and heterogeneous proposer/prosecutor reviews withresults.tsvprovenance. - L0 truth kernel & forward shadow ledger (
truth/shadow): enforce an append-onlyTrialLedgerwith Deflated Sharpe Ratio (DSR), shuffled-return null-signal controls, runtime point-in-time (PIT) leak probes, and SHA-256 hash-chained forward commitments. - Traceable research workflow: keep deterministic or LLM research committee verdicts, evolution trees, and SFT/DPO trajectory exports for every iteration.
git clone https://github.com/ZhuLinsen/alphaevo.git
cd alphaevo
pip install -e .
alphaevo showcaseThis runs a real historical-data showcase from a bundled yfinance snapshot:
Showcase Chain: baseline + up to 6 validated mutations
Round 1 │ rsi_reversion_v1 │ Signals: 0 │ Score: 8.1%
Committee: entry stack is too strict
Mutation: entry.logic and -> or
Round 2 │ rsi_reversion_v2 │ Signals: 79 │ Score: 17.8%
Mutation: exit.stop_loss.value 0.05 -> 0.08
Round 7 │ rsi_reversion_v7 │ Signals: 37 │ Score: 68.7% 🏆
| Goal | Command | Data | LLM |
|---|---|---|---|
| Real-data showcase (30s first run) | alphaevo showcase |
Bundled yfinance snapshot | No |
| Synthetic dev smoke test | alphaevo demo --synthetic |
Synthetic | No |
| Draft & research a plain-language idea | alphaevo strategy research "<idea>" |
Real data | No |
| Run a fuller real-data backtest | alphaevo run ma_crossover_v1 |
Live yfinance | No |
| Test breakout/volatility-compression template | alphaevo run volatility_compression_breakout_v1 |
Live yfinance | No |
| Search parameters with anti-overfit gates | alphaevo optimize <id> --objective robust_profit_quality --reject-overfit |
Real data | No |
| Flagship LLM research-agent evolution | alphaevo evolve <id> --method llm --output reports/ |
Real data | Yes |
Run Stock RSI ratchet loop (program.md) |
alphaevo rsi run rsi_reversion_v1 --program examples/rsi_stock_program.md |
Snapshot or --live |
Optional |
| Verify zero false promotions under shuffled noise | alphaevo rsi null-audit rsi_reversion_v1 |
Snapshot or --live |
No |
| Track bitemporal forward commitments | alphaevo shadow register <id> && alphaevo shadow status |
Snapshot or live | No |
Real-data commands need a data adapter extra: pip install -e ".[data-yfinance]" (US/global), pip install -e ".[data-akshare]" (A-share), or pip install -e ".[data-full]". For US strategies, optional ADANOS_API_KEY enriches L3 event indicators with sentiment context (falling back to price/volume proxies when unset).
alphaevo showcase --live tries live yfinance before falling back to the bundled snapshot. For optimize quality/overfit gates, inspect all options with alphaevo optimize --help (keep --full-eval-top high enough under --evaluation-mode fast when using --reject-overfit).
- Flagship LLM proof path:
rsi_reversion_v1andma_crossover_v1on real data. - Most reliable strategy families right now: trend + reversal strategies whose core signals come from OHLCV / benchmark context.
- Return-oriented trend template:
volatility_compression_breakout_v1uses explicit prior-high breakout triggers, range-position guards, volatility-compression filters, and trailing take profit. - Experimental families: event + rotation strategies still rely partly on proxy context for news / sector-flow semantics, so treat them as research previews rather than the main launch proof.
# From the cloned repo root, add LLM + default real-data support
pip install -e ".[llm,data-yfinance]"
# Set your LLM API key
export ALPHAEVO_API_KEY=your_api_key
export ALPHAEVO_LLM_MODEL=gemini/gemini-3.8-flash # or openai/gpt-6.1-sol, anthropic/claude-sonnet-5.5, deepseek/deepseek-v4-flash
# Run the flagship LLM research path
alphaevo evolve rsi_reversion_v1 --method llm --rounds 3 --output reports/rsi_evolve/
# Or run the L0-grounded Stock RSI loop with a research charter
alphaevo rsi run rsi_reversion_v1 --program examples/rsi_stock_program.md --output reports/rsi/For built-in A-share workflows, install pip install -e ".[llm,data-full]" and run alphaevo run trend_pullback_rebound_v1 --adapter akshare.
┌─────────────────────────────────────────────────────────┐
│ CLI (Typer + Rich) │
└────────────────────────┬────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────┐
│ Orchestrator & Stock RSI Loop │
│ charter → sample → backtest → evaluate (L0 Truth) │
│ → reflect / Co-STEER → evolve → shadow ledger │
└──┬────────┬────────┬────────┬────────┬────────┬─────────┘
│ │ │ │ │ │
┌──▼──┐ ┌──▼──┐ ┌───▼──┐ ┌──▼──┐ ┌───▼──┐ ┌──▼────────┐
│Data │ │Stgy │ │Sample│ │Back │ │Truth/│ │Reflection │
│Layer│ │Layer│ │Layer │ │test │ │Eval │ │& RSI Engine│
└─────┘ └─────┘ └──────┘ └─────┘ └──────┘ └───────────┘
| Layer | Purpose |
|---|---|
| Data Layer | Multi-source market data (yfinance, akshare, or daily_stock_analysis plugin) |
| Strategy Layer | Dual-representation: human-readable + executable YAML DSL (SetupSpec, PortfolioProfile) |
| Sampler Layer | Smart sampling by market regime, style, and strategy scope |
| Backtest Engine | Signal-level simulation with slippage, fees, and point-in-time truncation |
Evaluator & L0 Truth (truth) |
Multi-dimensional metrics + TrialLedger, Deflated Sharpe Ratio, null-signal controls, runtime PIT leak probe |
Reflection & RSI (reflection / rsi) |
LLM & deterministic committee failure attribution, Co-STEER L1/L2 routing, MAP-Elites archive, heterogeneous council, results.tsv ratchet |
Forward Shadow Ledger (forward) |
Bitemporal (as_of / available_at) SHA-256 hash-chained commitments, cluster-adjusted |
See Dual-Clock Stock RSI Architecture and examples/rsi_stock_program.md for details.
Round 1: rsi_reversion_v1 — live yfinance data, LLM-only evolve
→ 0 signals
→ Confidence: 8.1% ❌ non-functional
LLM diagnosis: "Entry conditions are contradictory and too strict."
Changes: entry.logic and→or, RSI 30→35
Round 2: rsi_reversion_v2 — strategy becomes tradable
→ 522 signals
→ Win rate: 52.7%, Avg return: +0.96%
→ Confidence: 39.2%
LLM diagnosis: "The OR logic over-corrected and now admits noisy entries."
Changes: RSI 35→32, volume_ratio 1.3→1.15, stop_loss pct→atr
Round 3: rsi_reversion_v3 — champion
→ 498 signals
→ Win rate: 52.6%, Avg return: +1.22%
→ Confidence: 56.3% (+48.2pp from start)
These are real results from an April 10, 2026 run using live yfinance data and a configured external LLM provider with
--method llm. Not synthetic, not heuristic fallback.
Strategies are stored as human-readable YAML, so the LLM can explain and mutate them without hiding the logic in code.
meta:
id: trend_pullback_rebound_v3
name: 强趋势回踩放量反包
version: 3
category: trend
entry:
logic: and
triggers:
- indicator: relative_strength_20d
op: ">"
value: 0.12
guards:
- indicator: ma5_above_ma10
op: "=="
value: true
exit:
triggers:
- indicator: close_below_ma10
op: "=="
value: true
stop_loss:
type: atr
atr_period: 21
multiplier: 2.0
take_profit:
type: rr
value: 2.0
params:
tunable:
- target: entry.triggers[indicator=relative_strength_20d].value
range: [0.05, 0.20]
step: 0.01See technical design for the full DSL.
We validate the system on live yfinance data with real --method llm runs, and we intentionally show both success and honest failure.
| Case | Start | Best Outcome | Why It Matters |
|---|---|---|---|
rsi_reversion_v1 |
8.1% |
56.3% champion |
LLM turned a zero-signal strategy into a tradable one in 3 rounds |
ma_crossover_v1 |
24.2% |
24.2% champion |
LLM proposed changes, but anti-overfit rejected weak generalization |
sector_rotation_leader_v1 smoke |
11.3% |
12.3% tested |
Candidate improved in-sample, but train_val_gap=18.9% blocked promotion |
This is part of the product story, not a footnote: AlphaEvo should be trusted more when it stops honestly than when it invents a prettier curve.
Real factor discovery is also live-tested: alphaevo factor discover AAPL proposed 3 factors, passed 3 through sandboxing, validated 2, and registered 2 (Factor Discovery Walkthrough).
Each real run can export <strategy_id>_research_report.md, <strategy_id>_llm_evidence.md, <strategy_id>_research_log.md, and trajectory/*.jsonl|json.
For a fixed-input benchmark suite, use:
python scripts/experiments/run_repro_benchmark.py \
--adapter yfinance \
--method llm \
--rounds 3 \
--output results/repro-benchmark/
python scripts/validate_real_data.py \
--adapter yfinance \
--days 365 \
--output results/real-validation/See the detailed write-up: April 10, 2026 real LLM validation.
Current limits:
- live external LLM providers can still introduce latency spikes and timeout-driven fallback
- some strategies, like
ma_crossover_v1, show that a valid LLM diagnosis does not automatically survive anti-overfit checks - discovered factors are research artifacts first and should still be reviewed before any production-style use
Every real evolution run can export more than scores:
trajectory.jsonlcaptures each round as(state -> diagnosis -> hypothesis -> change -> outcome)sharegpt.jsonlreformats the same run into SFT-style conversationspreference.jsonlstores improved vs. non-improved steps for preference learning
AlphaEvo takes overfitting seriously:
- Time Separation: Train / Validation / Test periods strictly separated
- Walk-Forward: Rolling 12-month train → 1-month test windows
-
Complexity & Stability Checks: Complexity penalty, minimum signal count (
< 30discounted), multi-year/sector consistency, ±10% parameter perturbation sensitivity -
Multiple-Testing Control (
TrialLedger+ DSR): Append-only trial counting prevents silent p-hacking and penalizes inflated historical Sharpe ratios - Null-Signal & Runtime PIT Probes: Random-entry / shuffled-return null floors plus isolated subprocess future-noise perturbation checks block forward-looking factor leaks
-
Forward Shadow Promotion Gate: Historical backtests only veto; promotion requires bitemporal forward commitments with cluster-adjusted effective sample size (
$N_{\text{eff}}$ ) and instantHALTEDtrips on drawdown/expectancy breaches
Works out of the box with yfinance or akshare for data.
Seamlessly integrates with daily_stock_analysis for multi-source data with automatic fallback.
from alphaevo.data.adapters.dsa import DSAAdapter
data_manager = DataManager([DSAAdapter(dsa_path="/path/to/dsa")])alphaevo showcase # Real-data 30s snapshot showcase (no API key)
alphaevo demo --real # Real data demo without API key
alphaevo run <id> # Full research loop
alphaevo evolve <id> --method llm --rounds 3 --output reports/ # LLM-first evolution
alphaevo rsi run <id> --program examples/rsi_stock_program.md # Stock RSI ratchet loop
alphaevo rsi null-audit <id> # Verify 0 false promotions under shuffled returns
alphaevo shadow status # Forward shadow ledger & promotion stages
alphaevo truth trials # Inspect append-only TrialLedger & DSR records
alphaevo factor discover <symbol> # LLM-driven factor discovery
alphaevo leaderboard # Strategy rankings
alphaevo tree <id> # Evolution tree visualizationFor the full command surface, run alphaevo --help.
- FunSearch (Nature 2024) — island-style parallel search and branch competition
- OPRO (DeepMind 2023) — optimizer-style prompt refinement with trajectory history
- Voyager (2023) — reusable skill/pattern libraries and long-horizon memory
- autoresearch (Karpathy) —
program.md-steered hypothesis charters, keep/revert ratchets, and verifiableresults.tsvledgers - RD-Agent / Co-STEER — co-steered strategy-level vs. factor-level blind-spot routing and empirical scar reuse
AlphaEvo adapts these ideas to falsifiable quantitative equity strategy research rather than general coding or benchmark optimization.
- Phase 1: Strategy Research Loop (MVP) — backtest engine, indicators, evaluator
- Phase 2: Self-Evolution Pipeline — LLM reflection, mutation, multi-round improvement
- Phase 3: CLI & Orchestration — full command suite, strategy store, leaderboard
- Phase 4: Open-Source Polish — CI/CD, docs, English templates, CHANGELOG
- Phase 5: Recursive Stock Self-Improvement & Shadow Ledger —
TrialLedger+ DSR, null controls, runtime PIT probe, MAP-Elites, heterogeneous council, bitemporal forward tracking - Phase 6: Market Regime Adaptive Gating — multi-strategy portfolio allocation, risk budgets & PIT event caches
- Phase 7: Web UI Dashboard — interactive strategy lineage, RSI ratchets & shadow ledger exploration
Contributions welcome! See CONTRIBUTING.md for guidelines.
Especially looking for:
- New strategy templates
- Data source adapters
- Evaluation metrics
- UI/visualization improvements
If this project helps your research, consider giving it a ⭐ and sharing it!
![]() Xiaohongshu 📱 Follow for quant strategy research updates |
📬 Contact & Collaboration 🐛 Submit an Issue — Bug reports / feature requests 📧 zhuls345@gmail.com — Business inquiries 🔗 daily_stock_analysis — Sister project, AI-powered daily stock analysis |
This project is for educational and research purposes only. It does not constitute investment advice. The authors are not responsible for any financial losses incurred from using this software. Always do your own research and consult qualified financial advisors before making investment decisions.
Past strategy performance does not guarantee future results. All backtesting results are simulated and may not reflect real market conditions.
Apache-2.0 License — see LICENSE for details.
If you use or build upon this project, a credit with a link back to this repository is appreciated.

