统一导出金额与表格四舍五入口径
This commit is contained in:
parent
f50449d0bd
commit
017ead5f77
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
09:25在155确认资金提示的ValueError实际为雷赛智能缺少盘前分钟行情,数量对账正常;09:30行情自然恢复后现金差0。修改只读估值为逐策略保留未知值,现金、数量继续独立核对,严格划拨和日结健康判断不放宽。成本均价固定显示三位,导出保留原始加权精度并按金额计算盈亏,补零股保护。用户确认48.296是含费成本,而原QMT成交及最新持仓均48.290、费用未知,故不改写成交或猜测手续费。自然执行依据刷新还暴露Decimal无法编码,复用既有JSON类型转换修复。
|
||||
|
||||
独立复核还发现公示导出把负向手续费流水再次相减,误加为平仓收益;已在导出边界修正费用和退款方向,保留原账本符号。新增估值18、精度及费用11、执行依据编码5项隔离检查,页面与全量验证及实际发布结果见[本次接续](docs/策略估值与成本精度修复_2026-11-04.md)。本条为实施记录,部署结果另补,不能当作已上线回执。
|
||||
独立复核还发现公示导出把负向手续费流水再次相减,误加为平仓收益;已在导出边界修正费用和退款方向,保留原账本符号。导出金额采用十进制累计、半分四舍五入,与Excel公式一致;市值与成本分别到分再相减,缺行情按成本顶价时不制造虚假盈亏。新增估值18、精度及费用14、执行依据编码5项隔离检查,页面与全量验证及实际发布结果见[本次接续](docs/策略估值与成本精度修复_2026-11-04.md)。本条为实施记录,部署结果另补,不能当作已上线回执。
|
||||
|
||||
> 这份文件的用途只有一个:**让下一次交接不必重新查一遍**。
|
||||
> 每个重要节点写一条,写完就补,不攒到最后。一条节点包含五样东西:
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ import logging
|
|||
import os
|
||||
from copy import copy
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
|
||||
from app.repo import downstream_repo, pms_repo
|
||||
from app.services import market, param_store
|
||||
|
|
@ -59,6 +60,16 @@ TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__f
|
|||
# 1 标题 · 2 起始时间 · 3 更新时间 · 4 持仓表头 · 5 持仓样式行 · 6 持仓小计
|
||||
# 7 卖出表头 · 8 卖出样式行 · 9 卖出小计 · 10 存量合计行 · 11 底部指标行
|
||||
_R_HPROTO, _R_HSUB, _R_CHEAD, _R_CPROTO, _R_CSUB, _R_SUM1, _R_SUM2 = 5, 6, 7, 8, 9, 10, 11
|
||||
_ZERO = Decimal('0')
|
||||
|
||||
|
||||
def _decimal(value):
|
||||
return value if isinstance(value, Decimal) else Decimal(str(value or 0))
|
||||
|
||||
|
||||
def _money(value):
|
||||
"""与表格 ROUND(..., 2) 一致,半分远离零舍入;不用于原始均价。"""
|
||||
return _decimal(value).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 取数与口径
|
||||
|
|
@ -105,7 +116,7 @@ def _fee_map() -> dict:
|
|||
读不到按空 —— 费用缺席只影响平仓行含费口径,
|
||||
表尾会把未摊费用标出来, 不拦导出。"""
|
||||
try:
|
||||
return {(int(r["ymd"]), r["ts_code"]): -float(r["fee"] or 0)
|
||||
return {(int(r["ymd"]), r["ts_code"]): -_decimal(r["fee"])
|
||||
for r in pms_repo.fee_sum_by_code()}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("公示导出读费用失败 (平仓行按不含费出): %s", e)
|
||||
|
|
@ -148,9 +159,9 @@ def _compute_snapshot() -> dict:
|
|||
for r in open_lots:
|
||||
code = r["ts_code"]
|
||||
qty = int(r.get("qty") or 0)
|
||||
cost = float(r.get("open_price") or 0)
|
||||
cost = _decimal(r.get("open_price"))
|
||||
od = _as_date(r.get("open_date")) or today
|
||||
g = grp.setdefault(code, {"qty": 0, "amount": 0.0, "open_date": od})
|
||||
g = grp.setdefault(code, {"qty": 0, "amount": _ZERO, "open_date": od})
|
||||
g["qty"] += qty
|
||||
g["amount"] += cost * qty
|
||||
g["open_date"] = min(g["open_date"], od)
|
||||
|
|
@ -168,8 +179,8 @@ def _compute_snapshot() -> dict:
|
|||
holdings.append({
|
||||
"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": cost,
|
||||
"amount": float(_money(g["amount"])), "open_date": g["open_date"],
|
||||
"upd_date": today, "structure": structure, "cost": float(cost),
|
||||
"qty": g["qty"], "price": float(px),
|
||||
"days": _days(g["open_date"], today),
|
||||
})
|
||||
|
|
@ -181,57 +192,58 @@ def _compute_snapshot() -> dict:
|
|||
cq = int(r.get("closed_qty") or 0)
|
||||
if cq <= 0:
|
||||
continue
|
||||
cost = float(r.get("open_price") or 0)
|
||||
settle = float(r.get("close_avg_price") or 0)
|
||||
cost = _decimal(r.get("open_price"))
|
||||
settle = _decimal(r.get("close_avg_price"))
|
||||
od = _as_date(r.get("open_date")) or today
|
||||
cd = _as_date(r.get("updated_at")) or today
|
||||
g = cgrp.setdefault((code, cd), {"qty": 0, "amount": 0.0, "settle_amt": 0.0,
|
||||
"pnl": 0.0, "open_date": od})
|
||||
g = cgrp.setdefault((code, cd), {"qty": 0, "amount": _ZERO, "settle_amt": _ZERO,
|
||||
"pnl": _ZERO, "open_date": od})
|
||||
g["qty"] += cq
|
||||
g["amount"] += cost * cq
|
||||
g["settle_amt"] += settle * cq
|
||||
g["pnl"] += float(r.get("realized_pnl") or 0)
|
||||
g["pnl"] += _decimal(r.get("realized_pnl"))
|
||||
g["open_date"] = min(g["open_date"], od)
|
||||
|
||||
closed, fee_alloc = [], 0.0
|
||||
closed, fee_alloc = [], _ZERO
|
||||
for (code, cd) in sorted(cgrp, key=lambda k: (k[1], k[0])):
|
||||
g = cgrp[(code, cd)]
|
||||
fee = fees.get((int(cd.strftime("%Y%m%d")), code), 0.0)
|
||||
fee = fees.get((int(cd.strftime("%Y%m%d")), code), _ZERO)
|
||||
fee_alloc += fee
|
||||
closed.append({
|
||||
"account": account, "code": code.split(".")[0],
|
||||
"name": _display_name(names.get(code), code),
|
||||
"amount": round(g["amount"], 2), "open_date": g["open_date"],
|
||||
"amount": float(_money(g["amount"])), "open_date": g["open_date"],
|
||||
"close_date": cd, "structure": structure,
|
||||
"cost": g["amount"] / g["qty"], "qty": g["qty"],
|
||||
"settle": g["settle_amt"] / g["qty"],
|
||||
"cost": float(g["amount"] / g["qty"]), "qty": g["qty"],
|
||||
"settle": float(g["settle_amt"] / g["qty"]),
|
||||
"days": _days(g["open_date"], cd),
|
||||
"pnl": round(g["pnl"] - fee, 2),
|
||||
"pnl": float(_money(g["pnl"] - fee)),
|
||||
})
|
||||
|
||||
# 未摊入明细的费用 (买入侧 + 无代码归属的校准行): 表尾如实标注, 不悄悄吞掉
|
||||
try:
|
||||
# 仓储返回有符号现金流,导出费用按成本口径反号;退款不可取绝对值。
|
||||
fee_total = -float(pms_repo.sum_fee_all())
|
||||
fee_total = -_decimal(pms_repo.sum_fee_all())
|
||||
except Exception: # noqa: BLE001
|
||||
fee_total = fee_alloc
|
||||
fee_resid = round(fee_total - fee_alloc, 2)
|
||||
fee_resid = float(_money(fee_total - fee_alloc))
|
||||
|
||||
hold_cost = sum(h["amount"] for h in holdings)
|
||||
hold_cost = sum((_decimal(h["amount"]) for h in holdings), _ZERO)
|
||||
# 金额先核算到分,均价只在页面/单元格格式上显示三位;不能先截均价再乘股数。
|
||||
hold_pnl = sum(round(h["price"] * h["qty"] - h["amount"], 2) for h in holdings)
|
||||
realized = sum(c["pnl"] for c in closed)
|
||||
hold_pnl = sum((_money(_decimal(h["price"]) * h["qty"]) - _decimal(h["amount"])
|
||||
for h in holdings), _ZERO)
|
||||
realized = sum((_decimal(c["pnl"]) for c in closed), _ZERO)
|
||||
total_pnl = hold_pnl + realized
|
||||
nav = 1.0 + total_pnl / scale
|
||||
openable = scale + realized # 可开仓总金额 = 净值规模 + 已实现盈亏 (模板口径)
|
||||
nav = 1.0 + float(total_pnl) / scale
|
||||
openable = _decimal(scale) + realized # 可开仓总金额 = 净值规模 + 已实现盈亏 (模板口径)
|
||||
return {
|
||||
"today": today, "scale": scale, "holdings": holdings, "closed": closed,
|
||||
"hold_cost": round(hold_cost, 2), "hold_pnl": round(hold_pnl, 2),
|
||||
"closed_cost": round(sum(c["amount"] for c in closed), 2),
|
||||
"realized": round(realized, 2), "total_pnl": round(total_pnl, 2),
|
||||
"nav": round(nav, 4), "openable": round(openable, 2),
|
||||
"open_room": round(openable - hold_cost, 2),
|
||||
"pos_ratio": round(hold_cost / openable, 4) if openable > 0 else None,
|
||||
"hold_cost": float(_money(hold_cost)), "hold_pnl": float(_money(hold_pnl)),
|
||||
"closed_cost": float(_money(sum((_decimal(c["amount"]) for c in closed), _ZERO))),
|
||||
"realized": float(_money(realized)), "total_pnl": float(_money(total_pnl)),
|
||||
"nav": round(nav, 4), "openable": float(_money(openable)),
|
||||
"open_room": float(_money(openable - hold_cost)),
|
||||
"pos_ratio": round(float(hold_cost / openable), 4) if openable > 0 else None,
|
||||
"price_missing": sorted(price_missing), "fee_resid": fee_resid,
|
||||
"title": str(param_store.get("PMS_PUBLISH_TITLE") or "量化产品基本信息"),
|
||||
}
|
||||
|
|
@ -296,7 +308,7 @@ def _entry_row(ws, row, seq, e, *, date2, px):
|
|||
_put(ws, row, 7, f"=ROUND(K{row}*L{row},2)")
|
||||
# S 总持股浮动盈亏: 持仓 = 市值减成本金额;平仓 = 含费实得,沿用账本数值
|
||||
if e.get("pnl") is None:
|
||||
_put(ws, row, 19, f"=ROUND(M{row}*L{row}-G{row},2)")
|
||||
_put(ws, row, 19, f"=ROUND(ROUND(M{row}*L{row},2)-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 持有收益率
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@
|
|||
<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><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:'退出并停用'};
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
- 只读展示把现金、数量对账与估值拆开。缺行情时保留现金、成本和股数,受影响策略及账户的市值、权益、盈利和净值为空,提示具体证券。严格估值仍用于初始化、资金划拨;不会用零、成本价或昨收代替执行行情。日结不得把缺估值标为健康。
|
||||
- 页面成本、开仓均价及核销均价固定显示三位;金额与均价采用各自精度。页面和表格标明费用另计,既有成交、账本、资金及费用记录不改写。
|
||||
- 导出保留加权均价的计算精度,仅用单元格格式显示三位;成本金额和盈亏核算到分。复现案例为100股48.290加200股48.291,实际成本14487.20,现价49.01时盈亏215.80;原来先舍入均价导致215.70。表格修改成本或股数后,成本金额和持仓盈亏同步重算。
|
||||
- 金额半分边界也须与Excel公式一致:Python的round(48.285,2)为48.28,而表格ROUND为48.29。导出计算采用原始十进制价格累计,金额按四舍五入到分,均价本身不量化成分;不把已舍入金额除股数反灌为新的均价。
|
||||
- 执行依据HTTP入口复用研判接口的明确类型转换,Decimal保留为JSON数值,未知对象和非有限数仍拒绝发送。没有注入模型请求、信号或验收委托。
|
||||
- 导出费用聚合原样读取负向现金流水,却再次从平仓收益中相减,导致费用被加为盈利。本次仅在导出边界转成费用口径,不取绝对值,退款方向保留,未分摊费用残差同步修正;账本现金流水定义不变。
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
新增限制价采集专项:core 25例、provider 21例、targets 18例、collector 28例,
|
||||
缓存消费23例、独立进程入口6例。
|
||||
策略资金缺行情展示与严格划拨专项18例;成本均价展示与导出精度专项11例。
|
||||
策略资金缺行情展示与严格划拨专项18例;成本均价展示与导出精度专项14例。
|
||||
执行依据数据库数值序列化专项5例。
|
||||
|
||||
包含 (例数按 2026-10-26 隔离回归实跑校正):
|
||||
|
|
|
|||
|
|
@ -116,7 +116,7 @@ class CostPrecisionTests(unittest.TestCase):
|
|||
# 表格可编辑:成本、股数变化同时进入成本金额与盈亏,再进入小计和净值。
|
||||
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['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)')
|
||||
self.assertEqual(sheet['G6'].value, '=SUM(G5:G5)')
|
||||
self.assertEqual(sheet['S6'].value, '=SUM(S5:S5)')
|
||||
|
||||
|
|
@ -152,14 +152,52 @@ class CostPrecisionTests(unittest.TestCase):
|
|||
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,
|
||||
def test_half_cent_cost_matches_workbook_round_without_rounding_unit_cost(self):
|
||||
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
|
||||
open_price=48.285, open_date=date.today())
|
||||
snapshot = publish_export.compute_snapshot()
|
||||
self.assertEqual(snapshot['holdings'][0]['cost'], 48.285)
|
||||
self.assertEqual(snapshot['holdings'][0]['amount'], 48.29)
|
||||
self.assertEqual(snapshot['hold_cost'], 48.29)
|
||||
self.assertEqual(snapshot['hold_pnl'], .72)
|
||||
self.assertEqual(snapshot['open_room'], 1999951.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.285)
|
||||
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)')
|
||||
self.assertEqual(sheet['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)')
|
||||
|
||||
def test_multiple_lots_accumulate_before_half_cent_rounding(self):
|
||||
for price in (48.281, 48.284):
|
||||
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
|
||||
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)
|
||||
row = snapshot['holdings'][0]
|
||||
self.assertEqual((row['qty'], row['cost'], row['amount']), (2, 48.2825, 96.57))
|
||||
self.assertEqual(snapshot['hold_pnl'], 1.45)
|
||||
|
||||
def test_market_value_rounds_to_cents_before_profit_subtraction(self):
|
||||
for cost, price, expected in ((48.29, 49.015, .73), (49.01, 48.285, -.72)):
|
||||
with self.subTest(cost=cost, price=price):
|
||||
self.fake = install_fakes(prices={'002979.SZ': price},
|
||||
params={'PMS_TOTAL_SCALE': '2000000'})
|
||||
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
|
||||
open_price=cost, open_date=date.today())
|
||||
snapshot = publish_export.compute_snapshot()
|
||||
self.assertEqual(snapshot['hold_pnl'], expected)
|
||||
self.assertIsInstance(snapshot['hold_pnl'], float)
|
||||
|
||||
def test_missing_quote_uses_exact_cost_without_false_profit(self):
|
||||
for lots in (((100, 48.290), (200, 48.291)), ((1, 48.285),)):
|
||||
with self.subTest(lots=lots):
|
||||
self.fake = install_fakes(prices={}, params={'PMS_TOTAL_SCALE': '2000000'})
|
||||
for qty, price in lots:
|
||||
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()
|
||||
|
|
|
|||
|
|
@ -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 == "=ROUND(M5*L5-G5,2)"
|
||||
assert ws["U5"].value == "=1+T5" and ws["S5"].value == "=ROUND(ROUND(M5*L5,2)-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)"
|
||||
|
|
|
|||
Loading…
Reference in New Issue