"""Build the isolated MSC rehearsal from the input file, offline""" from decimal import Decimal as D, getcontext import json,sys from pathlib import Path getcontext().prec=60 EPS=D('1e-8') def select(ranking,old): ranked=sorted(ranking,key=lambda x:(-D(x['cap']),x['address'])) incumbents=set(old) for n,r in enumerate(ranked,1):r['rank']=n chosen=ranked[:7] for row in ranked[7:12]: if len(chosen)<10 and row['address'] in incumbents:chosen.append(row) protected={r['address'] for r in chosen[7:]} for row in ranked[7:]: if len(chosen)==10:break if row not in chosen:chosen.append(row) if len(chosen)!=10:raise ValueError('Insufficient eligible contracts') left={r['address']:D(r['cap']).sqrt() for r in chosen} weights={};budget=D(10000) while left: total=sum(left.values()) uncapped={a:budget*w/total for a,w in left.items()} caps=[a for a,w in uncapped.items() if w>2000] if not caps:weights.update(uncapped);break for a in caps:weights[a]=D(2000);budget-=2000;del left[a] bps={a:int(v) for a,v in weights.items()} for a in sorted(weights,key=lambda a:(bps[a]-weights[a],a))[:10000-sum(bps.values())]:bps[a]+=1 assert sum(bps.values())==10000 and max(bps.values())<=2000 return bps,protected def build(d): old=d['old'];ranking=d['ranking'] bps,protected=select(ranking,old) preview=[] ranks={r['address']:r for r in ranking} for a in dict.fromkeys([r['address'] for r in sorted(ranking,key=lambda r:r['rank'])]+list(old)): r=ranks.get(a,{}); prev=old.get(a,{}) reason=('Top seven' if r.get('rank',99)<=7 else 'Incumbent buffer' if a in protected else 'Ranked fill') if a in bps else ('Outside selected ranks' if r else d['exclusions'].get(a,'Outside review universe')) preview.append(dict(address=a,symbol=r.get('symbol') or prev['symbol'],rank=r.get('rank'),old=prev.get('bps',0),new=bps.get(a,0),reason=reason)) units={a:D(r['bps'])/D(r['base']) for a,r in old.items()} output=[];deferred=[];bridge=None for t in d['minutes']: m=t['minute'];quotes={a:D(q['price']) for a,q in t['quotes'].items() if q['price'] and D(q['price'])>0 and m<=q['checkedAt']=d['scheduled']: missing=sorted((set(old)|set(bps))-quotes.keys()) if missing:deferred.append(dict(minute=m,missing=missing)) else: before={a:u*quotes[a] for a,u in units.items()};level=sum(before.values()) units={a:level*w/10000/quotes[a] for a,w in bps.items()} bridge=m marks={a:u*quotes[a] for a,u in units.items() if a in quotes} level=sum(marks.values()) if len(marks)==10 else None if before:assert abs(sum(before.values())-level)