"""R648:合成持仓快照只读输入,确认现金后建立独立虚拟分支。""" from decimal import Decimal as D from datetime import datetime from copy import deepcopy import json,hashlib def positive_price(value): out=D(str(value)) if not out.is_finite() or out<=0:raise ValueError('invalid mark') return out def initialize(snapshot,prices,cash,excluded): time=datetime.fromisoformat(snapshot['asof']) if time.utcoffset() is None or snapshot['currency']!='USD':raise ValueError('unsupported timestamp or currency') holdings=snapshot['holdings'];basket={'A','B'} if any(not isinstance(s,str) or not s.strip() or type(q) is not int or q<0 for s,q in holdings.items()):raise ValueError('invalid holding identity or quantity') uncovered=set(holdings)-basket if set(excluded)!=uncovered or any(not isinstance(v,str) or not v.strip() for v in excluded.values()):raise ValueError('unconfirmed exclusion') accepted={s:q for s,q in holdings.items() if s in basket} if set(prices)!=set(accepted):raise ValueError('missing snapshot mark') value=sum((q*positive_price(prices[s]) for s,q in accepted.items()),D(0)) if cash is None:return {'status':'waiting_cash','covered_value':value,'excluded':dict(excluded)} cash=D(str(cash)) if not cash.is_finite() or cash<0:raise ValueError('invalid independent cash') return {'status':'active_partial_scope','asof':snapshot['asof'],'currency':'USD','version':'human-v1','cash':cash,'shares':deepcopy(accepted),'excluded':dict(excluded),'initial_NAV':cash+value} def buy(state,security,qty,price,fee): out=deepcopy(state);price=positive_price(price);fee=D(str(fee)) if out['status']!='active_partial_scope' or security not in out['shares'] or type(qty) is not int or qty<=0 or not fee.is_finite() or fee<0:raise ValueError('invalid branch action') cost=qty*price+fee if cost>out['cash']:raise ValueError('cannot spend position value') before=out['cash']+out['shares'][security]*price out['cash']-=cost;out['shares'][security]+=qty assert out['cash']+out['shares'][security]*price==before-fee return out def nav(state,prices): if set(prices)!=set(state['shares']):raise ValueError('incomplete branch marks') return state['cash']+sum((q*positive_price(prices[s]) for s,q in state['shares'].items()),D(0)) snapshot={'asof':'2026-01-01T16:00:00+00:00','currency':'USD','holdings':{'A':2,'B':3,'C':5}} original=deepcopy(snapshot);sealed=hashlib.sha256(json.dumps(snapshot,sort_keys=True).encode()).hexdigest() excluded={'C':'outside fixed A/B basket; explicitly excluded from partial branch'} waiting=initialize(snapshot,{'A':100,'B':50},None,excluded) assert waiting['status']=='waiting_cash' and waiting['covered_value']==D(350) and 'cash' not in waiting branch=initialize(snapshot,{'A':100,'B':50},200,excluded) assert branch['initial_NAV']==D(550) and nav(branch,{'A':110,'B':45})==D(555) branch=buy(branch,'A',1,110,1) assert branch['cash']==D(89) and branch['shares']=={'A':3,'B':3} and nav(branch,{'A':110,'B':45})==D(554) later_real_snapshot={'holdings':{'A':2,'B':0,'C':5},'cash':'335'} assert branch['shares']['B']==3 and branch['cash']==D(89) assert nav(branch,{'A':105,'B':40})==D(524) assert snapshot==original and hashlib.sha256(json.dumps(snapshot,sort_keys=True).encode()).hexdigest()==sealed for action in [lambda:initialize(snapshot,{'A':100,'B':50},200,{}),lambda:buy(branch,'A',1,100,1),lambda:initialize(snapshot,{'A':'NaN','B':50},200,excluded)]: try:action() except ValueError:pass else:raise AssertionError('unknown scope, cash or valuation silently accepted') print('snapshot_covered_value=350 unknown_cash=waiting confirmed_cash=200 initial_NAV=550 explicit_uncovered=C') print('pretrade_NAV=555 posttrade_NAV=554 cash=89 shares=A:3,B:3 later_NAV=524') print('later_real_sale_does_not_sync=True original_snapshot_unchanged=True user_account_access=False partial_scope=True')