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 | |
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 | |
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 | |
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 | |
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 | |
UI copy, search, cards (user-facing strings; instrument/theme search)
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
fmt_ts(value)
Format a timestamp as '13 Sep 2026, 17:43'.
Source code in quant/ui/copy.py
180 181 182 183 184 | |
invest_remainder_line(amount_eur)
The one neutral remainder line: '
Source code in quant/ui/copy.py
317 318 319 320 321 322 323 324 | |
regime_word(regime)
Map a regime enum to its human word.
Source code in quant/ui/copy.py
230 231 232 | |
status_word(universe_status)
Map a universe_status enum to its human word.
Source code in quant/ui/copy.py
273 274 275 | |
tier_word(tier)
Map a tier enum to its plain display word (Section 11).
Source code in quant/ui/copy.py
361 362 363 | |
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 | |
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 | |
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 | |
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 | |
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 | |
resolve(query, limit=10)
Convenience: search the live index.
Source code in quant/ui/search.py
247 248 249 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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:
- fetch the Yahoo Finance RSS headlines of each symbol;
- skip titles already stored for that symbol;
- 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);
- insert them into
nlp_evidenceand 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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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
Splitand 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 | |
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 | |
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 | |
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_weightandtarget_weightare fractions of the invested pool;target_weight(anddrift) is None when no target is set.- With a plan set,
target_weightsits 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 | |
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 | |
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 | |
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 | |
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 | |
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_7dare reads only.persistnever 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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
open_since_line(item)
The 'open since
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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:
- top up the largest UNDERWEIGHT holding vs its target (the gap in points);
- else the highest-score idea (a watched symbol at or above
IDEA_FLOOR; the caller passes the idea list); - 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 | |
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 | |
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 | |
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 | |
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 forSNOOZE_DAYSeven 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
syncnever raises; on failure it returns the items unchanged.- Only
openrows 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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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
- FORTRESS never sells: the rules only size sells for Active and Speculative holdings (quant.engine.action_taxonomy).
- Sell amount = min(drift, value - 1 EUR), rounded DOWN to 5 EUR steps. Below 25 EUR, no advice (fee relevance).
- A position below 100 EUR is untouchable (never emit a sell advice).
- 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 | |
round_buy(amount_eur)
Round a buy amount to 10 EUR steps (down).
Source code in quant/engine/sizing.py
65 66 67 | |
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 | |
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 | |
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 | |
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 | |
failed_marker_path()
Absolute path of the last-failed-run marker file.
Source code in quant/engine/daily.py
78 79 80 | |
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 | |
is_trading_day(when)
Weekend-only rule: Saturday and Sunday are non-trading days.
Source code in quant/engine/daily.py
121 122 123 | |
marker_path()
Absolute path of the last-daily-run marker file.
Source code in quant/engine/daily.py
48 49 50 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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
sendnever 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 | |
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 | |
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 | |
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 | |
send(text, config=None)
The single dispatch function (Telegram). Never raises.
Source code in quant/engine/notify.py
107 108 109 110 111 112 | |
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 | |
send_test(config=None)
Send a test message (used by the inline Settings setup).
Source code in quant/engine/notify.py
115 116 117 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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_stageupserts 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 | |
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 | |
empty_state_reason(stage, conn=None)
The 'Not available —
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 | |
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 | |
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 | |
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 | |
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 | |
stage_word(stage)
Plain-word name for a stage key.
Source code in quant/engine/manifest.py
51 52 53 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
latest_price_date(conn=None)
The most recent stored valuation date, or None.
Source code in quant/engine/mtm.py
332 333 334 335 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
flow_sign(flow_type)
Signed direction of a flow for the return math.
Source code in quant/engine/flows.py
30 31 32 | |
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 | |
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 | |
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 | |
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]
|
|
required |
flows
|
list[dict]
|
|
required |
closes
|
dict
|
|
required |
fx
|
dict
|
|
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 | |
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 | |
QuantError
Bases: Exception
Base exception for all quant system errors.
Source code in quant/errors.py
15 16 | |
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_checknever 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 | |