feat: Phase 3 Web — 业务 API(stocks/factors/backtests)+ Next.js 前端
- 后端业务 API:GET /api/stocks(搜索/分页)、GET /api/factors(因子目录)、POST /api/factor-tests 与 /api/backtests(Research Spec 驱动同步执行)、GET /api/backtests/last;Annotated 依赖注入 + CORS(dev) - Repository 批量查询 get_range_many(研究装配一次查询,避免逐只拉取) - 前端 frontend/web:Next.js 15(TS) + ECharts —— 总览 / 股票池 / 因子研究(IC·RankIC·分层展示) / 回测(净值·回撤·月度·持仓·未建模标注) - 前端只消费业务 API 与标准化 BacktestResult,无 Qlib/SQL 概念泄漏 - 真实数据:同步 20 只权重股 2023-2024 日线(9680 根)支撑截面研究 - 验证:API 集成测试 8 项(DTO 校验/装配/引擎/标准结果,内存 repo 全链路)+ 全量 pytest 68 passed;前端 tsc + next build 通过;无头浏览器端到端(factors/backtest 页面渲染后端数据) - ruff clean
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
"""API 依赖注入:Repository / 研究服务的装配点(composition root 的一部分)。
|
||||
|
||||
路由层统一使用 Annotated 注入(FastAPI 推荐写法,配合 ruff B008 无冲突)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.domain.repositories.market import (
|
||||
DailyBarRepository,
|
||||
StockRepository,
|
||||
)
|
||||
from app.infrastructure.persistence.sqlalchemy.repositories.market_impl import (
|
||||
SqlAlchemyDailyBarRepository,
|
||||
SqlAlchemyStockRepository,
|
||||
)
|
||||
from app.infrastructure.persistence.sqlalchemy.session import get_session
|
||||
from app.quant.engine import LocalEngine, QuantEngine
|
||||
from app.quant.service import ResearchService
|
||||
|
||||
DbSession = Annotated[Session, Depends(get_session)]
|
||||
|
||||
|
||||
def _stock_repo_factory(session: DbSession) -> StockRepository:
|
||||
return SqlAlchemyStockRepository(session)
|
||||
|
||||
|
||||
def _daily_repo_factory(session: DbSession) -> DailyBarRepository:
|
||||
return SqlAlchemyDailyBarRepository(session)
|
||||
|
||||
|
||||
def _engine_factory() -> QuantEngine:
|
||||
return LocalEngine()
|
||||
|
||||
|
||||
def _service_factory(
|
||||
stock_repo: Annotated[StockRepository, Depends(_stock_repo_factory)],
|
||||
daily_repo: Annotated[DailyBarRepository, Depends(_daily_repo_factory)],
|
||||
engine: Annotated[QuantEngine, Depends(_engine_factory)],
|
||||
) -> ResearchService:
|
||||
return ResearchService(stock_repo, daily_repo, engine)
|
||||
|
||||
|
||||
StockRepoDep = Annotated[StockRepository, Depends(_stock_repo_factory)]
|
||||
DailyRepoDep = Annotated[DailyBarRepository, Depends(_daily_repo_factory)]
|
||||
EngineDep = Annotated[QuantEngine, Depends(_engine_factory)]
|
||||
ResearchServiceDep = Annotated[ResearchService, Depends(_service_factory)]
|
||||
@@ -0,0 +1,25 @@
|
||||
"""因子目录 API:/api/factors。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.quant.factors import list_factors
|
||||
|
||||
router = APIRouter(prefix="/factors", tags=["factors"])
|
||||
|
||||
|
||||
@router.get("", summary="因子目录(含元数据)")
|
||||
def list_factor_catalog() -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"name": d.name,
|
||||
"description": d.description,
|
||||
"formula": d.formula,
|
||||
"frequency": d.frequency,
|
||||
"lookback": d.lookback,
|
||||
"direction": d.direction,
|
||||
"requires": list(d.requires),
|
||||
}
|
||||
for d in list_factors()
|
||||
]
|
||||
@@ -0,0 +1,56 @@
|
||||
"""研究执行 API:/api/factor-tests 与 /api/backtests。
|
||||
|
||||
Phase 3 为同步执行(样本有限);Phase 4 将改为 Job + SSE 异步(接口契约不变)。
|
||||
最近一次结果在内存中可读,便于前端展示;持久化实验归档在 Phase 4。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from app.api.deps import ResearchServiceDep
|
||||
from app.domain.entities.research import (
|
||||
BacktestResult,
|
||||
FactorTestReport,
|
||||
ResearchSpec,
|
||||
)
|
||||
from app.quant.factors import FactorError
|
||||
|
||||
router = APIRouter(tags=["research"])
|
||||
|
||||
# 内存中的最近结果(Phase 4 迁移到 Experiment 表)
|
||||
_LAST_BACKTEST: dict[str, BacktestResult] = {}
|
||||
_LAST_FACTOR_TEST: dict[str, FactorTestReport] = {}
|
||||
|
||||
|
||||
@router.post("/factor-tests", response_model=FactorTestReport, summary="运行单因子测试(同步)")
|
||||
def run_factor_test(
|
||||
spec: ResearchSpec,
|
||||
service: ResearchServiceDep,
|
||||
) -> FactorTestReport:
|
||||
try:
|
||||
report = service.run_factor_test(spec)
|
||||
except (ValueError, FactorError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
_LAST_FACTOR_TEST["default"] = report
|
||||
return report
|
||||
|
||||
|
||||
@router.post("/backtests", response_model=BacktestResult, summary="运行回测(同步)")
|
||||
def run_backtest(
|
||||
spec: ResearchSpec,
|
||||
service: ResearchServiceDep,
|
||||
) -> BacktestResult:
|
||||
try:
|
||||
result = service.run_backtest(spec)
|
||||
except (ValueError, FactorError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
_LAST_BACKTEST["default"] = result
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/backtests/last", response_model=BacktestResult, summary="最近一次回测结果")
|
||||
def last_backtest() -> BacktestResult:
|
||||
if "default" not in _LAST_BACKTEST:
|
||||
raise HTTPException(status_code=404, detail="尚无回测结果,请先 POST /api/backtests")
|
||||
return _LAST_BACKTEST["default"]
|
||||
@@ -1,14 +1,17 @@
|
||||
"""API 路由聚合。
|
||||
|
||||
后续业务路由按 AGENT.md §17 面向业务对象挂载:
|
||||
/api/stocks /api/universes /api/factors /api/strategies /api/backtests /api/experiments /api/jobs
|
||||
业务路由面向业务对象(AGENT.md §17):/api/stocks /api/factors
|
||||
/api/factor-tests /api/backtests /api/experiments(Phase4) /api/jobs(Phase4) /api/agent(Phase5)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api import health
|
||||
from app.api import factors, health, research, stocks
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(health.router)
|
||||
api_router.include_router(stocks.router)
|
||||
api_router.include_router(factors.router)
|
||||
api_router.include_router(research.router)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""股票查询 API:/api/stocks。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from app.api.deps import StockRepoDep
|
||||
from app.domain.entities.market import Stock
|
||||
|
||||
router = APIRouter(prefix="/stocks", tags=["stocks"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[Stock], summary="股票列表")
|
||||
def list_stocks(
|
||||
repo: StockRepoDep,
|
||||
q: str | None = None,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
) -> list[Stock]:
|
||||
if limit > 500:
|
||||
limit = 500
|
||||
stocks = repo.list()
|
||||
if q:
|
||||
needle = q.upper()
|
||||
stocks = [s for s in stocks if needle in s.symbol or needle in s.name.upper()]
|
||||
return stocks[offset : offset + limit]
|
||||
|
||||
|
||||
@router.get("/{symbol}", response_model=Stock, summary="按代码查询")
|
||||
def get_stock(symbol: str, repo: StockRepoDep) -> Stock:
|
||||
stock = repo.get_by_symbol(symbol)
|
||||
if stock is None:
|
||||
raise HTTPException(status_code=404, detail=f"未找到股票 {symbol}")
|
||||
return stock
|
||||
Reference in New Issue
Block a user