按用户目标把原来「一个策略 = 全套参数」拆开(已确认的设计决策):
- 公共配置 GlobalConfig(全局唯一):佣金/印花税/滑点/最低佣金/复权口径/基准
- 选股策略 SelectionStrategy(原 StrategyDefinition 改名):只剩股票池+因子+条件,
不再持有 selection/rebalance/costs/portfolio/区间/资金
- 回测组合 BacktestCombo:引用若干选股策略 + 回测时才定的参数
(起始资金、持仓数 N、持仓天数区间 [Tmin,Tmax]、调仓时机 日/周/月、区间)
引擎(app/quant/combo_engine.py,新增):
- 多策略打分 = 并集 + Borda 秩和(各策略 1/名次 求和;不假设不同策略分值可比,
能容纳各策略股票池不同);抽出纯函数 borda_combine 便于单测
- 持仓天数区间 [Tmin,Tmax]:Tmax **每个交易日**强制了结(安全阀,月频下也不超期);
Tmin 仅在调仓日保护(掉出 TopN 但未满 Tmin 暂留,防频繁换手);调仓日为增量调仓
(只卖超期/掉队且满 Tmin 的,从 TopN 补买至 N 只,不主动减持以尊重 Tmin)
- 调仓时机 daily/weekly/monthly(local_engine.rebalance_dates 新增日频分支)
- 产出与旧 runner 同构的 BacktestResult,前端可视化无需改动;config_snapshot 固化
ComboRunSpec(组合+当时各策略定义+当时成本/复权)保证可复现
数据层:
- 新表 global_config(默认行:万三/hfq/最低佣金5元)、backtest_combo
- 迁移 b4c5d6e7f8a9:建两表 + 把存量 strategy.config_json 的回测参数键剥掉、
spec_type 收敛为 selection(已在真实 MariaDB 验证:STG-16BFBF08 清洗后只剩
universe/factors/conditions)
- 仓储 SqlAlchemyGlobalConfigRepository / SqlAlchemyComboRepository + Protocol
API:
- /api/config GET/PUT;/api/combos CRUD + /{id}/run + /run(kind=combo 异步 Job)
- job_executor 新增 combo 分支:取齐策略+读公共配置→ComboService.run,归档 kind
记 backtest(结果结构相同)
- /api/strategies 切到 SelectionStrategy,移除已废弃的 /{id}/expand
- strategy_doc.describe_strategy 支持 SelectionStrategy(只讲「怎么选」,如实声明
资金/持仓/调仓/成本/区间在回测组合里定)
旧的 ResearchSpec + /api/backtests 保留(因子测试与既有契约自检仍用),
作为底层 escape hatch;用户产品路径改为回测组合。
测试:新增 test_combo_engine(6)/test_combo_service(3)/test_combo_api(5),
改写 test_strategies/test_strategy_doc 适配新模型。全量 403 passed(原 388)。
110 lines
4.4 KiB
Python
110 lines
4.4 KiB
Python
"""公共配置 + 回测组合 API 测试(TestClient + 内存 SQLite)。
|
||
|
||
覆盖:
|
||
- /api/config GET 返回默认值、PUT 持久化;
|
||
- /api/combos CRUD(name 唯一、原地更新保留 created_at、删除);
|
||
- /api/combos/{id}/run 在策略缺失时提前 400(不等到后台才失败)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
from app.api import deps
|
||
from app.infrastructure.persistence.sqlalchemy.base import Base
|
||
from app.main import app
|
||
from fastapi.testclient import TestClient
|
||
from sqlalchemy import create_engine
|
||
from sqlalchemy.orm import sessionmaker
|
||
|
||
|
||
@pytest.fixture()
|
||
def client(tmp_path) -> TestClient:
|
||
engine = create_engine(f"sqlite:///{tmp_path / 'combo_api.db'}", future=True)
|
||
Base.metadata.create_all(engine)
|
||
Session = sessionmaker(bind=engine, expire_on_commit=False)
|
||
|
||
def _session_override():
|
||
with Session() as s:
|
||
yield s
|
||
|
||
app.dependency_overrides[deps.get_session] = _session_override
|
||
with TestClient(app) as c:
|
||
yield c
|
||
app.dependency_overrides.clear()
|
||
|
||
|
||
class TestConfigApi:
|
||
def test_get_returns_defaults(self, client: TestClient) -> None:
|
||
cfg = client.get("/api/config").json()
|
||
assert cfg["id"] == "default"
|
||
assert cfg["price_adjustment"] == "hfq"
|
||
assert cfg["min_commission"] == 5.0
|
||
|
||
def test_put_persists(self, client: TestClient) -> None:
|
||
body = {
|
||
"commission_rate": 0.00025, "stamp_tax_rate": 0.0005,
|
||
"slippage_rate": 0.0008, "min_commission": 3.0,
|
||
"price_adjustment": "qfq", "benchmark": "000905.SH",
|
||
}
|
||
resp = client.put("/api/config", json=body)
|
||
assert resp.status_code == 200
|
||
got = client.get("/api/config").json()
|
||
assert got["commission_rate"] == pytest.approx(0.00025)
|
||
assert got["price_adjustment"] == "qfq"
|
||
assert got["benchmark"] == "000905.SH"
|
||
|
||
|
||
class TestCombosApi:
|
||
def _make_strategy(self, client: TestClient, name: str) -> str:
|
||
resp = client.post(
|
||
"/api/strategies",
|
||
json={"name": name, "factors": [{"name": "dividend_yield", "weight": 1}]},
|
||
)
|
||
assert resp.status_code == 200
|
||
return resp.json()["id"]
|
||
|
||
def test_crud(self, client: TestClient) -> None:
|
||
sid = self._make_strategy(client, "高股息")
|
||
body = {
|
||
"name": "组合A", "strategy_ids": [sid],
|
||
"initial_capital": 500000, "hold_count": 10,
|
||
"hold_min_days": 5, "hold_max_days": 30,
|
||
"rebalance_freq": "weekly", "period": ["2024-01-01", "2024-06-01"],
|
||
}
|
||
created = client.post("/api/combos", json=body)
|
||
assert created.status_code == 200
|
||
cid = created.json()["id"]
|
||
assert cid.startswith("CMB-")
|
||
assert created.json()["hold_max_days"] == 30
|
||
|
||
assert len(client.get("/api/combos").json()) == 1
|
||
detail = client.get(f"/api/combos/{cid}").json()
|
||
assert detail["strategy_ids"] == [sid]
|
||
assert detail["rebalance_freq"] == "weekly"
|
||
|
||
# 原地更新保留 id 与 created_at
|
||
created_at = detail["created_at"]
|
||
upd = client.put(f"/api/combos/{cid}", json={**body, "name": "组合A", "hold_count": 15})
|
||
assert upd.status_code == 200
|
||
assert upd.json()["id"] == cid
|
||
assert upd.json()["created_at"] == created_at
|
||
assert upd.json()["hold_count"] == 15
|
||
|
||
assert client.delete(f"/api/combos/{cid}").status_code == 200
|
||
assert client.get(f"/api/combos/{cid}").status_code == 404
|
||
|
||
def test_duplicate_name_400(self, client: TestClient) -> None:
|
||
sid = self._make_strategy(client, "S")
|
||
body = {"name": "重名", "strategy_ids": [sid], "hold_count": 5,
|
||
"rebalance_freq": "monthly", "period": ["2024-01-01", "2024-02-01"]}
|
||
assert client.post("/api/combos", json=body).status_code == 200
|
||
assert client.post("/api/combos", json=body).status_code == 400
|
||
|
||
def test_run_missing_strategy_400(self, client: TestClient) -> None:
|
||
"""引用不存在的策略 → 提交时即 400,而非等后台 Job 才失败。"""
|
||
body = {"name": "缺策略组合", "strategy_ids": ["STG-NOT-EXIST"], "hold_count": 5,
|
||
"rebalance_freq": "monthly", "period": ["2024-01-01", "2024-02-01"]}
|
||
resp = client.post("/api/combos/run", json=body)
|
||
assert resp.status_code == 400
|
||
assert "不存在" in resp.json()["detail"]
|