"""持仓收益展示。保留负净成本,不用收益展示反推交易安全垫。""" from decimal import Decimal, InvalidOperation def calculate(row, lots): empty = {'ready': False, 'profit': None, 'profit_pct': None, 'net_cost': None, 'remaining_cost': None, 'realized': None, 'unrealized': None, 'cost_recovered': False, 'reason': '持仓成本待核实'} try: def number(value): if value is None or isinstance(value, bool): raise ValueError('缺少金额') n = Decimal(str(value)) if not n.is_finite(): raise ValueError('金额无效') return n qty = int(row['total_qty']) if qty <= 0: return dict(empty, ready=True, profit=0., net_cost=0., remaining_cost=0., realized=0., unrealized=0., reason=None) if not lots or sum(int(l['qty']) for l in lots) != qty: return empty remaining = Decimal(0) realized = Decimal(0) for lot in lots: n = int(lot['qty']) price = number(lot['open_price']) if n < 0 or price <= 0: return empty remaining += n * price realized += number(lot['realized_pnl']) net = remaining - realized result = dict(empty, net_cost=float(net), remaining_cost=float(remaining), realized=float(realized), cost_recovered=net <= 0) if not row.get('price_ok'): return dict(result, reason='持仓行情待补齐') price = number(row['price']) if price <= 0: return dict(result, reason='持仓行情待补齐') value = price * qty profit = value - net return dict(result, ready=True, profit=float(profit.quantize(Decimal('.01'))), profit_pct=float(profit / net) if net > 0 else None, unrealized=float((value - remaining).quantize(Decimal('.01'))), reason=None) except (ValueError, TypeError, KeyError, InvalidOperation): return empty