"""Alpha41同一合成成交带的真实VWAP与典型价格代理对照。""" import json from math import sqrt, isclose tapes = {'A': [(12, 90), (8, 10)], 'B': [(8, 90), (12, 10)]} def vwap(amount, volume, low, high): if volume <= 0: raise ValueError('零成交量没有VWAP') value = amount / volume if not low <= value <= high: raise ValueError('单位或窗口不一致') return value exact, proxy = {}, {} for symbol, trades in tapes.items(): amount = sum(p * q for p, q in trades) volume = sum(q for _, q in trades) weighted = vwap(amount, volume, 8, 12) typical = (12 + 8 + trades[-1][0]) / 3 exact[symbol] = sqrt(12 * 8) - weighted proxy[symbol] = sqrt(12 * 8) - typical assert isclose(exact['A'], sqrt(96) - 11.6) assert isclose(exact['B'], sqrt(96) - 8.4) selected = max(exact, key=exact.get) approx_selected = max(proxy, key=proxy.get) assert selected == 'B' and approx_selected == 'A' marks = {'A': 9.8, 'B': 10.2} ending = {s: 1000 - 40 * 10 - 1 + 40 * marks[s] - 1 for s in 'AB'} assert ending == {'A': 990, 'B': 1006} rejected = [] for amount, volume in [(1.16, 100), (0, 0)]: try: vwap(amount, volume, 8, 12) except ValueError: rejected.append([amount, volume]) assert len(rejected) == 2 print(json.dumps({'exact_scores': exact, 'proxy_scores': proxy, 'exact_selected': selected, 'proxy_selected': approx_selected, 'ending_cash': ending, 'invalid_unit_and_zero_volume_rejected': rejected}))