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:
+48
@@ -0,0 +1,48 @@
|
||||
"""factor_definition:支持参数化因子实例(2026-10)
|
||||
|
||||
两处改动:
|
||||
1. `name` 64 → 128:参数化实例把参数写进名字
|
||||
(`momentum(window=90,direction=higher_is_better)`),64 位不够留余量。
|
||||
2. 新增 `enabled`:唯一由人配置的字段 —— 是否出现在因子下拉/字段库里。
|
||||
内置实例的开关注仍由代码注册表收敛;停用**不影响**已引用它的策略/归档解析,
|
||||
历史口径不能被开关改义。
|
||||
|
||||
SQLite 不支持直接改列类型,因此用 batch_alter_table(与本仓库既有迁移一致)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "a7c1e4b90f21"
|
||||
down_revision: str | None = "d6e7f8a9b0c1"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("factor_definition", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"name",
|
||||
existing_type=sa.String(length=64),
|
||||
type_=sa.String(length=128),
|
||||
existing_nullable=False,
|
||||
)
|
||||
op.add_column(
|
||||
"factor_definition",
|
||||
sa.Column("enabled", sa.Boolean(), nullable=False, server_default="1"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("factor_definition", "enabled")
|
||||
with op.batch_alter_table("factor_definition", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"name",
|
||||
existing_type=sa.String(length=128),
|
||||
type_=sa.String(length=64),
|
||||
existing_nullable=False,
|
||||
)
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
"""重算存量选股策略的过时 description(2026-09 重构收尾)
|
||||
|
||||
Revision ID: c5d6e7f8a9b0
|
||||
Revises: b4c5d6e7f8a9
|
||||
Create Date: 2026-10-01
|
||||
|
||||
背景:b4c5d6e7f8a9 把一个策略的 config_json 里回测执行参数剥掉了,但**没有**重算
|
||||
`strategy.description`。旧描述是重构前由 describe_strategy 从「全套参数」自动生成的,
|
||||
于是策略库里会出现这种自相矛盾的说明:
|
||||
|
||||
「…每 6 个月重新择股、每 6 个月调仓,后复权口径、按调仓日收盘价成交
|
||||
(含佣金 0.03%/印花税 0.05%/滑点 0.1%)。」
|
||||
|
||||
而选股策略现在**不再持有**调仓/成本/复权,这些由「回测组合 + 公共配置」在回测时决定。
|
||||
本迁移用当前口径的 describe_strategy(纯函数,无 IO/DB)重算这些陈旧说明。
|
||||
|
||||
安全性 —— 只改「可证明是旧自动生成」的行,不碰人工撰写的说明:
|
||||
1. description 为空/纯空白(API 保存契约要求必须有说明,空值必然是历史遗留)→ 补全;
|
||||
2. description 含旧自动文案独有的回测执行词(佣金/印花税/滑点/调仓/择股/复权口径/
|
||||
收盘价成交/最低佣金/初始资金)→ 重算。新口径的说明**绝不会**出现这些词
|
||||
(见 strategy_doc._describe_selection_only),因此命中即旧自动文案。
|
||||
其余行原样保留(kept)。无法解析/校验失败的行跳过并打印告警,绝不静默改写。
|
||||
|
||||
为什么在迁移里 import 应用代码:说明文本的唯一事实来源就是 `describe_strategy`
|
||||
(AGENT.md §24:不许另写一份近似文案)。自己复制一份文案逻辑才是真正的漂移风险。
|
||||
代价是该迁移的产物依赖当时的代码版本 —— 对「一次性回填存量说明」这个用途可以接受,
|
||||
且新库 upgrade 时 strategy 表为空、不受影响。
|
||||
|
||||
downgrade 仅回滚结构层面:**不恢复**被重算的旧说明(原文未备份),因此不可逆。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "c5d6e7f8a9b0"
|
||||
down_revision: str | None = "b4c5d6e7f8a9"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
# 与 strategy.description 列宽一致(StrategyModel.description = String(300))
|
||||
_DESCRIPTION_MAX_CHARS = 300
|
||||
|
||||
# 选股策略不再承载的键(与 b4c5d6e7f8a9 一致;历史行可能仍残留)
|
||||
_LEGACY_KEYS = (
|
||||
"selection",
|
||||
"rebalance",
|
||||
"costs",
|
||||
"portfolio",
|
||||
"price_adjustment",
|
||||
"selection_interval_months",
|
||||
"rebalance_interval_months",
|
||||
)
|
||||
|
||||
# 由 DB 列承载、不应从 config_json 再喂给实体的键
|
||||
_COLUMN_KEYS = ("id", "name", "description", "spec_type", "version")
|
||||
|
||||
# 旧「全套参数」自动文案独有的回测执行词 —— 新口径说明不会出现(命中即认定陈旧)
|
||||
_LEGACY_MARKERS = (
|
||||
"佣金",
|
||||
"印花税",
|
||||
"滑点",
|
||||
"调仓",
|
||||
"择股",
|
||||
"复权口径",
|
||||
"收盘价成交",
|
||||
"最低佣金",
|
||||
"初始资金",
|
||||
)
|
||||
|
||||
_LEGACY_MARKER_RE = re.compile("|".join(_LEGACY_MARKERS))
|
||||
|
||||
|
||||
def _truncate(text: str) -> str:
|
||||
"""与 API 的说明补全同口径:超列宽按字符截断并显式加省略号。"""
|
||||
if len(text) <= _DESCRIPTION_MAX_CHARS:
|
||||
return text
|
||||
return text[: _DESCRIPTION_MAX_CHARS - 1] + "…"
|
||||
|
||||
|
||||
def _derive_summary(name: str, description: str, data: dict) -> str | None:
|
||||
"""按当前口径重算一句话说明;无法构造实体时返回 None(调用方跳过并告警)。"""
|
||||
# 延迟 import:保持迁移模块导入轻量,且让 alembic env 先完成自身引导。
|
||||
from app.domain.entities.strategy import SelectionStrategy
|
||||
from app.quant.strategy_doc import describe_strategy
|
||||
|
||||
payload = dict(data)
|
||||
for key in _COLUMN_KEYS + _LEGACY_KEYS:
|
||||
payload.pop(key, None)
|
||||
try:
|
||||
st = SelectionStrategy(name=name, description=description, **payload)
|
||||
except Exception as exc: # noqa: BLE001 —— 逐行容错:坏行跳过并告警,不阻断整次迁移
|
||||
print(f"[refresh-strategy-docs] 跳过无法解析的策略 {name!r}: {exc}", flush=True)
|
||||
return None
|
||||
return describe_strategy(st).summary
|
||||
|
||||
|
||||
def _is_stale(name: str, description: str) -> bool:
|
||||
return (not (description or "").strip()) or bool(_LEGACY_MARKER_RE.search(description or ""))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
rows = conn.execute(
|
||||
sa.text("SELECT id, name, description, config_json FROM strategy")
|
||||
).fetchall()
|
||||
|
||||
rewritten = kept = broken = 0
|
||||
for row_id, name, description, cfg_text in rows:
|
||||
try:
|
||||
data = json.loads(cfg_text) if cfg_text else {}
|
||||
except json.JSONDecodeError:
|
||||
broken += 1
|
||||
print(f"[refresh-strategy-docs] 跳过 config_json 损坏的策略 {row_id}", flush=True)
|
||||
continue
|
||||
if not isinstance(data, dict):
|
||||
broken += 1
|
||||
print(f"[refresh-strategy-docs] 跳过 config_json 非对象的策略 {row_id}", flush=True)
|
||||
continue
|
||||
if not _is_stale(name, description):
|
||||
kept += 1 # 人工撰写的说明:不动它
|
||||
continue
|
||||
summary = _derive_summary(name, description or "", data)
|
||||
if summary is None:
|
||||
broken += 1
|
||||
continue
|
||||
summary = _truncate(summary)
|
||||
if summary == (description or ""):
|
||||
kept += 1
|
||||
continue
|
||||
conn.execute(
|
||||
sa.text("UPDATE strategy SET description = :desc WHERE id = :id"),
|
||||
{"desc": summary, "id": row_id},
|
||||
)
|
||||
rewritten += 1
|
||||
|
||||
print(
|
||||
f"[refresh-strategy-docs] 重算 {rewritten} 条陈旧/空说明,"
|
||||
f"保留 {kept} 条,跳过 {broken} 条异常行(共 {len(rows)} 条)",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# 旧说明原文未备份,无法还原:回滚只表示「结构层面无事可做」。
|
||||
# 显式空实现(而非 pass 无说明),避免读者误以为会恢复文案。
|
||||
print(
|
||||
"[refresh-strategy-docs] downgrade:被重算的说明不可还原(原文未备份),不执行任何写操作",
|
||||
flush=True,
|
||||
)
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
"""condition_field 表(2026-10 字段库:过滤条件字段目录入库)
|
||||
|
||||
Revision ID: d6e7f8a9b0c1
|
||||
Revises: c5d6e7f8a9b0
|
||||
Create Date: 2026-10-01
|
||||
|
||||
背景:策略库的过滤条件此前只能手填字段名(dv_ratio / static.industry …),
|
||||
用户看不到含义、写错也不报错(未知字段求值恒为 None,条件永远不通过)。
|
||||
本表存放字段库目录:内置字段由 quant/condition_fields.py 注册表在 API 首次读取时
|
||||
seed(只补不删,不覆盖用户改过的文案),自定义字段与停用状态也落在本表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "d6e7f8a9b0c1"
|
||||
down_revision: str | None = "c5d6e7f8a9b0"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"condition_field",
|
||||
sa.Column("name", sa.String(length=64), nullable=False),
|
||||
sa.Column("label", sa.String(length=64), nullable=False),
|
||||
sa.Column("description", sa.String(length=500), nullable=False),
|
||||
sa.Column("kind", sa.String(length=8), nullable=False),
|
||||
sa.Column("group_name", sa.String(length=32), nullable=False),
|
||||
sa.Column("unit", sa.String(length=16), nullable=False),
|
||||
sa.Column("source", sa.String(length=8), nullable=False),
|
||||
sa.Column("enabled", sa.Boolean(), nullable=False),
|
||||
sa.Column("sort_order", sa.Integer(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("condition_field")
|
||||
Reference in New Issue
Block a user