feat(backend): 字段库(condition_field)+ 因子参数化(模板/受控参数)+ 单位换算底座
字段库(本次新增的表与接口): - `condition_field` 表 + `/api/condition-fields`:中文名/说明可编辑、可停用; `kind`/单位阶梯/`base_unit` 由代码注册表收敛(改类型 422,伪字段 422, 越界单位 422),停用的字段不再进条件下拉,但既有策略仍按名字解析。 - 说明书里的数值条件按字段注册表补**基准单位**后缀(字段间比较不加,不猜单位)。 因子参数化(键即身份,冻结口径): - 模板 + 参数注册表(`quant/factors.py`):`ParamSpec`(类型/范围/枚举/默认值/说明)+ `FactorTemplate`(公式/依赖列/参数);规范键把**全部**参数写进名字,如 `momentum(window=90,direction=lower_is_better)`,所以改参数 = 新建一个身份, 旧因子/既有策略/已归档实验都不变义;`momentum(window=90)`(缺参数)明确拒绝 —— 缺项要靠模板默认值补齐,而默认值是可改的代码细节,一旦改动会追溯性改义。 - 参数只在受控范围内取值(窗口 2~500、方向二选一),越界/未知模板/多给参数一律 422 并列出允许范围,不静默截断、不悄悄取默认值;内置实例的启用开关由代码决定(422)。 - `/api/factors` 暴露 `template`/`params`/`param_specs`/`label`/`source`/`enabled`/ `resolvable`;新增 `/api/factors/templates`、`POST /api/factors`、`PATCH /api/factors`; `get_factor = resolve_factor` 兼容全部旧调用点,参数化键也是一等条件字段。 - 迁移链:c5d6(存量策略陈旧说明重算)→ d6e7(condition_field)→ a7c1 (factor_definition.enabled + name varchar(128))。 测试:新增 test_condition_fields.py / test_factor_params.py;全量 pytest 500 passed。
This commit is contained in:
@@ -18,7 +18,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from app.domain.entities.research import CostSpec
|
||||
|
||||
@@ -31,8 +31,13 @@ class GlobalConfig(BaseModel):
|
||||
为什么把复权口径也放这里:一次回测只能有一个复权口径(同一份行情不能既前复权
|
||||
又后复权),而多个选股策略可能想混用 —— 与其让它们在组合里打架,不如统一为
|
||||
全局口径,高股息默认 hfq。若将来确需按组合区分,再加字段即可(向前兼容)。
|
||||
|
||||
`extra="forbid"`:PUT /api/config 若带未知字段(拼错键名、旧版遗留键)直接报错,
|
||||
避免「以为改了某项、其实被静默忽略」。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str = Field(default="default", description="单例主键,恒为 default")
|
||||
commission_rate: float = Field(default=0.0003, ge=0, le=0.01, description="佣金率(如 0.0003 = 万三)")
|
||||
stamp_tax_rate: float = Field(default=0.0005, ge=0, le=0.01, description="印花税率(仅卖出)")
|
||||
@@ -72,8 +77,13 @@ class BacktestCombo(BaseModel):
|
||||
- `hold_max_days` = Tmax:个股**最多**持有天数 —— 超过即强制了结(None = 不限)。
|
||||
- `rebalance_freq`:多久重新打分排序并调仓一次(日/周/月)。
|
||||
⚠️ Tmax 强制卖出**每个交易日**都检查(不只调仓日),否则月频下会远超 Tmax。
|
||||
|
||||
`extra="forbid"`:回测参数写错键名(如 hold_days、capital)时报错而非静默用默认值 ——
|
||||
静默用默认值会让「我明明设了 30 天」变成「其实没生效」,是本项目明确禁止的降级方式。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str = ""
|
||||
name: str = Field(min_length=1, max_length=64)
|
||||
description: str = ""
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""字段库领域实体(2026-10:过滤条件字段目录 DB 化)。
|
||||
|
||||
与因子目录(``FactorDefinition``)同一套思路:
|
||||
|
||||
- **DB 是字段库的契约源**:中文名、含义、单位、是否启用、自定义条目都入库;
|
||||
- **引擎是字段可用性的唯一事实来源**:字段能不能算由 ``quant.condition_fields``
|
||||
对着引擎域校验,登记不出来的字段一律拒绝(防「建出来永远选不出股票」的伪字段)。
|
||||
|
||||
可编辑边界(有意为之):
|
||||
- ``name`` 是引擎字段名,**不可改**(改了就指向另一个字段,等于换字段);
|
||||
- ``kind`` 由引擎类型决定,**不可改**(字符串字段不能比大小);
|
||||
- ``label`` / ``description`` / ``group_name`` / ``unit`` / ``enabled`` 可编辑 ——
|
||||
内置字段也允许改文案(seed「只补不删」,不会覆盖用户的措辞)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, computed_field
|
||||
|
||||
FIELD_KINDS: tuple[str, ...] = ("num", "str")
|
||||
FIELD_SOURCES: tuple[str, ...] = ("builtin", "custom")
|
||||
|
||||
# 类型 → 可用比较符(单一事实来源)。
|
||||
# 字符串字段只能等值/集合:引擎 _compare 对字符串的 >/≥/</≤ 一律返回 False,
|
||||
# 若前端把「行业 > 5」这类选项摆出来,用户点出来的就是永远为假的条件。
|
||||
OPS_NUM: tuple[str, ...] = ("gt", "gte", "lt", "lte", "eq", "ne")
|
||||
OPS_STR: tuple[str, ...] = ("eq", "ne", "in", "not_in")
|
||||
OPS_BY_KIND: dict[str, tuple[str, ...]] = {"num": OPS_NUM, "str": OPS_STR}
|
||||
|
||||
|
||||
class ConditionField(BaseModel):
|
||||
"""字段库中的一个条件字段。"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str = Field(min_length=1, max_length=64, description="引擎字段名,如 dv_ratio / static.industry")
|
||||
label: str = Field(default="", max_length=64, description="中文名(下拉里展示)")
|
||||
description: str = Field(default="", max_length=500, description="含义 / 口径(含单位)")
|
||||
kind: str = Field(default="num", pattern="^(num|str)$")
|
||||
group_name: str = Field(default="行情", max_length=32)
|
||||
unit: str = Field(default="", max_length=16)
|
||||
source: str = Field(default="builtin", pattern="^(builtin|custom)$")
|
||||
enabled: bool = Field(default=True, description="False=从选择器隐藏(内置不可删除,只能停用)")
|
||||
sort_order: int = 100
|
||||
created_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
|
||||
@computed_field # type: ignore[prop-decorator]
|
||||
@property
|
||||
def ops(self) -> list[str]:
|
||||
"""该字段可用的比较符(前端据此收窄下拉,不自己猜)。"""
|
||||
return list(OPS_BY_KIND.get(self.kind, OPS_NUM))
|
||||
@@ -1,19 +1,51 @@
|
||||
"""因子目录领域实体(M7.1:因子元数据 DB 化,v2 §11)。
|
||||
"""因子目录领域实体(M7.1:因子元数据 DB 化,v2 §11;2026-10 参数化)。
|
||||
|
||||
DB 是因子目录的契约源:元数据(含自定义因子登记)入库;
|
||||
计算执行仍由代码注册表(quant/factors.py)提供 —— 登记但未注册计算的因子
|
||||
在 score/condition 中引用时仍抛 FactorError(防静默伪因子)。
|
||||
DB 是因子目录的契约源:**哪些因子存在**(含用户从模板派生的参数化实例)入库;
|
||||
**能不能算**仍由代码注册表(quant/factors.py)唯一决定 —— 登记但解析不出来的因子
|
||||
在 score/condition 里引用时抛 FactorError(不假装支持)。
|
||||
|
||||
参数化的读法:参数化实例的名字本身就是身份(`momentum(window=90,direction=...…)`),
|
||||
所以 template / params / param_specs / label / source / resolvable 都是**由名字解析出来的
|
||||
投影**,不落库。落库的只有 `enabled`(是否出现在下拉里)—— 这是人做的配置,
|
||||
不是引擎事实。好处:参数不可能出现「表里一套、键里一套」的分裂。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class FactorParam(BaseModel):
|
||||
"""一个可编辑参数的约束(与 quant/factors.ParamSpec 对齐,供界面渲染表单)。"""
|
||||
|
||||
name: str
|
||||
label: str = ""
|
||||
kind: str = "int" # "int" | "enum"
|
||||
default: Any = None
|
||||
minimum: int | None = None
|
||||
maximum: int | None = None
|
||||
choices: list[str] = Field(default_factory=list)
|
||||
note: str = ""
|
||||
|
||||
@classmethod
|
||||
def from_spec(cls, spec) -> FactorParam:
|
||||
return cls(
|
||||
name=spec.name,
|
||||
label=spec.label,
|
||||
kind=spec.kind,
|
||||
default=spec.default,
|
||||
minimum=spec.minimum,
|
||||
maximum=spec.maximum,
|
||||
choices=list(spec.choices),
|
||||
note=spec.note,
|
||||
)
|
||||
|
||||
|
||||
class FactorDefinition(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
description: str = ""
|
||||
formula: str = ""
|
||||
brief: str = ""
|
||||
@@ -23,10 +55,23 @@ class FactorDefinition(BaseModel):
|
||||
requires: list[str] = Field(default_factory=list)
|
||||
version: str = "1"
|
||||
created_at: datetime | None = None
|
||||
# ---- 参数化(落库的只有 enabled;其余由 name 解析投影而来)----
|
||||
enabled: bool = True
|
||||
template: str = "" # 模板名,如 "momentum"
|
||||
params: dict[str, Any] = Field(default_factory=dict) # 冻结的参数取值
|
||||
param_specs: list[FactorParam] = Field(default_factory=list) # 可编辑参数与约束
|
||||
label: str = "" # 中文显示名(含参数)
|
||||
source: str = "builtin" # builtin(代码注册表实例)| custom(目录里的参数化实例)
|
||||
resolvable: bool = True # False = 登记了但引擎算不出来(历史手工登记行)
|
||||
|
||||
@classmethod
|
||||
def from_registry_def(cls, d) -> FactorDefinition:
|
||||
"""由 quant/factors.FactorDef(dataclass)构造目录实体(seed 用)。"""
|
||||
return cls.from_factor_def(d, enabled=True)
|
||||
|
||||
@classmethod
|
||||
def from_factor_def(cls, d, *, enabled: bool = True) -> FactorDefinition:
|
||||
"""由因子实例(内置或参数化)构造目录实体(seed / 新建用)。"""
|
||||
return cls(
|
||||
name=d.name,
|
||||
description=d.description,
|
||||
@@ -36,4 +81,11 @@ class FactorDefinition(BaseModel):
|
||||
lookback=d.lookback,
|
||||
direction=d.direction,
|
||||
requires=list(d.requires),
|
||||
)
|
||||
enabled=enabled,
|
||||
template=d.template,
|
||||
params=dict(d.params),
|
||||
param_specs=[FactorParam.from_spec(s) for s in d.param_specs],
|
||||
label=d.label,
|
||||
source=d.source,
|
||||
resolvable=True,
|
||||
)
|
||||
@@ -54,6 +54,10 @@ class ConditionSpec(BaseModel):
|
||||
|
||||
右操作数取 value(字面量)或 ref(另一字段名),二者二选一。
|
||||
|
||||
字段域的事实来源:`quant/condition_fields.py`(字段库注册表,含中文名与口径)。
|
||||
`/api/condition-fields`(前端下拉)、该注册表与引擎求值共用同一份定义,
|
||||
避免「前端列一个、引擎算另一个」的漂移。
|
||||
|
||||
定义位置说明:本模型被 ResearchSpec(回测)与 SelectionQuery(选股)共用,
|
||||
故落在 research.py(被 selection.py 依赖的低层模块),selection.py 再 re-export,
|
||||
避免循环导入。
|
||||
|
||||
@@ -12,18 +12,29 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.domain.entities.research import ConditionSpec, FactorSpec, UniverseSpec
|
||||
|
||||
|
||||
class SelectionStrategy(BaseModel):
|
||||
"""一个选股策略 = 选股条件组合(不含任何回测执行参数)。"""
|
||||
"""一个选股策略 = 选股条件组合(不含任何回测执行参数)。
|
||||
|
||||
`extra="forbid"`(2026-09 收尾):请求里若混入旧版的回测执行参数(selection /
|
||||
rebalance / costs / portfolio / initial_capital / period …),一律**报错**而不是
|
||||
静默丢弃 —— 否则调用方会以为「在策略上设了费率/调仓」,实际服务端根本没存
|
||||
(AGENT.md 禁止静默降级与假装支持)。回测参数的正确位置是 BacktestCombo + GlobalConfig。
|
||||
兼容性:历史行残留的旧键由仓储 `_to_entity` 在**读出前**剔除,因此不受 forbid 影响。
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: str = ""
|
||||
name: str = Field(min_length=1, max_length=64)
|
||||
description: str = ""
|
||||
spec_type: str = Field(default="selection", pattern="^(selection|backtest)$")
|
||||
# 取值域收敛为 selection:本实体就是「选股策略」。历史 DB 列里的 "backtest"
|
||||
# 不会被读出(仓储 _to_entity 丢弃该键并回落到默认值),故收紧不会破坏旧数据。
|
||||
spec_type: str = Field(default="selection", pattern="^selection$")
|
||||
universe: UniverseSpec = UniverseSpec()
|
||||
factors: list[FactorSpec] = Field(min_length=1, description="打分因子(至少 1 个)")
|
||||
conditions: list[ConditionSpec] = Field(
|
||||
@@ -33,7 +44,7 @@ class SelectionStrategy(BaseModel):
|
||||
created_at: datetime | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _no_duplicate_factors(self) -> "SelectionStrategy":
|
||||
def _no_duplicate_factors(self) -> SelectionStrategy:
|
||||
names = [f.name for f in self.factors]
|
||||
if len(set(names)) != len(names):
|
||||
raise ValueError("factors 存在重复因子名")
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""字段库 Repository 协议(依赖倒置)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Protocol
|
||||
|
||||
from app.domain.entities.condition_field import ConditionField
|
||||
|
||||
|
||||
class ConditionFieldRepository(Protocol):
|
||||
def list(self) -> list[ConditionField]:
|
||||
"""按 sort_order, name 排序返回全部条目(含停用项)。"""
|
||||
...
|
||||
|
||||
def get(self, name: str) -> ConditionField | None: ...
|
||||
|
||||
def insert_missing(self, items: list[ConditionField]) -> int:
|
||||
"""只插入不存在的条目(seed 内置字段用)。
|
||||
|
||||
语义上是「只补不删、不覆盖」:已存在的行**原样保留** —— 用户在字段库里
|
||||
改过的中文名/含义不会被下次 seed 冲掉(与 factor_definition 同规矩)。
|
||||
"""
|
||||
...
|
||||
|
||||
def save(self, item: ConditionField) -> ConditionField:
|
||||
"""新增或整体更新一条(自定义字段增改、内置字段改文案/停用)。"""
|
||||
...
|
||||
|
||||
def delete(self, name: str) -> bool: ...
|
||||
Reference in New Issue
Block a user