"""接收基座已发布的专项研究;不触发研究,不改变交易候选资格。""" import json import re import urllib.parse import urllib.request def collect(codes, cutoff, base): from dividend_watch import instant result = {} ordered = sorted(set(codes)) for start in range(0, len(ordered), 200): batch = ordered[start:start+200] try: url = base.rstrip('/') + '/research/dividends?' + urllib.parse.urlencode( {'codes': ','.join(batch), 'asof': str(cutoff)}) with urllib.request.urlopen(url, timeout=15) as response: body = response.read(8_000_001) if len(body) > 8_000_000: raise ValueError('研究摘要过大') raw = json.loads(body) if raw.get('schema_version') != 1 or instant(raw['cutoff_at']) != instant(cutoff): raise ValueError('研究契约或截止时刻不符') for code in batch: value = raw['items'][code] research = value.get('research') if research: if (research.get('ts_code') != code or research.get('schema_version') != 1 or research.get('kind') != 'dividend_sustainability' or not re.fullmatch('[0-9a-f]{64}', str(research.get('ref', ''))) or research.get('conclusion') not in ('有支持', '存在压力', '证据不足') or instant(research['cutoff_at']) > instant(cutoff) or instant(research['generated_at']) > instant(cutoff)): raise ValueError('专项研究身份、时间或结论异常') for code in batch: value = raw['items'][code] research = value.get('research') last = value.get('last_check') or {} status = ('pending' if last.get('state') == 'running' else 'unavailable' if last.get('state') == 'failed' else 'due' if value.get('review_due') and research else 'ok' if research else 'missing') result[code] = {'status': status, **value, 'url': base.rstrip('/') + '/research/dividends/' + code + '?ref=' + research['ref'] if research else None} except Exception as exc: for code in batch: result[code] = {'status': 'unavailable', 'error_type': type(exc).__name__, 'research': None} return result def display(value): value = value or {} status = value.get('status') if status == 'ok' and value.get('research'): return value['research']['conclusion'] return {'pending': '专项研究更新中', 'unavailable': '专项研究暂不可用', 'due': '待月度复核'}.get(status, '待核验')