From 5e9de289669e68c3bed84eb39d4ea115e97bf3a3 Mon Sep 17 00:00:00 2001 From: hmo Date: Thu, 30 Jul 2026 22:26:06 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20sector=5Fctx=E6=97=A5=E6=9C=9F=E5=9B=9E?= =?UTF-8?q?=E6=BA=AF+=E6=8C=89=E9=94=AE=E5=90=88=E5=B9=B6=E2=80=94?= =?UTF-8?q?=E2=80=94snapshot=E6=97=A5=E5=8F=AA=E6=9C=89=E9=83=A8=E5=88=86?= =?UTF-8?q?=E8=A1=8C=E4=B8=9A=E6=97=B6=E5=9B=9E=E9=80=80=E5=8F=96=E6=9D=BF?= =?UTF-8?q?=E5=9D=97=E6=8C=87=E6=95=B0adx,=E4=BF=AE=E5=A4=8D=E7=94=9F?= =?UTF-8?q?=E4=BA=A7=E8=A1=8C=E4=B8=9A=E7=89=9B=E6=9D=A0=E6=9D=86=E4=B8=8D?= =?UTF-8?q?=E8=A7=A6=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- strategy_lab.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/strategy_lab.py b/strategy_lab.py index 0cc355d8..38712c1c 100644 --- a/strategy_lab.py +++ b/strategy_lab.py @@ -546,7 +546,7 @@ def is_hk_code(code): def prepare_sector_context(start_date, end_date): """行业上下文: sector_index_daily(全历史) 提供板块趋势; sector_snapshots(近期) 补充净流入""" - global _SECTOR_CTX, _STOCK_SECTOR + global _SECTOR_CTX, _STOCK_SECTOR, _SECTOR_DATES _SECTOR_CTX, _STOCK_SECTOR = {}, {} conn = sqlite3.connect(DB_PATH) try: @@ -615,6 +615,7 @@ def prepare_sector_context(start_date, end_date): "SELECT code, sector_name, source FROM stock_sectors").fetchall(): if code not in _STOCK_SECTOR and src in ('ths', 'hk_em', 'hk_manual'): _STOCK_SECTOR[code] = sec + _SECTOR_DATES = sorted(_SECTOR_CTX.keys()) finally: conn.close() @@ -624,11 +625,26 @@ def mkt_ctx(date, code=None): return _MKT_CTX_HK.get(date, {}) return _MKT_CTX.get(date, {}) +_SECTOR_DATES = [] # sorted list of dates present in _SECTOR_CTX + def sector_ctx(code, date): sec = _STOCK_SECTOR.get(code) - if not sec: + if not sec or not _SECTOR_DATES: return {} - return _SECTOR_CTX.get(date, {}).get(sec, {}) + import bisect + i = bisect.bisect_right(_SECTOR_DATES, date) - 1 + # 从 <= date 向前回溯,按键合并:snapshot 日期可能只有部分行业/字段, + # 取每个字段最近一次出现的值(inflow/change 来自 snapshot,adx/slope 来自板块指数) + result = {} + while i >= 0: + v = _SECTOR_CTX[_SECTOR_DATES[i]].get(sec) + if v: + for k, val in v.items(): + result.setdefault(k, val) + if 'adx' in result and ('change' in result or 'inflow' in result or 'slope' in result): + break + i -= 1 + return result # ══════════════════════════════════════════════════════