137 lines
6.5 KiB
Python
137 lines
6.5 KiB
Python
"""两次清仓信号与买方评级下降。只识别事实,不生成新的研判。"""
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
TZ = timezone(timedelta(hours=8))
|
|
GRADES = {'差': 0, '中': 1, '好': 2}
|
|
|
|
|
|
def stamp(value):
|
|
try:
|
|
if isinstance(value, datetime):
|
|
d = value
|
|
elif isinstance(value, (int, float)) or str(value).isdigit():
|
|
n = float(value)
|
|
d = datetime.fromtimestamp(n / 1000 if n > 100000000000 else n, TZ)
|
|
else:
|
|
d = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
|
return d.replace(tzinfo=TZ) if d.tzinfo is None else d.astimezone(TZ)
|
|
except (ValueError, TypeError, OverflowError, OSError):
|
|
return None
|
|
|
|
|
|
def digest(value):
|
|
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
separators=(',', ':'), allow_nan=False).encode()).hexdigest()
|
|
|
|
|
|
def user_stop_event(command, quote, *, now, max_age=90):
|
|
"""人工止损只认有效命令与生效后的当日行情,不读取系统参考位。"""
|
|
from app.core.execution_policy import positive, timestamp, supported_code
|
|
command, quote = command or {}, quote or {}
|
|
code = command.get('ts_code')
|
|
if (not supported_code(code) or command.get('cmd_type') != 'SET_STOP_PRICE'
|
|
or command.get('status') != 'EFFECTIVE' or not command.get('command_id')):
|
|
return None, '没有有效的人工止损命令'
|
|
stop = positive((command.get('params') or {}).get('price'))
|
|
if not stop:
|
|
return None, '未设置有效人工止损价'
|
|
current, issued = stamp(now), stamp(command.get('issued_at'))
|
|
at, price = timestamp(quote.get('as_of')), positive(quote.get('last'))
|
|
if (not current or not issued or issued > current or not at or not price
|
|
or quote.get('kind') != 'minute' or not quote.get('source')):
|
|
return None, '人工止损等待可核实的命令时间与当日行情'
|
|
if (at.date() != current.date() or at < issued or at > current
|
|
or (current-at).total_seconds() > max_age):
|
|
return None, '人工止损等待命令生效后的有效行情'
|
|
if price > stop:
|
|
return None, '尚未触及人工止损价'
|
|
return {'command_id': command['command_id'], 'issued_at': issued.isoformat(),
|
|
'stop_price': stop, 'price': price, 'quote_at': at.isoformat(),
|
|
'quote_source': quote['source'], 'observed_at': current.isoformat()}, ''
|
|
|
|
|
|
def signal_event(sig, *, now, since, threshold=.85, max_age=300, actions=('SELL',)):
|
|
"""真正的清仓级信号才计次。过期、未来、回退结论及无出处不计数。"""
|
|
code = str(sig.get('ts_code') or '')
|
|
from app.core.command_spec import is_stock_code
|
|
if not is_stock_code(code) or not code.endswith(('.SH', '.SZ')):
|
|
return None, '证券不在沪深范围'
|
|
try:
|
|
conf = float(sig.get('confidence'))
|
|
except (TypeError, ValueError):
|
|
return None, '没有有效置信度'
|
|
if (sig.get('action') not in actions or not math.isfinite(conf) or conf < threshold or conf > 1
|
|
or sig.get('is_fallback') not in (None, False, 0, 'false', '0', '')):
|
|
return None, '不是有效清仓级结论'
|
|
source = sig.get('source')
|
|
if source not in ('intraday', 'risk_sell'):
|
|
return None, '信号来源不可核实'
|
|
if source == 'risk_sell' and sig.get('action') != 'SELL':
|
|
return None, '风控卖出流不能提供转多结论'
|
|
reason = ' '.join(str(sig.get('reason') or '').split())[:500]
|
|
at = stamp(sig.get('event_time'))
|
|
now, start = stamp(now), stamp(since)
|
|
if not at or not now or not start or not reason or not sig.get('msg_id'):
|
|
return None, '缺少原始信号时间、内容或标识'
|
|
if at < start or at > now or (now-at).total_seconds() > max_age:
|
|
return None, '信号不在当前有效窗口'
|
|
expiry = stamp(sig.get('expires_at'))
|
|
if sig.get('expires_at') is not None and (not expiry or now >= expiry):
|
|
return None, '信号已过期或期限无效'
|
|
producer = str(sig.get('producer_id') or '')
|
|
if source == 'intraday' and not producer.startswith('bionic_brain_intraday'):
|
|
return None, '不是决策系统盘中研判'
|
|
source_id = str(sig.get('signal_id') or '')
|
|
# 风控流未提供研判编号,保留原始时间与内容指纹;不把消费时刻当研判时刻。
|
|
key = digest([code, source, source_id or at.isoformat(), reason])
|
|
return {'key': key, 'source': source, 'source_id': source_id,
|
|
'msg_id': str(sig['msg_id']), 'at': at.isoformat(), 'confidence': conf,
|
|
'reason': reason[:500], 'content': digest([code, reason])}, ''
|
|
|
|
|
|
def duplicate(events, event, *, mirror_seconds=120):
|
|
for old in events:
|
|
if old.get('key') == event['key']:
|
|
return True
|
|
if old.get('source') == event['source'] and old.get('msg_id') == event['msg_id']:
|
|
return True
|
|
if old.get('source') == event['source'] and event.get('source_id') and old.get('source_id') == event['source_id']:
|
|
return True
|
|
# 上游两条流没有共同研判编号,文案也可能不同。近时跨流不能证明独立,只记一次。
|
|
if old.get('source') != event['source']:
|
|
a, b = stamp(old.get('at')), stamp(event.get('at'))
|
|
if a and b and abs((a-b).total_seconds()) <= mirror_seconds:
|
|
return True
|
|
return False
|
|
|
|
|
|
def review_snapshot(review, *, now, stale_days=120):
|
|
"""只接受可追溯的正式买方评析整体评级;缺失、过期不等于降级。"""
|
|
r = review if isinstance(review, dict) else {}
|
|
grade, ref = r.get('overall'), str(r.get('review_ref') or '')
|
|
at, current = stamp(r.get('report_ran_at')), stamp(now)
|
|
if grade not in GRADES or len(ref) != 64 or any(c not in '0123456789abcdef' for c in ref):
|
|
return None
|
|
if not at or not current or at > current or (current-at).days > stale_days:
|
|
return None
|
|
if r.get('qual') != 'ok' or r.get('brain_status') != 'ok':
|
|
return None
|
|
return {'grade': grade, 'ref': ref, 'at': at.isoformat()}
|
|
|
|
|
|
def review_change(before, after):
|
|
if not after:
|
|
return 'missing'
|
|
if not before:
|
|
return 'baseline'
|
|
if before['ref'] == after['ref']:
|
|
if before != after:
|
|
raise ValueError('同一买方评析版本内容不一致,等待核实')
|
|
return 'same'
|
|
if stamp(after['at']) <= stamp(before['at']):
|
|
return 'old'
|
|
return 'downgrade' if GRADES[after['grade']] < GRADES[before['grade']] else 'updated'
|