Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "StratEvo Dev",
"image": "mcr.microsoft.com/devcontainers/python:3.12",
"postCreateCommand": "pip install -e '.[dev]' && pre-commit install",
"forwardPorts": [8000],
"customizations": {
"vscode": {
"extensions": [
"ms-python.python",
"ms-python.vscode-pylance",
"charliermarsh.ruff"
],
"settings": {
"python.defaultInterpreterPath": "/usr/local/bin/python",
"python.testing.pytestEnabled": true,
"editor.formatOnSave": true,
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
}
}
}
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
Chinese version: [中文版](CONTRIBUTING.zh-CN.md)

# Contributing to StratEvo

Thanks for your interest in contributing! StratEvo is an AI-native quantitative finance engine and we welcome contributions of all kinds — bug reports, new factors, fitness functions, data sources, documentation improvements, and more.
Expand Down
186 changes: 186 additions & 0 deletions CONTRIBUTING.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
English version: [English](CONTRIBUTING.md)

# 贡献指南

感谢你对 StratEvo 的关注!StratEvo 是一款 AI 原生量化金融引擎,我们欢迎各类贡献——Bug 报告、新因子、适应度函数、数据源、文档改进等。

## 环境要求

- **Python 3.10+**
- Git
- (可选)[pre-commit](https://pre-commit.com/) 自动代码检查

## 快速开始

```bash
# 1. 克隆仓库
git clone https://github.com/NeuZhou/stratevo.git
cd stratevo

# 2. 以开发模式安装(并配置 pre-commit 钩子)
make dev
# 或手动执行:
pip install -e ".[dev]"
pre-commit install

# 3. 运行测试套件
python -m pytest tests/ -v

# 4. 检查代码风格
make check
```

### 常用 Make 命令

| 命令 | 说明 |
|------|------|
| `make dev` | 以开发模式安装并配置 pre-commit 钩子 |
| `make test` | 运行完整测试套件 |
| `make format` | 使用 ruff 自动格式化代码 |
| `make check` | 代码检查 + 快速测试 |

## 贡献方式

| 类型 | 说明 |
|------|------|
| Bug 报告 | 发现了问题?[提交 Issue](https://github.com/NeuZhou/stratevo/issues/new?template=bug_report.yml) |
| 功能建议 | 有新想法?[提交功能请求](https://github.com/NeuZhou/stratevo/issues/new?template=feature_request.yml) |
| Alpha 因子 | 为进化引擎添加新的 Alpha 因子 |
| 适应度函数 | 实现新的策略评估适应度函数 |
| 数据源 | 接入新的数据提供商 |
| 文档 | 改进文档、补充示例、修正错别字 |

---

## 添加新因子

这是最常见的贡献方式。StratEvo 的进化引擎使用因子作为策略生成的基本构建块。

### 1. 生成脚手架

```bash
stratevo scaffold factor --name my_awesome_factor --category momentum
```

这会创建两个文件:
- `my_awesome_factor_factor.py` — 因子实现
- `test_my_awesome_factor_factor.py` — 初始测试

### 2. 实现 `compute()`

打开生成的源文件,实现因子逻辑:

```python
def compute(self, closes, highs=None, lows=None, opens=None, volumes=None, **params):
period = params.get("period", self.default_params()["period"])
# 你的因子逻辑
result = [float("nan")] * len(closes)
for i in range(period, len(closes)):
result[i] = closes[i] - closes[i - period]
return result
```

核心要求:
- 返回与 `closes` 等长的列表
- 预热期使用 `float("nan")` 填充
- 通过 `**params` 接收参数,回退至 `default_params()`
- 设置合理的 `param_ranges()` 供进化引擎使用

### 3. 编写测试

脚手架会生成基础测试。你应补充更多测试来验证逻辑:
- 使用已知数据测试可计算的正确结果
- 测试边界情况(空数据、单元素、全 NaN)
- 测试不同参数值

### 4. 提交 PR

将文件移动到对应目录:
- 源码 → `stratevo/factor_registry/builtin/<category>/`
- 测试 → `tests/`

然后提交 Pull Request!

---

## 添加适应度函数

适应度函数用于对回测结果评分,驱动进化搜索。

### 1. 生成脚手架

```bash
stratevo scaffold fitness --name risk_adjusted_return
```

### 2. 实现 `evaluate()`

```python
def evaluate(self, returns, **kwargs):
if not returns:
return 0.0
mean_ret = sum(returns) / len(returns)
variance = sum((r - mean_ret) ** 2 for r in returns) / len(returns)
std = variance ** 0.5
return mean_ret / std if std > 0 else 0.0
```

### 3. 编写测试并提交 PR

流程相同:验证实现后提交 Pull Request。

---

## 添加数据源

```bash
stratevo scaffold datasource --name polygon_io
```

实现 `fetch()` 和 `supported_symbols()`,编写测试后提交 PR。

---

## 代码规范

- **Linter**:[ruff](https://docs.astral.sh/ruff/) — 推送前运行 `ruff check .`
- **类型注解**:所有公开函数和方法需添加类型注解
- **文档字符串**:所有公开类和函数需添加 docstring
- **导入**:使用绝对导入(`from stratevo.factor_registry.base import BaseFactor`)

## PR 流程

1. **Fork** 仓库
2. **创建分支** — 新建功能分支(`git checkout -b feat/my-new-factor`)
3. **提交** — 使用清晰、有描述性的提交信息
4. **推送**并创建 **Pull Request**
5. **CI** — 所有测试必须通过
6. **审查** — 维护者将审查你的代码
7. **合并** — 审查通过后,你的贡献即被合入!

### CI 要求

PR 合并前必须通过以下检查:

- `python -m pytest tests/ -v` — 完整测试套件
- `ruff check .` — 代码检查
- 不能导致现有测试回归

> **首次贡献者须知:** 出于安全考虑,GitHub 要求维护者批准来自 Fork 的首次 PR 的 CI 运行。请放心,我们会尽快审批!

## Issue 标签

| 标签 | 说明 |
|------|------|
| `bug` | 功能异常 |
| `enhancement` | 新功能或改进请求 |
| `new-factor` | 新 Alpha 因子提案 |
| `good first issue` | 适合新手 |
| `help wanted` | 需要额外关注 |
| `documentation` | 文档改进 |

## 社区

加入我们的 Discord:**https://discord.gg/kAQD7Cj8**

欢迎提问、分享策略、讨论因子思路——我们是一个友好的社区!
12 changes: 12 additions & 0 deletions tests/snapshots/analyze.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
usage: stratevo analyze [-h] [--ticker TICKER_FLAG] [--indicators INDICATORS]
[ticker]

positional arguments:
ticker Ticker symbol (positional)

options:
-h, --help show this help message and exit
--ticker TICKER_FLAG, -t TICKER_FLAG
Ticker symbol (flag)
--indicators INDICATORS, -i INDICATORS
Comma-separated indicators
19 changes: 19 additions & 0 deletions tests/snapshots/backtest.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
usage: stratevo backtest [-h] [--strategy STRATEGY] [--tickers TICKERS]
[--ticker TICKER] [--start START] [--end END]
[--benchmark BENCHMARK] [--capital CAPITAL]
[--output OUTPUT]

options:
-h, --help show this help message and exit
--strategy STRATEGY, -s STRATEGY
Strategy name
--tickers TICKERS, -t TICKERS
Comma-separated tickers
--ticker TICKER Single ticker (alias for --tickers)
--start START Start date (YYYY-MM-DD)
--end END End date (YYYY-MM-DD)
--benchmark BENCHMARK, -b BENCHMARK
Benchmark ticker
--capital CAPITAL, -c CAPITAL
--output OUTPUT, -o OUTPUT
Save results to JSON
43 changes: 43 additions & 0 deletions tests/snapshots/evolve.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
usage: stratevo evolve [-h] [--market {crypto,a-share,cn,us}] [--quick]
[--demo] [--generations GENERATIONS]
[--population POPULATION] [--data-dir DATA_DIR]
[--results-dir RESULTS_DIR]
[--mutation-rate MUTATION_RATE] [--elite ELITE]
[--seed SEED] [--save-interval SAVE_INTERVAL]
[--max-stocks MAX_STOCKS] [--download]
[--symbols SYMBOLS] [--pareto] [--pareto-complexity]
[--held-out HELD_OUT]

options:
-h, --help show this help message and exit
--market {crypto,a-share,cn,us}
Market type: crypto, a-share/cn, us (default: crypto)
--quick Quick mode: small dataset, fast iterations — see
results in ~2 minutes
--demo Demo mode: use built-in sample data, zero setup —
experience evolution in 30 seconds
--generations GENERATIONS
Number of generations (default: 100, quick: 10)
--population POPULATION
Population size (default: 30, quick: 15)
--data-dir DATA_DIR Path to CSV data directory
--results-dir RESULTS_DIR
Directory for results (default: evolution_results)
--mutation-rate MUTATION_RATE
Mutation rate 0.0-1.0 (default: 0.3, quick: 0.5)
--elite ELITE Number of elite strategies to keep (default: 5, quick:
3)
--seed SEED Random seed for reproducibility
--save-interval SAVE_INTERVAL
Save every N generations (default: 10, quick: 1)
--max-stocks MAX_STOCKS
Max stocks to evaluate (default: 500, quick: 3)
--download Force re-download market data even if local CSVs exist
--symbols SYMBOLS Comma-separated symbols to download (overrides
defaults)
--pareto Enable multi-objective Pareto evolution (NSGA-III)
--pareto-complexity Include strategy complexity as 4th objective in Pareto
mode
--held-out HELD_OUT Held-out validation ratio (0.0-1.0). Last N% of data
reserved for final validation after evolution. Set to
0 to disable. (default: 0.2)
Loading
Loading