"""R639:人工提供候选规则的可执行审查;不调用模型或提取真实交易。""" from math import isfinite from copy import deepcopy FIELDS={'version','lookback','entry','exit','execution','qty','currency','basket','approved_by'} def approve(rule): if set(rule)!=FIELDS:raise ValueError('missing or unknown rule field') if any(not isinstance(rule[k],str) or not rule[k].strip() for k in ['version','approved_by']):raise ValueError('unknown approval identity') if type(rule['lookback']) is not int or rule['lookback']<1 or type(rule['qty']) is not int or rule['qty']!=1:raise ValueError('unsupported numeric rule') if rule['entry']!='close_gt_previous_mean' or rule['exit']!='close_lt_previous_mean':raise ValueError('unobservable or unsupported condition') if rule['execution']!='next_open' or rule['currency']!='USD' or rule['basket']!=['A']:raise ValueError('unsupported execution scope') return deepcopy(rule) def replay(rule,closes,opens): rule=approve(rule) if len(closes)!=len(opens):raise ValueError('unaligned sessions') if any(x is not None and (not isfinite(x) or x<=0) for x in closes+opens):raise ValueError('invalid price') events=[];unknown=[];holding=False for t in range(rule['lookback'],len(closes)): history=closes[t-rule['lookback']:t] if closes[t] is None or any(x is None for x in history):unknown.append(t);continue average=sum(history)/len(history) side='buy' if not holding and closes[t]>average else 'sell' if holding and closes[t]=len(opens) or opens[t+1] is None:unknown.append(t);continue events.append({'side':side,'decision':t,'fill':t+1,'price':opens[t+1]}) holding=side=='buy' return events,unknown rule={'version':'human-v1','lookback':2,'entry':'close_gt_previous_mean','exit':'close_lt_previous_mean','execution':'next_open','qty':1,'currency':'USD','basket':['A'],'approved_by':'fixture-reviewer'} closes=[100.,102.,105.,99.,98.];opens=[100.,101.,103.,104.,100.] events,unknown=replay(rule,closes,opens) assert [(e['side'],e['decision'],e['fill'],e['price']) for e in events]==[('buy',2,3,104.),('sell',3,4,100.)] assert unknown==[] for change in [{'entry':'buy_when_confident'},{'entry':'tomorrow_close_up'},{'approved_by':''},{'mood':'bullish'},{'lookback':True}]: try:approve(dict(rule,**change)) except ValueError:pass else:raise AssertionError('unconfirmed or unsupported rule approved') gaps=list(closes);gaps[1]=None gap_events,gap_unknown=replay(rule,gaps,opens) assert 2 in gap_unknown and 3 in gap_unknown and not gap_events bad=list(opens);bad[3]=float('nan') try:replay(rule,closes,bad) except ValueError:pass else:raise AssertionError('nonfinite market input') assert rule['version']=='human-v1' print('human_candidate=True model_calls=0 approved_scope=USD:A next_open=True') print('events='+str(events)+' unknown='+str(unknown)) print('vague_or_future_condition=rejected missing_history=unknown_not_bridged profitable_input_gate_is_not_validation=True')