"""R614:独立标准库合成方法样例,不是实际历史绩效。""" from math import isclose prices={'A':[100,120,120],'B':[100,100,110],'C':[100,90,90]} initial=300 def run(universe): if not universe:raise ValueError('empty universe') equity=float(initial);shares={s:0 for s in universe};ledger=[];first={} for t in range(2): target={s:equity/len(universe)/prices[s][t] for s in universe} fills={s:target[s]-shares[s] for s in universe} contributions={s:target[s]*(prices[s][t+1]-prices[s][t]) for s in universe} equity+=sum(contributions.values());shares=target ledger.append({'session':t,'target_qty':target,'fills':fills,'equity':equity}) if t==0:first=contributions return equity,ledger,first original,orig_rows,contrib=run(['A','B','C']) removed=min(contrib,key=lambda s:(-contrib[s],s)) residual,rows,_=run([s for s in prices if s!=removed]) assert removed=='A' and rows[0]['target_qty']['B']==1.5 assert isclose(residual,299.25,abs_tol=1e-10) assert not isclose(original-contrib[removed],residual,abs_tol=1e-10) try:run([]) except ValueError:pass else:raise AssertionError('empty universe accepted') print('removed_from_seen_development=A first_contributions='+str(contrib)) print('original='+format(original,'.6f')+' residual='+format(residual,'.6f')+' naive_subtraction='+format(original-contrib[removed],'.6f')) print('residual_first_quantities='+str(rows[0]['target_qty'])+' weights_regenerated=True fractional_synthetic=True')