131 lines
6.8 KiB
Python
131 lines
6.8 KiB
Python
"""宽基查询契约和展示投影。只接受整体15分钟事实,不生成交易信号。"""
|
||
from datetime import date, datetime, timedelta
|
||
import math
|
||
import re
|
||
|
||
from app.core.etf_intraday_view import SLOTS, TZ
|
||
|
||
CONTRACT = 'etf-intraday-query-1.0'
|
||
VIEW = 'latest_facts'
|
||
|
||
|
||
def timestamp(value):
|
||
at = datetime.fromisoformat(value)
|
||
if at.tzinfo is None:
|
||
raise ValueError('时间缺少时区')
|
||
return at.astimezone(TZ)
|
||
|
||
|
||
def number(value):
|
||
return type(value) in (int, float) and math.isfinite(value)
|
||
|
||
|
||
def latest_day(catalog, at):
|
||
if (catalog.get('contract_version') != CONTRACT
|
||
or 15 not in catalog.get('intervals_minutes', [])
|
||
or VIEW not in catalog.get('views', [])
|
||
or catalog.get('timezone') != 'Asia/Shanghai'):
|
||
raise ValueError('查询目录契约不匹配')
|
||
days = [date.fromisoformat(r['trade_date']) for r in catalog.get('dates', [])]
|
||
# 最新日标为不可用也请求该日,不能悄悄退回旧日并宣称更新正常。
|
||
days = [d for d in days if d <= at.astimezone(TZ).date()]
|
||
if not days:
|
||
raise ValueError('尚无可查询日期')
|
||
return max(days).isoformat()
|
||
|
||
|
||
def validate(document, day, at):
|
||
expected = {'contract_version': CONTRACT, 'trade_date': day, 'view': VIEW,
|
||
'interval_minutes': 15, 'timezone': 'Asia/Shanghai', 'amount_unit': 'CNY',
|
||
'purpose': 'MARKET_OBSERVATION',
|
||
'flow_basis': 'PRICE_VOLUME_PROXY_NOT_NET_SUBSCRIPTION',
|
||
'proxy_method': 'minute-price-change-signed-turnover-v1',
|
||
'intraday_net_subscription_status': 'UNAVAILABLE_DAILY_ONLY'}
|
||
if any(document.get(k) != v for k, v in expected.items()):
|
||
raise ValueError('查询口径不匹配')
|
||
if (document.get('trade_instruction') is not False
|
||
or document.get('live_signal_eligibility') is not False
|
||
or document.get('historical_use_allowed') is not True
|
||
or document.get('intraday_net_subscription_yuan') is not None):
|
||
raise ValueError('查询用途不匹配')
|
||
for k in ('data_version', 'cohort_sha256'):
|
||
if not re.fullmatch('[0-9a-f]{64}', str(document.get(k, ''))):
|
||
raise ValueError('查询版本缺失')
|
||
revision = document.get('projection_revision')
|
||
if type(revision) is not int or revision < 0 or timestamp(document['projected_at']) > at + timedelta(seconds=60):
|
||
raise ValueError('查询修订时间无效')
|
||
groups = document.get('groups', [])
|
||
if len(groups) != 1 or groups[0].get('subject_type') != 'MARKET' or groups[0].get('subject_id') != 'BROAD_ETF':
|
||
raise ValueError('查询必须为宽基整体')
|
||
members = groups[0].get('members', [])
|
||
if (not members or len(set(members)) != len(members)
|
||
or any(not re.fullmatch(r'\d{6}\.(SH|SZ)', str(code)) for code in members)):
|
||
raise ValueError('查询成分必须为沪深证券')
|
||
rows = document.get('rows')
|
||
if not isinstance(rows, list) or len(rows) > 16:
|
||
raise ValueError('查询窗口数量无效')
|
||
seen = set()
|
||
for row in rows:
|
||
end, start = timestamp(row['window_end']), timestamp(row['window_start'])
|
||
if (row.get('subject_type') != 'MARKET' or row.get('subject_id') != 'BROAD_ETF'
|
||
or row.get('interval_minutes') != 15 or end.date().isoformat() != day
|
||
or row.get('member_count') != len(members)
|
||
or end.strftime('%H:%M') not in SLOTS or end.second or end.microsecond
|
||
or end - start != timedelta(minutes=15) or end in seen):
|
||
raise ValueError('查询窗口不匹配')
|
||
seen.add(end)
|
||
for member in row.get('top_turnover_members', []):
|
||
if not re.fullmatch(r'\d{6}\.(SH|SZ)', str(member.get('ts_code', ''))):
|
||
raise ValueError('查询证券超出沪深范围')
|
||
if end > at and any(row.get(k) is not None for k in ('turnover_yuan', 'direction_balance', 'cumulative_turnover_yuan')):
|
||
raise ValueError('查询包含未来事实')
|
||
return document
|
||
|
||
|
||
def complete(row, kind):
|
||
count = row.get('member_count')
|
||
return (type(count) is int and count > 0
|
||
and row.get(kind + '_member_count') == count
|
||
and number(row.get(kind + '_coverage')) and row[kind + '_coverage'] == 1)
|
||
|
||
|
||
def presentation(document, at):
|
||
"""直接采用上游加权结果。缺失不补零,累计取末窗,不再相加。"""
|
||
day = document['trade_date']
|
||
base = datetime.combine(date.fromisoformat(day), datetime.min.time(), TZ)
|
||
lookup = {timestamp(r['window_end']).strftime('%H:%M'): r for r in document['rows']}
|
||
result, latest = [], None
|
||
for hm in SLOTS:
|
||
end = base.replace(hour=int(hm[:2]), minute=int(hm[3:]))
|
||
row = lookup.get(hm, {}) if end <= at else {}
|
||
amount = row.get('turnover_yuan')
|
||
amount_ok = (row.get('amount_status') == 'COMPLETE' and complete(row, 'amount')
|
||
and number(amount) and amount >= 0)
|
||
value = row.get('direction_balance')
|
||
direction_ok = (row.get('direction_status') == 'OK' and complete(row, 'direction')
|
||
and number(value) and -1 <= value <= 1
|
||
and row.get('direction') in ('BUY', 'SELL', 'MIXED'))
|
||
item = {'start': (end - timedelta(minutes=15)).strftime('%H:%M'), 'end': hm,
|
||
'value': value if direction_ok else None,
|
||
'direction': row.get('direction') if direction_ok else None,
|
||
'amount': amount if amount_ok else None,
|
||
'state': 'ok' if direction_ok else 'pending' if end > at else 'missing'}
|
||
result.append(item)
|
||
# 未来空窗、尚无事实的占位窗不夺走最后实际时间;部分到达的窗必须暴露缺失。
|
||
if row and (row.get('source_windows') and any(w.get('sources') for w in row['source_windows'])
|
||
or amount is not None or value is not None):
|
||
latest = (row, end, amount_ok)
|
||
summary = {'trade_date': day, 'window_end': None, 'cumulative_amount': None}
|
||
if latest:
|
||
row, end, amount_ok = latest
|
||
cumulative = row.get('cumulative_turnover_yuan')
|
||
# latest_facts 的累计值仅在所有前窗金额齐备时有效;方向缺失不掩盖金额。
|
||
prior = [i for i in result if i['end'] <= end.strftime('%H:%M')]
|
||
cumulative_ok = amount_ok and all(i['amount'] is not None for i in prior)
|
||
summary.update(window_end=end.isoformat(), session_closed=end.strftime('%H:%M') == '15:00',
|
||
cumulative_amount=cumulative if cumulative_ok and number(cumulative) and cumulative >= 0 else None)
|
||
return {'summary': summary, 'intraday_series': result,
|
||
'data_version': document['data_version'], 'projected_at': document['projected_at'],
|
||
'projection_revision': document['projection_revision'], 'view': VIEW,
|
||
'trade_instruction': False, 'live_signal_eligibility': False}
|