汇总三轮未提交的开发(每轮均在本机 MariaDB + 真实浏览器上验证):
1) 股息率案例(全市场股息率最高 n 只,默认 20,每 m 月择股)
- 新增日频估值表 daily_basic + 迁移;股息率因子(dv_ratio / dividend_yield / TTM)
- 名称历史表 stock_name_history:剔除 ST 按**择股日当时名称**判定,消除
「曾高股息后 ST」的股息陷阱(实测 3.70pp 偏差)
- 区间择股/调仓双周期(m 择股 / y 调仓)、指数成分与白名单、停牌近似剔除
- 复权因子口径核对(4,164,742 行、缺失 0.0%)、收盘价成交与涨跌停拦单
- 案例实测:2020-01-01~2026-09-04 总收益 +24.86%(年化 3.52%、回撤 -28.58%)
2) 策略库与前端统一
- strategy 表 + CRUD/PUT 原地更新 + `describe_strategy` 按 spec 真实推导
「一句话说明 + 计算公式 + 执行步骤 + 注意事项」(与引擎实执行规则同源)
- 任何出现股票代码处都成对显示名称且可点击进个股页
- 全站图表基座统一 TradingView Lightweight Charts(ECharts 依赖、
锁文件、组件与文档标注一并清除),买卖点标记只落在真实交易日上
3) 回测存档完整化(可往复查看)
- 同步端点(POST /api/backtests、/api/factor-tests)此前完全不落库 → 现在同样归档,
归档 id 经响应头 X-Experiment-Id 返回(不破坏 response_model)
- data_version 首次真实写入(数据快照指纹:最新交易日 + 各表规模)
- 个股收益曲线默认**全量保存**(此前硬截断 60 只);超出体积预算才裁剪,
并写 archive_meta(机器可读)+ unimplemented(人可读)如实标注
- 列表 kind/q 过滤 + X-Total-Count(此前 limit=50 静默截断)、DELETE 归档
- 只读归档页 /experiments/{id}(Server Component,SSR 直出**选股条件**与
**交易执行依据**);结果视图按 kind 分发(backtest/factor_test/selection),
非回测归档不套用回测口径
- 新增 CLI:prune_experiments(保留策略,默认 dry-run)、
restore_experiment_from_job(从 Job 副本按原 id 重建被删的历史归档,默认 dry-run)
门禁:pytest 388 passed、ruff All checks passed、tsc 0 错误、图表单测 7 passed、
next build 成功、契约脚本 verify_strategy_workspace 59/59(含按 kind 逐类验证归档页)。
131 lines
5.4 KiB
Python
131 lines
5.4 KiB
Python
"""D2 选股 Job 化测试:kind=selection 异步执行(executor + API 提交/轮询)。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date, datetime
|
|
|
|
import pytest
|
|
from app.api import deps
|
|
from app.application.services import job_executor as je
|
|
from app.domain.entities.market import Stock
|
|
from app.domain.entities.research import JobRecord, JobStatus
|
|
from app.domain.entities.selection import SelectionQuery, SelectionResult
|
|
from app.infrastructure.persistence.sqlalchemy.base import Base
|
|
from app.infrastructure.persistence.sqlalchemy.repositories.jobs_impl import (
|
|
SqlAlchemyExperimentRepository,
|
|
SqlAlchemyJobRepository,
|
|
)
|
|
from app.infrastructure.persistence.sqlalchemy.repositories.market_impl import (
|
|
SqlAlchemyDailyBarRepository,
|
|
SqlAlchemyStockRepository,
|
|
)
|
|
from app.main import app
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from conftest_quant import bars_dataframe_to_daily_bars, synthetic_daily
|
|
|
|
_SYMS = ["600000.SH", "600001.SH", "600002.SH", "600003.SH", "600004.SH"]
|
|
|
|
|
|
def _query(symbols=_SYMS) -> SelectionQuery:
|
|
return SelectionQuery(
|
|
universe={"exclude_st": False, "min_listing_days": 0, "symbols": list(symbols)},
|
|
factors=[{"name": "momentum_60", "weight": 1.0}],
|
|
top_n=3,
|
|
as_of=date(2024, 12, 31),
|
|
)
|
|
|
|
|
|
@pytest.fixture()
|
|
def engine_session(tmp_path):
|
|
engine = create_engine(f"sqlite:///{tmp_path / 'db.db'}", future=True)
|
|
Base.metadata.create_all(engine)
|
|
Session = sessionmaker(bind=engine, expire_on_commit=False)
|
|
df = synthetic_daily({s: 0.006 - 0.0015 * i for i, s in enumerate(_SYMS)}, n=320)
|
|
with Session() as session:
|
|
SqlAlchemyStockRepository(session).upsert_many(
|
|
[Stock(symbol=s, name=f"测试{i}", list_date=date(1999, 1, 1)) for i, s in enumerate(_SYMS)]
|
|
)
|
|
SqlAlchemyDailyBarRepository(session).upsert_many(bars_dataframe_to_daily_bars(df))
|
|
session.commit()
|
|
return Session
|
|
|
|
|
|
class TestSelectionJobExecutor:
|
|
def test_execute_and_archive(self, engine_session) -> None:
|
|
Session = engine_session
|
|
with Session() as session:
|
|
SqlAlchemyJobRepository(session).create(
|
|
JobRecord(id="JOB-SEL-1", kind="selection",
|
|
spec_json=_query().model_dump_json(),
|
|
status=JobStatus.QUEUED, created_at=datetime.now())
|
|
)
|
|
session.commit()
|
|
je.execute_job(
|
|
"JOB-SEL-1",
|
|
session_factory=Session,
|
|
job_repo_factory=lambda s: SqlAlchemyJobRepository(s),
|
|
experiment_repo_factory=lambda s: SqlAlchemyExperimentRepository(s),
|
|
stock_repo_factory=lambda s: SqlAlchemyStockRepository(s),
|
|
daily_repo_factory=lambda s: SqlAlchemyDailyBarRepository(s),
|
|
engine=None,
|
|
)
|
|
with Session() as session:
|
|
job = SqlAlchemyJobRepository(session).get("JOB-SEL-1")
|
|
exp = SqlAlchemyExperimentRepository(session).get(job.experiment_id or "")
|
|
assert job.status == JobStatus.SUCCESS
|
|
# 完整结果只在 experiment 存一份:从归档解码验证(job.result_json 为新形态空值)
|
|
assert job.result_json is None
|
|
assert exp is not None and exp.kind == "selection"
|
|
result = SelectionResult.model_validate_json(exp.result_json)
|
|
assert len(result.candidates) == 3
|
|
assert "as_of" in (exp.summary_text or "") and "选出 3" in (exp.summary_text or "")
|
|
|
|
|
|
class TestSelectionJobApi:
|
|
@pytest.fixture()
|
|
def client(self, tmp_path, monkeypatch):
|
|
from app.infrastructure.persistence.sqlalchemy import session as sess_mod
|
|
|
|
engine = create_engine(f"sqlite:///{tmp_path / 'api.db'}", future=True)
|
|
Base.metadata.create_all(engine)
|
|
Session = sessionmaker(bind=engine, expire_on_commit=False)
|
|
monkeypatch.setattr(sess_mod, "SessionLocal", Session)
|
|
df = synthetic_daily({s: 0.006 - 0.0015 * i for i, s in enumerate(_SYMS)}, n=320)
|
|
with Session() as session:
|
|
SqlAlchemyStockRepository(session).upsert_many(
|
|
[Stock(symbol=s, name=f"测试{i}", list_date=date(1999, 1, 1))
|
|
for i, s in enumerate(_SYMS)]
|
|
)
|
|
SqlAlchemyDailyBarRepository(session).upsert_many(bars_dataframe_to_daily_bars(df))
|
|
session.commit()
|
|
|
|
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()
|
|
|
|
def test_submit_poll(self, client) -> None:
|
|
body = _query().model_dump(mode="json")
|
|
resp = client.post("/api/selections/jobs", json=body)
|
|
assert resp.status_code == 200
|
|
job_id = resp.json()["job_id"]
|
|
state = None
|
|
for _ in range(40):
|
|
state = client.get(f"/api/jobs/{job_id}").json()
|
|
if state["status"] in ("success", "failed", "cancelled"):
|
|
break
|
|
assert state["status"] == "success"
|
|
result = state["result"]
|
|
assert result is not None and len(result["candidates"]) == 3
|
|
assert result["statistics"]["selected"] == 3
|
|
# 实验归档存在(selection 类型)
|
|
exps = client.get("/api/experiments").json()
|
|
assert any(e["kind"] == "selection" for e in exps)
|