From dc703e1bb8e0604dfa9238f89edf548016e9c9d1 Mon Sep 17 00:00:00 2001 From: Antigravity Agent Date: Sat, 13 Jun 2026 13:59:29 +0200 Subject: [PATCH] Closes #014 - System-wide handbook sweep, English consolidation & Crypto state persistence --- DEV_LOG.md | 18 + QUANT_ROADMAP.md | 23 ++ app/page.tsx | 16 +- components/modules/crypto/CryptoDemo.tsx | 384 +++++++++++++++--- .../modules/events/EconometricsMathModal.tsx | 53 +-- components/modules/events/EventsDemo.tsx | 35 +- components/modules/insider/InsiderDemo.tsx | 138 +++---- .../modules/insider/InsiderMathModal.tsx | 21 +- .../modules/macro/MacroIndicatorsDemo.tsx | 76 ++-- .../modules/sandbox/PortfolioMathModal.tsx | 115 ------ components/modules/sandbox/SandboxDemo.tsx | 226 +++++------ .../modules/sandbox/SandboxMathModal.tsx | 135 ++++++ components/modules/scanner/ScannerDemo.tsx | 14 +- .../modules/scanner/ScannerMathModal.tsx | 41 +- components/modules/tech/AiSpecialSilo.tsx | 6 +- components/modules/tech/TechMathModal.tsx | 12 +- components/modules/whale/WhaleMathModal.tsx | 6 +- components/modules/whale/WhaleScreener.tsx | 8 +- 18 files changed, 839 insertions(+), 488 deletions(-) delete mode 100644 components/modules/sandbox/PortfolioMathModal.tsx create mode 100644 components/modules/sandbox/SandboxMathModal.tsx diff --git a/DEV_LOG.md b/DEV_LOG.md index 0287813..9498584 100644 --- a/DEV_LOG.md +++ b/DEV_LOG.md @@ -122,3 +122,21 @@ This document tracks all modifications, npm packages, active compilation states, ### Active Bugs / Compile Status * **Active Bugs**: None. * **Type Checker Status**: Verified clean compilation (`npx tsc --noEmit` returns exit code 0). + +--- + +## [2026-06-13] - System-Wide Handbook Sweep, English Consolidation & Crypto State Persistence (#ISSUE-014) + +### Added +* **Sandbox Math Handbook**: Created `components/modules/sandbox/SandboxMathModal.tsx` detailing the Kelly Criterion, Half-Kelly safety buffers, percentage weightings (\(w_i\)), and synthetic portfolio returns (\(R_{pt}\)) in double-escaped BlockMath LaTeX. +* **Crypto Online Learning Loop**: Integrated a client-side background evaluation routine inside `components/modules/crypto/CryptoDemo.tsx` that resolves active forecasts against price histories from `/api/finance?region=crypto` and updates the Bayesian online calibration parameters. + +### Modified +* **KaTeX Escaping & Close Handler Audit**: Standardized all 8 math handbook modals with Escape key listeners and glassmorphic floating top-right "X" buttons. Repaired all escaping sequences for KaTeX rendering strings across all components. +* **100% Institutional English Translation**: Swapped all remaining German UI texts, buttons (e.g. `📖 Modulerklärung` renamed to `📖 Quantitative Handbook`), table cells, and warnings to professional English across all tabs (`Smart Money`, `Events/Econometrics`, `Macro`, `Tech Silo`, `Sandbox`, `Scanner`). +* **Next.js SSR Hydration Safeguard**: Wrapped `localStorage` operations for `alphaSuccess`, `betaFailure`, and active forecasts inside a React `useEffect` hook in `CryptoDemo.tsx` to prevent hydration mismatches. +* **`QUANT_ROADMAP.md`**: Updated Section 1 and Section 4.VI detailing the Sandbox Portfolio and Kelly sizing formulations. + +### Active Bugs / Compile Status +* **Active Bugs**: None. +* **Type Checker Status**: Verified clean compilation (`npx tsc --noEmit` returns exit code 0). diff --git a/QUANT_ROADMAP.md b/QUANT_ROADMAP.md index 67dcaef..e91770b 100644 --- a/QUANT_ROADMAP.md +++ b/QUANT_ROADMAP.md @@ -197,6 +197,29 @@ $$P_{\text{Posterior}} = \frac{\alpha_{\text{prior}} + (P_{\text{ML}} \times w)} --- +### VI. Sandbox Portfolio Cockpit & Kelly Sizing + +Integrates fractional betting algorithms and asset weight models inside the active Portfolio Sandbox environment. + +#### 1. Active Portfolio Weighting ($w_i$) +Calculates the dynamic percentage value allocation of constituent assets: +$$w_i = \frac{\text{Shares}_i \times P_{\text{current}, i}}{\sum_{j} \text{Shares}_j \times P_{\text{current}, j}}$$ + +#### 2. Synthetic Portfolio Return ($R_{pt}$) +Simulates active log returns of the combined holdings: +$$R_{pt} = \sum_{i} w_i \times \ln\left(\frac{P_{t, i}}{P_{t-1, i}}\right)$$ + +#### 3. Theoretical Kelly Sizing ($f^*$) +Calculates the optimal size fraction to maximize the log growth of capital: +$$f^* = \frac{p \cdot b - (1 - p)}{b}$$ +Where $p$ is the probability of success, and $b$ is the payout odds ratio (average win/average loss). + +#### 4. Half-Kelly Safety Buffer Sizing +Applies a fractional buffer to lower estimation variance and protect against drawdowns: +$$f_{\text{applied}} = \max\left(0, 0.5 \times f^*\right)$$ + +--- + ## 5. Multi-Regime Transition Classifier The core cognitive brain of the sandbox dynamically adjusts allocation weights across our portfolio modules based on estimated macroeconomic and market states. diff --git a/app/page.tsx b/app/page.tsx index e878e9e..f4234f5 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -30,16 +30,16 @@ export default function Home() {

- QuantSandbox Ökonometrie + QuantSandbox Econometrics

-

KI-gestützte Investment-Sandbox

+

AI-Powered Investment Sandbox

- Verbindung aktiv + Connection Active
Workspace: @@ -58,10 +58,10 @@ export default function Home() { Scaffolding Version 1.0.0

- Statistische Investment-Analyse & Sandbox + Statistical Investment Analysis & Sandbox

- Diese modulare Architektur bündelt fortgeschrittene ökonometrische Modelle – von EWMA und GJR-GARCH Volatilitätsprognosen über Bayesianisches On-Chain-Lernen bis hin zu Überlebens- und LMM-Regressionsmodellen. + This modular architecture pools advanced econometric models – from EWMA and GJR-GARCH volatility forecasts to Bayesian on-chain learning, survival analysis, and LMM panel regressions.

@@ -88,13 +88,13 @@ export default function Home() { onClick={() => setActiveTab('crypto')} className={`flex-1 lg:flex-none px-4 py-2.5 rounded-xl text-xs font-semibold flex items-center justify-center gap-2 transition-all ${activeTab === 'crypto' ? 'bg-gradient-to-r from-cyan-500 to-sky-500 text-slate-950 font-bold shadow-lg shadow-cyan-500/25' : 'text-slate-400 hover:text-slate-200 hover:bg-slate-900/50'}`} > - Krypto Bayes + Crypto Bayes
-

A-Priori Genauigkeit

+

Prior Accuracy

{priorAccuracy.toFixed(1)}% (n={totalTrials})

@@ -245,7 +456,7 @@ export default function CryptoDemo() { setSearchQuery(e.target.value)} @@ -279,14 +490,14 @@ export default function CryptoDemo() { {/* Left Column: Metrics Widgets */}

- On-Chain & Derivate-Indikatoren ({activeCoin.ticker}) + On-Chain & Derivative Indicators ({activeCoin.ticker})

{/* Funding & Open Interest Widget */}
-

Ref-Zinssatz & Kontrakte (OI)

+

Funding Rates & Open Interest

Daily Funding Rate: @@ -305,14 +516,14 @@ export default function CryptoDemo() { {/* Long/Short & Liquidation Widget */}
-

Positionierung & Liquidationen

+

Positioning & Liquidations

Long / Short Ratio: {activeCoin.longShortRatio}
- Liq-Cluster: + Liq Cluster: Long: {activeCoin.liqLong} | Short: {activeCoin.liqShort}
@@ -320,32 +531,32 @@ export default function CryptoDemo() { {/* Whale Flows Widget */}
-

Whale-Ströme (Nettozufluss)

+

Whale Flows (Net Inflow)

- Netto Inflow (Wallets): + Net Inflow (Wallets): = 0 ? 'text-emerald-400' : 'text-rose-400'}`}> {activeCoin.whaleInflow > 0 ? '+' : ''}{activeCoin.whaleInflow} {activeCoin.ticker}
- Positive Werte signalisieren, dass Großinvestoren Bestände von Börsen auf private Wallets (Akkumulation) abziehen. + Positive values signal that large investors are withdrawing assets from exchanges to private wallets (accumulation).
{/* Exchange Reserves Widget */}
-

Börsenreserven (Spot)

+

Exchange Reserves (Spot)

- Reservenänderung (7d): + Reserve Change (7d): {activeCoin.exchangeReserves > 0 ? '+' : ''}{activeCoin.exchangeReserves}%
- Sinkende Reserven an den Spot-Börsen reduzieren den verfügbaren Verkaufsdruck und begünstigen Squeezes. + Falling reserves at spot exchanges reduce available selling pressure and favor squeezes.
@@ -356,7 +567,7 @@ export default function CryptoDemo() { {/* Right Column: Predictive Gauges & Correction Calibration */}

- Vorhersage-Wahrscheinlichkeiten + Prediction Probabilities

{/* Gauges / Progress Bars */} @@ -369,27 +580,25 @@ export default function CryptoDemo() { {(correctedPredictions.shortTerm * 100).toFixed(0)}%
- {/* ML Baseline Overlay */}
- {/* Corrected Posterior Marker */}
- ML-Signal: {(mlPredictions.shortTermProb * 100).toFixed(0)}% - Bayes-Korrigiert: {(correctedPredictions.shortTerm * 100).toFixed(0)}% + ML Signal: {(mlPredictions.shortTermProb * 100).toFixed(0)}% + Bayes Corrected: {(correctedPredictions.shortTerm * 100).toFixed(0)}%
{/* 14d Gauge */}
- 14d Struktureller Bullish-Trend (Medium-Term) + 14d Structural Bullish Trend (Medium-Term) {(correctedPredictions.mediumTerm * 100).toFixed(0)}%
@@ -403,8 +612,8 @@ export default function CryptoDemo() { />
- ML-Signal: {(mlPredictions.mediumTermProb * 100).toFixed(0)}% - Bayes-Korrigiert: {(correctedPredictions.mediumTerm * 100).toFixed(0)}% + ML Signal: {(mlPredictions.mediumTermProb * 100).toFixed(0)}% + Bayes Corrected: {(correctedPredictions.mediumTerm * 100).toFixed(0)}%
@@ -413,88 +622,161 @@ export default function CryptoDemo() { {/* Model Calibration Log & Simulation */}
-

Bayes Modell-Kalibrierung

+

Bayes Model Calibration

n = {totalTrials} Trials
-
Erfolge (α):
+
Successes (α):
{alphaSuccess}
-
Fehlalarme (β):
+
False Alarms (β):
{betaFailure}
{/* Trial simulator */}
-

Modell-Drift simulieren: Fügen Sie richtige/falsche Outcomes hinzu, um die Beta-Verteilung anzupassen.

+

Simulate model drift: Add correct/false outcomes to calibrate the Beta distribution.

{simulatedTrialLogged && (
- Trial geloggt! Bayes-Prior wurde auf {lastTrialSuccess ? 'Erfolg' : 'Fehlalarm'} aktualisiert. + Trial logged! Bayes prior updated to {lastTrialSuccess ? 'Success' : 'False Alarm'}.
)}
-
- {/* SECTION 3: Mathematical LaTeX Accordion */} + {/* SECTION 3: Active Forecasts (Feedback Loop) */} +
+
+
+

+ Active Learning Feedback Loop +

+ +
+ + {learningLoopLog && ( +
+ + {learningLoopLog} +
+ )} + +
+ + + + + + + + + + + + + {forecasts.length === 0 ? ( + + + + ) : ( + forecasts.map((fc) => ( + + + + + + + + + )) + )} + +
TickerDirectionProbabilityEntry PriceStatusResult
No forecasts registered yet.
{fc.ticker} + + {fc.predictedDirection} + + {(fc.predictedProb * 100).toFixed(0)}%${fc.entryPrice.toLocaleString()}{fc.resolved ? 'RESOLVED' : 'PENDING'} + {fc.result || '-'} +
+
+
+ + {/* Informational overlay */} +
+

Econometric Feedback Loop Spec

+

+ The learning loop automatically evaluates active forecast parameters in the background against actual price histories returned by /api/finance?region=crypto. +

+

+ When a logged forecast passes its evaluation target timestamp, it resolves against live market data, updating the Bayesian online calibration metrics and . +

+
+
+ + {/* SECTION 4: Mathematical LaTeX Accordion */}
{showMathAccordion && (
-

1. Bayesianische Beta-Konjugierte Fehlerkorrektur

+

1. Bayesian Beta-Conjugate Error Correction

- Wir modellieren das Vertrauensintervall über die Fehlerraten des Modells mittels einer Beta-Verteilung. Der A-Priori Fehlerzustand wird durch die Parameter (Erfolge) und (Fehlalarme) dargestellt: + We model the error rate confidence interval of the model using a Beta distribution. The prior error state is represented by the parameters (Successes) and (False Alarms):

- +

- Bei einem neuen ML-Signal führen wir ein konjugiertes Bayes-Update mit einem Vertrauensgewicht aus: + With a new ML signal , we perform a conjugate Bayes update with a confidence weight :

- +
- +

- Ist das Modell historisch sehr instabil (hohes ), korrigiert der Bayesianische Term ein übermütiges ML-Signal nach unten, was die Robustheit des Gesamtsystems schützt. + If the model is historically highly unstable (high ), the Bayesian term corrects an overconfident ML signal downwards, safeguarding the robustness of the system.

-

2. Random Forest Nicht-Lineares Signalmapping

+

2. Random Forest Non-Linear Signal Mapping

- Der Random Forest simuliert ein Ensemble von 10 schwachen Entscheidungsbäumen. Jeder Baum spaltet die Daten nach Schwellenwerten (z.B. „Funding-Rate < -0.04%“ und „Open Interest > 10%“) auf: + The Random Forest simulates an ensemble of 10 weak decision trees. Each tree splits the data based on threshold criteria (e.g., 'Funding Rate < -0.04%' and 'Open Interest > 10%'):

- +

- wobei der prognostizierte Ausgabewert des -ten Entscheidungsbaumes für den Featurevektor ist. + where is the predicted output value of the -th decision tree for the feature vector .

diff --git a/components/modules/events/EconometricsMathModal.tsx b/components/modules/events/EconometricsMathModal.tsx index 38b00a1..d9e26ce 100644 --- a/components/modules/events/EconometricsMathModal.tsx +++ b/components/modules/events/EconometricsMathModal.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import { BookOpen } from 'lucide-react'; +import { BookOpen, X } from 'lucide-react'; import 'katex/dist/katex.min.css'; import { BlockMath, InlineMath } from 'react-katex'; @@ -26,8 +26,8 @@ export default function EconometricsMathModal({ isOpen, onClose }: EconometricsM if (!isOpen) return null; return ( -
-
+
+
{/* Modal Header */}
@@ -39,9 +39,10 @@ export default function EconometricsMathModal({ isOpen, onClose }: EconometricsM
@@ -69,10 +70,10 @@ export default function EconometricsMathModal({ isOpen, onClose }: EconometricsM

B. Endogenous Calibration

- Active future matrix cells pre-fill suggested scores by looking up the corresponding historical LMM coefficient and scaling it to our native score scale: + Active future matrix cells pre-fill suggested scores by looking up the corresponding historical LMM coefficient and scaling it to our native score scale:

- +
@@ -82,13 +83,17 @@ export default function EconometricsMathModal({ isOpen, onClose }: EconometricsM The engine estimates direct event drift and impact returns, isolating asset-level intercepts as random deviances and purging macro volatility using VIX indices:

- +

- Where:
- - is the log-return of asset at relative index .
- - design matrix elements isolate Pre-Event Drift () and Post-Event Impact () while controlling for systemic covariates (VIX).
- - random intercept captures unique baseline asset variance.
- - residuals noise. + {"Where:"} +
+ {"- "}{" is the log-return "}{" of asset "}{" at relative index "}{"."} +
+ {"- "}{" design matrix elements isolate Pre-Event Drift ("}{") and Post-Event Impact ("}{") while controlling for systemic covariates (VIX)."} +
+ {"- "}{" random intercept captures unique baseline asset variance."} +
+ {"- "}{" residuals noise."}

@@ -101,15 +106,15 @@ export default function EconometricsMathModal({ isOpen, onClose }: EconometricsM

Logistic Probability Projection:

- +

Optimal Youden Index (J):

- +
-

Inverting probability optimal threshold back to native score via Logit:

- +

{"Inverting probability optimal threshold "}{" back to native score "}{" via Logit:"}

+
@@ -121,16 +126,18 @@ export default function EconometricsMathModal({ isOpen, onClose }: EconometricsM

- -

- Where:
- - is the number of active asset-run observations at risk at day .
- - is the number of trend-reversal events recorded on day . + +

+ {"Where:"} +
+ {"- "}{" is the number of active asset-run observations at risk at day "}{"."} +
+ {"- "}{" is the number of trend-reversal events recorded on day "}{"."}

Reversal trigger with 1% Volatility Buffer:

- +
diff --git a/components/modules/events/EventsDemo.tsx b/components/modules/events/EventsDemo.tsx index bd21c48..fa0b713 100644 --- a/components/modules/events/EventsDemo.tsx +++ b/components/modules/events/EventsDemo.tsx @@ -43,20 +43,20 @@ import { // Predefined archetypes for Event Creation const ARCHETYPES: Record }> = { - '🏦 Fed-Zinsentscheid (FOMC)': { - name: 'Fed-Zinsentscheid (FOMC)', + '🏦 Fed Rate Decision (FOMC)': { + name: 'Fed Rate Decision (FOMC)', defaultScores: { Apple: 1, NASDAQ: 2, Gold: -1, Bitcoin: 2 } }, - '📈 US-Inflationsdaten (CPI)': { - name: 'US-Inflationsdaten (CPI)', + '📈 US Inflation Data (CPI)': { + name: 'US Inflation Data (CPI)', defaultScores: { Apple: 1, NASDAQ: 2, Gold: -2, Bitcoin: 1 } }, '💼 Non-Farm Payrolls (NFP)': { name: 'Non-Farm Payrolls (NFP)', defaultScores: { Apple: 0, NASDAQ: 1, Gold: -1, Bitcoin: 0 } }, - '🛒 OPEC-Treffen': { - name: 'OPEC-Treffen', + '🛒 OPEC Meeting': { + name: 'OPEC Meeting', defaultScores: { Apple: -1, NASDAQ: -1, Gold: 2, Bitcoin: 1 } } }; @@ -258,7 +258,6 @@ export default function EventsDemo() { - // Custom Event Form State const [customName, setCustomName] = useState(''); const [customDate, setCustomDate] = useState('2026-06-15'); const [selectedArchetype, setSelectedArchetype] = useState('Custom'); @@ -522,7 +521,7 @@ export default function EventsDemo() { scores[asset.name] = typeof arch.defaultScores[asset.name] === 'number' ? arch.defaultScores[asset.name] : 0; }); } else { - name = name || 'Benutzerdefiniertes Ereignis'; + name = name || 'Custom Event'; } addEventToMatrix(name, customDate, scores); @@ -608,7 +607,7 @@ export default function EventsDemo() { className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-slate-950/80 hover:bg-slate-905 border border-slate-800 hover:border-slate-700 transition-all font-semibold text-xs tracking-wider text-rose-400" > - 📖 Modulerklärung + 📖 Quantitative Handbook
@@ -630,7 +629,7 @@ export default function EventsDemo() {
setNewTickerInput(e.target.value)} className="bg-transparent text-[11px] text-slate-200 focus:outline-none px-2 py-0.5 w-24 uppercase font-mono" @@ -664,7 +663,7 @@ export default function EventsDemo() { @@ -687,7 +686,7 @@ export default function EventsDemo() { {ev.date} - {d === 0 ? 'Heute' : d > 0 ? `In ${d} Tagen` : `Vor ${-d} Tagen`} + {d === 0 ? 'Today' : d > 0 ? `In ${d} days` : `${-d} days ago`} @@ -750,7 +749,7 @@ export default function EventsDemo() { @@ -1082,7 +1081,7 @@ export default function EventsDemo() { {calibrationSuccess && (
- Kalibrierung erfolgreich abgeschlossen! + Calibration successfully completed!
)} @@ -1101,7 +1100,7 @@ export default function EventsDemo() { {lastCalibrationTime && (
- Letzter Durchlauf: {lastCalibrationTime} ({lmmObservations.length} Obs.) + Last run: {lastCalibrationTime} ({lmmObservations.length} Obs.)
)}
@@ -1169,7 +1168,7 @@ export default function EventsDemo() {

- + setSearchQuery(e.target.value)} @@ -331,31 +331,31 @@ export default function InsiderDemo() {
-

{selectedTicker} Einzelauswertung

+

{selectedTicker} Single Evaluation

{tickerStats.isAnomaly && FLOW OUTLIER}
- Volumetrischer Z-Score: + Volumetric Z-Score: Z = {tickerStats.zScore.toFixed(2)}
- Konzertiertes Cluster (14 Tage): + Concerted Cluster (14 Days): - {tickerStats.isCluster ? `JA (${tickerStats.clusterCount} Insiders)` : `NEIN (${tickerStats.clusterCount})`} + {tickerStats.isCluster ? `YES (${tickerStats.clusterCount} Insiders)` : `NO (${tickerStats.clusterCount})`}
{tickerStats.isCluster && (
- Cluster Exponent-Multiplikator: + Cluster Exponent Multiplier: x{tickerStats.multiplier.toFixed(2)}
)}
- Gekoppelte Rebound-Wahrsch.: + Coupled Rebound Prob.: {(tickerStats.coupledRebound * 100).toFixed(0)}% @@ -366,14 +366,14 @@ export default function InsiderDemo() { {/* Volume chart */}
-
Insider Handelsvolumen (24 Monate Baseline)
+
Insider Trading Volume (24-Month Baseline)
- +
@@ -383,12 +383,12 @@ export default function InsiderDemo() { {/* Global Scan Outlier List */} {scanResults && (
-

Ergebnisse des Global Flow Scans

+

Global Flow Scan Results

{scanResults.length === 0 ? (
-

Keine signifikanten Volumen-Anomalien gefunden

-

Es wurden keine Transaktionen mit einem berechneten volumetric Z-Score > 2.0 in den aktiven Live-Feeds identifiziert.

+

No Significant Volume Anomalies Found

+

No transactions with a calculated volumetric Z-Score > 2.0 were identified in the active live feeds.

) : (
@@ -421,13 +421,13 @@ export default function InsiderDemo() { onClick={() => setActiveSegment('executives')} className={`flex-1 py-2 rounded-lg text-xs font-semibold font-sans transition-all flex items-center justify-center gap-1.5 ${activeSegment === 'executives' ? 'bg-purple-500 text-white font-bold' : 'text-slate-400 hover:text-slate-200'}`} > - Vorstände (Form 4) + Executives (Form 4)