diff --git a/DEVLOG.md b/DEVLOG.md index 1236683..d06fcce 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -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)。本条为实施记录,部署结果另补,不能当作已上线回执。 + > 这份文件的用途只有一个:**让下一次交接不必重新查一遍**。 > 每个重要节点写一条,写完就补,不攒到最后。一条节点包含五样东西: > 做了什么、动了哪些文件、部署方式、真机判收结果、还欠着什么。 diff --git a/app/core/rotation_account.py b/app/core/rotation_account.py index 34a9300..f6f6245 100644 --- a/app/core/rotation_account.py +++ b/app/core/rotation_account.py @@ -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'] diff --git a/app/services/exec_advisor.py b/app/services/exec_advisor.py index a8825cd..cfdff23 100644 --- a/app/services/exec_advisor.py +++ b/app/services/exec_advisor.py @@ -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 {} diff --git a/app/services/publish_export.py b/app/services/publish_export.py index c8e07e1..4dff022 100644 --- a/app/services/publish_export.py +++ b/app/services/publish_export.py @@ -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])}" diff --git a/app/services/rotation_accounting.py b/app/services/rotation_accounting.py index 64f0389..97ca334 100644 --- a/app/services/rotation_accounting.py +++ b/app/services/rotation_accounting.py @@ -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'])} diff --git a/app/services/rotation_service.py b/app/services/rotation_service.py index 35e94fc..93c8499 100644 --- a/app/services/rotation_service.py +++ b/app/services/rotation_service.py @@ -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) diff --git a/app/web/static/index.html b/app/web/static/index.html index d063b1e..7dae681 100644 --- a/app/web/static/index.html +++ b/app/web/static/index.html @@ -1063,7 +1063,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}

持仓

占比按总操作规模计算。 - ?
+ ?
@@ -1082,7 +1082,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} - + @@ -1105,7 +1105,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} - +