修复缺行情资金提示与成本导出精度

This commit is contained in:
baobao 2026-11-04 09:36:09 +08:00
parent af681bbb75
commit 484aa2a879
15 changed files with 575 additions and 45 deletions

View File

@ -1,5 +1,11 @@
# 开发节点记录(三系统量化交易)
## 2026-11-04 策略缺行情展示和成本精度修复
09:25在155确认资金提示的ValueError实际为雷赛智能缺少盘前分钟行情,数量对账正常;09:30行情自然恢复后现金差0。修改只读估值为逐策略保留未知值,现金、数量继续独立核对,严格划拨和日结健康判断不放宽。成本均价固定显示三位,导出保留原始加权精度并按金额计算盈亏,补零股保护。用户确认48.296是含费成本,而原QMT成交及最新持仓均48.290、费用未知,故不改写成交或猜测手续费。自然执行依据刷新还暴露Decimal无法编码,复用既有JSON类型转换修复。
新增估值18、精度8、执行依据编码5项隔离检查,页面与全量验证及实际发布结果见[本次接续](docs/策略估值与成本精度修复_2026-11-04.md)。本条为实施记录,部署结果另补,不能当作已上线回执。
> 这份文件的用途只有一个:**让下一次交接不必重新查一遍**。
> 每个重要节点写一条,写完就补,不攒到最后。一条节点包含五样东西:
> 做了什么、动了哪些文件、部署方式、真机判收结果、还欠着什么。

View File

@ -14,16 +14,22 @@ def seed(cash, values):
def metrics(account, values):
"""缺少市值时保留现金和本金,不把未知市值算成零。"""
result = {}
for b in BOOKS:
equity = account['cash'][b]+values.get(b, 0.)
market_value = values.get(b, 0.)
equity = account['cash'][b]+market_value if market_value is not None else None
units = account['units'][b]
result[b] = {'cash': account['cash'][b], 'market_value': values.get(b, 0.), 'equity': equity,
'net_capital': account['net_capital'][b], 'profit': equity-account['net_capital'][b],
'nav': equity/units if units > 1e-8 else None, 'fees': account['fees'][b]}
result['account'] = {'cash': sum(account['cash'].values()), 'market_value': sum(values.values()),
'equity': sum(r['equity'] for r in result.values()),
'profit': sum(r['profit'] for r in result.values()), 'fees': sum(account['fees'].values())}
result[b] = {'cash': account['cash'][b], 'market_value': market_value, 'equity': equity,
'net_capital': account['net_capital'][b],
'profit': equity-account['net_capital'][b] if equity is not None else None,
'nav': equity/units if equity is not None and units > 1e-8 else None, 'fees': account['fees'][b]}
complete = all(r['market_value'] is not None for r in result.values())
result['account'] = {'cash': sum(account['cash'].values()),
'market_value': sum(r['market_value'] for r in result.values()) if complete else None,
'equity': sum(r['equity'] for r in result.values()) if complete else None,
'profit': sum(r['profit'] for r in result.values()) if complete else None,
'fees': sum(account['fees'].values())}
return result
@ -37,6 +43,8 @@ def transfer(account, source, target, amount, values, key):
raise ValueError('划拨参数非法')
if account['cash'][source]+1e-6 < amount:
raise ValueError('策略可划拨现金不足')
if any(v is None or not math.isfinite(v) for v in values.values()):
raise ValueError('策略估值不完整,不能划拨现金')
before = metrics(account, values)
for b, change in ((source, -amount), (target, amount)):
nav = before[b]['nav']

View File

@ -73,9 +73,11 @@ def status() -> dict:
def _post(url: str, payload: dict, timeout: int) -> dict:
"""HTTP 一跳, 单测在这里打桩。"""
"""HTTP 一跳;数据库数值保持 JSON 数值,不转成展示用字符串。"""
import requests
r = requests.post(url, json=payload, timeout=timeout)
# 独立执行依据刷新直接读取仓储,成本与参考位可能仍为 Decimal。
# 复用研判接口的明确类型转换,未知类型和非有限数仍由 JSON 编码拒绝。
r = requests.post(url, json=judge.jsonable(payload), timeout=timeout)
r.raise_for_status()
return r.json() or {}

View File

@ -20,7 +20,8 @@
* 自然天数 = 起始日到截止日**含头含尾** (模板实测口径: 7-03 到 8-03 记 32 天)。
金额口径 (逐项对模板核过数):
* 持仓行: 浮动盈亏 = (现价 − 成本) × 数量, **不含费** (模板 S 列与 Q×L 逐分一致)。
* 持仓行: 浮动盈亏 = 市值 − 成本金额, **不含费**。均价保留计算精度、显示三位,
金额按分舍入;不能先把均价舍入到三位再乘数量。
* 平仓行: 盈亏 = 批次已实现盈亏 − **平仓当日该票的费用** (模板卖出行含费:
Q×L 与 S 的差恰为双边费用)。费用取 pms_cash_flow 的 FEE 行按 (日期, 代码) 聚合;
买入侧费用与无代码归属的校准费摊不进任何一行, 有此残差时在表尾如实标注金额 ——
@ -167,8 +168,8 @@ def _compute_snapshot() -> dict:
"account": account, "code": code.split(".")[0],
"name": _display_name(names.get(code), code),
"amount": round(g["amount"], 2), "open_date": g["open_date"],
"upd_date": today, "structure": structure, "cost": round(cost, 3),
"qty": g["qty"], "price": round(float(px), 3),
"upd_date": today, "structure": structure, "cost": cost,
"qty": g["qty"], "price": float(px),
"days": _days(g["open_date"], today),
})
@ -201,8 +202,8 @@ def _compute_snapshot() -> dict:
"name": _display_name(names.get(code), code),
"amount": round(g["amount"], 2), "open_date": g["open_date"],
"close_date": cd, "structure": structure,
"cost": round(g["amount"] / g["qty"], 3), "qty": g["qty"],
"settle": round(g["settle_amt"] / g["qty"], 3),
"cost": g["amount"] / g["qty"], "qty": g["qty"],
"settle": g["settle_amt"] / g["qty"],
"days": _days(g["open_date"], cd),
"pnl": round(g["pnl"] - fee, 2),
})
@ -215,7 +216,8 @@ def _compute_snapshot() -> dict:
fee_resid = round(fee_total - fee_alloc, 2)
hold_cost = sum(h["amount"] for h in holdings)
hold_pnl = sum(round((h["price"] - h["cost"]) * h["qty"], 2) for h in holdings)
# 金额先核算到分,均价只在页面/单元格格式上显示三位;不能先截均价再乘股数。
hold_pnl = sum(round(h["price"] * h["qty"] - h["amount"], 2) for h in holdings)
realized = sum(c["pnl"] for c in closed)
total_pnl = hold_pnl + realized
nav = 1.0 + total_pnl / scale
@ -283,9 +285,16 @@ def _entry_row(ws, row, seq, e, *, date2, px):
f"=IF(K{row}=0,0,Q{row}/K{row})"] # R 较期初价涨跌幅
for i, v in enumerate(vals):
_put(ws, row, 3 + i, v)
# S 总持股浮动盈亏: 持仓 = Q×L (不含费, 模板同); 平仓 = 含费实得, 写值
# 均价统一显示三位、金额两位;格式不能反过来截断原始数值。
for col in (11, 13, 17):
ws.cell(row=row, column=col).number_format = "0.000"
for col in (7, 19):
ws.cell(row=row, column=col).number_format = "#,##0.00"
# 表格里手动修订成本或股数后,成本金额和持仓盈亏必须一起重算。
_put(ws, row, 7, f"=ROUND(K{row}*L{row},2)")
# S 总持股浮动盈亏: 持仓 = 市值减成本金额;平仓 = 含费实得,沿用账本数值
if e.get("pnl") is None:
_put(ws, row, 19, f"=Q{row}*L{row}")
_put(ws, row, 19, f"=ROUND(M{row}*L{row}-G{row},2)")
else:
_put(ws, row, 19, e["pnl"])
_put(ws, row, 20, f"=IF(G{row}=0,0,S{row}/G{row})") # T 持有收益率
@ -412,7 +421,7 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
# ---- 表尾注 (模板之外的诚实行: 缺价与未摊费用不许静默) ----
note_row = sum2 + 1
notes = []
notes = ["持仓成本和成交均价不含手续费,费用单独列示;未回报费用不视为零"]
if s["price_missing"]:
notes.append(f"{len(s['price_missing'])} 只标的当日无行情,按成本价计入市值"
f"({'、'.join(s['price_missing'][:5])}"

View File

@ -1,12 +1,14 @@
"""实有策略现金与净值。账本迁移演练后,在无在途委托的维护窗口初始化。"""
import datetime as dt
import math
from app.core import rotation_account as core, strategy_book as books
from app.repo import rotation_repo as store, pms_repo, qmt_repo
from app.services import market
from app.core import ws_codec
def marked_values():
def marked_values(*, strict=True):
"""默认给资金动作严格估值;展示允许缺行情,但未知值必须保留为空。"""
values = {b: 0. for b in core.BOOKS}
missing = []
positions = []
@ -14,15 +16,22 @@ def marked_values():
rows = pms_repo.list_positions(only_open=True)
for r in rows:
quote = market.day_snapshot(r['ts_code'])
price = quote.get('price')
if not price or price <= 0:
raw_price = quote.get('price')
try:
price = float(raw_price) if raw_price is not None and not isinstance(raw_price, bool) else None
except (TypeError, ValueError):
price = None
if price is None or not math.isfinite(price) or price <= 0:
missing.append(r['ts_code'])
continue
value = int(r['total_qty'])*price
values[r['book_id']] += value
price, value = None, None
values[r['book_id']] = None
else:
value = int(r['total_qty'])*price
if values[r['book_id']] is not None:
values[r['book_id']] += value
positions.append({'book_id': r['book_id'], 'code': r['ts_code'], 'qty': r['total_qty'],
'market_value': value, 'price': price, 'cost': float(r.get('avg_cost') or 0)*int(r['total_qty'])})
if missing:
if missing and strict:
raise ValueError('策略估值行情缺失:'+','.join(missing))
return values, positions
@ -96,7 +105,8 @@ def view():
value, _ = store.get('capital:live')
if not value:
return {'ready': False, 'reason': '分策略现金尚未初始化'}
values, positions = marked_values()
values, positions = marked_values(strict=False)
missing = sorted({p['code'] for p in positions if p['market_value'] is None})
result = core.metrics(value, values)
snap = qmt_repo.latest_snapshot('funds')
cash_difference = None
@ -104,5 +114,8 @@ def view():
funds = ws_codec.parse_funds_snapshot(snap['payload'])
if funds.get('available_cash') is not None and funds.get('frozen_cash') is not None:
cash_difference = result['account']['cash']-funds['available_cash']-funds['frozen_cash']
return {'ready': True, 'metrics': result, 'positions': positions, 'cash_difference': cash_difference,
return {'ready': not missing, 'cash_ready': True, 'valuation_ready': not missing,
'valuation_missing': missing,
'reason': '持仓估值等待行情:'+','.join(missing)+';现金和持仓数量仍单独核对。' if missing else None,
'metrics': result, 'positions': positions, 'cash_difference': cash_difference,
'started_at': value.get('started_at'), 'transfer_count': len(value['transfers'])}

View File

@ -2,6 +2,7 @@
import datetime as dt
import hashlib
import json
import logging
import math
from zoneinfo import ZoneInfo
import requests
@ -11,6 +12,7 @@ from app.repo import pms_repo, qmt_repo, rotation_repo as store
from app.services import param_store, portfolio, market
TZ = ZoneInfo('Asia/Shanghai')
logger = logging.getLogger('pms.rotation')
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
TERMINAL = qmt_repo.FINAL
@ -146,9 +148,19 @@ def status():
try:
from app.services.rotation_accounting import view
out['accounting'] = view()
if out['accounting'].get('reason'):
out['errors'].append(out['accounting']['reason'])
except Exception as exc:
logger.warning('策略资金读取失败:%s', type(exc).__name__)
out['errors'].append('策略资金暂不可用,请稍后刷新;持仓数量仍单独核对。')
# 数量对账不依赖估值,单只股票没有分钟行情不能遮蔽账户持仓核验。
try:
out['reconciliation'] = reconcile_books()
except Exception as exc:
out['errors'].append('策略资金待核实:'+type(exc).__name__)
out['reconciliation'] = {'ok': False, 'diffs': [], 'fixes': [],
'errors': ['持仓数量对账暂不可用'], 'severity': 'ERROR'}
logger.warning('策略持仓数量对账失败:%s', type(exc).__name__)
out['errors'].append('持仓数量暂未核实,请稍后刷新。')
else:
out['activation_errors'] = ['策略账本迁移尚未启用']
out['stock_budget'] = param_store.get_float('PMS_TOTAL_SCALE', 0)*param_store.get_float('PMS_PORTFOLIO_CAP', 0)

View File

@ -1063,7 +1063,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
<div class="panel tblk postbl" id="t-pos">
<h3>持仓</h3>
<div class="sub2">占比按总操作规模计算。
<span class="help" data-tip="摊薄成本=(剩余批次买入金额-此前卖出已实现盈亏)÷剩余股数,不是券商买入均价。综合盈亏与安全垫均按摊薄成本计算;减仓后股数较少时,收益率可能明显放大。人工设定价仅随人工命令变更,系统参考位另见管理视图。">?</span></div>
<span class="help" data-tip="摊薄成本=(剩余批次买入金额-此前卖出已实现盈亏)÷剩余股数,不含手续费,也不是券商含费成本。费用单独记账,未回报费用不视为零。综合盈亏与安全垫均按摊薄成本计算;减仓后股数较少时,收益率可能明显放大。人工设定价仅随人工命令变更,系统参考位另见管理视图。">?</span></div>
<el-tabs v-model="positionTab" class="position-tabs">
<el-tab-pane v-for="group in positionGroups" :key="group.book_id" :name="'hold-'+group.book_id" class="position-book" :data-book="group.book_id">
<template #label>{{ group.name }} <span class="tabn">{{ group.ready ? group.totals.names_count : '—' }}</span></template>
@ -1082,7 +1082,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
<el-table v-if="lotsByPosition[positionKey(s.row)] && lotsByPosition[positionKey(s.row)].length" :data="lotsByPosition[positionKey(s.row)]" size="small">
<el-table-column label="批次" min-width="84"><template #default="l">{{ tx('lot', l.row.lot_type) }}</template></el-table-column>
<el-table-column prop="qty" label="还剩" width="72" align="right"></el-table-column>
<el-table-column prop="open_price" label="买入价" width="80" align="right"></el-table-column>
<el-table-column prop="open_price" label="买入价" width="80" align="right"><template #default="s"><span title="成交均价,不含手续费。">{{ costPrice(s.row.open_price) }}</span></template></el-table-column>
<el-table-column prop="open_date" label="买入日" width="104"></el-table-column>
<el-table-column prop="realized_pnl" label="已落袋" width="84" align="right"></el-table-column>
</el-table>
@ -1105,7 +1105,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
</el-table-column>
<el-table-column v-if="group.book_id==='micro30'" label="持仓 / 可卖" width="110"><template #default="s">{{ s.row.total_qty }} / {{ s.row.avail_qty }}</template></el-table-column>
<el-table-column label="现价 / 摊薄成本" width="96">
<template #default="s">{{ s.row.price }}<span v-if="!s.row.price_ok" class="muted"> 估</span><br><span class="muted">{{ s.row.avg_cost||'—' }}</span></template>
<template #default="s">{{ s.row.price }}<span v-if="!s.row.price_ok" class="muted"> 估</span><br><span class="muted" title="摊薄成本不含手续费,费用单独记账。">{{ costPrice(s.row.avg_cost) }}</span></template>
</el-table-column>
<!-- 我设的止损价与目标价: 读命令表带出来的 user_stop_price / user_target_price,
不是持仓行上的 stop_ref。stop_ref 每天早上会被系统重算的参考位整列盖掉,
@ -1902,8 +1902,8 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
<el-table-column prop="lot_type" label="批次" width="90"></el-table-column>
<el-table-column prop="qty" label="剩余" width="90"></el-table-column>
<el-table-column prop="closed_qty" label="已核销" width="90"></el-table-column>
<el-table-column prop="open_price" label="开仓价" width="100"></el-table-column>
<el-table-column prop="close_avg_price" label="核销均价" width="100"></el-table-column>
<el-table-column prop="open_price" label="开仓价" width="100"><template #default="s"><span title="成交均价,不含手续费。">{{ costPrice(s.row.open_price) }}</span></template></el-table-column>
<el-table-column prop="close_avg_price" label="核销均价" width="100"><template #default="s"><span title="成交均价,不含手续费。">{{ costPrice(s.row.close_avg_price) }}</span></template></el-table-column>
<el-table-column prop="realized_pnl" label="已实现" width="100"></el-table-column>
<el-table-column prop="open_date" label="开仓日" width="110"></el-table-column>
<el-table-column prop="instruction_id" label="来源指令" min-width="180"
@ -1933,7 +1933,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
<el-table-column v-if="group.book_id==='original'" label="批次(底/补/加/补仓/T)" width="170">
<template #default="s"><span class="mono nowrap">{{ s.row.base_qty }}/{{ s.row.fill_qty }}/{{ s.row.add_qty }}/{{ s.row.dca_qty }}/{{ s.row.t0_qty }}</span></template>
</el-table-column>
<el-table-column prop="avg_cost" label="摊薄成本" width="100"></el-table-column>
<el-table-column prop="avg_cost" label="摊薄成本" width="100"><template #default="s"><span title="摊薄成本不含手续费,费用单独记账。">{{ costPrice(s.row.avg_cost) }}</span></template></el-table-column>
<el-table-column prop="price" label="现价" width="90"></el-table-column>
<el-table-column v-if="group.book_id==='original'" label="安全垫" width="130">
<template #default="s">
@ -3112,6 +3112,8 @@ createApp({
const money = v => (v === null || v === undefined || v === '') ? '—'
: Number(v).toLocaleString('zh-CN', { maximumFractionDigits: 0 });
const costPrice = v => (v === null || v === undefined || v === '' || !Number.isFinite(Number(v)))
? '—' : Number(v).toFixed(3);
const pct = v => (v === null || v === undefined || v === '') ? '—'
: (Number(v) * 100).toFixed(2) + '%';
const groupLabel = g => ({ A: 'A 资金与总体参数', B: 'B 组合级动作', C: 'C 个股级动作' }[g]);
@ -3891,14 +3893,14 @@ createApp({
const curSet = v => (v != null ? '你现在设的是 ' + v + ' 元。' : '你还没设过。');
async function actStop(row) {
const v = await promptNum(curSet(row.user_stop_price)
+ '现价 ' + row.price + ',成本 ' + (row.avg_cost || '—')
+ '现价 ' + row.price + ',成本 ' + costPrice(row.avg_cost)
+ '。止损价只做提醒:跌破了会在合规检查里留一条记录,系统不会替你挂单卖出。'
+ '真要卖请下清仓或减持命令。填多少元?', '设止损 ' + nm(row.ts_code));
if (v != null) quickCmd('SET_STOP_PRICE', { ts_code: row.ts_code, price: v });
}
async function actTargetPrice(row) {
const v = await promptNum(curSet(row.user_target_price)
+ '现价 ' + row.price + ',成本 ' + (row.avg_cost || '—')
+ '现价 ' + row.price + ',成本 ' + costPrice(row.avg_cost)
+ '。目标价(元):到价后生成一条清仓提议放进「待确认提议」,卖不卖由你点头,'
+ '系统不自动卖。不想要了就再设一次、填 0 即取消。', '设目标价 ' + nm(row.ts_code));
if (v != null) quickCmd('SET_TARGET_PRICE', { ts_code: row.ts_code, price: v });
@ -5294,7 +5296,7 @@ createApp({
return { tab, loading, err, health, ov, params, catalog, commands, plans, plansOf,
positions, positionGroups, positionTab, positionLedgerTab, positionKey, lotsByPosition, instructions, ledger, ledgerToday, proposals, preparingProposals, report, reportDrawer,
opsDrawer, opsResult, opsLoading, issuing, form, curSpec, dirtyCount, dm,
money, pct, groupLabel, fieldLabel, stTag, cuTag, logicTag, canCancel, progPct, insPct,
money, costPrice, pct, groupLabel, fieldLabel, stTag, cuTag, logicTag, canCancel, progPct, insPct,
scaleGap,
wsRaw, wsAuto, wsHidePong, wsc, wst, wsMode, wsOrders, wsInbox, wsWarnings, loadWs,
loadAll, loadParams, saveParams, loadPlans, loadLots, onCmdChange, issue,

View File

@ -12,11 +12,12 @@
<div class="grid"><section class="card"><div class="label">运行档位</div><div class="metric" id="mode">读取中</div><div class="sub" id="control"></div></section><section class="card"><div class="label">账户资金使用阶段</div><div class="metric" id="phase">读取中</div><div class="sub" id="reason"></div></section><section class="card"><div class="label">名单与数据日期</div><div class="metric" id="count">—</div><div class="sub" id="date"></div></section></div>
<section class="card"><h2>宏观信号</h2><div class="grid"><div><div class="label">成长主线瓦解</div><div class="metric" id="growth">—</div></div><div><div class="label">微盘活跃度历史位置</div><div class="metric" id="percentile">—</div></div><div><div class="label">本次判断</div><div class="metric" id="signal">—</div></div></div><p class="sub" id="rule-summary">规则读取中。</p><div class="small sub" id="version"></div></section>
<section class="card"><div class="section-heading"><h2>目标名单与实际进度</h2><button id="copy-members" type="button" title="复制目标股票的代码和名称" aria-live="polite" disabled>复制名单</button></div><p class="sub" id="basket-summary">目标数量读取中。</p><p id="progress" class="sub"></p><div class="scroll"><table><thead><tr><th>排名</th><th>代码</th><th>名称</th><th>总市值(亿元)</th><th>收盘价</th><th>全日成交额(万元)</th><th>资格</th><th>实际股数</th><th>名单变动</th><th>初始金额/日成交额</th></tr></thead><tbody id="members"></tbody></table></div><div class="warning" id="waits" hidden></div></section>
<section class="card"><h2>资金与收益记录</h2><div id="account" class="sub">尚无纸面或自动执行账本。</div><div class="scroll"><table><thead><tr><th>策略</th><th>资产</th><th>净投入</th><th>盈亏</th><th>单位净值</th><th>最大回撤</th><th>累计费用</th></tr></thead><tbody id="summary"></tbody></table><table><thead><tr><th>策略</th><th>股票</th><th>股数</th><th>账面成本</th><th>持仓权重</th><th>估值</th></tr></thead><tbody id="positions"></tbody></table></div><div id="reconcile" class="small sub"></div><p class="small sub">历史研究收益不等于账户轮换收益。纸面结果单独记录,资金划拨不计为盈利。开盘窗口容量与实际成交偏差在执行后记录。</p></section>
<section class="card"><h2>资金与收益记录</h2><div id="account" class="sub">尚无纸面或自动执行账本。</div><div class="scroll"><table><thead><tr><th>策略</th><th>账面现金</th><th>资产</th><th>净投入</th><th>盈亏</th><th>单位净值</th><th>最大回撤</th><th>累计费用</th></tr></thead><tbody id="summary"></tbody></table><table><thead><tr><th>策略</th><th>股票</th><th>股数</th><th>账面成本</th><th>持仓权重</th><th>估值</th></tr></thead><tbody id="positions"></tbody></table></div><div id="reconcile" class="small sub"></div><p class="small sub">历史研究收益不等于账户轮换收益。纸面结果单独记录,资金划拨不计为盈利。开盘窗口容量与实际成交偏差在执行后记录。</p></section>
<section class="card"><h2>运行控制</h2><div class="warning" id="activation"></div><p class="sub" id="activation-policy"></p><div class="controls"><button data-mode="observe">观察</button><button data-mode="paper">纸面模拟</button><button data-mode="auto" id="automatic">自动执行</button><button data-action="pause_new">暂停新增</button><button data-action="pause_all">暂停全部</button><button data-action="run">恢复运行</button><button data-action="exit_disable">退出并停用</button></div><div class="small sub">控制操作需要系统管理员权限。退出并停用会产生卖出安排;观察和纸面档不会向QMT发单。</div></section>
</main><script>
const modes={observe:'观察',paper:'纸面模拟',auto:'自动执行'},phases={original:'主观量化运行',entering_micro:'转入微盘轮动',micro:'微盘轮动运行',returning_original:'转回主观量化'},controls={run:'运行',pause_new:'暂停新增',pause_all:'暂停全部',exit_disable:'退出并停用'};
const el=id=>document.getElementById(id),fmt=(x,n=2)=>x==null?'—':Number(x).toLocaleString('zh-CN',{maximumFractionDigits:n});
const cashAmount=x=>x==null?'—':Number(x).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2});
let memberCopyText='',copyBusy=false,copyTimer;
function prepareCopy(snapshot={}){
clearTimeout(copyTimer);const rows=snapshot.members||[];
@ -43,21 +44,21 @@ async function copyMembers(){
function cell(row,value){const td=document.createElement('td');td.textContent=value;row.append(td);return td}
function line(table,values){const tr=document.createElement('tr');values.forEach(v=>cell(tr,v));table.append(tr)}
async function request(url,options){const r=await fetch(url,options);if(r.status===401)throw Error('请先返回工作台登录');if(r.status===403)throw Error('此操作需要系统管理员权限');const v=await r.json();if(!r.ok||v.ok===false)throw Error(v.error||'请求失败');return v.data||v}
async function load(){prepareCopy();try{const v=await request('/api/rotation'),s=v.snapshot||{},g=s.signal||{},st=v.state||{},a=st.account;el('errors').textContent=[...(v.errors||[]),...(s.errors||[]),...(!s.basket_ready?['目标名单尚未就绪,停止新增和换仓。']:[])].join('\n');el('mode').textContent=modes[v.mode]||'未知档位';el('control').textContent=controls[v.control]||'未知控制';el('phase').textContent=phases[v.phase]||'等待状态';el('reason').textContent=(st.rotation||{}).reason||'等待有效信号';el('count').textContent=(s.members||[]).length+' / '+(v.basket_size||'—');el('date').textContent=s.data_date?('数据 '+s.data_date+' · 执行 '+s.effective_date+' · '+(s.frozen?'已冻结':'未冻结')):'尚无快照';el('growth').textContent=s.signal_ready?(g.growth_break?'已触发':'未触发'):'数据未就绪';el('percentile').textContent=g.activity_percentile==null?'—':fmt(g.activity_percentile*100)+'%';el('signal').textContent=!s.signal_ready?'等待数据':!s.frozen?'待冻结':g.high?'高位退出':g.low?'极低位入场':g.growth_break?'成长瓦解入场':'保持当前阶段';el('version').textContent='规则 '+(s.rule_version||v.rule_version)+' · 快照 '+(s.snapshot_version||'暂无');el('members').replaceChildren();(s.members||[]).forEach(m=>line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),m.eligible?'通过':'未通过']));el('waits').hidden=!(st.blocked||[]).length;el('waits').textContent=(st.blocked||[]).join('\n');el('positions').replaceChildren();if(a){el('account').textContent='纸面可用现金 '+fmt(a.cash)+' 元 · 最近估值 '+fmt(st.nav)+' 元 · 初始化 '+a.seeded_at;Object.entries(a.books||{}).forEach(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).forEach(([code,p])=>line(el('positions'),[book==='micro30'?'微盘轮动':'主观量化',code,p.qty,fmt(p.cost),fmt(a.realized[book]),fmt(a.fees[book])])))}else el('account').textContent='尚无纸面或自动执行账本。';el('activation').textContent=(v.activation_errors||[]).join('\n')||(v.simulation_direct?'模拟仓直接运行条件已就绪。':'自动执行的前置验收已完成。');el('automatic').disabled=!!(v.activation_errors||[]).length;renderDetails(v);prepareCopy(s)}catch(e){el('errors').textContent=e.message}}
async function load(){prepareCopy();try{const v=await request('/api/rotation'),s=v.snapshot||{},g=s.signal||{},st=v.state||{},a=v.mode==='paper'?st.account:null;el('errors').textContent=[...(v.errors||[]),...(s.errors||[]),...(!s.basket_ready?['目标名单尚未就绪,停止新增和换仓。']:[])].join('\n');el('mode').textContent=modes[v.mode]||'未知档位';el('control').textContent=controls[v.control]||'未知控制';el('phase').textContent=phases[v.phase]||'等待状态';el('reason').textContent=(st.rotation||{}).reason||'等待有效信号';el('count').textContent=(s.members||[]).length+' / '+(v.basket_size||'—');el('date').textContent=s.data_date?('数据 '+s.data_date+' · 执行 '+s.effective_date+' · '+(s.frozen?'已冻结':'未冻结')):'尚无快照';el('growth').textContent=s.signal_ready?(g.growth_break?'已触发':'未触发'):'数据未就绪';el('percentile').textContent=g.activity_percentile==null?'—':fmt(g.activity_percentile*100)+'%';el('signal').textContent=!s.signal_ready?'等待数据':!s.frozen?'待冻结':g.high?'高位退出':g.low?'极低位入场':g.growth_break?'成长瓦解入场':'保持当前阶段';el('version').textContent='规则 '+(s.rule_version||v.rule_version)+' · 快照 '+(s.snapshot_version||'暂无');el('members').replaceChildren();(s.members||[]).forEach(m=>line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),m.eligible?'通过':'未通过']));el('waits').hidden=!(st.blocked||[]).length;el('waits').textContent=(st.blocked||[]).join('\n');el('positions').replaceChildren();if(a){el('account').textContent='纸面可用现金 '+fmt(a.cash)+' 元 · 最近估值 '+fmt(st.nav)+' 元 · 初始化 '+a.seeded_at;Object.entries(a.books||{}).forEach(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).forEach(([code,p])=>line(el('positions'),[book==='micro30'?'微盘轮动':'主观量化',code,p.qty,fmt(p.cost),fmt(a.realized[book]),fmt(a.fees[book])])))}else el('account').textContent='尚无纸面或自动执行账本。';el('activation').textContent=(v.activation_errors||[]).join('\n')||(v.simulation_direct?'模拟仓直接运行条件已就绪。':'自动执行的前置验收已完成。');el('automatic').disabled=!!(v.activation_errors||[]).length;renderDetails(v);prepareCopy(s)}catch(e){el('errors').textContent=e.message}}
function renderDetails(v){
const st=v.state||{},a=st.account,s=v.snapshot||{},p=st.progress||{},rule=s.rule_parameters||v.rule_parameters||{},size=v.basket_size,metrics=st.metrics||(v.accounting||{}).metrics||{};
const st=v.state||{},isPaper=v.mode==='paper',a=isPaper?st.account:null,s=v.snapshot||{},p=st.progress||{},rule=s.rule_parameters||v.rule_parameters||{},size=v.basket_size,metrics=isPaper?(st.metrics||{}):((v.accounting||{}).metrics||{});
el('rule-summary').textContent='成长主线瓦解或低于历史'+fmt(rule.entry_percentile==null?null:rule.entry_percentile*100)+'%分位时入场,高于历史'+fmt(rule.exit_percentile==null?null:rule.exit_percentile*100)+'%分位时退出。股汇对冲指标只作用于主观量化。';
el('basket-summary').textContent='目标'+fmt(size)+'只。未成交或残余持仓可能使实际数量暂时偏离目标。保留成员不重新等权。';
el('activation-policy').textContent=v.simulation_direct?'模拟仓直接运行,不设观察或纸面等待期。每笔交易继续核对账户资金、持仓、数据和用户控制。':'观察至少3个交易日,再纸面运行至少10个交易日。自动档需要回测、容量、账本、资金占用及页面验收完成。';
const names={original:'主观量化',micro30:'微盘轮动',account:'全账户'};
const positions=a?Object.entries(a.books||{}).flatMap(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).map(([code,p])=>({book_id:book,code,qty:p.qty,cost:p.cost,market_value:null}))):((v.accounting||{}).positions||[]);
const positions=a?Object.entries(a.books||{}).flatMap(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).map(([code,p])=>({book_id:book,code,qty:p.qty,cost:p.cost,market_value:null}))):(isPaper?[]:((v.accounting||{}).positions||[]));
el('progress').textContent='股票预算上限 '+fmt(v.stock_budget)+' 元 · 主观量化剩余 '+fmt(p.original_market_value)+' 元 · 微盘轮动已建 '+fmt(p.micro_market_value)+' 元 · 可用现金 '+fmt(p.available_cash)+' 元'+(v.simulation_direct?'':(' · 观察 '+(v.observed_days||0)+' 日 · 健康纸面 '+(v.paper_days||0)+' 日'));
el('members').replaceChildren();const target=new Set((s.members||[]).map(x=>x.code));
(s.members||[]).forEach(m=>{const held=positions.find(x=>x.book_id==='micro30'&&x.code===m.code);line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),s.basket_ready&&m.eligible?'通过':'待核实',held?held.qty:'—',!positions.length?'待建仓':held?'保留':'调入',m.daily_amount_yuan?fmt(v.stock_budget/size/m.daily_amount_yuan*100)+'%':'未知']);});
positions.filter(x=>x.book_id==='micro30'&&!target.has(x.code)).forEach(x=>line(el('members'),['—',x.code,'残余持仓','—','—','—','等待卖出',x.qty,'调出','—']));
el('positions').replaceChildren();positions.forEach(x=>line(el('positions'),[names[x.book_id],x.code,x.qty,fmt(x.cost),x.market_value&&metrics[x.book_id]?.equity?fmt(x.market_value/metrics[x.book_id].equity*100)+'%':'—',fmt(x.market_value)]));
el('summary').replaceChildren();Object.entries(metrics).forEach(([book,r])=>{let peak=0,dd=0;[...(v.daily||[])].reverse().forEach(x=>{const n=(x.value.metrics||{})[book]?.nav;if(n>0){peak=Math.max(peak,n);dd=Math.min(dd,n/peak-1);}});line(el('summary'),[names[book],fmt(r.equity),fmt(r.net_capital),fmt(r.profit),fmt(r.nav,4),book==='account'?'—':fmt(dd*100)+'%',fmt(r.fees)]);});
if(!a&&v.accounting?.ready)el('account').textContent='实际账本自 '+v.accounting.started_at+' 起记录 · 内部划拨 '+v.accounting.transfer_count+' 笔';
el('summary').replaceChildren();Object.entries(metrics).forEach(([book,r])=>{let peak=0,dd=0;[...(v.daily||[])].reverse().forEach(x=>{const n=(x.value.metrics||{})[book]?.nav;if(n>0){peak=Math.max(peak,n);dd=Math.min(dd,n/peak-1);}});line(el('summary'),[names[book],cashAmount(r.cash),fmt(r.equity),fmt(r.net_capital),fmt(r.profit),fmt(r.nav,4),book==='account'||r.nav==null?'—':fmt(dd*100)+'%',fmt(r.fees)]);});
if(!isPaper&&(v.accounting?.cash_ready??v.accounting?.ready))el('account').textContent='实际账本自 '+v.accounting.started_at+' 起记录 · 内部划拨 '+v.accounting.transfer_count+' 笔 · 账面现金 '+cashAmount(metrics.account?.cash)+' 元'+(v.accounting.valuation_ready===false?' · '+(v.accounting.reason||'等待持仓行情,估值暂缺。'):'');
const diff=v.accounting?.cash_difference;el('reconcile').textContent=v.reconciliation?('持仓对账 '+(v.reconciliation.ok?'一致':'待核对')+' · 现金差异 '+fmt(diff)+' 元'):'交易账本尚未启用,当前仅观察。';
}
el('copy-members').onclick=copyMembers;el('refresh').onclick=load;document.querySelectorAll('[data-mode],[data-action]').forEach(b=>b.onclick=async()=>{try{if(b.dataset.mode==='auto'&&!confirm('将启用155模拟账户自动执行。确认启用?'))return;if(b.dataset.action==='exit_disable'&&!confirm('将停止新增并退出微盘持仓。确认执行?'))return;await request('/api/ops/rotation/control',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(b.dataset.mode?{mode:b.dataset.mode}:{action:b.dataset.action})});await load()}catch(e){el('errors').textContent=e.message}});load();setInterval(load,30000);

View File

@ -14,6 +14,7 @@
| 筹码断档、套牢盘与吸筹次数(已结束) | [研究归档](筹码断档与吸筹研究接续_2026-10-30.md),用户决定不再继续;历史数据口径不代表现行研究范围 |
| PMS通用迁移与既有修复 | [开发接续](开发接续_2026-10-12.md),按主题查对应节;旧时点未完成项可能已有后续结论 |
| 盘中改价、异步研判与微盘递补发布 | [执行链路发布接续](执行报价与异步研判发布接续_2026-11-03.md),区分部署、开关与自然判收;[实施规格](执行报价与异步研判实施规格_2026-11-03.md);[当日限制价采集边界](当日限制价采集边界_2026-11-03.md) |
| 策略资金缺行情提示、成本三位精度与含费口径 | [估值与成本精度修复](策略估值与成本精度修复_2026-11-04.md),含实际QMT回执、展示降级和导出舍入边界 |
| 架构与接口 | [README模块地图](../README.md)、[总体设计](../POSITION_MGMT_DESIGN.md);改接口再读[QMT协议](../QMT_WS_PROTOCOL.md)、[bionic接口](../BIONIC_PMS_INTERFACE.md)或[计划接口](../UPSTREAM_PLAN_API.md) |
| 后端、前端、测试、研究 | [后端规则](../app/AGENTS.md)、[页面规则](../app/web/AGENTS.md)、[脚本规则](../scripts/AGENTS.md)、[研究规则](../research/AGENTS.md),仅选择所涉及目录 |
| 部署与运行核验 | [pms-release](../.agents/skills/pms-release/SKILL.md);命令目录为`make help`,并非所有目标都是只读 |

View File

@ -0,0 +1,20 @@
# 策略估值与成本精度修复
## 核实的原因
2026年11月4日09:25,北京时间,在155模拟PMS复现“策略资金待核实:ValueError”。实际异常为“策略估值行情缺失:002979.SZ”:盘前雷赛智能没有当日分钟行情,估值函数抛错,连带遮住了与行情无关的现金和数量核对。独立数量对账一致。09:30自然开盘行情到达后,旧版本估值恢复,现金差异仍为0,进一步确认是缺行情展示问题。
09:28只读核对雷赛智能:原策略100股、可卖100股,批次1450开仓价和持仓成本均为48.290。昨日原始成交回执1599510为100股、48.29元、本金4829元、fee=null;最新QMT持仓cost_price仍为48.29。用户本次明确48.296是含手续费持仓成本。二者口径不同,不据此改写原成交或由三位四舍五入均价推算实际费用。费用明细仍待QMT补齐,不能把未知费用当作0。
另从自然调度发现execution_basis_refresh对已有持仓报“Object of type Decimal is not JSON serializable”。新增的独立刷新流程直接读取数据库Decimal成本和参考位,原HTTP入口未做既有数值转换;无持仓时未暴露。
## 修复边界
- 只读展示把现金、数量对账与估值拆开。缺行情时保留现金、成本和股数,受影响策略及账户的市值、权益、盈利和净值为空,提示具体证券。严格估值仍用于初始化、资金划拨;不会用零、成本价或昨收代替执行行情。日结不得把缺估值标为健康。
- 页面成本、开仓均价及核销均价固定显示三位;金额与均价采用各自精度。页面和表格标明费用另计,既有成交、账本、资金及费用记录不改写。
- 导出保留加权均价的计算精度,仅用单元格格式显示三位;成本金额和盈亏核算到分。复现案例为100股48.290加200股48.291,实际成本14487.20,现价49.01时盈亏215.80;原来先舍入均价导致215.70。表格修改成本或股数后,成本金额和持仓盈亏同步重算。
- 执行依据HTTP入口复用研判接口的明确类型转换,Decimal保留为JSON数值,未知对象和非有限数仍拒绝发送。没有注入模型请求、信号或验收委托。
## 验证与发布
本节在候选回归及实际发布完成后补充。当前修复不涉及188、QMT连接、限制价采集进程或微盘规则变更。费用来源缺失与自然异步验收须分别记录,不将展示修复视作费用已经核实。

View File

@ -8,6 +8,8 @@
新增限制价采集专项:core 25例、provider 21例、targets 18例、collector 28例,
缓存消费23例、独立进程入口6例。
策略资金缺行情展示与严格划拨专项18例;成本均价展示与导出精度专项8例。
执行依据数据库数值序列化专项5例。
包含 (例数按 2026-10-26 隔离回归实跑校正):
test_batch57_units.py 异步请求持久化、截止时间、旧结果隔离、失败续查、真实调度入口及行情来源 (24例)
@ -192,7 +194,8 @@ import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
SUITES = ["test_price_limits_core.py", "test_price_limit_provider.py",
SUITES = ["test_rotation_accounting_units.py", "test_cost_precision.py", "test_execution_basis_decimal.py",
"test_price_limits_core.py", "test_price_limit_provider.py",
"test_price_limit_targets.py", "test_price_limit_collector.py",
"test_price_limit_cache.py", "test_market_data_worker.py",
"test_batch54_units.py",

View File

@ -0,0 +1,140 @@
"""成本三位精度贯穿成交、账本、页面数据和公示表;费用单列。"""
import unit_test_guard # noqa: F401
import io
import unittest
from pathlib import Path
from datetime import date
import openpyxl
from test_wiring import install_fakes
from app.core import ws_codec
from app.services import ledger_service, portfolio, publish_export
class CostPrecisionTests(unittest.TestCase):
def setUp(self):
self.fake = install_fakes(prices={'002979.SZ': 49.01},
params={'PMS_TOTAL_SCALE': '2000000'})
def book_trade(self, price, fee=0):
self.fake.insert_instruction(instruction_id='INS_PRECISION', origin_type='plan',
origin_id='P1', ts_code='002979.SZ', action='OPEN', side='buy', qty=100,
status='DISPATCHED')
self.fake.qmt.enqueue_order(instruction_id='INS_PRECISION_D01',
parent_id='INS_PRECISION', ts_code='002979.SZ', side='buy', qty=100,
limit_price=49.01, valid_until=0)
self.fake.qmt.put_trade(seq=1, instruction_id='INS_PRECISION_D01',
ts_code='002979.SZ', side='buy', qty=100, price=price, fee=fee)
result = ledger_service.consume_ws_trades()
self.assertEqual((result['trades'], result['actions']), (1, 1))
def test_three_decimal_trade_reaches_book_page_and_xlsx_unchanged(self):
self.book_trade(48.296)
self.assertEqual(self.fake.lots[0]['open_price'], 48.296)
self.assertEqual(self.fake.positions['002979.SZ']['avg_cost'], 48.296)
self.assertEqual(portfolio.positions_view()['held'][0]['avg_cost'], 48.296)
snapshot = publish_export.compute_snapshot()
self.assertAlmostEqual(snapshot['holdings'][0]['cost'], 48.296)
self.assertEqual(snapshot['holdings'][0]['amount'], 4829.60)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1']
self.assertAlmostEqual(sheet['K5'].value, 48.296)
self.assertEqual(sheet['K5'].number_format, '0.000')
self.assertEqual(sheet['M5'].number_format, '0.000')
self.assertEqual(sheet['G5'].number_format, '#,##0.00')
self.assertEqual(sheet['S5'].number_format, '#,##0.00')
self.assertTrue(any('未回报费用不视为零' in str(cell.value or '')
for row in sheet for cell in row))
def test_fee_cost_is_not_invented_by_padding_trade_price(self):
# 券商可能含费成本48.296,但48.29成交+0.60费用在PMS必须分别记账。
self.book_trade(48.29, fee=.60)
self.assertEqual(self.fake.positions['002979.SZ']['avg_cost'], 48.29)
self.assertEqual(self.fake.cash_flows[0]['amount'], -.60)
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['holdings'][0]['cost'], 48.29)
self.assertEqual(snapshot['holdings'][0]['amount'], 4829.00)
self.assertEqual(abs(snapshot['fee_resid']), .60)
def test_qmt_position_snapshot_keeps_cost_third_decimal(self):
value = ws_codec.parse_positions_snapshot({'items': [
{'ts_code': '002979.SZ', 'total_qty': 100, 'avail_qty': 100,
'cost_price': '48.296', 'market_price': '49.01'}]})
self.assertEqual(value['rows'][0]['cost'], 48.296)
def test_weighted_average_is_displayed_to_three_places_without_losing_money(self):
for qty, price in ((100, 48.290), (200, 48.291)):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=qty,
open_price=price, open_date=date.today())
snapshot = publish_export.compute_snapshot()
row = snapshot['holdings'][0]
self.assertEqual(row['amount'], 14487.20)
self.assertAlmostEqual(row['cost'], 48.29066666666667)
self.assertEqual(snapshot['hold_pnl'], 215.80)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1']
self.assertAlmostEqual(sheet['K5'].value * sheet['L5'].value, 14487.20)
self.assertEqual(sheet['K5'].number_format, '0.000')
# 表格可编辑:成本、股数变化同时进入成本金额与盈亏,再进入小计和净值。
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)')
self.assertEqual(sheet['Q5'].value, '=M5-K5')
self.assertEqual(sheet['S5'].value, '=ROUND(M5*L5-G5,2)')
self.assertEqual(sheet['G6'].value, '=SUM(G5:G5)')
self.assertEqual(sheet['S6'].value, '=SUM(S5:S5)')
def test_closed_average_keeps_amount_precision(self):
for qty, price, close_price in ((100, 48.290, 49.010), (200, 48.291, 49.011)):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=qty,
open_price=price, open_date=date.today())
self.fake.close_lot_qty(self.fake.lots[-1]['id'], qty=qty,
close_price=close_price, realized_pnl=qty*(close_price-price))
snapshot = publish_export.compute_snapshot()
row = snapshot['closed'][0]
self.assertEqual(row['amount'], 14487.20)
self.assertAlmostEqual(row['cost'] * row['qty'], 14487.20)
self.assertAlmostEqual(row['settle'] * row['qty'], 14703.20)
self.assertEqual(row['pnl'], 216.00)
def test_odd_lot_cost_and_settlement_do_not_inherit_cent_rounding(self):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=2,
open_price=48.296, open_date=date.today())
self.fake.close_lot_qty(self.fake.lots[-1]['id'], qty=1,
close_price=49.011, realized_pnl=.715)
snapshot = publish_export.compute_snapshot()
for row in (snapshot['holdings'][0], snapshot['closed'][0]):
self.assertEqual(row['qty'], 1)
self.assertEqual(row['amount'], 48.30)
self.assertEqual(row['cost'], 48.296)
self.assertEqual(snapshot['closed'][0]['settle'], 49.011)
self.assertEqual(snapshot['hold_pnl'], .71)
workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1']
self.assertEqual(sheet['K5'].value, 48.296)
self.assertEqual(sheet['K8'].value, 48.296)
self.assertEqual(sheet['M8'].value, 49.011)
def test_missing_quote_uses_exact_cost_without_false_profit(self):
self.fake = install_fakes(prices={}, params={'PMS_TOTAL_SCALE': '2000000'})
for qty, price in ((100, 48.290), (200, 48.291)):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=qty,
open_price=price, open_date=date.today())
snapshot = publish_export.compute_snapshot()
self.assertEqual(snapshot['price_missing'], ['002979.SZ'])
self.assertEqual(snapshot['hold_pnl'], 0)
def test_price_formatting_is_separate_from_amount_and_quote_fields(self):
page = (Path(__file__).resolve().parents[1] / 'app/web/static/index.html').read_text()
self.assertIn("? '—' : Number(v).toFixed(3)", page)
for field in ('avg_cost', 'open_price', 'close_avg_price'):
self.assertIn('costPrice(s.row.' + field + ')', page)
self.assertNotIn('costPrice(s.row.market_value)', page)
self.assertNotIn('costPrice(s.row.limit_price)', page)
self.assertIn('不是券商含费成本', page)
self.assertIn('成交均价,不含手续费。', page)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,103 @@
"""执行依据真实 JSON 编码边界:数据库 Decimal 保持数值,非法值不发请求。"""
import unit_test_guard # noqa: F401
import json
import unittest
from datetime import date, datetime, timedelta
from decimal import Decimal
from unittest.mock import patch
import requests
from test_wiring import install_fakes
from app.core import execution_policy as policy
from app.services import execution_basis, exec_advisor, market
NOW = datetime(2026, 11, 4, 10, 0, tzinfo=policy.BEIJING)
CODE = '002979.SZ'
def fact(version='v1'):
return {'version': version, 'quality': 'VALID', 'continuation': 'CONTINUE',
'reason': '已有授权未撤销', 'source': 'test:daily', 'source_date': '2026-11-03',
'generated_at': (NOW-timedelta(hours=2)).isoformat(),
'valid_until': (NOW+timedelta(minutes=5)).isoformat()}
class ExecutionBasisDecimalTests(unittest.TestCase):
def setUp(self):
self.fake = install_fakes(positions=[{'ts_code': CODE, 'total_qty': 100,
'avail_qty': 100, 'avg_cost': Decimal('48.296'),
'support_ref': Decimal('47.100'), 'pressure_ref': Decimal('52.300'),
'stop_ref': None}], params={'PMS_EXEC_REPRICE_ENABLED': True,
'PMS_EXEC_IMPL': 'A', 'PMS_EXEC_API_BASE': 'https://unit.invalid'})
self.fake.insert_instruction(instruction_id='P', origin_type='plan', origin_id='P1',
ts_code=CODE, side='buy', action='OPEN', qty=300,
status='DISPATCHED', progress={'children': [{'ref': 'P_D01', 'qty': 100}],
'execution_basis_cache': {'basis': fact()}})
self.fake.instructions['P']['exec_qty'] = 100
self.sent = []
# 保留 requests 的真实参数准备与 JSON 编码,只在网络发送之前换成内存应答。
self.send = patch('requests.sessions.Session.send', side_effect=self.respond).start()
patch.object(market, 'day_snapshot', return_value={'price': 48.72, 'bars': 1}).start()
self.addCleanup(patch.stopall)
def respond(self, request, **kwargs):
self.sent.append(json.loads(request.body))
response = requests.Response()
response.status_code = 200
response._content = json.dumps({'execution_basis': fact('v2')}).encode()
return response
def test_refresh_preserves_database_decimal_prices_as_json_numbers(self):
result = execution_basis.refresh(NOW)
self.assertEqual(result['errors'], [])
self.assertEqual(result['refreshed'], ['P'])
self.assertEqual(len(self.sent), 1)
payload = self.sent[0]
self.assertEqual(payload['position'], {'total_qty': 100, 'avail_qty': 100,
'avg_cost': 48.296})
self.assertEqual(payload['refs'], {'support': 47.1, 'pressure': 52.3, 'stop': None})
self.assertIsInstance(payload['position']['avg_cost'], float)
self.assertEqual(payload['qty_left'], 200)
progress = self.fake.instructions['P']['progress']
self.assertEqual(progress['children'], [{'ref': 'P_D01', 'qty': 100}])
self.assertEqual(progress['execution_basis_cache']['basis']['version'], 'v2')
self.assertEqual(self.fake.positions[CODE]['avg_cost'], Decimal('48.296'))
def test_new_position_retains_nulls_instead_of_inventing_zero_cost(self):
self.fake.positions.clear()
self.assertEqual(execution_basis.refresh(NOW)['errors'], [])
self.assertEqual(self.sent[0]['position'], {'total_qty': None, 'avail_qty': None,
'avg_cost': None})
self.assertEqual(self.sent[0]['refs'], {'support': None, 'pressure': None, 'stop': None})
def test_shared_http_boundary_handles_nested_known_database_types(self):
payload = {'position': {'avg_cost': Decimal('48.296')},
'refs': {'support': Decimal('47.1')},
'history': [{'price': Decimal('48.290'), 'day': date(2026, 11, 3)}]}
exec_advisor._post('https://unit.invalid/api/intraday/pms_exec', payload, 2)
self.assertEqual(self.sent[0]['history'], [{'price': 48.29, 'day': '2026-11-03'}])
self.assertEqual(self.sent[0]['position']['avg_cost'], 48.296)
self.assertIsInstance(payload['position']['avg_cost'], Decimal)
def test_nonfinite_database_number_is_rejected_before_network(self):
for value in (Decimal('NaN'), Decimal('Infinity'), Decimal('-Infinity')):
with self.subTest(value=value):
with self.assertRaises(requests.exceptions.InvalidJSONError):
exec_advisor._post('https://unit.invalid/api/intraday/pms_exec',
{'position': {'avg_cost': value}}, 2)
self.send.assert_not_called()
def test_unknown_type_does_not_become_string_or_extend_old_authorization(self):
self.fake.positions[CODE]['avg_cost'] = object()
result = execution_basis.refresh(NOW)
self.assertEqual(len(result['errors']), 1)
self.send.assert_not_called()
cache = self.fake.instructions['P']['progress']['execution_basis_cache']
self.assertEqual(cache['basis'], fact())
self.assertTrue(cache['error'])
self.assertTrue(execution_basis.cache_reason({'execution_basis_cache': cache},
NOW+timedelta(minutes=6)))
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,210 @@
"""策略估值缺行情时保留现金和数量核验,资金动作继续严格阻断。"""
import unit_test_guard # noqa: F401
import copy
import datetime as dt
from contextlib import contextmanager, nullcontext
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.core import rotation_account as core, strategy_book as books
from app.services import rotation_accounting as accounting, rotation_service as rotation
def held(code='002979.SZ', book='original', qty=100, cost=48.296):
return {'book_id': book, 'ts_code': code, 'total_qty': qty, 'avg_cost': cost}
class AccountingTests(unittest.TestCase):
def setUp(self):
self.capital = core.seed(10000, {'original': 0, 'micro30': 0})
self.capital['started_at'] = '2026-11-03T15:00:00+08:00'
for obj, name, kw in (
(accounting.store, 'get', {'return_value': (self.capital, 1)}),
(accounting.pms_repo, 'list_positions', {'return_value': [held()]}),
(accounting.market, 'day_snapshot', {'return_value': {}}),
(accounting.qmt_repo, 'latest_snapshot', {'return_value': {
'age_sec': 5, 'seq': 10, 'payload': {'available_cash': 9000, 'frozen_cash': 1000}}}),
):
p = patch.object(obj, name, **kw)
setattr(self, name, p.start())
self.addCleanup(p.stop)
def test_missing_quote_preserves_cash_cost_quantity_and_cash_reconciliation(self):
value = accounting.view()
self.assertFalse(value['ready'])
self.assertTrue(value['cash_ready'])
self.assertFalse(value['valuation_ready'])
self.assertEqual(value['valuation_missing'], ['002979.SZ'])
self.assertEqual(value['cash_difference'], 0)
self.assertEqual(value['metrics']['account']['cash'], 10000)
self.assertEqual(value['positions'][0]['qty'], 100)
self.assertAlmostEqual(value['positions'][0]['cost'], 4829.6)
self.assertIsNone(value['positions'][0]['price'])
self.assertIsNone(value['positions'][0]['market_value'])
self.assertIn('等待行情', value['reason'])
def test_missing_quote_does_not_publish_zero_valuation_or_false_loss(self):
value = accounting.view()
for book in ('original', 'account'):
for key in ('market_value', 'equity', 'profit'):
self.assertIsNone(value['metrics'][book][key])
self.assertIsNone(value['metrics']['original']['nav'])
self.assertEqual(value['metrics']['micro30']['market_value'], 0)
def test_only_affected_book_loses_valuation(self):
self.list_positions.return_value = [held(), held('600000.SH', 'micro30', cost=10)]
self.day_snapshot.side_effect = lambda c: {} if c == '002979.SZ' else {'price': 11.}
value = accounting.view()
self.assertIsNone(value['metrics']['original']['equity'])
self.assertEqual(value['metrics']['micro30']['equity'], 1100)
self.assertIsNone(value['metrics']['account']['equity'])
def test_same_book_quote_order_does_not_hide_missing_position(self):
for rows in ([held(), held('600000.SH')], [held('600000.SH'), held()]):
self.list_positions.return_value = rows
self.day_snapshot.side_effect = lambda c: {} if c == '002979.SZ' else {'price': 11.}
value = accounting.view()
self.assertIsNone(value['metrics']['original']['market_value'])
self.assertEqual(len(value['positions']), 2)
def test_quote_recovery_restores_complete_valuation_without_restart(self):
self.assertFalse(accounting.view()['ready'])
self.day_snapshot.return_value = {'price': 49.}
value = accounting.view()
self.assertTrue(value['ready'])
self.assertTrue(value['valuation_ready'])
self.assertEqual(value['valuation_missing'], [])
self.assertEqual(value['metrics']['original']['market_value'], 4900)
self.assertEqual(value['metrics']['account']['equity'], 14900)
self.assertIsNone(value['reason'])
def test_invalid_prices_remain_missing_and_json_safe(self):
for price in (None, 0, -1, float('nan'), float('inf'), 'bad', True):
self.day_snapshot.return_value = {'price': price}
value = accounting.view()
self.assertFalse(value['ready'], repr(price))
self.assertIsNone(value['positions'][0]['price'])
self.assertIsNone(value['metrics']['account']['equity'])
def test_empty_position_book_has_known_zero_market_value(self):
self.list_positions.return_value = []
value = accounting.view()
self.assertTrue(value['ready'])
self.assertEqual(value['metrics']['account']['equity'], 10000)
self.day_snapshot.assert_not_called()
def test_strict_marked_values_still_reject_missing_quote(self):
with self.assertRaisesRegex(ValueError, '策略估值行情缺失:002979.SZ'):
accounting.marked_values()
def test_reservation_cannot_transfer_cash_without_complete_valuation(self):
before = copy.deepcopy(self.capital)
@contextmanager
def locked(*args, **kwargs):
yield self.capital
with patch.object(accounting.store, 'locked', side_effect=locked), \
patch.object(accounting.store, 'put_once') as write:
with self.assertRaisesRegex(ValueError, '策略估值行情缺失'):
accounting.reserve_book('micro30', 100, [], 'entering_micro')
write.assert_not_called()
self.assertEqual(self.capital, before)
def test_unknown_pure_valuation_rejects_transfer_before_mutation(self):
before = copy.deepcopy(self.capital)
with self.assertRaisesRegex(ValueError, '估值不完整'):
core.transfer(self.capital, 'original', 'micro30', 100,
{'original': 0., 'micro30': None}, 'key')
self.assertEqual(self.capital, before)
def test_initialization_cannot_seed_unknown_valuation_as_zero(self):
from app.db import session as db
self.get.return_value = (None, 0)
self.latest_snapshot.return_value['payload']['frozen_cash'] = 0
with patch.object(accounting.store, 'account_guard', side_effect=nullcontext), \
patch.object(db, 'fetch_all', return_value=[]), \
patch.object(rotation, 'reconcile_books', return_value={'ok': True}), \
patch.object(accounting.store, 'put_once') as write:
with self.assertRaisesRegex(ValueError, '策略估值行情缺失'):
accounting.initialize()
write.assert_not_called()
def test_missing_quote_never_loads_cost_or_daily_close_as_price(self):
with patch.object(accounting.market, 'get_last_close') as close, \
patch.object(accounting.market, 'get_prev_close') as previous:
accounting.view()
close.assert_not_called()
previous.assert_not_called()
def test_stale_funds_do_not_fake_cash_reconciliation(self):
self.latest_snapshot.return_value['age_sec'] = 61
self.assertIsNone(accounting.view()['cash_difference'])
def test_no_capital_still_reports_uninitialized(self):
self.get.return_value = (None, 0)
value = accounting.view()
self.assertFalse(value['ready'])
self.assertIn('尚未初始化', value['reason'])
self.list_positions.assert_not_called()
class StatusTests(unittest.TestCase):
def setUp(self):
config = {'mode': 'auto', 'control': 'run', 'rule_version': rotation.core.RULE,
'boards': set(), 'costs': {}, 'candidate_pool_size': 100}
for obj, name, kw in (
(rotation, 'configuration', {'return_value': config}),
(rotation, 'pull', {'return_value': {}}),
(rotation, 'documents_ready', {'return_value': True}),
(rotation.settings, 'INFRA_STRATEGY_BOOK_SCHEMA', {'new': True}),
(rotation.settings, 'PMS_TABLE_PREFIX', {'new': ''}),
(rotation.store, 'get', {'return_value': (None, 0)}),
(rotation.store, 'recent', {'return_value': []}),
(rotation, 'activation_errors', {'return_value': []}),
(rotation.param_store, 'get_bool', {'return_value': False}),
(rotation.param_store, 'get_float', {'return_value': 0}),
(rotation, 'reconcile_books', {'return_value': {'ok': True, 'diffs': []}}),
(accounting, 'view', {'return_value': {'ready': False, 'reason': '持仓估值等待行情:002979.SZ'}}),
):
p = patch.object(obj, name, **kw)
setattr(self, name, p.start())
self.addCleanup(p.stop)
def test_partial_valuation_keeps_independent_quantity_reconciliation(self):
value = rotation.status()
self.assertTrue(value['reconciliation']['ok'])
self.assertIn('持仓估值等待行情:002979.SZ', value['errors'])
self.assertFalse(any('ValueError' in e for e in value['errors']))
def test_accounting_error_does_not_skip_quantity_reconciliation(self):
self.view.side_effect = RuntimeError('internal details')
value = rotation.status()
self.reconcile_books.assert_called_once()
self.assertTrue(value['reconciliation']['ok'])
self.assertNotIn('internal details', str(value))
self.assertNotIn('RuntimeError', str(value))
def test_quantity_error_does_not_hide_accounting_or_claim_reconciliation(self):
self.reconcile_books.side_effect = ValueError('unsafe internal details')
value = rotation.status()
self.assertIn('accounting', value)
self.assertFalse(value['reconciliation']['ok'])
self.assertEqual(value['reconciliation']['severity'], 'ERROR')
self.assertNotIn('unsafe internal details', str(value))
self.assertNotIn('ValueError', str(value))
def test_incomplete_valuation_cannot_mark_daily_settlement_healthy(self):
with patch.object(rotation.td, 'calendar_degraded', return_value=False), \
patch.object(rotation.td, 'is_trade_day', return_value=True), \
patch.object(rotation.store, 'put_once') as put:
rotation.settle_day(dt.datetime(2026, 11, 4, 15, 30, tzinfo=rotation.TZ))
record = put.call_args.args[2]
self.assertFalse(record['healthy'])
if __name__ == '__main__':
unittest.main()

View File

@ -2824,7 +2824,7 @@ def _():
assert ws["E5"].value == "000001" and ws["E6"].value == "600000", (
ws["E5"].value, ws["E6"].value) # 按最早开仓日排序
assert ws["L6"].value == 2000 and ws["D5"].value == "测试账户"
assert ws["U5"].value == "=1+T5" and ws["S5"].value == "=Q5*L5"
assert ws["U5"].value == "=1+T5" and ws["S5"].value == "=ROUND(M5*L5-G5,2)"
assert ws["C8"].value == "序" + chr(10) + "号", repr(ws["C8"].value)
assert ws["S9"].value == 987.5 and ws["T9"].value == "=IF(G9=0,0,S9/G9)"
assert ws["G7"].value == "=SUM(G5:G6)" and ws["G10"].value == "=SUM(G9:G9)"