Skip to content

API Reference

Auto-generated from docstrings via mkdocstrings.

Data assertions

assertions.py — Hard Data Quality Assertions (v10.4.0, Phase 1).

Intent: institutional systems do not trust data, they verify it. Unlike the soft repair in data_quality.py, these assertions are a HARD gate: a violation raises DataAssertionError and aborts the pipeline. They are pure and offline so CI can run them without network access.

Invariants
  • Each assert_* raises DataAssertionError on violation, returns None on pass.
  • run_assertions returns the list of passed check names; raises on first fail.
  • No I/O. pandas/numpy only.

Dependencies: pandas, numpy, config.

DataAssertionError

Bases: Exception

Raised when a hard data-quality assertion fails. Aborts the pipeline.

Source code in quant/data/assertions.py
24
25
class DataAssertionError(Exception):
    """Raised when a hard data-quality assertion fails. Aborts the pipeline."""

assert_fundamentals_sane(f_data, symbol)

Fail if a profitable company has NaN or negative Debt/Equity.

Intent: profitable firms with missing/negative leverage are a data error, not a signal. ROE > 0 defines "profitable". Invariants: raises DataAssertionError on violation; pure function.

Source code in quant/data/assertions.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def assert_fundamentals_sane(f_data: dict, symbol: str) -> None:
    """Fail if a profitable company has NaN or negative Debt/Equity.

    Intent: profitable firms with missing/negative leverage are a data error, not
    a signal. ROE > 0 defines "profitable".
    Invariants: raises DataAssertionError on violation; pure function.
    """
    if not f_data:
        return
    roe = f_data.get("ROE")
    de = f_data.get("DebtToEquity")
    profitable = roe is not None and np.isfinite(roe) and roe > 0
    if not profitable:
        return
    if de is None or (isinstance(de, float) and not np.isfinite(de)):
        raise DataAssertionError(
            f"[{symbol}] profitable company (ROE={roe}) has NaN Debt/Equity"
        )
    if de < 0:
        raise DataAssertionError(
            f"[{symbol}] profitable company (ROE={roe}) has negative Debt/Equity={de}"
        )

assert_no_duplicate_timestamps(df, symbol)

Fail if (Symbol, Date) or Date has duplicates.

Intent: duplicate timestamps corrupt rolling windows and double-count volume. Invariants: raises DataAssertionError on any duplicate; pure function.

Source code in quant/data/assertions.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def assert_no_duplicate_timestamps(df: pd.DataFrame, symbol: str) -> None:
    """Fail if (Symbol, Date) or Date has duplicates.

    Intent: duplicate timestamps corrupt rolling windows and double-count volume.
    Invariants: raises DataAssertionError on any duplicate; pure function.
    """
    if df is None or df.empty:
        return
    if "Date" in df.columns:
        dups = int(df["Date"].duplicated().sum())
        if dups > 0:
            raise DataAssertionError(
                f"[{symbol}] {dups} duplicate timestamps in market data"
            )
    elif df.index.has_duplicates:
        raise DataAssertionError(f"[{symbol}] duplicate index timestamps")

assert_no_unexplained_drop(df, symbol, max_drop=ASSERT_MAX_DAILY_DROP, split_dates=None)

Fail if Close drops more than max_drop in one day without a split flag.

Intent: a >50% one-day drop is either a split (legitimate, must be flagged) or data corruption. If it is not explained by a known split date, abort. Invariants: raises DataAssertionError on an unexplained drop; pure function.

Source code in quant/data/assertions.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def assert_no_unexplained_drop(
    df: pd.DataFrame,
    symbol: str,
    max_drop: float = ASSERT_MAX_DAILY_DROP,
    split_dates: set | None = None,
) -> None:
    """Fail if Close drops more than max_drop in one day without a split flag.

    Intent: a >50% one-day drop is either a split (legitimate, must be flagged) or
    data corruption. If it is not explained by a known split date, abort.
    Invariants: raises DataAssertionError on an unexplained drop; pure function.
    """
    if df is None or df.empty or "Close" not in df.columns:
        return
    close = df["Close"].astype(float)
    ret = close.pct_change()
    split_dates = split_dates or set()
    dates = df["Date"] if "Date" in df.columns else df.index

    for i in range(1, len(close)):
        r = ret.iloc[i]
        if not np.isfinite(r) or r >= -max_drop:
            continue
        d = pd.Timestamp(dates.iloc[i] if hasattr(dates, "iloc") else dates[i])
        if d in split_dates:
            continue
        raise DataAssertionError(
            f"[{symbol}] {r:.1%} one-day drop on {d.date()} without a split flag"
        )

run_assertions(df, symbol, f_data=None, split_dates=None)

Run the full hard-assertion suite. Returns passed check names.

Intent: single entry point for the pipeline and for CI. Raises DataAssertionError on the first violation. Invariants: returns list of passed check names; pure function (no I/O).

Source code in quant/data/assertions.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def run_assertions(
    df: pd.DataFrame,
    symbol: str,
    f_data: dict | None = None,
    split_dates: set | None = None,
) -> list[str]:
    """Run the full hard-assertion suite. Returns passed check names.

    Intent: single entry point for the pipeline and for CI. Raises
    DataAssertionError on the first violation.
    Invariants: returns list of passed check names; pure function (no I/O).
    """
    passed: list[str] = []
    assert_no_duplicate_timestamps(df, symbol)
    passed.append("no_duplicate_timestamps")
    assert_no_unexplained_drop(df, symbol, split_dates=split_dates)
    passed.append("no_unexplained_drop")
    if f_data is not None:
        assert_fundamentals_sane(f_data, symbol)
        passed.append("fundamentals_sane")
    return passed

copy.py — Central user-facing copy + formatting (v10.5.1, spec 3).

Intent: ONE module holds every user-facing string and every number formatter. Pages import from here so the vocabulary is consistent and the banned-token test (spec 9) can scan a single source. No internal identifiers (run ids, command names, file names, paths, column names, enum values, exit codes) may appear in any string here (P2).

Invariants
  • No emoji, no exclamation marks (P8).
  • Every number carries its unit inline (P10).
  • Pure module: no I/O, no imports from the pipeline.

Dependencies: datetime only.

class_word(instrument_class)

Map an instrument_class enum to its human word.

Source code in quant/ui/copy.py
225
226
227
def class_word(instrument_class: str) -> str:
    """Map an instrument_class enum to its human word."""
    return CLASS_WORDS.get(str(instrument_class).upper(), "Asset")

delta_badge(eur, pct)

The ONE delta badge: (icon, color, text) from the sign of eur (R-P3).

icon/color: up/green, down/red, dot/neutral when |eur| < 0.5. text: "<eur:+.0f> EUR (<pct:+.1f>%)". A non-zero value that rounds to zero is written as a signed "less than" instead: "-<1 EUR" / "+<0.1%" (the pct sign follows eur when eur != 0). Exact zero is "+0 EUR (+0.0%)", so "-0 EUR" and "-0.0%" are unrepresentable.

Source code in quant/ui/copy.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def delta_badge(eur, pct) -> tuple[str, str, str]:
    """The ONE delta badge: ``(icon, color, text)`` from the sign of ``eur`` (R-P3).

    icon/color: up/green, down/red, dot/neutral when ``|eur| < 0.5``.
    text: ``"<eur:+.0f> EUR (<pct:+.1f>%)"``. A non-zero value that rounds to zero
    is written as a signed "less than" instead: ``"-<1 EUR"`` / ``"+<0.1%"`` (the
    pct sign follows ``eur`` when ``eur != 0``). Exact zero is ``"+0 EUR (+0.0%)"``,
    so ``"-0 EUR"`` and ``"-0.0%"`` are unrepresentable.
    """
    e = 0.0 if _is_missing(eur) else float(eur)
    p = 0.0 if _is_missing(pct) else float(pct)
    if e >= 0.5:
        icon, color = _DELTA_UP, _palette.GAIN
    elif e <= -0.5:
        icon, color = _DELTA_DOWN, _palette.LOSS
    else:
        icon, color = _DELTA_FLAT, _palette.TEXT_MUTED
    whole = int(abs(e) + 0.5)  # half away from zero, matching the icon boundary
    if whole == 0:
        eur_txt = "+0" if e == 0 else ("-<1" if e < 0 else "+<1")
    else:
        eur_txt = f"{'-' if e < 0 else '+'}{whole}"
    if round(p, 1) == 0.0:
        sign = e if e != 0 else p
        pct_txt = "+0.0%" if sign == 0 else ("-<0.1%" if sign < 0 else "+<0.1%")
    else:
        pct_txt = f"{p:+.1f}%"
    return icon, color, f"{eur_txt} EUR ({pct_txt})"

fmt_date(value)

Format a date as '13 Sep 2026'.

Source code in quant/ui/copy.py
154
155
156
157
158
159
160
161
162
163
164
165
def fmt_date(value: date | datetime | str | None) -> str:
    """Format a date as '13 Sep 2026'."""
    if _is_missing(value):
        return ""
    if isinstance(value, str):
        try:
            value = datetime.fromisoformat(value)
        except ValueError:
            return value
    if not isinstance(value, date | datetime):
        return ""
    return f"{value.day} {_MONTHS[value.month - 1]} {value.year}"

fmt_eur(value)

Format EUR with two decimals and the unit after the number.

Source code in quant/ui/copy.py
126
127
128
129
130
def fmt_eur(value: float | None) -> str:
    """Format EUR with two decimals and the unit after the number."""
    if value is None:
        return ""
    return f"{value:.2f} EUR"

fmt_eur_whole(value)

Format EUR as a whole number with the unit (v10.7.3, Part 1.12).

Big plaques show whole EUR ("852 EUR"); cents live in the caption line. Tables keep two decimals via fmt_eur.

Source code in quant/ui/copy.py
133
134
135
136
137
138
139
140
141
def fmt_eur_whole(value: float | None) -> str:
    """Format EUR as a whole number with the unit (v10.7.3, Part 1.12).

    Big plaques show whole EUR ("852 EUR"); cents live in the caption line.
    Tables keep two decimals via fmt_eur.
    """
    if value is None:
        return ""
    return f"{value:.0f} EUR"

fmt_time(value)

Format a time as '17:43'.

Source code in quant/ui/copy.py
168
169
170
171
172
173
174
175
176
177
def fmt_time(value: datetime | str | None) -> str:
    """Format a time as '17:43'."""
    if _is_missing(value):
        return ""
    if isinstance(value, str):
        try:
            value = datetime.fromisoformat(value)
        except ValueError:
            return value
    return value.strftime("%H:%M")

fmt_ts(value)

Format a timestamp as '13 Sep 2026, 17:43'.

Source code in quant/ui/copy.py
180
181
182
183
184
def fmt_ts(value: datetime | str | None) -> str:
    """Format a timestamp as '13 Sep 2026, 17:43'."""
    if value is None:
        return ""
    return f"{fmt_date(value)}, {fmt_time(value)}"

invest_remainder_line(amount_eur)

The one neutral remainder line: ' EUR remain(s) at the broker (not tracked).'

Source code in quant/ui/copy.py
317
318
319
320
321
322
323
324
def invest_remainder_line(amount_eur) -> str:
    """The one neutral remainder line: '<X> EUR remain(s) at the broker (not tracked).'"""
    try:
        amount = float(amount_eur)
    except (TypeError, ValueError):
        amount = 0.0
    verb = "remains" if abs(amount - 1.0) < 0.005 else "remain"
    return f"{fmt_eur(amount)} {verb} at the broker (not tracked)."

regime_word(regime)

Map a regime enum to its human word.

Source code in quant/ui/copy.py
230
231
232
def regime_word(regime: str) -> str:
    """Map a regime enum to its human word."""
    return REGIME_WORDS.get(str(regime).lower(), "mixed")

status_word(universe_status)

Map a universe_status enum to its human word.

Source code in quant/ui/copy.py
273
274
275
def status_word(universe_status: str) -> str:
    """Map a universe_status enum to its human word."""
    return STATUS_WORDS.get(str(universe_status).upper(), "Watching")

tier_word(tier)

Map a tier enum to its plain display word (Section 11).

Source code in quant/ui/copy.py
361
362
363
def tier_word(tier: str) -> str:
    """Map a tier enum to its plain display word (Section 11)."""
    return TIER_WORDS.get(str(tier).upper(), "Active (may sell)")

search.py — Instrument search index (v10.5.3, R5).

Intent: resolve a typed query to instruments by display name, name, symbol, ISIN, or keyword tag. "amazon" -> AMZN, "gold" -> the gold family, "world" -> the world ETFs. Labels use the "Name (TICKER)" form with duplicate-paren removal.

Invariants
  • search(records, query, limit) ranks exact symbol/ISIN first.
  • label_for never doubles the parens: "Name (TICKER)" is appended once.
  • Pure over an in-memory list; load_index() reads via a read-only connection.

Dependencies: quant.data.universe_builder (seed), quant.data.database (read path).

discovery_candidates(query, limit=10)

universe_master-only matches for the discovery loop (H3.5, F5).

Source code in quant/ui/search.py
242
243
244
def discovery_candidates(query: str, limit: int = 10) -> list[dict]:
    """universe_master-only matches for the discovery loop (H3.5, F5)."""
    return search(load_universe_index(), query, limit)

label_for(name, symbol)

Return the canonical "Name (TICKER)" label without duplicate parens.

H3.5 (F4): if the BASE ticker (symbol before the first dot) already appears in a paren group inside the name, the name stands alone — appending the symbol would duplicate it ("Global Aero & Def (5J50) (5J50.DE)").

Source code in quant/ui/search.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def label_for(name: str, symbol: str) -> str:
    """Return the canonical "Name (TICKER)" label without duplicate parens.

    H3.5 (F4): if the BASE ticker (symbol before the first dot) already appears
    in a paren group inside the name, the name stands alone — appending the
    symbol would duplicate it ("Global Aero & Def (5J50) (5J50.DE)").
    """
    # B2: never trust the registry value is pre-cleaned; clean at render time.
    name = clean_display_name((name or "").strip(), symbol).strip()
    if not name or name.upper() == (symbol or "").upper():
        return symbol
    if re.search(rf"\({re.escape(symbol)}\)$", name, re.IGNORECASE):
        return name
    base = (symbol or "").split(".")[0]
    if base and re.search(rf"\({re.escape(base)}\)", name, re.IGNORECASE):
        return name
    return f"{name} ({symbol})"

load_index()

Build the search index: static ETF seed + asset_registry + themes.

Corpus = display_name + name + symbol + ISIN + themes, all substring and case-insensitive (H3.4).

Source code in quant/ui/search.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def load_index() -> list[dict]:
    """Build the search index: static ETF seed + asset_registry + themes.

    Corpus = display_name + name + symbol + ISIN + themes, all substring and
    case-insensitive (H3.4).
    """
    try:
        sym_themes = symbol_themes(load_themes())
    except Exception:  # noqa: BLE001
        sym_themes = {}
    records = {r["symbol"]: r for r in _static_seed(sym_themes)}
    try:
        from quant.data.database import read_only_connection

        with read_only_connection() as conn:
            rows = conn.execute(
                "SELECT symbol, COALESCE(display_name, name) AS nm, isin "
                "FROM asset_registry"
            ).fetchall()
        for sym, nm, isin in rows:
            s = (sym or "").strip().upper()
            if not s:
                continue
            records[s] = _record(s, nm or s, isin or "", TAG_KEYWORDS.get(s),
                                 nm or s, sym_themes.get(s))
    except Exception:  # noqa: BLE001
        pass
    return list(records.values())

load_themes(path=None)

Load data/themes.csv -> {theme: [tokens]}. Tokens are symbols or themes.

Themes are prose tags (H3.4), not identifiers (F1 does not apply). A token that names another theme links to it (theme-to-theme). The symbols column is an UNQUOTED comma list (per the file format), so parse on the FIRST comma (pandas would mis-split the 2-column layout). Best-effort.

Source code in quant/ui/search.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def load_themes(path: str | None = None) -> dict[str, list[str]]:
    """Load data/themes.csv -> {theme: [tokens]}. Tokens are symbols or themes.

    Themes are prose tags (H3.4), not identifiers (F1 does not apply). A token
    that names another theme links to it (theme-to-theme). The symbols column is
    an UNQUOTED comma list (per the file format), so parse on the FIRST comma
    (pandas would mis-split the 2-column layout). Best-effort.
    """
    path = path or THEMES_PATH
    if not os.path.exists(path):
        return {}
    out: dict[str, list[str]] = {}
    try:
        with open(path, encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#") or "," not in line:
                    continue
                theme, rest = line.split(",", 1)
                theme = theme.strip().lower()
                if not theme or theme == "theme":      # skip the header row
                    continue
                toks = [t.strip() for t in rest.split(",") if t.strip()]
                if toks:
                    out[theme] = toks
    except Exception:  # noqa: BLE001
        return {}
    return out

load_universe_index()

universe_master records NOT already in the working universe (H3.5, F5).

These are discovery-pool instruments a user may choose to track. They are NOT in asset_registry; selecting one adds a held row that enters W on save.

Source code in quant/ui/search.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def load_universe_index() -> list[dict]:
    """universe_master records NOT already in the working universe (H3.5, F5).

    These are discovery-pool instruments a user may choose to track. They are
    NOT in asset_registry; selecting one adds a held row that enters W on save.
    """
    try:
        from quant.data.database import read_only_connection

        with read_only_connection() as conn:
            w = {str(r[0]).strip().upper()
                 for r in conn.execute("SELECT symbol FROM asset_registry").fetchall()
                 if r[0]}
            rows = conn.execute("SELECT symbol, name FROM universe_master").fetchall()
    except Exception:  # noqa: BLE001
        return []
    # H3.8 (M5): prefer real longNames (cache) so a company query ("apple")
    # resolves to a discovery symbol, not just the symbol itself.
    try:
        from quant.data.names import read_universe_names

        names = read_universe_names()
    except Exception:  # noqa: BLE001
        names = {}
    out: list[dict] = []
    for sym, nm in rows:
        s = (sym or "").strip().upper()
        if not s or s in w:
            continue
        nm = (names.get(s) or nm or s).strip()
        out.append(_record(s, nm, display_name=nm))
    return out

resolve(query, limit=10)

Convenience: search the live index.

Source code in quant/ui/search.py
247
248
249
def resolve(query: str, limit: int = 10) -> list[dict]:
    """Convenience: search the live index."""
    return search(load_index(), query, limit)

resolve_theme_symbols(themes)

Resolve each theme to its symbol set (recursive; cycle-safe).

Source code in quant/ui/search.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def resolve_theme_symbols(themes: dict[str, list[str]]) -> dict[str, set[str]]:
    """Resolve each theme to its symbol set (recursive; cycle-safe)."""
    cache: dict[str, set[str]] = {}

    def _resolve(name: str, seen: frozenset[str]) -> set[str]:
        if name in cache:
            return cache[name]
        if name in seen:
            return set()
        out: set[str] = set()
        for tok in themes.get(name, []):
            low = tok.strip().lower()
            if low in themes:
                out |= _resolve(low, seen | {name})
            else:
                out.add(tok.strip().upper())
        cache[name] = out
        return out

    for name in themes:
        _resolve(name, frozenset())
    return cache

search(records, query, limit=10)

Rank records against a query. Returns the top limit matches.

Source code in quant/ui/search.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def search(records: list[dict], query: str, limit: int = 10) -> list[dict]:
    """Rank records against a query. Returns the top ``limit`` matches."""
    q = (query or "").strip().lower()
    if not q:
        return []

    scored: list[tuple[float, dict]] = []
    for r in records:
        sym = r["symbol"].lower()
        nm = r["name"].lower()
        dn = str(r.get("display_name") or r["name"]).lower()
        isin = r["isin"].lower()
        score = 0.0
        if q == sym or (isin and q == isin):
            score = 100.0
        elif q in dn or q in nm:
            score = 60.0
        elif q in sym:
            score = 50.0
        else:
            for kw in r.get("keywords", []):
                if q in kw:
                    score = 40.0
                    break
        if score == 0.0:
            tokens = [t for t in q.replace("-", " ").split() if t]
            text = f"{sym} {nm} {dn} {' '.join(r.get('keywords', []))}"
            if tokens and all(t in text for t in tokens):
                score = 20.0
        if score > 0:
            label = label_for(r.get("display_name") or r["name"], r["symbol"])
            scored.append((score, {**r, "score": score, "label": label}))

    scored.sort(key=lambda x: (-x[0], x[1]["symbol"]))
    return [rec for _, rec in scored[:limit]]

symbol_themes(themes)

Inverse map: symbol -> set of theme names that (transitively) include it.

Source code in quant/ui/search.py
109
110
111
112
113
114
115
def symbol_themes(themes: dict[str, list[str]]) -> dict[str, set[str]]:
    """Inverse map: symbol -> set of theme names that (transitively) include it."""
    inv: dict[str, set[str]] = {}
    for theme, syms in resolve_theme_symbols(themes).items():
        for s in syms:
            inv.setdefault(s.upper(), set()).add(theme)
    return inv

cards.py — streamlit-free card field resolution (H3.5).

Intent: ONE helper computes the Explore card's title/class/subtitle so the page and the doctor probe read the SAME fields — F1-F3 become diagnosable forever and can never diverge (decision-memo style: one source).

Invariants
  • name/class/currency/ISIN prefer asset_registry (the working universe).
  • The CSV routing metadata (broker_registry.csv) is the FALLBACK only.
  • Never raises; missing cells degrade to the symbol / empty string.

Dependencies: quant.data.database (read path), quant.execution.taxonomy, quant.ui.copy (pure).

explore_card_fields(symbol)

Resolve the Explore card fields for symbol (H3.5, F1-F3).

Returns: symbol, name, class, class_word, currency, isin, subtitle, isin_source. Registry values win; CSV routing metadata is the fallback.

Source code in quant/ui/cards.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def explore_card_fields(symbol: str) -> dict:
    """Resolve the Explore card fields for ``symbol`` (H3.5, F1-F3).

    Returns: symbol, name, class, class_word, currency, isin, subtitle,
    isin_source. Registry values win; CSV routing metadata is the fallback.
    """
    row = None
    try:
        with read_only_connection() as conn:
            row = conn.execute(
                "SELECT COALESCE(display_name, name) AS nm, instrument_class, "
                "currency, isin FROM asset_registry WHERE symbol = ?", [symbol]
            ).fetchone()
    except Exception:  # noqa: BLE001
        row = None

    # F-series (bug 4): has_details distinguishes a real registry row from a
    # bare-symbol fallback, so the page can render an honest empty state instead
    # of showing the ticker as if it were a name.
    has_details = bool(row)
    nm = (row[0] if row and row[0] else "")
    cls = (row[1] if row and row[1] else "") or classify_instrument(symbol)
    reg_cur = (row[2] if row and row[2] else "")
    reg_isin = (row[3] if row and row[3] else "")
    broker = resolve_broker(symbol)

    currency = reg_cur or broker.get("currency", "")
    isin = reg_isin or broker.get("isin", "")
    name = nm or symbol
    word = class_word(cls)
    subtitle = " · ".join(p for p in (word, currency, isin) if p)
    return {
        "symbol": symbol,
        "name": name,
        "class": cls,
        "class_word": word,
        "currency": currency,
        "isin": isin,
        "subtitle": subtitle,
        "isin_source": broker.get("isin_source", ""),
        "has_details": has_details,
    }

Reporting artifacts (the UI accessors)

artifacts.py — the read helpers the pages use, plus the per-run log directory.

Reads: the regime estimate, a symbol's score row, the valuation store (portfolio_total), the value series and the chart math (day delta, growth view, value hover, tick dates). new_run_dir creates the outputs/run_<ts>/ folder for a run's pipeline.log. Never raise.

Point

Bases: NamedTuple

One chart point: a date and its value (normalized in the Growth view).

Source code in quant/reporting/artifacts.py
186
187
188
189
190
class Point(NamedTuple):
    """One chart point: a date and its value (normalized in the Growth view)."""

    date: date
    value: float

chart_tick_dates(dates, max_ticks=6)

Unique, evenly sampled X-axis tick dates (v10.8.6, B5). Pure.

Deduplicates and limits to max_ticks evenly spaced entries. The renderer uses these as tickvals so the axis can never show a duplicate date.

Source code in quant/reporting/artifacts.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def chart_tick_dates(dates, max_ticks: int = 6) -> list[date]:
    """Unique, evenly sampled X-axis tick dates (v10.8.6, B5). Pure.

    Deduplicates and limits to ``max_ticks`` evenly spaced entries. The renderer
    uses these as ``tickvals`` so the axis can never show a duplicate date.
    """
    seen: list[date] = []
    for d in dates or []:
        c = _coerce_date(d)
        if c is not None and c not in seen:
            seen.append(c)
    unique = sorted(seen)
    if len(unique) <= max_ticks:
        return unique
    step = max(1, len(unique) // max_ticks)
    return unique[::step]

compute_day_delta(series, as_of=None)

The day change from a portfolio-total series (v10.8.6, B6).

series is [{date, value_eur}, ...]; the total is the invested value only (v10.8.7, R-C1). Returns (delta_eur, delta_pct) = total(D) - total(D-1) where D is as_of (default: the last point). No forward-fill, no fallback. Pure.

Source code in quant/reporting/artifacts.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def compute_day_delta(series, as_of=None) -> tuple[float, float]:
    """The day change from a portfolio-total series (v10.8.6, B6).

    ``series`` is ``[{date, value_eur}, ...]``; the total is the invested value
    only (v10.8.7, R-C1). Returns ``(delta_eur, delta_pct)`` =
    ``total(D) - total(D-1)`` where D is ``as_of`` (default: the last point). No
    forward-fill, no fallback. Pure.
    """
    pts: list[tuple[date, float]] = []
    for row in series or []:
        d = _coerce_date(row.get("date"))
        if d is None:
            continue
        total = float(row.get("value_eur") or 0)
        pts.append((d, total))
    pts.sort(key=lambda t: t[0])
    if len(pts) < 2:
        return 0.0, 0.0
    idx = len(pts) - 1
    if as_of is not None:
        target = _coerce_date(as_of)
        earlier = [i for i, (d, _t) in enumerate(pts) if target is not None and d <= target]
        if not earlier:
            return 0.0, 0.0
        idx = earlier[-1]
    if idx <= 0:
        return 0.0, 0.0
    prev = pts[idx - 1][1]
    today = pts[idx][1]
    delta = round(today - prev, 2)
    pct = (today / prev - 1.0) * 100.0 if prev else 0.0
    return delta, pct

compute_growth_view(portfolio, per_symbol, held_symbols)

Normalized-to-100 series per line for the Growth view (v10.8.6, B3/5).

portfolio is [{date, value_eur}, ...]; per_symbol is {symbol: [{date, value_eur}, ...]}; held_symbols are the lines to draw. Returns {"portfolio": [Point, ...], <sym>: [Point, ...]}, each rebased to 100 at its first point. Pure.

Source code in quant/reporting/artifacts.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def compute_growth_view(portfolio, per_symbol: dict, held_symbols) -> dict:
    """Normalized-to-100 series per line for the Growth view (v10.8.6, B3/5).

    ``portfolio`` is ``[{date, value_eur}, ...]``; ``per_symbol`` is
    ``{symbol: [{date, value_eur}, ...]}``; ``held_symbols`` are the lines to draw.
    Returns ``{"portfolio": [Point, ...], <sym>: [Point, ...]}``, each rebased to
    100 at its first point. Pure.
    """
    out: dict = {"portfolio": _normalize_100(portfolio)}
    for sym in held_symbols or []:
        pts = _normalize_100((per_symbol or {}).get(sym))
        if pts:
            out[str(sym)] = pts
    return out

compute_value_view_hover(as_of, portfolio, per_symbol, held_symbols)

The Value-view hover payload for as_of (v10.8.6, B3/6; v10.8.7, R-C1).

Returns {"total": <invested sum>, <sym>: <value>, ...} where the symbol values sum to the invested total. Cash is not an entity (R-C1), so there is no cash key. Only stored values are used (no forward-fill). Pure.

Source code in quant/reporting/artifacts.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def compute_value_view_hover(as_of, portfolio, per_symbol: dict,
                             held_symbols) -> dict:
    """The Value-view hover payload for ``as_of`` (v10.8.6, B3/6; v10.8.7, R-C1).

    Returns ``{"total": <invested sum>, <sym>: <value>, ...}`` where the symbol
    values sum to the invested total. Cash is not an entity (R-C1), so there is no
    cash key. Only stored values are used (no forward-fill). Pure.
    """
    day = _coerce_date(as_of)
    out: dict = {}
    for sym in held_symbols or []:
        v = _value_at((per_symbol or {}).get(sym), day)
        if v is not None:
            out[str(sym)] = round(float(v), 2)
    out["total"] = round(sum(out.values()), 2)
    return out

format_chart_ticks(dates, max_ticks=6)

Unique, readable X-axis labels, evenly sampled (v10.8.6, B5).

Deduplicates, limits to max_ticks evenly spaced entries, and formats each as DD Mon. Pure.

Source code in quant/reporting/artifacts.py
236
237
238
239
240
241
242
def format_chart_ticks(dates, max_ticks: int = 6) -> list[str]:
    """Unique, readable X-axis labels, evenly sampled (v10.8.6, B5).

    Deduplicates, limits to ``max_ticks`` evenly spaced entries, and formats each
    as ``DD Mon``. Pure.
    """
    return [d.strftime("%d %b") for d in chart_tick_dates(dates, max_ticks)]

new_run_dir()

Create and return outputs/run_/.

Invariant (v10.5.0): idempotent per process. The first call creates the directory; later calls return the same path so one run writes all artifacts (factor scores, telemetry, pipeline.log, web/) into a single dir. Before v10.5.0 each call minted a new timestamped dir, scattering one run's output.

Source code in quant/reporting/artifacts.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def new_run_dir() -> str:
    """Create and return outputs/run_<YYYY-MM-DD_HHMMSS>/.

    Invariant (v10.5.0): idempotent per process. The first call creates the
    directory; later calls return the same path so one run writes all artifacts
    (factor scores, telemetry, pipeline.log, web/) into a single dir. Before
    v10.5.0 each call minted a new timestamped dir, scattering one run's output.
    """
    global _RUN_DIR
    if _RUN_DIR is not None:
        return _RUN_DIR
    ts = datetime.now().strftime("%Y-%m-%d_%H%M%S")
    path = os.path.join(OUTPUTS_DIR, f"run_{ts}")
    os.makedirs(path, exist_ok=True)
    _RUN_DIR = path
    return path

read_portfolio_total()

The daily portfolio total from the valuation store (v10.8.4, T1).

The single source for the home chart and the day delta. Columns date and value_eur (invested only; v10.8.7, R-C1); empty when nothing is stored. Never raises.

Source code in quant/reporting/artifacts.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def read_portfolio_total() -> pd.DataFrame:
    """The daily portfolio total from the valuation store (v10.8.4, T1).

    The single source for the home chart and the day delta. Columns ``date`` and
    ``value_eur`` (invested only; v10.8.7, R-C1); empty when nothing is stored.
    Never raises.
    """
    empty = pd.DataFrame(columns=["date", "value_eur"])
    try:
        from quant.engine import mtm

        series = mtm.read_total_series()
    except Exception:  # noqa: BLE001
        return empty
    if not series:
        return empty
    return pd.DataFrame(series)

read_regime()

The market regime stored by the analysis chain; neutral default when absent.

Label: bull / bear / chop (consumers normalise with :func:quant.portfolio.regime_constraints.regime_key).

Source code in quant/reporting/artifacts.py
76
77
78
79
80
81
82
83
def read_regime() -> dict:
    """The market regime stored by the analysis chain; neutral default when absent.

    Label: bull / bear / chop (consumers normalise with
    :func:`quant.portfolio.regime_constraints.regime_key`).
    """
    stored = _analysis_regime()
    return {**_REGIME_DEFAULT, **stored} if stored else dict(_REGIME_DEFAULT)

read_score_row(symbol)

The full score row for a symbol from the scores store (v10.8.7, T2).

Returns {composite, confidence, structural_grade, tactical_grade, sentiment, stewardship, present, total}; empty when nothing is stored.

Source code in quant/reporting/artifacts.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def read_score_row(symbol: str) -> dict:
    """The full score row for a symbol from the ``scores`` store (v10.8.7, T2).

    Returns ``{composite, confidence, structural_grade, tactical_grade,
    sentiment, stewardship, present, total}``; empty when nothing is stored.
    """
    try:
        from quant.data.database import read_only_connection

        with read_only_connection() as conn:
            res = conn.execute(
                "SELECT composite, confidence, structural_grade, tactical_grade, "
                "sentiment, stewardship, present_components, total_components "
                "FROM scores WHERE symbol = ?", [symbol]).fetchone()
    except Exception:  # noqa: BLE001
        return {}
    if not res:
        return {}
    return {
        "composite": res[0], "confidence": str(res[1] or "low"),
        "structural_grade": res[2], "tactical_grade": res[3],
        "sentiment": res[4], "stewardship": res[5],
        "present": int(res[6] or 0), "total": int(res[7] or 0),
    }

read_value_series()

The daily invested-value series (v10.8.0; store v10.8.4, T1).

Reads the mark-to-market portfolio_total store (the single source) and falls back to the legacy snapshot+flow builder only when the store is empty, so a pre-v10.8.4 database still charts. Independent of reviews. Returns a frame with columns date and value_eur (empty when there is no data). Never raises.

Source code in quant/reporting/artifacts.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def read_value_series() -> pd.DataFrame:
    """The daily invested-value series (v10.8.0; store v10.8.4, T1).

    Reads the mark-to-market ``portfolio_total`` store (the single source) and
    falls back to the legacy snapshot+flow builder only when the store is empty,
    so a pre-v10.8.4 database still charts. Independent of reviews. Returns a
    frame with columns ``date`` and ``value_eur`` (empty when there is no data).
    Never raises.
    """
    store = read_portfolio_total()
    if not store.empty:
        return store[["date", "value_eur"]].copy()

    from quant.data.currency import get_fx_to_eur
    from quant.data.database import read_only_connection
    from quant.engine.value_series import build_value_series

    empty = pd.DataFrame(columns=["date", "value_eur"])
    try:
        with read_only_connection() as conn:
            snaps = conn.execute(
                "SELECT snapshot_date, symbol, shares FROM position_snapshots"
            ).fetchall()
            flows = conn.execute(
                "SELECT date, type, amount_eur, symbol FROM flows"
            ).fetchall()
            symbols = {str(s[1]) for s in snaps}
            closes: dict = {}
            if symbols:
                placeholders = ",".join("?" for _ in symbols)
                rows = conn.execute(
                    f"SELECT Symbol, Date, Close FROM market_history "
                    f"WHERE Symbol IN ({placeholders})", list(symbols)).fetchall()
                closes = {(str(r[0]), str(r[1])[:10]): float(r[2])
                          for r in rows if r[2] is not None}
    except Exception:  # noqa: BLE001
        return empty

    snap_dicts = [{"date": s[0], "symbol": s[1], "shares": s[2]} for s in snaps]
    flow_dicts = [{"date": f[0], "type": f[1], "amount_eur": f[2], "symbol": f[3]}
                  for f in flows]
    fx = {sym: get_fx_to_eur(sym) for sym in symbols}
    series = build_value_series(snap_dicts, flow_dicts, closes, fx)
    if not series:
        return empty
    return pd.DataFrame(series)

Data: names, registry repair, news, currency

names.py — Display-name cleaning + backfill (v10.5.3, R5).

Intent: one home for the friendly-name pipeline. Fill order: curated (data/names_curated.csv) > cleaned Yahoo longName > symbol. Clean rules drop boilerplate tokens; an empty result falls back to the symbol. Backfill fills MISSING cells only and never overwrites curated/existing values.

Invariants
  • clean_display_name never returns empty (falls back to the symbol).
  • backfill_display_names is idempotent and missing-cells-only.
  • Cleaning is pure (no I/O); backfill touches only the rows it reads.

Dependencies: pandas, re, quant.paths.

backfill_display_names(conn, metadata_source=None, curated_path=None, fill_currency=False)

Fill MISSING display_name / name / currency cells. Returns a summary.

metadata_source is injectable (returns (long_name, currency)) for hermetic tests. Curated values are never overwritten; existing cells are left alone.

Source code in quant/data/names.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def backfill_display_names(conn: Any, metadata_source: Any =None, curated_path: str | None = None,
                           fill_currency: bool = False) -> dict:
    """Fill MISSING display_name / name / currency cells. Returns a summary.

    ``metadata_source`` is injectable (returns (long_name, currency)) for hermetic
    tests. Curated values are never overwritten; existing cells are left alone.
    """
    metadata_source = metadata_source or _yahoo_identity
    curated = load_curated_names(curated_path)
    rows = conn.execute(
        "SELECT symbol, display_name, name, currency FROM asset_registry"
    ).fetchall()
    d_fill = n_fill = c_fill = 0
    unreachable = 0
    for sym, dn, nm, cur in rows:
        sym = str(sym or "")
        if not sym:
            continue
        need_dn = _symbolish(dn, sym)
        need_nm = _symbolish(nm, sym)
        need_cur = _blank(cur)
        if not (need_dn or need_nm or need_cur):
            continue
        long_name, meta_cur = "", ""
        need_meta = (sym not in curated) and _symbolish(nm, sym)
        if need_dn or need_nm or need_cur:
            if sym in curated:
                long_name = curated[sym]
            elif not _symbolish(nm, sym):
                # Reuse whatever real name we already have before the network.
                long_name = str(nm)
        if need_meta:
            long_name, meta_cur = metadata_source(sym)
            if not long_name:
                unreachable += 1
        if need_dn:
            conn.execute("UPDATE asset_registry SET display_name = ? WHERE symbol = ?",
                         [clean_display_name(long_name, sym), sym])
            d_fill += 1
        if need_nm and long_name:
            conn.execute("UPDATE asset_registry SET name = ? WHERE symbol = ?",
                         [long_name, sym])
            n_fill += 1
        if need_cur and meta_cur and fill_currency:
            conn.execute("UPDATE asset_registry SET currency = ? WHERE symbol = ?",
                         [meta_cur, sym])
            c_fill += 1
    return {"display_filled": d_fill, "name_filled": n_fill,
            "currency_filled": c_fill, "unreachable": unreachable}

backfill_universe_names(conn=None, limit=200, source=None)

Fill universe_master.name with real longNames (H3.8, M5).

Bounded per call and cached in outputs/universe_names.json, so repeated updates progress without refetching. Only symbol-valued/empty cells change.

Source code in quant/data/names.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def backfill_universe_names(conn: Any =None, limit: int = 200, source: Any =None) -> dict:
    """Fill universe_master.name with real longNames (H3.8, M5).

    Bounded per call and cached in outputs/universe_names.json, so repeated
    updates progress without refetching. Only symbol-valued/empty cells change.
    """
    source = source or _yahoo_identity
    if conn is None:
        from quant.data.database import get_connection

        conn = get_connection()
    cache = read_universe_names()
    try:
        rows = conn.execute(
            "SELECT symbol, name FROM universe_master "
            "WHERE name IS NULL OR trim(name) = '' OR upper(name) = upper(symbol)"
        ).fetchall()
    except Exception:  # noqa: BLE001
        return {"filled": 0, "remaining": 0}
    filled = 0
    for sym, _nm in rows[:limit]:
        s = str(sym or "").strip()
        if not s:
            continue
        long_name = cache.get(s, "")
        if not long_name:
            long_name, _cur = source(s)
            long_name = str(long_name or "").strip()
            if long_name:
                cache[s] = long_name
        if long_name and long_name.upper() != s.upper():
            conn.execute("UPDATE universe_master SET name = ? WHERE symbol = ?",
                         [long_name, s])
            filled += 1
    _write_universe_names(cache)
    return {"filled": filled, "remaining": max(0, len(rows) - limit)}

clean_display_name(long_name, symbol)

Clean a Yahoo longName into a short display name. Never empty.

Source code in quant/data/names.py
31
32
33
34
35
36
37
38
39
def clean_display_name(long_name: str | None, symbol: str) -> str:
    """Clean a Yahoo longName into a short display name. Never empty."""
    if long_name is None or str(long_name).strip() == "":
        return symbol
    s = _PAREN.sub(" ", str(long_name))
    for tok in _BOILERPLATE:
        s = re.sub(rf"(?i)\b{re.escape(tok)}\b", " ", s)
    s = re.sub(r"\s+", " ", s).strip(" -,.:")
    return s or symbol

display_name(symbol, allow_probe=False)

Resolve a friendly company name for symbol (never empty for a symbol).

Invariants: a value equal to the symbol carries no information and is treated as missing; the fallback is the symbol itself.

Source code in quant/data/names.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def display_name(symbol: str, allow_probe: bool = False) -> str:
    """Resolve a friendly company name for ``symbol`` (never empty for a symbol).

    Invariants: a value equal to the symbol carries no information and is
    treated as missing; the fallback is the symbol itself.
    """
    sym = str(symbol or "").strip()
    if not sym:
        return ""
    # 1. registry display_name / name (the working universe).
    try:
        from quant.data.database import read_only_connection

        with read_only_connection() as conn:
            row = conn.execute(
                "SELECT COALESCE(display_name, name) FROM asset_registry "
                "WHERE symbol = ?", [sym]).fetchone()
        if row and row[0] and not _symbolish(row[0], sym):
            return clean_display_name(str(row[0]), sym)
    except Exception:  # noqa: BLE001
        pass
    # 2. cached probe (written once by the daily run).
    cache = read_universe_names()
    cached = cache.get(sym)
    if cached and not _symbolish(cached, sym):
        return clean_display_name(str(cached), sym)
    # 3. probe once, only when explicitly allowed (daily run).
    if allow_probe:
        long_name, _cur = _yahoo_identity(sym)
        long_name = str(long_name or "").strip()
        if long_name and not _symbolish(long_name, sym):
            cache[sym] = long_name
            _write_universe_names(cache)
            return clean_display_name(long_name, sym)
    return sym

ensure_display_names()

Startup backfill: migrate + fill missing names. Never raises.

v10.8.7 (T5/R-C4): runs once per process (the caller guards it), with bounded retry + exponential backoff. On final failure: ONE quiet log line and a names stage stale flag in run_manifest. No stdout spam, no writes during reruns. Idempotent: missing cells only.

Source code in quant/data/names.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def ensure_display_names() -> dict:
    """Startup backfill: migrate + fill missing names. Never raises.

    v10.8.7 (T5/R-C4): runs once per process (the caller guards it), with bounded
    retry + exponential backoff. On final failure: ONE quiet log line and a
    ``names`` stage ``stale`` flag in run_manifest. No stdout spam, no writes
    during reruns. Idempotent: missing cells only.
    """
    try:
        from quant.data.database import (
            connect_with_retry,
            migrate_registry_display_name,
        )
    except Exception:  # noqa: BLE001
        return {}
    conn = None
    try:
        conn = connect_with_retry(attempts=3, delay=0.5)
    except Exception as e:  # noqa: BLE001
        # Lock held (another app instance / update running): skip for this
        # process; the app still starts. Retried on the next start/update.
        import logging

        logging.getLogger("quant.ui").warning(
            "Display names backfill skipped: database busy.")
        _mark_names_stale(e)
        _write_names_state({"ts": time.time(), "rows_total": 0, "filled": 0,
                            "still_missing": 0, "skipped_reason": "lock",
                            "unreachable_symbols": 0})
        return {"skipped_reason": "lock"}
    try:
        migrate_registry_display_name(conn)
        summary = backfill_display_names(conn, fill_currency=False)
        try:
            rows_total = conn.execute("SELECT COUNT(*) FROM asset_registry").fetchone()[0]
            still_missing = conn.execute(
                "SELECT COUNT(*) FROM asset_registry "
                "WHERE display_name IS NULL OR trim(display_name) = ''"
            ).fetchone()[0]
        except Exception:  # noqa: BLE001
            rows_total = still_missing = 0
        _write_names_state({
            "ts": time.time(), "rows_total": int(rows_total),
            "filled": summary.get("display_filled", 0),
            "still_missing": int(still_missing),
            "skipped_reason": "metadata_unreachable" if summary.get("unreachable") else None,
            "unreachable_symbols": summary.get("unreachable", 0),
        })
        return summary
    except Exception:  # noqa: BLE001
        return {}
    finally:
        if conn is not None:
            try:
                conn.close()
            except Exception:  # noqa: BLE001
                pass

load_curated_names(path=None)

Load data/names_curated.csv (symbol -> display_name). Curated wins forever.

Source code in quant/data/names.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def load_curated_names(path: str | None = None) -> dict[str, str]:
    """Load data/names_curated.csv (symbol -> display_name). Curated wins forever."""
    import pandas as pd

    path = path or paths.DATA_NAMES_CURATED
    if not os.path.exists(path):
        return {}
    try:
        df = pd.read_csv(path, comment="#")
    except Exception:  # noqa: BLE001
        return {}
    if df.empty or "symbol" not in df.columns or "display_name" not in df.columns:
        return {}
    out: dict[str, str] = {}
    for _, r in df.iterrows():
        sym = str(r.get("symbol", "") or "").strip()
        name = str(r.get("display_name", "") or "").strip()
        if sym and name:
            out[sym] = name
    return out

probe_and_store(symbol, conn=None)

Probe + cache a name and persist it to asset_registry when possible.

Used by the daily run so funnel survivors not yet in the registry (for example MU, SOXX) get a real name and candidate cards never render "MU (MU)". Never raises.

Source code in quant/data/names.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
def probe_and_store(symbol: str, conn: Any =None) -> str:
    """Probe + cache a name and persist it to asset_registry when possible.

    Used by the daily run so funnel survivors not yet in the registry (for
    example MU, SOXX) get a real name and candidate cards never render
    "MU (MU)". Never raises.
    """
    sym = str(symbol or "").strip()
    if not sym:
        return ""
    name = display_name(sym, allow_probe=True)
    if conn is not None and name and name.upper() != sym.upper():
        try:
            conn.execute(
                "UPDATE asset_registry SET display_name = ? WHERE symbol = ?",
                [name, sym])
        except Exception:  # noqa: BLE001
            pass
    return name

probe_metadata(symbol)

Read-only metadata probe for quant doctor (raw longName or the exact error).

Source code in quant/data/names.py
163
164
165
166
167
168
169
170
171
172
173
174
175
def probe_metadata(symbol: str) -> dict:
    """Read-only metadata probe for quant doctor (raw longName or the exact error)."""
    try:
        import yfinance as yf

        info = yf.Ticker(symbol).get_info()
        return {"symbol": symbol,
                "long_name": str(info.get("longName") or info.get("shortName") or ""),
                "currency": str(info.get("currency") or ""),
                "error": None}
    except Exception as e:  # noqa: BLE001
        return {"symbol": symbol, "long_name": "", "currency": "",
                "error": f"{type(e).__name__}: {e}"}

read_names_state()

Read outputs/names_state.json (the last backfill outcome). {} when absent.

Source code in quant/data/names.py
138
139
140
141
142
143
144
145
146
def read_names_state() -> dict:
    """Read outputs/names_state.json (the last backfill outcome). {} when absent."""
    import json

    try:
        with open(_state_path(), encoding="utf-8") as f:
            return json.load(f)
    except Exception:  # noqa: BLE001
        return {}

read_universe_names()

Read outputs/universe_names.json (symbol -> longName). {} when absent.

H3.8 (M5): the discovery index needs real names to match a company query.

Source code in quant/data/names.py
72
73
74
75
76
77
78
79
80
81
82
83
def read_universe_names() -> dict:
    """Read outputs/universe_names.json (symbol -> longName). {} when absent.

    H3.8 (M5): the discovery index needs real names to match a company query.
    """
    import json

    try:
        with open(_universe_names_path(), encoding="utf-8") as f:
            return json.load(f)
    except Exception:  # noqa: BLE001
        return {}

registry_repair.py — Validated ISIN backfill (v10.5.2, A6/F1).

Intent: fill MISSING ISIN cells in data/broker_registry.csv from a source hierarchy — data/isin_curated.csv (user-verified) > existing non-empty cells (never overwritten) > live Yahoo instrument metadata. Every written value passes is_valid_isin; invalid or absent metadata yields "not found", never a guess. Provenance is recorded in the isin_source column (user/curated/yahoo).

Invariants
  • Idempotent: a second run changes nothing.
  • Missing cells only; existing ISINs are never overwritten.
  • No synthesized identifiers (F1): a value is written only if checksum-valid.

Dependencies: pandas, quant.paths, quant.data.identifiers.

heal_registry_isins(conn, symbols=None, *, curated_path=paths.DATA_ISIN_CURATED, metadata_source=None)

Fill missing asset_registry.isin for W rows (H3-fix part 2, spec 3).

Source hierarchy: curated (data/isin_curated.csv) > cache (outputs/isin_cache.json) > live metadata. Every written value passes is_valid_isin (F1). Missing cells only; per-symbol failures stay silent. Idempotent: a filled cell is never refetched.

Source code in quant/data/registry_repair.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def heal_registry_isins(conn: Any, symbols: Any =None, *,
                        curated_path: str = paths.DATA_ISIN_CURATED,
                        metadata_source=None) -> dict:
    """Fill missing asset_registry.isin for W rows (H3-fix part 2, spec 3).

    Source hierarchy: curated (data/isin_curated.csv) > cache
    (outputs/isin_cache.json) > live metadata. Every written value passes
    is_valid_isin (F1). Missing cells only; per-symbol failures stay silent.
    Idempotent: a filled cell is never refetched.
    """
    metadata_source = metadata_source or _yahoo_isin
    cache = _read_isin_cache()
    curated = {str(k).strip().upper(): v for k, v in load_curated(curated_path).items()}
    want = {str(s).strip().upper() for s in symbols} if symbols else None

    rows = conn.execute("SELECT symbol, isin FROM asset_registry").fetchall()
    filled = 0
    not_found = 0
    cache_dirty = False
    for sym, isin in rows:
        sym_u = str(sym or "").strip().upper()
        if not sym_u or (want is not None and sym_u not in want):
            continue
        cur = str(isin or "").strip()
        if cur and cur.lower() != "nan":
            continue
        candidate = curated.get(sym_u)
        if not candidate:
            entry = cache.get(sym_u)
            candidate = entry.get("isin") if isinstance(entry, dict) else entry
        if not candidate:
            candidate = metadata_source(sym_u)
            if candidate:
                cache[sym_u] = {"isin": str(candidate).strip().upper(),
                                "retrieved_at": time.time()}
                cache_dirty = True
        if candidate and is_valid_isin(candidate):
            conn.execute("UPDATE asset_registry SET isin = ? WHERE symbol = ?",
                         [str(candidate).strip().upper(), sym])
            filled += 1
        else:
            not_found += 1
    if cache_dirty:
        _write_isin_cache(cache)
    return {"filled": filled, "not_found": not_found, "curated": len(curated)}

load_curated(path=paths.DATA_ISIN_CURATED)

Load user-verified ISINs. Aborts with a plain error on an invalid row.

Intent (F1): a curated row is the highest-trust source, so a malformed one is a hard error naming the row, never a silent skip.

Source code in quant/data/registry_repair.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def load_curated(path: str = paths.DATA_ISIN_CURATED) -> dict[str, str]:
    """Load user-verified ISINs. Aborts with a plain error on an invalid row.

    Intent (F1): a curated row is the highest-trust source, so a malformed one is
    a hard error naming the row, never a silent skip.
    """
    if not os.path.exists(path):
        return {}
    df = pd.read_csv(path, comment="#")
    if df.empty or "symbol" not in df.columns or "isin" not in df.columns:
        return {}
    curated: dict[str, str] = {}
    for _, row in df.iterrows():
        sym = str(row.get("symbol", "") or "").strip()
        isin = str(row.get("isin", "") or "").strip()
        if not sym:
            continue
        if not is_valid_isin(isin):
            raise ValueError(
                f"curated row {sym}: invalid ISIN {isin!r} "
                f"(fails ISO 6166 checksum)"
            )
        curated[sym] = isin
    return curated

set_instrument_class(symbol, instrument_class)

Set one symbol's instrument class in asset_registry (v10.8.3).

The "Change type" override on the Update holdings page. Returns True when a row was written. Never raises.

Source code in quant/data/registry_repair.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def set_instrument_class(symbol: str, instrument_class: str) -> bool:
    """Set one symbol's instrument class in asset_registry (v10.8.3).

    The "Change type" override on the Update holdings page. Returns True when a
    row was written. Never raises.
    """
    from quant.data.database import write_connection

    sym = str(symbol or "").strip()
    cls = str(instrument_class or "").strip().upper()
    if not sym or not cls:
        return False
    try:
        with write_connection() as conn:
            conn.execute(
                "UPDATE asset_registry SET instrument_class = ? WHERE symbol = ?",
                [cls, sym])
        return True
    except Exception:  # noqa: BLE001
        return False

sync_registry_to_working_universe(conn, **kwargs)

Two-way sync of asset_registry to W (H3-fix part 2).

Intent: asset_registry holds exactly W. Insert missing W members (status WATCHLIST; class from taxonomy; currency by suffix heuristic); prune rows outside W. Membership only: surviving rows keep every cell. Idempotent. A fresh (empty) registry is a no-op — nothing stale to heal.

Source code in quant/data/registry_repair.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def sync_registry_to_working_universe(conn: Any, **kwargs) -> dict:
    """Two-way sync of asset_registry to W (H3-fix part 2).

    Intent: asset_registry holds exactly W. Insert missing W members (status
    WATCHLIST; class from taxonomy; currency by suffix heuristic); prune rows
    outside W. Membership only: surviving rows keep every cell. Idempotent.
    A fresh (empty) registry is a no-op — nothing stale to heal.
    """
    n_before = int(conn.execute("SELECT COUNT(*) FROM asset_registry").fetchone()[0])
    if n_before == 0:
        return {"added": 0, "pruned": 0, "total": 0, "skipped": "empty"}

    wu = working_universe(conn, **kwargs)
    rows = conn.execute("SELECT symbol FROM asset_registry").fetchall()
    existing = {str(r[0]).strip().upper(): str(r[0]) for r in rows if r[0]}
    to_prune = [existing[u] for u in existing if u not in wu]
    to_add = sorted(wu - set(existing))

    if to_prune:
        placeholders = ",".join(["?"] * len(to_prune))
        conn.execute(
            f"DELETE FROM asset_registry WHERE symbol IN ({placeholders})", to_prune)

    added = 0
    if to_add:
        from quant.data.universe_builder import BROAD_ETFS
        from quant.execution.taxonomy import classify_instrument

        # H3.5 (F3): classify WITH a known name so keyword rules fire (e.g.
        # SGLN.L "Silver ETF" -> COMMODITY). classify_instrument prefers the CSV
        # class when a broker_registry row exists, else the taxonomy heuristics.
        broad = {str(s).strip().upper(): n for n, s in BROAD_ETFS.items()}
        for sym in to_add:
            nm = broad.get(sym, "") or None
            conn.execute(
                """INSERT INTO asset_registry
                       (symbol, name, instrument_class, currency, universe_status, updated_at)
                   VALUES (?, ?, ?, ?, 'WATCHLIST', ?)
                   ON CONFLICT (symbol) DO NOTHING""",
                [sym, nm, classify_instrument(sym, nm or ""), _currency(sym), time.time()],
            )
            added += 1

    # Fill blank currency cells with the pure suffix heuristic (H3-fix part 2;
    # a venue suffix, not an identifier). Non-blank cells are never touched.
    for (sym,) in conn.execute(
        "SELECT symbol FROM asset_registry "
        "WHERE currency IS NULL OR trim(currency) = ''"
    ).fetchall():
        if sym:
            conn.execute(
                "UPDATE asset_registry SET currency = ? WHERE symbol = ?",
                [_currency(str(sym)), sym],
            )

    total = int(conn.execute("SELECT COUNT(*) FROM asset_registry").fetchone()[0])
    if added or to_prune:
        logging.getLogger("quant.data").info(
            "registry sync: +%d -%d", added, len(to_prune))
    return {"added": added, "pruned": len(to_prune), "total": total}

working_universe(conn=None, **kwargs)

The working universe W (see module note). Union of all sources.

Source code in quant/data/registry_repair.py
196
197
198
199
200
201
def working_universe(conn: Any =None, **kwargs) -> set[str]:
    """The working universe W (see module note). Union of all sources."""
    union: set[str] = set()
    for members in working_universe_sources(conn, **kwargs).values():
        union |= members
    return union

working_universe_sources(conn=None, *, portfolio_path=paths.DATA_PORTFOLIO, registry_path=paths.DATA_BROKER_REGISTRY, isin_curated_path=paths.DATA_ISIN_CURATED, names_curated_path=paths.DATA_NAMES_CURATED)

Per-source membership of W. Pure reads; never raises.

Source code in quant/data/registry_repair.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def working_universe_sources(
    conn: Any =None,
    *,
    portfolio_path: str = paths.DATA_PORTFOLIO,
    registry_path: str = paths.DATA_BROKER_REGISTRY,
    isin_curated_path: str = paths.DATA_ISIN_CURATED,
    names_curated_path: str = paths.DATA_NAMES_CURATED,
) -> dict[str, set[str]]:
    """Per-source membership of W. Pure reads; never raises."""
    sources: dict[str, set[str]] = {
        "broad_etfs": set(), "portfolio": set(), "broker_registry": set(),
        "curated": set(), "core_active": set(), "survivors": set(),
    }
    try:
        from quant.data.universe_builder import BROAD_ETFS

        sources["broad_etfs"] = {str(s).strip().upper()
                                 for s in BROAD_ETFS.values() if str(s).strip()}
    except Exception:  # noqa: BLE001
        pass
    try:
        from quant.portfolio.portfolio import load_portfolio

        pf = load_portfolio(str(portfolio_path))
        if not pf.empty and "Symbol" in pf.columns:
            sources["portfolio"] = {str(x).strip().upper()
                                    for x in pf["Symbol"].tolist() if str(x).strip()}
    except Exception:  # noqa: BLE001
        pass
    try:
        if os.path.exists(registry_path):
            reg = pd.read_csv(registry_path)
            if "yahoo_ticker" in reg.columns:
                sources["broker_registry"] = {str(x).strip().upper()
                                              for x in reg["yahoo_ticker"].dropna()
                                              if str(x).strip()}
    except Exception:  # noqa: BLE001
        pass
    try:
        sources["curated"] = {str(s).strip().upper()
                              for s in load_curated(isin_curated_path) if str(s).strip()}
    except Exception:  # noqa: BLE001
        pass
    try:
        from quant.data.names import load_curated_names

        sources["curated"] |= {str(s).strip().upper()
                               for s in load_curated_names(names_curated_path)
                               if str(s).strip()}
    except Exception:  # noqa: BLE001
        pass
    if conn is not None:
        try:
            sources["core_active"] = {str(r[0]).strip().upper() for r in conn.execute(
                "SELECT symbol FROM asset_registry WHERE universe_status IN ('CORE','ACTIVE')"
            ).fetchall() if r[0]}
        except Exception:  # noqa: BLE001
            pass
        try:
            sources["survivors"] = {str(r[0]).strip().upper() for r in conn.execute(
                "SELECT symbol FROM funnel_survivors"
            ).fetchall() if r[0]}
        except Exception:  # noqa: BLE001
            pass
    for key in sources:
        sources[key].discard("")
    return sources

news.py — headlines per symbol, scored by FinBERT, stored as nlp_evidence.

Run by refresh (so by the daily job and Run analysis) for the held symbols and the current funnel survivors:

  1. fetch the Yahoo Finance RSS headlines of each symbol;
  2. skip titles already stored for that symbol;
  3. score the new titles in one FinBERT batch: tone = P(positive) - P(negative) in -1..1 (the label order is read from the model config);
  4. insert them into nlp_evidence and prune rows older than 60 days.

Without the optional news extra (torch + transformers) headlines are still stored and shown, unscored; the sentiment score component then stays empty instead of being faked.

v10.8.10 replaces: a JSON news cache, a FinBERT scorer that skipped every text under 50 characters (so almost every headline scored a flat 0), a "news pillar" that then declared itself absent and stopped loading the model for good, and SEC 8-K filing text. nlp_evidence had had no writer since v10.5.

Invariants: ingest never raises; fetcher and scorer are injectable.

HeadlineScorer

FinBERT tone for short texts (loaded once, on first use).

Source code in quant/data/news.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
class HeadlineScorer:
    """FinBERT tone for short texts (loaded once, on first use)."""

    def __init__(self, model_name: str = FINBERT_MODEL) -> None:
        import torch
        from transformers import AutoModelForSequenceClassification, AutoTokenizer

        torch.set_num_threads(2)
        self._torch = torch
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        self.model = AutoModelForSequenceClassification.from_pretrained(model_name)
        self.model.eval()
        labels = {str(v).lower(): int(k) for k, v in self.model.config.id2label.items()}
        self._pos, self._neg = labels["positive"], labels["negative"]

    def score(self, texts: list[str]) -> list[float]:
        """Tone in -1..1 per text: P(positive) - P(negative)."""
        out: list[float] = []
        for i in range(0, len(texts), 32):
            enc = self.tokenizer(texts[i:i + 32], padding=True, truncation=True,
                                 max_length=64, return_tensors="pt")
            with self._torch.no_grad():
                probs = self._torch.softmax(self.model(**enc).logits, dim=-1)
            out += (probs[:, self._pos] - probs[:, self._neg]).tolist()
        return [round(float(s), 4) for s in out]

score(texts)

Tone in -1..1 per text: P(positive) - P(negative).

Source code in quant/data/news.py
 96
 97
 98
 99
100
101
102
103
104
105
def score(self, texts: list[str]) -> list[float]:
    """Tone in -1..1 per text: P(positive) - P(negative)."""
    out: list[float] = []
    for i in range(0, len(texts), 32):
        enc = self.tokenizer(texts[i:i + 32], padding=True, truncation=True,
                             max_length=64, return_tensors="pt")
        with self._torch.no_grad():
            probs = self._torch.softmax(self.model(**enc).logits, dim=-1)
        out += (probs[:, self._pos] - probs[:, self._neg]).tolist()
    return [round(float(s), 4) for s in out]

fetch_headlines(symbol, fetch=_rss)

[{title, published_at}] for a symbol; [] on any failure.

Source code in quant/data/news.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def fetch_headlines(symbol: str, fetch: Callable[[str], bytes] = _rss) -> list[dict]:
    """``[{title, published_at}]`` for a symbol; [] on any failure."""
    import feedparser

    try:
        feed = feedparser.parse(fetch(symbol))
    except Exception as e:  # noqa: BLE001
        logger.warning("[%s] news fetch failed: %s", symbol, e)
        return []
    out = []
    for entry in feed.entries[:MAX_PER_SYMBOL]:
        title = " ".join(str(entry.get("title", "")).split())
        if title:
            out.append({"title": title, "published_at": _published(entry.get("published"))})
    return out

ingest(conn, symbols, fetch=_rss, scorer='default', today=None)

Fetch, score and store new headlines. Returns {symbols, new, scored}.

Source code in quant/data/news.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def ingest(conn: Any, symbols: list[str], fetch: Callable[[str], bytes] = _rss,
           scorer: Any = "default", today: date | None = None) -> dict:
    """Fetch, score and store new headlines. Returns ``{symbols, new, scored}``."""
    today = today or date.today()
    stats = {"symbols": 0, "new": 0, "scored": 0}
    fresh: list[tuple[str, dict]] = []
    for sym in symbols:
        items = fetch_headlines(sym, fetch)
        if not items:
            continue
        stats["symbols"] += 1
        try:
            known = {r[0] for r in conn.execute(
                "SELECT title FROM nlp_evidence WHERE symbol = ?", [sym]).fetchall()}
        except Exception:  # noqa: BLE001
            known = set()
        for it in items:
            if it["title"] not in known:      # also drops repeats within one feed
                known.add(it["title"])
                fresh.append((sym, it))
    if not fresh:
        return stats
    if scorer == "default":
        scorer = _default_scorer()
    scores: list[float | None] = [None] * len(fresh)
    if scorer is not None:
        try:
            scores = list(scorer.score([it["title"] for _s, it in fresh]))
        except Exception as e:  # noqa: BLE001
            logger.warning("news scoring failed (%s); headlines stored unscored", e)
    try:
        for (sym, it), score in zip(fresh, scores, strict=True):
            conn.execute(
                "INSERT INTO nlp_evidence (symbol, source, title, published_at, score, "
                "confidence) VALUES (?, 'news', ?, ?, ?, ?)",
                [sym, it["title"], it["published_at"], score,
                 None if score is None else "model"])
        conn.execute("DELETE FROM nlp_evidence WHERE COALESCE(published_at, retrieved_at) "
                     "< ?", [datetime.combine(today, datetime.min.time())
                             - timedelta(days=KEEP_DAYS)])
    except Exception as e:  # noqa: BLE001
        logger.warning("news store failed: %s", e)
        return stats
    stats["new"] = len(fresh)
    stats["scored"] = sum(1 for s in scores if s is not None)
    return stats

model_available()

True when the optional news stack (torch + transformers) is installed.

Source code in quant/data/news.py
40
41
42
43
44
45
def model_available() -> bool:
    """True when the optional news stack (torch + transformers) is installed."""
    import importlib.util

    return (importlib.util.find_spec("torch") is not None
            and importlib.util.find_spec("transformers") is not None)

currency.py — EUR conversion for every price the app shows.

A symbol's currency is the one Yahoo reports for it (stored in asset_registry.currency by refresh); the ticker-suffix guess is only the fallback for a symbol never fetched. Rates are "units of X per 1 EUR" from Yahoo (EURX=X), then the ECB (frankfurter.dev), then the last live rate persisted in the data folder. Pence quotes (GBp/GBX) are divided by 100.

v10.8.10: before, every offline run used EUR/USD = 1.0 (the valuation backfill then rewrote the whole history of USD holdings at that rate), every .L listing was treated as pence, and non-USD rates were proxied through USD.

deduce_currency(symbol)

Guess a listing currency from the ticker suffix (fallback only). Pure.

.L is ambiguous on Yahoo (pence, pounds or dollars per line); the stored Yahoo currency always wins over this guess.

Source code in quant/data/currency.py
127
128
129
130
131
132
133
134
135
136
137
138
139
def deduce_currency(symbol: str) -> str:
    """Guess a listing currency from the ticker suffix (fallback only). Pure.

    ``.L`` is ambiguous on Yahoo (pence, pounds or dollars per line); the stored
    Yahoo currency always wins over this guess.
    """
    if "." not in symbol:
        return "USD"
    suffix = symbol.split(".")[-1].upper()
    if suffix in {"DE", "PA", "AS", "MI", "MC", "BR", "VI", "HE", "F", "IR", "LS"}:
        return "EUR"
    return {"L": "GBp", "SW": "CHF", "CO": "DKK", "OL": "NOK", "ST": "SEK",
            "TO": "CAD", "AX": "AUD", "KS": "KRW"}.get(suffix, "USD")

eur_rate(ccy)

Units of ccy per 1 EUR (live, else the last live rate), or None.

Source code in quant/data/currency.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def eur_rate(ccy: str) -> float | None:
    """Units of ``ccy`` per 1 EUR (live, else the last live rate), or None."""
    ccy = ccy.upper()
    if ccy == "EUR":
        return 1.0
    if ccy in _rate_cache:
        return _rate_cache[ccy]
    for source, fetch in (("Yahoo", _yahoo_rate), ("ECB", _ecb_rate)):
        rate = fetch(ccy)
        if rate is not None and _plausible(ccy, rate):
            _rate_cache[ccy] = rate
            _save_last_rate(ccy, rate)
            reporter.detail(f"  [FX] EUR/{ccy} = {rate:.4f} ({source})")
            return rate
    last = _load_last_rates().get(ccy)
    if last is not None and _plausible(ccy, last):
        reporter.detail(f"  [FX] WARNING: live EUR/{ccy} unavailable; using the "
                        f"last live rate {last:.4f}.")
        _rate_cache[ccy] = last
        return last
    return None

get_eur_rate()

EUR/USD (USD per EUR). 1.0 only on an install that has never been online.

Source code in quant/data/currency.py
118
119
120
121
122
123
124
def get_eur_rate() -> float:
    """EUR/USD (USD per EUR). 1.0 only on an install that has never been online."""
    rate = eur_rate("USD")
    if rate is None:
        reporter.detail("  [FX] WARNING: no EUR/USD rate known; using 1.0.")
        return 1.0
    return rate

get_fx_to_eur(symbol)

Multiplier from a symbol's quoted price to EUR. Never raises.

Source code in quant/data/currency.py
160
161
162
163
164
165
166
167
168
169
170
171
172
def get_fx_to_eur(symbol: str) -> float:
    """Multiplier from a symbol's quoted price to EUR. Never raises."""
    ccy = symbol_currency(symbol)
    factor = 1.0
    if ccy in ("GBp", "GBX"):          # pence
        factor, ccy = 0.01, "GBP"
    if ccy.upper() == "EUR":
        return factor
    rate = eur_rate(ccy) if ccy.upper() != "USD" else get_eur_rate()
    if rate is None:
        reporter.detail(f"  [FX] WARNING: no EUR/{ccy} rate known; {symbol} unconverted.")
        return factor
    return factor / rate

price_in_eur(symbol, as_of=None, conn=None)

The EUR price of a symbol on (or before) a date (v10.8.0, 2.2).

Intent: valuation, the daily job, the Overview estimate, buy and sell recording, the chart series and the audit all need a price in EUR. The native close comes from market_history; the FX multiplier comes from :func:get_fx_to_eur (the documented nearest-available rate). Returns None when no close exists.

as_of may be a date, an ISO string, or None (latest). conn is an optional open connection; when omitted a short-lived read-only connection is used.

Source code in quant/data/currency.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def price_in_eur(symbol: str, as_of: Any =None, conn: Any =None) -> float | None:
    """The EUR price of a symbol on (or before) a date (v10.8.0, 2.2).

    Intent: valuation, the daily job, the Overview estimate, buy and sell
    recording, the chart series and the audit all need a price in EUR. The
    native close comes from ``market_history``; the FX multiplier comes from
    :func:`get_fx_to_eur` (the documented nearest-available rate). Returns None
    when no close exists.

    ``as_of`` may be a date, an ISO string, or None (latest). ``conn`` is an
    optional open connection; when omitted a short-lived read-only connection is
    used.
    """
    close = _native_close(symbol, as_of, conn)
    if close is None:
        return None
    return close * get_fx_to_eur(symbol)

symbol_currency(symbol)

The currency Yahoo reports for symbol (stored by refresh), else a guess.

Source code in quant/data/currency.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def symbol_currency(symbol: str) -> str:
    """The currency Yahoo reports for ``symbol`` (stored by refresh), else a guess."""
    if symbol in _ccy_cache:
        return _ccy_cache[symbol]
    ccy = None
    try:
        from quant.data.database import read_only_connection

        with read_only_connection() as conn:
            row = conn.execute("SELECT currency FROM asset_registry WHERE symbol = ? "
                               "AND currency_source = 'yahoo'", [symbol]).fetchone()
        ccy = row[0] if row and row[0] else None
    except Exception:  # noqa: BLE001
        ccy = None
    _ccy_cache[symbol] = ccy or deduce_currency(symbol)
    return _ccy_cache[symbol]

The one workflow

diff.py — the Review diff against the last saved table (v10.8.2, section 3).

Intent: saving the table is the only way data enters the system. Before writing anything, the app shows what changed per ticker: Bought, Sold (with an estimated realized gain/loss), or a market move. Derived, never typed: invested = Value - Profit; shares = invested / Einstandskurs.

Invariants
  • Pure: no I/O.
  • A share change below 0.5 percent of the position, or below 1 EUR of invested, counts as unchanged (rounding).
  • A sell's realized gain is an estimate; Trade Republic's tax report is the authority. Proceeds use the latest EUR price when known.
  • A trade moves money: when the invested amount is unchanged but the share count changed by a stock-split ratio, the change is a Split and nothing is recorded in the ledger (v10.8.10; the valuation restates old lots itself).

diff_tables(old_rows, new_rows, prices=None, plans=None)

Diff the new table against the last saved one. Pure; no I/O.

Returns {changes: [...], summary: {...}} where each change is one of Bought / Sold / Split / Market move. A buy that matches the saved plan (plans: {symbol: EUR/month}) carries savings_plan: True.

Source code in quant/engine/diff.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def diff_tables(old_rows: list[dict] | None, new_rows: list[dict] | None,
                prices: dict | None = None, plans: dict | None = None) -> dict:
    """Diff the new table against the last saved one. Pure; no I/O.

    Returns ``{changes: [...], summary: {...}}`` where each change is one of
    ``Bought`` / ``Sold`` / ``Split`` / ``Market move``. A buy that matches the saved plan
    (``plans``: {symbol: EUR/month}) carries ``savings_plan: True``.
    """
    prices = prices or {}
    old = _index(old_rows)
    new = _index(new_rows)
    changes: list[dict] = []
    bought = sold = realized = 0.0

    for sym, p in new.items():
        prev = old.get(sym)
        if prev is None:
            if p["invested"] != 0 or p["shares"] > 0:
                changes.append({"kind": "Bought", "symbol": sym,
                                "shares": round(p["shares"], 6),
                                "amount_eur": round(p["invested"], 2),
                                "savings_plan": _matches_plan(
                                    sym, p["invested"], plans)})
                bought += p["invested"]
            continue
        d_shares = p["shares"] - prev["shares"]
        if _shares_unchanged(prev, d_shares):
            # Same shares: a value/profit move is a market move (no record).
            if abs(p["value"] - prev["value"]) >= TOL_INVESTED_EUR:
                changes.append({"kind": "Market move", "symbol": sym})
            continue
        ratio = _split_ratio(prev, p)
        if ratio is not None:
            changes.append({"kind": "Split", "symbol": sym, "ratio": ratio})
            continue
        if d_shares > 0:
            amount = p["invested"] - prev["invested"]
            changes.append({"kind": "Bought", "symbol": sym,
                            "shares": round(d_shares, 6),
                            "amount_eur": round(amount, 2),
                            "savings_plan": _matches_plan(sym, amount, plans)})
            bought += amount
        else:
            change = _sell(prev, -d_shares, prices)
            changes.append(change)
            sold += change["amount_eur"]
            realized += change["realized_eur"]

    for sym, prev in old.items():
        if sym in new:
            continue
        if prev["invested"] != 0 or prev["shares"] > 0:
            change = _sell(prev, prev["shares"], prices)
            changes.append(change)
            sold += change["amount_eur"]
            realized += change["realized_eur"]

    return {
        "changes": changes,
        "summary": {
            "bought_eur": round(bought, 2),
            "sold_eur": round(sold, 2),
            "realized_eur": round(realized, 2),
            "changed": bool(changes),
        },
    }

position(row)

One position with derived invested and shares (Einstandskurs based).

Source code in quant/engine/diff.py
37
38
39
40
41
42
43
44
45
46
def position(row: dict) -> dict:
    """One position with derived invested and shares (Einstandskurs based)."""
    symbol = str(row.get("Symbol") or row.get("symbol") or "").strip()
    entry = _num(row.get("Avg_Entry_Price", row.get("entry")))
    value = _num(row.get("Current_Value_EUR", row.get("value")))
    profit = _num(row.get("Broker_PnL_EUR", row.get("profit")))
    invested = value - profit
    shares = invested / entry if entry > 0 else 0.0
    return {"symbol": symbol, "entry": entry, "value": value, "profit": profit,
            "invested": invested, "shares": shares}

confirm.py — Confirm and save, one all-or-nothing action (v10.8.2, section 3).

Intent: saving the table is the only way data enters the system. Confirm and save backs up the previous table, writes the new one atomically, appends a position snapshot, and records the detected diff in the ledger. A failure before the table write leaves nothing changed; the table write itself is atomic (temp + rename).

Invariants
  • The previous table is backed up before the new one is written.
  • The position snapshot and the ledger rows are written in one DB transaction.
  • Shares are derived from the table (invested / Einstandskurs), never a price lookup.

confirm_save(cleaned, diff, when=None, path=None)

Persist a confirmed table + its diff. Returns {ok, changes, error}.

cleaned is a DataFrame with the four broker columns; diff is the result of :func:quant.engine.diff.diff_tables.

Source code in quant/engine/confirm.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def confirm_save(cleaned, diff: dict, when: date | None = None,
                 path: str | None = None) -> dict:
    """Persist a confirmed table + its diff. Returns ``{ok, changes, error}``.

    ``cleaned`` is a DataFrame with the four broker columns; ``diff`` is the
    result of :func:`quant.engine.diff.diff_tables`.
    """
    from quant.portfolio.editor import save_portfolio

    when = when or date.today()
    path = path or paths.DATA_PORTFOLIO

    # 1. Back up the previous table + settings (copy only; never raises).
    try:
        from quant.engine import backup as backup_mod

        backup_mod.snapshot_user_files()
    except Exception:  # noqa: BLE001
        pass

    # 2. Write the new table atomically.
    try:
        save_portfolio(cleaned, path)
    except Exception as e:  # noqa: BLE001
        return {"ok": False, "changes": 0, "error": str(e)}

    # 3+4. Snapshot + ledger in one transaction.
    try:
        from quant.data.database import write_connection

        with write_connection() as conn:
            _append_snapshot(conn, cleaned, when)
            _append_ledger(conn, diff, when)
    except Exception as e:  # noqa: BLE001
        return {"ok": False, "changes": 0, "error": str(e)}

    # 5. v10.8.4/v10.8.5 (T1/T2): backfill the mark-to-market valuation store from
    #    the ledger (every trading day), so every page reads the confirmed state
    #    and the chart is continuous.
    try:
        from quant.data.database import write_connection
        from quant.engine import mtm

        with write_connection() as conn:
            mtm.backfill(conn, source=mtm.SOURCE_CONFIRM)
    except Exception:  # noqa: BLE001
        pass  # the table + snapshot + ledger are already saved; never fail here

    # 6. v10.8.10 (R-C4): the confirm is a writer; persist the ONE list so the
    #    advice log reflects the new holdings (the render path only reads it).
    from quant.engine.today_list import persist

    persist()

    return {"ok": True, "changes": len(diff.get("changes", [])), "error": None}

holdings_view.py — the live per-holding view (v10.8.3).

Intent: the five pages must show the user's real holdings the moment the table is saved, without depending on a quant run review artifact. Before v10.8.3 the pages read read_actions(), which needs outputs/portfolio_audit.csv; the one-workflow never produces it, so Holdings and Full analysis were empty.

This module builds one list of holding dicts from the live position source (:func:quant.engine.positions.positions_now) plus the tier map and the per-symbol targets. It is the single input to the Portfolio table, the Full analysis table and :func:quant.engine.action_taxonomy.build (the ONE list).

Invariants
  • Pure read: no writes.
  • Never raises; returns [] on failure.
  • current_weight and target_weight are fractions of the invested pool; target_weight (and drift) is None when no target is set.
  • With a plan set, target_weight sits inside the plan's pot split (:func:quant.engine.plan.pot_targets); the saved targets are weights.

holdings_view(conn=None)

The live holdings, one dict per position.

Fields: symbol, name, tier, value_eur, shares, cost_per_share, profit_eur, invested_eur, pnl_pct, current_weight, target_weight, drift, estimated, as_of.

Source code in quant/engine/holdings_view.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def holdings_view(conn: Any = None) -> list[dict]:
    """The live holdings, one dict per position.

    Fields: symbol, name, tier, value_eur, shares, cost_per_share, profit_eur,
    invested_eur, pnl_pct, current_weight, target_weight, drift, estimated, as_of.
    """
    from quant.engine.positions import positions_now

    positions = positions_now(conn)   # never raises
    if not positions:
        return []

    tmap, targets = _tiers()
    out: list[dict] = []
    for p in positions:
        sym = str(p.get("symbol") or "")
        if not sym:
            continue
        out.append({
            "symbol": sym,
            "name": _display_name(sym),
            "tier": str(tmap.get(sym, DEFAULT_TIER)).upper(),
            "value_eur": float(p.get("value_eur") or 0),
            "shares": float(p.get("shares") or 0),
            "cost_per_share": float(p.get("entry_eur") or 0),
            "profit_eur": float(p.get("profit_eur") or 0),
            "invested_eur": float(p.get("invested_eur") or 0),
            "pnl_pct": p.get("pnl_pct"),
            "estimated": bool(p.get("estimated")),
            "as_of": p.get("as_of"),
        })
    # v10.8.7 (T3/R-C3): the ONE weight math. No local value/total here.
    weights = instrument_weights(out)
    targets = _plan_targets(out, targets)
    for h in out:
        h["current_weight"] = weights.get(h["symbol"], 0.0)
        # No target set -> None (no drift advice), never 0% (v10.8.10).
        h["target_weight"] = targets.get(h["symbol"])
        h["drift"] = (None if h["target_weight"] is None
                      else h["current_weight"] - h["target_weight"])
    return out

positions.py — the ONE source of current positions (v10.8.0; v10.8.10).

Every page, the ONE list and Telegram read the same positions. Per row of the holdings table:

invested = typed value - typed profit (what was paid, EUR) shares = invested / average cost per share value = the valuation store's latest value for the symbol (the same number the Portfolio header sums), else the typed value when the symbol has no price yet profit = value - invested

v10.8.10: values were the typed numbers (possibly weeks old), so weights, drift and stop-losses ignored the market; shares were computed as value / cost (too many shares for any position in profit); a holdings_meta "estimate" branch depended on a writer that no longer exists.

Invariants: pure read; never raises; returns [] on failure.

positions_now(conn=None)

The current positions: symbol, shares, value_eur, invested_eur, entry_eur, profit_eur, pnl_pct, as_of, estimated (True = marked to the latest close).

Source code in quant/engine/positions.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def positions_now(conn: Any = None) -> list[dict]:
    """The current positions: symbol, shares, value_eur, invested_eur, entry_eur,
    profit_eur, pnl_pct, as_of, estimated (True = marked to the latest close)."""
    from quant.portfolio.portfolio import load_portfolio

    portfolio = load_portfolio(paths.DATA_PORTFOLIO)
    if portfolio is None or portfolio.empty:
        return []
    if conn is not None:
        return _build(portfolio, conn)
    try:
        from quant.data.database import read_only_connection

        with read_only_connection() as c:
            return _build(portfolio, c)
    except Exception:  # noqa: BLE001
        return _build(portfolio, None)

ledger.py — the ONE transactional write for a recorded transaction (v10.8.0, 2.4).

Intent: before v10.8.0 a buy, sell, or dividend was written to flows and trades in two separate connections, so a failure between them left one ledger updated and the UI said "Could not record". This module writes both in ONE transaction, computes the FIFO realized gain for a sell, and returns the fee and gain so every caller (UI, tax, performance) reads the same facts.

Invariants
  • One connection, one transaction: a failure leaves nothing half-written.
  • FIFO realized gain is seeded by the broker's entry price for opening lots.
  • The fee default is zero for a savings-plan execution, else the broker fee.

default_fee(action, savings_plan=False)

The fee for a transaction: zero for a savings plan, else the broker fee.

Source code in quant/engine/ledger.py
27
28
29
30
31
def default_fee(action: str, savings_plan: bool = False) -> float:
    """The fee for a transaction: zero for a savings plan, else the broker fee."""
    if savings_plan:
        return 0.0
    return float(ACTIVE_TRADE_FEE_EUR) if str(action).lower() in ("buy", "sell") else 0.0

replace_trades(rows)

Replace the trades ledger with rows in one transaction (v10.8.3).

Each row: {id?, date, symbol, action, amount_eur, realized_pnl_eur}. A row with an existing id is updated; a row without one is inserted; any id not present in rows is deleted. Returns the number of rows written. Used by the History page so the user can correct the derived numbers.

Source code in quant/engine/ledger.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def replace_trades(rows: list[dict]) -> int:
    """Replace the trades ledger with ``rows`` in one transaction (v10.8.3).

    Each row: ``{id?, date, symbol, action, amount_eur, realized_pnl_eur}``. A row
    with an existing ``id`` is updated; a row without one is inserted; any id not
    present in ``rows`` is deleted. Returns the number of rows written. Used by the
    History page so the user can correct the derived numbers.
    """
    from quant.data.database import write_connection

    with write_connection() as conn:
        existing = {int(r[0]) for r in conn.execute("SELECT id FROM trades").fetchall()}
        keep: set[int] = set()
        for r in rows:
            rid = r.get("id")
            date = r.get("date")
            symbol = str(r.get("symbol") or "")
            action = str(r.get("action") or "").lower()
            amount = float(r.get("amount_eur") or 0)
            pnl = r.get("realized_pnl_eur")
            pnl = None if pnl is None or pnl == "" else float(pnl)
            if rid is not None and int(rid) in existing:
                conn.execute(
                    "UPDATE trades SET date = ?, symbol = ?, action = ?, "
                    "amount_eur = ?, realized_pnl_eur = ? WHERE id = ?",
                    [date, symbol, action, amount, pnl, int(rid)])
                keep.add(int(rid))
            else:
                conn.execute(
                    "INSERT INTO trades (date, symbol, action, amount_eur, "
                    "realized_pnl_eur) VALUES (?, ?, ?, ?, ?)",
                    [date, symbol, action, amount, pnl])
        for rid in existing - keep:
            conn.execute("DELETE FROM trades WHERE id = ?", [rid])
    return len(rows)

invest_plan.py — the class-based invest suggestion (v10.8.3; v10.8.7, T3).

Intent: the user enters ONE amount. The app compares the current mix of the three classes (FORTRESS / ALPHA / SPECULATIVE tiers) against the mix the chosen strategy (risk profile) wants, and suggests buys that move the portfolio toward it. It is a suggestion only: the app never controls the broker's plans and never sells here.

v10.8.7 (T3/R-C3): - The class Now comes from the ONE weight math (:mod:quant.engine.weights). - An instrument with an open trim/sell gets NO buy suggestion; if its class is under target the money routes to the next eligible instrument or the exclusion is noted in one line. - One-off EUR and savings-plan EUR/m are separate dimensions: the one-off row sums to at most the entered amount; the Long-term savings-plan increase is shown as "+Z EUR/m" and never added into the one-off sum. - A non-held idea can fill an active class (How = "New position").

Invariants
  • Pure: no I/O.
  • Never suggests a sell.
  • The one-off buys never exceed the entered amount.

propose_by_class(amount_eur, holdings=None, strategy=DEFAULT_RISK_PROFILE, candidates=None, open_advice=None)

Suggest buys per class toward the strategy's target mix.

Returns {classes, orders, savings_plan, not_allocated, total, savings_plan_eur_month, excluded} where classes is one row per tier (now fraction, target fraction, suggested EUR), orders are the one-off buys, savings_plan the EUR/m suggestions, total the one-off sum and savings_plan_eur_month the separate monthly sum.

Source code in quant/engine/invest_plan.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def propose_by_class(
    amount_eur: float,
    holdings: list[dict] | None = None,
    strategy: str = DEFAULT_RISK_PROFILE,
    candidates: list[dict] | None = None,
    open_advice: list[dict] | None = None,
) -> dict:
    """Suggest buys per class toward the strategy's target mix.

    Returns ``{classes, orders, savings_plan, not_allocated, total,
    savings_plan_eur_month, excluded}`` where ``classes`` is one row per tier
    (now fraction, target fraction, suggested EUR), ``orders`` are the one-off
    buys, ``savings_plan`` the EUR/m suggestions, ``total`` the one-off sum and
    ``savings_plan_eur_month`` the separate monthly sum.
    """
    amount = _num(amount_eur)
    holdings = holdings or []
    if amount <= 0:
        return {"classes": [], "orders": [], "savings_plan": [],
                "not_allocated": 0.0, "total": 0.0,
                "savings_plan_eur_month": 0.0, "excluded": []}

    invested = sum(_num(h.get("value_eur")) for h in holdings)
    new_pool = invested + amount
    targets = _class_targets(strategy, holdings)
    now = class_weights(holdings)  # fractions of the invested pool (R-C3)
    now_value = {c: now.get(c, 0.0) * invested for c in CLASS_ORDER}

    blocked = _blocked_symbols(open_advice)
    held = {str(h.get("symbol")) for h in holdings}

    # One-off budget goes to the active classes; the Long-term class is a
    # savings-plan (EUR/m) suggestion, a separate dimension (T3).
    buys = {c: max(0.0, targets[c] * new_pool - now_value[c])
            for c in _ACTIVE_CLASSES}
    total_buy = sum(buys.values())
    if total_buy > amount > 0:
        scale = amount / total_buy
        buys = {c: v * scale for c, v in buys.items()}
    fortress_gap = max(0.0, targets["FORTRESS"] * new_pool - now_value["FORTRESS"])

    members = {c: [] for c in CLASS_ORDER}
    for h in holdings:
        tier = str(h.get("tier", "ALPHA")).upper()
        if tier in members:
            members[tier].append(h)

    orders: list[dict] = []
    savings_plan: list[dict] = []
    excluded: list[dict] = []
    not_allocated = 0.0
    used = {c: 0.0 for c in CLASS_ORDER}

    for tier in _ACTIVE_CLASSES:
        rows = _distribute(buys[tier], members[tier], new_pool)
        if not rows and buys[tier] > 0:
            idea = _best_candidate(candidates, blocked, held)
            amt = round_down(buys[tier], ROUND_STEP)
            if idea is not None and amt >= MIN_ORDER_EUR:
                orders.append({"symbol": str(idea.get("symbol")),
                               "name": idea.get("name") or idea.get("symbol"),
                               "amount_eur": amt, "how": HOW_NEW_POSITION,
                               "tier": tier})
                used[tier] = amt
                continue
            not_allocated += buys[tier]
            continue
        for h, raw in rows:
            sym = str(h.get("symbol"))
            if sym in blocked:
                excluded.append({"symbol": sym, "name": h.get("name") or sym,
                                 "reason": "open sell/trim; no buy until it clears."})
                not_allocated += raw
                continue
            amt = round_down(raw, ROUND_STEP)
            if amt < MIN_ORDER_EUR:
                not_allocated += amt
                continue
            orders.append({"symbol": sym, "name": h.get("name") or sym,
                           "amount_eur": amt, "how": HOW_ONEOFF, "tier": tier})
            used[tier] += amt

    # The Long-term savings-plan suggestion (EUR/m), separate from the one-off.
    if fortress_gap > 0:
        sp_amt = round_down(fortress_gap, ROUND_STEP)
        if sp_amt >= MIN_ORDER_EUR:
            sym, name = _core_fund()
            savings_plan.append({"symbol": sym, "name": name,
                                 "amount_eur": sp_amt, "how": HOW_SAVINGS_PLAN,
                                 "tier": "FORTRESS"})
            used["FORTRESS"] = sp_amt

    classes = [{
        "tier": c,
        "now_pct": now.get(c, 0.0) * 100.0,
        "target_pct": targets[c] * 100.0,
        "suggested_eur": round(used[c], 2),
    } for c in CLASS_ORDER]

    one_off_total = sum(o["amount_eur"] for o in orders)
    sp_total = sum(o["amount_eur"] for o in savings_plan)
    return {"classes": classes, "orders": orders, "savings_plan": savings_plan,
            "not_allocated": round(amount - one_off_total, 2),
            "total": round(one_off_total, 2),
            "savings_plan_eur_month": round(sp_total, 2),
            "excluded": excluded}

The ONE list (decisions)

today_list.py — the ONE list's items, computed once and persisted by writers only.

Intent (v10.8.10, R-C4): the Portfolio page used to compute the list AND write the advice log on every render. The computation now lives here; the render path calls :func:build_items and :func:quant.engine.advice_state.annotate (read-only), and only the writers (the daily job, confirm and refresh) call :func:persist, which reconciles the advice log via :func:quant.engine.advice_state.sync.

The list is the one rule set in :mod:quant.engine.action_taxonomy (rebalance, plan change, threat, swap) over the live holdings, their 7-day price change, the scores and the ideas.

Invariants
  • build_items / watch_lines / scores_map / idea_rows / change_7d are reads only.
  • persist never raises; it returns the number of items synced.

build_items(holdings, regime=None, scores=None, ideas=None)

The ONE list (Today before This month) from the one rule set. Reads only.

Source code in quant/engine/today_list.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def build_items(holdings: list[dict] | None, regime: Any = None,
                scores: dict | None = None, ideas: list[dict] | None = None) -> list[dict]:
    """The ONE list (Today before This month) from the one rule set. Reads only."""
    from quant.engine import action_taxonomy as T

    holdings = list(holdings or [])
    scores = scores_map() if scores is None else scores
    ideas = idea_rows(holdings, scores) if ideas is None else ideas
    moves = change_7d([str(h.get("symbol")) for h in holdings])
    holdings = [{**h, "change_7d": moves.get(str(h.get("symbol")))} for h in holdings]
    money = _money()
    return [{**t, "direction": _DIRECTIONS.get(t["verb"], ui_copy.DIRECTION_BUY)}
            for t in T.build(holdings, scores=scores, ideas=ideas, regime=regime,
                             budget=money["budget"], proceeds=money["proceeds"],
                             proceeds_pot=money["pot"])]

change_7d(symbols, conn=None)

Per symbol: the close-to-close change over the last 7 trading days.

Source code in quant/engine/today_list.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def change_7d(symbols: list[str], conn: Any = None) -> dict:
    """Per symbol: the close-to-close change over the last 7 trading days."""
    if not symbols:
        return {}
    marks = ",".join("?" for _ in symbols)
    rows = _rows(
        "SELECT Symbol, Close FROM (SELECT Symbol, Close, ROW_NUMBER() OVER "
        "(PARTITION BY Symbol ORDER BY Date DESC) AS rn FROM market_history "
        f"WHERE Symbol IN ({marks}) AND Close IS NOT NULL) WHERE rn IN (1, 8) "
        "ORDER BY Symbol, rn", list(symbols), conn=conn)
    closes: dict = {}
    for sym, close in rows:
        closes.setdefault(str(sym), []).append(float(close))
    return {s: c[0] / c[1] - 1.0 for s, c in closes.items() if len(c) == 2 and c[1] > 0}

idea_rows(holdings, scores=None, limit=50)

Watched (non-held) symbols with a composite >= IDEA_FLOOR, best first.

Only high-confidence scores qualify: a stock needs its fundamentals, an ETF needs news, so a pure price trend never becomes an Idea.

Source code in quant/engine/today_list.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def idea_rows(holdings: list[dict] | None, scores: dict | None = None,
              limit: int = 50) -> list[dict]:
    """Watched (non-held) symbols with a composite >= ``IDEA_FLOOR``, best first.

    Only high-confidence scores qualify: a stock needs its fundamentals, an ETF
    needs news, so a pure price trend never becomes an Idea.
    """
    from quant.config import IDEA_FLOOR

    scores = scores_map() if scores is None else scores
    held = {str(h.get("symbol")) for h in holdings or []}
    out = [{"symbol": sym, "name": _display(sym), "score": float(s["composite"])}
           for sym, s in scores.items()
           if sym not in held and s.get("composite") is not None
           and str(s.get("confidence") or "high") == "high"
           and float(s["composite"]) >= IDEA_FLOOR]
    out.sort(key=lambda x: x["score"], reverse=True)
    return out[:limit]

persist(conn=None)

Writers only: rebuild the list from stored data and sync the advice log.

Source code in quant/engine/today_list.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def persist(conn: Any = None) -> int:
    """Writers only: rebuild the list from stored data and sync the advice log."""
    try:
        from quant.engine import advice_state
        from quant.engine.holdings_view import holdings_view
        from quant.reporting.artifacts import read_regime

        holdings = holdings_view()
        items = build_items(holdings, regime=read_regime())
        if conn is not None:
            return len(advice_state.sync(conn, items))
        from quant.data.database import write_connection

        with write_connection() as c:
            return len(advice_state.sync(c, items))
    except Exception:  # noqa: BLE001
        return 0

scores_map(conn=None)

The scores store as {symbol: {composite, structural_grade, confidence}}.

Source code in quant/engine/today_list.py
47
48
49
50
51
52
def scores_map(conn: Any = None) -> dict:
    """The scores store as ``{symbol: {composite, structural_grade, confidence}}``."""
    rows = _rows("SELECT symbol, composite, structural_grade, confidence FROM scores",
                 conn=conn)
    return {str(sym): {"composite": comp, "structural_grade": grade, "confidence": conf}
            for sym, comp, grade, conf in rows}

watch_lines(holdings, scores=None, ideas=None)

What the rules are watching per holding (see action_taxonomy). Reads only.

Source code in quant/engine/today_list.py
125
126
127
128
129
130
131
132
133
def watch_lines(holdings: list[dict] | None, scores: dict | None = None,
                ideas: list[dict] | None = None) -> list[str]:
    """What the rules are watching per holding (see action_taxonomy). Reads only."""
    from quant.engine import action_taxonomy as T

    holdings = list(holdings or [])
    scores = scores_map() if scores is None else scores
    ideas = idea_rows(holdings, scores) if ideas is None else ideas
    return T.watch_lines(holdings, scores=scores, ideas=ideas)

decisions.py — the ONE decision list (v10.8.0, Phase 1, redesign 3.2).

Intent: every surface that shows the user what to do renders from one list, grouped into three buckets:

  • "Needs your input": a holding that blocks advice (missing ISIN).
  • "Recommended": an actionable advice (buy, top up, sell part, plan change).
  • "Optional": a keep, or a considered-but-suppressed note.
Invariants
  • Pure: no I/O.
  • Every advice record lands in exactly one group.
  • A blocked holding is never also "Recommended".

format_item_line(item)

The first line of a decision item: "Verb Name (TICKER) amount".

v10.8.2 (section 6): never a bare reason. Falls back to the label when the kind has no verb template, so a line is always produced.

Source code in quant/engine/decisions.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def format_item_line(item: dict) -> str:
    """The first line of a decision item: "Verb Name (TICKER) amount".

    v10.8.2 (section 6): never a bare reason. Falls back to the label when the
    kind has no verb template, so a line is always produced.
    """
    kind = str(item.get("verb") or item.get("kind") or "").strip().lower()
    label = str(item.get("label") or _label(item))
    amount = _amount_text(item.get("amount_eur"))
    tpl = _VERB_TEMPLATES.get(kind)
    if tpl is None:
        return label
    if amount:
        return tpl.format(amount=amount, label=label)
    return tpl.format(amount="", label=label).replace("  ", " ").strip()

open_since_line(item)

The 'open since ' state line for a repeated advice (T5).

A repeated item is never byte-identical without showing how long it has been open; an item with no open_since returns an empty string.

Source code in quant/engine/decisions.py
52
53
54
55
56
57
58
59
60
61
def open_since_line(item: dict) -> str:
    """The 'open since <date>' state line for a repeated advice (T5).

    A repeated item is never byte-identical without showing how long it has been
    open; an item with no open_since returns an empty string.
    """
    value = item.get("open_since")
    if value is None:
        return ""
    return ui_copy.ADVICE_OPEN_SINCE.format(date=ui_copy.fmt_date(value))

action_taxonomy.py — the rules behind the ONE list (v10.8.10: the only ones).

One rule set, four kinds of item. Each item is one action with one reason, an evidence pointer, and a horizon (Today / This month):

rebalance an Active or Speculative holding more than REBALANCE_DRIFT_THRESHOLD above its target -> "Sell ~X EUR" (Today; paired with where the money goes), or as far below -> "Buy X EUR" (This month; not in a bear market). Holdings without a target get no drift advice. plan change a Long-term holding more than PLAN_CHANGE_GAP below / above its target -> raise / lower its savings plan (This month). Long-term holdings are never sold. threat Speculative stop-loss / take-profit; a drawdown from cost beyond THREAT_DRAWDOWN; a fall of THREAT_CRASH_7D within 7 days; a trusted score below SCORE_FLOOR (not Long-term); the Speculative part above BETS_MAX; a bear market (once). swap a scored (medium/high confidence) Active/Speculative holding, worth 200 EUR or more (two 1 EUR fees under 1%), trailing the best Idea by more than SWAP_HURDLE; one paired item, and that symbol gets no separate buy/sell.

Sizing laws (:mod:quant.engine.sizing): sells round down to 5 EUR, never below 25 EUR, never from a position under 100 EUR; buys round to 10 EUR.

v10.8.10 replaces advice.build_advice (whose Active buys needed a conviction field that never existed, and whose Long-term items duplicated the plan change here) and the separate alerts engine (a second threat system).

Invariants: pure, no I/O; every item carries verb, symbol, label, amount_eur, reason, horizon, class and evidence.

build(holdings, scores=None, ideas=None, regime=None, budget=None, proceeds=0.0, proceeds_pot=None)

All rules as ONE list, Today before This month.

Source code in quant/engine/action_taxonomy.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
def build(holdings: list[dict] | None, scores: dict | None = None,
          ideas: list[dict] | None = None, regime: Any = None,
          budget: float | None = None, proceeds: float = 0.0,
          proceeds_pot: str | None = None) -> list[dict]:
    """All rules as ONE list, Today before This month."""
    holdings = holdings or []
    swaps = swap_items(holdings, ideas, scores)
    swapped = {str(s["symbol"]) for s in swaps}
    items = [i for i in rebalance_items(holdings, regime, budget=budget)
             if str(i["symbol"]) not in swapped]
    if not swaps:  # a chosen swap spends its own proceeds
        for r in reinvest_items(proceeds, proceeds_pot, holdings):
            same = [i for i in items if i["verb"] == VERB_BUY and r["symbol"]
                    and i["symbol"] == r["symbol"]]
            for i in same:  # one buy per holding: merge free money and proceeds
                items.remove(i)
                r["amount_eur"] = r["amount_eur"] + i["amount_eur"]
            items.append(r)
    items += plan_change_items(holdings)
    items += threat_items(holdings, scores, regime)
    items += swaps
    items.sort(key=lambda i: i["horizon"] != HORIZON_TODAY)   # stable: Today first
    return items

plan_change_items(holdings, gap=PLAN_CHANGE_GAP)

A Long-term holding far off its target: raise or lower its savings plan.

Source code in quant/engine/action_taxonomy.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def plan_change_items(holdings: list[dict] | None,
                      gap: float = PLAN_CHANGE_GAP) -> list[dict]:
    """A Long-term holding far off its target: raise or lower its savings plan."""
    out: list[dict] = []
    for h in holdings or []:
        if _tier(h) != "FORTRESS" or h.get("target_weight") is None:
            continue
        cur, tgt = _num(h.get("current_weight")), _num(h.get("target_weight"))
        sym = str(h.get("symbol"))
        if tgt - cur > gap:
            out.append(_item(
                VERB_PLAN_UP, sym, _label(h), None,
                f"{(tgt - cur) * 100:.0f}pp below its {tgt * 100:.0f}% target.",
                HORIZON_MONTH, "FORTRESS", "Savings plan"))
        elif cur - tgt > gap:
            out.append(_item(
                VERB_PLAN_DOWN, sym, _label(h), None,
                f"{(cur - tgt) * 100:.0f}pp above its {tgt * 100:.0f}% target; "
                "Long-term holdings are never sold.",
                HORIZON_MONTH, "FORTRESS", "Savings plan"))
    return out

rebalance_items(holdings, regime=None, threshold=REBALANCE_DRIFT_THRESHOLD, budget=None)

Drift -> a sized buy (This month) or, far over target, a sell (Today).

v10.13.0: drift is fixed with new money first. A buy fires at threshold under target and is capped by budget (this month's free money plus unspent sale proceeds; None = no plan, uncapped). A sell fires only at SELL_DRIFT_THRESHOLD (or threshold if larger) over target.

Source code in quant/engine/action_taxonomy.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def rebalance_items(holdings: list[dict] | None, regime: Any = None,
                    threshold: float = REBALANCE_DRIFT_THRESHOLD,
                    budget: float | None = None) -> list[dict]:
    """Drift -> a sized buy (This month) or, far over target, a sell (Today).

    v10.13.0: drift is fixed with new money first. A buy fires at ``threshold``
    under target and is capped by ``budget`` (this month's free money plus
    unspent sale proceeds; None = no plan, uncapped). A sell fires only at
    ``SELL_DRIFT_THRESHOLD`` (or ``threshold`` if larger) over target.
    """
    holdings = holdings or []
    sell_at = max(threshold, SELL_DRIFT_THRESHOLD)
    left = budget
    total = sum(_num(h.get("value_eur")) for h in holdings)
    out: list[dict] = []
    for h in holdings:
        tier, tgt = _tier(h), h.get("target_weight")
        if tier not in _ACTIVE_TIERS or tgt is None:
            continue
        cur, tgt = _num(h.get("current_weight")), _num(tgt)
        drift = cur - tgt
        sym, value = str(h.get("symbol")), _num(h.get("value_eur"))
        if drift > sell_at:
            # Never a Long-term holding here (_ACTIVE_TIERS), so only the
            # untouchable and size laws apply.
            amount = (None if sizing.is_untouchable(value)
                      else sizing.sell_amount(drift * total, value))
            if amount is not None:
                out.append(_item(
                    VERB_SELL, sym, _label(h), amount,
                    f"{drift * 100:.0f}pp above its {tgt * 100:.0f}% target.",
                    HORIZON_TODAY, tier, "Holdings analysis"))
        elif -drift > threshold and not (tier == "ALPHA" and _is_bear(regime)):
            amount = sizing.round_buy(-drift * total)
            if left is not None:
                amount = min(amount, sizing.round_down(left, 10.0))
            # Buys are whole 10 EUR steps, so >= 25 and > 25 are the same.
            if amount >= sizing.SELL_MIN_EUR:  # pragma: no mutate
                if left is not None:
                    left -= amount
                out.append(_item(
                    VERB_BUY, sym, _label(h), amount,
                    f"{-drift * 100:.0f}pp below its {tgt * 100:.0f}% target"
                    + (" (from free money)." if budget is not None else "."),
                    HORIZON_MONTH, tier, "Holdings analysis"))
    return out

reinvest_items(proceeds, pot, holdings)

Unspent sale proceeds -> one buy into the pot furthest below target.

Source code in quant/engine/action_taxonomy.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def reinvest_items(proceeds: float, pot: str | None,
                   holdings: list[dict] | None) -> list[dict]:
    """Unspent sale proceeds -> one buy into the pot furthest below target."""
    if proceeds < sizing.SELL_MIN_EUR or pot is None:
        return []
    tier = {"core": "FORTRESS", "active": "ALPHA", "spec": "SPECULATIVE"}[pot]
    word = {"core": "core", "active": "active", "spec": "speculative"}[pot]
    in_pot = [h for h in holdings or [] if _tier(h) == tier]
    best = max(in_pot, key=lambda h: _num(h.get("target_weight"))
               - _num(h.get("current_weight")), default=None)
    amount = sizing.round_down(proceeds, 5.0)
    if best is None:
        return [_item(VERB_BUY, None, f"the {word} pot", amount,
                      f"money from your sales; the {word} pot is furthest below "
                      "its target.", HORIZON_MONTH, tier, "Sale proceeds")]
    return [_item(VERB_BUY, str(best.get("symbol")), _label(best), amount,
                  f"money from your sales goes to the {word} pot, furthest below "
                  "its target.", HORIZON_MONTH, tier, "Sale proceeds")]

swap_items(holdings, ideas, scores=None, hurdle=SWAP_HURDLE)

A scored Active/Speculative holding that trails the best idea after the hurdle.

Source code in quant/engine/action_taxonomy.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def swap_items(holdings: list[dict] | None, ideas: list[dict] | None,
               scores: dict | None = None, hurdle: float = SWAP_HURDLE) -> list[dict]:
    """A scored Active/Speculative holding that trails the best idea after the hurdle."""
    scores = scores or {}
    out: list[dict] = []
    ideas = ideas or []
    for h in holdings or []:
        tier = _tier(h)
        if tier not in _ACTIVE_TIERS:
            continue
        sym = str(h.get("symbol"))
        s = scores.get(sym) or {}
        held = _score_of({**h, **s})
        if held is None:
            continue  # an unscored holding is never swapped on a fake 0
        if str(s.get("confidence") or "medium") not in ("medium", "high"):
            continue  # a low-confidence score is too unsure to pay two fees on
        if 2 * ACTIVE_TRADE_FEE_EUR > SWAP_MAX_FEE_SHARE * _num(h.get("value_eur")):
            continue  # the sell + buy fees would eat more than 1% of the position
        best = max((i for i in ideas if str(i.get("symbol")) != sym),
                   key=lambda i: _num(_score_of(i)), default=None)
        if best is None:
            continue
        best_score = _num(_score_of(best))
        if best_score - _num(held) <= hurdle * 100.0:
            continue
        out.append(_item(
            VERB_SWAP, sym, _label(h), _num(h.get("value_eur")),
            f"{_label(best)} scores {best_score:.0f} vs {_num(held):.0f} for "
            f"{_label(h)}, more than the fee/tax hurdle.",
            HORIZON_TODAY, tier, "Research",
        ) | {"target_symbol": str(best.get("symbol")), "target_name": best.get("name")})
    return out

threat_items(holdings, scores=None, regime=None)

Price, score and market threats (one item per holding at most).

Source code in quant/engine/action_taxonomy.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def threat_items(holdings: list[dict] | None, scores: dict | None = None,
                 regime: Any = None) -> list[dict]:
    """Price, score and market threats (one item per holding at most)."""
    scores = scores or {}
    holdings = holdings or []
    out: list[dict] = []
    for h in holdings:
        sym, tier = str(h.get("symbol")), _tier(h)
        pnl = h.get("pnl_pct")
        change_7d = h.get("change_7d")
        reason = None
        if tier == "SPECULATIVE" and pnl is not None and pnl <= SPEC_STOP:
            reason = f"stop-loss hit ({pnl * 100:.0f}%)."
        elif tier == "SPECULATIVE" and pnl is not None and pnl >= SPEC_TAKE:
            reason = f"take-profit hit (+{pnl * 100:.0f}%)."
        elif tier != "FORTRESS" and pnl is not None and pnl <= -THREAT_DRAWDOWN:
            reason = f"down {abs(pnl) * 100:.0f}% from what you paid."
        elif change_7d is not None and change_7d <= -THREAT_CRASH_7D:
            reason = f"fell {abs(change_7d) * 100:.0f}% in the last 7 days."
        else:
            s = scores.get(sym) or {}
            comp = _score_of(s)
            trusted = str(s.get("confidence") or "medium") in ("medium", "high")
            if (comp is not None and trusted and tier != "FORTRESS"
                    and _num(comp) < SCORE_FLOOR):
                reason = f"score {_num(comp):.0f} below the {SCORE_FLOOR:.0f} floor."
        if reason is not None:
            out.append(_item(VERB_THREAT, sym, _label(h), None, reason,
                             HORIZON_TODAY, tier, "Holdings analysis"))
    total = sum(_num(h.get("value_eur")) for h in holdings)
    spec = sum(_num(h.get("value_eur")) for h in holdings if _tier(h) == "SPECULATIVE")
    if total > 0 and spec / total > BETS_MAX:
        out.append(_item(VERB_THREAT, None, "the Speculative part", None,
                         f"{spec / total * 100:.0f}% of your money, above the "
                         f"{BETS_MAX:.0%} cap.", HORIZON_TODAY, "SPECULATIVE",
                         "Holdings analysis"))
    if _is_bear(regime):
        out.append(_item(VERB_THREAT, None, "the Active part", None,
                         "the market is falling; no new Active buys, review risk.",
                         HORIZON_TODAY, "ALPHA", "Market"))
    return out

watch_lines(holdings, scores=None, ideas=None, hurdle=SWAP_HURDLE)

How close each holding is to an action, in one line each. Pure.

Shows what the rules are watching even when the ONE list is empty: for an Active/Speculative holding, the best idea it could be swapped for and the score a swap needs; for every holding, the drawdown alert distance.

Source code in quant/engine/action_taxonomy.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def watch_lines(holdings: list[dict] | None, scores: dict | None = None,
                ideas: list[dict] | None = None, hurdle: float = SWAP_HURDLE) -> list[str]:
    """How close each holding is to an action, in one line each. Pure.

    Shows what the rules are watching even when the ONE list is empty: for an
    Active/Speculative holding, the best idea it could be swapped for and the
    score a swap needs; for every holding, the drawdown alert distance.
    """
    scores = scores or {}
    ideas = ideas or []
    out: list[str] = []
    for h in holdings or []:
        sym, tier = str(h.get("symbol")), _tier(h)
        parts: list[str] = []
        held = _score_of({**h, **(scores.get(sym) or {})})
        if held is not None:
            parts.append(f"score {_num(held):.0f}")
        pnl = h.get("pnl_pct")
        if pnl is not None and tier != "FORTRESS":
            parts.append(f"{pnl * 100:+.0f}% vs paid (alert at -{THREAT_DRAWDOWN * 100:.0f}%)")
        if tier in _ACTIVE_TIERS and held is not None:
            best = max((i for i in ideas if str(i.get("symbol")) != sym),
                       key=lambda i: _num(_score_of(i)), default=None)
            if best is not None:
                need = _num(held) + hurdle * 100.0
                parts.append(f"best alternative {best.get('symbol')} "
                             f"{_num(_score_of(best)):.0f} (swap above {need:.0f})")
        if parts:
            out.append(f"{_label(h)}: " + ", ".join(parts))
    return out

pairing.py — pair a sell with where its proceeds go (v10.8.4, T5; v10.8.7, R-C1).

Intent: the ONE list must never tell the user to sell without saying what to do with the money. Every sell item proposes its proceeds routing inside the SAME item, by this fixed priority:

  1. top up the largest UNDERWEIGHT holding vs its target (the gap in points);
  2. else the highest-score idea (a watched symbol at or above IDEA_FLOOR; the caller passes the idea list);
  3. else hold the proceeds at the broker, untracked (v10.8.7, R-C1: there is no tracked-cash target; the only permitted trace of cash is this reasoned line).

The result renders as one line, for example: "Sell ~65 EUR of Nasdaq 100 (SXRV.DE) -> buy MSCI World (EUNL.DE), 4pp under target".

Invariants
  • Pure: no I/O.
  • Never proposes selling to buy the same symbol.
  • Deterministic: ties break by the larger gap, then alphabetically.

best_idea(candidates, held, exclude='')

The highest-score candidate idea not already a holding. None if none.

Source code in quant/engine/pairing.py
68
69
70
71
72
73
74
75
76
77
78
79
80
def best_idea(candidates: list[dict] | None, held: set, exclude: str = "") -> dict | None:
    """The highest-score candidate idea not already a holding. None if none."""
    best: dict | None = None
    best_score = float("-inf")
    for c in candidates or []:
        sym = str(c.get("symbol") or "")
        if not sym or sym == exclude or sym in held:
            continue
        score = _num(c.get("score"), float("-inf"))
        if score > best_score:
            best_score = score
            best = c
    return best

largest_underweight(holdings, exclude='')

The held symbol furthest below its target (by value gap). None if none.

Source code in quant/engine/pairing.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def largest_underweight(holdings: list[dict], exclude: str = "") -> dict | None:
    """The held symbol furthest below its target (by value gap). None if none."""
    best: dict | None = None
    best_gap = 0.0
    for h in holdings or []:
        sym = str(h.get("symbol") or "")
        if not sym or sym == exclude or h.get("target_weight") is None:
            continue
        current = _num(h.get("current_weight"))
        target = _num(h.get("target_weight"))
        gap = target - current
        if gap <= 1e-9:
            continue
        # Tie-break: larger gap wins; equal gaps break alphabetically.
        if (gap > best_gap + 1e-12
                or (abs(gap - best_gap) <= 1e-12 and best is not None
                    and sym < str(best.get("symbol")))):
            best_gap = gap
            best = {**h, "gap": gap}
    return best

paired_line(sell, holdings=None, candidates=None)

The full one-line pairing for a sell item (T5).

sell carries label (the "Name (TICKER)" form) and amount_eur.

Source code in quant/engine/pairing.py
112
113
114
115
116
117
118
119
120
121
def paired_line(sell: dict, holdings: list[dict] | None = None,
                candidates: list[dict] | None = None) -> str:
    """The full one-line pairing for a sell item (T5).

    ``sell`` carries ``label`` (the "Name (TICKER)" form) and ``amount_eur``.
    """
    amount = _num(sell.get("amount_eur"))
    label = str(sell.get("label") or _label(sell))
    route = route_sell(sell, holdings, candidates)
    return f"Sell ~{amount:.0f} EUR of {label} -> {route['text']}"

route_sell(sell, holdings=None, candidates=None)

Where a sell's proceeds should go. Returns {kind, symbol, text}.

Priority: underweight holding -> best idea -> hold proceeds at the broker (untracked). v10.8.7 (R-C1): there is no tracked-cash target.

Source code in quant/engine/pairing.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def route_sell(sell: dict, holdings: list[dict] | None = None,
               candidates: list[dict] | None = None) -> dict:
    """Where a sell's proceeds should go. Returns ``{kind, symbol, text}``.

    Priority: underweight holding -> best idea -> hold proceeds at the broker
    (untracked). v10.8.7 (R-C1): there is no tracked-cash target.
    """
    holdings = holdings or []
    exclude = str(sell.get("symbol") or "")
    held = {str(h.get("symbol") or "") for h in holdings}

    under = largest_underweight(holdings, exclude=exclude)
    if under is not None:
        pp = under["gap"] * 100.0
        text = f"buy {_label(under)}, {pp:.0f}pp under target"
        return {"kind": ROUTE_UNDERWEIGHT, "symbol": under.get("symbol"),
                "name": under.get("name"), "text": text}

    idea = best_idea(candidates, held, exclude=exclude)
    if idea is not None:
        text = f"buy {_label(idea)}, top idea"
        return {"kind": ROUTE_IDEA, "symbol": idea.get("symbol"),
                "name": idea.get("name"), "text": text}

    return {"kind": ROUTE_HOLD, "symbol": None,
            "text": "no underweight holding or idea to buy; hold proceeds at "
                    "the broker, untracked"}

advice_state.py — the stateful advice log (v10.8.4, T5).

Intent: advice is a persisted object, not a pure re-computation. Before v10.8.4 the same single sell advice repeated verbatim every day forever, with no record of how long it had been open. This module reconciles the freshly computed advice against the advice_log table:

  • an item not yet open is inserted with open_since = today;
  • an item already open keeps its original open_since (so the UI can say "open since ");
  • an item no longer produced is closed (status closed), so the list stops repeating it and History shows the advice log;
  • an item the user marks done (status done, done_at) stays hidden for SNOOZE_DAYS even if the rules still produce it.

Identity is (verb, symbol, horizon): the same recommendation for the same thing in the same time bucket is one open object.

Only the writers (daily job, confirm, refresh, via :func:quant.engine.today_list.persist) call :func:sync; the render path calls the read-only :func:annotate (v10.8.10, R-C4).

Invariants
  • sync never raises; on failure it returns the items unchanged.
  • Only open rows are returned by :func:open_items; a done row disappears from the active list but stays in History.

annotate(items, as_of=None, conn=None)

Read-only twin of :func:sync for the render path (v10.8.10, R-C4).

Enriches each item with the id / open_since of its open log row; an item the writers have not persisted yet gets id=None and open_since=as_of; an item marked done within SNOOZE_DAYS is dropped. Never writes, never raises.

Source code in quant/engine/advice_state.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def annotate(items: list[dict] | None, as_of: date | None = None,
             conn: Any = None) -> list[dict]:
    """Read-only twin of :func:`sync` for the render path (v10.8.10, R-C4).

    Enriches each item with the ``id`` / ``open_since`` of its open log row; an
    item the writers have not persisted yet gets ``id=None`` and
    ``open_since=as_of``; an item marked done within ``SNOOZE_DAYS`` is dropped.
    Never writes, never raises.
    """
    as_of = as_of or date.today()
    open_by_key = {_key(r): r for r in open_items(conn)}
    snoozed = _recently_done(conn, as_of)
    out: list[dict] = []
    for item in items or []:
        if _key(item) in snoozed:
            continue
        found = open_by_key.get(_key(item))
        enriched = dict(item)
        enriched["id"] = found["id"] if found else None
        enriched["open_since"] = (found.get("open_since") if found else None) or as_of
        out.append(enriched)
    return out

history(conn=None, limit=200)

The advice log for the History page (newest first).

Source code in quant/engine/advice_state.py
203
204
205
206
207
208
209
210
def history(conn: Any = None, limit: int = 200) -> list[dict]:
    """The advice log for the History page (newest first)."""
    rows = _query(conn, "SELECT id, verb, symbol, amount_eur, reason, horizon, "
                        "class, created_at, open_since, status FROM advice_log "
                        "ORDER BY created_at DESC LIMIT ?", [int(limit)])
    return [{"id": int(r[0]), "verb": r[1], "symbol": r[2], "amount_eur": r[3],
             "reason": r[4], "horizon": r[5], "class": r[6], "created_at": r[7],
             "open_since": r[8], "status": r[9]} for r in rows]

mark_done(conn, advice_id)

Mark one advice done (it stops repeating; History keeps it).

Source code in quant/engine/advice_state.py
181
182
183
184
185
186
187
188
189
190
def mark_done(conn: Any, advice_id: int | None) -> bool:
    """Mark one advice done (it stops repeating; History keeps it)."""
    if conn is None or advice_id is None:
        return False
    try:
        conn.execute("UPDATE advice_log SET status = ?, done_at = now() WHERE id = ?",
                     [STATUS_DONE, int(advice_id)])
        return True
    except Exception:  # noqa: BLE001
        return False

mark_item_done(conn, item, as_of=None)

Mark one item done, logging it first if the writers have not yet (user click).

Source code in quant/engine/advice_state.py
155
156
157
158
159
160
161
162
163
def mark_item_done(conn: Any, item: dict, as_of: date | None = None) -> bool:
    """Mark one item done, logging it first if the writers have not yet (user click)."""
    if conn is None:
        return False
    rid = item.get("id")
    if rid is None:
        found = {_key(r): r for r in open_items(conn)}.get(_key(item))
        rid = found["id"] if found else _insert(conn, item, as_of or date.today())
    return mark_done(conn, rid)

open_items(conn=None)

The currently open advice rows.

Source code in quant/engine/advice_state.py
193
194
195
196
197
198
199
200
def open_items(conn: Any = None) -> list[dict]:
    """The currently open advice rows."""
    rows = _query(conn, "SELECT id, verb, symbol, amount_eur, reason, horizon, "
                        "class, open_since FROM advice_log WHERE status = ? "
                        "ORDER BY open_since", [STATUS_OPEN])
    return [{"id": int(r[0]), "verb": r[1], "symbol": r[2], "amount_eur": r[3],
             "reason": r[4], "horizon": r[5], "class": r[6], "open_since": r[7]}
            for r in rows]

sync(conn, items, as_of=None)

Persist items and return them enriched with id/open_since.

items are the actionable records (each has verb, symbol, horizon, amount_eur, reason, class). Items no longer present are closed.

Source code in quant/engine/advice_state.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def sync(conn: Any, items: list[dict] | None, as_of: date | None = None) -> list[dict]:
    """Persist ``items`` and return them enriched with ``id``/``open_since``.

    ``items`` are the actionable records (each has verb, symbol, horizon,
    amount_eur, reason, class). Items no longer present are closed.
    """
    as_of = as_of or date.today()
    items = list(items or [])
    if conn is None:
        return items
    try:
        existing = conn.execute(
            "SELECT id, verb, symbol, horizon, open_since FROM advice_log "
            "WHERE status = ?", [STATUS_OPEN]).fetchall()
    except Exception:  # noqa: BLE001
        return items
    snoozed = _recently_done(conn, as_of)
    items = [i for i in items if _key(i) not in snoozed]
    open_by_key: dict = {}
    for rid, verb, symbol, horizon, open_since in existing:
        open_by_key[(str(verb or ""), str(symbol or ""), str(horizon or ""))] = (
            int(rid), open_since)

    seen: set = set()
    out: list[dict] = []
    for item in items:
        k = _key(item)
        seen.add(k)
        found = open_by_key.get(k)
        if found is None:
            rid = _insert(conn, item, as_of)
            enriched = dict(item)
            enriched["id"] = rid
            enriched["open_since"] = as_of
            out.append(enriched)
        else:
            rid, open_since = found
            try:
                conn.execute(
                    "UPDATE advice_log SET amount_eur = ?, reason = ?, class = ? "
                    "WHERE id = ?",
                    [item.get("amount_eur"), str(item.get("reason") or ""),
                     str(item.get("class") or ""), rid])
            except Exception:  # noqa: BLE001
                pass
            enriched = dict(item)
            enriched["id"] = rid
            enriched["open_since"] = open_since or as_of
            out.append(enriched)

    # Close the items no longer produced.
    for k, (rid, _open_since) in open_by_key.items():
        if k not in seen:
            try:
                conn.execute(
                    "UPDATE advice_log SET status = ? WHERE id = ?",
                    [STATUS_CLOSED, rid])
            except Exception:  # noqa: BLE001
                pass
    return out

weights.py — the ONE weight math (v10.8.7, T3/R-C3).

Intent: a single pair of functions produces instrument and class weights on the invested-only basis. Every consumer (Holdings table, class table, decision drift, invest plan) calls them; no local weight computation exists anywhere else.

Invariants
  • Pure: no I/O.
  • Weights are fractions of the invested pool (sum to 1.0 when invested > 0).
  • Cash is not an entity (R-C1): the basis is the sum of invested values only.

class_weights(holdings=None, as_of=None)

The invested-only weight per class (FORTRESS / ALPHA / SPECULATIVE). Pure.

Returns {class: fraction}; all zeros when nothing is invested.

Source code in quant/engine/weights.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def class_weights(holdings: list[dict] | None = None,
                  as_of=None) -> dict[str, float]:
    """The invested-only weight per class (FORTRESS / ALPHA / SPECULATIVE). Pure.

    Returns ``{class: fraction}``; all zeros when nothing is invested.
    """
    holdings = holdings or []
    total = sum(_num(h.get("value_eur")) for h in holdings)
    out = {c: 0.0 for c in CLASS_ORDER}
    if total <= 0:
        return out
    for h in holdings:
        tier = str(h.get("tier", "ALPHA")).upper()
        if tier in out:
            out[tier] += _num(h.get("value_eur"))
    return {c: v / total for c, v in out.items()}

instrument_weights(holdings=None, as_of=None)

The invested-only weight per symbol. Pure.

Returns {symbol: fraction}; empty when nothing is invested. as_of is accepted for a future date-based read; today the live holdings are the basis.

Source code in quant/engine/weights.py
25
26
27
28
29
30
31
32
33
34
35
36
37
def instrument_weights(holdings: list[dict] | None = None,
                       as_of=None) -> dict[str, float]:
    """The invested-only weight per symbol. Pure.

    Returns ``{symbol: fraction}``; empty when nothing is invested. ``as_of`` is
    accepted for a future date-based read; today the live holdings are the basis.
    """
    holdings = holdings or []
    total = sum(_num(h.get("value_eur")) for h in holdings)
    if total <= 0:
        return {}
    return {str(h.get("symbol")): _num(h.get("value_eur")) / total
            for h in holdings if h.get("symbol")}

sizing.py — Sizing rules for every advice (v10.7.0, Section 6).

Intent: the old system said "sell 200 EUR" of a 143 EUR position. These laws are absolute and every advice path must route through them.

Laws
  1. FORTRESS never sells: the rules only size sells for Active and Speculative holdings (quant.engine.action_taxonomy).
  2. Sell amount = min(drift, value - 1 EUR), rounded DOWN to 5 EUR steps. Below 25 EUR, no advice (fee relevance).
  3. A position below 100 EUR is untouchable (never emit a sell advice).
  4. Buy amounts round to 10 EUR steps.

Invariants: pure functions, no I/O.

is_untouchable(position_value_eur)

True when a position is too small for a sale to be worth the fee.

Source code in quant/engine/sizing.py
38
39
40
41
42
43
def is_untouchable(position_value_eur: float) -> bool:
    """True when a position is too small for a sale to be worth the fee."""
    try:
        return float(position_value_eur) < UNTOUCHABLE_POSITION_EUR
    except (TypeError, ValueError):
        return True

round_buy(amount_eur)

Round a buy amount to 10 EUR steps (down).

Source code in quant/engine/sizing.py
65
66
67
def round_buy(amount_eur: float) -> float:
    """Round a buy amount to 10 EUR steps (down)."""
    return round_down(amount_eur, BUY_ROUND_STEP_EUR)

round_down(value, step)

Round value down to the nearest step (never above value).

Source code in quant/engine/sizing.py
29
30
31
32
33
34
35
def round_down(value: float, step: float) -> float:
    """Round ``value`` down to the nearest ``step`` (never above value)."""
    if step <= 0:
        return float(value)
    # Round the quotient first: 0.6 - 0.4 is 0.19999... in floating point, and
    # 20% of 1000 EUR must round to 200, not 195.
    return math.floor(round(float(value) / step, 9)) * step

sell_amount(drift_eur, position_value_eur)

Suggested sell EUR, or None when the law forbids it.

amount = min(drift, value - 1 EUR), rounded down to 5 EUR steps; None when the result is below 25 EUR (which also covers a zero or negative drift or value).

Source code in quant/engine/sizing.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def sell_amount(drift_eur: float, position_value_eur: float) -> float | None:
    """Suggested sell EUR, or None when the law forbids it.

    amount = min(drift, value - 1 EUR), rounded down to 5 EUR steps; None when
    the result is below 25 EUR (which also covers a zero or negative drift or
    value).
    """
    try:
        drift = float(drift_eur)
        value = float(position_value_eur)
    except (TypeError, ValueError):
        return None
    amount = min(drift, value - 1.0)
    amount = round_down(amount, SELL_ROUND_STEP_EUR)
    if amount < SELL_MIN_EUR:
        return None
    return amount

Daily job and Telegram digest

daily.py — the daily job body, catch-up, and last-run marker (v10.7.0, Section 3).

Intent: merely owning a powered-on laptop is enough. The systemd timer runs quant daily at 18:45 and 07:45. Each run is idempotent and guarded by the runner lock; weekends are skipped. A run: refresh (prices with missed days, fundamentals, news), the analysis chain (regime, scores), the valuation store, the ONE list (persisted to the advice log), the day's digest written to outputs/daily_<date>.md, and, from the morning slot, the digest sent to Telegram once per price date.

Catch-up: if the previous run was more than one trading day ago, the run is a catch-up; every summary artifact gains the exact line "Monitoring gap: no runs for N days; conditions evaluated on the latest data."

Invariants
  • run_daily never raises; returns a DailyResult.
  • A weekend writes nothing and returns status "skipped".
  • The heavy steps (update, scoring) are injectable for tests.

DailyResult dataclass

Outcome of a daily run.

Source code in quant/engine/daily.py
36
37
38
39
40
41
42
43
44
45
@dataclass
class DailyResult:
    """Outcome of a daily run."""

    status: str  # "ok" | "skipped" | "error"
    message: str
    items: int = 0
    gap_days: int | None = None
    invested_eur: float | None = None
    digest_sent: bool = False

clear_last_failed_run()

Remove the failed-run marker after a successful run. Never raises.

Source code in quant/engine/daily.py
104
105
106
107
108
109
def clear_last_failed_run() -> None:
    """Remove the failed-run marker after a successful run. Never raises."""
    try:
        os.remove(failed_marker_path())
    except Exception:  # noqa: BLE001
        pass

failed_marker_path()

Absolute path of the last-failed-run marker file.

Source code in quant/engine/daily.py
78
79
80
def failed_marker_path() -> str:
    """Absolute path of the last-failed-run marker file."""
    return os.path.join(str(paths.OUTPUTS_DIR), FAILED_MARKER_NAME)

gap_line(gap_days)

The exact monitoring-gap sentence, or None when there is no gap.

Source code in quant/engine/daily.py
148
149
150
151
152
153
154
def gap_line(gap_days: int | None) -> str | None:
    """The exact monitoring-gap sentence, or None when there is no gap."""
    from quant.ui import copy as ui_copy

    if gap_days is None or gap_days <= 1:
        return None
    return ui_copy.MONITORING_GAP.format(n=gap_days)

is_trading_day(when)

Weekend-only rule: Saturday and Sunday are non-trading days.

Source code in quant/engine/daily.py
121
122
123
def is_trading_day(when: date) -> bool:
    """Weekend-only rule: Saturday and Sunday are non-trading days."""
    return when.weekday() < 5

marker_path()

Absolute path of the last-daily-run marker file.

Source code in quant/engine/daily.py
48
49
50
def marker_path() -> str:
    """Absolute path of the last-daily-run marker file."""
    return os.path.join(str(paths.OUTPUTS_DIR), MARKER_NAME)

monitoring_gap_days(today=None)

Calendar days since the last run; None when never run.

Source code in quant/engine/daily.py
112
113
114
115
116
117
118
def monitoring_gap_days(today: date | None = None) -> int | None:
    """Calendar days since the last run; None when never run."""
    last = read_last_daily_run()
    if last is None:
        return None
    today = today or date.today()
    return max(0, (today - last).days)

previous_trading_day(when)

The trading day before when (weekend-only rule).

Source code in quant/engine/daily.py
126
127
128
129
130
131
def previous_trading_day(when: date) -> date:
    """The trading day before ``when`` (weekend-only rule)."""
    prev = when - timedelta(days=1)
    while not is_trading_day(prev):
        prev -= timedelta(days=1)
    return prev

read_last_daily_run()

The date of the last successful daily run, or None when never run.

Source code in quant/engine/daily.py
53
54
55
56
57
58
59
def read_last_daily_run() -> date | None:
    """The date of the last successful daily run, or None when never run."""
    try:
        with open(marker_path(), encoding="utf-8") as f:
            return date.fromisoformat(f.read().strip()[:10])
    except Exception:  # noqa: BLE001
        return None

read_last_failed_run()

The last failed run as {reason, at}, or None when there is none.

Source code in quant/engine/daily.py
 94
 95
 96
 97
 98
 99
100
101
def read_last_failed_run() -> dict | None:
    """The last failed run as {reason, at}, or None when there is none."""
    try:
        with open(failed_marker_path(), encoding="utf-8") as f:
            data = json.load(f)
        return data if isinstance(data, dict) else None
    except Exception:  # noqa: BLE001
        return None

run_daily(today=None, *, update_fn=None, notify=True, conn=None)

Run the daily job. Idempotent; never raises.

update_fn: the market-data refresh (default: none, for tests). notify: send the morning digest (it still sends at most once per price date).

Source code in quant/engine/daily.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def run_daily(
    today: date | None = None,
    *,
    update_fn: Callable[[], Any] | None = None,
    notify: bool = True,
    conn: Any = None,
) -> DailyResult:
    """Run the daily job. Idempotent; never raises.

    update_fn: the market-data refresh (default: none, for tests).
    notify: send the morning digest (it still sends at most once per price date).
    """
    today = today or date.today()
    if not is_trading_day(today):
        return DailyResult("skipped", "non-trading day, skipped")

    from quant.data.database import get_connection

    if conn is None:
        try:
            conn = get_connection()
        except Exception:  # noqa: BLE001
            # v10.7.2 (Part 1.3): never crash with a traceback. Write the plain
            # reason, exit quietly, and let the morning slot retry.
            from quant.ui import copy as ui_copy

            write_last_failed_run(ui_copy.DB_BUSY_RETRY)
            return DailyResult("error", ui_copy.DB_BUSY_RETRY)
    gap = monitoring_gap_days(today)

    try:
        if update_fn is not None:
            update_fn()
    except Exception:  # noqa: BLE001
        pass

    # v10.8.7 (T2): the analysis chain (regime, scores, run manifest), then the
    # mark-to-market valuation store (idempotent).
    try:
        from quant.engine import analysis, mtm
        from quant.engine import manifest as manifest_mod

        analysis.run_analysis(conn)
        res = mtm.backfill(conn, source=mtm.SOURCE_DAILY)
        written = res.get("rows", 0)
        run_id = manifest_mod.latest_run_id(conn) or manifest_mod.new_run_id()
        manifest_mod.record_stage(
            conn, run_id, "valuation", manifest_mod.STATUS_OK,
            coverage=manifest_mod.coverage_text((written, written)))
    except Exception:  # noqa: BLE001
        pass

    # The ONE list from the fresh data: persisted (advice log), written to the
    # daily artifact, and sent as the morning digest (v10.8.10).
    from quant.engine import notify as notify_mod
    from quant.engine.holdings_view import holdings_view
    from quant.engine.mtm import latest_total
    from quant.engine.today_list import build_items, persist
    from quant.reporting.artifacts import read_regime

    persist(conn)
    holdings = holdings_view(conn)
    items = build_items(holdings, regime=read_regime())
    total = latest_total(conn)
    result = DailyResult(
        status="ok",
        message=f"daily run complete: {len(items)} item(s) on the list",
        items=len(items),
        gap_days=gap,
        invested_eur=total.get("value_eur") if total else None,
    )
    try:
        snap = notify_mod.digest_snapshot(conn, items, holdings, today)
        _write_daily_artifact(today, result, notify_mod.build_digest(snap))
    except Exception:  # noqa: BLE001
        _write_daily_artifact(today, result, "")
    if notify:
        result.digest_sent = notify_mod.send_daily_digest(conn, items, holdings, today)

    write_last_daily_run(today)
    clear_last_failed_run()
    return result

staleness_status(today=None)

One-line status when the last run is older than the previous trading day.

Returns None when the data is current. Used by the app-open fallback.

Source code in quant/engine/daily.py
134
135
136
137
138
139
140
141
142
143
144
145
def staleness_status(today: date | None = None) -> str | None:
    """One-line status when the last run is older than the previous trading day.

    Returns None when the data is current. Used by the app-open fallback.
    """
    today = today or date.today()
    last = read_last_daily_run()
    if last is None:
        return "Updating market data, no previous run."
    if last < previous_trading_day(today):
        return f"Updating market data, last run was {(today - last).days} days ago"
    return None

write_last_daily_run(when=None)

Record the date of a successful daily run. Never raises.

Source code in quant/engine/daily.py
62
63
64
65
66
67
68
69
70
def write_last_daily_run(when: date | None = None) -> None:
    """Record the date of a successful daily run. Never raises."""
    when = when or date.today()
    try:
        os.makedirs(str(paths.OUTPUTS_DIR), exist_ok=True)
        with open(marker_path(), "w", encoding="utf-8") as f:
            f.write(when.isoformat())
    except Exception:  # noqa: BLE001
        pass

write_last_failed_run(reason, when=None)

Record a failed run with its plain reason. Never raises.

Source code in quant/engine/daily.py
83
84
85
86
87
88
89
90
91
def write_last_failed_run(reason: str, when: datetime | None = None) -> None:
    """Record a failed run with its plain reason. Never raises."""
    when = when or datetime.now()
    try:
        os.makedirs(str(paths.OUTPUTS_DIR), exist_ok=True)
        with open(failed_marker_path(), "w", encoding="utf-8") as f:
            json.dump({"reason": reason, "at": when.isoformat(timespec="seconds")}, f)
    except Exception:  # noqa: BLE001
        pass

notify.py — Telegram: the daily analysis digest and the Settings test message.

Intent: the phone is where Trade Republic lives. Once per trading day the 07:45 run (after every market of the previous day has closed) sends ONE plain-text message: portfolio value and change, the market trend, the ONE list (Today / This month), each holding against its target with its score, up to three notable headlines for the holdings, and any data problem. It is sent even when there is nothing to do ("Nothing to do"), because it is also the analysis. Deduplicated by price date: a re-run for the same prices never resends.

v10.8.10 replaces three senders: an uncapped briefing on every quant run, one message per level-triggered alert, and a "list changed" rule that was never wired up.

Invariants
  • send never raises; returns True only on a real 2xx response.
  • At most one digest per price date.
  • The bot token never appears in any log or exception message.

build_digest(snap)

The digest text from a snapshot (see :func:digest_snapshot). Pure.

Source code in quant/engine/notify.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def build_digest(snap: dict) -> str:
    """The digest text from a snapshot (see :func:`digest_snapshot`). Pure."""
    from quant.engine.decisions import format_item_line
    from quant.ui import copy as C

    lines = [f"Quant-AI · {C.fmt_date(snap['today'])}"
             + (f" (prices of {C.fmt_date(snap['prices_date'])})"
                if snap.get("prices_date") else "")]
    if snap.get("total") is not None:
        _icon, _color, badge = C.delta_badge(snap.get("day_eur"), snap.get("day_pct"))
        since = snap.get("since_pct")
        lines.append(f"Portfolio {_fmt_eur(snap['total'])} · day {badge}"
                     + (f" · since first purchase {since:+.1f}%" if since is not None
                        else ""))
    if snap.get("regime_word"):
        lines.append(f"Market: {snap['regime_word']}")
    if snap.get("savings"):
        lines.append("")
        lines.append("Savings plan:")
        lines += [f"- {x}" for x in snap["savings"]]
    if snap.get("month"):
        lines.append("")
        lines.append("This month:")
        lines += [f"- {x}" for x in snap["month"]]
    if snap.get("coming_up"):
        lines.append("")
        lines.append("Coming up:")
        lines += [f"- {x}" for x in snap["coming_up"]]
    items = snap.get("items") or []
    lines.append("")
    if not items:
        lines.append("Nothing to do.")
    for horizon in (C.HORIZON_TODAY, C.HORIZON_MONTH):
        group = [i for i in items if i.get("horizon") == horizon][:MAX_ITEMS]
        if group:
            lines.append(f"{horizon}:")
            lines += [f"- {format_item_line(i)}: {i.get('reason') or ''}".rstrip(": ")
                      for i in group]
    if snap.get("watch"):
        lines.append("")
        lines.append("Watching:")
        lines += [f"- {w}" for w in snap["watch"]]
    elif snap.get("holdings"):
        lines.append("")
        lines.append("Holdings:")
        lines += [f"- {h}" for h in snap["holdings"]]
    if snap.get("news"):
        lines.append("")
        lines.append("News:")
        lines += [f"- {n}" for n in snap["news"][:MAX_NEWS]]
    if snap.get("issues"):
        lines.append("")
        lines += [f"Note: {i}" for i in snap["issues"]]
    return "\n".join(lines)

digest_snapshot(conn, items, holdings, today=None)

Collect the digest inputs from the stores (reads only).

Source code in quant/engine/notify.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def digest_snapshot(conn: Any, items: list[dict], holdings: list[dict],
                    today: date | None = None) -> dict:
    """Collect the digest inputs from the stores (reads only)."""
    from quant.engine import mtm
    from quant.portfolio.regime_constraints import regime_key
    from quant.reporting.artifacts import read_regime, read_score_row
    from quant.ui import copy as C

    today = today or date.today()
    total = mtm.latest_total(conn)
    day_eur, day_pct, _d = mtm.day_delta(conn)
    since = _since_first_purchase(conn, holdings)
    regime = read_regime()
    key = regime_key(regime)
    rows = []
    for h in sorted(holdings, key=lambda x: -float(x.get("value_eur") or 0)):
        tgt = h.get("target_weight")
        score = (read_score_row(str(h["symbol"])) or {}).get("composite")
        now_pct = float(h.get("current_weight") or 0) * 100
        rows.append(f"{h.get('name') or h['symbol']}: {now_pct:.0f}%"
                    + (f" (target {float(tgt) * 100:.0f}%)" if tgt is not None else "")
                    + (f", score {float(score):.0f}" if score is not None else ""))
    news = []
    held = [str(h["symbol"]) for h in holdings]
    if held:
        marks = ",".join("?" for _ in held)
        try:
            for sym, title, score in conn.execute(
                    "SELECT symbol, title, score FROM nlp_evidence WHERE symbol IN "
                    f"({marks}) AND score IS NOT NULL "
                    # published, not fetched: an old story fetched today is not news
                    "AND COALESCE(published_at, retrieved_at) >= ? "
                    "ORDER BY abs(score) DESC LIMIT ?",
                    [*held, datetime.combine(today, datetime.min.time())
                     - timedelta(days=2), MAX_NEWS]).fetchall():
                tone = "positive" if score > 0.15 else "negative" if score < -0.15 else "neutral"
                news.append(f"{sym}: {title} ({tone})")
        except Exception:  # noqa: BLE001
            news = []
    issues = []
    try:
        for stage, status, error in conn.execute(
                "SELECT stage, status, error FROM run_manifest WHERE run_id = "
                "(SELECT MAX(run_id) FROM run_manifest) AND status IN ('failed','missing')"
        ).fetchall():
            issues.append(f"{stage} {status}" + (f" ({error})" if error else ""))
    except Exception:  # noqa: BLE001
        issues = []
    return {"today": today, "prices_date": total.get("date"),
            "total": total.get("value_eur") if total else None,
            "day_eur": day_eur, "day_pct": day_pct,
            "since_pct": None if since is None else since * 100.0,
            "savings": _savings_lines(conn, today),
            "coming_up": _coming_up(today),
            "month": _month(today),
            "regime_word": (f"{C.regime_word(key)} ({regime.get('confidence')} confidence)"
                            if key else ""),
            "items": items, "holdings": rows, "watch": _watch(holdings),
            "news": news, "issues": issues}

load_config(path=None)

Load data/notify.toml. Missing/invalid file -> {'channel': 'none'}.

Source code in quant/engine/notify.py
42
43
44
45
46
47
48
49
50
51
52
53
54
def load_config(path: str | None = None) -> dict:
    """Load data/notify.toml. Missing/invalid file -> {'channel': 'none'}."""
    path = path or NOTIFY_FILE
    try:
        import tomllib

        with open(path, "rb") as f:
            data = tomllib.load(f)
        if not isinstance(data, dict):
            return {"channel": "none"}
        return data
    except Exception:  # noqa: BLE001
        return {"channel": "none"}

save_config(config, path=None)

Write data/notify.toml with local-only permissions. Never raises.

Source code in quant/engine/notify.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def save_config(config: dict, path: str | None = None) -> None:
    """Write data/notify.toml with local-only permissions. Never raises."""
    path = path or NOTIFY_FILE
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        lines = []
        for key, value in config.items():
            if isinstance(value, bool):
                lines.append(f"{key} = {'true' if value else 'false'}")
            elif isinstance(value, int | float):
                lines.append(f"{key} = {value}")
            else:
                lines.append(f'{key} = "{value}"')
        with open(path, "w", encoding="utf-8") as f:
            f.write("\n".join(lines) + "\n")
        os.chmod(path, 0o600)
    except Exception:  # noqa: BLE001
        pass

send(text, config=None)

The single dispatch function (Telegram). Never raises.

Source code in quant/engine/notify.py
107
108
109
110
111
112
def send(text: str, config: dict | None = None) -> bool:
    """The single dispatch function (Telegram). Never raises."""
    cfg = config if config is not None else load_config()
    if str(cfg.get("channel", "none")).lower() != "telegram":
        return False
    return _send_telegram(cfg, text)

send_daily_digest(conn, items, holdings, today=None, now=None, sender=None, force=False)

Send the digest once per price date, from the morning slot. Never raises.

Source code in quant/engine/notify.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def send_daily_digest(conn: Any, items: list[dict], holdings: list[dict],
                      today: date | None = None, now: datetime | None = None,
                      sender: Any = None, force: bool = False) -> bool:
    """Send the digest once per price date, from the morning slot. Never raises."""
    now = now or datetime.now()
    if not force and now.hour >= DIGEST_HOUR_BEFORE:
        return False
    try:
        snap = digest_snapshot(conn, items, holdings, today)
    except Exception:  # noqa: BLE001
        return False
    key = str(snap.get("prices_date") or snap["today"])
    if not force and _read_state().get("last_digest_prices") == key:
        return False
    ok = bool((sender or send)(build_digest(snap)))
    if ok:
        try:
            os.makedirs(str(paths.OUTPUTS_DIR), exist_ok=True)
            with open(_state_path(), "w", encoding="utf-8") as f:
                json.dump({"last_digest_prices": key, "sent_at": now.isoformat()}, f)
        except Exception:  # noqa: BLE001
            pass
    return ok

send_test(config=None)

Send a test message (used by the inline Settings setup).

Source code in quant/engine/notify.py
115
116
117
def send_test(config: dict | None = None) -> bool:
    """Send a test message (used by the inline Settings setup)."""
    return send("Quant-AI test message. Notifications are working.", config)

status_line(config=None)

The plain Telegram state, without the "Telegram" prefix (v10.8.5, D14).

Callers prepend the label, so the rendered line is "Telegram: on, last test ok" — never "Telegram: Telegram on, ...".

Source code in quant/engine/notify.py
77
78
79
80
81
82
83
84
85
86
87
88
def status_line(config: dict | None = None) -> str:
    """The plain Telegram state, without the "Telegram" prefix (v10.8.5, D14).

    Callers prepend the label, so the rendered line is "Telegram: on, last test
    ok" — never "Telegram: Telegram on, ...".
    """
    cfg = config if config is not None else load_config()
    channel = str(cfg.get("channel", "none")).lower()
    if channel == "telegram":
        return ("on, last test ok" if cfg.get("tested")
                else "on, not tested yet")
    return "off"

Analysis chain, scoring, valuation

analysis.py — the analysis pipeline + manifest (v10.8.7, T2/A3).

Intent: the daily job AND the on-demand "Run analysis" button execute the SAME ordered chain, and every stage writes one run_manifest row so the UI never guesses why a computation is missing:

prices -> fundamentals -> nlp -> regime -> scoring -> optimization

Fetch stages (prices, fundamentals, nlp) reuse stored data fresher than their TTL (prices 1 day, fundamentals 7 days, nlp 1 day); compute stages (regime, scoring, optimization) always recompute. A stage that cannot run is recorded as missing or failed with its reason, never silently skipped.

Scoring degrades gracefully (R-C2): any subset of components yields a numeric composite + a confidence tier; a missing component is a documented neutral penalty (:func:quant.analytics.scoring.composite_score). The composite is written to the scores store for every symbol with a price.

Invariants
  • Never raises: a failing stage is recorded and the chain continues.
  • One manifest row per stage per run.
  • The scores store is written for every symbol with a price.

components_for(conn, symbol)

The scoring components for a symbol (None when absent).

Source code in quant/engine/analysis.py
181
182
183
184
185
186
187
def components_for(conn: Any, symbol: str) -> dict:
    """The scoring components for a symbol (None when absent)."""
    return {
        "technical": _technical_from_prices(conn, symbol),
        "fundamental": score_model.fundamental_score(_fundamentals_row(conn, symbol)),
        "sentiment": _sentiment_component(conn, symbol),
    }

drop_score(conn, symbol)

Delete one symbol's row from the scores store. Never raises.

Source code in quant/engine/analysis.py
190
191
192
193
194
195
def drop_score(conn: Any, symbol: str) -> None:
    """Delete one symbol's row from the ``scores`` store. Never raises."""
    try:
        conn.execute("DELETE FROM scores WHERE symbol = ?", [str(symbol)])
    except Exception as e:  # noqa: BLE001
        logger.debug("drop_score failed: %s", type(e).__name__)

run_analysis(conn, symbols=None, now=None, fetchers=None, progress=None)

Run the ordered analysis chain, writing one manifest row per stage.

fetchers maps a fetch stage to a zero-arg callable (tests inject them; the on-demand button passes the real data updaters). progress is an optional (stage) -> None callback for the UI's per-stage progress line. Never raises. Returns {run_id, stages, scored}.

Source code in quant/engine/analysis.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def run_analysis(conn: Any, symbols: list[str] | None = None,
                 now: date | None = None,
                 fetchers: dict | None = None,
                 progress: Callable[[str], None] | None = None) -> dict:
    """Run the ordered analysis chain, writing one manifest row per stage.

    ``fetchers`` maps a fetch stage to a zero-arg callable (tests inject them;
    the on-demand button passes the real data updaters). ``progress`` is an
    optional ``(stage) -> None`` callback for the UI's per-stage progress line.
    Never raises. Returns ``{run_id, stages, scored}``.
    """
    now = now or date.today()
    fetchers = fetchers or {}
    run_id = manifest.new_run_id()
    symbols = symbols if symbols is not None else _universe(conn)

    stages: list[dict] = []
    for stage, table, col, sym_col in (
            ("prices", "market_history", "Date", "Symbol"),
            ("fundamentals", "fundamentals", "updated_at", "symbol"),
            ("nlp", "nlp_evidence", "retrieved_at", "symbol")):
        if progress:
            progress(stage)
        stages.append(_fetch_stage(conn, run_id, stage, table, col, sym_col,
                                   symbols, now, fetchers.get(stage)))
    if progress:
        progress("regime")
    stages.append(_regime_stage(conn, run_id, now))
    if progress:
        progress("scoring")
    stages.append(_scoring_stage(conn, run_id, symbols))
    if progress:
        progress("optimization")
    stages.append(_optimization_stage(conn, run_id, symbols))

    scored = 0
    for s in stages:
        if s["stage"] == "scoring" and s["status"] == manifest.STATUS_OK:
            try:
                scored = int(str(s["coverage"]).split("/")[0])
            except (ValueError, IndexError):
                scored = 0
    return {"run_id": run_id, "stages": stages, "scored": scored}

write_regime(conn, label, deviation, confidence, as_of)

Store the regime estimate where :func:artifacts.read_regime finds it.

Source code in quant/engine/analysis.py
251
252
253
254
255
256
257
258
259
260
261
262
def write_regime(conn: Any, label: str, deviation: float, confidence: str,
                 as_of: date) -> None:
    """Store the regime estimate where :func:`artifacts.read_regime` finds it."""
    import json

    payload = {"state": "estimated", "label": label, "deviation": round(deviation, 4),
               "confidence": confidence, "as_of": as_of.isoformat(), "error": None}
    try:
        conn.execute("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",
                     [REGIME_META_KEY, json.dumps(payload)])
    except Exception:  # noqa: BLE001
        pass

write_scores(conn, symbol, result)

Upsert one row into the scores store. Never raises.

Source code in quant/engine/analysis.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def write_scores(conn: Any, symbol: str, result: dict) -> None:
    """Upsert one row into the ``scores`` store. Never raises."""
    comps = result.get("components") or {}
    try:
        conn.execute(
            "INSERT OR REPLACE INTO scores "
            "(symbol, composite, confidence, structural_grade, tactical_grade, "
            " sentiment, stewardship, present_components, total_components, updated_at) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            [str(symbol), _num(result.get("composite")), str(result.get("confidence")),
             _num(comps.get("fundamental")), _num(comps.get("technical")),
             _num(comps.get("sentiment")), _num(comps.get("stewardship")),
             int(result.get("present") or 0), int(result.get("total") or 0),
             time.time()])
    except Exception:  # noqa: BLE001
        pass

manifest.py — the analysis-pipeline validity contract (v10.8.4, T7).

Intent: every run (daily or on-demand) writes one run_manifest row per stage so the UI never guesses why a computation is missing. An empty state reads the manifest and names the failed/stale/missing stage and its error; a literal None in the UI is forbidden. Scoring never silently skips: a missing NLP input yields a score with a documented confidence penalty and a confidence flag (None only when the whole stage failed, and then the manifest says why).

Stages (fixed vocabulary): prices, fundamentals, nlp, regime, scoring, optimization, valuation.

Invariants
  • record_stage upserts on (run_id, stage); never raises.
  • Status is one of ok / stale / failed / missing.
  • The reader returns the most recent run's rows, one per stage.

coverage_line(conn=None)

The ONE coverage line: coverage: <n>/<N> symbols, as of <ts> (R-P2).

Reads the run manifest's scoring stage. A bare "-" is forbidden: when no coverage is recorded the line is a reasoned empty state, never a dash.

Source code in quant/engine/manifest.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def coverage_line(conn: Any = None) -> str:
    """The ONE coverage line: ``coverage: <n>/<N> symbols, as of <ts>`` (R-P2).

    Reads the run manifest's scoring stage. A bare "-" is forbidden: when no
    coverage is recorded the line is a reasoned empty state, never a dash.
    """
    rows = {r["stage"]: r for r in read_manifest(conn)}
    scoring = rows.get("scoring", {})
    cov = str(scoring.get("coverage") or "").strip()
    if not cov or cov == "-":
        return "coverage: not available yet"
    when = _fmt_ts(scoring.get("finished_at"))
    if when:
        return f"coverage: {cov}, as of {when}"
    return f"coverage: {cov}"

coverage_text(line)

Format a coverage value as n/N symbols (T7/R3).

Source code in quant/engine/manifest.py
118
119
120
121
122
123
124
def coverage_text(line: str | list | tuple | None) -> str:
    """Format a coverage value as ``n/N symbols`` (T7/R3)."""
    if line is None:
        return ""
    if isinstance(line, list | tuple) and len(line) == 2:
        return f"{int(line[0])}/{int(line[1])} symbols"
    return str(line)

empty_state_reason(stage, conn=None)

The 'Not available — ' sentence for a missing/failed stage (R2).

Reads the manifest so the reason is never guessed.

Source code in quant/engine/manifest.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def empty_state_reason(stage: str, conn: Any = None) -> str:
    """The 'Not available — <reason>' sentence for a missing/failed stage (R2).

    Reads the manifest so the reason is never guessed.
    """
    rows = {r["stage"]: r for r in read_manifest(conn)}
    row = rows.get(stage)
    word = stage_word(stage)
    if row is None or row["status"] in (STATUS_MISSING, ""):
        return f"{word}: not available yet."
    if row["status"] == STATUS_FAILED:
        detail = row.get("error") or "the analysis did not complete"
        return f"{word}: not available - {detail}."
    if row["status"] == STATUS_STALE:
        return f"{word}: out of date."
    return ""

latest_run_id(conn=None)

The most recent run id in the manifest, or None.

Source code in quant/engine/manifest.py
85
86
87
88
89
def latest_run_id(conn: Any = None) -> str | None:
    """The most recent run id in the manifest, or None."""
    rows = _query(conn, "SELECT run_id FROM run_manifest "
                        "ORDER BY finished_at DESC LIMIT 1")
    return str(rows[0][0]) if rows else None

new_run_id(when=None)

A stable run id from a timestamp (second resolution).

Source code in quant/engine/manifest.py
45
46
47
48
def new_run_id(when: datetime | None = None) -> str:
    """A stable run id from a timestamp (second resolution)."""
    when = when or datetime.now()
    return when.strftime("%Y-%m-%d_%H%M%S")

read_manifest(conn=None, run_id=None)

The manifest rows for a run (default: the latest run), one per stage.

Returns [{stage, status, started_at, finished_at, coverage, error}] in the fixed stage order; empty when nothing is recorded.

Source code in quant/engine/manifest.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def read_manifest(conn: Any = None, run_id: str | None = None) -> list[dict]:
    """The manifest rows for a run (default: the latest run), one per stage.

    Returns ``[{stage, status, started_at, finished_at, coverage, error}]`` in
    the fixed stage order; empty when nothing is recorded.
    """
    run = run_id or latest_run_id(conn)
    if not run:
        return []
    rows = _query(conn, "SELECT stage, status, started_at, finished_at, coverage, "
                        "error FROM run_manifest WHERE run_id = ?", [run])
    by_stage = {str(r[0]): r for r in rows}
    out: list[dict] = []
    for stage in STAGES:
        r = by_stage.get(stage)
        if r is None:
            out.append({"stage": stage, "status": STATUS_MISSING,
                        "started_at": None, "finished_at": None,
                        "coverage": "", "error": ""})
        else:
            out.append({"stage": stage, "status": str(r[1]),
                        "started_at": r[2], "finished_at": r[3],
                        "coverage": str(r[4] or ""), "error": str(r[5] or "")})
    return out

record_stage(conn, run_id, stage, status, coverage='', error='', started_at=None, finished_at=None)

Upsert one manifest row. Never raises.

Source code in quant/engine/manifest.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def record_stage(conn: Any, run_id: str, stage: str, status: str,
                 coverage: str = "", error: str = "",
                 started_at: datetime | None = None,
                 finished_at: datetime | None = None) -> None:
    """Upsert one manifest row. Never raises."""
    try:
        conn.execute(
            "INSERT OR REPLACE INTO run_manifest "
            "(run_id, stage, status, started_at, finished_at, coverage, error) "
            "VALUES (?, ?, ?, ?, ?, ?, ?)",
            [str(run_id), str(stage), str(status),
             started_at or datetime.now(), finished_at or datetime.now(),
             str(coverage), str(error or "")])
    except Exception:  # noqa: BLE001
        pass

stage_word(stage)

Plain-word name for a stage key.

Source code in quant/engine/manifest.py
51
52
53
def stage_word(stage: str) -> str:
    """Plain-word name for a stage key."""
    return STAGE_WORDS.get(str(stage), str(stage))

status_word(status)

Plain-word status for a stage (v10.8.7, A3: ok-fresh / ok-reused).

Source code in quant/engine/manifest.py
56
57
58
59
60
61
62
63
64
65
def status_word(status: str) -> str:
    """Plain-word status for a stage (v10.8.7, A3: ok-fresh / ok-reused)."""
    return {
        STATUS_OK: "ok",
        STATUS_STALE: "stale",
        STATUS_FAILED: "failed",
        STATUS_MISSING: "missing",
        "ok-fresh": "ok (fresh)",
        "ok-reused": "ok (reused)",
    }.get(str(status), "missing")

score_model.py — the 0-100 score behind Research, ideas, swaps and the score floor.

Intent (v10.8.10): one small, explainable model for a private long-term investor. It replaces a composite that scored missing data at 12/100 (so every ETF sat at ~27, "below the 40 floor", and nothing could reach high confidence), used one month of momentum (noise), counted stewardship twice and read debt/equity in the wrong unit.

Components (each 0-100, or None when it cannot be computed):

technical trend for a monthly buyer: 12-minus-1-month momentum and the price against its 200-day average (needs ~1 year of closes; falls back to the 200-day average alone with >= 200 closes). fundamental stocks only: valuation (P/E, PEG), quality (ROE) and balance sheet (debt/equity, interest cover). Needs 3 of the 5 inputs. sentiment recency-weighted news tone (half-life 7 days, last 30 days), needs >= SENTIMENT_MIN_DOCS headlines.

The composite is the weighted mean over the components that are present. A component that does not apply (fundamentals of an ETF) is not "missing"; confidence is the present share of the applicable weight.

Invariants: pure functions, no I/O.

applicable(instrument_class)

Components that apply: fundamentals only exist for single stocks.

Source code in quant/engine/score_model.py
135
136
137
138
139
140
def applicable(instrument_class: str | None) -> tuple[str, ...]:
    """Components that apply: fundamentals only exist for single stocks."""
    cls = str(instrument_class).upper() if instrument_class else "EQUITY"
    if cls == "EQUITY":
        return ("technical", "fundamental", "sentiment")
    return ("technical", "sentiment")

composite(components, instrument_class=None)

Weighted mean of the present, applicable components + a confidence tier.

Returns {composite, confidence, present, total, components}; composite is None when no component is present.

Source code in quant/engine/score_model.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def composite(components: dict, instrument_class: str | None = None) -> dict:
    """Weighted mean of the present, applicable components + a confidence tier.

    Returns ``{composite, confidence, present, total, components}``;
    ``composite`` is None when no component is present.
    """
    names = applicable(instrument_class)
    present = {n: components.get(n) for n in names if components.get(n) is not None}
    total_w = sum(WEIGHTS[n] for n in names)
    present_w = sum(WEIGHTS[n] for n in present)
    value = (sum(WEIGHTS[n] * float(v) for n, v in present.items()) / present_w
             if present_w else None)
    share = present_w / total_w          # total_w > 0: technical always applies
    # No mix of components gives a share of exactly 0.8, so >= and > are the
    # same here; the comparison is excluded from mutation.
    if share >= HIGH_CONFIDENCE:  # pragma: no mutate
        confidence = "high"
    elif share >= MEDIUM_CONFIDENCE:
        confidence = "medium"
    else:
        confidence = "low"
    return {"composite": None if value is None else round(value, 1),
            "confidence": confidence, "present": len(present), "total": len(names),
            "components": {n: components.get(n) for n in names}}

fundamental_score(f)

Points for valuation, quality and balance sheet, scaled to 0-100.

Source code in quant/engine/score_model.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def fundamental_score(f: dict | None) -> float | None:
    """Points for valuation, quality and balance sheet, scaled to 0-100."""
    if not f:
        return None
    pe, peg, roe = _num(f.get("pe")), _num(f.get("peg")), _num(f.get("roe"))
    de = _debt_to_equity(f.get("debt_to_equity"))
    icr = interest_cover(f.get("ebit"), f.get("interest_expense"))
    parts: list[tuple[float, float]] = []                    # (points, max)
    if pe is not None:
        parts.append((0 if pe <= 0 else 25 if pe <= 15 else 15 if pe <= 25
                      else 5 if pe <= 40 else 0, 25))
    if peg is not None:
        parts.append((0 if peg <= 0 else 15 if peg <= 1 else 8 if peg <= 2 else 0, 15))
    if roe is not None:
        parts.append((25 if roe >= 0.20 else 15 if roe >= 0.10 else 5 if roe > 0 else 0, 25))
    if de is not None:
        # Negative debt/equity means negative equity: the weakest balance sheet.
        parts.append((0 if de < 0 else 20 if de <= 0.5 else 12 if de <= 1.0
                      else 5 if de <= 2.0 else 0, 20))
    if icr is not None:
        parts.append((15 if icr >= 8 else 8 if icr >= 3 else 0, 15))
    if len(parts) < 3:
        return None
    return _score(100.0 * sum(p for p, _ in parts) / sum(m for _, m in parts))

interest_cover(ebit, interest_expense)

EBIT / |interest expense|; None when either is unknown or interest is 0.

Source code in quant/engine/score_model.py
81
82
83
84
85
86
def interest_cover(ebit: Any, interest_expense: Any) -> float | None:
    """EBIT / |interest expense|; None when either is unknown or interest is 0."""
    e, ie = _num(ebit), _num(interest_expense)
    if e is None or ie is None or ie == 0:
        return None
    return e / abs(ie)

sentiment_score(evidence, today)

Recency-weighted tone of [(published_date, score -1..1), ...].

Source code in quant/engine/score_model.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def sentiment_score(evidence: list[tuple[Any, Any]], today: date) -> float | None:
    """Recency-weighted tone of ``[(published_date, score -1..1), ...]``."""
    total = weight = 0.0
    n = 0
    for when, score in evidence or []:
        s = _num(score)
        if s is None or when is None:
            continue
        age = (today - date.fromisoformat(str(when)[:10])).days
        if age < 0 or age > SENTIMENT_WINDOW_DAYS:
            continue
        w = 0.5 ** (age / SENTIMENT_HALF_LIFE_DAYS)
        total += w * max(-1.0, min(1.0, s))
        weight += w
        n += 1
    if n < SENTIMENT_MIN_DOCS:       # >= 1 document also means weight > 0
        return None
    return _score(50.0 + 50.0 * total / weight)

technical_score(closes)

Trend score from daily closes (oldest first).

Source code in quant/engine/score_model.py
57
58
59
60
61
62
63
64
65
66
67
def technical_score(closes: list[float]) -> float | None:
    """Trend score from daily closes (oldest first)."""
    px = [c for c in (_num(c) for c in closes) if c is not None and c > 0]
    if len(px) < 200:
        return None
    sma200 = sum(px[-200:]) / 200.0
    trend = math.tanh((px[-1] / sma200 - 1.0) * 5.0)        # +-10% vs the average
    if len(px) >= 253:
        mom = px[-22] / px[-253] - 1.0                       # 12 months, skip the last
        return _score(50.0 + 25.0 * trend + 25.0 * math.tanh(mom * 2.0))
    return _score(50.0 + 50.0 * trend)

trend_regime(closes)

(bull|bear|chop, deviation, confidence) from index closes, or None.

Source code in quant/engine/score_model.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def trend_regime(closes: list[float]) -> tuple[str, float, str] | None:
    """``(bull|bear|chop, deviation, confidence)`` from index closes, or None."""
    px = [c for c in (_num(c) for c in closes) if c is not None and c > 0]
    if len(px) < 200 + REGIME_DAYS:
        return None
    devs = []
    for k in range(REGIME_DAYS):
        end = len(px) - k
        sma = sum(px[end - 200:end]) / 200.0
        devs.append(px[end - 1] / sma - 1.0)
    # Deviations are continuous: a close landing exactly on a band edge does not
    # happen, so > and >= are the same on the four comparisons marked below.
    if all(d > REGIME_BAND for d in devs):  # pragma: no mutate
        label = "bull"
    elif all(d < -REGIME_BAND for d in devs):  # pragma: no mutate
        label = "bear"
    else:
        label = "chop"
    dev = devs[0]
    if abs(dev) >= REGIME_HIGH:  # pragma: no mutate
        confidence = "high"
    elif abs(dev) >= REGIME_BAND:  # pragma: no mutate
        confidence = "medium"
    else:
        confidence = "low"
    # A mixed (chop) label is never firm: today's distance from the average says
    # how far the index is, not how settled the trend is (v10.10.1).
    if label == "chop" and confidence == "high":
        confidence = "medium"
    return label, dev, confidence

mtm.py — the daily mark-to-market valuation store (v10.8.4, T1; v10.8.7, R-C1).

Intent: the product must show ONE value per datum. Before v10.8.4 a holding's value came from three places (the broker CSV, the holdings_meta estimate, a review artifact), so the chart lagged, the header delta was unlabeled and the holdings table disagreed with itself. This module is the single writer and reader of the valuation / portfolio_total stores:

valuation(date, symbol, shares, price_eur, fx, value_eur, source) portfolio_total(date, value_eur, cash_eur)

It is written by the daily job, by confirm & save, and by the on-demand refresh, and rebuilt from scratch each time. Shares on a day are the latest saved holdings table on or before it (position_snapshots), restated to today's units by later stock splits; value = shares x close x FX.

v10.8.7 (R-C1): uninvested cash is NOT an entity. portfolio_total is the sum of invested position values only. The cash_eur column is frozen audit data: it is written NULL and never read (the physical column drop is deferred). The flows->cash computation is deleted; the ledger flows remain for audit only.

Invariants
  • Pure helpers (restate, shares_on) do no I/O; the I/O wrappers take an explicit connection.
  • A missing price skips the symbol for that day, never zeroes it.
  • backfill lets a database error propagate; its callers (confirm, the daily job, refresh) catch it, and the rebuild is atomic per call.
  • value_eur = shares * price_eur * fx, rounded to 2 decimals.

backfill(conn, fx_lookup=None, source=SOURCE_BACKFILL)

Rebuild the store: one valuation row per held symbol per trading day.

v10.8.10: shares come from the saved holdings tables (position_snapshots), not from a reconstructed ledger (opening lots + diff trades), which one bad row could corrupt for good. The store is rebuilt from scratch on every call (small: days x holdings), so it heals itself. value = shares x close x FX. fx_lookup(symbol) replaces the live EUR rate (tests). Returns {days, rows}.

Source code in quant/engine/mtm.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def backfill(conn: Any, fx_lookup: Any = None, source: str = SOURCE_BACKFILL) -> dict:
    """Rebuild the store: one valuation row per held symbol per trading day.

    v10.8.10: shares come from the saved holdings tables (position_snapshots),
    not from a reconstructed ledger (opening lots + diff trades), which one bad
    row could corrupt for good. The store is rebuilt from scratch on every call
    (small: days x holdings), so it heals itself. value = shares x close x FX.
    ``fx_lookup(symbol)`` replaces the live EUR rate (tests). Returns
    ``{days, rows}``.
    """
    snapshots = _snapshots(conn)
    if not snapshots:
        return {"days": 0, "rows": 0}
    splits = _split_rows(conn)
    symbols = {s for _d, table in snapshots for s in table}
    hist = _price_history(conn, symbols)
    first = snapshots[0][0]
    days = sorted({d for s in hist.values() for d, _c in s if d >= first})
    conn.execute(SQL_CLEAR_VALUATION)
    conn.execute(SQL_CLEAR_TOTAL)
    fx = fx_lookup if callable(fx_lookup) else _fx_rate
    fx_cache: dict = {}
    rows = 0
    for d in days:
        total = 0.0
        for sym, sh in shares_on(snapshots, splits, d).items():
            price = _close_on_or_before(hist.get(sym, []), d)
            if price is None:
                continue
            if sym not in fx_cache:
                fx_cache[sym] = float(fx(sym)) or 1.0
            value = round(sh * price * fx_cache[sym], 2)
            conn.execute(SQL_WRITE_VALUATION,
                         [d, sym, sh, price, fx_cache[sym], value, str(source)])
            rows += 1
            total += value
        # The parts are whole cents; rounding only drops float noise, so 2 or 3
        # places are the same.
        conn.execute(SQL_WRITE_TOTAL, [d, round(total, 2)])  # pragma: no mutate
    return {"days": len(days), "rows": rows}

catch_up(retries=3, base_delay=0.5)

Catch the valuation store up to the latest price (v10.8.6, B1/B2).

Runs once per process start (the caller guards it); never inside a rerun. When the latest valuation date is behind the latest market_history date, backfill with bounded retry on lock contention. On final failure: one log line + mark the valuation stage stale in run_manifest. Never raises.

Source code in quant/engine/mtm.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def catch_up(retries: int = 3, base_delay: float = 0.5) -> dict:
    """Catch the valuation store up to the latest price (v10.8.6, B1/B2).

    Runs once per process start (the caller guards it); never inside a rerun. When
    the latest valuation date is behind the latest ``market_history`` date, backfill
    with bounded retry on lock contention. On final failure: one log line + mark the
    ``valuation`` stage ``stale`` in ``run_manifest``. Never raises.
    """
    import contextlib
    import time

    from quant.data.database import connect_with_retry

    last_err: Exception | None = None  # pragma: no mutate (always set before use)
    tries = max(1, int(retries))
    for attempt in range(tries):
        try:
            with contextlib.closing(connect_with_retry(attempts=1)) as conn:
                latest_price = _as_date(conn.execute(SQL_LAST_PRICE).fetchone()[0])
                latest_val = _as_date(conn.execute(SQL_LAST_VALUATION).fetchone()[0])
                if latest_price is None:
                    return {"ok": True, "skipped": True, "reason": "no prices"}
                if latest_val is not None and latest_val >= latest_price:
                    return {"ok": True, "skipped": True, "latest": str(latest_val)}
                res = backfill(conn, source=SOURCE_REFRESH)
                return {"ok": True, "rows": res["rows"], "days": res["days"],
                        "latest": str(latest_price)}
        except Exception as e:  # noqa: BLE001
            last_err = e
            if attempt < tries - 1:
                time.sleep(base_delay * (2 ** attempt))
    _mark_valuation_stale(last_err)
    return {"ok": False, "error": str(last_err)}

day_delta(conn=None)

The last day's change: (eur, pct, latest_date) from stored totals.

The home header delta is exactly total(D) - total(D-1) (invested value plus cash). It is computed by the ONE pure helper :func:quant.reporting.artifacts.compute_day_delta, so the number the header shows and the number the invariant test checks can never drift (v10.8.6, B6). Returns (0.0, 0.0, latest_date_or_None) when fewer than two days are stored.

Source code in quant/engine/mtm.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def day_delta(conn: Any = None) -> tuple[float, float, date | None]:
    """The last day's change: ``(eur, pct, latest_date)`` from stored totals.

    The home header delta is exactly ``total(D) - total(D-1)`` (invested value plus
    cash). It is computed by the ONE pure helper
    :func:`quant.reporting.artifacts.compute_day_delta`, so the number the header
    shows and the number the invariant test checks can never drift (v10.8.6, B6).
    Returns ``(0.0, 0.0, latest_date_or_None)`` when fewer than two days are stored.
    """
    from quant.reporting.artifacts import compute_day_delta

    series = read_total_series(conn)
    if not series:
        return 0.0, 0.0, None
    eur, pct = compute_day_delta(series)
    return eur, pct, _as_date(series[-1]["date"])

latest_price_date(conn=None)

The most recent stored valuation date, or None.

Source code in quant/engine/mtm.py
332
333
334
335
def latest_price_date(conn: Any = None) -> date | None:
    """The most recent stored valuation date, or None."""
    rows = _query(conn, SQL_LAST_VALUATION)
    return _as_date(rows[0][0]) if rows else None

latest_total(conn=None)

The most recent portfolio_total row (invested value only), or {}.

Source code in quant/engine/mtm.py
247
248
249
250
251
252
253
def latest_total(conn: Any = None) -> dict:
    """The most recent ``portfolio_total`` row (invested value only), or {}."""
    rows = _query(conn, SQL_LATEST_TOTAL)
    if not rows:
        return {}
    r = rows[0]
    return {"date": r[0], "value_eur": _num(r[1])}

read_symbol_series(conn=None)

The per-symbol value series from the valuation store.

Returns {symbol: [{date, value_eur}, ...]} oldest first, for the Growth chart's one-line-per-held-asset view. Empty when nothing is stored.

Source code in quant/engine/mtm.py
338
339
340
341
342
343
344
345
346
347
348
349
def read_symbol_series(conn: Any = None) -> dict:
    """The per-symbol value series from the valuation store.

    Returns ``{symbol: [{date, value_eur}, ...]}`` oldest first, for the Growth
    chart's one-line-per-held-asset view. Empty when nothing is stored.
    """
    rows = _query(conn, SQL_SYMBOL_SERIES)
    out: dict = {}
    for d, sym, v in rows:
        out.setdefault(str(sym), []).append(
            {"date": _as_date(d), "value_eur": _num(v)})
    return out

read_total_series(conn=None)

The daily portfolio-total series oldest first (invested value only).

Returns [{date, value_eur}]; empty when nothing is stored. v10.8.7 (R-C1): cash_eur is frozen audit data and is never read.

Source code in quant/engine/mtm.py
237
238
239
240
241
242
243
244
def read_total_series(conn: Any = None) -> list[dict]:
    """The daily portfolio-total series oldest first (invested value only).

    Returns ``[{date, value_eur}]``; empty when nothing is stored. v10.8.7 (R-C1):
    ``cash_eur`` is frozen audit data and is never read.
    """
    rows = _query(conn, SQL_TOTALS)
    return [{"date": r[0], "value_eur": _num(r[1])} for r in rows]

restate(shares, symbol, since, splits)

Shares counted at since, restated to today's units by later splits. Pure.

Prices in market_history are split-adjusted to today's share basis, so a count taken before a split is multiplied by that split's factor (2.0 for 2:1).

Source code in quant/engine/mtm.py
86
87
88
89
90
91
92
93
94
95
96
97
98
def restate(shares: float, symbol: str, since: date | None, splits: list) -> float:
    """Shares counted at ``since``, restated to today's units by later splits. Pure.

    Prices in ``market_history`` are split-adjusted to today's share basis, so a
    count taken before a split is multiplied by that split's factor (2.0 for 2:1).
    """
    for row in splits or []:
        eff, sym, factor = (list(row) + [None, None, None])[:3]
        ed, f = _as_date(eff), _num(factor)        # unknown factor -> 0 -> skipped
        if str(sym) == str(symbol) and ed is not None and f > 0 and (
                since is None or ed > since):
            shares *= f
    return shares

shares_on(snapshots, splits, day)

Shares per symbol held on day, in today's units. Pure.

snapshots is [(snapshot_date, {symbol: shares}), ...] sorted by date: each is the whole holdings table as saved that day (Confirm and save), so the latest one on or before day is what was held. Before the first one, nothing was held.

Source code in quant/engine/mtm.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def shares_on(snapshots: list, splits: list, day: date) -> dict[str, float]:
    """Shares per symbol held on ``day``, in today's units. Pure.

    ``snapshots`` is ``[(snapshot_date, {symbol: shares}), ...]`` sorted by date:
    each is the whole holdings table as saved that day (Confirm and save), so
    the latest one on or before ``day`` is what was held. Before the first one,
    nothing was held.
    """
    held: tuple | None = None
    for snap_day, table in snapshots:
        if snap_day <= day:
            held = (snap_day, table)
    if held is None:
        return {}
    snap_day, table = held
    return {sym: round(restate(sh, sym, snap_day, splits), 6)
            for sym, sh in table.items() if sh > 0}

flows.py — honest performance math (v10.7.0, Section 7; trimmed v10.8.2).

Intent: the old "+2.5 percent since 13 Sep" is a naive value change and lies whenever money enters. Modified Dietz excludes deposits:

R = (V_end - V_start - F) / (V_start + sum(w_i * F_i))
w_i = (days_in_period - days_from_start_to_flow) / days_in_period

Deposits do not count as profit. Flow signs: buy = +amount (money entered invested), sell = -amount (money left invested), dividend = -amount (left invested, landed in cash).

v10.8.2: the manual Sparplan flow writers were removed with the Monthly decision page. The ledger is written by quant.engine.confirm and quant.engine.ledger.

Invariants
  • modified_dietz is pure (no I/O).
  • load_flows takes an explicit connection; it never opens its own.

cost_based_return(rows, realized_sum)

Honest result since the first purchase, as a fraction (v10.9.2).

(open-position profit + realized profit) / money still invested in open positions (Current_Value_EUR - Broker_PnL_EUR). Missing numbers count as 0. None when nothing is invested.

Source code in quant/engine/flows.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def cost_based_return(rows: list[dict], realized_sum: float | None) -> float | None:
    """Honest result since the first purchase, as a fraction (v10.9.2).

    (open-position profit + realized profit) / money still invested in open
    positions (Current_Value_EUR - Broker_PnL_EUR). Missing numbers count as 0.
    None when nothing is invested.
    """
    def num(v: Any) -> float:
        if v is None or v != v:   # None / NaN count as 0
            return 0.0
        return float(v)

    profit = sum(num(r.get("Broker_PnL_EUR")) for r in rows or [])
    invested = sum(num(r.get("Current_Value_EUR")) - num(r.get("Broker_PnL_EUR"))
                   for r in rows or [])
    if invested <= 0:
        return None
    return (profit + num(realized_sum)) / invested

flow_sign(flow_type)

Signed direction of a flow for the return math.

Source code in quant/engine/flows.py
30
31
32
def flow_sign(flow_type: str) -> float:
    """Signed direction of a flow for the return math."""
    return _FLOW_SIGN.get(str(flow_type).lower(), 0.0)

load_flows(conn, start=None, end=None)

Load flows in [start, end] (inclusive), ordered by date.

Source code in quant/engine/flows.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def load_flows(conn: Any, start: date | None = None, end: date | None = None) -> list[dict]:
    """Load flows in [start, end] (inclusive), ordered by date."""
    # SQL keywords and column names are case-insensitive, so mutating their
    # case cannot change behavior; the SQL text lines are excluded from mutation.
    query = "SELECT id, date, type, amount_eur, symbol, note FROM flows"  # pragma: no mutate
    clauses: list[str] = []
    params: list = []
    if start is not None:
        clauses.append("date >= ?")  # pragma: no mutate
        params.append(start)
    if end is not None:
        clauses.append("date <= ?")  # pragma: no mutate
        params.append(end)
    if clauses:
        query += " WHERE " + " AND ".join(clauses)  # pragma: no mutate
    query += " ORDER BY date"  # pragma: no mutate
    try:
        rows = conn.execute(query, params).fetchall()
    except Exception:  # noqa: BLE001
        return []
    return [
        {
            "id": r[0],
            "date": r[1],
            "type": r[2],
            "amount_eur": r[3],
            "symbol": r[4],
            "note": r[5],
        }
        for r in rows
    ]

modified_dietz(v_start, v_end, flows, start, end)

Modified Dietz return over [start, end]. Returns a fraction or None.

flows: list of dicts with 'date', 'type', and 'amount_eur' (positive). The sign is applied from the type. Returns None when the period is empty or the denominator is non-positive.

Source code in quant/engine/flows.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def modified_dietz(
    v_start: float,
    v_end: float,
    flows: list[dict],
    start: date,
    end: date,
) -> float | None:
    """Modified Dietz return over [start, end]. Returns a fraction or None.

    flows: list of dicts with 'date', 'type', and 'amount_eur' (positive). The
    sign is applied from the type. Returns None when the period is empty or the
    denominator is non-positive.
    """
    start_d = _as_date(start)
    end_d = _as_date(end)
    total_days = (end_d - start_d).days
    if total_days <= 0:
        return None
    net_flow = 0.0
    weighted = 0.0
    for flow in flows:
        amount = float(flow.get("amount_eur") or 0) * flow_sign(flow.get("type", _BUY))
        flow_date = _as_date(flow.get("date"))
        days_from_start = (flow_date - start_d).days
        weight = (total_days - days_from_start) / total_days
        net_flow += amount
        weighted += weight * amount
    denominator = float(v_start) + weighted
    if denominator <= 0:
        return None
    return (float(v_end) - float(v_start) - net_flow) / denominator

since_first_return(series, flows)

Flow-adjusted return over a value series, as a fraction (v10.8.10).

series is [(date, value_eur), ...] in date order. The start value already contains every flow up to and including the first date, so only the flows strictly after it enter the Modified Dietz sum: a deposit (buy) is never counted as gain. None when there are fewer than two points.

Source code in quant/engine/flows.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def since_first_return(series: list[tuple], flows: list[dict]) -> float | None:
    """Flow-adjusted return over a value series, as a fraction (v10.8.10).

    ``series`` is ``[(date, value_eur), ...]`` in date order. The start value
    already contains every flow up to and including the first date, so only the
    flows strictly after it enter the Modified Dietz sum: a deposit (buy) is
    never counted as gain. None when there are fewer than two points.
    """
    if len(series or []) < 2:
        return None
    (d0, v0), (d1, v1) = series[0], series[-1]
    start, end = _as_date(d0), _as_date(d1)
    later = [f for f in flows or [] if start < _as_date(f.get("date")) <= end]
    return modified_dietz(float(v0), float(v1), later, start, end)

value_series.py — the daily invested-value series (v10.8.0, fixed v10.8.2).

Intent: the Portfolio chart must show the invested value over time without requiring a completed review, and must never draw a flat zero line. The series runs from the first saved table to the LATEST available price date, one point per calendar day. A day on which any held symbol has never yet had a price is skipped, not zeroed; once a symbol has a first price, its last close is carried forward. Cash is never part of the series.

Invariants
  • Pure: no I/O, no database writes.
  • The series ends at the latest price date, so new prices extend it.
  • A missing close carries the previous close forward.
  • All values are EUR (native close * the symbol's EUR rate).

build_value_series(snapshots, flows, closes, fx)

Build the daily invested-value series. Pure; no I/O.

Parameters:

Name Type Description Default
snapshots list[dict]

[{date, symbol, shares}] (append-only, any order).

required
flows list[dict]

[{date, type, amount_eur, symbol}] (buy/sell/dividend).

required
closes dict

{(symbol, date_iso): close_native}.

required
fx dict

{symbol: rate_to_eur} (the EUR multiplier).

required

Returns [{date, value_eur}] oldest first. Empty when there is no data.

Source code in quant/engine/value_series.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def build_value_series(snapshots: list[dict], flows: list[dict],
                       closes: dict, fx: dict) -> list[dict]:
    """Build the daily invested-value series. Pure; no I/O.

    Args:
        snapshots: ``[{date, symbol, shares}]`` (append-only, any order).
        flows: ``[{date, type, amount_eur, symbol}]`` (buy/sell/dividend).
        closes: ``{(symbol, date_iso): close_native}``.
        fx: ``{symbol: rate_to_eur}`` (the EUR multiplier).

    Returns ``[{date, value_eur}]`` oldest first. Empty when there is no data.
    """
    snaps = sorted(
        ({"date": _as_date(s["date"]), "symbol": str(s["symbol"]),
          "shares": float(s["shares"] or 0.0)} for s in snapshots),
        key=lambda s: s["date"])
    flws = sorted(
        ({"date": _as_date(f["date"]), "type": str(f["type"]),
          "amount_eur": float(f["amount_eur"] or 0.0),
          "symbol": str(f["symbol"])} for f in flows if f.get("symbol")),
        key=lambda f: f["date"])
    if not snaps and not flws:
        return []

    symbols = {s["symbol"] for s in snaps}
    by_sym: dict[str, list] = {}
    for s in snaps:
        by_sym.setdefault(s["symbol"], []).append(s)

    close_by_sym = _close_series(closes, symbols)

    # Start at the first saved table; end at the latest price date (so new
    # prices extend the series). With no prices, there is no series.
    start = min(s["date"] for s in snaps) if snaps else min(f["date"] for f in flws)
    latest = [s[-1][0] for s in close_by_sym.values() if s]
    if not latest:
        return []
    end = max([start] + latest)

    out: list[dict] = []
    for day in _days(start, end):
        total = 0.0
        day_ok = True
        for sym, rows in by_sym.items():
            base = None
            for s in rows:
                if s["date"] <= day:
                    base = s
                else:
                    break
            if base is None:
                continue  # not held yet
            shares = base["shares"]
            for f in flws:
                if (f["symbol"] != sym or f["date"] <= base["date"]
                        or f["date"] > day):
                    continue
                price = _price_on_or_before(close_by_sym.get(sym, []), f["date"])
                if price and price > 0:
                    if f["type"] == "buy":
                        shares += f["amount_eur"] / price
                    elif f["type"] == "sell":
                        shares -= f["amount_eur"] / price
            native = _price_on_or_before(close_by_sym.get(sym, []), day)
            if native is None:
                day_ok = False  # a held symbol has never had a price yet
                break
            total += shares * native * _rate(fx, sym)
        if not day_ok:
            continue
        out.append({"date": day, "value_eur": round(total, 2)})
    return out

Errors

errors.py — Standardized exception hierarchy (v10.6.5).

Intent: one base exception so callers can catch every quant error with a single except QuantError, plus specific subclasses for the common failure domains. Existing functions keep their current contracts (many return empty frames rather than raising); these types are for new code and for callers that want to be explicit.

Invariants: pure module; no I/O; no imports from the pipeline.

DataError

Bases: QuantError

Data is missing, corrupted, or invalid.

Source code in quant/errors.py
19
20
class DataError(QuantError):
    """Data is missing, corrupted, or invalid."""

QuantError

Bases: Exception

Base exception for all quant system errors.

Source code in quant/errors.py
15
16
class QuantError(Exception):
    """Base exception for all quant system errors."""

Health check

health.py — System health checks and diagnostics (v10.6.4).

Intent: one read-only check that reports the common failure modes: stale market data, an invalid tiers file, a broken database, and a missing data source. No writes, no secrets.

Invariants
  • run_health_check never raises; returns {status, checks} with status in {HEALTHY, WARNING, CRITICAL}.
  • Each check returns {name, status, message} with status in {OK, WARNING, CRITICAL}.

Dependencies: pandas, quant.paths, quant.data.database.

run_health_check()

Run the full system health check. Never raises.

Source code in quant/cli/health.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def run_health_check() -> dict:
    """Run the full system health check. Never raises."""
    checks = [
        _check_data_freshness(),
        _check_tiers_validation(),
        _check_database_integrity(),
        _check_external_apis(),
    ]
    statuses = [c["status"] for c in checks]
    if "CRITICAL" in statuses:
        overall = "CRITICAL"
    elif "WARNING" in statuses:
        overall = "WARNING"
    else:
        overall = "HEALTHY"
    return {"status": overall, "checks": checks}