tradingSystem/app/core/timing_fusion_contract.py

72 lines
3.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""核验决策系统合成结果的契约,不在PMS重算择时。"""
import math
from app.core import risk_exit as rules
from app.core.command_spec import is_stock_code
VERSION = 'timing_fusion_v1'
GROUPS = ('qrs', 'main_fund', 'v3f')
def valid(value, now, *, since=None):
if not isinstance(value, dict) or value.get('version') != VERSION or value.get('source') != 'timing_fusion':
return None
code = str(value.get('ts_code') or '')
if not is_stock_code(code) or not code.endswith(('.SH', '.SZ')):
return None
at, verified, expiry, now = map(rules.stamp, (value.get('at'), value.get('verified_at'), value.get('expires_at'), now))
if not all((at, verified, expiry, now)) or not at <= verified <= now < expiry or verified.date() != now.date():
return None
if (now-verified).total_seconds() > 120 or (expiry-verified).total_seconds() > 120:
return None
if since is not None:
start = rules.stamp(since)
if not start or at < start:
return None
key = value.get('key', '')
if len(key) != 64 or any(c not in '0123456789abcdef' for c in key):
return None
groups = value.get('groups')
if not isinstance(groups, dict) or set(groups) != set(GROUPS):
return None
try:
for name, group in groups.items():
if abs(float(group['weight'])-1/3)>1e-9 or group['direction'] not in (-1, 0, 1):
return None
if group['state'] not in ('VALID','UNKNOWN') or bool(group['evidence']) != (group['state']=='VALID'):
return None
if group['state']=='UNKNOWN' and group['direction'] != 0:
return None
for e in group['evidence']:
start, end = rules.stamp(e['at']), rules.stamp(e['expires_at'])
if (e['group'] != name or e['ts_code'] != code or not start or not end
or not start <= now < end or start.date() != now.date() or not e['identity']):
return None
sign = 1 if value.get('action') == 'BUY' else -1 if value.get('action') == 'SELL' else 0
if value.get('action') not in ('BUY','SELL','WAIT'):
return None
if not math.isfinite(float(value['score'])):
return None
if sign and (sum(g['direction']==sign for g in groups.values()) < 2
or float(value['score'])*sign < 2/3-1e-8):
return None
except (KeyError, TypeError, ValueError):
return None
return value
def duplicate(events, event):
"""重复读取不能形成第二次清仓;支持组需有新的独立观察。"""
for old in events:
if old.get('key') == event.get('key'):
return True
if old.get('source') == 'timing_fusion':
old_time = rules.stamp(old.get('at'))
fresh_groups = sum(g['direction'] == -1 and bool(g['evidence'])
and all(rules.stamp(e['at']) > old_time and e['identity'] not in
{x['identity'] for before in old.get('groups', {}).values() for x in before['evidence']}
for e in g['evidence'])
for g in event['groups'].values())
if fresh_groups < 2:
return True
return False