"""The premarket-low-retest study: measure a session, return numbers. The measurement is the whole of this module. There is no document, no template and no HTML: `GET /api/reports/candidates` returns the numbers and the frontend draws them with the app's own components. The study: among the names a filter selects on a session, what a resting limit order at the premarket low did between 09:30 and 16:00, with a real stop and a real exit. The universe is the scanner's: the same filter expression `/api/scan` takes, resolved for the one session and ordered by the expression's own ``sort``. """ from __future__ import annotations import logging import os import threading from dataclasses import dataclass, field from datetime import date as date_cls from datetime import timedelta import numpy as np import pandas as pd from core.infra.data_manager import DataManager from core.infra.session_frame import clock_minute from modules.reports.plan import ( PM_END, PM_START, Trade, TradePlan, build_plan, fill_index, resolve_entry, resolve_trigger, simulate, ) logger = logging.getLogger(__name__) #: How many names a filter may put in the study. The measurement reads a #: one-minute file per name, so the cap is what keeps a study a ten-second read #: rather than a sweep of the whole market. TOP_N = 100 SESSION_START, SESSION_END = "09:30", "16:00" # How many candidates carry a minute path for the frontend to draw. The rest # are listed as numbers only: a path is ~1.4k points, and 24 of them is a page # nobody scrolls through. DEFAULT_PATHS = 8 # One study costs ~10s (it reads ~100 one-minute files), so a handful are kept # in memory: moving back and forth between two dates should not pay that twice. # A study is a pure function of (date, filter, plan, files on disk), so the # filter AND the plan are part of the key -- one date measured under two # filters, or the same filter under two entries, is two studies. An entry only # goes out of date if the minute files are rewritten under us, which the caller # can force with refresh=True. _MEMO: dict[tuple[str, str, str, str, tuple[tuple[str, float, float], ...], float, bool], Study] = {} MEMO_MAX = 8 # `run_study` is dispatched onto SCAN_EXECUTOR (4 workers), so two studies can # be in the memo mutation at once. Eviction is a read-modify-write -- a `len` # check, a `next(iter(...))` over the live dict, a `pop`, and the insert -- and # unsynchronised it raises `KeyError` when both workers pop the same oldest key # and `RuntimeError: dictionary changed size during iteration` when one inserts # while the other iterates. The lock is deliberately NOT held across the study # itself (that is the expensive part and must stay parallel); it covers the memo # and the path rebuild, which both mutate shared state. _MEMO_LOCK = threading.Lock() @dataclass class Candidate: """One name that retested its level, and what happened after. ``entry`` is whatever the plan's entry expression resolved to for this name -- the premarket low by default, but a VWAP, a rolling low or any other level the caller can write, which is why it is not called ``pm_low`` here any more. """ symbol: str day_pct: float gap_pct: float volume_dollar: float entry: float premarket_bars: int touch_time: str touch_low: float session_low: float peak: float peak_time: str best_pct: float mae_pct: float trade: Trade # (minute of day, close) from 04:00 to 16:00, premarket included. Empty # when the caller did not ask for paths. path: list[tuple[int, float]] = field(default_factory=list) @dataclass class Study: session_date: str universe: int evaluated: int no_premarket: list[str] candidates: list[Candidate] reached_target: int minute_files_cached: int plan: TradePlan | None = None #: names the filter selected whose bars were there but whose entry #: expression resolved to no level -- a column that is null on every #: premarket bar, or an expression that does not fit this frame. Kept #: apart from no_premarket because the two have different fixes: one is a #: missing feed, the other is an expression to rewrite. no_level: list[str] = field(default_factory=list) #: true when the session had few minute files on disk, so the run had to #: fetch the rest over the network thin_coverage: bool = False # ── Data ────────────────────────────────────────────────────────────── _GAINER_COLUMNS = [ "symbol", "open", "high", "low", "close", "volume", "gap_pct", "change_pct", "rel_vol", "volume_dollar", ] def has_session(session_date: str) -> bool: """Whether the database holds a daily bar for that session at all. Kept apart from the filter query so "nobody has that date" and "the filter matched nothing" are two different answers, not one empty frame. """ frame = DataManager().query_raising( "select 1 from daily_data where cast(timestamp as date) = cast(? as date) limit 1", [session_date], ) return not frame.empty def session_rows(session_date: str, symbols: list[str]) -> pd.DataFrame: """The daily bar of each named session, in the order *symbols* came in. The order is the ranking the filter asked for, so it is re-imposed here: the database is free to hand the rows back in any order, and the report shows the names the way the sort clause ranked them. The date and the symbols are bound parameters, not an f-string: this is reachable from a query string as well as the CLI, and neither should interpolate a caller-supplied string into SQL. """ if not symbols: return pd.DataFrame(columns=_GAINER_COLUMNS) placeholders = ", ".join("?" for _ in symbols) frame = DataManager().query_raising( f""" select symbol, open, high, low, close, volume, gap_pct, change_pct, rel_vol, volume_dollar from daily_data where cast(timestamp as date) = cast(? as date) and symbol in ({placeholders}) """, [session_date, *symbols], ) if frame.empty: return pd.DataFrame(columns=_GAINER_COLUMNS) frame = frame.loc[:, _GAINER_COLUMNS] ranking = {symbol: position for position, symbol in enumerate(symbols)} frame = frame.assign(_rank=frame["symbol"].map(ranking)) frame = frame.sort_values("_rank", na_position="last") return frame.drop(columns="_rank").reset_index(drop=True) def session_universe( session_date: str, filter_expr: str, dm: DataManager, top_n: int = TOP_N, ) -> pd.DataFrame: """The names *filter_expr* selects on that session, with their daily bars. The expression is resolved by the scanner's own compiler for the single session, so a date filter inside it and a ``sort`` clause both mean here what they mean in the scanner. ``get_candidates`` treats ``end_date`` as exclusive, so the window is closed on the *next* calendar day: passing the session date itself asks for a range that starts where it ends, and answers with no names at all. """ end_exclusive = (date_cls.fromisoformat(session_date) + timedelta(days=1)).isoformat() matches = dm.get_candidates(session_date, filter_expr, 0, end_date=end_exclusive, limit=top_n) if matches.empty: return pd.DataFrame(columns=_GAINER_COLUMNS) return session_rows(session_date, [str(symbol) for symbol in matches["symbol"]]) def _cached_minute_files(gainers: pd.DataFrame, session_date: str, dm: DataManager) -> int: """How many of the universe already had a 1-minute file on disk. A stat per symbol, no file reads: this is what tells the caller whether the run is a second or a minute of network fetch. """ return sum(1 for symbol in gainers["symbol"] if os.path.exists(dm.minute_cache_path(str(symbol), session_date))) def _load_session(dm: DataManager, symbol: str, session_date: str) -> tuple[pd.DataFrame | None, pd.DataFrame | None]: frame = dm.get_minute_data(symbol, session_date) if frame is None or frame.empty: return None, None frame = frame.copy() frame["hhmm"] = pd.DatetimeIndex(frame.index).strftime("%H:%M") frame["minute"] = frame["hhmm"].map(clock_minute) minutes = frame["minute"] premarket = frame.loc[(minutes >= clock_minute(PM_START)) & (minutes < clock_minute(PM_END))] session = frame.loc[(minutes >= clock_minute(SESSION_START)) & (minutes < clock_minute(SESSION_END))] return premarket, session.reset_index(drop=True) def run_study( session_date: str, filter_expr: str, plan: TradePlan | None = None, dm: DataManager | None = None, top_n: int = TOP_N, with_paths: int = DEFAULT_PATHS, refresh: bool = False, ) -> Study: """Measure the names *filter_expr* selects on *session_date* against the level *plan* rests an order on. `with_paths` is how many of the best candidates keep their minute path for the frontend to draw; the rest are returned as numbers only. """ plan = plan or build_plan() key = ( session_date, filter_expr, plan.entry_expr, plan.trigger, tuple((t.label, t.size, t.offset) for t in plan.targets), plan.stop_pct, plan.breakeven, ) if not refresh: with _MEMO_LOCK: memoised = _MEMO.get(key) if memoised is not None: return _with_paths(memoised, with_paths) manager = dm or DataManager() if not has_session(session_date): raise ValueError(f"No daily bars for {session_date}") daily = session_universe(session_date, filter_expr, manager, top_n) if daily.empty: raise ValueError(f"No names matched the filter on {session_date}") cached = _cached_minute_files(daily, session_date, manager) loaded: dict[str, tuple[pd.DataFrame | None, pd.DataFrame]] = {} for symbol in daily["symbol"]: premarket, session = _load_session(manager, str(symbol), session_date) if session is not None and not session.empty: loaded[str(symbol)] = (premarket, session) # The trigger is the same condition on every name's session bars, so it is # resolved once per frame and handed to the fill rather than re-parsed per # candidate. doors: dict[str, np.ndarray | None] = { str(symbol): resolve_trigger(plan.trigger, session) for symbol, (_, session) in loaded.items() } candidates: list[Candidate] = [] no_premarket: list[str] = [] no_level: list[str] = [] for row in daily.to_dict("records"): symbol = str(row["symbol"]) pair = loaded.get(symbol) if pair is None: continue premarket, session = pair if premarket is None or premarket.empty: no_premarket.append(symbol) continue # The level is the plan's own expression read off this name's # premarket, so a name whose expression is undefined there simply has # no order to rest and is not measured. entry = resolve_entry(plan.entry_expr, premarket) if entry is None: no_level.append(symbol) continue # The trigger is resolved once for the session and reused per name: # it is a condition on the bars, not on the name, and every name in a # study shares the same 09:30-16:00 frame. i = fill_index(session, entry, doors.get(symbol)) if i is None: continue lows = session["low"].to_numpy() tail = session.iloc[i:] peak_index = int(tail["high"].to_numpy().argmax()) peak = float(tail["high"].iloc[peak_index]) candidates.append( Candidate( symbol=symbol, day_pct=float(row["change_pct"]) * 100.0, gap_pct=float(row["gap_pct"]) * 100.0 if row.get("gap_pct") is not None else 0.0, volume_dollar=float(row["volume_dollar"] or 0), entry=entry, premarket_bars=len(premarket), touch_time=str(session["hhmm"].iloc[i]), touch_low=float(lows[i]), session_low=float(lows.min()), peak=peak, peak_time=str(session["hhmm"].iloc[i + peak_index]), best_pct=(peak / entry - 1.0) * 100.0, mae_pct=(float(np.min(tail["low"].to_numpy())) / entry - 1.0) * 100.0, trade=simulate(session, i, entry, plan), ) ) # The filter's ranking is the section's ranking: `session_universe` hands # the names back in the order the expression sorted them, and this loop # keeps that order. Ranking the cards by outcome instead would answer a # question nobody asked and bury the names the filter was written for. study = Study( session_date=session_date, universe=len(daily), evaluated=len(loaded) - len(no_premarket) - len(no_level), no_premarket=sorted(no_premarket), no_level=sorted(no_level), candidates=candidates, reached_target=sum(1 for c in candidates if c.trade.reached_target), minute_files_cached=cached, plan=plan, thin_coverage=bool(len(daily)) and cached / len(daily) < 0.5, ) with _MEMO_LOCK: if len(_MEMO) >= MEMO_MAX: _MEMO.pop(next(iter(_MEMO))) _MEMO[key] = study return _with_paths(study, with_paths, loaded) def _with_paths( study: Study, count: int, loaded: dict[str, tuple[pd.DataFrame | None, pd.DataFrame]] | None = None, ) -> Study: """Attach the minute path to the top *count* candidates. Rebuilt from the memo on each call rather than kept, so a caller asking for no paths pays nothing and a caller asking for more gets them. A cold study hands over the frames it already loaded, so the path is not a second read of files it just read. """ if count <= 0: return study # Held by the caller around the whole rebuild: `candidate.path` is mutated # in place on a memoised study, so two concurrent rebuilds would otherwise # hand the same candidates to the frontend mid-write. manager: DataManager | None = None for candidate in study.candidates[:count]: pair = loaded.get(candidate.symbol) if loaded is not None else None if pair is not None: premarket, session = pair else: if manager is None: manager = DataManager() premarket, session = _load_session(manager, candidate.symbol, study.session_date) points: list[tuple[int, float]] = [] for frame in (premarket, session): if frame is not None and not frame.empty: points.extend((int(m), float(c)) for m, c in zip(frame["minute"], frame["close"], strict=True)) candidate.path = sorted(points) return study