"""宽基已发布的15分钟市场方向,仅供历史展示,不推算资金净流入。""" from datetime import datetime, timedelta import math from zoneinfo import ZoneInfo TZ = ZoneInfo('Asia/Shanghai') SLOTS = tuple(f'{m // 60:02d}:{m % 60:02d}' for start in (9 * 60 + 30, 13 * 60) for m in range(start + 15, start + 121, 15)) def intraday_series(history, day, at): """午休不占柱;最新修订优先,缺失、未来窗口和真实零值分开。""" try: base = datetime.strptime(day, '%Y-%m-%d').replace(tzinfo=TZ) except (TypeError, ValueError): return [] latest = {} for row in history or []: try: end = datetime.fromisoformat(row['window_end']) published = datetime.fromisoformat(row['published_at']) if end.tzinfo is None or published.tzinfo is None: continue end = end.astimezone(TZ) hm = end.strftime('%H:%M') if (row.get('trade_date') != day or end.date() != base.date() or hm not in SLOTS or end.second or end.microsecond or end > at or published > at): continue rank = (int(row.get('revision', 0)), published) if hm not in latest or rank > latest[hm][0]: latest[hm] = (rank, row) except (KeyError, TypeError, ValueError): continue result = [] for hm in SLOTS: hour, minute = map(int, hm.split(':')) end = base.replace(hour=hour, minute=minute) row = latest.get(hm, (None, {}))[1] scope = (row.get('scopes') or {}).get('WINDOW_15M') or {} block = (row.get('market') or {}).get('WINDOW_15M') or {} value = (block.get('metrics') or {}).get('direction_balance') direction = block.get('direction') valid = (scope.get('quality_eligible') is True and block.get('direction_status') == 'OK' and direction in ('BUY', 'SELL', 'MIXED') and type(value) in (int, float) and math.isfinite(value) and -1 <= value <= 1) result.append({'start': (end - timedelta(minutes=15)).strftime('%H:%M'), 'end': hm, 'value': value if valid else None, 'direction': direction if valid else None, 'state': 'ok' if valid else 'pending' if end > at else 'missing'}) return result