diff --git a/app/repo/macro_repo.py b/app/repo/macro_repo.py index 1e5be75..5536024 100644 --- a/app/repo/macro_repo.py +++ b/app/repo/macro_repo.py @@ -41,6 +41,14 @@ def _loads(v): # ================================================================ 行情源表 (只读) +def latest_published_hedge(): + """现有指标表的最新发布记录,仅用于核对,不替换PMS执行信号。""" + return fetch_one( + 'SELECT id,trade_date,hedge_index,spread,zone,create_time ' + 'FROM gp_stock_fx_hedge_index ORDER BY trade_date DESC,id DESC LIMIT 1', + source="proxy") + + def fetch_hedge_inputs(limit_days: int = 140) -> dict: """股汇对冲指数的三条原始序列, 各取最近 N 条, 返回升序 (ymd, value) 列表。 diff --git a/app/services/macro_service.py b/app/services/macro_service.py index bab6d4f..72cd933 100644 --- a/app/services/macro_service.py +++ b/app/services/macro_service.py @@ -22,6 +22,7 @@ from __future__ import annotations import json import logging +import math import threading import time from datetime import datetime @@ -490,6 +491,25 @@ def gate_state() -> dict: # ================================================================ 页面 +def published_reading() -> dict: + """展示已发布值,读取失败不回填另一口径或把空值当零。""" + out = {"source": "gp_stock_fx_hedge_index", "ready": False} + try: + row = macro_repo.latest_published_hedge() + if not row or row.get("hedge_index") is None: + return {**out, "error": "已发布指数暂无有效记录"} + value = float(row["hedge_index"]) + day = mr.norm_ymd(row.get("trade_date")) + if not day or day > td.ymd() or not math.isfinite(value): + return {**out, "error": "已发布指数日期或数值无效"} + return {**out, "ready": True, "value": value, "data_ymd": day, + "row_id": row["id"], "zone": row.get("zone"), + "recorded_at": str(row.get("create_time") or "")} + except Exception: + logger.exception("已发布股汇指数读取失败") + return {**out, "error": "已发布指数暂时读取失败"} + + def status() -> dict: """面板快照: 各信号的当前值/区域/近 20 日序列/当日建议/最近命令/冷却, 加闸状态。""" p = _params() @@ -502,6 +522,8 @@ def status() -> dict: "signals": []} for key in _enabled_signals(p): item = {"key": key, "label": SIGNALS[key].get("label") or key} + if key == "hedge_fx": + item["published"] = published_reading() try: rows = macro_repo.recent_signals(key, limit=22) except Exception as e: # noqa: BLE001 @@ -517,6 +539,7 @@ def status() -> dict: det = latest.get("detail") or {} item.update({ "ymd": int(latest["trade_date"]), + "data_ymd": det.get("zs_last"), "value": None if latest.get("value") is None else float(latest["value"]), "zone": latest.get("zone"), "note": latest.get("note"), "action": latest.get("action"), "ref_id": latest.get("ref_id"), diff --git a/app/web/static/index.html b/app/web/static/index.html index 38704b6..2534607 100644 --- a/app/web/static/index.html +++ b/app/web/static/index.html @@ -40,6 +40,11 @@ body{margin:0;background:var(--plane);color:var(--ink); .hst.warn{background:var(--warn-weak);color:var(--warn);} .hst.idle{background:rgba(138,136,130,.14);color:var(--ink-2);} .hst.stop{background:var(--stop-weak);color:var(--stop);} +.hst.entry{background:var(--up-weak);color:var(--up);} +.hst.exit{background:var(--down-weak);color:var(--down);} +.hst.missing{background:transparent;color:var(--muted);outline:1px dashed var(--muted);outline-offset:-1px;} +.micro-readings{display:grid;grid-template-columns:1fr auto;gap:5px 18px;margin:8px 0;} +.micro-popover{max-width:min(440px,calc(100vw - 40px));line-height:1.8;} .hd .tbtn{padding:4px 11px;} .hd-menu .car{margin-left:5px;font-size:10px;color:var(--muted);} .hd-menu:focus,.hd-menu:focus-visible{outline:none;} @@ -227,7 +232,10 @@ pre.json{background:var(--surface-2);border:1px solid var(--hair);border-radius: /* 顶栏不许掉成两行: 宽度不够时按重要性从低到高依次收起 (2026-09-18 标签化后阈值下调) */ @media(max-width:1500px){ .hd .ver{display:none;} } @media(max-width:1340px){ .hd .hd-refresh-at{display:none;} } -@media(max-width:1200px){ .hd .hd-macro{display:none;} } +@media(max-width:1350px){ .hd .hd-exec,.hd .hd-tech{display:none;} } +@media(max-width:1100px){ .hd .hd-plan{display:none;} } +@media(max-width:1000px){ .hd{flex-wrap:wrap;} .hd-tags{order:3;flex:1 0 100%;overflow-x:auto;} .hd-tags::-webkit-scrollbar{display:none;} } +@media(max-width:600px){ .hd-tags > .hst:not(.hd-macro):not(.hd-micro){display:none;} .hd .hd-acts{gap:4px;} .hd .tbtn{padding:4px 7px;} } @media(max-width:1100px){ .hd .hd-exec{display:none;} .hd .hd-tech{display:none;} } @media(max-width:1000px){ .hd .hd-buy{display:none;} } @@ -583,17 +591,20 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} - 大盘 {{ mzChipText }} + 大盘 {{ mzChipText }} + + + + 微盘 {{ microChipText }} 下发 {{ dm.mode || '-' }} @@ -4311,15 +4350,50 @@ createApp({ ElementPlus.ElMessage[(d && d.ok) ? 'success' : 'error']((d && d.ok) ? ('已下达 ' + (d.command_id || '')) : ((d && d.error) || '采纳失败')); await Promise.all([loadMacro(), loadCommands()]); } + // 读取执行使用的每日快照;数据失败时清除旧值,不把未知判断显示为未触发。 + const micro = ref({}); + const microSnapshot = computed(() => micro.value.snapshot || {}); + const microSignal = computed(() => microSnapshot.value.signal || {}); + const microState = computed(() => micro.value.state || {}); + const microError = computed(() => { + const v = micro.value, s = microSnapshot.value; + if (v.error) return '微盘指标读取失败:' + v.error; + if (!s.data_date) return '暂无有效微盘快照'; + if (s.effective_date !== String(health.value.now || '').slice(0,10)) return '快照执行日期与今天不一致,等待有效数据'; + if (!s.signal_ready || !microSignal.value.ready) return '微盘信号数据未就绪'; + if (!s.frozen) return '执行快照尚未冻结'; + return ''; + }); + const microReady = computed(() => !microError.value); + const microPhaseText = computed(() => ({original:'主观量化运行',entering_micro:'转入微盘',micro:'微盘运行',returning_original:'转回主观量化'})[micro.value.phase] || '阶段待核实'); + const microModeText = computed(() => ({auto:'自动执行',paper:'纸面模拟',observe:'观察'})[micro.value.mode] || '档位待核实'); + function microNumber(v) { return v == null || !Number.isFinite(Number(v)) ? '—' : Number(v).toFixed(4); } + function microPercent(v) { return v == null || !Number.isFinite(Number(v)) ? '—' : (Number(v)*100).toFixed(2)+'%'; } + const microChipClass = computed(() => !microReady.value ? 'missing' : microSignal.value.high ? 'exit' : (microSignal.value.low || microSignal.value.growth_break) ? 'entry' : 'idle'); + const microChipText = computed(() => { + if (!microReady.value) return '数据待核实'; + const g = microSignal.value; + return microPercent(g.activity_percentile) + ' · ' + (g.high ? '退出信号' : g.low || g.growth_break ? '入场信号' : '未触发'); + }); + async function loadMicro() { + try { + const d = await call('get','/api/rotation'); + micro.value = d && d.ok !== false ? (d.data || d) : {error:(d && d.error) || '接口未返回有效数据'}; + } catch (e) { micro.value = {error:'接口暂不可用'}; } + } + // 首行徽标 (2026-08-19 用户要求由大面板改为首行紧凑显示, 详情进悬浮提示) const mzSig = computed(() => (((macro.value || {}).signals) || [])[0] || null); + const mzPublished = computed(() => (mzSig.value || {}).published || {}); + const mzDifferent = computed(() => mzPublished.value.ready && mzSig.value && mzSig.value.value != null && (mzPublished.value.data_ymd !== mzSig.value.data_ymd || Math.abs(mzPublished.value.value - Number(mzSig.value.value)) > 0.00005)); + function mzDate(v) { const s=String(v || ''); return /^\d{8}$/.test(s) ? s.slice(0,4)+'-'+s.slice(4,6)+'-'+s.slice(6) : '未知'; } const mzAdvicePending = computed(() => { const s = mzSig.value; return !!(s && s.advice && !s.advice.adopted); }); const mzChipCls = computed(() => { const m = macro.value || {}; if (m.enabled === false) return 'idle'; const s = mzSig.value; if (!s) return 'idle'; - if (mzAdvicePending.value || macroGateOn.value || s.zone === 'UNAVAILABLE') return 'warn'; + if (mzDifferent.value || !mzPublished.value.ready || mzAdvicePending.value || macroGateOn.value || s.zone === 'UNAVAILABLE') return 'warn'; return 'ok'; }); const mzChipText = computed(() => { @@ -4329,7 +4403,7 @@ createApp({ if (!s) return '—'; if (s.zone === 'UNAVAILABLE') return '数据不可用'; const v = s.value == null ? '—' : ((s.value > 0 ? '+' : '') + Number(s.value).toFixed(1)); - let t = v + ' ' + mzLabel(s.zone); + let t = mzPublished.value.ready ? Number(mzPublished.value.value).toFixed(1) + (mzDifferent.value ? ' / 计算 ' + v : ' ' + mzLabel(s.zone)) : '发布值待核实 / 计算 ' + v; if (mzAdvicePending.value) t += ' · 有建议'; return t; }); @@ -4391,7 +4465,7 @@ createApp({ // (通道告警对交易员改由 dispatch-mode 里的 channel 兜底, 见 wsc 的注释) (isAdmin.value ? loadWs() : Promise.resolve()), loadStrategies(), loadOpLog(), loadOpenScan(), loadDividend(), loadUpstream(), - loadMacro(), loadTech()]); + loadMacro(), loadMicro(), loadTech()]); await loadNames(); lastRefresh.value = new Date().toTimeString().slice(0, 8); loading.value = false; @@ -4763,7 +4837,7 @@ createApp({ async function refreshLive() { // allSettled: 单个 loader 失败/超时(axios 60s 兜底)不拖累其余与时间戳更新。 await Promise.allSettled([loadOverview(), loadPositions(), loadInstructions(), loadLedger(), - loadProposals(), loadStrategies(), loadOpLog(), loadOpenScan(), loadDividend(), loadUpstream(), loadMacro()]); + loadProposals(), loadStrategies(), loadOpLog(), loadOpenScan(), loadDividend(), loadUpstream(), loadMacro(), loadMicro()]); try { await loadNames(); } catch (e) {} // 用客户端钟, 保证"自动·HH:MM:SS"稳定跳动, 不依赖 /health 的 now。 lastRefresh.value = new Date().toTimeString().slice(0, 8); @@ -5053,7 +5127,8 @@ createApp({ techFeed, techFeedErr, techStanceCls, macro, macroGateOn, macroUnavailable, mzLabel, mzColor, mzBarStyle, loadMacro, macroScan, macroAdopt, - mzSig, mzAdvicePending, mzChipCls, mzChipText, macroChipClick, + microSnapshot, microSignal, microState, microError, microReady, microPhaseText, microModeText, microNumber, microPercent, microChipClass, microChipText, + mzSig, mzPublished, mzDifferent, mzDate, mzAdvicePending, mzChipCls, mzChipText, macroChipClick, showAlerts, alertItems, alertLatest, alertLevelClass, alertGroups, alertStripItems, alertStripCount, alertTotalCount, catShown, toggleCat, ageText, alertRowClass, alertItemsF, levelShown, toggleLevel, sellOpen, toggleSell, levelCount, ALERT_LEVELS, lvLabel, lvClass, alertGridFixed, passLevel, flowText, flowClass, diff --git a/scripts/run_tests.py b/scripts/run_tests.py index d9e1014..a43eddf 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -6,7 +6,7 @@ 包含 (例数按 2026-10-26 隔离回归实跑校正): test_batch49_units.py 持仓分组、同名股票与批次归属、未迁移及缺数展示 (8例) - test_batch48_units.py 策略账本隔离、微盘轮换优先级、真实交易单位及模拟直接启用 (41例) + test_batch48_units.py 策略账本隔离、微盘轮换优先级、真实交易单位、模拟直接启用及市场读数 (44例) test_batch47_units.py 账户资金去重、买入额度与账户展示和策略估值分离 (9 例) test_batch46_units.py 质地排序切换、档位准入、命令分配与白名单优先 (11 例) test_batch45_units.py 父指令总量:回放延迟、部分成交、跨日预留、故障守成与影子模式 (16 例) diff --git a/scripts/test_batch48_units.py b/scripts/test_batch48_units.py index 74a7232..39712a3 100644 --- a/scripts/test_batch48_units.py +++ b/scripts/test_batch48_units.py @@ -269,5 +269,38 @@ class BoundaryTests(unittest.TestCase): self.assertEqual(b.CURRENT.get(),'original') +class MarketReadingsTests(unittest.TestCase): + def test_published_value_and_execution_date_are_not_confused(self): + from app.services import macro_service as ms + from app.repo import macro_repo + row = {'id': 1, 'trade_date': '2026-10-27', 'hedge_index': '-17.8949', 'zone': 'neutral'} + signal = {'trade_date': 20261028, 'value': -20.3242, 'zone': 'COLD', 'action': 'NONE', 'detail': {'zs_last': 20261027}} + params = dict(enabled=True, autonomy='full', signals=['hedge_fx'], hot_th=25., cold_th=-20., exit_band=15., cooldown_tdays=3, trigger_hot='zone_exit', trigger_cold='zone_enter') + with patch.object(ms, '_params', return_value=params), patch.object(ms, 'gate_state', return_value={}), patch.object(ms.td, 'ymd', return_value=20261028), patch.object(macro_repo, 'latest_published_hedge', return_value=row), patch.object(macro_repo, 'recent_signals', return_value=[signal]), patch.object(macro_repo, 'upsert_signal') as write, patch.object(ms.param_store, 'set_param') as set_param: + result = ms.status()['signals'][0] + self.assertEqual((result['value'], result['ymd'], result['data_ymd']), (-20.3242, 20261028, 20261027)) + self.assertEqual(result['published']['value'], -17.8949) + self.assertEqual(result['zone'], 'COLD') + write.assert_not_called();set_param.assert_not_called() + + def test_invalid_published_data_is_not_zero_or_execution_fallback(self): + from app.services import macro_service as ms + from app.repo import macro_repo + for value in (None, 'NaN', 'Infinity'): + with patch.object(macro_repo, 'latest_published_hedge', return_value={'id':1, 'trade_date':'2026-10-27', 'hedge_index':value}), patch.object(ms.td, 'ymd', return_value=20261028): + result = ms.published_reading() + self.assertFalse(result['ready']) + self.assertNotIn('value', result) + with patch.object(macro_repo, 'latest_published_hedge', side_effect=RuntimeError('offline')): + self.assertFalse(ms.published_reading()['ready']) + + def test_published_zero_valid_future_date_invalid(self): + from app.services import macro_service as ms + from app.repo import macro_repo + for day, ready in (('2026-10-27', True), ('2026-10-29', False)): + with patch.object(macro_repo, 'latest_published_hedge', return_value={'id':1, 'trade_date':day, 'hedge_index':0}), patch.object(ms.td, 'ymd', return_value=20261028): + self.assertEqual(ms.published_reading()['ready'], ready) + + if __name__=='__main__': unittest.main()