Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

general bug fixes

tilakpatel22f5809b7306cb
diff --git a/.gitignore b/.gitignore
index 73e50489c..29c8e4676 100644
--- a/.gitignore
+++ b/.gitignore
@@ -160,3 +160,10 @@ docs/superpowers/
# ── Local planning docs ───────────────────────────────────────
plans/
**/plans/
+
+# ── Internal Crypto Center phase notes ────────────────────────
+fincept-qt/docs/CRYPTO_CENTER_PHASE_2.md
+fincept-qt/docs/CRYPTO_CENTER_PHASE_3.md
+fincept-qt/docs/CRYPTO_CENTER_PHASE_4.md
+fincept-qt/docs/CRYPTO_CENTER_PHASE_5.md
+fincept-qt/docs/CRYPTO_WALLET_CONNECT.md
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 351ce9e34..2564959af 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -730,6 +730,7 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v019_sector_cache.cpp
src/storage/sqlite/migrations/v020_security_audit_log.cpp
src/storage/sqlite/migrations/v021_max_tokens_default.cpp
+ src/storage/sqlite/migrations/v022_portfolio_broker_link.cpp
)
# Python runner
@@ -871,6 +872,7 @@ set(SERVICE_SOURCES
src/services/portfolio/PortfolioAnalyticsService.cpp
src/services/quantlib/QuantLibClient.cpp
src/services/economics/EconomicsService.cpp
+ src/services/economics/MacroCalendarService.cpp
src/services/agents/AgentService.cpp
src/services/file_manager/FileManagerService.cpp
@@ -1227,6 +1229,9 @@ set(SCREEN_SOURCES
src/screens/ai_quant_lab/QuantModulePanel_RL.cpp
src/screens/ai_quant_lab/QuantModulePanel_DeepAgent.cpp
src/screens/ai_quant_lab/QuantModulePanel_QuantReporting.cpp
+ src/screens/ai_quant_lab/QuantModulePanel_AdvancedDisplays.cpp
+ src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
+ src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
# Backtesting
@@ -1432,6 +1437,9 @@ set_source_files_properties(
src/screens/ai_quant_lab/QuantModulePanel_RL.cpp
src/screens/ai_quant_lab/QuantModulePanel_DeepAgent.cpp
src/screens/ai_quant_lab/QuantModulePanel_QuantReporting.cpp
+ src/screens/ai_quant_lab/QuantModulePanel_AdvancedDisplays.cpp
+ src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
+ src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
src/screens/akshare/AkShareScreen.cpp
src/screens/algo_trading/AlgoTradingScreen.cpp
@@ -1485,7 +1493,6 @@ set_source_files_properties(
src/screens/dashboard/DashboardToolBar.cpp
src/screens/dashboard/MarketPulsePanel.cpp
src/screens/dashboard/TickerBar.cpp
- src/screens/dashboard/WidgetGrid.cpp
src/screens/dashboard/canvas/AddWidgetDialog.cpp
src/screens/dashboard/canvas/DashboardCanvas.cpp
src/screens/dashboard/canvas/DashboardTemplates.cpp
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_2.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_2.md
deleted file mode 100644
index 021f29d2a..000000000
--- a/fincept-qt/docs/CRYPTO_CENTER_PHASE_2.md
+++ /dev/null
@@ -1,152 +0,0 @@
-# Crypto Center — Phase 2 user guide
-
-Phase 2 turns the Crypto Center from a read-only identity surface into a transactional one. You can now:
-
-- See **every token** your wallet holds (SOL + every SPL token), with USD prices and portfolio total.
-- **Buy or sell $FNCPT** for SOL through PumpPortal directly inside the terminal.
-- Browse **the last 50 on-chain operations** for your wallet, parsed into human-readable events.
-- Earn a **30% fee discount** on premium features when you hold ≥ 1,000 $FNCPT.
-
-The terminal never holds your private keys. Every transaction is signed in your wallet (Phantom, Solflare, etc.) — the terminal only forwards the unsigned bytes and waits for the signed result. See `CRYPTO_WALLET_CONNECT.md` for the connection flow.
-
----
-
-## The screen at a glance
-
-```
-┌─ FINCEPT / CRYPTO CENTER ──────────── ● CONNECTED · 7eV4z…aoowY ────┐
-│ HOLDINGS BAR │
-│ SOL 9.74 · $FNCPT 0 · TOTAL $1,247.82 · ● LIVE · HELIUS │
-├──────┬───────┬─────────┬────────┬───────┬────────┬─────────────────┤
-│ HOME │ TRADE │ ACTIVITY│ SETTINGS│ STAKE│ MARKETS│ ROADMAP │
-└──────┴───────┴─────────┴────────┴───────┴────────┴─────────────────┘
-```
-
-The HOLDINGS BAR sits above every tab — your portfolio total never disappears even when you switch tabs. Stake / Markets / Roadmap are placeholders for Phases 3 / 4 / 5 respectively.
-
----
-
-## HOME tab
-
-The HOME tab now shows a **holdings table** instead of three stat boxes. One row per asset:
-
-| TOKEN | BALANCE | PRICE | USD VALUE | % OF PORT |
-|---|---|---|---|---|
-| SOL | 9.7425 | $84.28 | $820.31 | 65.7% |
-| USDC | 420.10 | $1.00 | $420.10 | 33.7% |
-| $FNCPT | 12,304 | $0.0000185 | $0.23 | 0.0% |
-
-Click a row → you're dropped into the **TRADE** tab with that token pre-filled as the FROM side of a swap.
-
-**Verified vs unverified.** By default only Jupiter-verified tokens show — pump.fun wallets accumulate junk airdrops, and showing them all would be noisy. The footer reads `7 verified · 12 unverified hidden` with a **Show all** link. The persistent toggle lives in **Settings**.
-
-**Refresh.** The holdings refresh themselves on a 30-second cadence (or via WebSocket if you're on Helius streaming). Click **REFRESH** to force an immediate re-fetch.
-
----
-
-## TRADE tab — Swap
-
-```
-┌─ SWAP ──────────────────── via PumpPortal · pool=auto ──┐
-│ YOU PAY [ 0.50 ] SOL ▾ Balance: 1.20 SOL │
-│ [MAX] │
-│ │
-│ YOU RECEIVE (EST.) ≈ 12,304 $FNCPT (~$0.23) │
-│ [$FNCPT ▾] │
-│ ────────────────────────────────────────────────── │
-│ ROUTE PumpSwap (auto) │
-│ PRICE IMPACT set by PumpSwap; capped by slippage │
-│ MAX SLIPPAGE 1.00% │
-│ [SWAP] │
-└─────────────────────────────────────────────────────────┘
-```
-
-**Direction.** The FROM and TO combos are populated from your real holdings (FROM) and from the Jupiter verified list + your holdings (TO). For Phase 2, **PumpPortal only routes SOL ↔ $FNCPT** — selecting any other pair shows a "Phase 3 supports arbitrary pairs" message and disables the SWAP button. The combo plumbing is already there for Phase 3.
-
-**Estimate.** PumpPortal has no quote endpoint, so the "YOU RECEIVE" estimate is computed locally from live spot prices (`market:price:token:<mint>`) times the slippage budget. The actual fill is set by PumpSwap at execution; the wallet shows you the decoded transaction independently.
-
-**Slippage.** Default 1%, adjustable up to 5% in Settings. PumpPortal expects an integer percent.
-
-**The SWAP click flow:**
-
-1. **Build** — terminal asks PumpPortal for an unsigned versioned tx (~1 KB).
-2. **MITM gate** — terminal simulates the tx against your RPC. If the simulation reports a revert, the flow aborts before the wallet ever pops. This catches a malicious PumpPortal response that would drain or otherwise misbehave.
-3. **Confirm dialog** — you see a decoded summary: route, amount paid, estimated received, slippage, priority fee, and the simulation result ("OK · N CU"). The SWAP button has a **1.5-second anti-muscle-memory delay** before it arms.
-4. **Freshness gate** — right after you click SWAP in the dialog, the terminal re-simulates with the tx's own blockhash (no replacement). If the blockhash has expired during the time you were reading the dialog, the flow aborts and asks you to retry.
-5. **Wallet signature** — the terminal forwards the unsigned bytes to your wallet over the local bridge. You sign in the wallet UI.
-6. **Submit + poll** — the terminal sends the signed tx to the network and polls `getSignatureStatuses` every 1.5 seconds. After `confirmed`, your balance refreshes automatically (within ~5 seconds).
-
-If anything goes wrong at any step, you see a red error strip with the specific failure. Funds never leave your wallet without your signature.
-
----
-
-## ACTIVITY tab
-
-The last 50 on-chain operations involving your wallet, refreshed every 30 seconds:
-
-```
-TIMESTAMP EVENT ASSET AMOUNT STATUS
-2026-04-28 09:14:02 SWAP SOL → FNCPT 0.5 → 12,304 confirmed
-2026-04-27 14:02:11 RECEIVE SOL 0.10 confirmed
-2026-04-26 11:44:30 SEND USDC 50.00 confirmed
-```
-
-**Filter chips** above the table: ALL · SWAP · SEND · RECEIVE · OTHER.
-
-**Click a row** → opens Solscan in your default browser at the transaction signature.
-
-**Helius parsing.** SWAP / SEND / RECEIVE come from the Helius parsed-tx endpoint (`api.helius.xyz/v0/addresses/<pk>/transactions`). Without a Helius key, the tab falls back to raw signatures only — every event shows as OTHER, but the Solscan link still works. Add a Helius key in **Settings** for real parsing.
-
----
-
-## Fee discount
-
-Every paid feature in Fincept Terminal — AI reports, deep backtests, premium screens — accepts $FNCPT at a **30% discount** when you hold **≥ 1,000 $FNCPT**.
-
-The eligibility chip lights up on the HOLDINGS BAR (`30% OFF`) and the TRADE tab shows projected savings against your current balance. If your balance drops below the threshold, the chip extinguishes within one publish cycle (~30 seconds).
-
-The threshold and applied SKUs are read from `services/billing/FeeDiscountConfig.h` — header-only constants that get easier to swap as Phase 3's tier system lands.
-
----
-
-## Settings tab
-
-- **Default slippage** — 1% (default) up to 5%. Stored in SecureStorage as `wallet.default_slippage_bps`.
-- **Solana RPC** — paste a custom RPC URL in `solana.rpc_url`, or a Helius API key in `solana.helius_api_key`. The HOLDINGS BAR shows `PUBLIC` / `HELIUS` / `CUSTOM` so you always know which RPC you're hitting. Helius is recommended — the public mainnet RPC is rate-limited and disables WebSocket streaming.
-- **Show unverified tokens** — toggle for the holdings table and SWAP combos.
-
-Stake / Markets / Roadmap settings ship with their respective phases.
-
----
-
-## What's not in Phase 2
-
-These ship in later phases:
-
-- **Burn $FNCPT** — deferred to Phase 5 where the buyback worker burns from a treasury account.
-- **Arbitrary pair swaps** — Phase 3 lifts the SOL↔$FNCPT constraint via a generalized router.
-- **Stake / lock** — Phase 3, veFNCPT-style lock with USDC yield.
-- **Prediction markets** — Phase 4, internal venue settling in $FNCPT.
-- **Buyback dashboard** — Phase 5, replaces the static ROADMAP placeholder.
-
-See `plans/crypto-center-future-phases.md` for the full roadmap.
-
----
-
-## Where to find this in code
-
-- `src/screens/crypto_center/` — screen + tabs + panels
-- `src/services/wallet/PumpFunSwapService.{h,cpp}` — PumpPortal client
-- `src/services/wallet/SolanaRpcClient.{h,cpp}` — RPC wrapper, simulation, status polling
-- `src/services/wallet/WalletActivityProducer.{h,cpp}` — Helius parsed-tx
-- `src/services/wallet/TokenPriceProducer.{h,cpp}` — Jupiter Lite Price API, batched per-mint
-- `src/services/wallet/TokenMetadataService.{h,cpp}` — Jupiter verified token list, daily refresh
-- `src/services/billing/FeeDiscountService.{h,cpp}` — eligibility derived from balance
-- `resources/wallet/swap.html` — wallet-side signing bridge
-- `docs/DATAHUB_TOPICS.md` — every hub topic the screen subscribes to
-- `plans/crypto-center-phase-2.md` — implementation plan
-- `plans/crypto-center-trade-security.md` — security walkthrough
-
----
-
-**Last updated:** 2026-05-01
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_3.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_3.md
deleted file mode 100644
index 25eba910c..000000000
--- a/fincept-qt/docs/CRYPTO_CENTER_PHASE_3.md
+++ /dev/null
@@ -1,90 +0,0 @@
-# Crypto Center — Phase 3 user guide (STAKE)
-
-The **STAKE** tab lets you lock $FNCPT for 3 months to 4 years in exchange for **veFNCPT weight** — a non-transferable token-account that grants two things:
-
-1. A pro-rata share of **terminal revenue paid in USDC** (real yield), settled per epoch by the buyback worker.
-2. A **billing tier** (Bronze / Silver / Gold) that unlocks paid screens elsewhere in the terminal — AI Quant Lab, Alpha Arena, premium agents.
-
----
-
-## What you see
-
-```
-┌─ STAKE / LOCK ──────────────────────────────────── DEMO ────────────┐
-│ AMOUNT [ 1,000 ] $FNCPT AVAILABLE 12,304 │
-│ DURATION ◯ 3 MO ◯ 6 MO ● 1 YR ◯ 2 YR ◯ 4 YR │
-│ WEIGHT 1,000 veFNCPT × 0.25 (1 yr) = 250 veFNCPT │
-│ EST. YIELD $42 / week (USDC) │
-│ TIER Silver → Gold (after lock) │
-│ [PREVIEW LOCK] [LOCK] │
-└──────────────────────────────────────────────────────────────────────┘
-
-┌─ ACTIVE LOCKS · 3 positions · Σ 4,500 veFNCPT ── DEMO ──────────────┐
-│ LOCKED DURATION UNLOCKS WEIGHT YIELD (LIFETIME) │
-│ 2,000 4 yr 2030-04-27 2,000 $1,240 USDC │
-│ 1,000 1 yr 2027-04-01 250 $42 USDC │
-│ 500 6 mo 2026-10-27 62.5 $14 USDC │
-└──────────────────────────────────────────────────────────────────────┘
-
-┌─ TIER ────────────────────────────────── current GOLD ──────────────┐
-│ BRONZE 100+ veFNCPT basic API quota │
-│ SILVER 1k+ veFNCPT premium screens │
-│ GOLD 10k+ veFNCPT all agents + arena │
-└──────────────────────────────────────────────────────────────────────┘
-```
-
----
-
-## Demo mode
-
-Phase 3 ships in **demo mode** today. The on-chain `fincept_lock` Anchor program (the contract that actually escrows your $FNCPT and mints the veFNCPT position NFT) is not yet deployed. While in demo mode:
-
-- Every payload carries `is_mock=true`; the head pill on each panel reads **DEMO**.
-- The **PREVIEW LOCK** button shows the math you'd get from the multiplier table.
-- The **LOCK** button is disabled with a "fincept_lock not deployed" tooltip.
-- `ActiveLocks` shows three illustrative positions so you can see the table layout. These are not your positions; they are the same demo numbers shown to every user.
-
-When the program ships:
-
-1. We'll publish the program ID.
-2. You set `fincept.lock_program_id` in `SecureStorage` (Settings → Crypto → Advanced).
-3. The next refresh moves you off mock data: `wallet:locks:<pubkey>` will query `getProgramAccounts` and render your real positions; the **LOCK** button enables and routes through `WalletService::sign_and_send`.
-
-No code changes on your side — the seam is wired.
-
----
-
-## How the multiplier works
-
-veFNCPT weight is computed at lock time and **decays linearly to zero** as you approach the unlock date. The duration multipliers (vs. a 4-yr max-weight lock):
-
-| Duration | Multiplier |
-|---|---|
-| 3 months | 0.0625 |
-| 6 months | 0.125 |
-| 1 year | 0.25 |
-| 2 years | 0.5 |
-| 4 years | 1.0 |
-
-Example: locking 1,000 $FNCPT for 1 year = 250 veFNCPT. Locking 1,000 $FNCPT for 4 years = 1,000 veFNCPT.
-
-The expected weekly USDC yield is `your_weight / total_weight × 25 % × terminal_revenue`. 25 % is the staker share of revenue per the Phase 5 buyback split (50 / 25 / 25 across buyback / staker yield / treasury top-up).
-
----
-
-## Tier-driven gating
-
-Once `billing:tier:<your_pubkey>` lands at Silver+, paid screens that were hidden in the nav appear. Specifically (plan §3.6):
-
-- **Silver** (1k+ veFNCPT) reveals premium screens (AI Quant Lab access).
-- **Gold** (10k+ veFNCPT) reveals Alpha Arena + every agent.
-
-The `TierService` emits `tier_changed(pubkey, tier)` and the gated screens listen for it — so the moment your tier increases, the nav updates without a restart. If you can't see a screen you expect, check the TIER panel on the STAKE tab; the `next_threshold_raw` field tells you exactly how much more veFNCPT you need.
-
----
-
-## What's not here yet
-
-- **Governance voting.** Phase 3 ships the lock surface only; voting on `fincept_market` listings (Phase 4) and on protocol parameters (Phase 5) lands in a follow-up.
-- **Lock extension UI.** You can only create new locks today. Extending an existing lock will land alongside the program deployment — the helper exists in `StakingService::build_extend_tx` but the UI button is hidden in mock mode.
-- **Withdraw on expiry.** Same as above — the auto-prompt fires when `unlock_ts <= now`, but only against real on-chain positions.
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_4.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_4.md
deleted file mode 100644
index 3449f740e..000000000
--- a/fincept-qt/docs/CRYPTO_CENTER_PHASE_4.md
+++ /dev/null
@@ -1,78 +0,0 @@
-# Crypto Center — Phase 4 user guide (MARKETS)
-
-The **MARKETS** tab is Fincept's **internal prediction market** entry point. Markets are denominated and settled in **$FNCPT only** — no USDC, no off-chain ledger. Examples (curated demo dataset until launch):
-
-- "Fed cuts in May 2026"
-- "NYC max 80F+ on May 1"
-- "$FNCPT > $0.0001 by month end"
-
-This is a third sibling alongside Polymarket and Kalshi in the terminal's prediction-market tooling. Browsing on the MARKETS tab feels identical to those — same `PredictionExchangeAdapter` interface, same data shape, same hub-driven refresh pattern.
-
----
-
-## What you see today
-
-```
-┌─ MARKETS ────────────────────────────────────────────── DEMO ────────┐
-│ MARKET YES NO 24h VOL EXPIRES │
-│ Fed cuts in May 2026 0.62 0.38 1.2M 2026-05-07│
-│ NYC max 80F+ on May 1 0.71 0.29 83k 2026-05-01│
-│ $FNCPT > $0.0001 by month end 0.45 0.55 421k 2026-05-31│
-│ │
-│ Demo dataset. Set `fincept.markets_endpoint` in SecureStorage and │
-│ deploy the fincept_market Anchor program for live trading. │
-└───────────────────────────────────────────────────────────────────────┘
-```
-
----
-
-## Demo mode (current)
-
-Phase 4 ships in **demo mode**. Two things have to land before the tab becomes transactional:
-
-1. The Fincept **matching engine** (HTTP + WebSocket on `markets.fincept.in`). When this is up, set `fincept.markets_endpoint` in SecureStorage and the adapter will fetch live markets, books, and price history.
-2. The on-chain **`fincept_market` Anchor program** that escrows YES/NO collateral and resolves payouts. When deployed, set `fincept.market_program_id` and the order-entry path enables.
-
-Until both are present, the MARKETS tab serves the curated three-market dataset baked into `FinceptInternalAdapter` so you can see what the screen will look like and verify the data shapes integrate cleanly with the unified `PredictionExchangeAdapter` (which also serves Polymarket and Kalshi).
-
----
-
-## How it integrates
-
-The Fincept internal adapter is registered with `PredictionExchangeRegistry` alongside `PolymarketAdapter` and `KalshiAdapter`. Any code that already iterates the registry (Polymarket / Kalshi screen, command bar, MCP tools) can switch to `fincept` without special-casing.
-
-**Hub topics** are reserved (with policies) for the live path:
-
-- `prediction:fincept:markets` — market list, refreshes every 30 s.
-- `prediction:fincept:orderbook:<asset_id>` — per-asset book, WebSocket-driven.
-- `prediction:fincept:price:<asset_id>` — last-trade price scalar.
-
-When the matching engine ships, the adapter will publish to those topics; existing consumers attach automatically.
-
----
-
-## What you can't do yet
-
-- **Place orders.** `place_order` returns `error_occurred("not deployed", …)` while in demo mode — the order ticket UI shows a clear "service unavailable" banner.
-- **See your positions.** Same gate — needs the on-chain program for any real escrow to exist.
-- **Create markets.** Plan §4.1 reserves market creation for **Gold tier** users; the proposal/vote flow lands with the engine.
-- **Earn from order flow.** veFNCPT lockers will receive a share of trading fees (Phase 3 §3.4) once the engine is settling real volume.
-
----
-
-## When the engine ships
-
-You won't need to update the terminal — the seam is already in place. Configuration lives in SecureStorage:
-
-- `fincept.markets_endpoint` — base URL of the matching engine. Empty = demo mode.
-- `fincept.market_program_id` — base58 program ID for `fincept_market`. Empty = trading disabled.
-
-Both keys are user-configurable from Settings → Crypto → Advanced. The MARKETS tab will pick them up on the next visibility tick.
-
----
-
-## Why $FNCPT-only
-
-Real-money prediction markets are regulated as derivatives in many jurisdictions. By denominating in $FNCPT we keep the venue framed as a **play-money internal mechanic** of the terminal, not a regulated financial product. We may geo-block sign-up in regions where legal review concludes otherwise.
-
-This is a policy decision; the engineering plan ships the same regardless. See `plans/crypto-center-future-phases.md` §4.7 for the rationale.
diff --git a/fincept-qt/docs/CRYPTO_CENTER_PHASE_5.md b/fincept-qt/docs/CRYPTO_CENTER_PHASE_5.md
deleted file mode 100644
index 701746a29..000000000
--- a/fincept-qt/docs/CRYPTO_CENTER_PHASE_5.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Crypto Center — Phase 5 user guide (Buyback & Burn)
-
-The **ROADMAP** tab in the Crypto Center shows Fincept's **value loop**: how much terminal revenue is being spent buying $FNCPT off the market and burning it. This is the demand engine that justifies the token long-term.
-
----
-
-## What you see
-
-```
-┌─ BUYBACK & BURN ─ epoch 47 · 2026-04-21 → 2026-04-27 ─── ● LIVE ────┐
-│ THIS EPOCH │
-│ REVENUE $42,310 (subs $32k · pred-mkt $8k · misc $2k) │
-│ BUYBACK $21,155 (50% of revenue) │
-│ $FNCPT BOUGHT 82.4 M $FNCPT (avg $0.0002570) │
-│ $FNCPT BURNED 82.4 M $FNCPT │
-│ BURN TX 5kj3w…XXXX (click to open Solscan) │
-│ ──────────────────────────────────────────────────────── │
-│ ALL-TIME │
-│ BURNED 1.42 B $FNCPT │
-│ SUPPLY REMAINING 8.58 B $FNCPT │
-│ SPENT ON BUYBACK $384,201.00 │
-└──────────────────────────────────────────────────────────────────────┘
-
-┌─ SUPPLY CHART · 12 MONTHS ─── ● TOTAL ● CIRCULATING ● BURNED ─────┐
-│ [ time-series chart, three lines, last 12 months ] │
-└──────────────────────────────────────────────────────────────────────┘
-
-┌─ TREASURY ───────────────────────────────────── ● LIVE ─────────────┐
-│ USDC RESERVES $1.84M │
-│ SOL RESERVES 234.00 SOL ($19.7k) │
-│ TOTAL USD $1.86M │
-│ RUNWAY @ CURRENT 18 months ($100,000/mo) │
-│ MULTI-SIG 3-of-5 (click to open Squads) │
-└──────────────────────────────────────────────────────────────────────┘
-```
-
-Three panels stacked, scrollable on short windows. Each has its own LIVE / DEMO pill showing whether the data is real or mocked (see below).
-
----
-
-## Where the data comes from
-
-A separate **Fincept buyback worker** (lives outside this repo, in `services/buyback-worker/`) does the heavy lifting:
-
-1. **Tally revenue** — sums Stripe subscriptions + on-chain prediction-market fees + misc, weekly.
-2. **Compute budget** — initial split is **50% buyback / 25% staker yield / 25% treasury**.
-3. **Execute** — splits the budget into hourly chunks and routes through Jupiter to avoid frontrunning a single big buy.
-4. **Burn** — once $FNCPT is in the treasury account, the worker calls SPL Token `burn_checked` to permanently destroy it. The burn transaction signature is the canonical receipt.
-5. **Publish** — the worker POSTs an epoch summary + cumulative totals + 12-month supply history to a Fincept HTTP endpoint that the terminal polls.
-
-The terminal **only reads** — it has no on-chain code in Phase 5, no custodial mechanism, and no signing authority over the treasury vault.
-
----
-
-## Demo mode
-
-Until the buyback worker endpoint is configured, the dashboard ships built-in mock data so the UI is reviewable. The mock numbers are illustrative:
-
-- **Epoch 47** revenue $42,310 → buyback $21,155 → 82.4 M $FNCPT bought + burned.
-- **All-time** 1.42 B $FNCPT burned, 8.58 B remaining, $384,201 spent.
-- **Treasury** $1.84M USDC + 234 SOL = ~$1.86M total, 18 months runway @ $100k/mo.
-
-Each panel head shows **DEMO** in amber when any data on it is mocked, and the BURN TX link tooltip reads "Demo signature — connect a treasury endpoint for a real burn tx" so nobody mistakes the placeholders for real on-chain receipts.
-
----
-
-## Configuring real data
-
-When the worker is deployed, configure the following keys in **SecureStorage**:
-
-| Key | Required | Notes |
-|---|---|---|
-| `fincept.treasury_endpoint` | yes | HTTP base URL where the worker publishes summaries. The terminal hits `<endpoint>/buyback/current`, `<endpoint>/burn/total`, `<endpoint>/supply/history`. |
-| `fincept.treasury_pubkey` | yes | base58 pubkey of the Squads multisig vault. Used by `TreasuryService` to fetch SOL + USDC reserves directly from Solana RPC. |
-| `fincept.treasury_monthly_opex_usd` | optional | default $100,000. Used for runway. Update as the team scales. |
-| `fincept.treasury_multisig_label` | optional | default `3-of-5`. Free-form chip text. |
-| `fincept.treasury_multisig_url` | optional | default `https://app.squads.so/squads/<pubkey>`. Override if you point at a different vault UI. |
-
-Once `fincept.treasury_endpoint` is set, the head pill on **Buyback & Burn** flips from `DEMO` to `LIVE`. Same for the treasury card the moment `fincept.treasury_pubkey` is configured.
-
----
-
-## Hub topics
-
-Five terminal-wide topics power the dashboard. None carry a `<pubkey>` segment — the same numbers are shown to every user.
-
-| Topic | Producer | TTL | Notes |
-|---|---|---|---|
-| `treasury:buyback_epoch` | `BuybackBurnService` | 60 s | Current epoch summary + burn signature |
-| `treasury:burn_total` | `BuybackBurnService` | 5 min | All-time burned + remaining supply |
-| `treasury:supply_history` | `BuybackBurnService` | 1 h | 12-month time-series (`QVector<SupplyHistoryPoint>`) |
-| `treasury:reserves` | `TreasuryService` | 5 min | USDC + SOL + USD value, multisig label/url |
-| `treasury:runway` | `TreasuryService` | 5 min | Derived: `total_usd / monthly_opex_usd` |
-
-See `docs/DATAHUB_TOPICS.md` for full payload shapes.
-
----
-
-## Where to find this in code
-
-- `src/services/wallet/BuybackBurnService.{h,cpp}` — Producer, three topics, dual real/mock paths
-- `src/services/wallet/TreasuryService.{h,cpp}` — Producer, two topics, peeks SOL price from `market:price:token:<wSOL>`
-- `src/screens/crypto_center/panels/BuybackBurnPanel.{h,cpp}` — top section, Solscan-clickable burn signature
-- `src/screens/crypto_center/panels/SupplyChartPanel.{h,cpp}` — middle section, QtCharts QChartView
-- `src/screens/crypto_center/panels/TreasuryPanel.{h,cpp}` — bottom section, Squads-clickable multisig
-- `src/screens/crypto_center/tabs/RoadmapTab.{h,cpp}` — wraps the three panels in a QScrollArea
-- `plans/crypto-center-future-phases.md` §5 — original plan
-- `docs/DATAHUB_TOPICS.md` "Buyback & burn dashboard" section — topic catalogue
-
----
-
-**Last updated:** 2026-05-01
diff --git a/fincept-qt/docs/CRYPTO_WALLET_CONNECT.md b/fincept-qt/docs/CRYPTO_WALLET_CONNECT.md
deleted file mode 100644
index b43b67c56..000000000
--- a/fincept-qt/docs/CRYPTO_WALLET_CONNECT.md
+++ /dev/null
@@ -1,91 +0,0 @@
-# Connecting your Solana wallet
-
-The **Crypto Center** screen lets you connect a Solana wallet to Fincept Terminal so you can see your $FNCPT and SOL balances, swap, and earn the fee discount on premium features. The terminal **never sees your private keys** — your wallet (Phantom, Solflare, Backpack, etc.) signs every operation locally.
-
----
-
-## Supported wallets
-
-Any Solana wallet that handles a `signMessage` request in your default browser will work, including:
-
-- **Phantom** — recommended (most active development, broad hardware-wallet support)
-- **Solflare** — desktop + mobile, native Ledger
-- **Backpack** — newer, desktop + mobile
-- **Glow**, **Coinbase Wallet (Solana mode)** — also work
-
-The wallet does **not** need a browser extension to be installed in the same browser as Fincept Terminal — the terminal opens your default browser, the wallet's extension or webapp picks up the request there.
-
----
-
-## Connecting
-
-1. Open the **Crypto Center** screen from the main nav.
-2. Click **CONNECT WALLET**.
-3. Your default browser opens a one-page Fincept handshake. Click **Connect** there. Your wallet pops a "Sign this message" prompt — approve it.
-4. The browser tab closes automatically and the terminal shows your public key, SOL balance, and $FNCPT balance.
-
-The "Sign this message" prompt is a **one-time identity challenge** — Fincept asks the wallet to sign a random nonce so we know the public key really belongs to you. Nothing is sent on-chain; no SOL leaves your wallet for this step.
-
----
-
-## What gets stored locally
-
-Fincept Terminal saves only:
-
-- Your **public key** (base58 string)
-- The wallet **label** ("Phantom", "Solflare", etc.)
-- The **timestamp** of the connection
-
-These live in the encrypted **SecureStorage** under the keys `wallet.pubkey`, `wallet.label`, and `wallet.connected_at`. **Private keys, signatures, and seed phrases are never seen by the terminal** — they stay in your wallet's vault.
-
----
-
-## Reconnecting on next launch
-
-When you restart Fincept Terminal with a previously-connected wallet, the screen restores the public key from SecureStorage and shows balances immediately, **without** prompting your wallet again. This is a "soft connect" — any operation that needs a signature (a swap, for example) re-prompts the wallet at that moment.
-
----
-
-## Disconnecting
-
-Click **Disconnect** on the wallet status card. The terminal:
-
-1. Wipes the public key, label, and timestamp from SecureStorage.
-2. Stops all subscriptions tied to that wallet (balance, activity, fee discount).
-3. Returns the screen to its empty state.
-
-If you connect a different wallet next time, the new public key replaces the old — the previous one is fully removed.
-
----
-
-## Security model in one paragraph
-
-The terminal opens a loopback HTTP server on `127.0.0.1` with a random port and a single-use token, then opens your default browser to that URL. The browser-side page handles the wallet adapter handshake (extension or WalletConnect), then POSTs the signed nonce + public key back to the loopback server. The terminal verifies the ed25519 signature against the public key before persisting anything. The bridge port is bound to **localhost only** — other machines on your network cannot see it. The signed nonce is single-use and expires after 60 seconds. See `plans/crypto-center-security-walkthrough.md` for the full threat model and mitigations.
-
----
-
-## Troubleshooting
-
-**"Connection cancelled"** — you closed the browser tab or clicked Cancel in the wallet. Click **CONNECT WALLET** again to retry.
-
-**"Signature verification failed"** — extremely rare; almost always indicates a wallet bug or a deliberately-malformed signature. Try a different wallet or upgrade your wallet extension.
-
-**Browser doesn't open** — your default browser may not be set, or the OS is blocking handler launches. Set a default browser in OS settings and try again.
-
-**Balances show `—` after connecting** — the RPC may be slow. The Settings tab lets you provide a Helius API key for a faster RPC; without one, the terminal falls back to the public mainnet RPC (rate-limited).
-
----
-
-## Where to find this in code
-
-- `src/services/wallet/WalletService.{h,cpp}` — connection state machine
-- `src/services/wallet/ConnectWalletDialog.{h,cpp}` — challenge + verification
-- `src/services/wallet/LocalWalletBridge.{h,cpp}` — loopback HTTP server
-- `src/services/wallet/Ed25519Verifier.{h,cpp}` — signature verification (orlp/ed25519)
-- `resources/wallet/connect.html` — browser-side handshake page
-- `plans/crypto-center-wallet-connect.md` — original plan
-- `plans/crypto-center-security-walkthrough.md` — security review
-
----
-
-**Last updated:** 2026-05-01
diff --git a/fincept-qt/docs/DATAHUB_TOPICS.md b/fincept-qt/docs/DATAHUB_TOPICS.md
index 10b350647..44318d34e 100644
--- a/fincept-qt/docs/DATAHUB_TOPICS.md
+++ b/fincept-qt/docs/DATAHUB_TOPICS.md
@@ -45,6 +45,7 @@ hub registrant for `ws:<exchange>:*`.
| Pattern | Producer | TTL | Min interval | Notes |
|---|---|---|---|---|
| `econ:<source>:<request_id>` | `EconomicsService` | 1 h | 60 s | `source` = fred, worldbank, imf, oecd, etc. |
+| `econ:fincept:upcoming_events` | `MacroCalendarService` | 5 min | 60 s | HTTP-backed (`api.fincept.in/macro/upcoming-events?limit=25`). Payload: `QJsonArray` of `{event, country, date, time, importance, actual, forecast, previous}`. Consumed by the dashboard `EconomicCalendarWidget`. |
| `dbnomics:<provider>:<dataset>:<series>` | `DBnomicsService` | 1 h | 60 s | Observations endpoint only |
| `govdata:<provider>:<request_id>` | `GovDataService` | 1 h | 60 s | Gov open-data APIs |
diff --git a/fincept-qt/scripts/yfinance_data.py b/fincept-qt/scripts/yfinance_data.py
index 0edc9118e..6959ddac1 100644
--- a/fincept-qt/scripts/yfinance_data.py
+++ b/fincept-qt/scripts/yfinance_data.py
@@ -757,6 +757,161 @@ def get_portfolio_nav_history(positions, period='6mo'):
return {"dates": [], "navs": [], "error": str(e)}
+def get_portfolio_nav_history_replay(transactions):
+ """Reconstruct true daily NAV by replaying transactions over time.
+
+ Unlike get_portfolio_nav_history (which back-projects today's quantities),
+ this walks the transaction list and computes position[sym](t) = running
+ sum of BUY qty − SELL qty for transactions whose date ≤ t. The chart line
+ therefore reflects when capital was actually deployed: it starts at the
+ first BUY date (not 1y back from today), steps when buys/sells occur, and
+ moves with market prices in between.
+
+ transactions: list of {"date": "YYYY-MM-DD", "symbol": str, "type": str,
+ "quantity": float, "price": float}.
+ Types BUY / SELL drive position changes. DIVIDEND and SPLIT
+ are ignored for now (DIVIDEND adds cash but we don't model
+ cash; SPLIT would multiply qty but is a future addition).
+
+ Returns: {
+ "dates": ["YYYY-MM-DD", ...], # ascending, trading days only
+ "navs": [float, ...], # market value of positions on each day
+ "costs": [float, ...], # cost basis on each day (BUY-WAC, SELL reduces proportionally)
+ "resolved": {sym: yf_sym}, "missing": [sym, ...]
+ }
+ """
+ try:
+ from datetime import date as _date, timedelta
+ import pandas as pd
+
+ if not transactions:
+ return {"dates": [], "navs": [], "costs": []}
+
+ # Filter to BUY / SELL only (DIVIDEND / SPLIT don't move position).
+ txns = [t for t in transactions
+ if str(t.get("type", "")).upper() in ("BUY", "SELL")
+ and t.get("symbol") and t.get("date")]
+ if not txns:
+ return {"dates": [], "navs": [], "costs": []}
+
+ # Sort ascending by date so the replay walk is monotonic.
+ txns.sort(key=lambda t: t["date"])
+
+ symbols = sorted({t["symbol"] for t in txns})
+ first_date = pd.Timestamp(txns[0]["date"]).normalize()
+ today = pd.Timestamp(_date.today()).normalize()
+ if first_date > today:
+ return {"dates": [], "navs": [], "costs": [],
+ "error": "earliest transaction date is in the future"}
+
+ # Pick a yfinance period string that covers first_date → today with a
+ # bit of slack. yfinance period accepts {1mo,3mo,6mo,1y,2y,5y,10y,ytd,max}.
+ days_back = (today - first_date).days + 7
+ if days_back <= 31:
+ period = "1mo"
+ elif days_back <= 95:
+ period = "3mo"
+ elif days_back <= 190:
+ period = "6mo"
+ elif days_back <= 370:
+ period = "1y"
+ elif days_back <= 740:
+ period = "2y"
+ elif days_back <= 1850:
+ period = "5y"
+ elif days_back <= 3700:
+ period = "10y"
+ else:
+ period = "max"
+
+ resolved = _resolve_for_history(symbols, period)
+ if not resolved:
+ return {"dates": [], "navs": [], "costs": [],
+ "error": "no historical data for any symbol",
+ "missing": symbols}
+
+ # Build a DataFrame of close prices, columns = symbols, indexed by date.
+ # Forward-fill so a symbol that listed mid-period contributes a stable
+ # price across non-trading gaps in its own series.
+ closes_df = pd.DataFrame({s: ser for s, (_yf, ser) in resolved.items()})
+ closes_df = closes_df.sort_index().ffill()
+
+ # Trim the index to the replay window: first_date → today.
+ closes_df = closes_df[closes_df.index >= first_date]
+ if closes_df.empty:
+ return {"dates": [], "navs": [], "costs": [],
+ "error": "no trading days in the requested window"}
+
+ # Walk transactions and the price index in lockstep. For each trading
+ # day we know the cumulative position vector — apply close prices to
+ # get NAV. Cost basis uses weighted-average cost (WAC): BUYs add to
+ # invested capital; SELLs reduce by (sold_qty × current_avg_cost).
+ positions = {s: 0.0 for s in symbols} # qty per symbol
+ wac_cost = {s: 0.0 for s in symbols} # avg cost per share
+ cost_basis_total = 0.0 # running cost basis
+ tx_idx = 0
+ n_tx = len(txns)
+
+ out_dates = []
+ out_navs = []
+ out_costs = []
+
+ for ts, row in closes_df.iterrows():
+ day = ts.date().isoformat()
+
+ # Apply every transaction whose date ≤ today's trading day.
+ while tx_idx < n_tx and txns[tx_idx]["date"] <= day:
+ tx = txns[tx_idx]
+ sym = tx["symbol"]
+ qty = float(tx.get("quantity", 0))
+ price = float(tx.get("price", 0))
+ kind = str(tx["type"]).upper()
+ if sym not in positions:
+ # Symbol has no resolved price history — track position
+ # anyway so we don't desync, but it won't contribute to NAV.
+ positions[sym] = 0.0
+ wac_cost[sym] = 0.0
+ if kind == "BUY":
+ new_qty = positions[sym] + qty
+ if new_qty > 0:
+ # Weighted-average cost update.
+ wac_cost[sym] = (positions[sym] * wac_cost[sym] + qty * price) / new_qty
+ positions[sym] = new_qty
+ cost_basis_total += qty * price
+ elif kind == "SELL":
+ sell_qty = min(qty, positions[sym])
+ cost_basis_total -= sell_qty * wac_cost[sym]
+ positions[sym] -= sell_qty
+ if positions[sym] <= 1e-9:
+ positions[sym] = 0.0
+ wac_cost[sym] = 0.0
+ tx_idx += 1
+
+ # NAV = Σ close × qty for symbols we have prices for on this day.
+ nav = 0.0
+ for s in symbols:
+ if s not in row.index:
+ continue
+ close = row[s]
+ if pd.isna(close):
+ continue
+ nav += float(close) * positions.get(s, 0.0)
+
+ out_dates.append(day)
+ out_navs.append(round(nav, 4))
+ out_costs.append(round(cost_basis_total, 4))
+
+ return {
+ "dates": out_dates,
+ "navs": out_navs,
+ "costs": out_costs,
+ "resolved": {s: yf for s, (yf, _) in resolved.items()},
+ "missing": [s for s in symbols if s not in resolved],
+ }
+ except Exception as e:
+ return {"dates": [], "navs": [], "costs": [], "error": str(e)}
+
+
def get_historical_period(symbol, period='6mo', interval='1d'):
"""Fetch historical data using a period string (e.g., '1mo', '6mo', '1y', '5y')"""
try:
@@ -953,6 +1108,24 @@ def main(args=None):
if positions is not None:
result = get_portfolio_nav_history(positions, period)
+ elif command == "portfolio_nav_history_replay":
+ # Args layout: <transactions_json_path>
+ # The JSON file contains a list of {date, symbol, type, quantity, price}
+ # objects. We replay them over time to compute true historical NAV
+ # and cost basis instead of back-projecting today's positions.
+ if len(args) < 2:
+ result = {"error": "Usage: yfinance_data.py portfolio_nav_history_replay <transactions_json_path>"}
+ else:
+ try:
+ with open(args[1], "r", encoding="utf-8") as f:
+ txns = json.load(f)
+ if not isinstance(txns, list):
+ result = {"error": "transactions JSON must be a list"}
+ else:
+ result = get_portfolio_nav_history_replay(txns)
+ except Exception as e:
+ result = {"error": f"failed to read transactions JSON: {e}"}
+
elif command == "historical_period":
if len(args) < 2:
result = {"error": "Usage: python yfinance_data.py historical_period <symbol> [period] [interval]"}
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index fb96f4bca..e939e6b17 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -28,6 +28,7 @@
#include "services/agents/AgentService.h"
#include "services/dbnomics/DBnomicsService.h"
#include "services/economics/EconomicsService.h"
+#include "services/economics/MacroCalendarService.h"
#include "services/geopolitics/GeopoliticsService.h"
#include "services/gov_data/GovDataService.h"
#include "services/ma_analytics/MAAnalyticsService.h"
@@ -91,6 +92,27 @@
# define FT_MARK(n) do { fprintf(stderr, "FT_MARK %d\n", (n)); fflush(stderr); } while(0)
#endif
+// Wire the two app-level lifecycle handlers that fire after the primary
+// window exists: SingleApplication::receivedMessage (a re-launch of the exe
+// asks us to open another WindowFrame) and QApplication::lastWindowClosed
+// (surface the Launchpad instead of quitting; the Launchpad's own close
+// handler quits explicitly). Called from both the post-setup-screen path
+// and the no-setup path so the two branches stay in sync.
+static void wire_app_lifecycle(SingleApplication& app) {
+ QObject::connect(&app, &SingleApplication::receivedMessage,
+ [](quint32 /*instanceId*/, QByteArray /*message*/) {
+ auto* w = new fincept::WindowFrame(fincept::WindowFrame::next_window_id());
+ w->setAttribute(Qt::WA_DeleteOnClose);
+ w->show();
+ w->raise();
+ w->activateWindow();
+ LOG_INFO("App", "New window opened via secondary instance request");
+ });
+ QObject::connect(&app, &QApplication::lastWindowClosed, &app, []() {
+ fincept::screens::LaunchpadScreen::instance()->surface();
+ });
+}
+
int main(int argc, char* argv[]) {
FT_MARK(1);
// ── Parse --profile <name> from argv before Qt initialises ───────────────
@@ -137,6 +159,14 @@ int main(int argc, char* argv[]) {
#endif
app.setApplicationVersion(QStringLiteral(FINCEPT_VERSION_STRING));
+ // Quit only when LaunchpadScreen::closeEvent calls QCoreApplication::quit().
+ // Default Qt behaviour fires lastWindowClosed AND schedules an auto-quit;
+ // we connect a slot to surface() the Launchpad on lastWindowClosed, and
+ // the auto-quit would race that slot — sometimes killing the app while
+ // the launchpad is mid-show. With this off, the only quit path is the
+ // explicit one in LaunchpadScreen::closeEvent.
+ app.setQuitOnLastWindowClosed(false);
+
// ── Secondary instance: signal primary to open a new window, then exit ───
// The primary receives receivedMessage() and calls open_new_window().
if (app.isSecondary()) {
@@ -234,6 +264,9 @@ int main(int argc, char* argv[]) {
fincept::services::EconomicsService::instance().ensure_registered_with_hub();
fincept::services::DBnomicsService::instance().ensure_registered_with_hub();
fincept::services::GovDataService::instance().ensure_registered_with_hub();
+ // Macro calendar: HTTP-backed `econ:fincept:upcoming_events` producer
+ // serving the dashboard EconomicCalendarWidget.
+ fincept::services::MacroCalendarService::instance().ensure_registered_with_hub();
// Phase 7: DataStreamManager as the broker:* producer (positions,
// orders, balance, holdings, quote, ticks). Per-account topic shape
// `broker:<id>:<account_id>:<channel>`.
@@ -480,6 +513,7 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v019();
fincept::register_migration_v020();
fincept::register_migration_v021();
+ fincept::register_migration_v022();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
@@ -679,21 +713,10 @@ int main(int argc, char* argv[]) {
.arg(saved_ids.size() > 0 ? saved_ids.size() - 1 : 0));
}
- // Wire new-window handler now that the primary window exists
- QObject::connect(&app, &SingleApplication::receivedMessage,
- [](quint32 /*instanceId*/, QByteArray /*message*/) {
- auto* w = new fincept::WindowFrame(fincept::WindowFrame::next_window_id());
- w->setAttribute(Qt::WA_DeleteOnClose);
- w->show();
- w->raise();
- w->activateWindow();
- LOG_INFO("App", "New window opened via secondary instance request");
- });
- // Phase 9 trim: surface Launchpad instead of quitting on last
- // frame close. Closing the Launchpad itself quits.
- QObject::connect(&app, &QApplication::lastWindowClosed, &app, []() {
- fincept::screens::LaunchpadScreen::instance()->surface();
- });
+ // Wire new-window handler + Launchpad surface now that the
+ // primary window exists. Single source of truth — see
+ // wire_app_lifecycle() at the top of this file.
+ wire_app_lifecycle(app);
if (!fincept::ai_chat::LlmService::instance().is_configured())
LOG_WARN("App",
@@ -755,24 +778,9 @@ int main(int argc, char* argv[]) {
.arg(saved_ids.size() - 1));
}
- // ── New-window handler: fires when the user re-launches the exe ──────────
- // The secondary instance sends "--new-window" and exits. We construct a new
- // independent WindowFrame in this process. WA_DeleteOnClose ensures cleanup.
- // QApplication::lastWindowClosed() → quit() handles the final exit.
- QObject::connect(&app, &SingleApplication::receivedMessage, [](quint32 /*instanceId*/, QByteArray /*message*/) {
- auto* w = new fincept::WindowFrame(fincept::WindowFrame::next_window_id());
- w->setAttribute(Qt::WA_DeleteOnClose);
- w->show();
- w->raise();
- w->activateWindow();
- LOG_INFO("App", "New window opened via secondary instance request");
- });
-
- // Phase 9 trim: surface Launchpad instead of quitting on last frame
- // close. The launchpad's own close event quits explicitly.
- QObject::connect(&app, &QApplication::lastWindowClosed, &app, []() {
- fincept::screens::LaunchpadScreen::instance()->surface();
- });
+ // Wire new-window handler + Launchpad surface — see wire_app_lifecycle()
+ // at the top of this file for the contract.
+ wire_app_lifecycle(app);
// If requirements files changed (app update), sync packages in background
// without blocking the user. Connect setup_complete so failures are logged
diff --git a/fincept-qt/src/datahub/DataHub.cpp b/fincept-qt/src/datahub/DataHub.cpp
index 18d9f9116..dce347164 100644
--- a/fincept-qt/src/datahub/DataHub.cpp
+++ b/fincept-qt/src/datahub/DataHub.cpp
@@ -18,6 +18,13 @@ qint64 now_ms() {
return QDateTime::currentMSecsSinceEpoch();
}
+// Gap 3 helper: returns the freshness window in ms for a topic state.
+// Picks the per-publish override if set; otherwise the policy TTL.
+template <typename TopicStateT>
+inline int effective_ttl_ms(const TopicStateT& st) {
+ return st.ttl_override_ms > 0 ? st.ttl_override_ms : st.policy.ttl_ms;
+}
+
// Phase 8 / decision 9.2: walk up from the owner to its top-level widget
// and read the `fincept.active_for_work` dynamic property that WindowFrame
// sets in its constructor + changeEvent. If the owner is not a QWidget or
@@ -166,45 +173,87 @@ void DataHub::rebuild_pattern_index() {
void DataHub::on_owner_destroyed(QObject* owner) {
// Note: owner is being destroyed, do NOT dereference it as QObject*.
// We only use the pointer value as a map key.
- QMutexLocker lock(&mutex_);
+ QStringList newly_idle; // emitted outside the lock at the end
+ {
+ QMutexLocker lock(&mutex_);
- auto topics_it = owner_topics_.find(owner);
- if (topics_it != owner_topics_.end()) {
- for (const auto& topic : topics_it.value()) {
- auto sub_it = subscriptions_.find(topic);
- if (sub_it == subscriptions_.end()) continue;
- auto& vec = sub_it.value();
- vec.erase(std::remove_if(vec.begin(), vec.end(),
- [owner](const Subscription& s) { return s.owner.data() == owner; }),
- vec.end());
- if (vec.isEmpty()) {
- subscriptions_.erase(sub_it);
- // Topic just went idle — drop cached state if policy opted in.
- // Done under the same lock to keep state coherent.
- if (auto ts_it = topics_.find(topic);
- ts_it != topics_.end() && ts_it->policy.drop_on_idle) {
- topics_.erase(ts_it);
+ // Gap 1 fix: also drop owner from the per-topic error map. Done
+ // first because the data unsubscribe path uses the same maps for
+ // bookkeeping cleanup.
+ if (auto eit = error_owner_topics_.find(owner); eit != error_owner_topics_.end()) {
+ for (const auto& topic : eit.value()) {
+ auto bucket = error_subscriptions_.find(topic);
+ if (bucket == error_subscriptions_.end()) continue;
+ bucket.value().erase(std::remove_if(bucket.value().begin(), bucket.value().end(),
+ [owner](const ErrorSub& e) { return e.owner.data() == owner; }), bucket.value().end());
+ if (bucket.value().isEmpty()) error_subscriptions_.erase(bucket);
+ }
+ error_owner_topics_.erase(eit);
+ }
+ if (auto epit = error_owner_patterns_.find(owner); epit != error_owner_patterns_.end()) {
+ for (const auto& pattern : epit.value()) {
+ auto bucket = error_pattern_subscriptions_.find(pattern);
+ if (bucket == error_pattern_subscriptions_.end()) continue;
+ bucket.value().erase(std::remove_if(bucket.value().begin(), bucket.value().end(),
+ [owner](const ErrorSub& e) { return e.owner.data() == owner; }), bucket.value().end());
+ if (bucket.value().isEmpty()) error_pattern_subscriptions_.erase(bucket);
+ }
+ error_owner_patterns_.erase(epit);
+ }
+
+ auto topics_it = owner_topics_.find(owner);
+ if (topics_it != owner_topics_.end()) {
+ for (const auto& topic : topics_it.value()) {
+ auto sub_it = subscriptions_.find(topic);
+ if (sub_it == subscriptions_.end()) continue;
+ auto& vec = sub_it.value();
+ vec.erase(std::remove_if(vec.begin(), vec.end(),
+ [owner](const Subscription& s) { return s.owner.data() == owner; }),
+ vec.end());
+ if (vec.isEmpty()) {
+ subscriptions_.erase(sub_it);
+ // Topic just went idle — drop cached state if policy opted in.
+ if (auto ts_it = topics_.find(topic);
+ ts_it != topics_.end() && ts_it->policy.drop_on_idle) {
+ topics_.erase(ts_it);
+ }
+ newly_idle.append(topic);
}
- emit topic_idle(topic);
}
+ owner_topics_.erase(topics_it);
}
- owner_topics_.erase(topics_it);
- }
-
- auto pats_it = owner_patterns_.find(owner);
- if (pats_it != owner_patterns_.end()) {
- for (const auto& pattern : pats_it.value()) {
- auto sub_it = pattern_subscriptions_.find(pattern);
- if (sub_it == pattern_subscriptions_.end()) continue;
- auto& vec = sub_it.value();
- vec.erase(std::remove_if(vec.begin(), vec.end(),
- [owner](const Subscription& s) { return s.owner.data() == owner; }),
- vec.end());
- if (vec.isEmpty())
- pattern_subscriptions_.erase(sub_it);
+
+ auto pats_it = owner_patterns_.find(owner);
+ if (pats_it != owner_patterns_.end()) {
+ for (const auto& pattern : pats_it.value()) {
+ auto sub_it = pattern_subscriptions_.find(pattern);
+ if (sub_it == pattern_subscriptions_.end()) continue;
+ auto& vec = sub_it.value();
+ vec.erase(std::remove_if(vec.begin(), vec.end(),
+ [owner](const Subscription& s) { return s.owner.data() == owner; }),
+ vec.end());
+ if (vec.isEmpty())
+ pattern_subscriptions_.erase(sub_it);
+ }
+ owner_patterns_.erase(pats_it);
+ }
+
+ // Gap 4 fix: any topics that just lost their final subscriber must
+ // also be removed from coalesce_pending_ — otherwise we'd dispatch
+ // a producer refresh() for a topic nobody is listening to anymore.
+ if (!newly_idle.isEmpty()) {
+ QSet<QString> idle_set;
+ for (const auto& t : newly_idle) idle_set.insert(t);
+ for (auto it = coalesce_pending_.begin(); it != coalesce_pending_.end(); ) {
+ it.value().erase(std::remove_if(it.value().begin(), it.value().end(),
+ [&idle_set](const QString& t) { return idle_set.contains(t); }),
+ it.value().end());
+ if (it.value().isEmpty()) it = coalesce_pending_.erase(it);
+ else ++it;
+ }
}
- owner_patterns_.erase(pats_it);
}
+ for (const auto& topic : newly_idle) emit topic_idle(topic);
}
void DataHub::deliver_initial_value(
@@ -220,7 +269,7 @@ void DataHub::deliver_initial_value(
if (it != topics_.end() && it->value.isValid()) {
const auto policy = it->policy;
if (policy.push_only ||
- (now_ms() - it->last_publish_ms) < policy.ttl_ms) {
+ (now_ms() - it->last_publish_ms) < effective_ttl_ms(it.value())) {
snapshot = it->value;
have_value = true;
}
@@ -263,7 +312,7 @@ QMetaObject::Connection DataHub::subscribe(
// topics have no producer-side pull, so skip — they only get data via
// explicit publish() calls.
const bool have_fresh_value = st.value.isValid() && st.last_publish_ms > 0 &&
- (now_ms() - st.last_publish_ms) < st.policy.ttl_ms;
+ (now_ms() - st.last_publish_ms) < effective_ttl_ms(st);
if (!have_fresh_value && !st.in_flight && !st.policy.push_only) {
needs_cold_start_fetch = true;
}
@@ -272,9 +321,15 @@ QMetaObject::Connection DataHub::subscribe(
// Auto-cleanup on owner destruction. The QObject::destroyed signal
// fires on the owner's thread — marshal to ours via QueuedConnection
// so mutex_ is acquired from the hub thread.
+ // Gap 8 fix: bind to the member function (not a fresh lambda) so
+ // Qt::UniqueConnection actually deduplicates the connection for
+ // owners that re-subscribe repeatedly (show/hide cycles). Lambdas
+ // would create a fresh slot pointer per call, defeating dedup.
+ // The destroyed signal hands us the dying QObject* — use it directly
+ // instead of capturing.
auto conn = connect(owner, &QObject::destroyed, this,
- [this, owner](QObject*) { on_owner_destroyed(owner); },
- Qt::QueuedConnection);
+ &DataHub::on_owner_destroyed,
+ Qt::ConnectionType(Qt::QueuedConnection | Qt::UniqueConnection));
if (became_active) {
emit topic_active(topic);
@@ -315,13 +370,19 @@ QMetaObject::Connection DataHub::subscribe_pattern(
if (it->in_flight) continue;
const bool have_fresh =
it->value.isValid() && it->last_publish_ms > 0 &&
- (t - it->last_publish_ms) < it->policy.ttl_ms;
+ (t - it->last_publish_ms) < effective_ttl_ms(it.value());
if (!have_fresh) cold_start_topics.append(it.key());
}
}
+ // Gap 8 fix: bind to the member function (not a fresh lambda) so
+ // Qt::UniqueConnection actually deduplicates the connection for
+ // owners that re-subscribe repeatedly (show/hide cycles). Lambdas
+ // would create a fresh slot pointer per call, defeating dedup.
+ // The destroyed signal hands us the dying QObject* — use it directly
+ // instead of capturing.
auto conn = connect(owner, &QObject::destroyed, this,
- [this, owner](QObject*) { on_owner_destroyed(owner); },
- Qt::QueuedConnection);
+ &DataHub::on_owner_destroyed,
+ Qt::ConnectionType(Qt::QueuedConnection | Qt::UniqueConnection));
if (!cold_start_topics.isEmpty())
request(cold_start_topics, /*force=*/true);
return conn;
@@ -332,24 +393,127 @@ void DataHub::unsubscribe(QObject* owner) {
}
void DataHub::unsubscribe(QObject* owner, const QString& topic) {
- QMutexLocker lock(&mutex_);
- auto sub_it = subscriptions_.find(topic);
- if (sub_it == subscriptions_.end()) return;
- auto& vec = sub_it.value();
- vec.erase(std::remove_if(vec.begin(), vec.end(),
- [owner](const Subscription& s) { return s.owner.data() == owner; }),
- vec.end());
- if (vec.isEmpty()) {
- subscriptions_.erase(sub_it);
- if (auto ts_it = topics_.find(topic);
- ts_it != topics_.end() && ts_it->policy.drop_on_idle) {
- topics_.erase(ts_it);
+ bool became_idle = false;
+ {
+ QMutexLocker lock(&mutex_);
+ auto sub_it = subscriptions_.find(topic);
+ if (sub_it == subscriptions_.end()) {
+ // Still need to clean owner_topics_ in case of bookkeeping skew.
+ if (auto it = owner_topics_.find(owner); it != owner_topics_.end()) {
+ it.value().remove(topic);
+ if (it.value().isEmpty()) owner_topics_.erase(it);
+ }
+ return;
+ }
+ auto& vec = sub_it.value();
+ vec.erase(std::remove_if(vec.begin(), vec.end(),
+ [owner](const Subscription& s) { return s.owner.data() == owner; }),
+ vec.end());
+ if (vec.isEmpty()) {
+ subscriptions_.erase(sub_it);
+ if (auto ts_it = topics_.find(topic);
+ ts_it != topics_.end() && ts_it->policy.drop_on_idle) {
+ topics_.erase(ts_it);
+ }
+ became_idle = true;
+ // Gap 4 fix: if the topic was buffered for a coalesced refresh,
+ // drop it now — there's no point dispatching a producer call for
+ // a topic that has no subscribers left.
+ for (auto it = coalesce_pending_.begin(); it != coalesce_pending_.end(); ) {
+ it.value().removeAll(topic);
+ if (it.value().isEmpty()) it = coalesce_pending_.erase(it);
+ else ++it;
+ }
+ }
+ if (auto it = owner_topics_.find(owner); it != owner_topics_.end()) {
+ it.value().remove(topic);
+ if (it.value().isEmpty()) owner_topics_.erase(it);
}
- emit topic_idle(topic);
}
- if (auto it = owner_topics_.find(owner); it != owner_topics_.end()) {
+ if (became_idle) emit topic_idle(topic);
+}
+
+void DataHub::unsubscribe_pattern(QObject* owner, const QString& pattern) {
+ QMutexLocker lock(&mutex_);
+ auto sub_it = pattern_subscriptions_.find(pattern);
+ if (sub_it != pattern_subscriptions_.end()) {
+ auto& vec = sub_it.value();
+ vec.erase(std::remove_if(vec.begin(), vec.end(),
+ [owner](const Subscription& s) { return s.owner.data() == owner; }),
+ vec.end());
+ if (vec.isEmpty()) pattern_subscriptions_.erase(sub_it);
+ }
+ if (auto it = owner_patterns_.find(owner); it != owner_patterns_.end()) {
+ it.value().remove(pattern);
+ if (it.value().isEmpty()) owner_patterns_.erase(it);
+ }
+}
+
+// ── Error subscriptions (Gap 7 fix) ────────────────────────────────────────
+
+QMetaObject::Connection DataHub::subscribe_errors(
+ QObject* owner, const QString& topic,
+ std::function<void(const QString&)> slot) {
+ Q_ASSERT(owner && "subscribe_errors requires a non-null owner");
+ {
+ QMutexLocker lock(&mutex_);
+ ErrorSub e;
+ e.owner = owner;
+ e.single_slot = std::move(slot);
+ e.is_pattern = false;
+ error_subscriptions_[topic].append(std::move(e));
+ error_owner_topics_[owner].insert(topic);
+ }
+ return connect(owner, &QObject::destroyed, this,
+ &DataHub::on_owner_destroyed,
+ Qt::ConnectionType(Qt::QueuedConnection | Qt::UniqueConnection));
+}
+
+QMetaObject::Connection DataHub::subscribe_pattern_errors(
+ QObject* owner, const QString& pattern,
+ std::function<void(const QString&, const QString&)> slot) {
+ Q_ASSERT(owner && "subscribe_pattern_errors requires a non-null owner");
+ {
+ QMutexLocker lock(&mutex_);
+ ErrorSub e;
+ e.owner = owner;
+ e.pattern_slot = std::move(slot);
+ e.is_pattern = true;
+ error_pattern_subscriptions_[pattern].append(std::move(e));
+ error_owner_patterns_[owner].insert(pattern);
+ }
+ return connect(owner, &QObject::destroyed, this,
+ &DataHub::on_owner_destroyed,
+ Qt::ConnectionType(Qt::QueuedConnection | Qt::UniqueConnection));
+}
+
+void DataHub::unsubscribe_errors(QObject* owner, const QString& topic) {
+ QMutexLocker lock(&mutex_);
+ if (auto it = error_subscriptions_.find(topic); it != error_subscriptions_.end()) {
+ auto& vec = it.value();
+ vec.erase(std::remove_if(vec.begin(), vec.end(),
+ [owner](const ErrorSub& e) { return e.owner.data() == owner; }),
+ vec.end());
+ if (vec.isEmpty()) error_subscriptions_.erase(it);
+ }
+ if (auto it = error_owner_topics_.find(owner); it != error_owner_topics_.end()) {
it.value().remove(topic);
- if (it.value().isEmpty()) owner_topics_.erase(it);
+ if (it.value().isEmpty()) error_owner_topics_.erase(it);
+ }
+}
+
+void DataHub::unsubscribe_pattern_errors(QObject* owner, const QString& pattern) {
+ QMutexLocker lock(&mutex_);
+ if (auto it = error_pattern_subscriptions_.find(pattern); it != error_pattern_subscriptions_.end()) {
+ auto& vec = it.value();
+ vec.erase(std::remove_if(vec.begin(), vec.end(),
+ [owner](const ErrorSub& e) { return e.owner.data() == owner; }),
+ vec.end());
+ if (vec.isEmpty()) error_pattern_subscriptions_.erase(it);
+ }
+ if (auto it = error_owner_patterns_.find(owner); it != error_owner_patterns_.end()) {
+ it.value().remove(pattern);
+ if (it.value().isEmpty()) error_owner_patterns_.erase(it);
}
}
@@ -439,9 +603,12 @@ void DataHub::do_publish(const QString& topic, const QVariant& value,
st.total_publishes += 1;
st.in_flight = false;
st.last_error.clear(); // successful publish clears any stored error
- if (ttl_override.count() > 0) {
- st.policy.ttl_ms = static_cast<int>(ttl_override.count());
- }
+ // Gap 3 fix: store the per-publish TTL separately so the next
+ // override-less publish reverts to policy.ttl_ms. Zero = no
+ // override, fall back to policy.ttl_ms.
+ st.ttl_override_ms = ttl_override.count() > 0
+ ? static_cast<int>(ttl_override.count())
+ : 0;
coalesce_ms = st.policy.coalesce_within_ms;
if (coalesce_ms > 0) {
st.coalesce_latest = value;
@@ -508,6 +675,16 @@ void DataHub::publish_error(const QString& topic, const QString& error) {
}, Qt::QueuedConnection);
return;
}
+
+ // Snapshot per-topic error subscribers under the lock so we invoke
+ // their slots outside it (same pattern as emit_to_subscribers).
+ struct PendingErr {
+ QPointer<QObject> owner;
+ std::function<void(const QString&)> single_slot;
+ std::function<void(const QString&, const QString&)> pattern_slot;
+ bool is_pattern = false;
+ };
+ QVector<PendingErr> error_targets;
{
QMutexLocker lock(&mutex_);
auto& st = state_for(topic);
@@ -515,7 +692,24 @@ void DataHub::publish_error(const QString& topic, const QString& error) {
st.last_error = error;
st.last_error_ms = now_ms();
st.total_errors += 1;
+
+ if (auto it = error_subscriptions_.find(topic); it != error_subscriptions_.end()) {
+ for (const auto& e : it.value())
+ if (e.owner) error_targets.append({e.owner, e.single_slot, {}, false});
+ }
+ for (auto it = error_pattern_subscriptions_.begin();
+ it != error_pattern_subscriptions_.end(); ++it) {
+ if (!pattern_matches(it.key(), topic)) continue;
+ for (const auto& e : it.value())
+ if (e.owner) error_targets.append({e.owner, {}, e.pattern_slot, true});
+ }
+ }
+ for (const auto& t : error_targets) {
+ if (!t.owner) continue;
+ if (t.is_pattern) t.pattern_slot(topic, error);
+ else t.single_slot(error);
}
+
LOG_WARN("DataHub", QString("publish_error topic='%1' error='%2'").arg(topic).arg(error.left(200)));
emit topic_error(topic, error);
}
@@ -594,7 +788,7 @@ QVariant DataHub::peek(const QString& topic) const {
return it->value;
if (it->last_publish_ms <= 0)
return {};
- if ((now_ms() - it->last_publish_ms) >= it->policy.ttl_ms)
+ if ((now_ms() - it->last_publish_ms) >= effective_ttl_ms(it.value()))
return {}; // stale
return it->value;
}
@@ -659,14 +853,19 @@ void DataHub::request(const QStringList& topics, bool force) {
if (!orphan_topics.isEmpty()) {
// Topic requested by a consumer but no producer claims a matching
- // pattern. This is almost always a typo in the topic string or a
- // missing ensure_registered_with_hub() call — log once per request
- // so the miss surfaces during development.
- LOG_WARN("DataHub",
- QString("request(): %1 topic(s) have no producer — likely unregistered "
- "service or typo. First few: %2")
- .arg(orphan_topics.size())
- .arg(orphan_topics.mid(0, 3).join(QStringLiteral(", "))));
+ // pattern. This is almost always a missing
+ // ensure_registered_with_hub() call in main.cpp (the producer
+ // didn't run before the consumer subscribed) or a typo in the
+ // topic string. Surface it loudly so the miss is obvious during
+ // development — silent orphans cause "subscribe but never get
+ // data" bugs that are hard to trace.
+ LOG_ERROR("DataHub",
+ QString("ORPHAN TOPIC(S) — %1 topic(s) have no registered producer. "
+ "Check that the owning service ran ensure_registered_with_hub() "
+ "in main.cpp BEFORE any consumer subscribed, and verify the "
+ "topic string spelling. First few: %2")
+ .arg(orphan_topics.size())
+ .arg(orphan_topics.mid(0, 5).join(QStringLiteral(", "))));
}
if (need_arm) {
// The coalesce timer lives on the hub thread; arming from another
@@ -748,7 +947,7 @@ void DataHub::scheduler_body() {
const bool have_value = st.value.isValid() && st.last_publish_ms > 0;
const bool ttl_expired = !have_value ||
- (t - st.last_publish_ms) >= st.policy.ttl_ms;
+ (t - st.last_publish_ms) >= effective_ttl_ms(st);
const bool min_interval_ok =
(t - st.last_refresh_request_ms) >= st.policy.min_interval_ms;
if (!ttl_expired || !min_interval_ok) continue;
diff --git a/fincept-qt/src/datahub/DataHub.h b/fincept-qt/src/datahub/DataHub.h
index 2d3526461..62c5ab2e4 100644
--- a/fincept-qt/src/datahub/DataHub.h
+++ b/fincept-qt/src/datahub/DataHub.h
@@ -78,10 +78,39 @@ class DataHub : public QObject {
const QString& pattern,
std::function<void(const QString&, const QVariant&)> slot);
- /// Remove every subscription owned by `owner`.
+ /// Remove every subscription (concrete + pattern) owned by `owner`.
void unsubscribe(QObject* owner);
- /// Remove only the subscription for `owner` on `topic`.
+ /// Remove only the concrete-topic subscription for `owner` on `topic`.
+ /// Does NOT touch pattern subscriptions — use `unsubscribe_pattern()`
+ /// for that. The two registries are separate.
void unsubscribe(QObject* owner, const QString& topic);
+ /// Remove only the wildcard-pattern subscription for `owner` on `pattern`.
+ /// Symmetric to `subscribe_pattern()`. No-op if not currently subscribed.
+ void unsubscribe_pattern(QObject* owner, const QString& pattern);
+
+ // ── Error subscriptions ─────────────────────────────────────────────────
+ //
+ // The `topic_error` Qt signal fans every error to every connected slot;
+ // each handler then has to filter by topic name. For consumers that
+ // only care about errors on one specific topic family, the
+ // `subscribe_errors` family below provides per-topic / per-pattern
+ // filtering inside the hub. The `owner` lifetime contract is identical
+ // to the data subscribe API: auto-cleanup on destroyed().
+
+ /// Receive `publish_error()` events for a single concrete topic.
+ QMetaObject::Connection subscribe_errors(
+ QObject* owner,
+ const QString& topic,
+ std::function<void(const QString& error)> slot);
+
+ /// Receive `publish_error()` events for every topic matching `pattern`.
+ QMetaObject::Connection subscribe_pattern_errors(
+ QObject* owner,
+ const QString& pattern,
+ std::function<void(const QString& topic, const QString& error)> slot);
+
+ void unsubscribe_errors(QObject* owner, const QString& topic);
+ void unsubscribe_pattern_errors(QObject* owner, const QString& pattern);
// ── Publishing (producer side) ──────────────────────────────────────────
@@ -212,6 +241,19 @@ class DataHub : public QObject {
// Coalesce state — non-zero policy.coalesce_within_ms only.
bool coalesce_pending = false; ///< a deferred publish is armed
QVariant coalesce_latest; ///< most recent value inside window
+ // Gap 3 fix: a per-publish ttl override used to be written into
+ // policy.ttl_ms, leaking the override into subsequent publishes.
+ // Stored separately now; do_publish reads policy.ttl_ms unless
+ // ttl_override_ms > 0, in which case the override is applied
+ // ONLY for the current publish's freshness window.
+ int ttl_override_ms = 0;
+ };
+
+ struct ErrorSub {
+ QPointer<QObject> owner;
+ std::function<void(const QString&)> single_slot; // subscribe_errors
+ std::function<void(const QString&, const QString&)> pattern_slot; // subscribe_pattern_errors
+ bool is_pattern = false;
};
// ── Helpers ─────────────────────────────────────────────────────────────
@@ -241,6 +283,14 @@ class DataHub : public QObject {
QHash<QString, TopicState> topics_;
+ // Per-topic / per-pattern error subscriptions (Gap 7 fix). Symmetric
+ // to subscriptions_ / pattern_subscriptions_ but keyed for the error
+ // fan-out path inside publish_error().
+ QHash<QString, QVector<ErrorSub>> error_subscriptions_;
+ QHash<QString, QVector<ErrorSub>> error_pattern_subscriptions_;
+ QHash<QObject*, QSet<QString>> error_owner_topics_;
+ QHash<QObject*, QSet<QString>> error_owner_patterns_;
+
// Policies applied by pattern — lower-priority than explicit set_policy().
QList<QPair<QString, TopicPolicy>> pattern_policies_;
diff --git a/fincept-qt/src/python/PythonRunner.cpp b/fincept-qt/src/python/PythonRunner.cpp
index 434e90b6b..cdca6bfb1 100644
--- a/fincept-qt/src/python/PythonRunner.cpp
+++ b/fincept-qt/src/python/PythonRunner.cpp
@@ -380,8 +380,29 @@ void PythonRunner::start_next() {
QStringList full_args;
// If the script is inside a sub-package (contains '/'), use -m <module>
- // so Python can resolve relative imports (from .core import ...).
+ // so Python can resolve relative imports (from .core import ...). This
+ // only works if every directory along the path has an `__init__.py` —
+ // otherwise the package's `__init__.py` may rely on absolute imports
+ // (e.g. `from finagent_core.x import ...`) that resolve against the
+ // top-level `sys.path` entry the bare-script invocation sets up via
+ // its own `sys.path.insert(...)` bootstrap. When any ancestor dir is
+ // missing `__init__.py`, fall back to direct script invocation so the
+ // script's bootstrap can run before the failing import.
+ bool use_module_form = false;
if (!is_code && req.script.contains('/')) {
+ use_module_form = true;
+ QString check_path = scripts_dir_;
+ QStringList parts = req.script.split('/');
+ parts.removeLast(); // drop the file itself
+ for (const QString& p : parts) {
+ check_path += "/" + p;
+ if (!QFileInfo::exists(check_path + "/__init__.py")) {
+ use_module_form = false;
+ break;
+ }
+ }
+ }
+ if (use_module_form) {
QString module = req.script;
module.remove(".py");
module.replace('/', '.');
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
index f9901adf6..c75eacacf 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
@@ -534,12 +534,38 @@ void QuantModulePanel::on_result(const QString& module_id, const QString& comman
return;
// RL Trading: training finished → re-enable button, keep progress/logs visible so
- // the user can inspect the run. The generic result display below still runs.
+ // the user can inspect the run. The card-based renderer below paints into
+ // the bottom results pane (in addition to the bespoke log/progress widgets).
if (module_id == "rl_trading" && command == "train" && rl_train_button_) {
rl_train_button_->setEnabled(true);
if (rl_progress_bar_)
rl_progress_bar_->setValue(100);
}
+ if (module_id == "rl_trading") {
+ display_rl_trading_result(command, payload);
+ return;
+ }
+ if (module_id == "online_learning") {
+ display_online_learning_result(command, payload);
+ return;
+ }
+ if (module_id == "meta_learning") {
+ display_meta_learning_result(command, payload);
+ return;
+ }
+ // CORE-category renderers (backtesting handled later via display_backtest_result)
+ if (module_id == "factor_discovery") {
+ display_factor_discovery_result(command, payload);
+ return;
+ }
+ if (module_id == "model_library") {
+ display_model_library_result(command, payload);
+ return;
+ }
+ if (module_id == "live_signals") {
+ display_live_signals_result(command, payload);
+ return;
+ }
// ── CFA Quant: uniform result shape across all analyses ──────────────────
if (module_id == "cfa_quant") {
@@ -583,6 +609,37 @@ void QuantModulePanel::on_result(const QString& module_id, const QString& comman
return;
}
+ // ── ADVANCED-category panels: card-based displays ────────────────────────
+ // hft and rolling_retraining are intentionally NOT dispatched here — they
+ // have bespoke per-tab UI (in-tab card grid + order-book tables for HFT;
+ // progress bar + schedule cards for Rolling Retraining) handled later in
+ // this function. Re-routing them to the generic results pane would create
+ // a duplicate, disconnected display.
+ if (module_id == "advanced_models") {
+ display_advanced_models_result(command, payload);
+ return;
+ }
+ if (module_id == "feature_engineering") {
+ display_feature_engineering_result(command, payload);
+ return;
+ }
+ if (module_id == "portfolio_opt") {
+ display_portfolio_opt_result(command, payload);
+ return;
+ }
+ if (module_id == "factor_evaluation") {
+ display_factor_evaluation_result(command, payload);
+ return;
+ }
+ if (module_id == "strategy_builder") {
+ display_strategy_builder_result(command, payload);
+ return;
+ }
+ if (module_id == "data_processors") {
+ display_data_processors_result(command, payload);
+ return;
+ }
+
// ── LangGraph deep analysis result ───────────────────────────────────────
if (command == "execute_task") {
if (!payload["success"].toBool()) {
@@ -807,361 +864,13 @@ void QuantModulePanel::on_result(const QString& module_id, const QString& comman
return;
}
- // ── Factor Discovery ─────────────────────────────────────────────────────
- if (module_id == "factor_discovery") {
- if (!payload["success"].toBool()) {
- display_error(payload["error"].toString());
- return;
- }
- clear_results();
- if (command == "get_factor_library") {
- auto factors = payload["factors"].toArray();
- QString out = QString("Factor Library — %1 factors\n\n").arg(factors.size());
- for (const auto& f : factors) {
- auto obj = f.toObject();
- out += QString("• %1\n Category: %2 | Expression: %3\n")
- .arg(obj["name"].toString(), obj["category"].toString("-"), obj["expression"].toString("-"));
- }
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 factors").arg(factors.size()));
- return;
- }
- if (command == "get_data") {
- auto total = payload["total_records"].toInt();
- auto range = payload["date_range"].toObject();
- auto warning = payload["warning"].toString();
- QString summary = QString("Data fetched — %1 records | %2 → %3")
- .arg(total)
- .arg(range["start"].toString())
- .arg(range["end"].toString());
- if (!warning.isEmpty())
- summary += QString("\n⚠ %1").arg(warning);
- auto* lbl = new QLabel(summary, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 records").arg(total));
- return;
- }
- if (command == "get_instruments") {
- auto instruments = payload["instruments"].toArray();
- QStringList names;
- for (const auto& i : instruments)
- names << i.toString();
- auto* lbl = new QLabel(QString("Instruments (%1): %2").arg(names.size()).arg(names.join(", ")), this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 instruments").arg(names.size()));
- return;
- }
- display_result(payload);
- return;
- }
-
- // ── Model Library ────────────────────────────────────────────────────────
- if (module_id == "model_library") {
- if (!payload["success"].toBool()) {
- display_error(payload["error"].toString());
- return;
- }
- clear_results();
- if (command == "list_models") {
- auto models = payload["models"].toArray();
- QString out = QString("Available Models (%1)\n\n").arg(models.size());
- for (const auto& m : models) {
- auto obj = m.toObject();
- out += QString("• %1 [%2]\n %3\n")
- .arg(obj["name"].toString(), obj["id"].toString(), obj["description"].toString("-"));
- }
- if (models.isEmpty())
- out += "No models listed (check qlib availability)";
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 models").arg(models.size()));
- return;
- }
- if (command == "check_status") {
- auto qlib_ok = payload["qlib_available"].toBool();
- auto models_avail = payload["models_available"].toObject();
- QStringList available, unavailable;
- for (auto it = models_avail.begin(); it != models_avail.end(); ++it)
- (it.value().toBool() ? available : unavailable) << it.key();
- auto* lbl = new QLabel(QString("Qlib: %1\nAvailable: %2\nUnavailable: %3")
- .arg(qlib_ok ? "✓ Ready" : "✗ Not installed")
- .arg(available.join(", "))
- .arg(unavailable.join(", ")),
- this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(qlib_ok ? "Qlib ready" : "Qlib unavailable");
- return;
- }
- if (command == "train_model") {
- auto model_id = payload["model_id"].toString();
- auto metrics = payload["metrics"].toObject();
- QString out = QString("Model Trained: %1\n").arg(model_id);
- for (auto it = metrics.begin(); it != metrics.end(); ++it)
- out += QString(" %1: %2\n").arg(it.key()).arg(it.value().toDouble(), 0, 'f', 4);
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("Trained: %1").arg(model_id));
- return;
- }
- display_result(payload);
- return;
- }
-
- // ── Live Signals ─────────────────────────────────────────────────────────
- if (module_id == "live_signals") {
- if (!payload["success"].toBool()) {
- display_error(payload["error"].toString());
- return;
- }
- clear_results();
- if (command == "get_data") {
- auto total = payload["total_records"].toInt();
- auto range = payload["date_range"].toObject();
- auto warning = payload["warning"].toString();
- auto instr = payload["instruments"].toArray();
- QStringList names;
- for (const auto& i : instr)
- names << i.toString();
- QString out = QString("Signal Data — %1 records\nInstruments: %2\nRange: %3 → %4")
- .arg(total)
- .arg(names.join(", "))
- .arg(range["start"].toString())
- .arg(range["end"].toString());
- if (!warning.isEmpty())
- out += QString("\n⚠ %1").arg(warning);
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 records").arg(total));
- return;
- }
- if (command == "get_factor_analysis") {
- auto factors = payload["factors"].toArray();
- QString out = QString("Factor Analysis — %1 factors\n\n").arg(factors.size());
- for (const auto& f : factors) {
- auto obj = f.toObject();
- out += QString("• %1 IC: %2 Sharpe: %3\n")
- .arg(obj["name"].toString("-"))
- .arg(obj["ic"].isNull() ? "N/A" : QString::number(obj["ic"].toDouble(), 'f', 4))
- .arg(obj["sharpe"].isNull() ? "N/A" : QString::number(obj["sharpe"].toDouble(), 'f', 3));
- }
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 factors").arg(factors.size()));
- return;
- }
- if (command == "get_feature_importance") {
- auto features = payload["feature_importance"].toObject();
- QString out = "Feature Importance\n\n";
- QVector<QPair<QString, double>> sorted;
- for (auto it = features.begin(); it != features.end(); ++it)
- sorted.append({it.key(), it.value().toDouble()});
- std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) { return a.second > b.second; });
- for (const auto& p : sorted)
- out += QString("• %-20s %1\n").arg(p.second, 0, 'f', 4).arg(p.first, -20);
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText("Feature importance loaded");
- return;
- }
- display_result(payload);
- return;
- }
-
- // ── Online Learning ──────────────────────────────────────────────────────
- if (module_id == "online_learning") {
- if (!payload["success"].toBool()) {
- display_error(payload["error"].toString());
- return;
- }
- clear_results();
- if (command == "list_models") {
- auto models = payload["models"].toArray();
- auto river = payload["river_available"].toBool();
- QString out = QString("Online Models (%1) | River: %2\n\n")
- .arg(models.size())
- .arg(river ? "available" : "not installed");
- for (const auto& m : models) {
- auto obj = m.toObject();
- out += QString("• %1 [%2]\n Trained: %3 samples | Updated: %4\n")
- .arg(obj["model_id"].toString(), obj["type"].toString())
- .arg(obj["samples_trained"].toInt())
- .arg(obj["last_updated"].isNull() ? "never" : obj["last_updated"].toString());
- }
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 model(s)").arg(models.size()));
- return;
- }
- if (command == "create_model") {
- auto* lbl = new QLabel(
- QString("Created: %1 [%2]").arg(payload["model_id"].toString(), payload["model_type"].toString()), this);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText("Model created");
- return;
- }
- if (command == "train") {
- auto mae = payload["current_mae"].toDouble();
- auto samples = payload["samples_trained"].toInt();
- auto drift = payload["drift_detected"].toBool();
- auto pred = payload["prediction"];
- QString out = QString("Trained — Samples: %1 | MAE: %2\nDrift: %3")
- .arg(samples)
- .arg(mae, 0, 'f', 6)
- .arg(drift ? "DETECTED" : "none");
- if (!pred.isNull())
- out += QString("\nPrediction: %1 → Actual: %2 | Error: %3")
- .arg(pred.toDouble(), 0, 'f', 6)
- .arg(payload["actual"].toDouble(), 0, 'f', 6)
- .arg(payload["error"].toDouble(), 0, 'f', 6);
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(drift ? ui::colors::NEGATIVE() : ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(drift ? "⚠ Drift detected" : QString("MAE: %1").arg(mae, 0, 'f', 4));
- return;
- }
- if (command == "predict") {
- auto pred = payload["prediction"];
- auto* lbl = new QLabel(
- QString("Prediction: %1").arg(pred.isNull() ? "N/A" : QString::number(pred.toDouble(), 'f', 6)), this);
- lbl->setStyleSheet(QString("color:%1; font-weight:700;").arg(module_.color.name()));
- results_layout_->addWidget(lbl);
- status_label_->setText("Prediction ready");
- return;
- }
- if (command == "performance") {
- auto mae = payload["current_mae"].toDouble();
- auto samples = payload["samples_trained"].toInt();
- auto drift = payload["drift_detected"].toBool();
- auto* lbl = new QLabel(QString("Model: %1 [%2]\nSamples: %3 | MAE: %4\nDrift: %5\nLast updated: %6")
- .arg(payload["model_id"].toString(), payload["model_type"].toString())
- .arg(samples)
- .arg(mae, 0, 'f', 6)
- .arg(drift ? "DETECTED" : "none")
- .arg(payload["last_updated"].isNull() ? "never" : payload["last_updated"].toString()),
- this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("MAE: %1").arg(mae, 0, 'f', 4));
- return;
- }
- display_result(payload);
- return;
- }
-
- // ── Meta Learning ────────────────────────────────────────────────────────
- if (module_id == "meta_learning") {
- if (!payload["success"].toBool()) {
- display_error(payload["error"].toString());
- return;
- }
- clear_results();
- if (command == "list_models") {
- auto models = payload["models"].toArray();
- QString out = QString("Available Models (%1)\n\n").arg(models.size());
- for (const auto& m : models) {
- auto obj = m.toObject();
- out += QString("• %1 [%2 / %3]\n %4\n")
- .arg(obj["name"].toString(), obj["type"].toString(), obj["library"].toString(),
- obj["description"].toString("-"));
- }
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 models").arg(models.size()));
- return;
- }
- if (command == "run_selection") {
- auto best = payload["best_model"].toString();
- auto trained = payload["trained_count"].toInt();
- auto ranking = payload["ranking"].toArray();
- QString out = QString("Best Model: %1 | Trained: %2\n\nRanking:\n").arg(best).arg(trained);
- int rank = 1;
- for (const auto& r : ranking) {
- auto obj = r.toObject();
- auto metrics = obj["metrics"].toObject();
- out += QString(" %1. %2 R²: %3 RMSE: %4\n")
- .arg(rank++)
- .arg(obj["model_id"].toString())
- .arg(metrics["r2_score"].toDouble(), 0, 'f', 4)
- .arg(metrics["rmse"].toDouble(), 0, 'f', 4);
- }
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("Best: %1").arg(best));
- return;
- }
- if (command == "create_ensemble") {
- auto* lbl = new QLabel(QString("Ensemble: %1 [%2]\nModels: %3")
- .arg(payload["ensemble_id"].toString("-"), payload["method"].toString("-"))
- .arg(payload["models"].toArray().size()),
- this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText("Ensemble created");
- return;
- }
- if (command == "tune_hyperparameters") {
- auto best_params = payload["best_params"].toObject();
- auto best_score = payload["best_score"].toDouble();
- QString out = QString("Best score: %1\nBest params:\n").arg(best_score, 0, 'f', 4);
- for (auto it = best_params.begin(); it != best_params.end(); ++it)
- out += QString(" %1: %2\n").arg(it.key()).arg(it.value().toVariant().toString());
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("Best score: %1").arg(best_score, 0, 'f', 4));
- return;
- }
- if (command == "get_results") {
- auto results = payload["results"].toObject();
- QString out = QString("All Results (%1)\n\n").arg(results.size());
- for (auto it = results.begin(); it != results.end(); ++it) {
- auto obj = it.value().toObject();
- auto metrics = obj["metrics"].toObject();
- out += QString("• %1\n R²: %2 RMSE: %3\n")
- .arg(it.key())
- .arg(metrics["r2_score"].toDouble(), 0, 'f', 4)
- .arg(metrics["rmse"].toDouble(), 0, 'f', 4);
- }
- auto* lbl = new QLabel(out, this);
- lbl->setWordWrap(true);
- lbl->setStyleSheet(QString("color:%1;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
- status_label_->setText(QString("%1 result(s)").arg(results.size()));
- return;
- }
- display_result(payload);
- return;
- }
+ // factor_discovery, model_library, live_signals are now rendered by the
+ // card-based dispatch at the top of this function (display_*_result in
+ // QuantModulePanel_CoreDisplays.cpp).
+ //
+ // online_learning and meta_learning are also rendered by card-based
+ // dispatches at the top (display_*_result in
+ // QuantModulePanel_AIMLDisplays.cpp).
// ── HFT ──────────────────────────────────────────────────────────────────
if (module_id == "hft") {
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.h b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.h
index b7e6cef3d..ff920b592 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.h
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.h
@@ -77,6 +77,28 @@ class QuantModulePanel : public QWidget {
void display_fortitudo_result(const QString& command, const QJsonObject& data);
void display_quant_reporting_result(const QString& command, const QJsonObject& data);
void display_gluonts_result(const QString& command, const QJsonObject& data);
+ // ADVANCED-category panel renderers (card-based, mirror analytics pattern).
+ // hft and rolling_retraining have bespoke per-tab UI in on_result() (in-tab
+ // cards/tables, progress bar, schedule cards) — these display_*_result
+ // versions exist as fallbacks for direct invocation but are not dispatched
+ // by on_result() because the bespoke UI is the primary surface.
+ void display_hft_result(const QString& command, const QJsonObject& data);
+ void display_rolling_retraining_result(const QString& command, const QJsonObject& data);
+ void display_advanced_models_result(const QString& command, const QJsonObject& data);
+ void display_feature_engineering_result(const QString& command, const QJsonObject& data);
+ // AI/ML-category renderers (rl_trading, online_learning, meta_learning)
+ void display_rl_trading_result(const QString& command, const QJsonObject& data);
+ void display_online_learning_result(const QString& command, const QJsonObject& data);
+ void display_meta_learning_result(const QString& command, const QJsonObject& data);
+ // CORE-category renderers (factor_discovery, model_library, live_signals)
+ // backtesting kept on its existing display_backtest_result KPI grid.
+ void display_factor_discovery_result(const QString& command, const QJsonObject& data);
+ void display_model_library_result(const QString& command, const QJsonObject& data);
+ void display_live_signals_result(const QString& command, const QJsonObject& data);
+ void display_portfolio_opt_result(const QString& command, const QJsonObject& data);
+ void display_factor_evaluation_result(const QString& command, const QJsonObject& data);
+ void display_strategy_builder_result(const QString& command, const QJsonObject& data);
+ void display_data_processors_result(const QString& command, const QJsonObject& data);
void show_loading(const QString& message);
void display_error(const QString& msg);
void clear_results();
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
new file mode 100644
index 000000000..76a1220e1
--- /dev/null
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
@@ -0,0 +1,684 @@
+// src/screens/ai_quant_lab/QuantModulePanel_AIMLDisplays.cpp
+//
+// Card-based result renderers for AI/ML category panels that previously
+// rendered plain QLabel text into the bottom results pane.
+//
+// - rl_trading — train (streaming progress + final result), evaluate
+// - online_learning — list_models, create_model, train, predict, performance
+// - meta_learning — list_models, run_selection, create_ensemble,
+// tune_hyperparameters, get_results
+//
+// Skipped:
+// - deep_agent — has bespoke per-tab UI (LangGraph + RD-Agent text outputs,
+// task table widget). Handled by legacy on_result branch.
+// - pattern_intelligence — module declared but no panel/service wired yet.
+#include "screens/ai_quant_lab/QuantModulePanel.h"
+#include "screens/ai_quant_lab/QuantModulePanel_Common.h"
+#include "screens/ai_quant_lab/QuantModulePanel_GsHelpers.h"
+#include "screens/ai_quant_lab/QuantModulePanel_Styles.h"
+
+#include "ui/theme/Theme.h"
+
+#include <QAbstractItemView>
+#include <QColor>
+#include <QHBoxLayout>
+#include <QHash>
+#include <QHeaderView>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QJsonValue>
+#include <QLabel>
+#include <QList>
+#include <QPair>
+#include <QPlainTextEdit>
+#include <QProgressBar>
+#include <QString>
+#include <QStringList>
+#include <QTableWidget>
+#include <QTableWidgetItem>
+#include <QVBoxLayout>
+#include <QWidget>
+
+#include <algorithm>
+#include <cmath>
+#include <functional>
+#include <limits>
+
+namespace fincept::screens {
+
+using namespace fincept::services::quant;
+using namespace fincept::screens::quant_styles;
+using namespace fincept::screens::quant_common;
+using namespace fincept::screens::quant_gs_helpers;
+
+namespace {
+
+QString fmt_num_safe(const QJsonValue& v, int decimals = 4) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toDouble(), 'f', decimals);
+}
+
+QString fmt_int_safe(const QJsonValue& v) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toInt());
+}
+
+QString fmt_pct_safe(const QJsonValue& v, int decimals = 2) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toDouble() * 100.0, 'f', decimals) + "%";
+}
+
+// Returns false if the payload was an error (already displayed via callback).
+bool check_success(const QJsonObject& payload,
+ const std::function<void(const QString&)>& display_error_fn) {
+ if (!payload.value("success").toBool(false)) {
+ const QString err = payload.value("error").toString("Unknown error");
+ const QString kind = payload.value("error_kind").toString();
+ const QString prefix = kind == "validation" ? "Input error: "
+ : kind == "runtime" ? "Computation failed: "
+ : "";
+ display_error_fn(prefix + err);
+ return false;
+ }
+ return true;
+}
+
+} // namespace
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 1. RL TRADING
+// ═════════════════════════════════════════════════════════════════════════════
+//
+// Streaming progress / log events are consumed by AIQuantLabService's
+// training_progress / training_log signals (NOT result_ready) — they update
+// the bespoke rl_progress_bar_ / rl_log_console_ widgets directly. By the time
+// payloads reach this renderer they are the FINAL `event:"result"` payload of
+// `train` (with the event field stripped by the service) or the single-shot
+// `evaluate` result.
+void QuantModulePanel::display_rl_trading_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ if (payload.contains("algorithm"))
+ header_text += " | " + payload.value("algorithm").toString().toUpper();
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ // ── train: minimal final-result card row ─────────────────────────────────
+ if (command == "train") {
+ QList<QWidget*> top = {
+ gs_make_card("ALGORITHM", payload.value("algorithm").toString().toUpper(), this, ui::colors::POSITIVE()),
+ gs_make_card("TIMESTEPS", fmt_int_safe(payload.value("timesteps")), this),
+ gs_make_card("STATUS", "TRAINED", this, ui::colors::POSITIVE()),
+ gs_make_card("MESSAGE", payload.value("message").toString().left(40), this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ const QString msg = payload.value("message").toString();
+ if (!msg.isEmpty()) {
+ auto* lbl = new QLabel(msg);
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-size:11px; padding:8px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+ status_label_->setText(QString("Trained %1 — %2 steps")
+ .arg(payload.value("algorithm").toString())
+ .arg(payload.value("timesteps").toInt()));
+ return;
+ }
+
+ // ── evaluate: rich card view of episode metrics ──────────────────────────
+ if (command == "evaluate") {
+ const double mean_reward = payload.value("mean_reward").toDouble();
+ const double std_reward = payload.value("std_reward").toDouble();
+ const double mean_pv = payload.value("mean_portfolio_value").toDouble();
+ const double port_ret = payload.value("portfolio_return").toDouble();
+ const int n_eps = payload.value("n_episodes").toInt();
+ const double mean_len = payload.value("mean_length").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("EPISODES", QString::number(n_eps), this, ui::colors::POSITIVE()),
+ gs_make_card("MEAN REWARD",
+ QString::number(mean_reward, 'f', 4) + " ± " + QString::number(std_reward, 'f', 4),
+ this, gs_pos_neg_color(mean_reward)),
+ gs_make_card("PORTFOLIO RETURN", fmt_pct_safe(QJsonValue(port_ret), 2), this, gs_pos_neg_color(port_ret)),
+ gs_make_card("MEAN PORTFOLIO VAL", QString::number(mean_pv, 'f', 2), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Compute best/worst episode rewards once
+ const auto rewards = payload.value("all_rewards").toArray();
+ double best_ep = -std::numeric_limits<double>::infinity();
+ double worst_ep = std::numeric_limits<double>::infinity();
+ for (const auto& v : rewards) {
+ const double d = v.toDouble();
+ best_ep = std::max(best_ep, d);
+ worst_ep = std::min(worst_ep, d);
+ }
+ const bool has_eps = !rewards.isEmpty();
+
+ QList<QWidget*> stats = {
+ gs_make_card("MEAN EP LENGTH", QString::number(mean_len, 'f', 1) + " steps", this),
+ gs_make_card("REWARD STD", QString::number(std_reward, 'f', 4), this),
+ gs_make_card("BEST EP",
+ has_eps ? QString::number(best_ep, 'f', 4) : QString("—"),
+ this, ui::colors::POSITIVE()),
+ gs_make_card("WORST EP",
+ has_eps ? QString::number(worst_ep, 'f', 4) : QString("—"),
+ this, ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(stats, this));
+
+ // Per-episode rewards table (sampled if many episodes)
+ if (!rewards.isEmpty()) {
+ const int rows = std::min<int>(15, rewards.size());
+ const int step = std::max<int>(1, rewards.size() / rows);
+ auto* table = new QTableWidget(rows, 2, this);
+ table->setHorizontalHeaderLabels({"Episode", "Reward"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < rewards.size() && r < rows; i += step, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(i + 1)));
+ const double v = rewards[i].toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ it->setForeground(QColor(gs_pos_neg_color(v)));
+ table->setItem(r, 1, it);
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Eval %1 eps reward=%2 return=%3%")
+ .arg(n_eps).arg(mean_reward, 0, 'f', 4).arg(port_ret * 100, 0, 'f', 2));
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 2. ONLINE LEARNING
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_online_learning_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "list_models") {
+ const auto models = payload.value("models").toArray();
+ const bool river = payload.value("river_available").toBool();
+ const bool qlib_online = payload.value("qlib_online_available").toBool();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODELS", QString::number(models.size()), this,
+ models.isEmpty() ? ui::colors::TEXT_TERTIARY() : ui::colors::POSITIVE()),
+ gs_make_card("RIVER", river ? "AVAILABLE" : "MISSING", this,
+ river ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("QLIB ONLINE", qlib_online ? "AVAILABLE" : "MISSING", this,
+ qlib_online ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("COUNT", fmt_int_safe(payload.value("count")), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!models.isEmpty()) {
+ auto* table = new QTableWidget(models.size(), 5, this);
+ table->setHorizontalHeaderLabels({"Model ID", "Type", "Samples", "Created", "Last Updated"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(models.size() * 26 + 32, 360));
+ for (int i = 0; i < models.size(); ++i) {
+ const auto m = models[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(m.value("model_id").toString()));
+ table->setItem(i, 1, new QTableWidgetItem(m.value("type").toString().toUpper()));
+ auto* s = new QTableWidgetItem(QString::number(m.value("samples_trained").toInt()));
+ s->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 2, s);
+ table->setItem(i, 3, new QTableWidgetItem(m.value("created_at").toString()));
+ const QJsonValue lu = m.value("last_updated");
+ table->setItem(i, 4, new QTableWidgetItem(lu.isNull() ? "never" : lu.toString()));
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 online model(s)").arg(models.size()));
+ return;
+ }
+
+ if (command == "create_model") {
+ QList<QWidget*> top = {
+ gs_make_card("MODEL ID", payload.value("model_id").toString(), this, ui::colors::POSITIVE()),
+ gs_make_card("TYPE", payload.value("model_type").toString().toUpper(), this),
+ gs_make_card("STATUS", "CREATED", this, ui::colors::POSITIVE()),
+ gs_make_card("MESSAGE", payload.value("message").toString("OK"), this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText(payload.value("message").toString("Online model created"));
+ return;
+ }
+
+ if (command == "train") {
+ const QJsonValue pred = payload.value("prediction");
+ const QJsonValue actual = payload.value("actual");
+ const double err = payload.value("error").toDouble();
+ const double mae = payload.value("current_mae").toDouble();
+ const int samples = payload.value("samples_trained").toInt();
+ const bool drift = payload.value("drift_detected").toBool();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", payload.value("model_id").toString(), this),
+ gs_make_card("SAMPLES", QString::number(samples), this, ui::colors::POSITIVE()),
+ gs_make_card("CURRENT MAE", QString::number(mae, 'f', 6), this,
+ mae < 0.01 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("DRIFT", drift ? "DETECTED" : "NONE", this,
+ drift ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!pred.isNull() && !actual.isNull()) {
+ QList<QWidget*> pred_row = {
+ gs_make_card("PREDICTION", QString::number(pred.toDouble(), 'f', 6), this,
+ gs_pos_neg_color(pred.toDouble())),
+ gs_make_card("ACTUAL", QString::number(actual.toDouble(), 'f', 6), this,
+ gs_pos_neg_color(actual.toDouble())),
+ gs_make_card("ERROR", QString::number(err, 'f', 6), this,
+ std::abs(err) < std::abs(actual.toDouble()) * 0.1
+ ? ui::colors::POSITIVE()
+ : ui::colors::WARNING()),
+ gs_make_card("ABS ERROR", QString::number(std::abs(err), 'f', 6), this),
+ };
+ results_layout_->addWidget(gs_card_row(pred_row, this));
+ }
+ status_label_->setText(drift ? "⚠ Drift detected"
+ : QString("MAE: %1").arg(mae, 0, 'f', 6));
+ return;
+ }
+
+ if (command == "predict") {
+ const QJsonValue pred = payload.value("prediction");
+ const auto preds = payload.value("predictions").toArray();
+ const int count = payload.value("count").toInt();
+
+ if (preds.isEmpty() && !pred.isNull()) {
+ // Single prediction
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", payload.value("model_id").toString(), this),
+ gs_make_card("PREDICTION", QString::number(pred.toDouble(), 'f', 6), this,
+ gs_pos_neg_color(pred.toDouble())),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Prediction ready");
+ return;
+ }
+
+ // Batch predictions
+ double sum = 0, mn = std::numeric_limits<double>::infinity(),
+ mx = -std::numeric_limits<double>::infinity();
+ for (const auto& v : preds) {
+ const double d = v.toDouble();
+ sum += d;
+ mn = std::min(mn, d);
+ mx = std::max(mx, d);
+ }
+ const double mean = preds.isEmpty() ? 0.0 : sum / preds.size();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", payload.value("model_id").toString(), this),
+ gs_make_card("PREDICTIONS", QString::number(count > 0 ? count : preds.size()), this,
+ ui::colors::POSITIVE()),
+ gs_make_card("MEAN", QString::number(mean, 'f', 6), this, gs_pos_neg_color(mean)),
+ gs_make_card("RANGE",
+ preds.isEmpty() ? "—"
+ : QString("[%1, %2]").arg(mn, 0, 'f', 4).arg(mx, 0, 'f', 4),
+ this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!preds.isEmpty()) {
+ const int rows = std::min<int>(12, preds.size());
+ const int step = std::max<int>(1, preds.size() / rows);
+ auto* table = new QTableWidget(rows, 2, this);
+ table->setHorizontalHeaderLabels({"Index", "Prediction"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < preds.size() && r < rows; i += step, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(i)));
+ const double v = preds[i].toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 6));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ it->setForeground(QColor(gs_pos_neg_color(v)));
+ table->setItem(r, 1, it);
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 prediction(s)").arg(count > 0 ? count : preds.size()));
+ return;
+ }
+
+ if (command == "performance") {
+ const double mae = payload.value("current_mae").toDouble();
+ const int samples = payload.value("samples_trained").toInt();
+ const bool drift = payload.value("drift_detected").toBool();
+ const QJsonValue lu = payload.value("last_updated");
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", payload.value("model_id").toString(), this),
+ gs_make_card("TYPE", payload.value("model_type").toString().toUpper(), this),
+ gs_make_card("SAMPLES", QString::number(samples), this, ui::colors::POSITIVE()),
+ gs_make_card("CURRENT MAE", QString::number(mae, 'f', 6), this,
+ mae < 0.01 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> meta = {
+ gs_make_card("DRIFT", drift ? "DETECTED" : "NONE", this,
+ drift ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()),
+ gs_make_card("LAST UPDATED", lu.isNull() ? "never" : lu.toString(), this),
+ gs_make_card("CREATED", payload.value("created_at").toString(), this),
+ gs_make_card("HEALTH", drift ? "RETRAIN ADVISED" : "OK", this,
+ drift ? ui::colors::WARNING() : ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(meta, this));
+ status_label_->setText(QString("MAE: %1 samples: %2").arg(mae, 0, 'f', 6).arg(samples));
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 3. META LEARNING
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_meta_learning_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "list_models") {
+ const auto models = payload.value("models").toArray();
+ const bool sk = payload.value("sklearn_available").toBool();
+ const bool lgbm = payload.value("lightgbm_available").toBool();
+ const bool xgb = payload.value("xgboost_available").toBool();
+ const bool cat = payload.value("catboost_available").toBool();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODELS", QString::number(models.size()), this, ui::colors::POSITIVE()),
+ gs_make_card("SKLEARN", sk ? "OK" : "MISSING", this,
+ sk ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("LIGHTGBM", lgbm ? "OK" : "MISSING", this,
+ lgbm ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("XGBOOST", xgb ? "OK" : "MISSING", this,
+ xgb ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> extras = {
+ gs_make_card("CATBOOST", cat ? "OK" : "MISSING", this,
+ cat ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("QLIB", payload.value("qlib_available").toBool() ? "OK" : "MISSING", this,
+ payload.value("qlib_available").toBool() ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("COUNT", fmt_int_safe(payload.value("count")), this),
+ gs_make_card("LIBRARIES",
+ QString::number(int(sk) + int(lgbm) + int(xgb) + int(cat)
+ + int(payload.value("qlib_available").toBool())),
+ this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(extras, this));
+
+ if (!models.isEmpty()) {
+ auto* table = new QTableWidget(models.size(), 4, this);
+ table->setHorizontalHeaderLabels({"ID", "Name", "Type", "Library"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(models.size() * 26 + 32, 360));
+ for (int i = 0; i < models.size(); ++i) {
+ const auto m = models[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(m.value("id").toString()));
+ table->setItem(i, 1, new QTableWidgetItem(m.value("name").toString()));
+ table->setItem(i, 2, new QTableWidgetItem(m.value("type").toString().toUpper()));
+ table->setItem(i, 3, new QTableWidgetItem(m.value("library").toString()));
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 model(s) available").arg(models.size()));
+ return;
+ }
+
+ if (command == "run_selection") {
+ const QString best = payload.value("best_model").toString();
+ const int trained = payload.value("trained_count").toInt();
+ const QString task = payload.value("task_type").toString();
+ const auto ranking = payload.value("ranking").toArray();
+
+ QList<QWidget*> top = {
+ gs_make_card("BEST MODEL", best.isEmpty() ? "—" : best, this, ui::colors::POSITIVE()),
+ gs_make_card("TRAINED", QString::number(trained), this),
+ gs_make_card("TASK TYPE", task.toUpper(), this, ui::colors::INFO()),
+ gs_make_card("RANKED", QString::number(ranking.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Determine task type from ranking metrics
+ bool is_classification = false;
+ if (!ranking.isEmpty()) {
+ const auto first_metrics = ranking.first().toObject().value("metrics").toObject();
+ is_classification = first_metrics.contains("accuracy");
+ }
+
+ if (!ranking.isEmpty()) {
+ QStringList headers = is_classification
+ ? QStringList{"Rank", "Model ID", "Score", "Accuracy", "F1", "AUC-ROC"}
+ : QStringList{"Rank", "Model ID", "Score", "R²", "RMSE", "MSE"};
+ QStringList metric_keys = is_classification
+ ? QStringList{"accuracy", "f1_score", "auc_roc"}
+ : QStringList{"r2_score", "rmse", "mse"};
+
+ auto* table = new QTableWidget(ranking.size(), headers.size(), this);
+ table->setHorizontalHeaderLabels(headers);
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(ranking.size() * 26 + 32, 360));
+
+ for (int i = 0; i < ranking.size(); ++i) {
+ const auto r = ranking[i].toObject();
+ const QString mid = r.value("model_id").toString();
+ const auto metrics = r.value("metrics").toObject();
+ const double score = r.value("score").toDouble();
+
+ auto* rank_it = new QTableWidgetItem(QString::number(i + 1));
+ rank_it->setTextAlignment(Qt::AlignCenter);
+ if (i == 0) rank_it->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(i, 0, rank_it);
+
+ auto* mid_it = new QTableWidgetItem(mid);
+ if (mid == best) mid_it->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(i, 1, mid_it);
+
+ auto* score_it = new QTableWidgetItem(QString::number(score, 'f', 4));
+ score_it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ score_it->setForeground(QColor(gs_pos_neg_color(score)));
+ table->setItem(i, 2, score_it);
+
+ for (int c = 0; c < metric_keys.size(); ++c) {
+ const double v = metrics.value(metric_keys[c]).toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (metric_keys[c] == "accuracy" || metric_keys[c] == "r2_score") {
+ if (v > 0.7) it->setForeground(QColor(ui::colors::POSITIVE()));
+ else if (v < 0) it->setForeground(QColor(ui::colors::NEGATIVE()));
+ }
+ table->setItem(i, c + 3, it);
+ }
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Best: %1 (%2 model(s) trained)").arg(best).arg(trained));
+ return;
+ }
+
+ if (command == "create_ensemble") {
+ const auto keys = payload.value("model_keys").toArray();
+ QStringList key_list;
+ for (const auto& v : keys) key_list << v.toString();
+
+ QList<QWidget*> top = {
+ gs_make_card("ENSEMBLE ID", payload.value("ensemble_id").toString(), this, ui::colors::POSITIVE()),
+ gs_make_card("METHOD", payload.value("method").toString().toUpper(), this, ui::colors::INFO()),
+ gs_make_card("MODELS", fmt_int_safe(payload.value("n_models")), this, ui::colors::POSITIVE()),
+ gs_make_card("STATUS", "CREATED", this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!key_list.isEmpty()) {
+ auto* lbl = new QLabel("Composition: " + key_list.join(" + "));
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:11px;"
+ "padding:8px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+ status_label_->setText("Ensemble created");
+ return;
+ }
+
+ if (command == "tune_hyperparameters") {
+ const double best_score = payload.value("best_score").toDouble();
+ const auto best_params = payload.value("best_params").toObject();
+ const QString method = payload.value("search_method").toString();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", payload.value("model_id").toString(), this),
+ gs_make_card("BEST SCORE", QString::number(best_score, 'f', 4), this,
+ best_score > 0.7 ? ui::colors::POSITIVE()
+ : best_score > 0 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ gs_make_card("SEARCH METHOD", method.toUpper(), this, ui::colors::INFO()),
+ gs_make_card("CV FOLDS", fmt_int_safe(payload.value("cv_folds")), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!best_params.isEmpty()) {
+ results_layout_->addWidget(gs_section_header("BEST PARAMETERS", accent));
+ auto* table = new QTableWidget(best_params.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Hyperparameter", "Value"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(best_params.size() * 24 + 32, 280));
+ int r = 0;
+ for (auto it = best_params.begin(); it != best_params.end(); ++it, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(it.key().toUpper()));
+ auto* vi = new QTableWidgetItem(format_val(it.value()));
+ vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 1, vi);
+ table->setRowHeight(r, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1: best score %2")
+ .arg(method).arg(best_score, 0, 'f', 4));
+ return;
+ }
+
+ if (command == "get_results") {
+ const auto results = payload.value("results").toObject();
+ const QString best = payload.value("best_model").toString();
+ const int n_models = payload.value("n_models").toInt();
+
+ QList<QWidget*> top = {
+ gs_make_card("RESULTS", QString::number(results.size()), this, ui::colors::POSITIVE()),
+ gs_make_card("BEST MODEL", best.isEmpty() ? "—" : best, this, ui::colors::POSITIVE()),
+ gs_make_card("N MODELS", QString::number(n_models), this),
+ gs_make_card("KEYS", QString::number(results.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!results.isEmpty()) {
+ // Determine task type from first result's metrics
+ bool is_classification = false;
+ const auto first = results.begin().value().toObject();
+ const auto first_metrics = first.value("metrics").toObject();
+ if (first_metrics.contains("accuracy")) is_classification = true;
+
+ QStringList headers = is_classification
+ ? QStringList{"Model Key", "Model ID", "Accuracy", "F1", "Train N", "Test N"}
+ : QStringList{"Model Key", "Model ID", "R²", "RMSE", "Train N", "Test N"};
+ QStringList metric_keys = is_classification
+ ? QStringList{"accuracy", "f1_score"}
+ : QStringList{"r2_score", "rmse"};
+
+ auto* table = new QTableWidget(results.size(), headers.size(), this);
+ table->setHorizontalHeaderLabels(headers);
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(results.size() * 26 + 32, 360));
+
+ int r = 0;
+ for (auto it = results.begin(); it != results.end(); ++it, ++r) {
+ const QString key = it.key();
+ const auto obj = it.value().toObject();
+ const auto metrics = obj.value("metrics").toObject();
+
+ auto* k = new QTableWidgetItem(key);
+ if (key == best || obj.value("model_id").toString() == best)
+ k->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(r, 0, k);
+ table->setItem(r, 1, new QTableWidgetItem(obj.value("model_id").toString()));
+
+ for (int c = 0; c < metric_keys.size(); ++c) {
+ const double v = metrics.value(metric_keys[c]).toDouble();
+ auto* mi = new QTableWidgetItem(QString::number(v, 'f', 4));
+ mi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if ((metric_keys[c] == "accuracy" || metric_keys[c] == "r2_score") && v > 0.7)
+ mi->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(r, c + 2, mi);
+ }
+ auto* tn = new QTableWidgetItem(QString::number(obj.value("n_train_samples").toInt()));
+ tn->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, headers.size() - 2, tn);
+ auto* en = new QTableWidgetItem(QString::number(obj.value("n_test_samples").toInt()));
+ en->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, headers.size() - 1, en);
+ table->setRowHeight(r, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 result(s) best=%2").arg(results.size()).arg(best));
+ return;
+ }
+
+ display_result(payload);
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AdvancedDisplays.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AdvancedDisplays.cpp
new file mode 100644
index 000000000..6fd0380f6
--- /dev/null
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_AdvancedDisplays.cpp
@@ -0,0 +1,1706 @@
+// src/screens/ai_quant_lab/QuantModulePanel_AdvancedDisplays.cpp
+//
+// Card-based result renderers for the 8 ADVANCED-category panels.
+// Mirrors the analytics pattern (gs_make_card / gs_card_row / gs_section_header).
+// Replaces the generic display_result() flat-table fallback for these modules.
+//
+// - hft (3 commands: fetch_orderbook, market_making, toxic_flow, slippage, analyze)
+// - rolling_retraining (list, create, preview, retrain events, delete)
+// - advanced_models (list_models, list_available, create, train, predict, info)
+// - feature_engineering (per-indicator, select_features_by_ic, evaluate_expression)
+// - portfolio_opt (BL, HRP, MinVar, MaxSharpe, EF)
+// - factor_evaluation (calculate_ic, generate_evaluation_report, calculate_risk_metrics, analyze_factor_returns)
+// - strategy_builder (create_*, portfolio_metrics)
+// - data_processors (list_processors, create_pipeline, process_data)
+#include "screens/ai_quant_lab/QuantModulePanel.h"
+#include "screens/ai_quant_lab/QuantModulePanel_Common.h"
+#include "screens/ai_quant_lab/QuantModulePanel_GsHelpers.h"
+#include "screens/ai_quant_lab/QuantModulePanel_Styles.h"
+
+#include "ui/theme/Theme.h"
+
+#include <QAbstractItemView>
+#include <QColor>
+#include <QFileInfo>
+#include <QHBoxLayout>
+#include <QHash>
+#include <QHeaderView>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QJsonValue>
+#include <QLabel>
+#include <QList>
+#include <QPair>
+#include <QSet>
+#include <QString>
+#include <QStringList>
+#include <QTableWidget>
+#include <QTableWidgetItem>
+#include <QVBoxLayout>
+#include <QWidget>
+
+#include <algorithm>
+#include <cmath>
+#include <functional>
+#include <limits>
+
+namespace fincept::screens {
+
+using namespace fincept::services::quant;
+using namespace fincept::screens::quant_styles;
+using namespace fincept::screens::quant_common;
+using namespace fincept::screens::quant_gs_helpers;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Local helpers (anonymous namespace — file-local)
+// ─────────────────────────────────────────────────────────────────────────────
+namespace {
+
+QString fmt_pct_safe(const QJsonValue& v, int decimals = 2) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toDouble() * 100.0, 'f', decimals) + "%";
+}
+
+QString fmt_num_safe(const QJsonValue& v, int decimals = 4) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toDouble(), 'f', decimals);
+}
+
+QString fmt_int_safe(const QJsonValue& v) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toInt());
+}
+
+QString fmt_bps(const QJsonValue& v, int decimals = 2) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toDouble(), 'f', decimals) + " bps";
+}
+
+QString verdict_color_for(const QString& v) {
+ const QString u = v.toUpper();
+ if (u == "STRONG" || u == "GOOD" || u == "EXCELLENT" || u == "CLEAN" || u == "NORMAL" || u == "BUY")
+ return ui::colors::POSITIVE();
+ if (u == "MODERATE" || u == "MAINTAIN" || u == "FAIR" || u == "MIXED")
+ return ui::colors::TEXT_PRIMARY();
+ if (u == "WEAK" || u == "WARNING" || u == "ELEVATED" || u == "NEUTRAL")
+ return ui::colors::WARNING();
+ if (u == "TOXIC" || u == "POOR" || u == "AVOID" || u == "SELL")
+ return ui::colors::NEGATIVE();
+ return ui::colors::TEXT_PRIMARY();
+}
+
+// Returns false if the payload was an error (already displayed via callback) — caller should bail.
+bool check_success(const QJsonObject& payload,
+ const std::function<void(const QString&)>& display_error_fn) {
+ if (!payload.value("success").toBool(false)) {
+ const QString err = payload.value("error").toString("Unknown error");
+ const QString kind = payload.value("error_kind").toString();
+ const QString prefix = kind == "validation" ? "Input error: "
+ : kind == "runtime" ? "Computation failed: "
+ : "";
+ display_error_fn(prefix + err);
+ return false;
+ }
+ return true;
+}
+
+// Render a {asset → weight} dict as a sorted-by-weight table.
+QTableWidget* build_weights_table(const QJsonObject& weights, QWidget* parent, int max_height = 320) {
+ QList<QPair<QString, double>> rows;
+ for (auto it = weights.begin(); it != weights.end(); ++it)
+ rows.append({it.key(), it.value().toDouble()});
+ std::sort(rows.begin(), rows.end(),
+ [](const auto& a, const auto& b) { return std::abs(a.second) > std::abs(b.second); });
+
+ auto* table = new QTableWidget(rows.size(), 2, parent);
+ table->setHorizontalHeaderLabels({"Asset", "Weight"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(rows.size() * 24 + 32, max_height));
+ for (int r = 0; r < rows.size(); ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(rows[r].first));
+ const double w = rows[r].second;
+ auto* wi = new QTableWidgetItem(QString::number(w * 100.0, 'f', 3) + "%");
+ wi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (w > 0.001) wi->setForeground(QColor(ui::colors::POSITIVE()));
+ else if (w < -0.001) wi->setForeground(QColor(ui::colors::NEGATIVE()));
+ table->setItem(r, 1, wi);
+ table->setRowHeight(r, 24);
+ }
+ return table;
+}
+
+} // namespace
+
+// NOTE: hft and rolling_retraining have bespoke per-tab UI handlers in
+// QuantModulePanel.cpp::on_result() (in-tab card grid + book tables for HFT,
+// progress bar + schedule cards for Rolling Retraining). The display_hft_result
+// and display_rolling_retraining_result functions defined below are NOT
+// dispatched by on_result() (the bespoke handlers take precedence). They exist
+// as a fallback rendering style and as a starting point if a future round
+// migrates those panels to the generic pattern.
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 1. HFT
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_hft_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ const QString symbol = payload.value("symbol").toString();
+ const QString exchange = payload.value("exchange").toString();
+ const double latency = payload.value("latency_ms").toDouble();
+
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ if (!symbol.isEmpty()) header_text += " | " + symbol.toUpper();
+ if (!exchange.isEmpty()) header_text += " | " + exchange.toUpper();
+ if (latency > 0.0) header_text += QString(" | %1 ms").arg(latency, 0, 'f', 1);
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ // ── Helper: book-metrics card row ────────────────────────────────────────
+ auto book_row = [this](const QJsonObject& bm) {
+ const double mid = bm.value("mid_price").toDouble();
+ const double spread_bps = bm.value("spread_bps").toDouble();
+ const double obi = bm.value("obi").toDouble();
+ const QString pressure = bm.value("pressure").toString();
+ QList<QWidget*> top = {
+ gs_make_card("MID PRICE", QString::number(mid, 'f', 4), this),
+ gs_make_card("SPREAD", fmt_bps(spread_bps), this,
+ spread_bps > 20 ? ui::colors::WARNING() : ui::colors::TEXT_PRIMARY()),
+ gs_make_card("OBI", QString::number(obi, 'f', 3), this, gs_pos_neg_color(obi)),
+ gs_make_card("PRESSURE", pressure.isEmpty() ? "—" : pressure.toUpper(), this,
+ verdict_color_for(pressure)),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ const double bb = bm.value("best_bid").toDouble();
+ const double ba = bm.value("best_ask").toDouble();
+ const double bvol = bm.value("bid_volume").toDouble();
+ const double avol = bm.value("ask_volume").toDouble();
+ QList<QWidget*> book = {
+ gs_make_card("BEST BID", QString::number(bb, 'f', 4), this, ui::colors::POSITIVE()),
+ gs_make_card("BEST ASK", QString::number(ba, 'f', 4), this, ui::colors::NEGATIVE()),
+ gs_make_card("BID VOLUME", QString::number(bvol, 'f', 2), this),
+ gs_make_card("ASK VOLUME", QString::number(avol, 'f', 2), this),
+ };
+ results_layout_->addWidget(gs_card_row(book, this));
+ };
+
+ // ── Helper: bids/asks side-by-side mini tables ───────────────────────────
+ auto book_tables = [this](const QJsonArray& bids, const QJsonArray& asks) {
+ if (bids.isEmpty() && asks.isEmpty()) return;
+ const int rows = std::min<int>(10, std::max(bids.size(), asks.size()));
+ auto* table = new QTableWidget(rows, 4, this);
+ table->setHorizontalHeaderLabels({"Bid Size", "Bid Px", "Ask Px", "Ask Size"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ auto pair_double = [](const QJsonValue& v, int idx) -> double {
+ const auto a = v.toArray();
+ return a.size() > idx ? a[idx].toDouble() : 0.0;
+ };
+ for (int i = 0; i < rows; ++i) {
+ if (i < bids.size()) {
+ auto* sz = new QTableWidgetItem(QString::number(pair_double(bids[i], 1), 'f', 4));
+ sz->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 0, sz);
+ auto* px = new QTableWidgetItem(QString::number(pair_double(bids[i], 0), 'f', 4));
+ px->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ px->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(i, 1, px);
+ }
+ if (i < asks.size()) {
+ auto* px = new QTableWidgetItem(QString::number(pair_double(asks[i], 0), 'f', 4));
+ px->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ px->setForeground(QColor(ui::colors::NEGATIVE()));
+ table->setItem(i, 2, px);
+ auto* sz = new QTableWidgetItem(QString::number(pair_double(asks[i], 1), 'f', 4));
+ sz->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 3, sz);
+ }
+ table->setRowHeight(i, 22);
+ }
+ results_layout_->addWidget(table);
+ };
+
+ // ── Helper: market-making card row ───────────────────────────────────────
+ auto mm_row = [this, accent](const QJsonObject& mm) {
+ results_layout_->addWidget(gs_section_header("MARKET MAKING", accent));
+ const QString rec = mm.value("recommendation").toString();
+ QList<QWidget*> top = {
+ gs_make_card("BID PRICE", fmt_num_safe(mm.value("bid_price"), 4), this, ui::colors::POSITIVE()),
+ gs_make_card("ASK PRICE", fmt_num_safe(mm.value("ask_price"), 4), this, ui::colors::NEGATIVE()),
+ gs_make_card("QUOTED SPREAD", fmt_bps(mm.value("quoted_spread_bps")), this),
+ gs_make_card("EDGE PER SIDE", fmt_bps(mm.value("edge_per_side_bps")), this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> sizes = {
+ gs_make_card("BID SIZE", fmt_num_safe(mm.value("bid_size"), 0), this),
+ gs_make_card("ASK SIZE", fmt_num_safe(mm.value("ask_size"), 0), this),
+ gs_make_card("INVENTORY", fmt_num_safe(mm.value("inventory"), 4), this,
+ gs_pos_neg_color(mm.value("inventory").toDouble())),
+ gs_make_card("RECOMMENDATION", rec.isEmpty() ? "—" : rec.toUpper(), this, verdict_color_for(rec)),
+ };
+ results_layout_->addWidget(gs_card_row(sizes, this));
+ };
+
+ // ── Helper: toxic-flow card row ──────────────────────────────────────────
+ auto tox_row = [this, accent](const QJsonObject& tx) {
+ results_layout_->addWidget(gs_section_header("TOXIC FLOW", accent));
+ const double score = tx.value("toxicity_score").toDouble();
+ const bool is_toxic = tx.value("is_toxic").toBool();
+ const QString action = tx.value("action").toString();
+ const QString classification = tx.value("classification").toString();
+ QList<QWidget*> top = {
+ gs_make_card("TOXICITY SCORE", QString::number(score, 'f', 2), this,
+ score >= 70 ? ui::colors::NEGATIVE()
+ : score >= 40 ? ui::colors::WARNING()
+ : ui::colors::POSITIVE()),
+ gs_make_card("IS TOXIC", is_toxic ? "YES" : "NO", this,
+ is_toxic ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()),
+ gs_make_card("ACTION", action.isEmpty() ? "—" : action.toUpper(), this, verdict_color_for(action)),
+ gs_make_card("CLASS", classification.isEmpty() ? "—" : classification.toUpper(), this,
+ verdict_color_for(classification)),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> stats = {
+ gs_make_card("VOL IMBALANCE", fmt_num_safe(tx.value("vol_imbalance"), 4), this,
+ gs_pos_neg_color(tx.value("vol_imbalance").toDouble())),
+ gs_make_card("PRICE IMPACT", fmt_bps(tx.value("price_impact_bps")), this),
+ gs_make_card("BUY VOLUME", fmt_num_safe(tx.value("buy_volume"), 2), this, ui::colors::POSITIVE()),
+ gs_make_card("SELL VOLUME", fmt_num_safe(tx.value("sell_volume"), 2), this, ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(stats, this));
+
+ QList<QWidget*> trade_stats = {
+ gs_make_card("AVG TRADE", fmt_num_safe(tx.value("avg_trade_size"), 4), this),
+ gs_make_card("MAX TRADE", fmt_num_safe(tx.value("max_trade_size"), 4), this),
+ gs_make_card("SIZE CONC.", fmt_num_safe(tx.value("size_concentration"), 2), this),
+ gs_make_card("TRADE COUNT", fmt_int_safe(tx.value("trade_count")), this),
+ };
+ results_layout_->addWidget(gs_card_row(trade_stats, this));
+ };
+
+ // ── Helper: slippage card row + fills table ──────────────────────────────
+ auto slip_row = [this, accent](const QJsonObject& sl) {
+ results_layout_->addWidget(gs_section_header("SLIPPAGE ESTIMATE", accent));
+ const double slip_bps = sl.value("slippage_bps").toDouble();
+ const bool viable = sl.value("viable").toBool();
+ QList<QWidget*> top = {
+ gs_make_card("SIDE", sl.value("side").toString().toUpper(), this,
+ sl.value("side").toString() == "buy" ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("QUANTITY", fmt_num_safe(sl.value("quantity"), 4), this),
+ gs_make_card("FILLED", fmt_num_safe(sl.value("filled_quantity"), 4), this),
+ gs_make_card("VIABLE", viable ? "YES" : "NO", this,
+ viable ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> px = {
+ gs_make_card("AVG PRICE", fmt_num_safe(sl.value("average_price"), 4), this),
+ gs_make_card("MID PRICE", fmt_num_safe(sl.value("mid_price"), 4), this),
+ gs_make_card("SLIPPAGE", fmt_bps(slip_bps), this,
+ std::abs(slip_bps) > 10 ? ui::colors::WARNING() : ui::colors::TEXT_PRIMARY()),
+ gs_make_card("TOTAL COST", fmt_num_safe(sl.value("total_cost"), 4), this),
+ };
+ results_layout_->addWidget(gs_card_row(px, this));
+
+ // Fills table
+ const auto fills = sl.value("fills").toArray();
+ if (!fills.isEmpty()) {
+ auto* table = new QTableWidget(fills.size(), 3, this);
+ table->setHorizontalHeaderLabels({"Price", "Quantity", "Cost"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(fills.size() * 22 + 32, 220));
+ for (int i = 0; i < fills.size(); ++i) {
+ const auto f = fills[i].toObject();
+ auto add = [&](int col, double v, int dec) {
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', dec));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, col, it);
+ };
+ add(0, f.value("price").toDouble(), 4);
+ add(1, f.value("quantity").toDouble(), 4);
+ add(2, f.value("cost").toDouble(), 4);
+ table->setRowHeight(i, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ };
+
+ // ── Dispatch by command ──────────────────────────────────────────────────
+ if (command == "fetch_orderbook") {
+ book_row(payload);
+ book_tables(payload.value("bids").toArray(), payload.value("asks").toArray());
+ status_label_->setText(QString("OB %1: mid=%2 spread=%3bps")
+ .arg(symbol)
+ .arg(payload.value("mid_price").toDouble(), 0, 'f', 4)
+ .arg(payload.value("spread_bps").toDouble(), 0, 'f', 2));
+ } else if (command == "market_making") {
+ book_row(payload.value("book_metrics").toObject());
+ mm_row(payload.value("market_making").toObject());
+ status_label_->setText("Market making quote ready");
+ } else if (command == "toxic_flow") {
+ book_row(payload.value("book_metrics").toObject());
+ tox_row(payload.value("toxic_flow").toObject());
+ status_label_->setText(QString("Toxicity: %1")
+ .arg(payload.value("toxic_flow").toObject().value("toxicity_score").toDouble(), 0, 'f', 2));
+ } else if (command == "slippage") {
+ slip_row(payload);
+ status_label_->setText(QString("Slippage: %1 bps").arg(payload.value("slippage_bps").toDouble(), 0, 'f', 2));
+ } else if (command == "analyze") {
+ // Full snapshot: book + market_making + toxic_flow + slippage
+ book_row(payload.value("book_metrics").toObject());
+ book_tables(payload.value("bids").toArray(), payload.value("asks").toArray());
+ if (payload.contains("market_making"))
+ mm_row(payload.value("market_making").toObject());
+ if (payload.contains("toxic_flow"))
+ tox_row(payload.value("toxic_flow").toObject());
+ if (payload.contains("slippage"))
+ slip_row(payload.value("slippage").toObject());
+ status_label_->setText(QString("Full snapshot: %1 trades").arg(payload.value("trade_count").toInt()));
+ } else {
+ // Unknown command — fall through to generic flat display
+ display_result(payload);
+ }
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 2. ROLLING RETRAINING
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_rolling_retraining_result(const QString& command, const QJsonObject& payload) {
+ // Streaming events keep state across multiple calls — accumulate progress
+ if (command == "retrain") {
+ const QString event = payload.value("event").toString();
+ if (event == "start") {
+ clear_results();
+ results_layout_->addWidget(gs_section_header(
+ QString("RETRAIN START: %1 | %2 windows")
+ .arg(payload.value("model_id").toString())
+ .arg(payload.value("total_windows").toInt()),
+ module_.color.name()));
+ status_label_->setText("Retraining started…");
+ return;
+ }
+ if (event == "window") {
+ auto* lbl = new QLabel(QString("Window %1/%2: train→%3, test %4–%5")
+ .arg(payload.value("index").toInt())
+ .arg(payload.value("total").toInt())
+ .arg(payload.value("train_end").toString())
+ .arg(payload.value("test_start").toString())
+ .arg(payload.value("test_end").toString()));
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:10px;"
+ "padding:4px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BG_SURFACE(),
+ module_.color.name()));
+ results_layout_->addWidget(lbl);
+ status_label_->setText(QString("Window %1/%2")
+ .arg(payload.value("index").toInt())
+ .arg(payload.value("total").toInt()));
+ return;
+ }
+ if (event == "ensemble") {
+ auto* lbl = new QLabel(QString("Combining: %1").arg(payload.value("message").toString()));
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:10px;"
+ "padding:4px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), ui::colors::INFO()));
+ results_layout_->addWidget(lbl);
+ status_label_->setText("Ensembling rolling results…");
+ return;
+ }
+ if (event == "done") {
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", payload.value("model_id").toString(), this),
+ gs_make_card("WINDOWS TRAINED", fmt_int_safe(payload.value("windows_trained")), this,
+ ui::colors::POSITIVE()),
+ gs_make_card("ELAPSED",
+ QString::number(payload.value("elapsed_sec").toDouble(), 'f', 1) + " s", this),
+ gs_make_card("EXPERIMENT", payload.value("exp_name").toString(), this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Retrain complete");
+ return;
+ }
+ return;
+ }
+
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "list") {
+ const QJsonObject schedules = payload.value("schedules").toObject();
+ const int count = payload.value("count").toInt();
+ const bool qlib = payload.value("qlib_available").toBool();
+
+ QList<QWidget*> top = {
+ gs_make_card("SCHEDULES", QString::number(count), this,
+ count > 0 ? ui::colors::POSITIVE() : ui::colors::TEXT_TERTIARY()),
+ gs_make_card("QLIB", qlib ? "AVAILABLE" : "MISSING", this,
+ qlib ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (count > 0) {
+ auto* table = new QTableWidget(count, 6, this);
+ table->setHorizontalHeaderLabels({"Model ID", "Frequency", "Window", "Step", "Last Status", "Next Run"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(count * 26 + 32, 360));
+ int r = 0;
+ for (auto it = schedules.begin(); it != schedules.end(); ++it, ++r) {
+ const auto sch = it.value().toObject();
+ table->setItem(r, 0, new QTableWidgetItem(it.key()));
+ table->setItem(r, 1, new QTableWidgetItem(sch.value("frequency").toString()));
+ table->setItem(r, 2, new QTableWidgetItem(QString::number(sch.value("window").toInt())));
+ table->setItem(r, 3, new QTableWidgetItem(QString::number(sch.value("step").toInt())));
+ const QString status = sch.value("last_status").toString();
+ auto* st = new QTableWidgetItem(status);
+ if (status == "completed") st->setForeground(QColor(ui::colors::POSITIVE()));
+ else if (status == "failed") st->setForeground(QColor(ui::colors::NEGATIVE()));
+ else if (status == "running") st->setForeground(QColor(ui::colors::WARNING()));
+ table->setItem(r, 4, st);
+ table->setItem(r, 5, new QTableWidgetItem(sch.value("next_run").toString()));
+ table->setRowHeight(r, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 schedule(s)").arg(count));
+ return;
+ }
+
+ if (command == "create") {
+ const auto sch = payload.value("schedule").toObject();
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", payload.value("model_id").toString(), this, ui::colors::POSITIVE()),
+ gs_make_card("FREQUENCY", sch.value("frequency").toString(), this),
+ gs_make_card("WINDOW", QString::number(sch.value("window").toInt()), this),
+ gs_make_card("HORIZON", QString::number(sch.value("horizon").toInt()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ QList<QWidget*> next = {
+ gs_make_card("STEP", QString::number(sch.value("step").toInt()), this),
+ gs_make_card("NEXT RUN", sch.value("next_run").toString(), this, ui::colors::INFO()),
+ gs_make_card("TEMPLATE", sch.value("template_generated").toBool() ? "YES" : "NO", this,
+ sch.value("template_generated").toBool() ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("CREATED", sch.value("created_at").toString(), this),
+ };
+ results_layout_->addWidget(gs_card_row(next, this));
+ status_label_->setText("Schedule created");
+ return;
+ }
+
+ if (command == "preview") {
+ const int total = payload.value("total_windows").toInt();
+ const auto windows = payload.value("windows").toArray();
+ QList<QWidget*> top = {
+ gs_make_card("TOTAL WINDOWS", QString::number(total), this, ui::colors::POSITIVE()),
+ gs_make_card("STEP", QString::number(payload.value("step").toInt()), this),
+ gs_make_card("HORIZON", QString::number(payload.value("horizon").toInt()), this),
+ gs_make_card("CONFIG", QFileInfo(payload.value("conf_path").toString()).fileName(), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!windows.isEmpty()) {
+ auto* table = new QTableWidget(windows.size(), 4, this);
+ table->setHorizontalHeaderLabels({"Train Start", "Train End", "Test Start", "Test End"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(windows.size() * 24 + 32, 360));
+ for (int i = 0; i < windows.size(); ++i) {
+ const auto w = windows[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(w.value("train_start").toString()));
+ table->setItem(i, 1, new QTableWidgetItem(w.value("train_end").toString()));
+ table->setItem(i, 2, new QTableWidgetItem(w.value("test_start").toString()));
+ table->setItem(i, 3, new QTableWidgetItem(w.value("test_end").toString()));
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Preview: %1 rolling windows").arg(total));
+ return;
+ }
+
+ if (command == "delete") {
+ QList<QWidget*> top = {
+ gs_make_card("DELETED", payload.value("model_id").toString(), this, ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Schedule removed");
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 3. ADVANCED MODELS
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_advanced_models_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "list_available") {
+ const auto models = payload.value("models").toArray();
+ const bool torch = payload.value("torch_available").toBool();
+ const bool qlib = payload.value("qlib_available").toBool();
+ QSet<QString> categories;
+ for (const auto& m : models)
+ categories.insert(m.toObject().value("category").toString());
+ QList<QWidget*> top = {
+ gs_make_card("MODELS", QString::number(models.size()), this, ui::colors::POSITIVE()),
+ gs_make_card("PYTORCH", torch ? "AVAILABLE" : "MISSING", this,
+ torch ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("QLIB", qlib ? "AVAILABLE" : "MISSING", this,
+ qlib ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("CATEGORIES", QString::number(categories.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!models.isEmpty()) {
+ auto* table = new QTableWidget(models.size(), 4, this);
+ table->setHorizontalHeaderLabels({"ID", "Name", "Category", "Available"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(models.size() * 26 + 32, 360));
+ for (int i = 0; i < models.size(); ++i) {
+ const auto m = models[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(m.value("id").toString().toUpper()));
+ table->setItem(i, 1, new QTableWidgetItem(m.value("name").toString()));
+ table->setItem(i, 2, new QTableWidgetItem(m.value("category").toString()));
+ const bool avail = m.value("available").toBool();
+ auto* a = new QTableWidgetItem(avail ? "YES" : "NO");
+ a->setForeground(QColor(avail ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ a->setTextAlignment(Qt::AlignCenter);
+ table->setItem(i, 3, a);
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 advanced model(s) available").arg(models.size()));
+ return;
+ }
+
+ if (command == "create_model") {
+ const auto cfg = payload.value("config").toObject();
+ QList<QWidget*> top = {
+ gs_make_card("MODEL ID", payload.value("model_id").toString(), this, ui::colors::POSITIVE()),
+ gs_make_card("TYPE", payload.value("model_type").toString().toUpper(), this),
+ gs_make_card("CONFIG KEYS", QString::number(cfg.size()), this),
+ gs_make_card("STATUS", "CREATED", this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!cfg.isEmpty()) {
+ auto* table = new QTableWidget(cfg.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Hyperparameter", "Value"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(cfg.size() * 24 + 32, 240));
+ int r = 0;
+ for (auto it = cfg.begin(); it != cfg.end(); ++it, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(it.key().toUpper()));
+ auto* vi = new QTableWidgetItem(format_val(it.value()));
+ vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 1, vi);
+ table->setRowHeight(r, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(payload.value("message").toString("Model created"));
+ return;
+ }
+
+ if (command == "train_model") {
+ const double final_loss = payload.value("final_loss").toDouble();
+ const int epochs = payload.value("epochs_trained").toInt();
+ const int total_epochs = payload.value("total_epochs").toInt(epochs);
+ const auto loss_hist = payload.value("loss_history").toArray();
+ double initial_loss = loss_hist.isEmpty() ? 0.0 : loss_hist[0].toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL ID", payload.value("model_id").toString(), this),
+ gs_make_card("EPOCHS",
+ total_epochs > 0 && total_epochs != epochs
+ ? QString("%1 / %2").arg(epochs).arg(total_epochs)
+ : QString::number(epochs),
+ this, ui::colors::POSITIVE()),
+ gs_make_card("FINAL LOSS", QString::number(final_loss, 'g', 4), this,
+ final_loss < initial_loss * 0.5 ? ui::colors::POSITIVE()
+ : ui::colors::WARNING()),
+ gs_make_card("LOSS REDUCTION",
+ initial_loss > 0
+ ? QString::number((1.0 - final_loss / initial_loss) * 100, 'f', 1) + "%"
+ : "—",
+ this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Loss history table — sample to first/middle/last 12 epochs
+ if (!loss_hist.isEmpty()) {
+ const int rows = std::min<int>(12, loss_hist.size());
+ const int step = std::max<int>(1, loss_hist.size() / rows);
+ auto* table = new QTableWidget(rows, 2, this);
+ table->setHorizontalHeaderLabels({"Epoch", "Loss"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < loss_hist.size() && r < rows; i += step, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(i)));
+ auto* it = new QTableWidgetItem(QString::number(loss_hist[i].toDouble(), 'g', 6));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 1, it);
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Trained %1 epochs final loss=%2")
+ .arg(epochs).arg(final_loss, 0, 'g', 4));
+ return;
+ }
+
+ if (command == "predict") {
+ const auto preds = payload.value("predictions").toArray();
+ double mean = 0.0, mn = std::numeric_limits<double>::infinity(), mx = -std::numeric_limits<double>::infinity();
+ for (const auto& v : preds) {
+ const double d = v.toDouble();
+ mean += d;
+ mn = std::min(mn, d);
+ mx = std::max(mx, d);
+ }
+ if (!preds.isEmpty()) mean /= preds.size();
+ QList<QWidget*> top = {
+ gs_make_card("MODEL ID", payload.value("model_id").toString(), this),
+ gs_make_card("PREDICTIONS", QString::number(preds.size()), this, ui::colors::POSITIVE()),
+ gs_make_card("MEAN", QString::number(mean, 'f', 6), this, gs_pos_neg_color(mean)),
+ gs_make_card("RANGE",
+ preds.isEmpty() ? "—"
+ : QString("[%1, %2]").arg(mn, 0, 'f', 4).arg(mx, 0, 'f', 4),
+ this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Show first/middle/last 12 predictions
+ if (!preds.isEmpty()) {
+ const int rows = std::min<int>(12, preds.size());
+ const int step = std::max<int>(1, preds.size() / rows);
+ auto* table = new QTableWidget(rows, 2, this);
+ table->setHorizontalHeaderLabels({"Index", "Prediction"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < preds.size() && r < rows; i += step, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(i)));
+ const double v = preds[i].toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 6));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ it->setForeground(QColor(gs_pos_neg_color(v)));
+ table->setItem(r, 1, it);
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 predictions").arg(preds.size()));
+ return;
+ }
+
+ if (command == "info" || command == "list_models") {
+ // info: single model; list_models: array of summaries
+ if (command == "info") {
+ QList<QWidget*> top = {
+ gs_make_card("MODEL ID", payload.value("model_id").toString(), this),
+ gs_make_card("TYPE", payload.value("model_type").toString().toUpper(), this),
+ gs_make_card("TRAINED", payload.value("trained").toBool() ? "YES" : "NO", this,
+ payload.value("trained").toBool() ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("EPOCHS", fmt_int_safe(payload.value("epochs_trained")), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Model info loaded");
+ } else {
+ const auto models = payload.value("models").toArray();
+ QList<QWidget*> top = {
+ gs_make_card("REGISTERED", QString::number(models.size()), this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ if (!models.isEmpty()) {
+ auto* table = new QTableWidget(models.size(), 5, this);
+ table->setHorizontalHeaderLabels({"Model ID", "Type", "Trained", "Epochs", "Created"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(models.size() * 26 + 32, 360));
+ for (int i = 0; i < models.size(); ++i) {
+ const auto m = models[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(m.value("model_id").toString()));
+ table->setItem(i, 1, new QTableWidgetItem(m.value("type").toString().toUpper()));
+ const bool tr = m.value("trained").toBool();
+ auto* t = new QTableWidgetItem(tr ? "YES" : "NO");
+ t->setForeground(QColor(tr ? ui::colors::POSITIVE() : ui::colors::WARNING()));
+ t->setTextAlignment(Qt::AlignCenter);
+ table->setItem(i, 2, t);
+ table->setItem(i, 3, new QTableWidgetItem(QString::number(m.value("epochs_trained").toInt())));
+ table->setItem(i, 4, new QTableWidgetItem(m.value("created_at").toString()));
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 trained model(s)").arg(models.size()));
+ }
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 4. FEATURE ENGINEERING
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_feature_engineering_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ // ── check_status ─────────────────────────────────────────────────────────
+ if (command == "check_status") {
+ const bool pd = payload.value("pandas_available").toBool();
+ const auto inds = payload.value("indicators_available").toArray();
+ QList<QWidget*> top = {
+ gs_make_card("PANDAS", pd ? "AVAILABLE" : "MISSING", this,
+ pd ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("INDICATORS", QString::number(inds.size()), this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ if (!inds.isEmpty()) {
+ QStringList lst;
+ for (const auto& v : inds) lst << v.toString();
+ auto* lbl = new QLabel("Available: " + lst.join(", "));
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:10px;"
+ "padding:6px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+ status_label_->setText("Feature engineering ready");
+ return;
+ }
+
+ // ── select_features_by_ic ────────────────────────────────────────────────
+ if (command == "select_features_by_ic") {
+ const auto sel = payload.value("selected_features").toArray();
+ QList<QWidget*> top = {
+ gs_make_card("SELECTED", QString::number(sel.size()), this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!sel.isEmpty()) {
+ auto* table = new QTableWidget(sel.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Rank", "Feature"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(sel.size() * 24 + 32, 320));
+ for (int i = 0; i < sel.size(); ++i) {
+ table->setItem(i, 0, new QTableWidgetItem(QString::number(i + 1)));
+ table->setItem(i, 1, new QTableWidgetItem(sel[i].toString()));
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Selected %1 feature(s) by IC").arg(sel.size()));
+ return;
+ }
+
+ // ── Multi-series indicators (MACD, Bollinger, Stochastic) ────────────────
+ auto render_multi_series = [this](const QStringList& keys, const QJsonObject& payload) {
+ QList<QWidget*> stats;
+ QHash<QString, QJsonArray> series;
+ for (const auto& k : keys) {
+ const auto arr = payload.value(k).toArray();
+ series.insert(k, arr);
+ double sum = 0, mn = std::numeric_limits<double>::infinity(),
+ mx = -std::numeric_limits<double>::infinity();
+ int n = 0;
+ for (const auto& v : arr) {
+ if (v.isNull()) continue;
+ const double d = v.toDouble();
+ sum += d;
+ mn = std::min(mn, d);
+ mx = std::max(mx, d);
+ ++n;
+ }
+ const double mean = n > 0 ? sum / n : 0.0;
+ stats << gs_make_card(k.toUpper(), QString::number(mean, 'f', 4), this, gs_pos_neg_color(mean));
+ }
+ results_layout_->addWidget(gs_card_row(stats, this));
+
+ // Multi-column table sample
+ int max_n = 0;
+ // QJsonArray::size() returns qsizetype (qint64); std::max requires
+ // matching arg types — explicit cast keeps both as int.
+ for (const auto& a : series) max_n = std::max(max_n, static_cast<int>(a.size()));
+ const int rows = std::min<int>(15, max_n);
+ const int step = std::max<int>(1, max_n / rows);
+ auto* table = new QTableWidget(rows, keys.size() + 1, this);
+ QStringList hdr = {"Index"};
+ for (const auto& k : keys) hdr << k.toUpper();
+ table->setHorizontalHeaderLabels(hdr);
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < max_n && r < rows; i += step, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(i)));
+ for (int c = 0; c < keys.size(); ++c) {
+ const auto& a = series[keys[c]];
+ if (i < a.size() && !a[i].isNull()) {
+ const double v = a[i].toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, c + 1, it);
+ }
+ }
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ };
+
+ if (command == "macd") {
+ render_multi_series({"macd", "signal", "histogram"}, payload);
+ status_label_->setText("MACD computed");
+ return;
+ }
+ if (command == "bollinger_bands") {
+ render_multi_series({"upper", "middle", "lower"}, payload);
+ status_label_->setText("Bollinger bands computed");
+ return;
+ }
+ if (command == "stochastic_oscillator") {
+ render_multi_series({"k", "d"}, payload);
+ status_label_->setText("Stochastic oscillator computed");
+ return;
+ }
+
+ // ── Single-series indicators + evaluate_expression ───────────────────────
+ if (payload.contains("data") && payload.value("data").isArray()) {
+ const auto series = payload.value("data").toArray();
+ double sum = 0, mn = std::numeric_limits<double>::infinity(),
+ mx = -std::numeric_limits<double>::infinity();
+ int n = 0;
+ for (const auto& v : series) {
+ if (v.isNull()) continue;
+ const double d = v.toDouble();
+ sum += d;
+ mn = std::min(mn, d);
+ mx = std::max(mx, d);
+ ++n;
+ }
+ const double mean = n > 0 ? sum / n : 0.0;
+
+ QList<QWidget*> top = {
+ gs_make_card("INDICATOR", command.toUpper(), this),
+ gs_make_card("OBSERVATIONS", QString::number(n), this),
+ gs_make_card("MEAN", QString::number(mean, 'f', 4), this, gs_pos_neg_color(mean)),
+ gs_make_card("RANGE",
+ n > 0 ? QString("[%1, %2]").arg(mn, 0, 'f', 4).arg(mx, 0, 'f', 4) : "—",
+ this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Sampled table
+ const int rows = std::min<int>(15, series.size());
+ const int step = std::max<int>(1, series.size() / rows);
+ auto* table = new QTableWidget(rows, 2, this);
+ table->setHorizontalHeaderLabels({"Index", command.toUpper()});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < series.size() && r < rows; i += step, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(i)));
+ if (!series[i].isNull()) {
+ const double v = series[i].toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 1, it);
+ }
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ status_label_->setText(QString("%1: %2 obs").arg(command).arg(n));
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 5. PORTFOLIO OPTIMIZATION
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_portfolio_opt_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ const QString method = payload.value("method").toString();
+ QString header_text = (method.isEmpty() ? command : method).toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "check_status") {
+ const bool sp = payload.value("scipy_available").toBool();
+ const auto methods = payload.value("methods_available").toArray();
+ QList<QWidget*> top = {
+ gs_make_card("SCIPY", sp ? "AVAILABLE" : "MISSING", this,
+ sp ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("METHODS", QString::number(methods.size()), this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Portfolio optimization ready");
+ return;
+ }
+
+ // Efficient frontier — special case: array of {return, volatility, sharpe, weights}
+ if (command == "efficient_frontier") {
+ const auto frontier = payload.value("frontier").toArray();
+ // Find min-vol and max-sharpe portfolios
+ double min_vol = std::numeric_limits<double>::infinity();
+ double max_sharpe = -std::numeric_limits<double>::infinity();
+ QJsonObject min_vol_pt, max_sharpe_pt;
+ for (const auto& v : frontier) {
+ const auto p = v.toObject();
+ const double vol = p.value("volatility").toDouble();
+ const double sh = p.value("sharpe").toDouble();
+ if (vol < min_vol) { min_vol = vol; min_vol_pt = p; }
+ if (sh > max_sharpe) { max_sharpe = sh; max_sharpe_pt = p; }
+ }
+
+ QList<QWidget*> top = {
+ gs_make_card("PORTFOLIOS", QString::number(payload.value("num_portfolios").toInt()), this,
+ ui::colors::POSITIVE()),
+ gs_make_card("MIN VOL", fmt_pct_safe(QJsonValue(min_vol)), this, ui::colors::INFO()),
+ gs_make_card("MAX SHARPE", QString::number(max_sharpe, 'f', 3), this,
+ max_sharpe > 1.0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("RANGE",
+ frontier.isEmpty() ? "—"
+ : QString("%1% – %2%")
+ .arg(frontier.first().toObject().value("return").toDouble() * 100, 0, 'f', 1)
+ .arg(frontier.last().toObject().value("return").toDouble() * 100, 0, 'f', 1),
+ this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Sample frontier
+ if (!frontier.isEmpty()) {
+ const int rows = std::min<int>(15, frontier.size());
+ const int step = std::max<int>(1, frontier.size() / rows);
+ auto* table = new QTableWidget(rows, 3, this);
+ table->setHorizontalHeaderLabels({"Return", "Volatility", "Sharpe"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 24 + 32);
+ for (int i = 0, r = 0; i < frontier.size() && r < rows; i += step, ++r) {
+ const auto p = frontier[i].toObject();
+ const double ret = p.value("return").toDouble();
+ const double vol = p.value("volatility").toDouble();
+ const double sh = p.value("sharpe").toDouble();
+ auto add = [&](int col, const QString& s, const QString& fg = {}) {
+ auto* it = new QTableWidgetItem(s);
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (!fg.isEmpty()) it->setForeground(QColor(fg));
+ table->setItem(r, col, it);
+ };
+ add(0, QString::number(ret * 100, 'f', 2) + "%", gs_pos_neg_color(ret));
+ add(1, QString::number(vol * 100, 'f', 2) + "%");
+ add(2, QString::number(sh, 'f', 3),
+ sh >= 1.0 ? ui::colors::POSITIVE() : sh > 0 ? ui::colors::WARNING() : ui::colors::NEGATIVE());
+ table->setRowHeight(r, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("EF: %1 portfolios best Sharpe=%2")
+ .arg(payload.value("num_portfolios").toInt())
+ .arg(max_sharpe, 0, 'f', 3));
+ return;
+ }
+
+ // Standard optimization methods (BL, HRP, MinVar, MaxSharpe)
+ const QJsonObject weights = payload.value("weights").toObject();
+ const double exp_ret = payload.value("expected_return").toDouble();
+ const double exp_vol = payload.value("expected_volatility").toDouble();
+ const double sharpe = payload.value("sharpe_ratio").toDouble();
+ const bool has_ret = payload.contains("expected_return");
+ const bool has_sharpe = payload.contains("sharpe_ratio");
+
+ QList<QWidget*> top = {
+ gs_make_card("ASSETS", QString::number(weights.size()), this, ui::colors::POSITIVE()),
+ gs_make_card("EXP. VOLATILITY", fmt_pct_safe(QJsonValue(exp_vol)), this),
+ gs_make_card("EXP. RETURN", has_ret ? fmt_pct_safe(QJsonValue(exp_ret)) : "—", this,
+ has_ret ? gs_pos_neg_color(exp_ret) : ui::colors::TEXT_TERTIARY()),
+ gs_make_card("SHARPE", has_sharpe ? QString::number(sharpe, 'f', 3) : "—", this,
+ !has_sharpe ? ui::colors::TEXT_TERTIARY()
+ : sharpe >= 1.0 ? ui::colors::POSITIVE()
+ : sharpe > 0 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Black-Litterman extras
+ if (command == "black_litterman") {
+ QList<QWidget*> bl = {
+ gs_make_card("VIEWS", QString::number(payload.value("views_incorporated").toInt()), this, ui::colors::INFO()),
+ gs_make_card("EQUILIBRIUM",
+ QString::number(payload.value("equilibrium_returns").toObject().size()) + " assets", this),
+ gs_make_card("POSTERIOR",
+ QString::number(payload.value("posterior_returns").toObject().size()) + " assets", this),
+ gs_make_card("METHOD", "BL", this),
+ };
+ results_layout_->addWidget(gs_card_row(bl, this));
+ }
+
+ if (!weights.isEmpty()) {
+ results_layout_->addWidget(gs_section_header("WEIGHTS", accent));
+ results_layout_->addWidget(build_weights_table(weights, this));
+ }
+
+ status_label_->setText(QString("%1: %2 assets, vol=%3%")
+ .arg(method.isEmpty() ? command : method)
+ .arg(weights.size())
+ .arg(exp_vol * 100, 0, 'f', 2));
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 6. FACTOR EVALUATION
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_factor_evaluation_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "check_status") {
+ const bool pd = payload.value("pandas_available").toBool();
+ const bool ql = payload.value("qlib_available").toBool();
+ QList<QWidget*> top = {
+ gs_make_card("PANDAS", pd ? "AVAILABLE" : "MISSING", this,
+ pd ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("QLIB", ql ? "AVAILABLE" : "MISSING", this,
+ ql ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Factor evaluation ready");
+ return;
+ }
+
+ // ── calculate_ic ─────────────────────────────────────────────────────────
+ if (command == "calculate_ic") {
+ const double ic_mean = payload.value("IC_mean").toDouble();
+ const double ic_std = payload.value("IC_std").toDouble();
+ const double icir = payload.value("ICIR").toDouble();
+ const double ic_pos = payload.value("IC_positive_rate").toDouble();
+ const double pval = payload.value("p_value").toDouble();
+ const bool sig = payload.value("is_significant").toBool();
+
+ QList<QWidget*> top = {
+ gs_make_card("IC MEAN", QString::number(ic_mean, 'f', 4), this, gs_pos_neg_color(ic_mean)),
+ gs_make_card("IC STD", QString::number(ic_std, 'f', 4), this),
+ gs_make_card("ICIR", QString::number(icir, 'f', 3), this,
+ icir >= 0.5 ? ui::colors::POSITIVE()
+ : icir > 0 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ gs_make_card("POS RATE",
+ QString::number(ic_pos * 100, 'f', 1) + "%", this,
+ ic_pos > 0.55 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> stats = {
+ gs_make_card("IC MAX", QString::number(payload.value("IC_max").toDouble(), 'f', 4), this,
+ ui::colors::POSITIVE()),
+ gs_make_card("IC MIN", QString::number(payload.value("IC_min").toDouble(), 'f', 4), this,
+ ui::colors::NEGATIVE()),
+ gs_make_card("IC MEDIAN", QString::number(payload.value("IC_median").toDouble(), 'f', 4), this),
+ gs_make_card("OBSERVATIONS", QString::number(payload.value("observations").toInt()), this),
+ };
+ results_layout_->addWidget(gs_card_row(stats, this));
+
+ QList<QWidget*> moments = {
+ gs_make_card("SKEWNESS", QString::number(payload.value("IC_skewness").toDouble(), 'f', 4), this),
+ gs_make_card("KURTOSIS", QString::number(payload.value("IC_kurtosis").toDouble(), 'f', 4), this),
+ gs_make_card("p-VALUE", QString::number(pval, 'f', 4), this,
+ pval < 0.05 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("SIGNIFICANT", sig ? "YES" : "NO", this,
+ sig ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(moments, this));
+
+ // Sample IC series
+ const auto series = payload.value("ic_series").toArray();
+ if (!series.isEmpty()) {
+ const int rows = std::min<int>(15, series.size());
+ const int step = std::max<int>(1, series.size() / rows);
+ auto* table = new QTableWidget(rows, 2, this);
+ table->setHorizontalHeaderLabels({"Date", "IC"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < series.size() && r < rows; i += step, ++r) {
+ const auto o = series[i].toObject();
+ table->setItem(r, 0, new QTableWidgetItem(o.value("date").toString()));
+ const double ic = o.value("ic").toDouble();
+ auto* it = new QTableWidgetItem(QString::number(ic, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ it->setForeground(QColor(gs_pos_neg_color(ic)));
+ table->setItem(r, 1, it);
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("IC=%1 ICIR=%2 p=%3")
+ .arg(ic_mean, 0, 'f', 4).arg(icir, 0, 'f', 3).arg(pval, 0, 'f', 4));
+ return;
+ }
+
+ // ── analyze_factor_returns ───────────────────────────────────────────────
+ if (command == "analyze_factor_returns") {
+ const double ls_sharpe = payload.value("long_short_sharpe").toDouble();
+ const double ls_ret = payload.value("long_short_mean_return").toDouble();
+ const double mono = payload.value("monotonicity").toDouble();
+ const double spread = payload.value("spread").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("L/S SHARPE", QString::number(ls_sharpe, 'f', 3), this,
+ ls_sharpe >= 1.0 ? ui::colors::POSITIVE()
+ : ls_sharpe > 0 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ gs_make_card("L/S MEAN RET", fmt_pct_safe(QJsonValue(ls_ret), 4), this, gs_pos_neg_color(ls_ret)),
+ gs_make_card("SPREAD", fmt_pct_safe(QJsonValue(spread), 4), this, gs_pos_neg_color(spread)),
+ gs_make_card("MONOTONICITY",
+ QString::number(mono * 100, 'f', 1) + "%", this,
+ mono >= 0.7 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ const auto qs = payload.value("quantile_stats").toObject();
+ if (!qs.isEmpty()) {
+ QList<QPair<QString, QJsonObject>> rows;
+ for (auto it = qs.begin(); it != qs.end(); ++it)
+ rows.append({it.key(), it.value().toObject()});
+ std::sort(rows.begin(), rows.end(),
+ [](const auto& a, const auto& b) { return a.first < b.first; });
+
+ auto* table = new QTableWidget(rows.size(), 5, this);
+ table->setHorizontalHeaderLabels({"Quantile", "Mean Return", "Std", "Sharpe", "Win Rate"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(rows.size() * 26 + 32, 280));
+ for (int r = 0; r < rows.size(); ++r) {
+ const auto& q = rows[r].second;
+ table->setItem(r, 0, new QTableWidgetItem(rows[r].first));
+ const double mr = q.value("mean_return").toDouble();
+ auto* mri = new QTableWidgetItem(QString::number(mr * 100, 'f', 4) + "%");
+ mri->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ mri->setForeground(QColor(gs_pos_neg_color(mr)));
+ table->setItem(r, 1, mri);
+ auto* sd = new QTableWidgetItem(QString::number(q.value("std_return").toDouble() * 100, 'f', 4) + "%");
+ sd->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 2, sd);
+ const double sh = q.value("sharpe").toDouble();
+ auto* shi = new QTableWidgetItem(QString::number(sh, 'f', 3));
+ shi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ shi->setForeground(QColor(gs_pos_neg_color(sh)));
+ table->setItem(r, 3, shi);
+ auto* wi = new QTableWidgetItem(QString::number(q.value("win_rate").toDouble() * 100, 'f', 1) + "%");
+ wi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 4, wi);
+ table->setRowHeight(r, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("L/S Sharpe=%1 spread=%2%")
+ .arg(ls_sharpe, 0, 'f', 3).arg(spread * 100, 0, 'f', 4));
+ return;
+ }
+
+ // ── calculate_risk_metrics ───────────────────────────────────────────────
+ if (command == "calculate_risk_metrics") {
+ const double vol = payload.value("volatility").toDouble();
+ const double mdd = payload.value("max_drawdown").toDouble();
+ const double beta = payload.value("beta").toDouble();
+ const double te = payload.value("tracking_error").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("VOLATILITY", fmt_pct_safe(QJsonValue(vol)), this),
+ gs_make_card("MAX DRAWDOWN", fmt_pct_safe(QJsonValue(mdd)), this,
+ mdd <= -0.20 ? ui::colors::NEGATIVE() : ui::colors::WARNING()),
+ gs_make_card("BETA", QString::number(beta, 'f', 3), this,
+ beta > 1.2 ? ui::colors::WARNING() : ui::colors::TEXT_PRIMARY()),
+ gs_make_card("TRACKING ERROR", fmt_pct_safe(QJsonValue(te)), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> tail = {
+ gs_make_card("DOWNSIDE DEV", fmt_pct_safe(payload.value("downside_deviation")), this,
+ ui::colors::WARNING()),
+ gs_make_card("VaR 95%", fmt_pct_safe(payload.value("var_95")), this, ui::colors::WARNING()),
+ gs_make_card("CVaR 95%", fmt_pct_safe(payload.value("cvar_95")), this, ui::colors::NEGATIVE()),
+ gs_make_card("DD DURATION",
+ QString::number(payload.value("max_drawdown_duration").toInt()) + " days", this),
+ };
+ results_layout_->addWidget(gs_card_row(tail, this));
+
+ QList<QWidget*> capture = {
+ gs_make_card("UP CAPTURE",
+ QString::number(payload.value("up_capture").toDouble() * 100, 'f', 1) + "%", this,
+ payload.value("up_capture").toDouble() > 1.0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("DOWN CAPTURE",
+ QString::number(payload.value("down_capture").toDouble() * 100, 'f', 1) + "%", this,
+ payload.value("down_capture").toDouble() < 1.0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("SKEWNESS", QString::number(payload.value("skewness").toDouble(), 'f', 3), this,
+ gs_pos_neg_color(payload.value("skewness").toDouble())),
+ gs_make_card("KURTOSIS", QString::number(payload.value("kurtosis").toDouble(), 'f', 3), this),
+ };
+ results_layout_->addWidget(gs_card_row(capture, this));
+ status_label_->setText(QString("Vol=%1% MaxDD=%2% β=%3")
+ .arg(vol * 100, 0, 'f', 2).arg(mdd * 100, 0, 'f', 2).arg(beta, 0, 'f', 3));
+ return;
+ }
+
+ // ── generate_evaluation_report ───────────────────────────────────────────
+ if (command == "generate_evaluation_report") {
+ const auto rep = payload.value("report").toObject();
+ const QString rating = rep.value("rating").toString();
+ const double score = rep.value("overall_score").toDouble();
+ const auto ic = rep.value("ic_analysis").toObject();
+ const auto qa = rep.value("quantile_analysis").toObject();
+ const auto turn = rep.value("turnover_analysis").toObject();
+
+ QList<QWidget*> top = {
+ gs_make_card("FACTOR", rep.value("factor_name").toString(), this),
+ gs_make_card("OVERALL SCORE", QString::number(score, 'f', 1) + " / 100", this,
+ score >= 70 ? ui::colors::POSITIVE()
+ : score >= 40 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ gs_make_card("RATING", rating.toUpper(), this, verdict_color_for(rating)),
+ gs_make_card("PERIODS",
+ QString::number(rep.value("data_range").toObject().value("periods").toInt()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ results_layout_->addWidget(gs_section_header("IC ANALYSIS", accent));
+ QList<QWidget*> ic_cards = {
+ gs_make_card("IC MEAN", QString::number(ic.value("IC_mean").toDouble(), 'f', 4), this,
+ gs_pos_neg_color(ic.value("IC_mean").toDouble())),
+ gs_make_card("ICIR", QString::number(ic.value("ICIR").toDouble(), 'f', 3), this,
+ ic.value("ICIR").toDouble() >= 0.5 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("POS RATE",
+ QString::number(ic.value("IC_positive_rate").toDouble() * 100, 'f', 1) + "%", this),
+ gs_make_card("p-VALUE", QString::number(ic.value("p_value").toDouble(), 'f', 4), this,
+ ic.value("p_value").toDouble() < 0.05 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(ic_cards, this));
+
+ results_layout_->addWidget(gs_section_header("QUANTILE ANALYSIS", accent));
+ QList<QWidget*> qa_cards = {
+ gs_make_card("L/S SHARPE", QString::number(qa.value("long_short_sharpe").toDouble(), 'f', 3), this,
+ qa.value("long_short_sharpe").toDouble() >= 1.0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("SPREAD", fmt_pct_safe(qa.value("spread"), 4), this,
+ gs_pos_neg_color(qa.value("spread").toDouble())),
+ gs_make_card("MONOTONICITY",
+ QString::number(qa.value("monotonicity").toDouble() * 100, 'f', 1) + "%", this,
+ qa.value("monotonicity").toDouble() >= 0.7 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("L/S MEAN RET",
+ fmt_pct_safe(qa.value("long_short_mean_return"), 4), this,
+ gs_pos_neg_color(qa.value("long_short_mean_return").toDouble())),
+ };
+ results_layout_->addWidget(gs_card_row(qa_cards, this));
+
+ if (!turn.isEmpty()) {
+ results_layout_->addWidget(gs_section_header("TURNOVER", accent));
+ QList<QWidget*> tu_cards = {
+ gs_make_card("MEAN", fmt_pct_safe(turn.value("mean_turnover")), this),
+ gs_make_card("MEDIAN", fmt_pct_safe(turn.value("median_turnover")), this),
+ gs_make_card("MAX", fmt_pct_safe(turn.value("max_turnover")), this, ui::colors::WARNING()),
+ gs_make_card("OBS", QString::number(turn.value("observations").toInt()), this),
+ };
+ results_layout_->addWidget(gs_card_row(tu_cards, this));
+ }
+ status_label_->setText(QString("%1: %2/100 (%3)")
+ .arg(rep.value("factor_name").toString())
+ .arg(score, 0, 'f', 1).arg(rating));
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 7. STRATEGY BUILDER
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_strategy_builder_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ const QString stype = payload.value("strategy_type").toString();
+ QString header_text = (stype.isEmpty() ? command : stype).toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "check_status") {
+ QList<QWidget*> top = {
+ gs_make_card("QLIB", payload.value("qlib_available").toBool() ? "AVAILABLE" : "MISSING", this,
+ payload.value("qlib_available").toBool() ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("PANDAS", payload.value("pandas_available").toBool() ? "AVAILABLE" : "MISSING", this,
+ payload.value("pandas_available").toBool() ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("NUMPY", payload.value("numpy_available").toBool() ? "AVAILABLE" : "MISSING", this,
+ payload.value("numpy_available").toBool() ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("SCIPY", payload.value("scipy_available").toBool() ? "AVAILABLE" : "MISSING", this,
+ payload.value("scipy_available").toBool() ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Strategy builder ready");
+ return;
+ }
+
+ // portfolio_metrics — a flat dict of stats
+ if (command == "portfolio_metrics") {
+ const double sh = payload.value("sharpe_ratio").toDouble();
+ const double ann = payload.value("annual_return").toDouble();
+ const double mdd = payload.value("max_drawdown").toDouble();
+ const double cal = payload.value("calmar_ratio").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("ANN. RETURN", fmt_pct_safe(QJsonValue(ann)), this, gs_pos_neg_color(ann)),
+ gs_make_card("VOLATILITY", fmt_pct_safe(payload.value("volatility")), this),
+ gs_make_card("SHARPE", QString::number(sh, 'f', 3), this,
+ sh >= 1.0 ? ui::colors::POSITIVE() : sh > 0 ? ui::colors::WARNING() : ui::colors::NEGATIVE()),
+ gs_make_card("MAX DD", fmt_pct_safe(QJsonValue(mdd)), this,
+ mdd <= -0.20 ? ui::colors::NEGATIVE() : ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> ratios = {
+ gs_make_card("SORTINO", QString::number(payload.value("sortino_ratio").toDouble(), 'f', 3), this,
+ payload.value("sortino_ratio").toDouble() >= 1.0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("CALMAR", QString::number(cal, 'f', 3), this,
+ cal >= 0.5 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("INFO RATIO", QString::number(payload.value("information_ratio").toDouble(), 'f', 3), this,
+ payload.value("information_ratio").toDouble() > 0.5 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("BETA", QString::number(payload.value("beta").toDouble(), 'f', 3), this),
+ };
+ results_layout_->addWidget(gs_card_row(ratios, this));
+
+ QList<QWidget*> day = {
+ gs_make_card("WIN RATE",
+ QString::number(payload.value("win_rate").toDouble() * 100, 'f', 1) + "%", this,
+ payload.value("win_rate").toDouble() > 0.55 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("BEST DAY", fmt_pct_safe(payload.value("best_day"), 3), this, ui::colors::POSITIVE()),
+ gs_make_card("WORST DAY", fmt_pct_safe(payload.value("worst_day"), 3), this, ui::colors::NEGATIVE()),
+ gs_make_card("ALPHA", fmt_pct_safe(payload.value("alpha"), 3), this,
+ gs_pos_neg_color(payload.value("alpha").toDouble())),
+ };
+ results_layout_->addWidget(gs_card_row(day, this));
+ status_label_->setText(QString("Annual %1% Sharpe %2 MaxDD %3%")
+ .arg(ann * 100, 0, 'f', 2).arg(sh, 0, 'f', 3).arg(mdd * 100, 0, 'f', 2));
+ return;
+ }
+
+ // Strategy creation commands — common fields: strategy_id, strategy_type, config?, weights?, suitable_for[]
+ QList<QWidget*> top = {
+ gs_make_card("STRATEGY ID", payload.value("strategy_id").toString(), this, ui::colors::POSITIVE()),
+ gs_make_card("TYPE", stype, this),
+ gs_make_card("STATUS", "CREATED", this, ui::colors::POSITIVE()),
+ gs_make_card("DESCRIPTION", "↓ see below", this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Risk parity / mean variance: weights present
+ if (payload.contains("weights")) {
+ const auto weights = payload.value("weights").toObject();
+ if (payload.contains("expected_return")) {
+ QList<QWidget*> mv = {
+ gs_make_card("EXP. RETURN", fmt_pct_safe(payload.value("expected_return")), this,
+ gs_pos_neg_color(payload.value("expected_return").toDouble())),
+ gs_make_card("EXP. VOL", fmt_pct_safe(payload.value("expected_volatility")), this),
+ gs_make_card("SHARPE",
+ QString::number(payload.value("sharpe_ratio").toDouble(), 'f', 3), this,
+ payload.value("sharpe_ratio").toDouble() >= 1.0 ? ui::colors::POSITIVE()
+ : ui::colors::WARNING()),
+ gs_make_card("RISK-FREE",
+ fmt_pct_safe(payload.value("risk_free_rate")), this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(mv, this));
+ } else if (payload.contains("target_risk")) {
+ QList<QWidget*> rp = {
+ gs_make_card("TARGET RISK", fmt_pct_safe(payload.value("target_risk")), this),
+ gs_make_card("EXP. VOL",
+ payload.value("expected_volatility").isString()
+ ? payload.value("expected_volatility").toString()
+ : fmt_pct_safe(payload.value("expected_volatility")),
+ this),
+ gs_make_card("REBALANCE", payload.value("rebalance_frequency").toString().toUpper(), this),
+ gs_make_card("ASSETS", QString::number(weights.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(rp, this));
+ }
+ results_layout_->addWidget(gs_section_header("WEIGHTS", accent));
+ results_layout_->addWidget(build_weights_table(weights, this));
+ } else if (payload.contains("config")) {
+ // TopK-Dropout / Enhanced Indexing / Weight Strategy: render config dict
+ const auto cfg = payload.value("config").toObject();
+ if (!cfg.isEmpty()) {
+ results_layout_->addWidget(gs_section_header("CONFIG", accent));
+ auto* table = new QTableWidget(cfg.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Parameter", "Value"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(cfg.size() * 24 + 32, 240));
+ int r = 0;
+ for (auto it = cfg.begin(); it != cfg.end(); ++it, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(it.key().toUpper()));
+ auto* vi = new QTableWidgetItem(format_val(it.value()));
+ vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 1, vi);
+ table->setRowHeight(r, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+
+ // Show extra Enhanced-Indexing fields
+ if (payload.contains("expected_tracking_error") || payload.contains("expected_alpha")) {
+ QList<QWidget*> ei = {
+ gs_make_card("TRACKING ERROR", payload.value("expected_tracking_error").toString(), this),
+ gs_make_card("ALPHA TARGET", payload.value("expected_alpha").toString(), this, ui::colors::POSITIVE()),
+ gs_make_card("BENCHMARK",
+ payload.value("config").toObject().value("benchmark").toString(), this, ui::colors::INFO()),
+ gs_make_card("ACTIVE SHARE",
+ QString::number(payload.value("config").toObject().value("active_share").toDouble() * 100, 'f', 1) + "%",
+ this),
+ };
+ results_layout_->addWidget(gs_card_row(ei, this));
+ } else if (payload.contains("expected_turnover")) {
+ QList<QWidget*> tk = {
+ gs_make_card("EXPECTED TURNOVER", payload.value("expected_turnover").toString(), this, ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(tk, this));
+ }
+ }
+
+ // Description + suitable_for badges
+ const QString desc = payload.value("description").toString();
+ if (!desc.isEmpty()) {
+ auto* lbl = new QLabel(desc);
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-size:11px; padding:8px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+ const auto sf = payload.value("suitable_for").toArray();
+ if (!sf.isEmpty()) {
+ QStringList sf_list;
+ for (const auto& v : sf) sf_list << "• " + v.toString();
+ auto* sf_lbl = new QLabel("Suitable for:\n" + sf_list.join("\n"));
+ sf_lbl->setWordWrap(true);
+ sf_lbl->setStyleSheet(QString("color:%1; font-size:10px; padding:6px 10px;")
+ .arg(ui::colors::TEXT_SECONDARY()));
+ results_layout_->addWidget(sf_lbl);
+ }
+
+ status_label_->setText(QString("%1 strategy created").arg(stype));
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 8. DATA PROCESSORS
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_data_processors_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ if (command == "check_status") {
+ QList<QWidget*> top = {
+ gs_make_card("PANDAS", payload.value("pandas_available").toBool() ? "AVAILABLE" : "MISSING", this,
+ payload.value("pandas_available").toBool() ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("PROCESSORS", QString::number(payload.value("processors_available").toInt()), this,
+ ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+ status_label_->setText("Data processors ready");
+ return;
+ }
+
+ if (command == "list_processors") {
+ const auto procs = payload.value("processors").toArray();
+ const auto descs = payload.value("descriptions").toObject();
+
+ QList<QWidget*> top = {
+ gs_make_card("AVAILABLE", QString::number(procs.size()), this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!procs.isEmpty()) {
+ auto* table = new QTableWidget(procs.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Processor", "Description"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(procs.size() * 26 + 32, 360));
+ for (int i = 0; i < procs.size(); ++i) {
+ const QString name = procs[i].toString();
+ table->setItem(i, 0, new QTableWidgetItem(name.toUpper()));
+ table->setItem(i, 1, new QTableWidgetItem(descs.value(name).toString()));
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 processor(s)").arg(procs.size()));
+ return;
+ }
+
+ if (command == "create_pipeline") {
+ const auto procs = payload.value("processors").toArray();
+ QStringList plist;
+ for (const auto& v : procs) plist << v.toString();
+
+ QList<QWidget*> top = {
+ gs_make_card("PIPELINE ID", payload.value("pipeline_id").toString(), this, ui::colors::POSITIVE()),
+ gs_make_card("PROCESSORS", QString::number(payload.value("num_processors").toInt()), this),
+ gs_make_card("STATUS", "CREATED", this, ui::colors::POSITIVE()),
+ gs_make_card("STAGES", QString::number(plist.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!plist.isEmpty()) {
+ auto* lbl = new QLabel("Pipeline order: " + plist.join(" → "));
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:11px;"
+ "padding:8px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+ status_label_->setText("Pipeline created");
+ return;
+ }
+
+ if (command == "process_data") {
+ const auto stats = payload.value("statistics").toObject();
+ const auto in_shape = stats.value("input_shape").toArray();
+ const auto out_shape = stats.value("output_shape").toArray();
+ auto shape_str = [](const QJsonArray& a) {
+ QStringList s;
+ for (const auto& v : a) s << QString::number(v.toInt());
+ return "(" + s.join(", ") + ")";
+ };
+
+ QList<QWidget*> top = {
+ gs_make_card("PIPELINE", payload.value("pipeline_id").toString(), this),
+ gs_make_card("INPUT SHAPE", shape_str(in_shape), this),
+ gs_make_card("OUTPUT SHAPE", shape_str(out_shape), this, ui::colors::POSITIVE()),
+ gs_make_card("ROWS DROPPED",
+ in_shape.size() > 0 && out_shape.size() > 0
+ ? QString::number(in_shape[0].toInt() - out_shape[0].toInt())
+ : "—",
+ this, ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> nulls = {
+ gs_make_card("INPUT NULLS", QString::number(stats.value("input_nulls").toInt()), this,
+ ui::colors::WARNING()),
+ gs_make_card("OUTPUT NULLS", QString::number(stats.value("output_nulls").toInt()), this,
+ stats.value("output_nulls").toInt() == 0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("INPUT MEAN", QString::number(stats.value("input_mean").toDouble(), 'f', 4), this),
+ gs_make_card("OUTPUT MEAN", QString::number(stats.value("output_mean").toDouble(), 'f', 4), this),
+ };
+ results_layout_->addWidget(gs_card_row(nulls, this));
+
+ QList<QWidget*> std_row = {
+ gs_make_card("INPUT STD", QString::number(stats.value("input_std").toDouble(), 'f', 4), this),
+ gs_make_card("OUTPUT STD", QString::number(stats.value("output_std").toDouble(), 'f', 4), this,
+ std::abs(stats.value("output_std").toDouble() - 1.0) < 0.1 ? ui::colors::POSITIVE()
+ : ui::colors::TEXT_PRIMARY()),
+ gs_make_card("STD RATIO",
+ stats.value("input_std").toDouble() > 0
+ ? QString::number(stats.value("output_std").toDouble() / stats.value("input_std").toDouble(), 'f', 3)
+ : "—",
+ this),
+ gs_make_card("DROPPED %",
+ in_shape.size() > 0 && in_shape[0].toInt() > 0
+ ? QString::number((1.0 - double(out_shape[0].toInt()) / in_shape[0].toInt()) * 100, 'f', 2) + "%"
+ : "—",
+ this),
+ };
+ results_layout_->addWidget(gs_card_row(std_row, this));
+ status_label_->setText(QString("Processed: %1 → %2").arg(shape_str(in_shape)).arg(shape_str(out_shape)));
+ return;
+ }
+
+ display_result(payload);
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp
index 85e4a8f0e..fe8b54087 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CFA.cpp
@@ -17,6 +17,7 @@
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
+#include <QColor>
#include <QHash>
#include <QHBoxLayout>
#include <QHeaderView>
@@ -27,6 +28,7 @@
#include <QLabel>
#include <QLineEdit>
#include <QList>
+#include <QPair>
#include <QPushButton>
#include <QRegularExpression>
#include <QSpinBox>
@@ -39,6 +41,7 @@
#include <QVBoxLayout>
#include <QWidget>
+#include <algorithm>
#include <cmath>
#include <initializer_list>
@@ -111,6 +114,7 @@ QWidget* QuantModulePanel::build_cfa_quant_panel() {
vl->addWidget(params_lbl);
auto* stack = new QStackedWidget(w);
+ stack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
auto add_page = [&](std::initializer_list<QWidget*> rows) {
auto* page = new QWidget(stack);
auto* pv = new QVBoxLayout(page);
@@ -447,29 +451,31 @@ QWidget* QuantModulePanel::build_cfa_quant_panel() {
// ── CFA Quant Result Display ───────────────────────────────────────────────
//
-// CFA Python returns a uniform shape:
+// CFA Python returns a uniform envelope:
// { success, analysis_type,
// result: { value, method, parameters, metadata, calculation_time, timestamp, calculator } }
//
-// validate_data is the exception: result is a DataQualityReport.to_dict() with
-// quality_score, issues, warnings, statistics, recommendations.
+// validate_data is the exception: result is a DataQualityReport.to_dict()
+// (quality_score, issues, warnings, statistics, recommendations).
//
-// We render flat scalars in result.value + result.metadata as a metrics table,
-// surface the analysis method/calc-time as a header line, and keep the raw JSON
-// + export button for inspection.
+// Each command has its own card layout — same visual language as Quant
+// Reporting (gs_make_card / gs_card_row / gs_section_header). The flattened
+// 2-col fallback only runs when the shape doesn't match a known command.
namespace {
+// Fallback flattener — only used for unknown commands.
void cfa_flatten_scalars(const QJsonObject& obj, const QString& prefix, QStringList& keys,
QHash<QString, QJsonValue>& out) {
for (auto it = obj.begin(); it != obj.end(); ++it) {
const auto& v = it.value();
const QString key = prefix.isEmpty() ? it.key() : prefix + "." + it.key();
if (v.isObject()) {
- // Recurse one level deep so nested {slope, intercept} flattens nicely;
- // skip very deep / array-heavy fields (parameters.data, fitted_values).
if (key.endsWith(".data") || key.endsWith(".fitted_values") ||
- key.endsWith(".residuals") || key.endsWith(".model_summary"))
+ key.endsWith(".residuals") || key.endsWith(".model_summary") ||
+ key.endsWith(".predictions") || key.endsWith(".sample_means") ||
+ key.endsWith(".resampled_statistics") || key.endsWith(".cluster_labels") ||
+ key.endsWith(".principal_components") || key.endsWith(".cluster_centers"))
continue;
cfa_flatten_scalars(v.toObject(), key, keys, out);
} else if (!v.isArray()) {
@@ -479,6 +485,21 @@ void cfa_flatten_scalars(const QJsonObject& obj, const QString& prefix, QStringL
}
}
+QString fmt_num_safe(const QJsonValue& v, int decimals = 4) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toDouble(), 'f', decimals);
+}
+
+QString fmt_pct(const QJsonValue& v, int decimals = 2) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toDouble() * 100.0, 'f', decimals) + "%";
+}
+
+QString fmt_bool(const QJsonValue& v) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return v.toBool() ? QStringLiteral("YES") : QStringLiteral("NO");
+}
+
} // namespace
void QuantModulePanel::display_cfa_result(const QString& command, const QJsonObject& payload) {
@@ -493,44 +514,832 @@ void QuantModulePanel::display_cfa_result(const QString& command, const QJsonObj
const QString method = result.value("method").toString();
const double calc_time = result.value("calculation_time").toDouble();
const QString analysis_type = payload.value("analysis_type").toString(command);
+ const QString accent = module_.color.name();
- // ── Header ──────────────────────────────────────────────────────────────
- auto* header = new QLabel(QString("%1 • %2 • %3 ms")
- .arg(analysis_type.toUpper())
- .arg(method)
- .arg(QString::number(calc_time * 1000.0, 'f', 1)));
- header->setStyleSheet(QString("color:%1; font-weight:700; font-family:%2; letter-spacing:1px;")
- .arg(module_.color.name())
- .arg(ui::fonts::DATA_FAMILY));
- results_layout_->addWidget(header);
-
- // ── validate_data has its own report shape ──────────────────────────────
- if (command == "validate_data") {
- const double score = result.value("quality_score").toDouble();
- auto* score_lbl = new QLabel(QString("Quality Score: %1 / 100").arg(score, 0, 'f', 1));
- score_lbl->setStyleSheet(QString("color:%1; font-size:16px; font-weight:700;")
- .arg(score >= 80 ? ui::colors::POSITIVE()
- : score >= 50 ? ui::colors::WARNING()
- : ui::colors::NEGATIVE()));
- results_layout_->addWidget(score_lbl);
+ // ── Section header ──────────────────────────────────────────────────────
+ QString header_text = analysis_type.toUpper();
+ header_text.replace('_', ' ');
+ if (!method.isEmpty())
+ header_text += QString(" | %1").arg(method.toUpper());
+ if (calc_time > 0.0)
+ header_text += QString(" | %1 ms").arg(QString::number(calc_time * 1000.0, 'f', 1));
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ const QJsonValue value_raw = result.value("value");
+ const QJsonObject value_obj = value_raw.toObject();
+ const QJsonObject meta = result.value("metadata").toObject();
+ bool rendered = false;
+
+ // ── 1. TREND ANALYSIS ───────────────────────────────────────────────────
+ if (command == "trend_analysis") {
+ const double slope = value_obj.value("slope").toDouble();
+ const double intercept = value_obj.value("intercept").toDouble();
+ const double r2 = meta.value("r_squared").toDouble();
+ const double tstat = meta.value("slope_t_statistic").toDouble();
+ const double pval = meta.value("slope_p_value").toDouble();
+ const QString direction = meta.value("trend_direction").toString().toUpper();
+ const bool significant = meta.value("trend_significant").toBool();
+
+ auto dir_color = [&]() {
+ if (direction == "UPWARD") return ui::colors::POSITIVE();
+ if (direction == "DOWNWARD") return ui::colors::NEGATIVE();
+ return ui::colors::TEXT_PRIMARY();
+ };
+
+ QList<QWidget*> top = {
+ gs_make_card("DIRECTION", direction.isEmpty() ? "—" : direction, this, dir_color()),
+ gs_make_card("SLOPE", gs_fmt_num(slope, 6), this, gs_pos_neg_color(slope)),
+ gs_make_card("INTERCEPT", gs_fmt_num(intercept, 4), this),
+ gs_make_card("R²", gs_fmt_num(r2, 4), this,
+ r2 >= 0.7 ? ui::colors::POSITIVE()
+ : r2 >= 0.3 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> stats = {
+ gs_make_card("t-STATISTIC", gs_fmt_num(tstat, 3), this),
+ gs_make_card("p-VALUE", gs_fmt_num(pval, 4), this,
+ pval < 0.05 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("SIGNIFICANT", significant ? "YES" : "NO", this,
+ significant ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("OBSERVATIONS",
+ QString::number(result.value("parameters").toObject()
+ .value("data").toArray().size()),
+ this),
+ };
+ results_layout_->addWidget(gs_card_row(stats, this));
+ status_label_->setText(QString("Trend %1 slope=%2 R²=%3 p=%4")
+ .arg(direction).arg(slope, 0, 'g', 4)
+ .arg(r2, 0, 'f', 3).arg(pval, 0, 'f', 4));
+ rendered = true;
+ }
+
+ // ── 2. STATIONARITY TEST ────────────────────────────────────────────────
+ else if (command == "stationarity_test") {
+ const QString test = result.value("parameters").toObject().value("test_type").toString().toUpper();
+ const double tstat = value_obj.value("test_statistic").toDouble();
+ const double pval = value_obj.value("p_value").toDouble();
+ const bool stationary = value_obj.value("is_stationary").toBool();
+ const QString h0 = value_obj.value("null_hypothesis").toString();
+
+ QList<QWidget*> top = {
+ gs_make_card("TEST", test.isEmpty() ? "ADF" : test, this),
+ gs_make_card("TEST STAT", gs_fmt_num(tstat, 4), this),
+ gs_make_card("p-VALUE", gs_fmt_num(pval, 4), this,
+ pval < 0.05 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("STATIONARY", stationary ? "YES" : "NO", this,
+ stationary ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Critical values row
+ const QJsonObject crit = value_obj.value("critical_values").toObject();
+ if (!crit.isEmpty()) {
+ QList<QWidget*> crit_cards;
+ for (auto it = crit.begin(); it != crit.end(); ++it) {
+ crit_cards << gs_make_card("CRIT " + it.key(), gs_fmt_num(it.value().toDouble(), 4), this);
+ }
+ results_layout_->addWidget(gs_card_row(crit_cards, this));
+ }
+
+ if (!h0.isEmpty()) {
+ auto* note = new QLabel("H₀: " + h0);
+ note->setStyleSheet(QString("color:%1; font-size:10px; padding:6px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BG_SURFACE(), accent));
+ note->setWordWrap(true);
+ results_layout_->addWidget(note);
+ }
+ status_label_->setText(QString("%1: stat=%2 p=%3 → %4")
+ .arg(test).arg(tstat, 0, 'f', 3).arg(pval, 0, 'f', 4)
+ .arg(stationary ? "stationary" : "non-stationary"));
+ rendered = true;
+ }
+
+ // ── 3. ARIMA MODEL ──────────────────────────────────────────────────────
+ else if (command == "arima_model") {
+ const QJsonArray order = result.value("parameters").toObject().value("order").toArray();
+ const QString order_str = order.size() == 3
+ ? QString("(%1, %2, %3)").arg(order[0].toInt()).arg(order[1].toInt()).arg(order[2].toInt())
+ : QStringLiteral("—");
+ const double aic = meta.value("aic").toDouble();
+ const double bic = meta.value("bic").toDouble();
+ const double llf = meta.value("log_likelihood").toDouble();
+ const double lb_p = meta.value("ljung_box_p_value").toDouble();
+ const bool autocorr = meta.value("residuals_autocorrelated").toBool();
+
+ QList<QWidget*> top = {
+ gs_make_card("ORDER (p,d,q)", order_str, this),
+ gs_make_card("AIC", gs_fmt_num(aic, 2), this),
+ gs_make_card("BIC", gs_fmt_num(bic, 2), this),
+ gs_make_card("LOG-LIKELIHOOD", gs_fmt_num(llf, 2), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> diag = {
+ gs_make_card("LJUNG-BOX p", gs_fmt_num(lb_p, 4), this,
+ lb_p > 0.05 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("RESID. AUTOCORR.", autocorr ? "YES" : "NO", this,
+ autocorr ? ui::colors::WARNING() : ui::colors::POSITIVE()),
+ gs_make_card("FITTED POINTS",
+ QString::number(value_obj.value("fitted_values").toArray().size()), this),
+ gs_make_card("RESIDUALS",
+ QString::number(value_obj.value("residuals").toArray().size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(diag, this));
+
+ // Coefficient list (value.parameters can be an array OR a {const, ar.L1, ...} object)
+ const QJsonValue coef_raw = value_obj.value("parameters");
+ QStringList coef_lines;
+ if (coef_raw.isArray()) {
+ const auto arr = coef_raw.toArray();
+ for (int i = 0; i < arr.size(); ++i)
+ coef_lines << QString("β%1 = %2").arg(i).arg(arr[i].toDouble(), 0, 'f', 6);
+ } else if (coef_raw.isObject()) {
+ const auto o = coef_raw.toObject();
+ for (auto it = o.begin(); it != o.end(); ++it)
+ coef_lines << QString("%1 = %2").arg(it.key()).arg(it.value().toDouble(), 0, 'f', 6);
+ }
+ if (!coef_lines.isEmpty()) {
+ auto* coef_lbl = new QLabel("Coefficients: " + coef_lines.join(" "));
+ coef_lbl->setWordWrap(true);
+ coef_lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:10px;"
+ "padding:6px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(coef_lbl);
+ }
+ status_label_->setText(QString("ARIMA%1 AIC=%2 Ljung-Box p=%3")
+ .arg(order_str).arg(aic, 0, 'f', 2).arg(lb_p, 0, 'f', 3));
+ rendered = true;
+ }
+
+ // ── 4. FORECASTING ──────────────────────────────────────────────────────
+ else if (command == "forecasting") {
+ const QJsonObject params = result.value("parameters").toObject();
+ const QString fmethod = params.value("method").toString().toUpper();
+ const int horizon = meta.value("forecast_horizon").toInt();
+ const int train_n = meta.value("train_data_size").toInt();
+ const int test_n = meta.value("test_data_size").toInt();
+ const QJsonValue mae = meta.value("mae");
+ const QJsonValue rmse = meta.value("rmse");
+ const QJsonValue mape = meta.value("mape");
+
+ QList<QWidget*> top = {
+ gs_make_card("METHOD", fmethod.isEmpty() ? "—" : fmethod, this),
+ gs_make_card("HORIZON", QString::number(horizon), this),
+ gs_make_card("TRAIN", QString::number(train_n) + " obs", this),
+ gs_make_card("TEST", QString::number(test_n) + " obs", this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> err = {
+ gs_make_card("MAE", fmt_num_safe(mae, 4), this,
+ mae.isNull() ? ui::colors::TEXT_TERTIARY() : ui::colors::WARNING()),
+ gs_make_card("RMSE", fmt_num_safe(rmse, 4), this,
+ rmse.isNull() ? ui::colors::TEXT_TERTIARY() : ui::colors::WARNING()),
+ gs_make_card("MAPE", mape.isNull() ? QStringLiteral("—")
+ : QString::number(mape.toDouble(), 'f', 2) + "%", this),
+ gs_make_card("FCST POINTS",
+ QString::number(value_raw.toArray().size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(err, this));
+
+ // Forecast values table
+ if (value_raw.isArray()) {
+ const auto arr = value_raw.toArray();
+ auto* table = new QTableWidget(arr.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Step", "Forecast"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(arr.size() * 24 + 32, 280));
+ for (int i = 0; i < arr.size(); ++i) {
+ table->setItem(i, 0, new QTableWidgetItem(QString("t+%1").arg(i + 1)));
+ auto* it = new QTableWidgetItem(QString::number(arr[i].toDouble(), 'f', 6));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 1, it);
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 forecast (%2 steps) MAE=%3")
+ .arg(fmethod).arg(horizon).arg(fmt_num_safe(mae, 4)));
+ rendered = true;
+ }
+
+ // ── 5. SUPERVISED LEARNING ──────────────────────────────────────────────
+ else if (command == "supervised_learning") {
+ const QJsonObject params = result.value("parameters").toObject();
+ const QString problem = params.value("problem_type").toString();
+ const bool is_reg = (problem == "regression");
+ const QString best = meta.value("best_algorithm").toString().toUpper();
+ const int train_n = meta.value("train_size").toInt();
+ const int test_n = meta.value("test_size").toInt();
+ const int n_feat = meta.value("n_features").toInt();
+
+ QList<QWidget*> top = {
+ gs_make_card("PROBLEM", problem.toUpper(), this),
+ gs_make_card("BEST ALGORITHM", best.isEmpty() ? "—" : best, this, ui::colors::POSITIVE()),
+ gs_make_card("FEATURES", QString::number(n_feat), this),
+ gs_make_card("TRAIN / TEST",
+ QString("%1 / %2").arg(train_n).arg(test_n), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Per-algorithm metrics table
+ QStringList headers = is_reg
+ ? QStringList{"Algorithm", "MSE", "RMSE", "R²"}
+ : QStringList{"Algorithm", "Accuracy", "Precision", "Recall"};
+ QStringList score_keys = is_reg
+ ? QStringList{"mse", "rmse", "r2_score"}
+ : QStringList{"accuracy", "precision", "recall"};
+ QList<QPair<QString, QJsonObject>> rows;
+ for (auto it = value_obj.begin(); it != value_obj.end(); ++it) {
+ if (it.value().isObject())
+ rows.append({it.key(), it.value().toObject()});
+ }
+
+ if (!rows.isEmpty()) {
+ auto* table = new QTableWidget(rows.size(), headers.size(), this);
+ table->setHorizontalHeaderLabels(headers);
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(rows.size() * 26 + 32, 320));
+ for (int r = 0; r < rows.size(); ++r) {
+ const auto& algo = rows[r].first;
+ const auto& metrics = rows[r].second;
+ auto* name_it = new QTableWidgetItem(algo.toUpper());
+ if (algo.toUpper() == best)
+ name_it->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(r, 0, name_it);
+
+ if (metrics.contains("error")) {
+ auto* err_it = new QTableWidgetItem("ERR: " + metrics.value("error").toString());
+ err_it->setForeground(QColor(ui::colors::NEGATIVE()));
+ table->setItem(r, 1, err_it);
+ table->setSpan(r, 1, 1, headers.size() - 1);
+ } else {
+ for (int c = 0; c < score_keys.size(); ++c) {
+ const double v = metrics.value(score_keys[c]).toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ // R² and accuracy: green if good
+ if ((score_keys[c] == "r2_score" || score_keys[c] == "accuracy") && v > 0.5)
+ it->setForeground(QColor(ui::colors::POSITIVE()));
+ else if ((score_keys[c] == "r2_score" || score_keys[c] == "accuracy") && v < 0)
+ it->setForeground(QColor(ui::colors::NEGATIVE()));
+ table->setItem(r, c + 1, it);
+ }
+ }
+ table->setRowHeight(r, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Supervised %1: best=%2 (%3 algos)")
+ .arg(problem).arg(best).arg(rows.size()));
+ rendered = true;
+ }
+
+ // ── 6. UNSUPERVISED LEARNING ────────────────────────────────────────────
+ else if (command == "unsupervised_learning") {
+ const int n_samples = meta.value("n_samples").toInt();
+ const int n_feat = meta.value("n_features").toInt();
+
+ QList<QWidget*> top = {
+ gs_make_card("SAMPLES", QString::number(n_samples), this),
+ gs_make_card("FEATURES", QString::number(n_feat), this),
+ gs_make_card("METHODS", QString::number(value_obj.size()), this),
+ gs_make_card("DATA SCALED", meta.value("data_scaled").toBool() ? "YES" : "NO", this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // PCA section
+ if (value_obj.contains("pca") && value_obj.value("pca").isObject()) {
+ const QJsonObject pca = value_obj.value("pca").toObject();
+ results_layout_->addWidget(gs_section_header("PCA", accent));
+ const QJsonArray evr = pca.value("explained_variance_ratio").toArray();
+ const QJsonArray cum = pca.value("cumulative_variance").toArray();
+ const int n95 = pca.value("components_for_95_variance").toInt();
+ const double total = evr.isEmpty() ? 0.0 : cum[cum.size() - 1].toDouble();
+
+ QList<QWidget*> pca_cards = {
+ gs_make_card("COMPONENTS", QString::number(evr.size()), this),
+ gs_make_card("FOR 95% VAR", QString::number(n95), this, ui::colors::POSITIVE()),
+ gs_make_card("TOP COMPONENT", evr.isEmpty() ? "—"
+ : QString::number(evr[0].toDouble() * 100, 'f', 2) + "%", this),
+ gs_make_card("CUM. EXPLAINED", QString::number(total * 100, 'f', 2) + "%", this),
+ };
+ results_layout_->addWidget(gs_card_row(pca_cards, this));
+
+ if (!evr.isEmpty()) {
+ const int rows = std::min<int>(10, evr.size());
+ auto* table = new QTableWidget(rows, 3, this);
+ table->setHorizontalHeaderLabels({"PC", "Explained Var", "Cumulative"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 24 + 32);
+ for (int i = 0; i < rows; ++i) {
+ table->setItem(i, 0, new QTableWidgetItem(QString("PC%1").arg(i + 1)));
+ auto* e = new QTableWidgetItem(QString::number(evr[i].toDouble() * 100, 'f', 3) + "%");
+ e->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 1, e);
+ auto* c = new QTableWidgetItem(QString::number(cum[i].toDouble() * 100, 'f', 3) + "%");
+ c->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 2, c);
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ }
+
+ // K-Means section
+ if (value_obj.contains("kmeans") && value_obj.value("kmeans").isObject()) {
+ const QJsonObject km = value_obj.value("kmeans").toObject();
+ results_layout_->addWidget(gs_section_header("K-MEANS", accent));
+ const int opt_k = km.value("optimal_k").toInt();
+ const QJsonArray sil = km.value("silhouette_by_k").toArray();
+ const QJsonArray ine = km.value("inertia_by_k").toArray();
+ double best_sil = 0.0;
+ for (const auto& v : sil) {
+ const auto pair = v.toArray();
+ if (pair.size() >= 2) best_sil = std::max(best_sil, pair[1].toDouble());
+ }
+ const QJsonArray labels = km.value("cluster_labels").toArray();
+
+ QList<QWidget*> km_cards = {
+ gs_make_card("OPTIMAL k", QString::number(opt_k), this, ui::colors::POSITIVE()),
+ gs_make_card("BEST SILHOUETTE", gs_fmt_num(best_sil, 4), this,
+ best_sil >= 0.5 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("k RANGE", QString::number(sil.size()), this),
+ gs_make_card("OBSERVATIONS", QString::number(labels.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(km_cards, this));
+
+ if (!sil.isEmpty()) {
+ auto* table = new QTableWidget(sil.size(), 3, this);
+ table->setHorizontalHeaderLabels({"k", "Silhouette", "Inertia"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(sil.size() * 24 + 32, 280));
+ for (int i = 0; i < sil.size(); ++i) {
+ const auto sp = sil[i].toArray();
+ const auto ip = i < ine.size() ? ine[i].toArray() : QJsonArray();
+ const int k = sp.size() > 0 ? sp[0].toInt() : 0;
+ const double s = sp.size() > 1 ? sp[1].toDouble() : 0.0;
+ const double in_v = ip.size() > 1 ? ip[1].toDouble() : 0.0;
+
+ auto* k_it = new QTableWidgetItem(QString::number(k));
+ if (k == opt_k) k_it->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(i, 0, k_it);
+ auto* s_it = new QTableWidgetItem(QString::number(s, 'f', 4));
+ s_it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (k == opt_k) s_it->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(i, 1, s_it);
+ auto* in_it = new QTableWidgetItem(QString::number(in_v, 'f', 2));
+ in_it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 2, in_it);
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ }
+
+ // Hierarchical (simple)
+ if (value_obj.contains("hierarchical") && value_obj.value("hierarchical").isObject()) {
+ const QJsonObject h = value_obj.value("hierarchical").toObject();
+ QList<QWidget*> h_cards = {
+ gs_make_card("HIERARCHICAL k", QString::number(h.value("n_clusters").toInt()), this),
+ gs_make_card("LABELS",
+ QString::number(h.value("cluster_labels").toArray().size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(h_cards, this));
+ }
+ status_label_->setText(QString("Unsupervised: %1 method(s) on %2×%3")
+ .arg(value_obj.size()).arg(n_samples).arg(n_feat));
+ rendered = true;
+ }
+
+ // ── 7. MODEL EVALUATION ─────────────────────────────────────────────────
+ else if (command == "model_evaluation") {
+ const QJsonObject params = result.value("parameters").toObject();
+ const QString model = params.value("model_type").toString().toUpper();
+ const QString problem = params.value("problem_type").toString().toUpper();
+ const int folds = params.value("cv_folds").toInt();
+ const double mean_cv = meta.value("mean_cv_score").toDouble();
+ const double std_cv = meta.value("std_cv_score").toDouble();
+ const double overfit = meta.value("overfitting_score").toDouble();
+ const bool is_overfit = meta.value("is_overfitting").toBool();
+ const double final_train = meta.value("final_train_score").toDouble();
+ const double final_val = meta.value("final_val_score").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", model.isEmpty() ? "—" : model, this),
+ gs_make_card("PROBLEM", problem, this),
+ gs_make_card("CV FOLDS", QString::number(folds), this),
+ gs_make_card("MEAN CV ± σ",
+ QString("%1 ± %2").arg(mean_cv, 0, 'f', 4).arg(std_cv, 0, 'f', 4), this,
+ mean_cv > 0.5 ? ui::colors::POSITIVE()
+ : mean_cv > 0 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> overfit_cards = {
+ gs_make_card("FINAL TRAIN", gs_fmt_num(final_train, 4), this),
+ gs_make_card("FINAL VAL", gs_fmt_num(final_val, 4), this,
+ final_val > 0.5 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("OVERFIT GAP", gs_fmt_num(overfit, 4), this,
+ overfit > 0.1 ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()),
+ gs_make_card("OVERFITTING", is_overfit ? "YES" : "NO", this,
+ is_overfit ? ui::colors::NEGATIVE() : ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(overfit_cards, this));
+
+ // CV scores + learning curves table
+ const QJsonArray cv = value_obj.value("cv_scores").toArray();
+ const QJsonArray train_s = value_obj.value("train_scores").toArray();
+ const QJsonArray val_s = value_obj.value("val_scores").toArray();
+ if (!cv.isEmpty() || !train_s.isEmpty()) {
+ auto* table = new QTableWidget(std::max(cv.size(), train_s.size()), 3, this);
+ table->setHorizontalHeaderLabels({"Idx", "CV / Train Score", "Val Score"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(table->rowCount() * 24 + 32, 280));
+ const int rows = table->rowCount();
+ for (int i = 0; i < rows; ++i) {
+ table->setItem(i, 0, new QTableWidgetItem(QString::number(i)));
+ if (i < cv.size()) {
+ auto* it = new QTableWidgetItem(QString::number(cv[i].toDouble(), 'f', 4) + " (cv)");
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 1, it);
+ } else if (i < train_s.size()) {
+ auto* it = new QTableWidgetItem(QString::number(train_s[i].toDouble(), 'f', 4) + " (tr)");
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(i, 1, it);
+ }
+ if (i < val_s.size()) {
+ const double v = val_s[i].toDouble();
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (v > 0.5) it->setForeground(QColor(ui::colors::POSITIVE()));
+ else if (v < 0) it->setForeground(QColor(ui::colors::NEGATIVE()));
+ table->setItem(i, 2, it);
+ }
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1: CV %2±%3 Overfit: %4")
+ .arg(model).arg(mean_cv, 0, 'f', 3).arg(std_cv, 0, 'f', 3)
+ .arg(is_overfit ? "YES" : "NO"));
+ rendered = true;
+ }
+
+ // ── 8. RESAMPLING METHODS ───────────────────────────────────────────────
+ else if (command == "resampling_methods") {
+ const double orig = meta.value("original_statistic").toDouble();
+ const int data_n = meta.value("data_size").toInt();
+ const QString stat_name = meta.value("statistic_name").toString();
+
+ QList<QWidget*> top = {
+ gs_make_card("STATISTIC", stat_name.isEmpty() ? "mean" : stat_name, this),
+ gs_make_card("ORIGINAL VALUE", gs_fmt_num(orig, 6), this, gs_pos_neg_color(orig)),
+ gs_make_card("DATA SIZE", QString::number(data_n), this),
+ gs_make_card("METHODS", QString::number(value_obj.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Bootstrap
+ if (value_obj.contains("bootstrap") && value_obj.value("bootstrap").isObject()) {
+ const QJsonObject b = value_obj.value("bootstrap").toObject();
+ results_layout_->addWidget(gs_section_header("BOOTSTRAP", accent));
+ const auto ci = b.value("confidence_interval").toArray();
+ const QString ci_str = ci.size() == 2
+ ? QString("[%1, %2]").arg(ci[0].toDouble(), 0, 'f', 4).arg(ci[1].toDouble(), 0, 'f', 4)
+ : QStringLiteral("—");
+ QList<QWidget*> b_cards = {
+ gs_make_card("MEAN", gs_fmt_num(b.value("mean").toDouble(), 6), this),
+ gs_make_card("STD", gs_fmt_num(b.value("std").toDouble(), 6), this),
+ gs_make_card("BIAS", gs_fmt_num(b.value("bias").toDouble(), 6), this,
+ gs_pos_neg_color(b.value("bias").toDouble())),
+ gs_make_card("95% CI", ci_str, this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(b_cards, this));
+ }
+
+ // Jackknife
+ if (value_obj.contains("jackknife") && value_obj.value("jackknife").isObject()) {
+ const QJsonObject j = value_obj.value("jackknife").toObject();
+ results_layout_->addWidget(gs_section_header("JACKKNIFE", accent));
+ QList<QWidget*> j_cards = {
+ gs_make_card("BIAS", gs_fmt_num(j.value("bias").toDouble(), 6), this,
+ gs_pos_neg_color(j.value("bias").toDouble())),
+ gs_make_card("BIAS-CORRECTED", gs_fmt_num(j.value("bias_corrected_estimate").toDouble(), 6), this),
+ gs_make_card("VARIANCE", gs_fmt_num(j.value("variance_estimate").toDouble(), 6), this),
+ gs_make_card("STD ERROR", gs_fmt_num(j.value("std_error").toDouble(), 6), this),
+ };
+ results_layout_->addWidget(gs_card_row(j_cards, this));
+ }
+
+ // Permutation
+ if (value_obj.contains("permutation") && value_obj.value("permutation").isObject()) {
+ const QJsonObject p = value_obj.value("permutation").toObject();
+ results_layout_->addWidget(gs_section_header("PERMUTATION", accent));
+ const double pv = p.value("p_value").toDouble();
+ const bool sig = p.value("significant").toBool();
+ QList<QWidget*> p_cards = {
+ gs_make_card("p-VALUE", gs_fmt_num(pv, 4), this,
+ pv < 0.05 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("SIGNIFICANT", sig ? "YES" : "NO", this,
+ sig ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("RESAMPLES",
+ QString::number(p.value("resampled_statistics").toArray().size()), this),
+ gs_make_card("ORIGINAL", gs_fmt_num(orig, 6), this),
+ };
+ results_layout_->addWidget(gs_card_row(p_cards, this));
+ }
+ status_label_->setText(QString("Resampling: original=%1 (%2 method(s))")
+ .arg(orig, 0, 'g', 4).arg(value_obj.size()));
+ rendered = true;
+ }
+
+ // ── 9. SAMPLING TECHNIQUES ──────────────────────────────────────────────
+ else if (command == "sampling_techniques") {
+ const QJsonObject params = result.value("parameters").toObject();
+ const int pop_n = params.value("population_size").toInt();
+ const int sample_n = params.value("sample_size").toInt();
+ const double frac = meta.value("sampling_fraction").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("POPULATION", QString::number(pop_n), this),
+ gs_make_card("SAMPLE SIZE", QString::number(sample_n), this),
+ gs_make_card("SAMPLING FRAC", QString::number(frac * 100, 'f', 2) + "%", this),
+ gs_make_card("METHODS", QString::number(value_obj.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Per-method comparison table — pick the first numeric column from each method's stats
+ if (!value_obj.isEmpty()) {
+ QList<QPair<QString, QJsonObject>> methods;
+ for (auto it = value_obj.begin(); it != value_obj.end(); ++it)
+ if (it.value().isObject()) methods.append({it.key(), it.value().toObject()});
+
+ auto* table = new QTableWidget(methods.size(), 5, this);
+ table->setHorizontalHeaderLabels({"Method", "Sample N", "Sample Mean", "Pop Mean", "Bias"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(methods.size() * 26 + 32, 240));
+ for (int r = 0; r < methods.size(); ++r) {
+ const auto& name = methods[r].first;
+ const auto& m = methods[r].second;
+ table->setItem(r, 0, new QTableWidgetItem(name.toUpper()));
+ if (m.contains("error")) {
+ auto* e = new QTableWidgetItem("ERR: " + m.value("error").toString());
+ e->setForeground(QColor(ui::colors::NEGATIVE()));
+ table->setItem(r, 1, e);
+ table->setSpan(r, 1, 1, 4);
+ } else {
+ table->setItem(r, 1, new QTableWidgetItem(QString::number(m.value("sample_size").toInt())));
+ auto first_val = [](const QJsonObject& o) -> double {
+ if (o.isEmpty()) return 0.0;
+ return o.begin().value().toDouble();
+ };
+ const double sm = first_val(m.value("sample_mean").toObject());
+ const double pm = first_val(m.value("population_mean").toObject());
+ const double bias = first_val(m.value("bias").toObject());
+ auto add_n = [&](int col, double v, bool pos_neg = false) {
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', 4));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (pos_neg) it->setForeground(QColor(gs_pos_neg_color(v)));
+ table->setItem(r, col, it);
+ };
+ add_n(2, sm);
+ add_n(3, pm);
+ add_n(4, bias, true);
+ }
+ table->setRowHeight(r, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Sampling: %1 method(s) pop=%2 n=%3 (%4%)")
+ .arg(value_obj.size()).arg(pop_n).arg(sample_n)
+ .arg(frac * 100, 0, 'f', 1));
+ rendered = true;
+ }
+
+ // ── 10. CENTRAL LIMIT THEOREM ───────────────────────────────────────────
+ else if (command == "central_limit_theorem") {
+ const QJsonObject params = result.value("parameters").toObject();
+ const QString dist = params.value("population_dist").toString().toUpper();
+ const double pmean = meta.value("population_mean").toDouble();
+ const double pstd = meta.value("population_std").toDouble();
+ const int pop_n = meta.value("population_size").toInt();
+
+ QList<QWidget*> top = {
+ gs_make_card("DISTRIBUTION", dist.isEmpty() ? "—" : dist, this),
+ gs_make_card("POP MEAN", gs_fmt_num(pmean, 4), this),
+ gs_make_card("POP STD", gs_fmt_num(pstd, 4), this),
+ gs_make_card("POP SIZE", QString::number(pop_n), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Per-sample-size table
+ QList<QPair<int, QJsonObject>> rows;
+ for (auto it = value_obj.begin(); it != value_obj.end(); ++it) {
+ if (!it.value().isObject()) continue;
+ const QString k = it.key(); // "n_5", "n_30", etc
+ const int n = k.startsWith("n_") ? k.mid(2).toInt() : 0;
+ rows.append({n, it.value().toObject()});
+ }
+ std::sort(rows.begin(), rows.end(),
+ [](const auto& a, const auto& b) { return a.first < b.first; });
+
+ if (!rows.isEmpty()) {
+ auto* table = new QTableWidget(rows.size(), 7, this);
+ table->setHorizontalHeaderLabels(
+ {"n", "Theor. Mean", "Theor. SE", "Empir. Mean", "Empir. SE", "Mean Bias", "Normal?"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(rows.size() * 26 + 32, 320));
+ for (int r = 0; r < rows.size(); ++r) {
+ const auto& o = rows[r].second;
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(rows[r].first)));
+ auto add = [&](int col, double v, int dec) {
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', dec));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, col, it);
+ };
+ add(1, o.value("theoretical_mean").toDouble(), 4);
+ add(2, o.value("theoretical_std").toDouble(), 4);
+ add(3, o.value("empirical_mean").toDouble(), 4);
+ add(4, o.value("empirical_std").toDouble(), 4);
+ const double mb = o.value("mean_bias").toDouble();
+ auto* mbi = new QTableWidgetItem(QString::number(mb, 'f', 4));
+ mbi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ mbi->setForeground(QColor(gs_pos_neg_color(mb)));
+ table->setItem(r, 5, mbi);
+ const QJsonValue norm = o.value("appears_normal");
+ QString norm_str = norm.isNull() ? "—" : (norm.toBool() ? "YES" : "NO");
+ auto* ni = new QTableWidgetItem(norm_str);
+ ni->setTextAlignment(Qt::AlignCenter);
+ if (!norm.isNull())
+ ni->setForeground(QColor(norm.toBool() ? ui::colors::POSITIVE() : ui::colors::WARNING()));
+ table->setItem(r, 6, ni);
+ table->setRowHeight(r, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("CLT %1: μ=%2 σ=%3 (%4 sample sizes)")
+ .arg(dist).arg(pmean, 0, 'f', 3).arg(pstd, 0, 'f', 3).arg(rows.size()));
+ rendered = true;
+ }
+
+ // ── 11. SAMPLING ERROR ANALYSIS ─────────────────────────────────────────
+ else if (command == "sampling_error_analysis") {
+ const int rec_n = meta.value("recommended_sample_size").toInt();
+ const double tgt_moe = meta.value("target_margin_of_error").toDouble();
+ const double zc = meta.value("z_critical").toDouble();
+ const double conf = meta.value("coverage_target").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("RECOMMENDED n", QString::number(rec_n), this, ui::colors::POSITIVE()),
+ gs_make_card("TARGET MoE", gs_fmt_num(tgt_moe, 4), this),
+ gs_make_card("Z CRITICAL", gs_fmt_num(zc, 4), this),
+ gs_make_card("CONFIDENCE", QString::number(conf * 100, 'f', 1) + "%", this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QPair<int, QJsonObject>> rows;
+ for (auto it = value_obj.begin(); it != value_obj.end(); ++it) {
+ if (!it.value().isObject()) continue;
+ const auto o = it.value().toObject();
+ rows.append({o.value("sample_size").toInt(), o});
+ }
+ std::sort(rows.begin(), rows.end(),
+ [](const auto& a, const auto& b) { return a.first < b.first; });
+
+ if (!rows.isEmpty()) {
+ auto* table = new QTableWidget(rows.size(), 6, this);
+ table->setHorizontalHeaderLabels(
+ {"n", "Theor. SE", "Empir. SE", "MoE", "Coverage", "MSE"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(rows.size() * 26 + 32, 320));
+ for (int r = 0; r < rows.size(); ++r) {
+ const auto& o = rows[r].second;
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(rows[r].first)));
+ auto add = [&](int col, double v, int dec) {
+ auto* it = new QTableWidgetItem(QString::number(v, 'f', dec));
+ it->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, col, it);
+ };
+ add(1, o.value("theoretical_se").toDouble(), 6);
+ add(2, o.value("empirical_se").toDouble(), 6);
+ add(3, o.value("theoretical_moe").toDouble(), 6);
+ const double cov = o.value("coverage_probability").toDouble();
+ auto* ci = new QTableWidgetItem(QString::number(cov * 100, 'f', 2) + "%");
+ ci->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ ci->setForeground(QColor(cov >= conf - 0.02 ? ui::colors::POSITIVE() : ui::colors::WARNING()));
+ table->setItem(r, 4, ci);
+ add(5, o.value("mean_squared_error").toDouble(), 6);
+ table->setRowHeight(r, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("Sampling error: recommended n=%1 target MoE=%2")
+ .arg(rec_n).arg(tgt_moe, 0, 'f', 4));
+ rendered = true;
+ }
+
+ // ── 12. VALIDATE DATA ───────────────────────────────────────────────────
+ else if (command == "validate_data") {
+ const double score = result.value("quality_score").toDouble();
+ const QString name = result.value("data_name").toString();
const auto issues = result.value("issues").toArray();
const auto warnings = result.value("warnings").toArray();
const auto recs = result.value("recommendations").toArray();
+ const auto stats_obj = result.value("statistics").toObject();
+
+ QList<QWidget*> top = {
+ gs_make_card("QUALITY SCORE", QString::number(score, 'f', 1) + " / 100", this,
+ score >= 80 ? ui::colors::POSITIVE()
+ : score >= 50 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ gs_make_card("DATA NAME", name.isEmpty() ? "data" : name, this),
+ gs_make_card("ISSUES", QString::number(issues.size()), this,
+ issues.isEmpty() ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("WARNINGS", QString::number(warnings.size()), this,
+ warnings.isEmpty() ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Statistics table (if present)
+ if (!stats_obj.isEmpty()) {
+ QStringList sk;
+ QHash<QString, QJsonValue> sv;
+ for (auto it = stats_obj.begin(); it != stats_obj.end(); ++it) {
+ if (!it.value().isObject() && !it.value().isArray()) {
+ sk << it.key();
+ sv.insert(it.key(), it.value());
+ }
+ }
+ if (!sk.isEmpty()) {
+ results_layout_->addWidget(gs_section_header("STATISTICS", accent));
+ auto* table = new QTableWidget(sk.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Statistic", "Value"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(sk.size() * 24 + 32, 280));
+ for (int r = 0; r < sk.size(); ++r) {
+ QString lbl = sk[r];
+ lbl.replace('_', ' ');
+ table->setItem(r, 0, new QTableWidgetItem(lbl.toUpper()));
+ auto* vi = new QTableWidgetItem(format_val(sv.value(sk[r])));
+ vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 1, vi);
+ table->setRowHeight(r, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ }
- auto add_section = [this](const QString& title, const QJsonArray& items, bool issue_shape) {
- if (items.isEmpty())
- return;
- auto* lbl = new QLabel(QString("%1 (%2)").arg(title).arg(items.size()));
- lbl->setStyleSheet(QString("color:%1; font-weight:700; margin-top:6px;")
- .arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(lbl);
+ // Issues / warnings / recommendations sections
+ auto add_section = [this, accent](const QString& title, const QJsonArray& items, bool issue_shape,
+ const QString& bar_color) {
+ if (items.isEmpty()) return;
+ auto* hdr = new QLabel(QString("%1 (%2)").arg(title).arg(items.size()));
+ hdr->setStyleSheet(QString("color:%1; font-weight:700; font-size:10px; letter-spacing:1px;"
+ "padding:6px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), bar_color));
+ results_layout_->addWidget(hdr);
for (const auto& v : items) {
QString text;
- if (issue_shape) {
- auto o = v.toObject();
+ QString fg = ui::colors::TEXT_SECONDARY();
+ if (issue_shape && v.isObject()) {
+ const auto o = v.toObject();
+ const QString sev = o.value("severity").toString().toUpper();
+ if (sev == "CRITICAL" || sev == "HIGH") fg = ui::colors::NEGATIVE();
+ else if (sev == "MEDIUM") fg = ui::colors::WARNING();
text = QString("[%1] %2: %3")
- .arg(o.value("severity").toString(),
+ .arg(sev.isEmpty() ? "—" : sev,
o.value("type").toString(),
o.value("description").toString(o.value("message").toString()));
} else {
@@ -538,36 +1347,35 @@ void QuantModulePanel::display_cfa_result(const QString& command, const QJsonObj
}
auto* item = new QLabel(text);
item->setWordWrap(true);
- item->setStyleSheet(QString("color:%1; padding:2px 0;").arg(ui::colors::TEXT_SECONDARY()));
+ item->setStyleSheet(QString("color:%1; padding:2px 12px;").arg(fg));
results_layout_->addWidget(item);
}
};
- add_section("Issues", issues, true);
- add_section("Warnings", warnings, true);
- add_section("Recommendations", recs, false);
- } else {
- // ── Standard analyses: flatten value + metadata into a metrics table ──
+ add_section("ISSUES", issues, true, ui::colors::NEGATIVE());
+ add_section("WARNINGS", warnings, true, ui::colors::WARNING());
+ add_section("RECOMMENDATIONS", recs, false, ui::colors::INFO());
+
+ status_label_->setText(QString("Validate %1: score=%2 issues=%3 warnings=%4")
+ .arg(name).arg(score, 0, 'f', 1).arg(issues.size()).arg(warnings.size()));
+ rendered = true;
+ }
+
+ // ── Fallback for unknown commands: flat metrics table ───────────────────
+ if (!rendered) {
QStringList keys;
QHash<QString, QJsonValue> kv;
- const QJsonObject value_obj = result.value("value").toObject();
- const QJsonObject meta_obj = result.value("metadata").toObject();
-
- // value can also be a scalar (e.g. forecasting → array, but value can be number)
- const QJsonValue value_raw = result.value("value");
if (value_obj.isEmpty() && !value_raw.isNull() && !value_raw.isObject() && !value_raw.isArray()) {
keys.append("value");
kv.insert("value", value_raw);
} else {
cfa_flatten_scalars(value_obj, "value", keys, kv);
}
- cfa_flatten_scalars(meta_obj, "metadata", keys, kv);
-
+ cfa_flatten_scalars(meta, "metadata", keys, kv);
if (!keys.isEmpty()) {
- auto* table = new QTableWidget(keys.size(), 2);
+ auto* table = new QTableWidget(keys.size(), 2, this);
table->setHorizontalHeaderLabels({"Metric", "Value"});
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
- table->setAlternatingRowColors(true);
- table->horizontalHeader()->setStretchLastSection(true);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
table->verticalHeader()->setVisible(false);
table->setMaximumHeight(qMin(keys.size() * 28 + 32, 480));
table->setStyleSheet(table_ss());
@@ -579,28 +1387,19 @@ void QuantModulePanel::display_cfa_result(const QString& command, const QJsonObj
vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
table->setItem(r, 1, vi);
}
- table->resizeColumnsToContents();
results_layout_->addWidget(table);
}
-
- // For forecasting the value is an array of forecast values — show inline
- if (value_raw.isArray()) {
- const auto arr = value_raw.toArray();
- QStringList parts;
- parts.reserve(arr.size());
- for (const auto& v : arr)
- parts << QString::number(v.toDouble(), 'f', 4);
- auto* fcst = new QLabel(QString("Forecast (%1 steps): %2").arg(arr.size()).arg(parts.join(", ")));
- fcst->setWordWrap(true);
- fcst->setStyleSheet(QString("color:%1; padding:6px 0;").arg(ui::colors::TEXT_PRIMARY()));
- results_layout_->addWidget(fcst);
- }
}
- // ── Raw JSON viewer ─────────────────────────────────────────────────────
+ // ── Raw JSON viewer (collapsed by default — capped height) ──────────────
+ auto* raw_hdr = new QLabel("RAW JSON");
+ raw_hdr->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; letter-spacing:1px; margin-top:4px;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ results_layout_->addWidget(raw_hdr);
+
auto* raw = new QTextEdit;
raw->setReadOnly(true);
- raw->setMaximumHeight(220);
+ raw->setMaximumHeight(180);
raw->setPlainText(QJsonDocument(payload).toJson(QJsonDocument::Indented));
raw->setStyleSheet(output_ss());
results_layout_->addWidget(raw);
@@ -633,7 +1432,8 @@ void QuantModulePanel::display_cfa_result(const QString& command, const QJsonObj
});
results_layout_->addWidget(export_btn);
- status_label_->setText("Done");
+ if (status_label_->text() == "Running...")
+ status_label_->setText("Done");
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
new file mode 100644
index 000000000..82fbd6065
--- /dev/null
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
@@ -0,0 +1,684 @@
+// src/screens/ai_quant_lab/QuantModulePanel_CoreDisplays.cpp
+//
+// Card-based result renderers for CORE-category panels that previously
+// rendered plain QLabel text into the bottom results pane.
+//
+// - factor_discovery — get_factor_library, get_data, get_instruments,
+// get_calendar
+// - model_library — list_models, check_status, train_model
+// - live_signals — get_data, get_factor_analysis,
+// get_feature_importance
+//
+// Skipped:
+// - backtesting — already has display_backtest_result (KPI grid in
+// QuantModulePanel_Backtesting.cpp). The dispatch in on_result still
+// routes there directly.
+#include "screens/ai_quant_lab/QuantModulePanel.h"
+#include "screens/ai_quant_lab/QuantModulePanel_Common.h"
+#include "screens/ai_quant_lab/QuantModulePanel_GsHelpers.h"
+#include "screens/ai_quant_lab/QuantModulePanel_Styles.h"
+
+#include "ui/theme/Theme.h"
+
+#include <QAbstractItemView>
+#include <QColor>
+#include <QHBoxLayout>
+#include <QHash>
+#include <QHeaderView>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QJsonValue>
+#include <QLabel>
+#include <QList>
+#include <QPair>
+#include <QString>
+#include <QStringList>
+#include <QTableWidget>
+#include <QTableWidgetItem>
+#include <QVBoxLayout>
+#include <QWidget>
+
+#include <algorithm>
+#include <cmath>
+#include <functional>
+#include <limits>
+
+namespace fincept::screens {
+
+using namespace fincept::services::quant;
+using namespace fincept::screens::quant_styles;
+using namespace fincept::screens::quant_common;
+using namespace fincept::screens::quant_gs_helpers;
+
+namespace {
+
+QString fmt_int_safe(const QJsonValue& v) {
+ if (v.isNull() || v.isUndefined()) return QStringLiteral("—");
+ return QString::number(v.toInt());
+}
+
+// Returns false if the payload was an error (already displayed via callback).
+bool check_success(const QJsonObject& payload,
+ const std::function<void(const QString&)>& display_error_fn) {
+ if (!payload.value("success").toBool(false)) {
+ const QString err = payload.value("error").toString("Unknown error");
+ const QString kind = payload.value("error_kind").toString();
+ const QString prefix = kind == "validation" ? "Input error: "
+ : kind == "runtime" ? "Computation failed: "
+ : "";
+ display_error_fn(prefix + err);
+ return false;
+ }
+ return true;
+}
+
+} // namespace
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 1. FACTOR DISCOVERY
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_factor_discovery_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ // ── get_data ─────────────────────────────────────────────────────────────
+ if (command == "get_data") {
+ const int total = payload.value("total_records").toInt();
+ const auto range = payload.value("date_range").toObject();
+ const auto instruments = payload.value("instruments").toArray();
+ const auto fields = payload.value("fields").toArray();
+ const QString freq = payload.value("freq").toString("day");
+ const QString warning = payload.value("warning").toString();
+
+ QList<QWidget*> top = {
+ gs_make_card("RECORDS", QString::number(total), this, ui::colors::POSITIVE()),
+ gs_make_card("INSTRUMENTS", QString::number(instruments.size()), this),
+ gs_make_card("FIELDS", QString::number(fields.size()), this),
+ gs_make_card("FREQUENCY", freq.toUpper(), this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> range_row = {
+ gs_make_card("START DATE", range.value("start").toString("—"), this),
+ gs_make_card("END DATE", range.value("end").toString("—"), this),
+ gs_make_card("WARNING", warning.isEmpty() ? "NONE" : "PRESENT", this,
+ warning.isEmpty() ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("STATUS", "OK", this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(range_row, this));
+
+ if (!warning.isEmpty()) {
+ auto* lbl = new QLabel("⚠ " + warning);
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-size:11px; padding:8px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), ui::colors::WARNING()));
+ results_layout_->addWidget(lbl);
+ }
+
+ // Instruments list (compact)
+ if (!instruments.isEmpty()) {
+ QStringList names;
+ for (const auto& v : instruments) names << v.toString();
+ const int show = std::min<int>(20, names.size());
+ QString text = "Instruments (" + QString::number(names.size()) + "): "
+ + names.mid(0, show).join(", ");
+ if (names.size() > show)
+ text += " … +" + QString::number(names.size() - show) + " more";
+ auto* lbl = new QLabel(text);
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:10px;"
+ "padding:6px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+
+ status_label_->setText(QString("%1 records %2→%3")
+ .arg(total).arg(range.value("start").toString())
+ .arg(range.value("end").toString()));
+ return;
+ }
+
+ // ── get_instruments ──────────────────────────────────────────────────────
+ if (command == "get_instruments") {
+ const auto instruments = payload.value("instruments").toArray();
+ const QString market = payload.value("market").toString();
+ const int count = payload.value("count").toInt(instruments.size());
+
+ QList<QWidget*> top = {
+ gs_make_card("MARKET", market.toUpper().isEmpty() ? "—" : market.toUpper(), this, ui::colors::INFO()),
+ gs_make_card("COUNT", QString::number(count), this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Table of instrument symbols
+ if (!instruments.isEmpty()) {
+ const int rows = instruments.size();
+ const int cols = 4;
+ const int table_rows = (rows + cols - 1) / cols;
+ auto* table = new QTableWidget(table_rows, cols, this);
+ table->setHorizontalHeaderLabels({"Symbol", "Symbol", "Symbol", "Symbol"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(table_rows * 22 + 32, 360));
+ for (int i = 0; i < instruments.size(); ++i) {
+ const int r = i / cols;
+ const int c = i % cols;
+ auto* it = new QTableWidgetItem(instruments[i].toString());
+ it->setTextAlignment(Qt::AlignCenter);
+ table->setItem(r, c, it);
+ if (c == 0) table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 instrument(s) market=%2").arg(count).arg(market));
+ return;
+ }
+
+ // ── get_calendar ─────────────────────────────────────────────────────────
+ if (command == "get_calendar") {
+ const auto dates = payload.value("dates").toArray();
+ const int count = payload.value("count").toInt(dates.size());
+ const QString freq = payload.value("freq").toString("day");
+
+ QList<QWidget*> top = {
+ gs_make_card("DATES", QString::number(count), this, ui::colors::POSITIVE()),
+ gs_make_card("FREQUENCY", freq.toUpper(), this, ui::colors::INFO()),
+ gs_make_card("FIRST",
+ dates.isEmpty() ? "—" : dates.first().toString(), this),
+ gs_make_card("LAST",
+ dates.isEmpty() ? "—" : dates.last().toString(), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ // Sample dates table
+ if (!dates.isEmpty()) {
+ const int rows = std::min<int>(15, dates.size());
+ const int step = std::max<int>(1, dates.size() / rows);
+ auto* table = new QTableWidget(rows, 2, this);
+ table->setHorizontalHeaderLabels({"Index", "Date"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(rows * 22 + 32);
+ for (int i = 0, r = 0; i < dates.size() && r < rows; i += step, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(QString::number(i)));
+ table->setItem(r, 1, new QTableWidgetItem(dates[i].toString()));
+ table->setRowHeight(r, 22);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 trading day(s)").arg(count));
+ return;
+ }
+
+ // ── get_factor_library (legacy shape — Python may not implement it) ──────
+ if (command == "get_factor_library") {
+ const auto factors = payload.value("factors").toArray();
+ QList<QWidget*> top = {
+ gs_make_card("FACTORS", QString::number(factors.size()), this,
+ factors.isEmpty() ? ui::colors::WARNING() : ui::colors::POSITIVE()),
+ gs_make_card("STATUS",
+ factors.isEmpty() ? "EMPTY" : "LOADED", this,
+ factors.isEmpty() ? ui::colors::WARNING() : ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!factors.isEmpty()) {
+ auto* table = new QTableWidget(factors.size(), 3, this);
+ table->setHorizontalHeaderLabels({"Name", "Category", "Expression"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(factors.size() * 26 + 32, 360));
+ for (int i = 0; i < factors.size(); ++i) {
+ const auto f = factors[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(f.value("name").toString()));
+ table->setItem(i, 1, new QTableWidgetItem(f.value("category").toString("—")));
+ table->setItem(i, 2, new QTableWidgetItem(f.value("expression").toString("—")));
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 factor(s)").arg(factors.size()));
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 2. MODEL LIBRARY
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_model_library_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ // ── list_models ──────────────────────────────────────────────────────────
+ if (command == "list_models") {
+ const auto models = payload.value("models").toArray();
+ const int total = payload.value("count").toInt(models.size());
+ const int avail = payload.value("available_count").toInt();
+ const auto types = payload.value("model_types").toObject();
+
+ QList<QWidget*> top = {
+ gs_make_card("TOTAL", QString::number(total), this, ui::colors::POSITIVE()),
+ gs_make_card("AVAILABLE", QString::number(avail), this,
+ avail > 0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("TYPES", QString::number(types.size()), this),
+ gs_make_card("UNAVAILABLE", QString::number(total - avail), this,
+ (total - avail) > 0 ? ui::colors::WARNING() : ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!types.isEmpty()) {
+ QList<QWidget*> type_cards;
+ for (auto it = types.begin(); it != types.end(); ++it) {
+ const auto arr = it.value().toArray();
+ QString lbl = it.key().toUpper();
+ lbl.replace('_', ' ');
+ type_cards << gs_make_card(lbl, QString::number(arr.size()), this, ui::colors::INFO());
+ if (type_cards.size() == 4) {
+ results_layout_->addWidget(gs_card_row(type_cards, this));
+ type_cards.clear();
+ }
+ }
+ // Pad and emit any remainder
+ while (!type_cards.isEmpty() && type_cards.size() < 4)
+ type_cards << gs_make_card(" ", " ", this);
+ if (!type_cards.isEmpty())
+ results_layout_->addWidget(gs_card_row(type_cards, this));
+ }
+
+ if (!models.isEmpty()) {
+ auto* table = new QTableWidget(models.size(), 4, this);
+ table->setHorizontalHeaderLabels({"ID", "Name", "Type", "Available"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(models.size() * 26 + 32, 360));
+ for (int i = 0; i < models.size(); ++i) {
+ const auto m = models[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(m.value("id").toString().toUpper()));
+ table->setItem(i, 1, new QTableWidgetItem(m.value("name").toString()));
+ QString t = m.value("type").toString();
+ t.replace('_', ' ');
+ table->setItem(i, 2, new QTableWidgetItem(t.toUpper()));
+ const bool ok = m.value("available").toBool();
+ auto* a = new QTableWidgetItem(ok ? "YES" : "NO");
+ a->setForeground(QColor(ok ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ a->setTextAlignment(Qt::AlignCenter);
+ table->setItem(i, 3, a);
+ table->setRowHeight(i, 26);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 model(s) %2 available").arg(total).arg(avail));
+ return;
+ }
+
+ // ── check_status ─────────────────────────────────────────────────────────
+ if (command == "check_status") {
+ const bool qlib = payload.value("qlib_available").toBool();
+ const QString version = payload.value("version").toString("—");
+ const auto avail = payload.value("models_available").toObject();
+ const auto handlers = payload.value("handlers_available").toArray();
+ const auto strategies = payload.value("strategies_available").toArray();
+
+ int n_avail = 0, n_unavail = 0;
+ for (auto it = avail.begin(); it != avail.end(); ++it)
+ (it.value().toBool() ? n_avail : n_unavail)++;
+
+ QList<QWidget*> top = {
+ gs_make_card("QLIB", qlib ? "READY" : "MISSING", this,
+ qlib ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ gs_make_card("VERSION", version, this, ui::colors::INFO()),
+ gs_make_card("HANDLERS", QString::number(handlers.size()), this),
+ gs_make_card("STRATEGIES", QString::number(strategies.size()), this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> models = {
+ gs_make_card("MODELS AVAIL", QString::number(n_avail), this,
+ n_avail > 0 ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("MODELS MISSING", QString::number(n_unavail), this,
+ n_unavail > 0 ? ui::colors::WARNING() : ui::colors::POSITIVE()),
+ gs_make_card("MODELS TOTAL", QString::number(avail.size()), this),
+ gs_make_card("STATUS",
+ qlib ? "OPERATIONAL" : "DEGRADED", this,
+ qlib ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(models, this));
+
+ // Models availability table
+ if (!avail.isEmpty()) {
+ auto* table = new QTableWidget(avail.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Model", "Status"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(avail.size() * 24 + 32, 320));
+ int r = 0;
+ for (auto it = avail.begin(); it != avail.end(); ++it, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(it.key().toUpper()));
+ const bool ok = it.value().toBool();
+ auto* st = new QTableWidgetItem(ok ? "AVAILABLE" : "MISSING");
+ st->setForeground(QColor(ok ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
+ st->setTextAlignment(Qt::AlignCenter);
+ table->setItem(r, 1, st);
+ table->setRowHeight(r, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+
+ if (!handlers.isEmpty()) {
+ QStringList lst;
+ for (const auto& v : handlers) lst << v.toString();
+ auto* lbl = new QLabel("Handlers: " + lst.join(", "));
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:10px;"
+ "padding:6px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+
+ status_label_->setText(qlib ? QString("Qlib %1 ready %2 model(s)").arg(version).arg(n_avail)
+ : "Qlib unavailable");
+ return;
+ }
+
+ // ── train_model ──────────────────────────────────────────────────────────
+ if (command == "train_model") {
+ const QString model_id = payload.value("model_id").toString();
+ const QString model_type = payload.value("model_type").toString();
+ const QString handler = payload.value("handler").toString();
+ const int n_pred = payload.value("predictions_count").toInt();
+ const auto config = payload.value("config").toObject();
+ const auto train = payload.value("training_period").toObject();
+ const auto val = payload.value("validation_period").toObject();
+ // Legacy shape: metrics dict
+ const auto metrics = payload.value("metrics").toObject();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL ID", model_id, this, ui::colors::POSITIVE()),
+ gs_make_card("TYPE", model_type.toUpper(), this),
+ gs_make_card("HANDLER", handler.isEmpty() ? "—" : handler, this, ui::colors::INFO()),
+ gs_make_card("PREDICTIONS", n_pred > 0 ? QString::number(n_pred) : "—", this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!train.isEmpty() || !val.isEmpty()) {
+ QList<QWidget*> periods = {
+ gs_make_card("TRAIN START", train.value("start").toString("—"), this),
+ gs_make_card("TRAIN END", train.value("end").toString("—"), this),
+ gs_make_card("VAL START", val.value("start").toString("—"), this),
+ gs_make_card("VAL END", val.value("end").toString("—"), this),
+ };
+ results_layout_->addWidget(gs_card_row(periods, this));
+ }
+
+ // Render metrics dict (legacy) if present
+ if (!metrics.isEmpty()) {
+ results_layout_->addWidget(gs_section_header("METRICS", accent));
+ QList<QWidget*> metric_cards;
+ int emitted = 0;
+ for (auto it = metrics.begin(); it != metrics.end(); ++it) {
+ const double v = it.value().toDouble();
+ QString lbl = it.key().toUpper();
+ lbl.replace('_', ' ');
+ metric_cards << gs_make_card(lbl, QString::number(v, 'f', 4), this, gs_pos_neg_color(v));
+ if (metric_cards.size() == 4) {
+ results_layout_->addWidget(gs_card_row(metric_cards, this));
+ metric_cards.clear();
+ emitted += 4;
+ }
+ }
+ while (!metric_cards.isEmpty() && metric_cards.size() < 4)
+ metric_cards << gs_make_card(" ", " ", this);
+ if (!metric_cards.isEmpty())
+ results_layout_->addWidget(gs_card_row(metric_cards, this));
+ }
+
+ // Render config dict
+ if (!config.isEmpty()) {
+ results_layout_->addWidget(gs_section_header("CONFIG", accent));
+ auto* table = new QTableWidget(config.size(), 2, this);
+ table->setHorizontalHeaderLabels({"Hyperparameter", "Value"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(config.size() * 24 + 32, 280));
+ int r = 0;
+ for (auto it = config.begin(); it != config.end(); ++it, ++r) {
+ table->setItem(r, 0, new QTableWidgetItem(it.key().toUpper()));
+ auto* vi = new QTableWidgetItem(format_val(it.value()));
+ vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table->setItem(r, 1, vi);
+ table->setRowHeight(r, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+
+ status_label_->setText(payload.value("message").toString(QString("Trained: %1").arg(model_id)));
+ return;
+ }
+
+ display_result(payload);
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// 3. LIVE SIGNALS
+// ═════════════════════════════════════════════════════════════════════════════
+void QuantModulePanel::display_live_signals_result(const QString& command, const QJsonObject& payload) {
+ clear_results();
+ if (!check_success(payload, [this](const QString& s) { display_error(s); }))
+ return;
+
+ const QString accent = module_.color.name();
+ QString header_text = command.toUpper();
+ header_text.replace('_', ' ');
+ results_layout_->addWidget(gs_section_header(header_text, accent));
+
+ // ── get_data (same shape as factor_discovery::get_data) ──────────────────
+ if (command == "get_data") {
+ const int total = payload.value("total_records").toInt();
+ const auto range = payload.value("date_range").toObject();
+ const auto instruments = payload.value("instruments").toArray();
+ const auto fields = payload.value("fields").toArray();
+ const QString freq = payload.value("freq").toString("day");
+ const QString warning = payload.value("warning").toString();
+
+ QList<QWidget*> top = {
+ gs_make_card("RECORDS", QString::number(total), this, ui::colors::POSITIVE()),
+ gs_make_card("INSTRUMENTS", QString::number(instruments.size()), this),
+ gs_make_card("FIELDS", QString::number(fields.size()), this),
+ gs_make_card("FREQUENCY", freq.toUpper(), this, ui::colors::INFO()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> range_row = {
+ gs_make_card("START DATE", range.value("start").toString("—"), this),
+ gs_make_card("END DATE", range.value("end").toString("—"), this),
+ gs_make_card("WARNING", warning.isEmpty() ? "NONE" : "PRESENT", this,
+ warning.isEmpty() ? ui::colors::POSITIVE() : ui::colors::WARNING()),
+ gs_make_card("STATUS", "OK", this, ui::colors::POSITIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(range_row, this));
+
+ if (!warning.isEmpty()) {
+ auto* lbl = new QLabel("⚠ " + warning);
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-size:11px; padding:8px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_PRIMARY(), ui::colors::BG_SURFACE(), ui::colors::WARNING()));
+ results_layout_->addWidget(lbl);
+ }
+
+ if (!instruments.isEmpty()) {
+ QStringList names;
+ for (const auto& v : instruments) names << v.toString();
+ const int show = std::min<int>(20, names.size());
+ QString text = "Instruments (" + QString::number(names.size()) + "): "
+ + names.mid(0, show).join(", ");
+ if (names.size() > show)
+ text += " … +" + QString::number(names.size() - show) + " more";
+ auto* lbl = new QLabel(text);
+ lbl->setWordWrap(true);
+ lbl->setStyleSheet(QString("color:%1; font-family:'Courier New'; font-size:10px;"
+ "padding:6px 10px; background:%2; border-left:3px solid %3;")
+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BG_SURFACE(), accent));
+ results_layout_->addWidget(lbl);
+ }
+ status_label_->setText(QString("%1 records %2→%3")
+ .arg(total).arg(range.value("start").toString())
+ .arg(range.value("end").toString()));
+ return;
+ }
+
+ // ── get_factor_analysis ──────────────────────────────────────────────────
+ if (command == "get_factor_analysis") {
+ const QString model_id = payload.value("model_id").toString();
+ const QString analysis = payload.value("analysis_type").toString();
+ const auto results = payload.value("results").toObject();
+
+ // Modern shape: results = {IC_mean, IC_std, ICIR, Rank_IC_mean, Rank_IC_std, Rank_ICIR}
+ if (!results.isEmpty()) {
+ const double ic_mean = results.value("IC_mean").toDouble();
+ const double icir = results.value("ICIR").toDouble();
+ const double rank_ic = results.value("Rank_IC_mean").toDouble();
+ const double rank_icir = results.value("Rank_ICIR").toDouble();
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", model_id.isEmpty() ? "—" : model_id, this),
+ gs_make_card("TYPE", analysis.toUpper().isEmpty() ? "—" : analysis.toUpper(), this, ui::colors::INFO()),
+ gs_make_card("IC MEAN", QString::number(ic_mean, 'f', 4), this, gs_pos_neg_color(ic_mean)),
+ gs_make_card("ICIR", QString::number(icir, 'f', 3), this,
+ icir >= 0.5 ? ui::colors::POSITIVE()
+ : icir > 0 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ QList<QWidget*> rank = {
+ gs_make_card("IC STD", QString::number(results.value("IC_std").toDouble(), 'f', 4), this),
+ gs_make_card("RANK IC MEAN", QString::number(rank_ic, 'f', 4), this, gs_pos_neg_color(rank_ic)),
+ gs_make_card("RANK IC STD", QString::number(results.value("Rank_IC_std").toDouble(), 'f', 4), this),
+ gs_make_card("RANK ICIR", QString::number(rank_icir, 'f', 3), this,
+ rank_icir >= 0.5 ? ui::colors::POSITIVE()
+ : rank_icir > 0 ? ui::colors::WARNING()
+ : ui::colors::NEGATIVE()),
+ };
+ results_layout_->addWidget(gs_card_row(rank, this));
+ status_label_->setText(QString("IC=%1 ICIR=%2 RankIC=%3")
+ .arg(ic_mean, 0, 'f', 4).arg(icir, 0, 'f', 3).arg(rank_ic, 0, 'f', 4));
+ return;
+ }
+
+ // Legacy shape: factors = [{name, ic, sharpe}]
+ const auto factors = payload.value("factors").toArray();
+ QList<QWidget*> top = {
+ gs_make_card("FACTORS", QString::number(factors.size()), this, ui::colors::POSITIVE()),
+ gs_make_card("MODEL", model_id.isEmpty() ? "—" : model_id, this),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!factors.isEmpty()) {
+ auto* table = new QTableWidget(factors.size(), 3, this);
+ table->setHorizontalHeaderLabels({"Factor", "IC", "Sharpe"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(factors.size() * 24 + 32, 320));
+ for (int i = 0; i < factors.size(); ++i) {
+ const auto f = factors[i].toObject();
+ table->setItem(i, 0, new QTableWidgetItem(f.value("name").toString("—")));
+ const QJsonValue ic = f.value("ic");
+ auto* ici = new QTableWidgetItem(ic.isNull() ? "N/A" : QString::number(ic.toDouble(), 'f', 4));
+ ici->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (!ic.isNull()) ici->setForeground(QColor(gs_pos_neg_color(ic.toDouble())));
+ table->setItem(i, 1, ici);
+ const QJsonValue sh = f.value("sharpe");
+ auto* shi = new QTableWidgetItem(sh.isNull() ? "N/A" : QString::number(sh.toDouble(), 'f', 3));
+ shi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ if (!sh.isNull()) shi->setForeground(QColor(gs_pos_neg_color(sh.toDouble())));
+ table->setItem(i, 2, shi);
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 factor(s)").arg(factors.size()));
+ return;
+ }
+
+ // ── get_feature_importance ───────────────────────────────────────────────
+ if (command == "get_feature_importance") {
+ const QString model_id = payload.value("model_id").toString();
+ const auto features = payload.value("feature_importance").toObject();
+
+ QList<QPair<QString, double>> sorted;
+ for (auto it = features.begin(); it != features.end(); ++it)
+ sorted.append({it.key(), it.value().toDouble()});
+ std::sort(sorted.begin(), sorted.end(),
+ [](const auto& a, const auto& b) { return std::abs(a.second) > std::abs(b.second); });
+
+ const double top_val = sorted.isEmpty() ? 0.0 : sorted.first().second;
+ const QString top_feat = sorted.isEmpty() ? "—" : sorted.first().first;
+
+ QList<QWidget*> top = {
+ gs_make_card("MODEL", model_id.isEmpty() ? "—" : model_id, this),
+ gs_make_card("FEATURES", QString::number(sorted.size()), this, ui::colors::POSITIVE()),
+ gs_make_card("TOP FEATURE", top_feat, this, ui::colors::INFO()),
+ gs_make_card("TOP IMPORTANCE", QString::number(top_val, 'f', 4), this,
+ gs_pos_neg_color(top_val)),
+ };
+ results_layout_->addWidget(gs_card_row(top, this));
+
+ if (!sorted.isEmpty()) {
+ auto* table = new QTableWidget(sorted.size(), 3, this);
+ table->setHorizontalHeaderLabels({"Rank", "Feature", "Importance"});
+ table->verticalHeader()->setVisible(false);
+ table->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
+ table->setStyleSheet(table_ss());
+ table->setMaximumHeight(qMin(sorted.size() * 24 + 32, 360));
+ for (int i = 0; i < sorted.size(); ++i) {
+ auto* r = new QTableWidgetItem(QString::number(i + 1));
+ r->setTextAlignment(Qt::AlignCenter);
+ if (i == 0) r->setForeground(QColor(ui::colors::POSITIVE()));
+ table->setItem(i, 0, r);
+ table->setItem(i, 1, new QTableWidgetItem(sorted[i].first));
+ const double v = sorted[i].second;
+ auto* vi = new QTableWidgetItem(QString::number(v, 'f', 6));
+ vi->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ vi->setForeground(QColor(gs_pos_neg_color(v)));
+ table->setItem(i, 2, vi);
+ table->setRowHeight(i, 24);
+ }
+ results_layout_->addWidget(table);
+ }
+ status_label_->setText(QString("%1 feature(s) top=%2").arg(sorted.size()).arg(top_feat));
+ return;
+ }
+
+ display_result(payload);
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp
index 5aef92fc7..edd7b3001 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Fortitudo.cpp
@@ -128,6 +128,7 @@ QWidget* QuantModulePanel::build_fortitudo_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Portfolio Metrics ────────────────────────────────────────────────────
auto* pm = new QWidget(this);
@@ -444,6 +445,7 @@ QWidget* QuantModulePanel::build_fortitudo_panel() {
results_layout_->setContentsMargins(0, 8, 0, 0);
results_layout_->setSpacing(8);
vl->addWidget(rc);
+ vl->addStretch();
return w;
}
@@ -850,7 +852,6 @@ void QuantModulePanel::display_fortitudo_result(const QString& command, const QJ
// ── 6. EXPONENTIAL DECAY PROBABILITIES ──────────────────────────────────
if (command == "exp_decay_probabilities") {
- const int n = d.value("n_scenarios").toInt();
const int hl = d.value("half_life").toInt();
const double ess = d.value("effective_sample_size").toDouble();
const double ess_pct = d.value("ess_pct_of_n").toDouble();
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Functime.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Functime.cpp
index d735b617c..4b6c5ad26 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Functime.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Functime.cpp
@@ -55,6 +55,7 @@ QWidget* QuantModulePanel::build_functime_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// Local sample-button helper — same shape as gs_quant's
auto add_sample_btn = [this](QLineEdit* edit, QWidget* parent, unsigned seed,
@@ -435,6 +436,7 @@ QWidget* QuantModulePanel::build_functime_panel() {
results_layout_->setContentsMargins(0, 8, 0, 0);
results_layout_->setSpacing(8);
vl->addWidget(rc);
+ vl->addStretch();
return w;
}
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GS.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GS.cpp
index 3b257d14f..112dba47d 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GS.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GS.cpp
@@ -55,6 +55,7 @@ QWidget* QuantModulePanel::build_gs_quant_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// Helper: small "load sample" link button next to a CSV input
auto add_sample_btn = [this](QLineEdit* edit, QWidget* parent, unsigned seed,
@@ -392,6 +393,7 @@ QWidget* QuantModulePanel::build_gs_quant_panel() {
results_layout_->setContentsMargins(0, 8, 0, 0);
results_layout_->setSpacing(8);
vl->addWidget(rc);
+ vl->addStretch();
return w;
}
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Gluonts.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Gluonts.cpp
index 4627f55e2..2d96efd5d 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Gluonts.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Gluonts.cpp
@@ -57,6 +57,7 @@ QWidget* QuantModulePanel::build_gluonts_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
auto add_sample_btn = [this](QLineEdit* edit, QWidget* parent, unsigned seed,
const QString& tip) -> QPushButton* {
@@ -445,6 +446,7 @@ QWidget* QuantModulePanel::build_gluonts_panel() {
results_layout_->setContentsMargins(0, 8, 0, 0);
results_layout_->setSpacing(8);
vl->addWidget(rc);
+ vl->addStretch();
return w;
}
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
index 3850084d0..cffb6e294 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Misc.cpp
@@ -140,6 +140,7 @@ QWidget* QuantModulePanel::build_feature_engineering_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Indicators tab ──
auto* ind = new QWidget(this);
@@ -271,6 +272,7 @@ QWidget* QuantModulePanel::build_portfolio_opt_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Shared covariance / returns helper ──
auto make_cov_tab = [&](const QString& method_id, const QString& btn_label, bool needs_returns) -> QWidget* {
@@ -407,6 +409,7 @@ QWidget* QuantModulePanel::build_factor_evaluation_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── IC Metrics tab ──
auto* ic = new QWidget(this);
@@ -541,6 +544,7 @@ QWidget* QuantModulePanel::build_strategy_builder_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── TopK-Dropout ──
auto* topk = new QWidget(this);
@@ -670,6 +674,7 @@ QWidget* QuantModulePanel::build_data_processors_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── List Processors ──
auto* list_tab = new QWidget(this);
@@ -767,6 +772,7 @@ QWidget* QuantModulePanel::build_factor_discovery_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Factor Library ──
auto* lib_tab = new QWidget(this);
@@ -890,6 +896,7 @@ QWidget* QuantModulePanel::build_model_library_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Model Browser ──
auto* browse_tab = new QWidget(this);
@@ -1026,6 +1033,7 @@ QWidget* QuantModulePanel::build_live_signals_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Signal Data ──
auto* sig_tab = new QWidget(this);
@@ -1153,6 +1161,7 @@ QWidget* QuantModulePanel::build_online_learning_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Models ──
auto* models_tab = new QWidget(this);
@@ -1293,6 +1302,7 @@ QWidget* QuantModulePanel::build_meta_learning_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// ── Model Selection ──
auto* sel_tab = new QWidget(this);
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_QuantReporting.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_QuantReporting.cpp
index 89f43fc7e..161cd3786 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_QuantReporting.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_QuantReporting.cpp
@@ -56,6 +56,7 @@ QWidget* QuantModulePanel::build_quant_reporting_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// Local LOAD SAMPLE helper — same shape as the other panels.
auto add_sample_btn = [this](QLineEdit* edit, QWidget* parent, unsigned seed,
@@ -398,13 +399,14 @@ QWidget* QuantModulePanel::build_quant_reporting_panel() {
fqvl->addStretch();
tabs->addTab(fq_tab, "Factor Quantiles");
- vl->addWidget(tabs, 1);
+ vl->addWidget(tabs);
auto* rc = new QWidget(w);
results_layout_ = new QVBoxLayout(rc);
results_layout_->setContentsMargins(0, 8, 0, 0);
results_layout_->setSpacing(8);
vl->addWidget(rc);
+ vl->addStretch();
return w;
}
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Statsmodels.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Statsmodels.cpp
index a8c9e8e7f..bd2467ba3 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Statsmodels.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Statsmodels.cpp
@@ -57,6 +57,7 @@ QWidget* QuantModulePanel::build_statsmodels_panel() {
auto* tabs = new QTabWidget(w);
tabs->setStyleSheet(tab_ss(module_.color.name()));
+ tabs->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
// Same LOAD SAMPLE helper shape as functime
auto add_sample_btn = [this](QLineEdit* edit, QWidget* parent, unsigned seed,
@@ -420,6 +421,7 @@ QWidget* QuantModulePanel::build_statsmodels_panel() {
results_layout_->setContentsMargins(0, 8, 0, 0);
results_layout_->setSpacing(8);
vl->addWidget(rc);
+ vl->addStretch();
return w;
}
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp
index b5ddf7069..2f9f768fb 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp
@@ -995,6 +995,82 @@ QWidget* BacktestingScreen::build_right_panel() {
cmd_config_stack_->addWidget(page);
}
+ // Page 9: labels_to_signals — converts ML labels into trading signals.
+ // Reuses the same horizon/threshold spinboxes from the labels page (they
+ // describe the underlying label generation) and only adds a label-type
+ // selector here.
+ {
+ auto* page = new QWidget(this);
+ auto* pl = new QVBoxLayout(page);
+ pl->setContentsMargins(0, 0, 0, 0);
+ pl->setSpacing(4);
+ auto* t = new QLabel("LABELS -> SIGNALS", page);
+ t->setStyleSheet(section_style);
+ pl->addWidget(t);
+
+ auto* tl = new QLabel("LABEL TYPE", page);
+ tl->setStyleSheet(label_style);
+ pl->addWidget(tl);
+ l2s_label_type_combo_ = new QComboBox(page);
+ l2s_label_type_combo_->setStyleSheet(combo_style);
+ for (const auto& lt : label_types())
+ l2s_label_type_combo_->addItem(lt);
+ pl->addWidget(l2s_label_type_combo_);
+
+ pl->addStretch();
+ cmd_config_stack_->addWidget(page);
+ }
+
+ // Page 10: indicator_sweep — runs an indicator across a parameter grid
+ // and returns aggregated stats per parameter value. Indicator combo is
+ // populated dynamically via on_result("get_indicators").
+ {
+ auto* page = new QWidget(this);
+ auto* pl = new QVBoxLayout(page);
+ pl->setContentsMargins(0, 0, 0, 0);
+ pl->setSpacing(4);
+ auto* t = new QLabel("INDICATOR SWEEP", page);
+ t->setStyleSheet(section_style);
+ pl->addWidget(t);
+
+ auto* il = new QLabel("INDICATOR", page);
+ il->setStyleSheet(label_style);
+ pl->addWidget(il);
+ sweep_indicator_combo_ = new QComboBox(page);
+ sweep_indicator_combo_->setStyleSheet(combo_style);
+ pl->addWidget(sweep_indicator_combo_);
+
+ auto* mnl = new QLabel("MIN", page);
+ mnl->setStyleSheet(label_style);
+ pl->addWidget(mnl);
+ sweep_min_spin_ = new QSpinBox(page);
+ sweep_min_spin_->setRange(1, 1000);
+ sweep_min_spin_->setValue(5);
+ sweep_min_spin_->setStyleSheet(input_style);
+ pl->addWidget(sweep_min_spin_);
+
+ auto* mxl = new QLabel("MAX", page);
+ mxl->setStyleSheet(label_style);
+ pl->addWidget(mxl);
+ sweep_max_spin_ = new QSpinBox(page);
+ sweep_max_spin_->setRange(1, 1000);
+ sweep_max_spin_->setValue(50);
+ sweep_max_spin_->setStyleSheet(input_style);
+ pl->addWidget(sweep_max_spin_);
+
+ auto* sl = new QLabel("STEP", page);
+ sl->setStyleSheet(label_style);
+ pl->addWidget(sl);
+ sweep_step_spin_ = new QSpinBox(page);
+ sweep_step_spin_->setRange(1, 100);
+ sweep_step_spin_->setValue(1);
+ sweep_step_spin_->setStyleSheet(input_style);
+ pl->addWidget(sweep_step_spin_);
+
+ pl->addStretch();
+ cmd_config_stack_->addWidget(page);
+ }
+
cmd_config_stack_->setCurrentIndex(0);
vl->addWidget(cmd_config_stack_);
@@ -1098,9 +1174,13 @@ void BacktestingScreen::on_command_changed(int index) {
active_command_ = index;
update_command_buttons();
- // Map command index to config stack page
+ // Map command index to config stack page. The page order in
+ // build_left_panel must match the command order in
+ // BacktestingTypes::all_commands() — adding a new command requires
+ // appending a matching cmd_config_stack_ page in the same position.
// commands: backtest(0), optimize(1), walk_forward(2), indicator(3),
- // indicator_signals(4), labels(5), splits(6), returns(7), signals(8)
+ // indicator_signals(4), labels(5), splits(6), returns(7),
+ // signals(8), labels_to_signals(9), indicator_sweep(10)
cmd_config_stack_->setCurrentIndex(index);
}
@@ -1321,6 +1401,26 @@ QJsonObject BacktestingScreen::gather_args() {
args["generatorType"] = signal_gen_combo_->currentText();
}
+ if (cmd_id == "labels_to_signals") {
+ // Wire the same horizon/threshold inputs the labels page uses — the
+ // Python pipeline first generates labels and then converts them to
+ // signals, so the upstream label config still applies.
+ args["labelType"] = l2s_label_type_combo_->currentText();
+ QJsonObject params;
+ params["horizon"] = labels_horizon_spin_->value();
+ params["threshold"] = labels_threshold_spin_->value();
+ args["params"] = params;
+ }
+
+ if (cmd_id == "indicator_sweep") {
+ args["indicator"] = sweep_indicator_combo_->currentData().toString();
+ QJsonObject range;
+ range["min"] = sweep_min_spin_->value();
+ range["max"] = sweep_max_spin_->value();
+ range["step"] = sweep_step_spin_->value();
+ args["paramRange"] = range;
+ }
+
return args;
}
@@ -1562,10 +1662,14 @@ void BacktestingScreen::on_result(const QString& provider, const QString& comman
if (command == "get_indicators") {
if (provider != providers_[active_provider_].slug)
return;
- // Populate both indicator combos from {indicators:{Cat:[{id,name}]}}
+ // Populate all three indicator combos from {indicators:{Cat:[{id,name}]}}.
+ // sweep_indicator_combo_ may be null if a future refactor strips the
+ // sweep page — guard so we don't crash older builds during migration.
auto ind_obj = payload.value("indicators").toObject();
indicator_combo_->clear();
ind_signal_indicator_combo_->clear();
+ if (sweep_indicator_combo_)
+ sweep_indicator_combo_->clear();
for (const auto& cat : ind_obj.keys()) {
for (const auto& iv : ind_obj.value(cat).toArray()) {
auto o = iv.toObject();
@@ -1573,6 +1677,8 @@ void BacktestingScreen::on_result(const QString& provider, const QString& comman
auto name = o.value("name").toString(id);
indicator_combo_->addItem(name, id);
ind_signal_indicator_combo_->addItem(name, id);
+ if (sweep_indicator_combo_)
+ sweep_indicator_combo_->addItem(name, id);
}
}
return;
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.h b/fincept-qt/src/screens/backtesting/BacktestingScreen.h
index b50ae8f66..18876ff79 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.h
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.h
@@ -139,6 +139,13 @@ class BacktestingScreen : public QWidget, public IStatefulScreen, public IGroupL
QSpinBox* returns_window_spin_ = nullptr;
// Signals config
QComboBox* signal_gen_combo_ = nullptr;
+ // Labels-to-signals config
+ QComboBox* l2s_label_type_combo_ = nullptr;
+ // Indicator sweep config
+ QComboBox* sweep_indicator_combo_ = nullptr;
+ QSpinBox* sweep_min_spin_ = nullptr;
+ QSpinBox* sweep_max_spin_ = nullptr;
+ QSpinBox* sweep_step_spin_ = nullptr;
// Center - results
QTabWidget* result_tabs_ = nullptr;
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
index b3204f5cb..76debe0d2 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
@@ -4,6 +4,7 @@
#include "screens/dashboard/canvas/DashboardTemplates.h"
#include "screens/dashboard/canvas/TemplatePicker.h"
#include "screens/dashboard/canvas/WidgetRegistry.h"
+#include "screens/dashboard/widgets/BaseWidget.h"
#include "services/markets/MarketDataService.h"
#include "services/notifications/NotificationService.h"
#include "storage/repositories/SettingsRepository.h"
@@ -145,6 +146,8 @@ DashboardScreen::DashboardScreen(QWidget* parent) : QWidget(parent) {
connect(toolbar_, &DashboardToolBar::save_layout_clicked, this, &DashboardScreen::save_layout);
+ connect(toolbar_, &DashboardToolBar::refresh_clicked, this, &DashboardScreen::on_refresh_clicked);
+
connect(toolbar_, &DashboardToolBar::toggle_compact_clicked, this, [this]() {
static bool compact = false;
compact = !compact;
@@ -235,6 +238,33 @@ void DashboardScreen::refresh_ticker() {
hub_resubscribe_ticker();
}
+void DashboardScreen::on_refresh_clicked() {
+ // Toolbar REFRESH button — force-refresh every live data source on the
+ // dashboard. The hub's per-producer rate limit is still honoured, so
+ // rage-clicking can't hammer upstream APIs.
+ if (ticker_bar_ && !ticker_subscribed_.isEmpty()) {
+ QStringList topics;
+ topics.reserve(ticker_subscribed_.size());
+ for (const QString& sym : ticker_subscribed_)
+ topics.append(QStringLiteral("market:quote:") + sym);
+ datahub::DataHub::instance().request(topics, /*force=*/true);
+ }
+ if (market_pulse_)
+ market_pulse_->refresh_data();
+ // Fan refresh out to every visible BaseWidget tile on the canvas.
+ // Hidden tiles (collapsed, off-screen, on a non-visible workspace) are
+ // skipped — refreshing them burns the producer's rate limit on data
+ // the user can't see, and the visibility-driven subscribe/unsubscribe
+ // (P3) means hidden widgets aren't subscribed anyway.
+ if (canvas_) {
+ const auto widgets = canvas_->findChildren<widgets::BaseWidget*>();
+ for (auto* w : widgets) {
+ if (w && w->isVisible())
+ w->request_refresh();
+ }
+ }
+}
+
void DashboardScreen::rebuild_ticker_from_cache() {
if (!ticker_bar_)
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.h b/fincept-qt/src/screens/dashboard/DashboardScreen.h
index a1351b779..771a0bc75 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.h
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.h
@@ -43,6 +43,7 @@ class DashboardScreen : public QWidget {
void save_layout();
void restore_layout();
void refresh_ticker();
+ void on_refresh_clicked();
void hub_resubscribe_ticker();
void hub_unsubscribe_ticker();
diff --git a/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp b/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
index f99151d95..4f8d7ce42 100644
--- a/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
@@ -5,13 +5,26 @@
#include "ui/widgets/NotifBell.h"
#include "ui/widgets/NotifPanel.h"
+#include <QApplication>
#include <QDateTime>
+#include <QFile>
#include <QHBoxLayout>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPalette>
#include <QUrl>
+#if defined(Q_OS_WIN)
+// windows.h must come first — psapi.h depends on its types (BOOL, WINAPI, …)
+// and including psapi.h alone yields C2146 / C2086 cascades.
+# include <windows.h>
+# include <psapi.h>
+#elif defined(Q_OS_MAC)
+# include <mach/mach.h>
+#elif defined(Q_OS_LINUX)
+# include <unistd.h>
+#endif
+
namespace {
void apply_solid_background(QWidget* widget, const QColor& color) {
@@ -54,7 +67,9 @@ DashboardStatusBar::DashboardStatusBar(QWidget* parent) : QWidget(parent) {
ll->setContentsMargins(0, 0, 0, 0);
ll->setSpacing(8);
- ll->addWidget(make_lbl("v4.0.0", "dsVersion"));
+ const QString version_text = QStringLiteral("v") + QApplication::applicationVersion();
+ version_label_ = make_lbl(version_text, "dsVersion");
+ ll->addWidget(version_label_);
ll->addWidget(make_sep());
const char* feed_names[] = {"EQ", "FX", "CM", "FI", "CR"};
@@ -93,7 +108,9 @@ DashboardStatusBar::DashboardStatusBar(QWidget* parent) : QWidget(parent) {
rl->setContentsMargins(0, 0, 0, 0);
rl->setSpacing(8);
- rl->addWidget(make_lbl("MEM: OPTIMAL", "dsMem"));
+ mem_label_ = new QLabel(QStringLiteral("MEM: ---"));
+ mem_label_->setObjectName("dsMem");
+ rl->addWidget(mem_label_);
rl->addWidget(make_sep());
latency_label_ = new QLabel("LAT: ---");
@@ -115,13 +132,18 @@ DashboardStatusBar::DashboardStatusBar(QWidget* parent) : QWidget(parent) {
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this](const ui::ThemeTokens&) { refresh_theme(); });
+ // P3: only set intervals + connect signals here. Timer.start() is
+ // deferred to showEvent so the status bar doesn't tick when the
+ // dashboard is hidden.
+ uptime_timer_.setInterval(1000);
connect(&uptime_timer_, &QTimer::timeout, this, &DashboardStatusBar::update_uptime);
- uptime_timer_.start(1000);
nam_ = new QNetworkAccessManager(this);
+ ping_timer_.setInterval(30000);
connect(&ping_timer_, &QTimer::timeout, this, &DashboardStatusBar::ping_api);
- ping_timer_.start(30000);
- ping_api();
+
+ mem_timer_.setInterval(5000); // 5s — memory probe is cheap; this is just a status hint
+ connect(&mem_timer_, &QTimer::timeout, this, &DashboardStatusBar::update_memory);
refresh_theme();
}
@@ -153,6 +175,24 @@ void DashboardStatusBar::refresh_theme() {
void DashboardStatusBar::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
refresh_theme();
+ // P3: start every owned QTimer here, stop in hideEvent.
+ if (!uptime_timer_.isActive())
+ uptime_timer_.start();
+ if (!ping_timer_.isActive())
+ ping_timer_.start();
+ if (!mem_timer_.isActive())
+ mem_timer_.start();
+ // Kick once immediately so the bar isn't blank on first show.
+ update_uptime();
+ update_memory();
+ ping_api();
+}
+
+void DashboardStatusBar::hideEvent(QHideEvent* event) {
+ QWidget::hideEvent(event);
+ uptime_timer_.stop();
+ ping_timer_.stop();
+ mem_timer_.stop();
}
void DashboardStatusBar::update_uptime() {
@@ -171,12 +211,50 @@ void DashboardStatusBar::set_widget_count(int count) {
}
void DashboardStatusBar::set_connected(bool connected) {
- connected_ = connected;
feeds_label_->setText(connected ? "CONNECTED" : "DISCONNECTED");
feeds_label_->setStyleSheet(QString("color:%1;font-weight:bold;background:transparent;")
.arg(connected ? ui::colors::POSITIVE() : ui::colors::NEGATIVE()));
}
+void DashboardStatusBar::update_memory() {
+ if (!mem_label_)
+ return;
+ double rss_mb = -1.0;
+#if defined(Q_OS_WIN)
+ PROCESS_MEMORY_COUNTERS_EX pmc{};
+ if (GetProcessMemoryInfo(GetCurrentProcess(),
+ reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc), sizeof(pmc))) {
+ rss_mb = static_cast<double>(pmc.WorkingSetSize) / (1024.0 * 1024.0);
+ }
+#elif defined(Q_OS_MAC)
+ mach_task_basic_info_data_t info{};
+ mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT;
+ if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO,
+ reinterpret_cast<task_info_t>(&info), &count) == KERN_SUCCESS) {
+ rss_mb = static_cast<double>(info.resident_size) / (1024.0 * 1024.0);
+ }
+#elif defined(Q_OS_LINUX)
+ QFile statm(QStringLiteral("/proc/self/statm"));
+ if (statm.open(QIODevice::ReadOnly)) {
+ const auto parts = QString::fromLatin1(statm.readLine()).split(QChar(' '), Qt::SkipEmptyParts);
+ if (parts.size() >= 2) {
+ const long page_kb = sysconf(_SC_PAGESIZE) / 1024;
+ rss_mb = parts[1].toDouble() * page_kb / 1024.0;
+ }
+ }
+#endif
+ if (rss_mb < 0) {
+ mem_label_->setText(QStringLiteral("MEM: ---"));
+ return;
+ }
+ // Colour: green < 512 MB, amber < 1024 MB, red beyond.
+ const QString color = rss_mb < 512.0 ? ui::colors::POSITIVE()
+ : rss_mb < 1024.0 ? ui::colors::AMBER()
+ : ui::colors::NEGATIVE();
+ mem_label_->setText(QStringLiteral("MEM: %1 MB").arg(rss_mb, 0, 'f', 0));
+ mem_label_->setStyleSheet(QString("color:%1;background:transparent;").arg(color));
+}
+
void DashboardStatusBar::ping_api() {
QNetworkRequest req(QUrl("https://api.fincept.in/health"));
req.setTransferTimeout(5000);
diff --git a/fincept-qt/src/screens/dashboard/DashboardStatusBar.h b/fincept-qt/src/screens/dashboard/DashboardStatusBar.h
index 39c607aac..7ee9c4dc5 100644
--- a/fincept-qt/src/screens/dashboard/DashboardStatusBar.h
+++ b/fincept-qt/src/screens/dashboard/DashboardStatusBar.h
@@ -1,5 +1,6 @@
#pragma once
#include <QElapsedTimer>
+#include <QHideEvent>
#include <QLabel>
#include <QNetworkAccessManager>
#include <QShowEvent>
@@ -27,29 +28,33 @@ class DashboardStatusBar : public QWidget {
protected:
void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private:
void refresh_theme();
void update_uptime();
+ void update_memory();
void ping_api();
void set_latency(int ms); // -1 = timeout/error
void toggle_notif_panel();
+ QLabel* version_label_ = nullptr;
QLabel* uptime_label_ = nullptr;
QLabel* layout_label_ = nullptr;
QLabel* feeds_label_ = nullptr;
QLabel* latency_label_ = nullptr;
+ QLabel* mem_label_ = nullptr;
fincept::ui::NotifBell* notif_bell_ = nullptr;
fincept::ui::NotifPanel* notif_panel_ = nullptr;
QTimer uptime_timer_;
QTimer ping_timer_;
+ QTimer mem_timer_;
QNetworkAccessManager* nam_ = nullptr;
QElapsedTimer ping_elapsed_;
qint64 start_time_ = 0;
- bool connected_ = true;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp b/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp
index 8f4308736..2fb08c727 100644
--- a/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardToolBar.cpp
@@ -100,6 +100,13 @@ DashboardToolBar::DashboardToolBar(QWidget* parent) : QWidget(parent) {
make_sep(rl);
+ auto* refresh_btn = new QPushButton("REFRESH");
+ refresh_btn->setFixedHeight(20);
+ refresh_btn->setObjectName("dtBtn");
+ refresh_btn->setToolTip(QStringLiteral("Force-refresh all live data on the dashboard"));
+ connect(refresh_btn, &QPushButton::clicked, this, &DashboardToolBar::refresh_clicked);
+ rl->addWidget(refresh_btn);
+
auto* add_btn = new QPushButton("+ ADD");
add_btn->setFixedHeight(20);
add_btn->setObjectName("dtAddBtn");
@@ -123,12 +130,19 @@ DashboardToolBar::DashboardToolBar(QWidget* parent) : QWidget(parent) {
connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
[this](const ui::ThemeTokens&) { refresh_theme(); });
+ // P3: timer interval is set here, but start() is deferred to showEvent()
+ // so the toolbar doesn't tick when the dashboard tab isn't visible.
+ clock_timer_.setInterval(1000);
connect(&clock_timer_, &QTimer::timeout, this, &DashboardToolBar::update_clock);
- clock_timer_.start(1000);
refresh_theme();
}
+void DashboardToolBar::hideEvent(QHideEvent* event) {
+ QWidget::hideEvent(event);
+ clock_timer_.stop();
+}
+
void DashboardToolBar::refresh_theme() {
const QColor surface(ui::colors::BG_SURFACE());
apply_solid_background(this, surface);
@@ -181,6 +195,9 @@ void DashboardToolBar::refresh_theme() {
void DashboardToolBar::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
refresh_theme();
+ update_clock();
+ if (!clock_timer_.isActive())
+ clock_timer_.start();
}
void DashboardToolBar::update_clock() {
@@ -192,7 +209,6 @@ void DashboardToolBar::set_widget_count(int count) {
}
void DashboardToolBar::set_connected(bool connected) {
- connected_ = connected;
status_text_->setText(connected ? "LIVE" : "OFFLINE");
// refresh_theme handles the base color; override just this label dynamically
status_text_->setStyleSheet(QString("color:%1;font-weight:bold;background:transparent;")
diff --git a/fincept-qt/src/screens/dashboard/DashboardToolBar.h b/fincept-qt/src/screens/dashboard/DashboardToolBar.h
index 4a259387b..926e031cb 100644
--- a/fincept-qt/src/screens/dashboard/DashboardToolBar.h
+++ b/fincept-qt/src/screens/dashboard/DashboardToolBar.h
@@ -1,5 +1,6 @@
#pragma once
#include <QDateTime>
+#include <QHideEvent>
#include <QLabel>
#include <QPushButton>
#include <QShowEvent>
@@ -21,11 +22,13 @@ class DashboardToolBar : public QWidget {
void add_widget_clicked();
void save_layout_clicked();
void reset_layout_clicked();
+ void refresh_clicked();
void toggle_pulse_clicked();
void toggle_compact_clicked();
protected:
void showEvent(QShowEvent* event) override;
+ void hideEvent(QHideEvent* event) override;
private:
void update_clock();
@@ -39,8 +42,6 @@ class DashboardToolBar : public QWidget {
QPushButton* pulse_btn_ = nullptr;
QPushButton* compact_btn_ = nullptr;
QTimer clock_timer_;
- bool connected_ = true;
- bool pulse_visible_ = true;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/dashboard/MarketPulsePanel.h b/fincept-qt/src/screens/dashboard/MarketPulsePanel.h
index a1e24f77a..6f62993ff 100644
--- a/fincept-qt/src/screens/dashboard/MarketPulsePanel.h
+++ b/fincept-qt/src/screens/dashboard/MarketPulsePanel.h
@@ -30,8 +30,12 @@ class MarketPulsePanel : public QWidget {
void showEvent(QShowEvent* e) override;
void hideEvent(QHideEvent* e) override;
- private slots:
+ public slots:
+ /// Public so the Dashboard REFRESH button can drive it directly. The
+ /// internal timer also wires to this slot.
void refresh_data();
+
+ private slots:
void refresh_market_hours();
private:
diff --git a/fincept-qt/src/screens/dashboard/WidgetGrid.cpp b/fincept-qt/src/screens/dashboard/WidgetGrid.cpp
deleted file mode 100644
index 6015bf351..000000000
--- a/fincept-qt/src/screens/dashboard/WidgetGrid.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-#include "screens/dashboard/WidgetGrid.h"
-
-#include "screens/dashboard/widgets/CommoditiesWidget.h"
-#include "screens/dashboard/widgets/CryptoWidget.h"
-#include "screens/dashboard/widgets/EconomicCalendarWidget.h"
-#include "screens/dashboard/widgets/ForexWidget.h"
-#include "screens/dashboard/widgets/IndicesWidget.h"
-#include "screens/dashboard/widgets/MarketSentimentWidget.h"
-#include "screens/dashboard/widgets/NewsWidget.h"
-#include "screens/dashboard/widgets/PerformanceWidget.h"
-#include "screens/dashboard/widgets/PortfolioSummaryWidget.h"
-#include "screens/dashboard/widgets/QuickTradeWidget.h"
-#include "screens/dashboard/widgets/RiskMetricsWidget.h"
-#include "screens/dashboard/widgets/ScreenerWidget.h"
-#include "screens/dashboard/widgets/SectorHeatmapWidget.h"
-#include "screens/dashboard/widgets/StockQuoteWidget.h"
-#include "screens/dashboard/widgets/TopMoversWidget.h"
-#include "screens/dashboard/widgets/WatchlistWidget.h"
-#include "ui/theme/Theme.h"
-#include "ui/theme/ThemeManager.h"
-
-namespace fincept::screens {
-
-WidgetGrid::WidgetGrid(QWidget* parent) : QWidget(parent) {
- auto* scroll = new QScrollArea;
- scroll->setWidgetResizable(true);
- scroll->setStyleSheet(QString("QScrollArea{border:none;background:transparent;}"
- "QScrollBar:vertical{width:6px;background:transparent;}"
- "QScrollBar::handle:vertical{background:%1;border-radius:3px;min-height:20px;}"
- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical{height:0;}")
- .arg(ui::colors::BORDER_MED()));
-
- setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this,
- [this](const ui::ThemeTokens&) { setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE())); });
-
- auto* content = new QWidget(this);
- grid_ = new QGridLayout(content);
- grid_->setContentsMargins(4, 4, 4, 4);
- grid_->setSpacing(4);
-
- // Row 0: Indices | Sector Heatmap | Top Movers
- auto* indices = widgets::create_indices_widget();
- auto* heatmap = new widgets::SectorHeatmapWidget;
- auto* movers = new widgets::TopMoversWidget;
-
- grid_->addWidget(indices, 0, 0);
- grid_->addWidget(heatmap, 0, 1);
- grid_->addWidget(movers, 0, 2);
- widget_count_ += 3;
-
- // Row 1: Forex | Commodities | Crypto
- auto* forex = widgets::create_forex_widget();
- auto* commodities = widgets::create_commodities_widget();
- auto* crypto = widgets::create_crypto_widget();
-
- grid_->addWidget(forex, 1, 0);
- grid_->addWidget(commodities, 1, 1);
- grid_->addWidget(crypto, 1, 2);
- widget_count_ += 3;
-
- // Row 2: News | Performance | Market Sentiment
- auto* news = new widgets::NewsWidget;
- auto* perf = new widgets::PerformanceWidget;
- auto* sentiment = new widgets::MarketSentimentWidget;
-
- grid_->addWidget(news, 2, 0);
- grid_->addWidget(perf, 2, 1);
- grid_->addWidget(sentiment, 2, 2);
- widget_count_ += 3;
-
- // Row 3: Stock Quote | Watchlist
- auto* quote = new widgets::StockQuoteWidget("AAPL");
- auto* watchlist = new widgets::WatchlistWidget;
-
- grid_->addWidget(quote, 3, 0);
- grid_->addWidget(watchlist, 3, 1, 1, 2); // span 2 columns
- widget_count_ += 2;
-
- // Row 4: Economic Calendar | Screener | Risk Metrics
- auto* econ_cal = new widgets::EconomicCalendarWidget;
- auto* screener = new widgets::ScreenerWidget;
- auto* risk = new widgets::RiskMetricsWidget;
-
- grid_->addWidget(econ_cal, 4, 0);
- grid_->addWidget(screener, 4, 1);
- grid_->addWidget(risk, 4, 2);
- widget_count_ += 3;
-
- // Row 5: Portfolio Summary | Quick Trade (spans 2 cols)
- auto* portfolio = new widgets::PortfolioSummaryWidget;
- auto* quick_trade = new widgets::QuickTradeWidget;
-
- grid_->addWidget(portfolio, 5, 0);
- grid_->addWidget(quick_trade, 5, 1, 1, 2); // span 2 columns
- widget_count_ += 2;
-
- grid_->setColumnStretch(0, 1);
- grid_->setColumnStretch(1, 1);
- grid_->setColumnStretch(2, 1);
-
- scroll->setWidget(content);
-
- auto* main_layout = new QVBoxLayout(this);
- main_layout->setContentsMargins(0, 0, 0, 0);
- main_layout->addWidget(scroll);
-}
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/dashboard/WidgetGrid.h b/fincept-qt/src/screens/dashboard/WidgetGrid.h
deleted file mode 100644
index a3fa795fc..000000000
--- a/fincept-qt/src/screens/dashboard/WidgetGrid.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#pragma once
-#include <QGridLayout>
-#include <QScrollArea>
-#include <QWidget>
-
-namespace fincept::screens {
-
-/// Main dashboard grid — 9 default widget cards using individual widget classes.
-/// All widgets source real data from yfinance via MarketDataService.
-class WidgetGrid : public QWidget {
- Q_OBJECT
- public:
- explicit WidgetGrid(QWidget* parent = nullptr);
-
- int widget_count() const { return widget_count_; }
-
- private:
- QGridLayout* grid_ = nullptr;
- int widget_count_ = 0;
-};
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
index 968c1fa02..d46014e78 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/BaseWidget.h
@@ -31,6 +31,11 @@ class BaseWidget : public QFrame {
void set_error(const QString& error);
void set_title(const QString& title);
+ /// External-trigger entry point — emits `refresh_requested` so the
+ /// widget runs the same refresh path as a user clicking the title-bar
+ /// refresh button. Used by the dashboard "REFRESH ALL" toolbar button.
+ void request_refresh() { emit refresh_requested(); }
+
/// Current per-instance config. Default: empty — subclasses override to
/// return their live state (symbol, broker id, filters, etc.).
virtual QJsonObject config() const { return {}; }
diff --git a/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp
index 409b0fa64..063f40240 100644
--- a/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.cpp
@@ -1,12 +1,16 @@
#include "screens/dashboard/widgets/EconomicCalendarWidget.h"
-#include "network/http/HttpClient.h"
+#include "datahub/DataHub.h"
#include "ui/theme/Theme.h"
#include <QFrame>
#include <QHBoxLayout>
#include <QJsonObject>
+namespace {
+constexpr const char* kTopic = "econ:fincept:upcoming_events";
+} // namespace
+
namespace fincept::screens::widgets {
EconomicCalendarWidget::EconomicCalendarWidget(QWidget* parent)
@@ -56,11 +60,15 @@ EconomicCalendarWidget::EconomicCalendarWidget(QWidget* parent)
scroll_area_->setWidget(list_widget);
vl->addWidget(scroll_area_, 1);
- connect(this, &BaseWidget::refresh_requested, this, &EconomicCalendarWidget::refresh_data);
+ // User-driven refresh button on the BaseWidget title bar — force the
+ // hub to refresh the topic. Per-producer rate limit (2/sec) still
+ // applies, so rage-clicking can't hammer api.fincept.in.
+ connect(this, &BaseWidget::refresh_requested, this, []() {
+ datahub::DataHub::instance().request(QString::fromLatin1(kTopic), /*force=*/true);
+ });
apply_styles();
set_loading(true);
- refresh_data();
}
void EconomicCalendarWidget::apply_styles() {
@@ -85,50 +93,61 @@ void EconomicCalendarWidget::on_theme_changed() {
populate(last_events_);
}
-void EconomicCalendarWidget::refresh_data() {
- set_loading(true);
+void EconomicCalendarWidget::showEvent(QShowEvent* e) {
+ BaseWidget::showEvent(e);
+ if (!hub_active_)
+ hub_subscribe();
+}
- // Response shape: {"success":true,"data":{"events":[...],"total_count":N,...}}
- QString url = "https://api.fincept.in/macro/upcoming-events?limit=25";
+void EconomicCalendarWidget::hideEvent(QHideEvent* e) {
+ BaseWidget::hideEvent(e);
+ if (hub_active_)
+ hub_unsubscribe();
+}
- fincept::HttpClient::instance().get(url, [this](fincept::Result<QJsonDocument> result) {
+void EconomicCalendarWidget::hub_subscribe() {
+ auto& hub = datahub::DataHub::instance();
+ hub.subscribe(this, QString::fromLatin1(kTopic), [this](const QVariant& v) {
set_loading(false);
- if (!result.is_ok()) {
- status_label_->setVisible(true);
- status_label_->setText("Failed to load calendar");
- return;
- }
-
- auto doc = result.value();
QJsonArray events;
-
- if (doc.isObject()) {
- auto root = doc.object();
- // {"success":true,"data":{"events":[...]}}
- if (root.contains("data") && root["data"].isObject()) {
- auto data = root["data"].toObject();
- if (data.contains("events") && data["events"].isArray())
- events = data["events"].toArray();
- }
- // fallback: {"data":[...]}
- if (events.isEmpty() && root.contains("data") && root["data"].isArray())
- events = root["data"].toArray();
- // fallback: {"events":[...]}
- if (events.isEmpty() && root.contains("events") && root["events"].isArray())
- events = root["events"].toArray();
- } else if (doc.isArray()) {
- events = doc.array();
- }
-
+ if (v.canConvert<QJsonArray>())
+ events = v.value<QJsonArray>();
if (events.isEmpty()) {
status_label_->setVisible(true);
- status_label_->setText("No events available");
+ status_label_->setText(QStringLiteral("No events available"));
return;
}
-
status_label_->setVisible(false);
populate(events);
});
+ // Per-topic error subscription — fires only when *our* topic errors,
+ // unlike the global topic_error signal which fans every error to every
+ // listener. Keeps the widget out of the global error broadcast path.
+ hub.subscribe_errors(this, QString::fromLatin1(kTopic),
+ [this](const QString& /*error*/) {
+ set_loading(false);
+ status_label_->setVisible(true);
+ status_label_->setText(QStringLiteral("Failed to load calendar"));
+ });
+ hub_active_ = true;
+ // Cold-cache fallback: if the producer warmed the topic earlier, paint
+ // it now even if it's slightly stale — beats a blank panel.
+ QVariant cached = hub.peek_raw(QString::fromLatin1(kTopic));
+ if (cached.canConvert<QJsonArray>()) {
+ const auto events = cached.value<QJsonArray>();
+ if (!events.isEmpty()) {
+ set_loading(false);
+ status_label_->setVisible(false);
+ populate(events);
+ }
+ }
+}
+
+void EconomicCalendarWidget::hub_unsubscribe() {
+ auto& hub = datahub::DataHub::instance();
+ hub.unsubscribe(this, QString::fromLatin1(kTopic));
+ hub.unsubscribe_errors(this, QString::fromLatin1(kTopic));
+ hub_active_ = false;
}
void EconomicCalendarWidget::populate(const QJsonArray& events) {
diff --git a/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.h b/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.h
index 322d2307b..356bab986 100644
--- a/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/EconomicCalendarWidget.h
@@ -1,15 +1,18 @@
#pragma once
#include "screens/dashboard/widgets/BaseWidget.h"
+#include <QHideEvent>
#include <QJsonArray>
#include <QLabel>
#include <QScrollArea>
+#include <QShowEvent>
#include <QVBoxLayout>
namespace fincept::screens::widgets {
-/// Economic Calendar Widget — fetches real macro events from
-/// GET http://api.fincept.in/macro/upcoming-events via HttpClient.
+/// Economic Calendar Widget — consumes the DataHub topic
+/// `econ:fincept:upcoming_events` (HTTP-backed by `MacroCalendarService`).
+/// All cadence is owned by the hub scheduler.
class EconomicCalendarWidget : public BaseWidget {
Q_OBJECT
public:
@@ -17,10 +20,13 @@ class EconomicCalendarWidget : public BaseWidget {
protected:
void on_theme_changed() override;
+ void showEvent(QShowEvent* e) override;
+ void hideEvent(QHideEvent* e) override;
private:
void apply_styles();
- void refresh_data();
+ void hub_subscribe();
+ void hub_unsubscribe();
void populate(const QJsonArray& events);
QWidget* header_widget_ = nullptr;
@@ -30,6 +36,7 @@ class EconomicCalendarWidget : public BaseWidget {
QLabel* status_label_ = nullptr;
QVector<QLabel*> header_labels_;
QJsonArray last_events_; // cached for theme-change re-populate
+ bool hub_active_ = false;
};
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp
index ec6b689df..8815a1856 100644
--- a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.cpp
@@ -1,14 +1,19 @@
#include "screens/dashboard/widgets/NewsWidget.h"
-#include "services/markets/MarketDataService.h"
+#include "datahub/DataHub.h"
+#include "datahub/DataHubMetaTypes.h"
#include "ui/theme/Theme.h"
-#include <QJsonArray>
-#include <QJsonObject>
+#include <QDateTime>
#include <QLabel>
namespace fincept::screens::widgets {
+namespace {
+constexpr const char* kTopic = "news:general";
+constexpr int kMaxArticles = 30; // headline cap; NewsService publishes the full feed
+} // namespace
+
NewsWidget::NewsWidget(QWidget* parent) : BaseWidget("MARKET NEWS", parent, ui::colors::CYAN) {
scroll_area_ = new QScrollArea;
scroll_area_->setWidgetResizable(true);
@@ -22,11 +27,14 @@ NewsWidget::NewsWidget(QWidget* parent) : BaseWidget("MARKET NEWS", parent, ui::
scroll_area_->setWidget(container);
content_layout()->addWidget(scroll_area_);
- connect(this, &BaseWidget::refresh_requested, this, &NewsWidget::refresh_data);
+ // Refresh button on the title bar — force-refresh through the hub.
+ // Per-producer rate limit still applies, so this can't hammer upstream.
+ connect(this, &BaseWidget::refresh_requested, this, []() {
+ datahub::DataHub::instance().request(QString::fromLatin1(kTopic), /*force=*/true);
+ });
apply_styles();
set_loading(true);
- refresh_data();
}
void NewsWidget::apply_styles() {
@@ -43,23 +51,45 @@ void NewsWidget::on_theme_changed() {
populate(last_articles_);
}
-void NewsWidget::refresh_data() {
- set_loading(true);
+void NewsWidget::showEvent(QShowEvent* e) {
+ BaseWidget::showEvent(e);
+ if (!hub_active_)
+ hub_subscribe();
+}
- // Fetch news for SPY (broad market news)
- services::MarketDataService::instance().fetch_news("SPY", 10, [this](bool ok, QJsonArray articles) {
- set_loading(false);
- if (!ok || articles.isEmpty()) {
- if (news_layout_->count() <= 1) {
- set_error("No news available. Check Python/yfinance.");
- }
+void NewsWidget::hideEvent(QHideEvent* e) {
+ BaseWidget::hideEvent(e);
+ if (hub_active_)
+ hub_unsubscribe();
+}
+
+void NewsWidget::hub_subscribe() {
+ auto& hub = datahub::DataHub::instance();
+ hub.subscribe(this, QString::fromLatin1(kTopic), [this](const QVariant& v) {
+ if (!v.canConvert<QVector<services::NewsArticle>>())
return;
- }
- populate(articles);
+ set_loading(false);
+ populate(v.value<QVector<services::NewsArticle>>());
});
+ hub_active_ = true;
+ // Cold-start cache fallback: if the hub already has a cached value
+ // (from a producer warm-up before this widget was mounted), surface it
+ // immediately. The subscribe path above also delivers it, but only if
+ // the value is still fresh; peek_raw() guarantees we render even on a
+ // stale-but-present cache so the panel never sits blank.
+ QVariant cached = hub.peek_raw(QString::fromLatin1(kTopic));
+ if (cached.canConvert<QVector<services::NewsArticle>>()) {
+ set_loading(false);
+ populate(cached.value<QVector<services::NewsArticle>>());
+ }
}
-void NewsWidget::populate(const QJsonArray& articles) {
+void NewsWidget::hub_unsubscribe() {
+ datahub::DataHub::instance().unsubscribe(this);
+ hub_active_ = false;
+}
+
+void NewsWidget::populate(const QVector<services::NewsArticle>& articles) {
last_articles_ = articles;
// Clear old items (keep the stretch)
@@ -70,19 +100,27 @@ void NewsWidget::populate(const QJsonArray& articles) {
delete item;
}
- for (const auto& val : articles) {
- auto obj = val.toObject();
- QString title = obj["title"].toString();
- QString publisher = obj["publisher"].toString();
- QString pub_date = obj["published_date"].toString();
+ if (articles.isEmpty()) {
+ auto* empty = new QLabel(QStringLiteral("No news available."));
+ empty->setAlignment(Qt::AlignCenter);
+ empty->setStyleSheet(QString("color: %1; font-size: 11px; padding: 12px; background: transparent;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ news_layout_->insertWidget(0, empty);
+ return;
+ }
- if (title.isEmpty())
+ int rendered = 0;
+ for (const auto& article : articles) {
+ if (rendered >= kMaxArticles)
+ break;
+ if (article.headline.isEmpty())
continue;
- // Extract time portion from date
- QString time_str;
- if (pub_date.length() >= 16) {
- time_str = pub_date.mid(11, 5); // "HH:MM"
+ // Time column: prefer NewsArticle.time, fall back to derived HH:MM
+ // from sort_ts (unix seconds) if `time` is missing.
+ QString time_str = article.time.left(5);
+ if (time_str.isEmpty() && article.sort_ts > 0) {
+ time_str = QDateTime::fromSecsSinceEpoch(article.sort_ts).toString(QStringLiteral("HH:mm"));
}
auto* row = new QWidget(this);
@@ -99,14 +137,14 @@ void NewsWidget::populate(const QJsonArray& articles) {
rl->addWidget(time_lbl);
}
- auto* headline = new QLabel(title);
+ auto* headline = new QLabel(article.headline);
headline->setWordWrap(true);
headline->setStyleSheet(
QString("color: %1; font-size: 11px; background: transparent;").arg(ui::colors::TEXT_PRIMARY()));
rl->addWidget(headline, 1);
- if (!publisher.isEmpty()) {
- auto* src = new QLabel(publisher);
+ if (!article.source.isEmpty()) {
+ auto* src = new QLabel(article.source);
src->setStyleSheet(
QString("color: %1; font-size: 9px; background: transparent;").arg(ui::colors::TEXT_TERTIARY()));
rl->addWidget(src);
@@ -114,6 +152,7 @@ void NewsWidget::populate(const QJsonArray& articles) {
// Insert before the stretch
news_layout_->insertWidget(news_layout_->count() - 1, row);
+ ++rendered;
}
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.h b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.h
index 783cefdaf..f1b527858 100644
--- a/fincept-qt/src/screens/dashboard/widgets/NewsWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/NewsWidget.h
@@ -1,12 +1,17 @@
#pragma once
#include "screens/dashboard/widgets/BaseWidget.h"
+#include "services/news/NewsService.h"
-#include <QJsonArray>
+#include <QHideEvent>
#include <QScrollArea>
+#include <QShowEvent>
+#include <QVector>
namespace fincept::screens::widgets {
-/// Market news widget — fetches real news via yfinance for major tickers.
+/// Market news widget — consumes the DataHub `news:general` topic
+/// (RSS-driven via `NewsService`). All fetch cadence is owned by the hub
+/// scheduler; this widget only subscribes/unsubscribes on visibility.
class NewsWidget : public BaseWidget {
Q_OBJECT
public:
@@ -14,15 +19,19 @@ class NewsWidget : public BaseWidget {
protected:
void on_theme_changed() override;
+ void showEvent(QShowEvent* e) override;
+ void hideEvent(QHideEvent* e) override;
private:
void apply_styles();
- void refresh_data();
- void populate(const QJsonArray& articles);
+ void hub_subscribe();
+ void hub_unsubscribe();
+ void populate(const QVector<services::NewsArticle>& articles);
QScrollArea* scroll_area_ = nullptr;
QVBoxLayout* news_layout_ = nullptr;
- QJsonArray last_articles_; // cached for theme-change re-populate
+ QVector<services::NewsArticle> last_articles_; // cached for theme-change re-populate
+ bool hub_active_ = false;
};
} // namespace fincept::screens::widgets
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
index 694ff8704..4c3a5df4e 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
@@ -12,11 +12,11 @@
namespace fincept::screens::widgets {
-// Demo holdings if no DB portfolio exists
-static const QVector<PortfolioSummaryWidget::Holding> kDemoHoldings = {
- {"AAPL", 10.0, 178.50}, {"MSFT", 5.0, 415.00}, {"NVDA", 8.0, 880.00},
- {"GOOGL", 3.0, 165.00}, {"TSLA", 6.0, 210.00}, {"SPY", 12.0, 520.00},
-};
+// Empty-state placeholder used when portfolio_holdings is empty. Previously
+// this fell back to a hardcoded `{AAPL, MSFT, NVDA, GOOGL, TSLA, SPY}` list,
+// which looked indistinguishable from a real portfolio — confusing for users
+// who'd just connected a broker. We now render a clear empty-state banner
+// instead so there's no ambiguity about what data they're looking at.
PortfolioSummaryWidget::PortfolioSummaryWidget(QWidget* parent)
: BaseWidget("PORTFOLIO SUMMARY", parent, ui::colors::POSITIVE) {
@@ -141,9 +141,32 @@ void PortfolioSummaryWidget::load_holdings() {
}
}
- // Fall back to demo portfolio
if (holdings.isEmpty()) {
- holdings = kDemoHoldings;
+ // Render empty-state instead of fake demo holdings.
+ set_loading(false);
+ last_holdings_.clear();
+ last_quotes_.clear();
+ hub_unsubscribe_all();
+ // Wipe rows + zero the summary counters.
+ while (list_layout_->count() > 0) {
+ auto* item = list_layout_->takeAt(0);
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ auto* empty = new QLabel(QStringLiteral(
+ "No holdings configured.\nAdd positions via the Portfolio screen."));
+ empty->setAlignment(Qt::AlignCenter);
+ empty->setWordWrap(true);
+ empty->setStyleSheet(QString("color: %1; font-size: 11px; padding: 20px; background: transparent;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ list_layout_->addWidget(empty);
+ list_layout_->addStretch();
+ total_value_lbl_->setText(QStringLiteral("$0"));
+ day_pnl_lbl_->setText(QStringLiteral("$0"));
+ total_pnl_lbl_->setText(QStringLiteral("$0"));
+ num_holdings_lbl_->setText(QStringLiteral("0"));
+ return;
}
fetch_prices(holdings);
diff --git a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
index 1b36aae99..74eee03f0 100644
--- a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
@@ -254,9 +254,13 @@ void QuickTradeWidget::apply_quote(const services::QuoteData& q) {
change_label_->setText(chg_str);
change_label_->setStyleSheet(QString("color: %1; font-size: 10px; background: transparent;").arg(chg_col));
- double spread = q.price * 0.0005;
- bid_label_->setText(QString("BID %1").arg(q.price - spread, 0, 'f', 2));
- ask_label_->setText(QString("ASK %1").arg(q.price + spread, 0, 'f', 2));
+ // QuoteData from yfinance has no bid/ask — show em-dashes rather than
+ // a fabricated spread (the previous price*0.0005 placeholder was
+ // misleading on a trade-entry widget). Real bid/ask must come from a
+ // broker quote stream (`broker:<id>:<account>:quote:<sym>`) which the
+ // user wires up via the gear-icon config — wiring deferred.
+ bid_label_->setText(QStringLiteral("BID —"));
+ ask_label_->setText(QStringLiteral("ASK —"));
double qty = qty_input_->text().toDouble();
if (qty > 0)
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index 82a27a1c3..f4aa45be9 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -1268,8 +1268,14 @@ void EquityTradingScreen::on_import_holdings_requested(const QVector<trading::Br
QObject::disconnect(conn);
// Collect selected rows with their (possibly edited) yfinance tickers.
+ // We carry the broker-native pair (symbol + exchange) alongside the
+ // yfinance form so PortfolioService can route live quote calls through
+ // the broker instead of yfinance for portfolios linked to a connected
+ // account. See migration v022.
struct ImportRow {
- QString symbol;
+ QString symbol; // yfinance-format ("RELIANCE.NS"). Canonical key.
+ QString broker_symbol; // broker-native ("RELIANCE")
+ QString exchange; // "NSE" / "BSE" / etc.
double quantity = 0;
double avg_price = 0;
};
@@ -1283,7 +1289,11 @@ void EquityTradingScreen::on_import_holdings_requested(const QVector<trading::Br
const QString yf = table->item(r, 3)->text().trimmed().toUpper();
if (yf.isEmpty())
continue;
- rows.push_back({yf, holdings[r].quantity, holdings[r].avg_price});
+ rows.push_back({yf,
+ holdings[r].symbol, // broker-native ticker as returned by broker
+ holdings[r].exchange,
+ holdings[r].quantity,
+ holdings[r].avg_price});
}
if (rows.isEmpty()) {
QMessageBox::information(this, "Import Holdings", "Nothing selected to import.");
@@ -1296,7 +1306,8 @@ void EquityTradingScreen::on_import_holdings_requested(const QVector<trading::Br
for (const auto& row : rows) {
if (row.quantity <= 0 || row.symbol.isEmpty())
continue;
- svc.add_asset(portfolio_id, row.symbol, row.quantity, row.avg_price, today);
+ svc.add_asset(portfolio_id, row.symbol, row.quantity, row.avg_price, today,
+ row.broker_symbol, row.exchange);
}
};
@@ -1323,7 +1334,11 @@ void EquityTradingScreen::on_import_holdings_requested(const QVector<trading::Br
.arg(count)
.arg(p.name));
});
- ps.create_portfolio(name, account.display_name, currency, "Imported from " + broker_id.toUpper());
+ // Stamp the new portfolio with the broker account_id so live quotes
+ // route through the broker (PortfolioService::build_summary).
+ ps.create_portfolio(name, account.display_name, currency,
+ "Imported from " + broker_id.toUpper(),
+ account.account_id);
} else {
const QString pid = existing_combo->currentData().toString();
if (pid.isEmpty()) {
diff --git a/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp b/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp
index 85536dc98..21549b0f7 100644
--- a/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp
+++ b/fincept-qt/src/screens/launchpad/LaunchpadScreen.cpp
@@ -28,9 +28,8 @@ constexpr const char* kLaunchpadTag = "Launchpad";
} // namespace
LaunchpadScreen* LaunchpadScreen::instance() {
- // Lazy singleton owned by Qt's top-level-widget tracking. Set
- // WA_QuitOnClose to true via the close handler so the user explicitly
- // closing the launchpad quits the app.
+ // Lazy singleton; lives until process exit. closeEvent calls
+ // QCoreApplication::quit() so we don't need WA_DeleteOnClose.
static LaunchpadScreen* s = new LaunchpadScreen(nullptr);
return s;
}
@@ -97,12 +96,17 @@ LaunchpadScreen::LaunchpadScreen(QWidget* parent) : QMainWindow(parent) {
}
void LaunchpadScreen::surface() {
+ // Profile may have changed since construction (Switch Profile relaunches
+ // a new process today, but this keeps the label honest if that ever
+ // becomes in-process). Cheap to refresh on every surface.
+ if (greeting_)
+ greeting_->setText(QString("Profile: %1").arg(ProfileManager::instance().active()));
+
if (isVisible() && !isMinimized()) {
raise();
activateWindow();
return;
}
- user_initiated_close_ = false;
showNormal();
raise();
activateWindow();
@@ -111,14 +115,11 @@ void LaunchpadScreen::surface() {
}
void LaunchpadScreen::closeEvent(QCloseEvent* event) {
- if (!user_initiated_close_) {
- // Path: a button handler (on_new_window etc.) called hide() and
- // closeEvent never fires for hide() — but if Qt does send one
- // via window-close protocol while we're in the middle of
- // surfacing a frame, accept it without quitting.
- event->accept();
- return;
- }
+ // Reaching closeEvent always means the OS sent a window-close (X button
+ // / Alt-F4 / system menu). Programmatic dismissals from button handlers
+ // use hide() and never enter here. Treat every close as a user quit so
+ // the app actually exits — otherwise lastWindowClosed re-surfaces this
+ // window in an unkillable loop.
LOG_INFO(kLaunchpadTag, "User closed Launchpad — quitting");
event->accept();
QCoreApplication::quit();
@@ -133,23 +134,46 @@ void LaunchpadScreen::on_new_window() {
}
void LaunchpadScreen::on_switch_profile() {
- // Minimal v1: prompt for a profile name. The full UI (list of all
- // profiles + per-profile metadata) lands when Phase 6 / Settings
- // hierarchy gets attention.
+ // Show known profiles + a "Create new…" entry. Picking an existing
+ // profile relaunches with --profile <name>. Picking the create entry
+ // falls through to a text prompt.
LOG_INFO(kLaunchpadTag, "Switch Profile button clicked");
+
+ static const QString kCreateNew = QStringLiteral("+ Create new profile…");
+ QStringList items = ProfileManager::instance().list_profiles();
+ items.removeDuplicates();
+ items.append(kCreateNew);
+
+ const QString current = ProfileManager::instance().active();
+ int current_idx = items.indexOf(current);
+ if (current_idx < 0) current_idx = 0;
+
bool ok = false;
- const QString name = QInputDialog::getText(
- this, "Switch Profile",
- "Enter profile name (will create if not exists):",
- QLineEdit::Normal, ProfileManager::instance().active(), &ok);
- if (!ok || name.trimmed().isEmpty())
+ const QString picked = QInputDialog::getItem(
+ this, "Switch Profile", "Pick a profile or create one:",
+ items, current_idx, /*editable=*/false, &ok);
+ if (!ok)
return;
- // Profile switch is a process-level operation today (set_active +
- // relaunch). The full in-process switch lands with Phase 1b's auth
- // lift. For now: spawn a new instance with --profile arg and quit.
+
+ QString target = picked;
+ if (picked == kCreateNew) {
+ bool name_ok = false;
+ target = QInputDialog::getText(
+ this, "Create Profile", "New profile name:",
+ QLineEdit::Normal, QString(), &name_ok).trimmed();
+ if (!name_ok || target.isEmpty())
+ return;
+ }
+
+ if (target == current) {
+ LOG_INFO(kLaunchpadTag, "Switch Profile: target equals current — no-op");
+ return;
+ }
+
+ // Process-level switch today (set_active + relaunch). In-process switch
+ // lands with Phase 1b's auth lift.
const QString exe = QCoreApplication::applicationFilePath();
- user_initiated_close_ = true; // ensures closeEvent quits
- QProcess::startDetached(exe, {"--profile", name.trimmed()});
+ QProcess::startDetached(exe, {"--profile", target});
QCoreApplication::quit();
}
diff --git a/fincept-qt/src/screens/launchpad/LaunchpadScreen.h b/fincept-qt/src/screens/launchpad/LaunchpadScreen.h
index 36b2f3130..e31fb1b39 100644
--- a/fincept-qt/src/screens/launchpad/LaunchpadScreen.h
+++ b/fincept-qt/src/screens/launchpad/LaunchpadScreen.h
@@ -54,11 +54,6 @@ class LaunchpadScreen : public QMainWindow {
QPushButton* btn_new_window_ = nullptr;
QPushButton* btn_switch_profile_ = nullptr;
QPushButton* btn_open_layout_ = nullptr;
-
- /// True once the user explicitly clicks the OS close button on the
- /// launchpad — distinguishes "user wants to quit" from "we're hiding
- /// because they spawned a new window from a button click."
- bool user_initiated_close_ = false;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
index ef2223627..e1b4f8b1b 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
@@ -3,12 +3,14 @@
#include "screens/portfolio/PortfolioSparkline.h"
#include "services/markets/MarketDataService.h"
+#include "storage/repositories/SettingsRepository.h"
#include "ui/theme/Theme.h"
# include "datahub/DataHub.h"
# include "datahub/DataHubMetaTypes.h"
#include <QAction>
+#include <QHBoxLayout>
#include <QHeaderView>
#include <QJsonArray>
#include <QJsonDocument>
@@ -26,6 +28,19 @@ static const QStringList kColumns = {"SYMBOL", "QTY", "LAST", "AVG COST", "MKT
"P&L", "P&L%", "CHG%", "TREND", "WT%"};
PortfolioBlotter::PortfolioBlotter(QWidget* parent) : QWidget(parent) {
+ // Restore persisted page size before building the UI so the combo and
+ // populate_table see the right value on first paint.
+ {
+ auto r = SettingsRepository::instance().get("portfolio.blotter.page_size");
+ if (r.is_ok() && !r.value().isEmpty()) {
+ bool ok = false;
+ const int saved = r.value().toInt(&ok);
+ // Only accept the four sanctioned page sizes — anything else
+ // (corrupted setting, future value) silently falls back to 10.
+ if (ok && (saved == 10 || saved == 20 || saved == 50 || saved == 100))
+ page_size_ = saved;
+ }
+ }
build_ui();
}
@@ -85,7 +100,133 @@ void PortfolioBlotter::build_ui() {
table_->setContextMenuPolicy(Qt::CustomContextMenu);
connect(table_, &QTableWidget::customContextMenuRequested, this, &PortfolioBlotter::on_context_menu);
- layout->addWidget(table_);
+ layout->addWidget(table_, 1);
+
+ // Pagination footer sits flush at the bottom of the panel.
+ build_pagination_footer();
+ layout->addWidget(footer_);
+}
+
+void PortfolioBlotter::build_pagination_footer() {
+ footer_ = new QWidget(this);
+ footer_->setObjectName("pfBlotterFooter");
+ footer_->setFixedHeight(28);
+ footer_->setStyleSheet(
+ QString("#pfBlotterFooter { background:%1; border-top:1px solid %2; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+
+ auto* h = new QHBoxLayout(footer_);
+ h->setContentsMargins(12, 0, 10, 0);
+ h->setSpacing(8);
+
+ // ── Left: "Showing X-Y of Z" ─────────────────────────────────────────────
+ footer_status_ = new QLabel("Showing 0 of 0");
+ footer_status_->setStyleSheet(
+ QString("color:%1; font-size:10px; font-weight:600; background:transparent;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ h->addWidget(footer_status_);
+
+ h->addStretch(1);
+
+ // ── Center: nav buttons + page label ─────────────────────────────────────
+ // All four buttons share the same neutral square style. Disabled state
+ // dims to TEXT_DIM and removes hover hint.
+ auto make_nav_btn = [this](const QString& glyph, const QString& tip) {
+ auto* b = new QPushButton(glyph);
+ b->setFixedSize(22, 22);
+ b->setCursor(Qt::PointingHandCursor);
+ b->setToolTip(tip);
+ b->setStyleSheet(
+ QString("QPushButton { background:transparent; color:%1; border:1px solid %2;"
+ " font-size:11px; font-weight:700; }"
+ "QPushButton:hover:enabled { color:%3; border-color:%3; }"
+ "QPushButton:disabled { color:%4; border-color:%5; }")
+ .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(),
+ ui::colors::AMBER(), ui::colors::TEXT_DIM(), ui::colors::BORDER_DIM()));
+ return b;
+ };
+
+ btn_first_ = make_nav_btn(QStringLiteral("«"), "First page"); // «
+ btn_prev_ = make_nav_btn(QStringLiteral("‹"), "Previous page"); // ‹
+ h->addWidget(btn_first_);
+ h->addWidget(btn_prev_);
+
+ footer_page_label_ = new QLabel("Page 1 of 1");
+ footer_page_label_->setMinimumWidth(80);
+ footer_page_label_->setAlignment(Qt::AlignCenter);
+ footer_page_label_->setStyleSheet(
+ QString("color:%1; font-size:11px; font-weight:700; background:transparent;")
+ .arg(ui::colors::TEXT_PRIMARY()));
+ h->addWidget(footer_page_label_);
+
+ btn_next_ = make_nav_btn(QStringLiteral("›"), "Next page"); // ›
+ btn_last_ = make_nav_btn(QStringLiteral("»"), "Last page"); // »
+ h->addWidget(btn_next_);
+ h->addWidget(btn_last_);
+
+ h->addStretch(1);
+
+ // ── Right: "Rows: [10 ▾]" ───────────────────────────────────────────────
+ auto* rows_label = new QLabel("Rows:");
+ rows_label->setStyleSheet(
+ QString("color:%1; font-size:10px; font-weight:600; background:transparent;")
+ .arg(ui::colors::TEXT_TERTIARY()));
+ h->addWidget(rows_label);
+
+ page_size_combo_ = new QComboBox(footer_);
+ page_size_combo_->setFixedHeight(22);
+ page_size_combo_->setCursor(Qt::PointingHandCursor);
+ page_size_combo_->addItem("10", 10);
+ page_size_combo_->addItem("20", 20);
+ page_size_combo_->addItem("50", 50);
+ page_size_combo_->addItem("100", 100);
+ page_size_combo_->setStyleSheet(
+ QString("QComboBox { background:%1; color:%2; border:1px solid %3;"
+ " padding:0 6px; font-size:11px; font-weight:700; min-width:48px; }"
+ "QComboBox::drop-down { border:none; width:14px; }"
+ "QComboBox QAbstractItemView { background:%1; color:%2;"
+ " selection-background-color:%4; selection-color:%5; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(),
+ ui::colors::BORDER_DIM(), ui::colors::AMBER_DIM(), ui::colors::AMBER()));
+ // Set initial selection to the persisted (or default) value.
+ for (int i = 0; i < page_size_combo_->count(); ++i) {
+ if (page_size_combo_->itemData(i).toInt() == page_size_) {
+ QSignalBlocker block(page_size_combo_);
+ page_size_combo_->setCurrentIndex(i);
+ break;
+ }
+ }
+ h->addWidget(page_size_combo_);
+
+ // ── Wiring ───────────────────────────────────────────────────────────────
+ connect(btn_first_, &QPushButton::clicked, this, [this]() {
+ if (current_page_ != 1) { current_page_ = 1; populate_table(); }
+ });
+ connect(btn_prev_, &QPushButton::clicked, this, [this]() {
+ if (current_page_ > 1) { --current_page_; populate_table(); }
+ });
+ connect(btn_next_, &QPushButton::clicked, this, [this]() {
+ if (current_page_ < total_pages()) { ++current_page_; populate_table(); }
+ });
+ connect(btn_last_, &QPushButton::clicked, this, [this]() {
+ const int last = total_pages();
+ if (current_page_ != last) { current_page_ = last; populate_table(); }
+ });
+ connect(page_size_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ [this](int idx) {
+ const int new_size = page_size_combo_->itemData(idx).toInt();
+ if (new_size <= 0 || new_size == page_size_)
+ return;
+ // Preserve the topmost visible row across page-size changes:
+ // figure out which row is at the top right now, then jump to
+ // the page that contains it under the new page size.
+ const int top_row_idx = (current_page_ - 1) * page_size_;
+ page_size_ = new_size;
+ current_page_ = (top_row_idx / page_size_) + 1;
+ SettingsRepository::instance().set("portfolio.blotter.page_size",
+ QString::number(page_size_), "portfolio");
+ populate_table();
+ });
}
void PortfolioBlotter::set_holdings(const QVector<portfolio::HoldingWithQuote>& holdings) {
@@ -217,16 +358,96 @@ void PortfolioBlotter::on_header_clicked(int section) {
}
emit sort_changed(sort_col_, sort_dir_);
+ // Sorting changes which rows are at the top — jump to page 1 so users
+ // see the new "highest" rows instead of staying on a deep page that may
+ // now contain unrelated content.
+ current_page_ = 1;
populate_table();
}
void PortfolioBlotter::on_row_clicked(int row, int) {
- if (row >= 0 && row < sorted_.size()) {
- selected_symbol_ = sorted_[row].symbol;
+ // Row index is into the current page slice (paged_view), not sorted_.
+ const auto page = paged_view();
+ if (row >= 0 && row < page.size()) {
+ selected_symbol_ = page[row].symbol;
emit symbol_selected(selected_symbol_);
}
}
+// ── Pagination helpers ──────────────────────────────────────────────────────
+
+QVector<portfolio::HoldingWithQuote> PortfolioBlotter::visible_view() const {
+ // Apply text filter + sector filter on top of the already-sorted set.
+ // We rebuild this every populate_table — the dataset is bounded (a few
+ // hundred holdings at most for a real portfolio).
+ QVector<portfolio::HoldingWithQuote> out;
+ out.reserve(sorted_.size());
+ const QString needle = filter_text_.toLower();
+ const bool has_sector = !sector_symbols_.isEmpty();
+
+ QSet<QString> sector_set;
+ if (has_sector) {
+ for (const auto& s : sector_symbols_)
+ sector_set.insert(s.toLower());
+ }
+
+ for (const auto& h : sorted_) {
+ if (!needle.isEmpty() && !h.symbol.toLower().contains(needle))
+ continue;
+ if (has_sector && !sector_set.contains(h.symbol.toLower()))
+ continue;
+ out.append(h);
+ }
+ return out;
+}
+
+QVector<portfolio::HoldingWithQuote> PortfolioBlotter::paged_view() const {
+ const auto all = visible_view();
+ if (page_size_ <= 0)
+ return all;
+ const int start = (current_page_ - 1) * page_size_;
+ if (start >= all.size())
+ return {};
+ const int end = std::min<int>(start + page_size_, all.size());
+ return all.mid(start, end - start);
+}
+
+int PortfolioBlotter::total_pages() const {
+ const int total = visible_view().size();
+ if (total == 0 || page_size_ <= 0)
+ return 1;
+ return (total + page_size_ - 1) / page_size_;
+}
+
+void PortfolioBlotter::clamp_current_page() {
+ const int last = total_pages();
+ if (current_page_ < 1) current_page_ = 1;
+ if (current_page_ > last) current_page_ = last;
+}
+
+void PortfolioBlotter::update_pagination_controls() {
+ if (!footer_status_)
+ return;
+
+ const int total = visible_view().size();
+ const int last_page = total_pages();
+ const int start_idx = (total == 0) ? 0 : (current_page_ - 1) * page_size_ + 1;
+ const int end_idx = std::min<int>(current_page_ * page_size_, total);
+
+ if (total == 0) {
+ footer_status_->setText("No positions");
+ } else {
+ footer_status_->setText(QString("Showing %1-%2 of %3").arg(start_idx).arg(end_idx).arg(total));
+ }
+
+ footer_page_label_->setText(QString("Page %1 of %2").arg(current_page_).arg(last_page));
+
+ btn_first_->setEnabled(current_page_ > 1);
+ btn_prev_->setEnabled(current_page_ > 1);
+ btn_next_->setEnabled(current_page_ < last_page);
+ btn_last_->setEnabled(current_page_ < last_page);
+}
+
void PortfolioBlotter::populate_table() {
// Clean up old sparkline cell widgets before repopulating (prevents memory leak)
for (int r = 0; r < table_->rowCount(); ++r) {
@@ -275,10 +496,15 @@ void PortfolioBlotter::populate_table() {
};
std::stable_sort(sorted_.begin(), sorted_.end(), cmp);
- table_->setRowCount(sorted_.size());
+ // Compute the current page's row slice — the rest of the function only
+ // populates the visible window. clamp_current_page handles the case where
+ // a filter/sort change shrinks the view below the current page index.
+ clamp_current_page();
+ const auto page_rows = paged_view();
+ table_->setRowCount(page_rows.size());
- for (int r = 0; r < sorted_.size(); ++r) {
- const auto& h = sorted_[r];
+ for (int r = 0; r < page_rows.size(); ++r) {
+ const auto& h = page_rows[r];
table_->setRowHeight(r, 28);
auto set_cell = [&](int col, const QString& text, const char* color = nullptr,
@@ -356,6 +582,9 @@ void PortfolioBlotter::populate_table() {
table_->selectRow(r);
}
}
+
+ // Footer status + nav button enabled-state must reflect what we just rendered.
+ update_pagination_controls();
}
QString PortfolioBlotter::format_value(double v, int dp) const {
@@ -373,34 +602,21 @@ void PortfolioBlotter::set_sector_filter(const QStringList& symbols) {
}
void PortfolioBlotter::apply_filter() {
- for (int r = 0; r < table_->rowCount(); ++r) {
- auto* item = table_->item(r, 0); // symbol column
- if (!item)
- continue;
- const QString sym = item->text().toLower();
-
- const bool text_ok = filter_text_.isEmpty() || sym.contains(filter_text_);
-
- bool sector_ok = sector_symbols_.isEmpty();
- if (!sector_ok) {
- for (const auto& s : sector_symbols_) {
- if (sym == s.toLower()) {
- sector_ok = true;
- break;
- }
- }
- }
-
- table_->setRowHidden(r, !(text_ok && sector_ok));
- }
+ // With pagination, the table only contains the current page slice — there
+ // are no hidden rows to toggle. Filter changes shrink the visible_view, so
+ // jump to page 1 and rebuild. visible_view() inside populate_table re-applies
+ // both filter_text_ and sector_symbols_ from scratch.
+ current_page_ = 1;
+ populate_table();
}
void PortfolioBlotter::on_context_menu(const QPoint& pos) {
const int row = table_->rowAt(pos.y());
- if (row < 0 || row >= sorted_.size())
+ const auto page = paged_view();
+ if (row < 0 || row >= page.size())
return;
- const QString symbol = sorted_[row].symbol;
+ const QString symbol = page[row].symbol;
QMenu menu(this);
menu.setStyleSheet(QString("QMenu { background:%1; color:%2; border:1px solid %3; padding:4px; }"
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h b/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
index 91535a5f4..a73ef659f 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.h
@@ -2,8 +2,11 @@
#pragma once
#include "screens/portfolio/PortfolioTypes.h"
+#include <QComboBox>
#include <QHash>
+#include <QLabel>
#include <QPointer>
+#include <QPushButton>
#include <QTableWidget>
#include <QWidget>
@@ -32,6 +35,7 @@ class PortfolioBlotter : public QWidget {
private:
void build_ui();
+ void build_pagination_footer();
void populate_table();
void apply_filter();
void on_header_clicked(int section);
@@ -39,8 +43,31 @@ class PortfolioBlotter : public QWidget {
void on_context_menu(const QPoint& pos);
QString format_value(double v, int dp = 2) const;
+ // ── Pagination ──────────────────────────────────────────────────────────
+ /// Filtered + sorted view (after filter/sector trim) used as the source
+ /// of truth for pagination math. Recomputed every populate_table().
+ QVector<portfolio::HoldingWithQuote> visible_view() const;
+ /// Rows for the current page only — what actually goes into table_.
+ QVector<portfolio::HoldingWithQuote> paged_view() const;
+ /// Update footer labels + button enabled-states from current state.
+ void update_pagination_controls();
+ /// Clamp current_page_ to a valid range given the latest filtered count.
+ void clamp_current_page();
+ /// Total pages for current filtered view + page size.
+ int total_pages() const;
+
QTableWidget* table_ = nullptr;
+ // Pagination footer widgets
+ QWidget* footer_ = nullptr;
+ QLabel* footer_status_ = nullptr; // "Showing 1-10 of 47"
+ QPushButton* btn_first_ = nullptr;
+ QPushButton* btn_prev_ = nullptr;
+ QLabel* footer_page_label_ = nullptr; // "Page 1 of 5"
+ QPushButton* btn_next_ = nullptr;
+ QPushButton* btn_last_ = nullptr;
+ QComboBox* page_size_combo_ = nullptr;
+
void fetch_sparklines();
void hub_resubscribe_sparklines();
@@ -56,6 +83,11 @@ class PortfolioBlotter : public QWidget {
portfolio::SortColumn sort_col_ = portfolio::SortColumn::Weight;
portfolio::SortDirection sort_dir_ = portfolio::SortDirection::Desc;
+ // Pagination state. page_size_ persists via SettingsRepository
+ // ("portfolio.blotter.page_size"). current_page_ is 1-indexed.
+ int page_size_ = 10;
+ int current_page_ = 1;
+
// Real sparkline data keyed by symbol — populated async via fetch_sparklines()
QHash<QString, QVector<double>> sparkline_cache_;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
index 1c894b072..8e78ac792 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioPerfChart.cpp
@@ -469,17 +469,46 @@ void PortfolioPerfChart::update_chart() {
chart->addSeries(area);
chart->addSeries(nav_line);
- // ── Cost basis reference line ────────────────────────────────────────────
+ // ── Cost basis reference line (per-day, from replay snapshots) ───────────
// Skipped in indexed mode (where the period baseline IS the reference at 100).
+ // Each snapshot now carries its own cost basis (BUYs add, SELLs reduce by
+ // weighted-average cost), so the cost line is a real step-shaped series
+ // that rises whenever the user added capital — not a flat horizontal at
+ // today's cost.
QLineSeries* cost_line = nullptr;
- if (cost_basis > 0 && !indexed_mode_) {
+ if (!indexed_mode_) {
cost_line = new QLineSeries;
cost_line->setName("Cost basis");
- cost_line->append(nav_pts.first().x(), cost_disp);
- cost_line->append(nav_pts.last().x(), cost_disp);
- QPen cp(QColor(ui::colors::TEXT_TERTIARY()), 1, Qt::DashLine);
- cost_line->setPen(cp);
- chart->addSeries(cost_line);
+
+ // Map snapshot_date → total_cost_basis for the filtered window. Each
+ // nav_pts x-coordinate is a ms_utc timestamp matching a snapshot date;
+ // pair them up and append a point per day so the line steps with the
+ // actual cost-basis trajectory. The synthesized "now" point at the
+ // tail (when filtered.size() < 2) reuses today's cost basis.
+ for (int i = 0; i < filtered.size() && i < nav_pts.size(); ++i) {
+ cost_line->append(nav_pts[i].x(), filtered[i].total_cost_basis);
+ }
+ // Pin the trailing "now" point to today's cost so the line meets the
+ // x-axis end (NAV series does the same).
+ if (!nav_pts.isEmpty() && cost_line->count() < nav_pts.size()) {
+ cost_line->append(nav_pts.last().x(), cost_basis);
+ }
+
+ if (cost_line->count() > 0) {
+ QPen cp(QColor(ui::colors::TEXT_TERTIARY()), 1, Qt::DashLine);
+ cost_line->setPen(cp);
+ chart->addSeries(cost_line);
+ // Update y-axis range to include the full cost-basis trajectory,
+ // not just today's value.
+ for (int i = 0; i < cost_line->count(); ++i) {
+ const double y = cost_line->at(i).y();
+ y_min = std::min(y_min, y);
+ y_max = std::max(y_max, y);
+ }
+ } else {
+ delete cost_line;
+ cost_line = nullptr;
+ }
}
// ── Axes ──────────────────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/portfolio/PortfolioTypes.h b/fincept-qt/src/screens/portfolio/PortfolioTypes.h
index 02c934bd9..05704d5c8 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioTypes.h
+++ b/fincept-qt/src/screens/portfolio/PortfolioTypes.h
@@ -18,17 +18,28 @@ struct Portfolio {
QString description;
QString created_at;
QString updated_at;
+ /// Empty for manually-created portfolios. Set when imported from a
+ /// connected broker account — links back to broker_accounts.id so
+ /// PortfolioService can route live quote fetches through the broker
+ /// instead of yfinance. See migration v022.
+ QString broker_account_id;
};
struct PortfolioAsset {
int id = 0;
QString portfolio_id;
- QString symbol;
+ QString symbol; // canonical: yfinance-format ("RELIANCE.NS"). Used by sparklines, replay, news, sectors.
double quantity = 0;
double avg_buy_price = 0;
QString first_purchase_date;
QString last_updated;
- QString sector; // empty = not yet resolved; filled from import JSON or SectorResolver
+ QString sector; // empty = not yet resolved; filled from import JSON or SectorResolver
+ /// Broker-native ticker (e.g. "RELIANCE", no exchange suffix). Empty for
+ /// manually-imported assets. Combined with `exchange` to form the
+ /// EXCHANGE:SYMBOL key brokers like Zerodha need for /quote calls.
+ QString broker_symbol;
+ /// Exchange code (e.g. "NSE", "BSE"). Empty for non-broker imports.
+ QString exchange;
};
struct Transaction {
diff --git a/fincept-qt/src/services/backtesting/BacktestingService.cpp b/fincept-qt/src/services/backtesting/BacktestingService.cpp
index 902ffbc65..7d8c3f740 100644
--- a/fincept-qt/src/services/backtesting/BacktestingService.cpp
+++ b/fincept-qt/src/services/backtesting/BacktestingService.cpp
@@ -37,6 +37,9 @@ void BacktestingService::execute(const QString& provider, const QString& command
{"labels", "generate_labels"},
{"splits", "generate_splits"},
{"returns", "analyze_returns"},
+ {"indicator_sweep", "indicator_param_sweep"},
+ // labels_to_signals, walk_forward, optimize, indicator_signals: UI
+ // short-id matches the Python long name; pass through unchanged.
};
const QString py_command = kPyCommandMap.value(command, command);
diff --git a/fincept-qt/src/services/backtesting/BacktestingTypes.h b/fincept-qt/src/services/backtesting/BacktestingTypes.h
index 88a7ba67c..e9c8175de 100644
--- a/fincept-qt/src/services/backtesting/BacktestingTypes.h
+++ b/fincept-qt/src/services/backtesting/BacktestingTypes.h
@@ -1,4 +1,13 @@
// src/services/backtesting/BacktestingTypes.h
+//
+// This file is the UI's view of provider capability. The `commands` array on
+// each Provider gates which buttons the BacktestingScreen renders and which
+// commands the user can invoke. It is a SUBSET of what each Python provider
+// actually dispatches — the source of truth for capability is each provider's
+// scripts/Analytics/backtesting/{provider}/{provider}_provider.py::main()
+// dispatcher. When a Python provider grows a new command, this file and the
+// matching cmd_config_stack_ page in BacktestingScreen.cpp must be updated
+// together to surface it.
#pragma once
#include <QColor>
#include <QJsonArray>
@@ -24,14 +33,19 @@ inline QVector<Provider> all_providers() {
"VectorBT",
QColor("#00E5FF"),
{"backtest", "optimize", "walk_forward", "indicator", "indicator_signals", "labels", "splits", "returns",
- "signals"}},
+ "signals", "labels_to_signals", "indicator_sweep"}},
{"backtestingpy", "Backtesting.py", QColor("#00D66F"), {"backtest", "optimize", "walk_forward", "indicator"}},
- {"fasttrade", "FastTrade", QColor("#FFC400"), {"backtest"}},
+ {"fasttrade", "FastTrade", QColor("#FFC400"), {"backtest", "indicator"}},
{"zipline",
"Zipline",
QColor("#FF3B8E"),
- {"backtest", "optimize", "walk_forward", "indicator", "indicator_signals"}},
- {"bt", "BT", QColor("#FF6B35"), {"backtest", "optimize", "walk_forward", "indicator", "indicator_signals"}},
+ {"backtest", "optimize", "walk_forward", "indicator", "indicator_signals", "labels", "splits", "returns",
+ "signals", "labels_to_signals"}},
+ {"bt",
+ "BT",
+ QColor("#FF6B35"),
+ {"backtest", "optimize", "walk_forward", "indicator", "indicator_signals", "labels", "splits", "returns",
+ "signals", "labels_to_signals"}},
{"fincept", "Fincept", QColor("#d97706"), {"backtest", "optimize", "walk_forward"}},
};
}
@@ -45,6 +59,10 @@ struct CommandDef {
};
inline QVector<CommandDef> all_commands() {
+ // New commands MUST be appended at the end. BacktestingScreen persists
+ // the active command as an integer index in save_state(), and the
+ // cmd_config_stack_ pages are looked up by the same index — reordering
+ // would break saved-state restore for existing users.
return {
{"backtest", "Run Backtest", QColor("#FF6B35")},
{"optimize", "Optimize", QColor("#00D66F")},
@@ -55,6 +73,8 @@ inline QVector<CommandDef> all_commands() {
{"splits", "CV Splits", QColor("#0088FF")},
{"returns", "Returns Analysis", QColor("#00D66F")},
{"signals", "Signal Generators", QColor("#FFC400")},
+ {"labels_to_signals", "Labels -> Signals", QColor("#9D4EDD")},
+ {"indicator_sweep", "Indicator Sweep", QColor("#00E5FF")},
};
}
diff --git a/fincept-qt/src/services/economics/MacroCalendarService.cpp b/fincept-qt/src/services/economics/MacroCalendarService.cpp
new file mode 100644
index 000000000..a926d1a61
--- /dev/null
+++ b/fincept-qt/src/services/economics/MacroCalendarService.cpp
@@ -0,0 +1,91 @@
+#include "services/economics/MacroCalendarService.h"
+
+#include "core/logging/Logger.h"
+#include "datahub/DataHub.h"
+#include "datahub/TopicPolicy.h"
+#include "network/http/HttpClient.h"
+
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QJsonValue>
+#include <QPointer>
+
+namespace fincept::services {
+
+namespace {
+constexpr const char* kTopic = "econ:fincept:upcoming_events";
+constexpr const char* kUrl = "https://api.fincept.in/macro/upcoming-events?limit=25";
+
+QJsonArray parse_events(const QJsonDocument& doc) {
+ if (doc.isArray())
+ return doc.array();
+ if (!doc.isObject())
+ return {};
+
+ const auto root = doc.object();
+ // {"success":true,"data":{"events":[...]}}
+ if (root.contains(QStringLiteral("data")) && root.value(QStringLiteral("data")).isObject()) {
+ const auto data = root.value(QStringLiteral("data")).toObject();
+ if (data.contains(QStringLiteral("events")) && data.value(QStringLiteral("events")).isArray())
+ return data.value(QStringLiteral("events")).toArray();
+ }
+ // {"data":[...]}
+ if (root.contains(QStringLiteral("data")) && root.value(QStringLiteral("data")).isArray())
+ return root.value(QStringLiteral("data")).toArray();
+ // {"events":[...]}
+ if (root.contains(QStringLiteral("events")) && root.value(QStringLiteral("events")).isArray())
+ return root.value(QStringLiteral("events")).toArray();
+ return {};
+}
+} // namespace
+
+MacroCalendarService& MacroCalendarService::instance() {
+ static MacroCalendarService s;
+ return s;
+}
+
+MacroCalendarService::MacroCalendarService(QObject* parent) : QObject(parent) {}
+
+void MacroCalendarService::ensure_registered_with_hub() {
+ if (hub_registered_)
+ return;
+ auto& hub = fincept::datahub::DataHub::instance();
+ hub.register_producer(this);
+
+ fincept::datahub::TopicPolicy policy;
+ policy.ttl_ms = 5 * 60 * 1000; // 5 min — macro events refresh slowly
+ policy.min_interval_ms = 60 * 1000; // 60 s
+ policy.refresh_timeout_ms = 30 * 1000;
+ hub.set_policy(QString::fromLatin1(kTopic), policy);
+
+ hub_registered_ = true;
+ LOG_INFO("MacroCalendarService", "Registered with DataHub (econ:fincept:upcoming_events)");
+}
+
+QStringList MacroCalendarService::topic_patterns() const {
+ return {QString::fromLatin1(kTopic)};
+}
+
+void MacroCalendarService::refresh(const QStringList& topics) {
+ // Single-topic producer — the hub may pass the topic list redundantly,
+ // but there's only ever one fetch to do.
+ if (!topics.contains(QString::fromLatin1(kTopic)))
+ return;
+
+ QPointer<MacroCalendarService> self = this;
+ fincept::HttpClient::instance().get(QString::fromLatin1(kUrl),
+ [self](fincept::Result<QJsonDocument> result) {
+ if (!self)
+ return;
+ auto& hub = fincept::datahub::DataHub::instance();
+ if (!result.is_ok()) {
+ hub.publish_error(QString::fromLatin1(kTopic),
+ QString::fromStdString(result.error()));
+ return;
+ }
+ const QJsonArray events = parse_events(result.value());
+ hub.publish(QString::fromLatin1(kTopic), QVariant::fromValue(events));
+ });
+}
+
+} // namespace fincept::services
diff --git a/fincept-qt/src/services/economics/MacroCalendarService.h b/fincept-qt/src/services/economics/MacroCalendarService.h
new file mode 100644
index 000000000..4d853d522
--- /dev/null
+++ b/fincept-qt/src/services/economics/MacroCalendarService.h
@@ -0,0 +1,47 @@
+#pragma once
+// MacroCalendarService — DataHub producer for the upcoming macro/economic
+// events feed served by Fincept's API (`api.fincept.in/macro/upcoming-events`).
+//
+// Topic: `econ:fincept:upcoming_events`. Payload: `QJsonArray` (the events
+// array as returned by the API). One topic, one producer, one HTTP fetch
+// per refresh — the hub fans out to the EconomicCalendarWidget and any
+// future consumers (report builder, MCP tools, agents).
+//
+// TTL: 5 min. Min interval: 60 s. Both honour the upstream cache and keep
+// rate-limit pressure low.
+
+#include <QJsonArray>
+#include <QObject>
+#include <QString>
+#include <QStringList>
+
+#include "datahub/Producer.h"
+
+namespace fincept::services {
+
+class MacroCalendarService : public QObject
+ , public fincept::datahub::Producer
+{
+ Q_OBJECT
+ public:
+ static MacroCalendarService& instance();
+
+ /// Register with the hub + install the topic policy. Idempotent.
+ void ensure_registered_with_hub();
+
+ // ── fincept::datahub::Producer ────────────────────────────────────────
+ QStringList topic_patterns() const override;
+ void refresh(const QStringList& topics) override;
+ int max_requests_per_sec() const override { return 2; }
+
+ private:
+ explicit MacroCalendarService(QObject* parent = nullptr);
+ Q_DISABLE_COPY(MacroCalendarService)
+
+ bool hub_registered_ = false;
+};
+
+} // namespace fincept::services
+
+// QJsonArray is built into QtCore's metatype system — no explicit
+// Q_DECLARE_METATYPE needed.
diff --git a/fincept-qt/src/services/portfolio/PortfolioService.cpp b/fincept-qt/src/services/portfolio/PortfolioService.cpp
index ac4ec0acd..35d3d0256 100644
--- a/fincept-qt/src/services/portfolio/PortfolioService.cpp
+++ b/fincept-qt/src/services/portfolio/PortfolioService.cpp
@@ -6,13 +6,18 @@
#include "services/sectors/SectorResolver.h"
#include "storage/repositories/PortfolioRepository.h"
#include "storage/repositories/SettingsRepository.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerInterface.h"
+#include "trading/BrokerRegistry.h"
#include <QDateTime>
+#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMutexLocker>
+#include <QStandardPaths>
#include <QtConcurrent>
#include <algorithm>
@@ -71,8 +76,8 @@ void PortfolioService::load_portfolios() {
}
void PortfolioService::create_portfolio(const QString& name, const QString& owner, const QString& currency,
- const QString& description) {
- auto r = PortfolioRepository::instance().create_portfolio(name, owner, currency, description);
+ const QString& description, const QString& broker_account_id) {
+ auto r = PortfolioRepository::instance().create_portfolio(name, owner, currency, description, broker_account_id);
if (r.is_ok()) {
auto p = PortfolioRepository::instance().get_portfolio(r.value());
if (p.is_ok())
@@ -141,112 +146,251 @@ void PortfolioService::refresh_summary(const QString& portfolio_id) {
void PortfolioService::build_summary(const QString& portfolio_id, const QVector<portfolio::PortfolioAsset>& assets,
const portfolio::Portfolio& portfolio) {
- // Collect symbols for batch quote fetch
+ // Routing decision: broker-first when the portfolio is linked to a
+ // connected broker account (broker_account_id non-empty + creds present
+ // + broker exposes get_quotes). yfinance is the universal fallback.
+ if (try_broker_quotes(portfolio_id, assets, portfolio))
+ return;
+
+ // ── yfinance path (legacy / unlinked portfolios) ─────────────────────────
QStringList symbols;
symbols.reserve(assets.size());
- for (const auto& a : assets) {
+ for (const auto& a : assets)
symbols.append(a.symbol);
- }
- // Use QPointer for safe async callback (P8)
QPointer<PortfolioService> self = this;
-
MarketDataService::instance().fetch_quotes(symbols, [self, portfolio_id, assets,
portfolio](bool ok, QVector<QuoteData> quotes) {
if (!self)
return;
-
- // Build quote lookup
QHash<QString, QuoteData> quote_map;
if (ok) {
for (const auto& q : quotes)
quote_map[q.symbol] = q;
}
+ self->finalize_summary(portfolio_id, assets, portfolio, quote_map);
+ });
+}
+
+bool PortfolioService::try_broker_quotes(const QString& portfolio_id,
+ const QVector<portfolio::PortfolioAsset>& assets,
+ const portfolio::Portfolio& portfolio) {
+ if (portfolio.broker_account_id.isEmpty())
+ return false; // unlinked portfolio — yfinance owns it.
+
+ // Resolve broker + creds. Any of these missing → fall back silently.
+ auto& acct_mgr = trading::AccountManager::instance();
+ const auto account = acct_mgr.get_account(portfolio.broker_account_id);
+ if (account.account_id.isEmpty() || account.broker_id.isEmpty()) {
+ LOG_WARN("PortfolioSvc",
+ QString("broker_account_id %1 not found — falling back to yfinance for %2")
+ .arg(portfolio.broker_account_id, portfolio_id));
+ return false;
+ }
- portfolio::PortfolioSummary summary;
- summary.portfolio = portfolio;
- summary.holdings.reserve(assets.size());
-
- double total_mv = 0;
- double total_cost = 0;
- double total_day = 0;
-
- for (const auto& asset : assets) {
- portfolio::HoldingWithQuote h;
- h.symbol = asset.symbol;
- h.quantity = asset.quantity;
- h.avg_buy_price = asset.avg_buy_price;
- h.cost_basis = asset.quantity * asset.avg_buy_price;
- // Prefer stored sector; fall back to resolver cache (which may
- // populate async — see sector_resolved handler in constructor).
- h.sector = asset.sector.isEmpty()
- ? SectorResolver::instance().sector_for(asset.symbol)
- : asset.sector;
-
- auto it = quote_map.find(asset.symbol);
- if (it != quote_map.end()) {
- h.current_price = it->price;
- h.day_change = it->change;
- h.day_change_percent = it->change_pct;
+ auto* broker = trading::BrokerRegistry::instance().get(account.broker_id);
+ if (!broker) {
+ LOG_WARN("PortfolioSvc",
+ QString("broker '%1' not registered — falling back to yfinance for %2")
+ .arg(account.broker_id, portfolio_id));
+ return false;
+ }
+
+ const auto creds = acct_mgr.load_credentials(portfolio.broker_account_id);
+ if (creds.access_token.isEmpty()) {
+ LOG_WARN("PortfolioSvc",
+ QString("broker account %1 has no access_token — falling back to yfinance for %2")
+ .arg(portfolio.broker_account_id, portfolio_id));
+ return false;
+ }
+
+ // Build the broker-native key list. Each asset stores broker_symbol +
+ // exchange (populated at import time). Skip assets without a broker
+ // pair — those slipped in before the v022 link or are non-broker rows
+ // mixed into a broker-linked portfolio. They get current_price = 0 from
+ // the lookup and the existing fallback (avg_buy_price) kicks in.
+ QVector<QString> broker_keys;
+ QHash<QString, QString> key_to_yf; // EXCHANGE:SYMBOL → asset.symbol (yfinance)
+ broker_keys.reserve(assets.size());
+ for (const auto& a : assets) {
+ if (a.broker_symbol.isEmpty() || a.exchange.isEmpty())
+ continue;
+ const QString key = a.exchange + ":" + a.broker_symbol;
+ broker_keys.append(key);
+ key_to_yf.insert(key, a.symbol);
+ }
+ if (broker_keys.isEmpty()) {
+ // Linked portfolio but no asset has a broker pair — nothing to fetch
+ // via broker. Fall back to yfinance so the portfolio still renders.
+ LOG_WARN("PortfolioSvc",
+ QString("broker-linked portfolio %1 has no broker_symbol/exchange on any asset — yfinance fallback")
+ .arg(portfolio_id));
+ return false;
+ }
+
+ // BrokerHttp::execute blocks on QEventLoop (memory: project_broker_http_blocking).
+ // Wrap the broker call in QtConcurrent::run so the UI thread stays responsive.
+ // P8: capture a QPointer; result is posted back via QMetaObject::invokeMethod.
+ // The QFuture return value is intentionally discarded — we don't need to
+ // wait or cancel; lifetime is governed by the captured QPointer guards.
+ QPointer<PortfolioService> self = this;
+ (void)QtConcurrent::run([self, portfolio_id, assets, portfolio, broker, creds, broker_keys, key_to_yf]() {
+ const auto resp = broker->get_quotes(creds, broker_keys);
+
+ // Hop back to the UI thread (the one that owns *self) before touching
+ // any shared state — finalize_summary writes to the cache mutex and
+ // emits a signal that drives UI updates.
+ QMetaObject::invokeMethod(self, [self, portfolio_id, assets, portfolio, resp, key_to_yf]() {
+ if (!self)
+ return;
+
+ QHash<QString, QuoteData> quote_map;
+ if (resp.success && resp.data.has_value()) {
+ for (const auto& bq : resp.data.value()) {
+ // bq.symbol is the EXCHANGE:SYMBOL key (Zerodha echoes the
+ // request key in its response). Translate back to the
+ // canonical yfinance key the rest of the pipeline uses.
+ const QString yf_key = key_to_yf.value(bq.symbol);
+ if (yf_key.isEmpty())
+ continue; // unknown key — broker returned a row we didn't ask for, skip.
+
+ QuoteData q;
+ q.symbol = yf_key;
+ q.name = yf_key; // brokers don't return a friendly name on /quote.
+ q.price = bq.ltp;
+ q.change = bq.change;
+ q.change_pct = bq.change_pct;
+ q.high = bq.high;
+ q.low = bq.low;
+ q.volume = bq.volume;
+ quote_map.insert(yf_key, q);
+ }
+ LOG_INFO("PortfolioSvc",
+ QString("Broker quotes: %1 of %2 for portfolio %3")
+ .arg(quote_map.size()).arg(key_to_yf.size()).arg(portfolio_id));
} else {
- // Fallback to avg buy price if no quote
- h.current_price = asset.avg_buy_price;
+ // Broker call failed — log and fall back to yfinance for
+ // _this_ refresh. The portfolio stays linked; next refresh
+ // will retry the broker.
+ LOG_WARN("PortfolioSvc",
+ QString("broker get_quotes failed for %1: %2 — falling back to yfinance")
+ .arg(portfolio_id, resp.error.left(200)));
+ QStringList symbols;
+ symbols.reserve(assets.size());
+ for (const auto& a : assets)
+ symbols.append(a.symbol);
+ MarketDataService::instance().fetch_quotes(symbols, [self, portfolio_id, assets,
+ portfolio](bool ok, QVector<QuoteData> quotes) {
+ if (!self)
+ return;
+ QHash<QString, QuoteData> qm;
+ if (ok)
+ for (const auto& q : quotes)
+ qm.insert(q.symbol, q);
+ self->finalize_summary(portfolio_id, assets, portfolio, qm);
+ });
+ return;
}
- h.market_value = h.quantity * h.current_price;
- h.unrealized_pnl = h.market_value - h.cost_basis;
- h.unrealized_pnl_percent = (h.cost_basis > 0) ? (h.unrealized_pnl / h.cost_basis) * 100.0 : 0;
-
- total_mv += h.market_value;
- total_cost += h.cost_basis;
- total_day += h.day_change * h.quantity;
+ self->finalize_summary(portfolio_id, assets, portfolio, quote_map);
+ }, Qt::QueuedConnection);
+ });
- if (h.unrealized_pnl >= 0)
- summary.gainers++;
- else
- summary.losers++;
+ return true; // broker path was taken
+}
- summary.holdings.append(h);
+void PortfolioService::finalize_summary(const QString& portfolio_id,
+ const QVector<portfolio::PortfolioAsset>& assets,
+ const portfolio::Portfolio& portfolio,
+ const QHash<QString, QuoteData>& quote_map) {
+ portfolio::PortfolioSummary summary;
+ summary.portfolio = portfolio;
+ summary.holdings.reserve(assets.size());
+
+ double total_mv = 0;
+ double total_cost = 0;
+ double total_day = 0;
+
+ for (const auto& asset : assets) {
+ portfolio::HoldingWithQuote h;
+ h.symbol = asset.symbol;
+ h.quantity = asset.quantity;
+ h.avg_buy_price = asset.avg_buy_price;
+ h.cost_basis = asset.quantity * asset.avg_buy_price;
+ // Prefer stored sector; fall back to resolver cache (which may
+ // populate async — see sector_resolved handler in constructor).
+ h.sector = asset.sector.isEmpty()
+ ? SectorResolver::instance().sector_for(asset.symbol)
+ : asset.sector;
+
+ auto it = quote_map.find(asset.symbol);
+ if (it != quote_map.end()) {
+ h.current_price = it->price;
+ h.day_change = it->change;
+ h.day_change_percent = it->change_pct;
+ } else {
+ // Fallback to avg buy price if no quote (broker missed the symbol,
+ // or yfinance returned nothing).
+ h.current_price = asset.avg_buy_price;
}
- // Compute weights
- for (auto& h : summary.holdings) {
- h.weight = (total_mv > 0) ? (h.market_value / total_mv) * 100.0 : 0;
- }
+ h.market_value = h.quantity * h.current_price;
+ h.unrealized_pnl = h.market_value - h.cost_basis;
+ h.unrealized_pnl_percent = (h.cost_basis > 0) ? (h.unrealized_pnl / h.cost_basis) * 100.0 : 0;
- summary.total_market_value = total_mv;
- summary.total_cost_basis = total_cost;
- summary.total_unrealized_pnl = total_mv - total_cost;
- summary.total_unrealized_pnl_percent = (total_cost > 0) ? ((total_mv - total_cost) / total_cost) * 100.0 : 0;
- summary.total_day_change = total_day;
- summary.total_day_change_percent =
- (total_mv - total_day > 0) ? (total_day / (total_mv - total_day)) * 100.0 : 0;
- summary.total_positions = assets.size();
- summary.last_updated = QDateTime::currentDateTimeUtc().toString(Qt::ISODate);
-
- // Cache the result (P11)
- {
- QMutexLocker lock(&self->cache_mutex_);
- self->summary_cache_[portfolio_id] = {summary, QDateTime::currentSecsSinceEpoch()};
- }
+ total_mv += h.market_value;
+ total_cost += h.cost_basis;
+ total_day += h.day_change * h.quantity;
- // Save snapshot for performance history
- QString today = QDate::currentDate().toString(Qt::ISODate);
- PortfolioRepository::instance().save_snapshot(portfolio_id, summary.total_market_value,
- summary.total_cost_basis, summary.total_unrealized_pnl,
- summary.total_unrealized_pnl_percent, today);
+ if (h.unrealized_pnl >= 0)
+ summary.gainers++;
+ else
+ summary.losers++;
- emit self->summary_loaded(summary);
- });
+ summary.holdings.append(h);
+ }
+
+ // Compute weights
+ for (auto& h : summary.holdings) {
+ h.weight = (total_mv > 0) ? (h.market_value / total_mv) * 100.0 : 0;
+ }
+
+ summary.total_market_value = total_mv;
+ summary.total_cost_basis = total_cost;
+ summary.total_unrealized_pnl = total_mv - total_cost;
+ summary.total_unrealized_pnl_percent = (total_cost > 0) ? ((total_mv - total_cost) / total_cost) * 100.0 : 0;
+ summary.total_day_change = total_day;
+ summary.total_day_change_percent =
+ (total_mv - total_day > 0) ? (total_day / (total_mv - total_day)) * 100.0 : 0;
+ summary.total_positions = assets.size();
+ summary.last_updated = QDateTime::currentDateTimeUtc().toString(Qt::ISODate);
+
+ // Cache the result (P11)
+ {
+ QMutexLocker lock(&cache_mutex_);
+ summary_cache_[portfolio_id] = {summary, QDateTime::currentSecsSinceEpoch()};
+ }
+
+ // Save snapshot for performance history
+ QString today = QDate::currentDate().toString(Qt::ISODate);
+ PortfolioRepository::instance().save_snapshot(portfolio_id, summary.total_market_value,
+ summary.total_cost_basis, summary.total_unrealized_pnl,
+ summary.total_unrealized_pnl_percent, today);
+
+ emit summary_loaded(summary);
}
// ── Asset operations ─────────────────────────────────────────────────────────
void PortfolioService::add_asset(const QString& portfolio_id, const QString& symbol, double qty, double price,
- const QString& date) {
+ const QString& date,
+ const QString& broker_symbol, const QString& exchange) {
auto& repo = PortfolioRepository::instance();
- auto r = repo.add_asset(portfolio_id, symbol, qty, price, date);
+ // Sector left empty here — SectorResolver fills it asynchronously after
+ // the asset lands in the DB. Broker fields pass through verbatim.
+ auto r = repo.add_asset(portfolio_id, symbol, qty, price, date, /*sector=*/QString(),
+ broker_symbol, exchange);
if (r.is_err()) {
LOG_ERROR("PortfolioSvc", "Failed to add asset: " + QString::fromStdString(r.error()));
return;
@@ -1052,32 +1196,65 @@ void PortfolioService::load_snapshots(const QString& portfolio_id, int days) {
}
}
-void PortfolioService::backfill_history(const QString& portfolio_id, const QString& period) {
+void PortfolioService::backfill_history(const QString& portfolio_id, const QString& /*period*/) {
if (portfolio_id.isEmpty())
return;
auto& repo = PortfolioRepository::instance();
- auto assets_r = repo.get_assets(portfolio_id);
- if (assets_r.is_err() || assets_r.value().isEmpty()) {
+
+ // Pull the full transaction history (not just the latest 50 — we need
+ // every BUY/SELL since the portfolio was created so the replay walks the
+ // whole timeline).
+ auto txns_r = repo.get_transactions(portfolio_id, /*limit=*/100000);
+ if (txns_r.is_err() || txns_r.value().isEmpty()) {
+ // No transactions → nothing to replay. Emit zero so callers don't wait.
emit history_backfilled(portfolio_id, 0);
return;
}
- const auto assets = assets_r.value();
+ const auto txns = txns_r.value();
+
+ // Serialize transactions to a temp JSON file. The Python side (action
+ // `portfolio_nav_history_replay`) reads it and walks the transactions in
+ // order to reconstruct daily position vectors and per-day cost basis.
+ // A file is used rather than CLI args because a portfolio with 500
+ // transactions × ~40 chars each would exceed Windows' 8191-char arg limit.
+ QJsonArray tx_arr;
+ for (const auto& t : txns) {
+ QJsonObject obj;
+ obj["date"] = t.transaction_date.left(10); // YYYY-MM-DD
+ obj["symbol"] = t.symbol;
+ obj["type"] = t.transaction_type;
+ obj["quantity"] = t.quantity;
+ obj["price"] = t.price;
+ tx_arr.append(obj);
+ }
- // Build the args list: [portfolio_nav_history, period, sym1, qty1, sym2, qty2, ...]
- // Cost basis is the same for every backfilled day (we don't have transaction-time
- // cost basis), so save_snapshot's pnl_pct uses today's cost — see comment below.
- QStringList args;
- args << "portfolio_nav_history" << period;
- double total_cost_basis = 0.0;
- for (const auto& a : assets) {
- args << a.symbol << QString::number(a.quantity, 'f', 8);
- total_cost_basis += a.quantity * a.avg_buy_price;
+ const QString tmp_dir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
+ QDir().mkpath(tmp_dir);
+ const QString tmp_path = QDir(tmp_dir).filePath(
+ QString("fincept_replay_%1_%2.json")
+ .arg(portfolio_id.left(16))
+ .arg(QDateTime::currentMSecsSinceEpoch()));
+
+ QFile f(tmp_path);
+ if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
+ LOG_WARN("PortfolioSvc", "backfill_history: cannot open temp file " + tmp_path);
+ emit history_backfilled(portfolio_id, 0);
+ return;
}
+ f.write(QJsonDocument(tx_arr).toJson(QJsonDocument::Compact));
+ f.close();
+
+ QStringList args;
+ args << "portfolio_nav_history_replay" << tmp_path;
QPointer<PortfolioService> self = this;
python::PythonRunner::instance().run("yfinance_data.py", args,
- [self, portfolio_id, total_cost_basis](python::PythonResult result) {
+ [self, portfolio_id, tmp_path](python::PythonResult result) {
+ // Always remove the temp file when we're done with it, regardless of
+ // success — leaks add up if a user re-imports often.
+ QFile::remove(tmp_path);
+
if (!self)
return;
if (!result.success || result.output.trimmed().isEmpty()) {
@@ -1101,28 +1278,32 @@ void PortfolioService::backfill_history(const QString& portfolio_id, const QStri
}
const auto dates = obj["dates"].toArray();
const auto navs = obj["navs"].toArray();
+ const auto costs = obj["costs"].toArray();
if (dates.isEmpty() || dates.size() != navs.size()) {
emit self->history_backfilled(portfolio_id, 0);
return;
}
+ const bool have_costs = (costs.size() == dates.size());
// Upsert each row. INSERT OR REPLACE keyed by (portfolio_id, snapshot_date)
- // so re-running backfill (with a different period or after the user adds
- // holdings) corrects existing rows in place.
+ // so re-running backfill corrects existing rows in place. Per-day cost
+ // basis comes from the replay (BUY adds, SELL reduces by WAC); falls
+ // back to NAV if the Python side didn't return a costs array.
auto& repo = PortfolioRepository::instance();
int written = 0;
for (int i = 0; i < dates.size(); ++i) {
const QString d = dates[i].toString();
const double nav = navs[i].toDouble();
- const double pnl = nav - total_cost_basis;
- const double pnl_pct = total_cost_basis > 0 ? (pnl / total_cost_basis) * 100.0 : 0.0;
- auto wr = repo.save_snapshot(portfolio_id, nav, total_cost_basis, pnl, pnl_pct, d);
+ const double cost_basis = have_costs ? costs[i].toDouble() : 0.0;
+ const double pnl = nav - cost_basis;
+ const double pnl_pct = cost_basis > 0 ? (pnl / cost_basis) * 100.0 : 0.0;
+ auto wr = repo.save_snapshot(portfolio_id, nav, cost_basis, pnl, pnl_pct, d);
if (wr.is_ok())
++written;
}
LOG_INFO("PortfolioSvc",
- QString("Backfilled %1 historical snapshots for %2").arg(written).arg(portfolio_id));
+ QString("Replayed %1 historical snapshots for %2").arg(written).arg(portfolio_id));
self->invalidate_cache(portfolio_id);
emit self->history_backfilled(portfolio_id, written);
});
diff --git a/fincept-qt/src/services/portfolio/PortfolioService.h b/fincept-qt/src/services/portfolio/PortfolioService.h
index c1272e2fd..4ebcde7d5 100644
--- a/fincept-qt/src/services/portfolio/PortfolioService.h
+++ b/fincept-qt/src/services/portfolio/PortfolioService.h
@@ -23,8 +23,12 @@ class PortfolioService : public QObject {
// ── Portfolio CRUD ───────────────────────────────────────────────────────
void load_portfolios();
+ /// `broker_account_id` links the new portfolio to a broker account so
+ /// PortfolioService routes live quotes via that broker instead of yfinance.
+ /// Empty for manual / JSON imports — yfinance fallback applies.
void create_portfolio(const QString& name, const QString& owner, const QString& currency,
- const QString& description = {});
+ const QString& description = {},
+ const QString& broker_account_id = {});
void delete_portfolio(const QString& id);
// ── Summary (assets + live quotes) ───────────────────────────────────────
@@ -32,8 +36,12 @@ class PortfolioService : public QObject {
void refresh_summary(const QString& portfolio_id); // invalidates cache first
// ── Asset operations ─────────────────────────────────────────────────────
+ /// `broker_symbol`+`exchange` are stored alongside the canonical
+ /// yfinance-format `symbol` so broker quote calls can use the native
+ /// pair. Both empty for manual / JSON imports.
void add_asset(const QString& portfolio_id, const QString& symbol, double qty, double price,
- const QString& date = {});
+ const QString& date = {},
+ const QString& broker_symbol = {}, const QString& exchange = {});
void sell_asset(const QString& portfolio_id, const QString& symbol, double qty, double price,
const QString& date = {});
@@ -137,6 +145,24 @@ class PortfolioService : public QObject {
void build_summary(const QString& portfolio_id, const QVector<portfolio::PortfolioAsset>& assets,
const portfolio::Portfolio& portfolio);
+ /// Common "I have quotes, build the summary and emit" path used by both
+ /// the broker and yfinance routes. quote_map is keyed by the asset's
+ /// canonical (yfinance) `symbol` field.
+ void finalize_summary(const QString& portfolio_id,
+ const QVector<portfolio::PortfolioAsset>& assets,
+ const portfolio::Portfolio& portfolio,
+ const QHash<QString, QuoteData>& quote_map);
+
+ /// Try to fetch live quotes via the broker linked to `portfolio.broker_account_id`.
+ /// On success, calls finalize_summary with broker-sourced QuoteData.
+ /// On any failure (no account, disconnected, broker null, API error),
+ /// silently falls back to the yfinance path. Returns true if the broker
+ /// path was attempted (even if it ultimately failed); false if we should
+ /// go straight to yfinance.
+ bool try_broker_quotes(const QString& portfolio_id,
+ const QVector<portfolio::PortfolioAsset>& assets,
+ const portfolio::Portfolio& portfolio);
+
// ── Summary cache (P11) ──────────────────────────────────────────────────
// In-memory (not CacheManager) intentionally: PortfolioSummary holds nested
// Portfolio + QVector<HoldingWithQuote>, which would require a large JSON
diff --git a/fincept-qt/src/storage/repositories/PortfolioRepository.cpp b/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
index 9c1b956eb..3f1c851f3 100644
--- a/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
+++ b/fincept-qt/src/storage/repositories/PortfolioRepository.cpp
@@ -24,6 +24,7 @@ portfolio::Portfolio PortfolioRepository::map_portfolio(QSqlQuery& q) {
q.value(4).toString(), // description
q.value(5).toString(), // created_at
q.value(6).toString(), // updated_at
+ q.value(7).toString(), // broker_account_id (v022)
};
}
@@ -31,12 +32,14 @@ portfolio::PortfolioAsset PortfolioRepository::map_asset(QSqlQuery& q) {
return {
q.value(0).toInt(), // id
q.value(1).toString(), // portfolio_id
- q.value(2).toString(), // symbol
+ q.value(2).toString(), // symbol (yfinance-format)
q.value(3).toDouble(), // quantity
q.value(4).toDouble(), // avg_buy_price
q.value(5).toString(), // first_purchase_date
q.value(6).toString(), // last_updated
q.value(7).toString(), // sector
+ q.value(8).toString(), // broker_symbol (v022)
+ q.value(9).toString(), // exchange (v022)
};
}
@@ -70,25 +73,33 @@ portfolio::PortfolioSnapshot PortfolioRepository::map_snapshot(QSqlQuery& q) {
// ── Portfolios CRUD ──────────────────────────────────────────────────────────
Result<QVector<portfolio::Portfolio>> PortfolioRepository::list_portfolios() {
- return query_list("SELECT id, name, owner, currency, description, created_at, updated_at "
+ return query_list("SELECT id, name, owner, currency, description, created_at, updated_at, "
+ "COALESCE(broker_account_id, '') "
"FROM portfolios ORDER BY name",
{}, map_portfolio);
}
Result<portfolio::Portfolio> PortfolioRepository::get_portfolio(const QString& id) {
- return query_one("SELECT id, name, owner, currency, description, created_at, updated_at "
+ return query_one("SELECT id, name, owner, currency, description, created_at, updated_at, "
+ "COALESCE(broker_account_id, '') "
"FROM portfolios WHERE id = ?",
{id}, map_portfolio);
}
Result<QString> PortfolioRepository::create_portfolio(const QString& name, const QString& owner,
- const QString& currency, const QString& description) {
+ const QString& currency, const QString& description,
+ const QString& broker_account_id) {
QString id = QUuid::createUuid().toString(QUuid::WithoutBraces);
- auto r = exec_write("INSERT INTO portfolios (id, name, owner, currency, description) VALUES (?, ?, ?, ?, ?)",
- {id, name, owner, currency, description});
+ auto r = exec_write(
+ "INSERT INTO portfolios (id, name, owner, currency, description, broker_account_id) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ {id, name, owner, currency, description, broker_account_id});
if (r.is_err())
return Result<QString>::err(r.error());
- LOG_INFO("PortfolioRepo", QString("Created portfolio '%1' (%2)").arg(name, id));
+ LOG_INFO("PortfolioRepo", QString("Created portfolio '%1' (%2)%3")
+ .arg(name, id,
+ broker_account_id.isEmpty() ? QString()
+ : QString(" [broker:%1]").arg(broker_account_id)));
return Result<QString>::ok(id);
}
@@ -109,20 +120,23 @@ Result<void> PortfolioRepository::delete_portfolio(const QString& id) {
Result<QVector<portfolio::PortfolioAsset>> PortfolioRepository::get_assets(const QString& portfolio_id) {
return query_list_as<portfolio::PortfolioAsset>(
"SELECT id, portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, last_updated, "
- "COALESCE(sector, '') "
+ "COALESCE(sector, ''), COALESCE(broker_symbol, ''), COALESCE(exchange, '') "
"FROM portfolio_assets WHERE portfolio_id = ? ORDER BY symbol",
{portfolio_id}, map_asset);
}
Result<qint64> PortfolioRepository::add_asset(const QString& portfolio_id, const QString& symbol, double qty,
- double price, const QString& date, const QString& sector) {
+ double price, const QString& date, const QString& sector,
+ const QString& broker_symbol, const QString& exchange) {
QString purchase_date = date.isEmpty() ? QDateTime::currentDateTimeUtc().toString(Qt::ISODate) : date;
// Upsert: if symbol already exists in portfolio, update quantity and avg price.
- // Preserve existing sector unless the caller provides a non-empty one.
+ // Preserve existing sector / broker_symbol / exchange unless the caller
+ // provides non-empty values (manual editors don't pass broker fields, so
+ // preserving prior values keeps a re-imported broker portfolio working).
auto existing = query_list_as<portfolio::PortfolioAsset>(
"SELECT id, portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, last_updated, "
- "COALESCE(sector, '') "
+ "COALESCE(sector, ''), COALESCE(broker_symbol, ''), COALESCE(exchange, '') "
"FROM portfolio_assets WHERE portfolio_id = ? AND symbol = ?",
{portfolio_id, symbol.toUpper()}, map_asset);
@@ -131,18 +145,20 @@ Result<qint64> PortfolioRepository::add_asset(const QString& portfolio_id, const
double new_qty = asset.quantity + qty;
double new_avg = ((asset.avg_buy_price * asset.quantity) + (price * qty)) / new_qty;
QString merged_sector = sector.isEmpty() ? asset.sector : sector;
+ QString merged_broker_symbol = broker_symbol.isEmpty() ? asset.broker_symbol : broker_symbol;
+ QString merged_exchange = exchange.isEmpty() ? asset.exchange : exchange;
auto r = exec_write("UPDATE portfolio_assets SET quantity = ?, avg_buy_price = ?, sector = ?, "
- "last_updated = datetime('now') WHERE id = ?",
- {new_qty, new_avg, merged_sector, asset.id});
+ "broker_symbol = ?, exchange = ?, last_updated = datetime('now') WHERE id = ?",
+ {new_qty, new_avg, merged_sector, merged_broker_symbol, merged_exchange, asset.id});
if (r.is_err())
return Result<qint64>::err(r.error());
return Result<qint64>::ok(static_cast<qint64>(asset.id));
}
return exec_insert(
- "INSERT INTO portfolio_assets (portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, sector) "
- "VALUES (?, ?, ?, ?, ?, ?)",
- {portfolio_id, symbol.toUpper(), qty, price, purchase_date, sector});
+ "INSERT INTO portfolio_assets (portfolio_id, symbol, quantity, avg_buy_price, first_purchase_date, "
+ "sector, broker_symbol, exchange) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ {portfolio_id, symbol.toUpper(), qty, price, purchase_date, sector, broker_symbol, exchange});
}
Result<void> PortfolioRepository::set_asset_sector(const QString& portfolio_id, const QString& symbol,
diff --git a/fincept-qt/src/storage/repositories/PortfolioRepository.h b/fincept-qt/src/storage/repositories/PortfolioRepository.h
index f73324f07..13a13ac42 100644
--- a/fincept-qt/src/storage/repositories/PortfolioRepository.h
+++ b/fincept-qt/src/storage/repositories/PortfolioRepository.h
@@ -12,16 +12,25 @@ class PortfolioRepository : public BaseRepository<portfolio::Portfolio> {
// ── Portfolios CRUD ──────────────────────────────────────────────────────
Result<QVector<portfolio::Portfolio>> list_portfolios();
Result<portfolio::Portfolio> get_portfolio(const QString& id);
+ /// `broker_account_id` ties this portfolio to a broker account so live
+ /// quotes can be sourced from the broker instead of yfinance. Empty for
+ /// manually-created / JSON-imported portfolios. See migration v022.
Result<QString> create_portfolio(const QString& name, const QString& owner, const QString& currency,
- const QString& description = {});
+ const QString& description = {},
+ const QString& broker_account_id = {});
Result<void> update_portfolio(const QString& id, const QString& name, const QString& owner, const QString& currency,
const QString& description = {});
Result<void> delete_portfolio(const QString& id);
// ── Assets CRUD ──────────────────────────────────────────────────────────
Result<QVector<portfolio::PortfolioAsset>> get_assets(const QString& portfolio_id);
+ /// `broker_symbol` + `exchange` are the broker-native pair (e.g.
+ /// "RELIANCE" + "NSE"); both empty for manual / JSON imports. The
+ /// canonical `symbol` arg stays in yfinance-format ("RELIANCE.NS")
+ /// regardless — every downstream consumer treats it as such.
Result<qint64> add_asset(const QString& portfolio_id, const QString& symbol, double qty, double price,
- const QString& date = {}, const QString& sector = {});
+ const QString& date = {}, const QString& sector = {},
+ const QString& broker_symbol = {}, const QString& exchange = {});
Result<void> update_asset(const QString& portfolio_id, const QString& symbol, double qty, double avg_price);
Result<void> set_asset_sector(const QString& portfolio_id, const QString& symbol, const QString& sector);
Result<void> remove_asset(const QString& portfolio_id, const QString& symbol);
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index 06397b96c..4894b3a79 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -68,5 +68,6 @@ void register_migration_v018();
void register_migration_v019();
void register_migration_v020();
void register_migration_v021();
+void register_migration_v022();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v022_portfolio_broker_link.cpp b/fincept-qt/src/storage/sqlite/migrations/v022_portfolio_broker_link.cpp
new file mode 100644
index 000000000..9c449e0e4
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v022_portfolio_broker_link.cpp
@@ -0,0 +1,98 @@
+// v022_portfolio_broker_link — Link portfolios to broker accounts for
+// broker-first live quote routing.
+//
+// Background: PortfolioService::build_summary fetches live prices via
+// MarketDataService → yfinance for every portfolio. For portfolios that
+// were imported from a connected broker (e.g. Zerodha), yfinance is a 15
+// minute-delayed and frequently incomplete fallback when the user has
+// already authenticated with a broker that provides true live ticks.
+//
+// This migration adds three columns:
+// - portfolios.broker_account_id — FK-ish to broker_accounts.id (kept
+// loose so portfolios survive account deletion). Empty = manual / non-
+// broker portfolio. yfinance path is preserved for these.
+// - portfolio_assets.broker_symbol — broker-native ticker (e.g. "RELIANCE")
+// - portfolio_assets.exchange — exchange code (e.g. "NSE")
+//
+// PortfolioAsset.symbol stays in yfinance format ("RELIANCE.NS") so every
+// existing downstream consumer (sparklines, correlation, NAV replay, news,
+// SectorResolver) keeps working unchanged. Live quote routing in
+// PortfolioService picks broker_symbol+exchange when broker_account_id is
+// present; everything else continues to read .symbol.
+//
+// Existing rows get '' defaults — backwards compatible.
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+// NOTE: static helpers are renamed v022_* on purpose — Unity builds may
+// concatenate multiple migration .cpp files into a single TU, and an
+// anonymous-namespace `sql()` here would clash with the same symbol in v019
+// or v021. The unity-build namespace trap is a documented gotcha for this
+// codebase; rename or move into per-migration anonymous-namespaces. We pick
+// rename so the file is grep-able by version.
+static Result<void> v022_sql(QSqlDatabase& db, const char* stmt) {
+ QSqlQuery q(db);
+ if (!q.exec(stmt))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+static bool v022_column_exists(QSqlDatabase& db, const QString& table, const QString& column) {
+ QSqlQuery q(db);
+ q.exec(QString("PRAGMA table_info(%1)").arg(table));
+ while (q.next()) {
+ if (q.value(1).toString().compare(column, Qt::CaseInsensitive) == 0)
+ return true;
+ }
+ return false;
+}
+
+Result<void> apply_v022(QSqlDatabase& db) {
+ // SQLite ALTER TABLE ADD COLUMN does not support IF NOT EXISTS.
+ // Use PRAGMA table_info to skip already-present columns (matches v019).
+ if (!v022_column_exists(db, "portfolios", "broker_account_id")) {
+ auto r = v022_sql(db, "ALTER TABLE portfolios ADD COLUMN broker_account_id TEXT DEFAULT ''");
+ if (r.is_err())
+ return r;
+ }
+
+ if (!v022_column_exists(db, "portfolio_assets", "broker_symbol")) {
+ auto r = v022_sql(db, "ALTER TABLE portfolio_assets ADD COLUMN broker_symbol TEXT DEFAULT ''");
+ if (r.is_err())
+ return r;
+ }
+
+ if (!v022_column_exists(db, "portfolio_assets", "exchange")) {
+ auto r = v022_sql(db, "ALTER TABLE portfolio_assets ADD COLUMN exchange TEXT DEFAULT ''");
+ if (r.is_err())
+ return r;
+ }
+
+ // Lookup index for "find all portfolios for this broker account" queries.
+ // Cheap on small tables, useful when the broker disconnect dialog wants
+ // to show "you have N portfolios using this account".
+ auto r = v022_sql(db, "CREATE INDEX IF NOT EXISTS idx_portfolios_broker_account "
+ "ON portfolios(broker_account_id)");
+ if (r.is_err())
+ return r;
+
+ return Result<void>::ok();
+}
+
+} // anonymous namespace
+
+void register_migration_v022() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({22, "portfolio_broker_link", apply_v022});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/ui/error/ErrorPipeline.cpp b/fincept-qt/src/ui/error/ErrorPipeline.cpp
index 0f8b44d8c..c2aefb54e 100644
--- a/fincept-qt/src/ui/error/ErrorPipeline.cpp
+++ b/fincept-qt/src/ui/error/ErrorPipeline.cpp
@@ -29,7 +29,7 @@ void ErrorPipeline::report_panel_error(const QString& panel_id, Severity sev,
}
void ErrorPipeline::clear_panel_errors(const QString& panel_id) {
- if (panel_errors_.remove(panel_id) > 0)
+ if (panel_errors_.remove(panel_id))
emit panel_errors_changed(panel_id);
}
@@ -54,7 +54,7 @@ void ErrorPipeline::report_shell_error(const QString& category, Severity sev,
}
void ErrorPipeline::clear_shell_error(const QString& category) {
- if (shell_errors_.remove(category) > 0)
+ if (shell_errors_.remove(category))
emit shell_errors_changed();
}
diff --git a/fincept-qt/src/ui/navigation/StatusBar.h b/fincept-qt/src/ui/navigation/StatusBar.h
index 36781d5bc..a49f788be 100644
--- a/fincept-qt/src/ui/navigation/StatusBar.h
+++ b/fincept-qt/src/ui/navigation/StatusBar.h
@@ -4,7 +4,7 @@
#include <QWidget>
namespace fincept {
-class SymbolRef;
+struct SymbolRef;
enum class SymbolGroup : char;
} // namespace fincept