Add causal EWMA forecasts, implied volatility and audited jump distributions
Browse filesFiles changed (11)
- IMPLEMENTATION.mdAdded+10
- METHODS.md+18
- README.md+8
- VERIFICATION.mdAdded+7
- app.js+9-2
- index.html+7-6
- model.js+16-7
- scenarios.jsAdded+95
- style.css+2
- test_model.cjs+16
- test_scenarios.cjsAdded+39
12345678910# Quantmind-inspired extensions · 25 October 2026
Approved scope: add EWMA volatility challenger, bracketed implied volatility, and a normal-jump distribution explorer while keeping the existing public Static Space free and CSV processing local.
1. model.js/test_model.cjs: fixed20-observation half-life, prequential ridge-residual variance, temperature/model selection on calibration only; own labels cannot update own variance. Annualized display assumes252 equal-length observations, with gaps qualified.2. scenarios.js/test_scenarios.cjs: independently written Black–Scholes bisection with arbitrage bounds; explicit user-specified Merton-style compensated jump diffusion, Gaussian moment match, Poisson truncation mass and finite-grid mass reporting. No scenario calibration or directional edge claim.3. index.html/app.js/style.css: expose challenger metadata, implied-vol form and dedicated PDF/CDF scenario workbench with accessible input errors and units.4. Update method/provenance notes; run baseline and extension tests, independent numerical/chronology checks, browser synthetic/CSV/scenario/error flows and responsive inspection; update existing public HF repository after verification.
No Quantmind source is vendored and no upstream dependency is installed. Standard algorithms are implemented independently; upstream documentation motivated scope. Preserve the saved Python benchmark as historical/precomputed, with its original candidate set. Python bundle is a separate prior release unless explicitly updated. No paid compute or service enabled.46 unmodified lines47484946 unmodified linesChronological splitting reduces a specific kind of leakage; it does not eliminate nonstationarity, dependence, survivorship bias, corporate-action errors, repeated-testing bias or poor calibration. Costs, executable fills, market impact and portfolio allocation are not modeled. Synthetic success verifies chosen simulated premises and software behavior, not investment performance. A hosted static page also cannot establish that local Python dependencies will install on every machine.Hosting configuration follows the official [Static HTML Spaces guide](https://huggingface.co/docs/hub/spaces-sdks-static) and [Spaces configuration reference](https://huggingface.co/docs/hub/spaces-config-reference), checked 25 October 2026. Claims about particular run results belong to the bundled provenance artifact and executed verification record.46 unmodified lines47484950515253545556575859606162636465666746 unmodified linesChronological splitting reduces a specific kind of leakage; it does not eliminate nonstationarity, dependence, survivorship bias, corporate-action errors, repeated-testing bias or poor calibration. Costs, executable fills, market impact and portfolio allocation are not modeled. Synthetic success verifies chosen simulated premises and software behavior, not investment performance. A hosted static page also cannot establish that local Python dependencies will install on every machine.Hosting configuration follows the official [Static HTML Spaces guide](https://huggingface.co/docs/hub/spaces-sdks-static) and [Spaces configuration reference](https://huggingface.co/docs/hub/spaces-config-reference), checked 25 October 2026. Claims about particular run results belong to the bundled provenance artifact and executed verification record.## Browser extensions · 26 October 2026The browser candidate set now also contains `ewma`, sharing the ridge conditional mean but replacing constant residual variance with a causal exponential filter. Its half-life is fixed at20 observations, with alpha=1-exp(-ln(2)/20). The filter begins from training residual mean square. A forecast at feature row i uses residuals strictly earlier than target y[i]. Once a prior test outcome is observable, it may update the variance for a later prediction; regression coefficients and calibration parameters remain frozen within a block. The audit labels this as online variance updating. Annualized residual volatility multiplies per-observation standard deviation by sqrt(252), an assumption that is unsuitable for irregular/gapped observation intervals. Half-life is not tuned on outer outcomes.The saved Python benchmark is unchanged and predates this EWMA challenger. Its candidate set and results remain historical. The downloadable Python bundle is the prior separate implementation; these additions execute as JavaScript in this Static Space.The implied-volatility calculator independently implements bracketed bisection of European, no-dividend Black–Scholes call/put pricing. It checks discounted-strike arbitrage bounds, treats the lower bound as zero volatility, rejects the upper bound (no finite solution), and caps its search at volatility10. Convergence is defined by premium residual <=1e-8*max(1,spot), not by a guarantee of parameter identification. Outputs include bounds, iterations, repriced premium and signed residual. Extreme in/out-of-money prices can poorly identify volatility even with small price residual. Negative rates are supported within numerical range. These are risk-neutral pricing quantities, separate from empirical forecast probabilities.The distribution explorer uses an independently written compensated compound-Poisson Gaussian-jump model:`X_T = (mu - sigma^2/2 - lambda*(exp(m+s^2/2)-1))*T + sigma*W_T + sum(J_i)`.J_i are independent Normal(m,s²); N_T is Poisson(lambda*T). `mu` is annual expected simple-return drift under this scenario, not log-return drift. Mean and variance of log return are reported analytically. The Gaussian comparison matches the mixture's full log-return mean and variance. User-selected scenarios are neither calibrated physical forecasts nor automatically risk-neutral models.Poisson terms are accumulated until omitted mass is below1e-12, without renormalization. PDF/CDF probabilities use the finite mixture directly, with an approximate normal CDF. The plotting grid combines a global grid with quarter-standard-deviation local component grids; it is clipped at mixture quantiles1e-7 and retainedMass-1e-7. Thus the chart omits roughly2e-7 tail mass without changing the downside probability calculation. The audit reports omitted Poisson mass, finite-grid CDF mass, trapezoidal PDF mass and their difference. A visible warning appears if integration discrepancy exceeds0.005. A density can exceed1; interval probability is its integral or a CDF difference.Conceptual references: [Quantflow EWMA](https://quantflow.quantmind.com/api/ta/ewma/), [Quantflow option-pricing source](https://github.com/quantmind/quantflow/blob/main/quantflow/options/bs.py), [Quantflow jump diffusion](https://quantflow.quantmind.com/api/sp/jump_diffusion/). No Quantmind source has been copied or vendored, and no Quantflow dependency is installed. Standard formulas are implemented independently and checked against analytical identities and an independent SciPy oracle. No performance improvement or trading edge is claimed.
30 unmodified lines31323330 unmodified linesThe [Python project ZIP](python-project.zip) is provided for local experiments with the broader library stack. Downloading it does not start a hosted Python service. Its server-side data-processing and temporary-storage rules apply if you run the Gradio version; those are distinct from this browser-only workbench. The Python package also includes the original research register: accessible abstracts and metadata were consulted, but the requested books were not read in full.The [precomputed Python benchmark](benchmark.json) records an actual 900-close synthetic experiment with seed 42: scikit-learn 1.9.1, XGBoost 2.1.4 and LightGBM 4.7.0 fitted; three Optuna trials; computed tree SHAP; and completed local MLflow metadata. It does not train these libraries on your browser-selected CSV. Check the benchmark's provenance and method status before interpreting its results.30 unmodified lines313233343536373839404130 unmodified linesThe [Python project ZIP](python-project.zip) is provided for local experiments with the broader library stack. Downloading it does not start a hosted Python service. Its server-side data-processing and temporary-storage rules apply if you run the Gradio version; those are distinct from this browser-only workbench. The Python package also includes the original research register: accessible abstracts and metadata were consulted, but the requested books were not read in full.The [precomputed Python benchmark](benchmark.json) records an actual 900-close synthetic experiment with seed 42: scikit-learn 1.9.1, XGBoost 2.1.4 and LightGBM 4.7.0 fitted; three Optuna trials; computed tree SHAP; and completed local MLflow metadata. It does not train these libraries on your browser-selected CSV. Check the benchmark's provenance and method status before interpreting its results.## New browser tools- Causal EWMA residual-volatility challenger with a fixed20-observation half-life and chronological calibration.- European Black–Scholes implied-volatility inversion with bounds, convergence and repricing diagnostics.- Compensated normal-jump distribution PDF/CDF explorer with a same-moment Gaussian comparison and explicit truncation/grid-mass audit.Run `node test_model.cjs`, `node test_labs.cjs`, and `node test_scenarios.cjs` to reproduce the browser numerical checks. The saved Python benchmark remains unchanged; these additional tools are browser JavaScript, while `python-project.zip` retains the separate Python release.
1234567# Browser extension verification · 26 October 2026
Node checks: test_model.cjs (baseline and EWMA), test_labs.cjs, test_scenarios.cjs; app.js syntax check. Chronology tests cover own-label invariance, future-data invariance, exact variance recurrence and next-observation shock reaction. Pricing tests cover call/put recovery, negative rates, arbitrage bounds, zero-volatility boundary and bracket rejection. Distribution checks cover analytical moments, normal limit, monotone CDF, Poisson truncation, mass integration and narrow separated modes.
Independent verifier checked92 SciPy-priced option inversions: maximum price residual9.55e-7. Mixture CDF errors against SciPy were below7.42e-8 in inspected scenarios. These checks concern numerical implementation, not predictive or investment validity.
A plotting defect was found: a uniform grid missed sharply separated narrow mixture modes. The grid now incorporates local component resolution and retains a finite quantile window. A regression test covers the failure; audit fields and a visible integration warning remain. No upstream source was copied. Graphify was not needed for this small, already mapped codebase.17 unmodified lines1819202122232425262713 unmodified lines41424317 unmodified lines$('stats').replaceChildren();for(const [label,value]of [['P(downside)',percent(q[0])],['P(positive)',percent(q[2])],['Test log loss',fmt(report.selected_metrics.log_loss)],['Unseen observations',report.test_observations.toLocaleString()]]){const div=document.createElement('div'),span=document.createElement('span'),strong=document.createElement('strong');span.textContent=label;strong.textContent=value;div.append(span,strong);$('stats').append(div);}const kind=report.precomputed?'PRECOMPUTED PYTHON BENCHMARK':source.synthetic?'SYNTHETIC · BROWSER FIT':'LOCAL CSV · BROWSER FIT';$('status').textContent=`${kind} · ${source.rows.toLocaleString()} closes · latest model: ${report.latest_forecast.model}. ${report.precomputed?'Saved run; Python libraries are not executing here.':'Models fit in your browser. CSV contents are not sent to a modeling server.'}`;drawProbabilities(q);drawTimeline(report.predictions,dates);drawCalibration(report.predictions);drawScores(report.candidate_metrics);$('scores-body').replaceChildren();Object.entries(report.candidate_metrics).sort((a,b)=>a[1].log_loss-b[1].log_loss).forEach(([name,m])=>{const row=document.createElement('tr');for(const value of [name,m.observations||report.test_observations,fmt(m.log_loss),fmt(m.brier_multiclass),fmt(m.up_brier),fmt(m.downside_brier)]){const td=document.createElement('td');td.textContent=value;row.append(td);}$('scores-body').append(row);});$('score-note').textContent=report.precomputed?'Saved Python scores; candidate counts must be compared before ranking. No historical investment performance is claimed.':'These three candidates score the same unseen rows. Model selection uses preceding calibration data, not this table.';$('audit').textContent=JSON.stringify({source,target:report.target,threshold:report.threshold,latest_forecast:report.latest_forecast,folds:report.folds,model_status:report.model_status||'Browser baselines only',limitations:report.limitations},null,2);$('diagnostics').textContent=JSON.stringify(diagnostics||{},null,2);$('explanations').textContent=report.precomputed?JSON.stringify({mode:'PRECOMPUTED; no Python executes on this host',tuning_trials:report.tuning_trials,shap_explanation:report.shap_explanation,mlflow:report.mlflow,benchmark_date:report.benchmark_date},null,2):'Browser run: no SHAP, Optuna, XGBoost, LightGBM or MLflow execution. Load the precomputed Python benchmark to inspect its saved results, or download the Python project.';$('download').disabled=false;setBusy(false);13 unmodified lines$('game').addEventListener('change',updateGame);function updateRisk(){try{const data=new FormData($('risk-form')),value=name=>Number(data.get(name));$('risk-output').textContent=JSON.stringify({black_scholes:QuantLabs.blackScholes(value('spot'),value('strike'),value('years'),.03,value('vol')),quarter_kelly_binary_fraction:QuantLabs.kelly(value('probability'),value('odds'))},null,2);}catch(error){$('risk-output').textContent=error.message;}}$('risk-form').addEventListener('submit',event=>{event.preventDefault();updateRisk();});updateGame();updateRisk();run();17 unmodified lines181920212223242526272813 unmodified lines42434445464748495017 unmodified lines$('stats').replaceChildren();for(const [label,value]of [['P(downside)',percent(q[0])],['P(positive)',percent(q[2])],['Test log loss',fmt(report.selected_metrics.log_loss)],['Unseen observations',report.test_observations.toLocaleString()]]){const div=document.createElement('div'),span=document.createElement('span'),strong=document.createElement('strong');span.textContent=label;strong.textContent=value;div.append(span,strong);$('stats').append(div);}const kind=report.precomputed?'PRECOMPUTED PYTHON BENCHMARK':source.synthetic?'SYNTHETIC · BROWSER FIT':'LOCAL CSV · BROWSER FIT';$('status').textContent=`${kind} · ${source.rows.toLocaleString()} closes · latest model: ${report.latest_forecast.model}. ${report.precomputed?'Saved run; Python libraries are not executing here.':'Models fit in your browser. CSV contents are not sent to a modeling server.'}`;const vol=report.latest_forecast.candidate_volatility_annualized; $('volatility-note').textContent=vol?`Latest residual volatility: EWMA ${percent(vol.ewma)}, constant ridge ${percent(vol.ridge)} annualized. Assumes 252 equal-length observations; CSV gaps may invalidate this scaling.`:'This saved Python benchmark predates the browser EWMA challenger.';drawProbabilities(q);drawTimeline(report.predictions,dates);drawCalibration(report.predictions);drawScores(report.candidate_metrics);$('scores-body').replaceChildren();Object.entries(report.candidate_metrics).sort((a,b)=>a[1].log_loss-b[1].log_loss).forEach(([name,m])=>{const row=document.createElement('tr');for(const value of [name,m.observations||report.test_observations,fmt(m.log_loss),fmt(m.brier_multiclass),fmt(m.up_brier),fmt(m.downside_brier)]){const td=document.createElement('td');td.textContent=value;row.append(td);}$('scores-body').append(row);});$('score-note').textContent=report.precomputed?'Saved Python scores; candidate counts must be compared before ranking. No historical investment performance is claimed.':'These browser candidates score the same unseen rows. Model selection uses preceding calibration data, not this table.';$('audit').textContent=JSON.stringify({source,target:report.target,threshold:report.threshold,latest_forecast:report.latest_forecast,model_details:report.model_details,folds:report.folds,model_status:report.model_status||'Browser baselines only',limitations:report.limitations},null,2);$('diagnostics').textContent=JSON.stringify(diagnostics||{},null,2);$('explanations').textContent=report.precomputed?JSON.stringify({mode:'PRECOMPUTED; no Python executes on this host',tuning_trials:report.tuning_trials,shap_explanation:report.shap_explanation,mlflow:report.mlflow,benchmark_date:report.benchmark_date},null,2):'Browser run: no SHAP, Optuna, XGBoost, LightGBM or MLflow execution. Load the precomputed Python benchmark to inspect its saved results, or download the Python project.';$('download').disabled=false;setBusy(false);13 unmodified lines$('game').addEventListener('change',updateGame);function updateRisk(){try{const data=new FormData($('risk-form')),value=name=>Number(data.get(name));$('risk-output').textContent=JSON.stringify({black_scholes:QuantLabs.blackScholes(value('spot'),value('strike'),value('years'),.03,value('vol')),quarter_kelly_binary_fraction:QuantLabs.kelly(value('probability'),value('odds'))},null,2);}catch(error){$('risk-output').textContent=error.message;}}$('risk-form').addEventListener('submit',event=>{event.preventDefault();updateRisk();});updateGame();updateRisk();run();function updateIV(){const out=$('iv-output');try{const data=new FormData($('iv-form')),value=name=>Number(data.get(name));const result=QuantScenarios.impliedVolatility({spot:value('spot'),strike:value('strike'),years:value('years'),rate:value('rate'),premium:value('premium'),type:data.get('type')});out.classList.remove('lab-error');out.textContent=JSON.stringify({...result,annualized_volatility_percent:result.volatility*100,scope:'European no-dividend Black–Scholes implied volatility; risk-neutral pricing input, not a real-world return probability.'},null,2);}catch(error){out.classList.add('lab-error');out.textContent=error.message;}}$('iv-form').addEventListener('submit',event=>{event.preventDefault();updateIV();});function drawScenario(grid,kind){const left=grid[0].x,right=grid.at(-1).x,key=kind==='pdf'?'pdf':'cdf',comparison=kind==='pdf'?'gaussianPdf':'gaussianCdf';const max=kind==='pdf'?Math.max(...grid.map(p=>Math.max(p.pdf,p.gaussianPdf)))*1.05:1;let s='';for(let i=0;i<=4;i++){const y=175-i*150/4,value=max*i/4;s+=`<line class="grid" x1="45" x2="425" y1="${y}" y2="${y}"/><text x="38" y="${y+4}" text-anchor="end">${kind==='cdf'?Math.round(value*100)+'%':value.toFixed(value>10?0:1)}</text>`;}for(const [column,color,dash]of [[comparison,GRAY,'4 3'],[key,BLUE,'']]){const d=grid.map((p,i)=>`${i?'L':'M'}${45+(p.x-left)/(right-left)*380},${175-p[column]/max*150}`).join(' ');s+=`<path d="${d}" fill="none" stroke="${color}" stroke-width="1.5" stroke-dasharray="${dash}"/>`;}s+=`<text x="45" y="200">${(left*100).toFixed(1)}%</text><text x="425" y="200" text-anchor="end">${(right*100).toFixed(1)}%</text><text x="235" y="219" text-anchor="middle">Log return · blue jump mixture / gray normal</text>`;$(kind==='pdf'?'jump-pdf':'jump-cdf').innerHTML=svg(s,kind==='pdf'?'Jump-mixture and same-moment normal probability densities':'Jump-mixture and same-moment normal cumulative probabilities');}function updateJump(){const status=$('jump-status');try{const data=new FormData($('jump-form')),value=name=>Number(data.get(name));const result=QuantScenarios.jumpDistribution({mu:value('mu'),sigma:value('sigma'),intensity:value('intensity'),jumpMean:value('jumpMean'),jumpStd:value('jumpStd'),years:value('horizon')/252,threshold:value('threshold')});status.classList.remove('lab-error');const error=Math.abs(result.gridPdfMass-result.gridCDFMass);status.textContent=error>.005?'Plot resolution warning: the PDF grid does not accurately integrate this scenario. Use the direct CDF probabilities and inspect the numerical audit.':'Scenario calculated locally. Probabilities follow your assumptions; they are not calibrated forecasts.';if(error>.005)status.classList.add('lab-error');$('jump-stats').replaceChildren();for(const [label,text]of [['Scenario downside',percent(result.downsideProbability)],['Matched normal downside',percent(result.gaussianDownsideProbability)],['Poisson mass omitted',result.omittedPoissonMass.toExponential(2)]]){const div=document.createElement('div'),span=document.createElement('span'),strong=document.createElement('strong');span.textContent=label;strong.textContent=text;div.append(span,strong);$('jump-stats').append(div);}drawScenario(result.grid,'pdf');drawScenario(result.grid,'cdf');const {grid,...audit}=result;$('jump-audit').textContent=JSON.stringify(audit,null,2);}catch(error){status.classList.add('lab-error');status.textContent=error.message;$('jump-stats').replaceChildren();$('jump-pdf').replaceChildren();$('jump-cdf').replaceChildren();$('jump-audit').textContent='No valid scenario. Correct the inputs and calculate again.';}}$('jump-form').addEventListener('submit',event=>{event.preventDefault();updateJump();});updateIV();updateJump();
4 unmodified lines56789101112131415161 unmodified line181920212223241 unmodified line2627282930313233343536373839404 unmodified lines<meta name="theme-color" content="#f2f4f7"><meta name="description" content="Browser-local probability research with chronological validation and a reproducible Python benchmark."><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css"><script src="labs.js" defer></script><script src="app.js" defer></script></head><body><a class="skip" href="#results">Skip to results</a><header><div><h1>QuantLab <span>/ probability research</span></h1><p>Forecast the next observed close. Inspect calibration before trusting conviction.</p></div><a class="source-link" href="python-project.zip" download>Download Python project ↗</a></header><nav aria-label="Research views"><button class="tab active" data-view="workbench" aria-pressed="true">Forecast workbench</button><button class="tab" data-view="mathematics" aria-pressed="false">Mathematics lab</button><button class="tab" data-view="methods" aria-pressed="false">Methods & limits</button></nav><main><section id="workbench" class="view"><aside><form id="experiment"><h2>Experiment setup</h2><p class="small">No paid compute. CSV data stays in your browser.</p>1 unmodified line<label for="csv-file">CSV · date,close</label><input id="csv-file" type="file" accept=".csv,text/csv"><p class="hint">714–2,500 rows · 2 MiB maximum · adjusted closes · ascending ISO dates</p><label for="observations">Synthetic observations</label><input id="observations" type="number" min="850" max="2500" step="50" value="1200" required><label for="seed">Random seed</label><input id="seed" type="number" min="0" max="100000" step="1" value="42" required><div class="model-list"><h3>Browser models</h3><p>Empirical frequency<br>Ridge + Gaussian residuals<br>Multinomial logistic</p><span class="hint">Train → calibrate → unseen test.<br>Selection uses calibration scores only.</span></div><button id="run" class="primary" type="submit">Run chronological experiment</button></form><div class="benchmark-control"><h2>Python benchmark</h2><p class="small">Inspect a saved, verified run with scikit-learn, XGBoost, LightGBM, Optuna and SHAP.</p><button id="benchmark" class="secondary">Load precomputed benchmark</button><p class="hint">Synthetic data · 900 observations.<br>Python libraries do not run on this static host.</p></div>1 unmodified line<div id="results" tabindex="-1"><div id="status" role="status" aria-live="polite">Preparing a browser-local synthetic experiment…</div><div class="stats" id="stats"><div><span>P(downside)</span><strong>—</strong></div><div><span>P(positive)</span><strong>—</strong></div><div><span>Test log loss</span><strong>—</strong></div><div><span>Unseen observations</span><strong>—</strong></div></div><div class="charts"><section class="plot"><h2>Next observed close</h2><p>Mutually exclusive log-return events</p><div id="probability-chart" class="chart"></div></section><section class="plot"><h2>Downside through time</h2><p>Probabilities on unseen observations</p><div id="timeline-chart" class="chart"></div></section><section class="plot"><h2>Calibration</h2><p>Sample counts matter; sparse bins are noisy</p><div id="calibration-chart" class="chart"></div></section><section class="plot"><h2>Candidate comparison</h2><p>Outer-test log loss · lower is better</p><div id="score-chart" class="chart"></div></section></div><section class="scores"><h2>Same-history evidence</h2><p id="score-note" class="small">Comparative test scores appear after a run.</p><div class="table-scroll"><table><caption class="sr-only">Candidate test scores</caption><thead><tr><th scope="col">Model</th><th scope="col">Scored rows</th><th scope="col">Log loss</th><th scope="col">Brier</th><th scope="col">Up Brier</th><th scope="col">Downside Brier</th></tr></thead><tbody id="scores-body"></tbody></table></div></section><div class="audit-grid"><details><summary>Chronology & run audit</summary><pre id="audit">No completed run.</pre></details><details><summary>Distribution diagnostics</summary><pre id="diagnostics">No completed run.</pre></details><details><summary>SHAP & Python provenance</summary><pre id="explanations">Load the precomputed Python benchmark to inspect its tree explanation.</pre></details></div><button id="download" class="secondary" disabled>Download current report JSON</button><p class="hint">A probability forecast is not an executable trade. No historical investment edge is established.</p></div></section><section id="mathematics" class="view" hidden><h2>Incentives, prices & sizing</h2><p>Separate mathematical examples. These assumptions do not establish a market forecasting edge.</p><div class="lab-grid"><section class="plot"><h3>Two-player games</h3><label for="game">Game</label><select id="game"><option value="prisoner">Prisoner’s dilemma</option><option value="matching">Matching pennies</option></select><pre id="game-output"></pre></section><section class="plot"><h3>Option prices & binary Kelly</h3><form id="risk-form"><div class="input-grid"><label>Spot<input name="spot" type="number" min="1" step="1" value="100" required></label><label>Strike<input name="strike" type="number" min="1" step="1" value="100" required></label><label>Years<input name="years" type="number" min="0.01" max="10" step="0.01" value="1" required></label><label>Annual volatility<input name="vol" type="number" min="0.01" max="3" step="0.01" value="0.2" required></label><label>Binary win probability<input name="probability" type="number" min="0" max="1" step="0.01" value="0.55" required></label><label>Net binary payoff odds<input name="odds" type="number" min="0.1" max="10" step="0.1" value="1" required></label></div><button class="secondary">Calculate</button></form><pre id="risk-output" aria-live="polite"></pre><p class="hint">Black–Scholes: European, no dividends, constant volatility and 3% rate. Kelly: capped quarter-Kelly for a fixed-payoff binary bet, not an equity allocation.</p></section></div></section><section id="methods" class="view prose" hidden><h2>What runs here</h2><p>This is a free Static Hugging Face Space. Browser models fit locally in a web worker. CSV contents are read by your browser; they are not uploaded to a modeling server. No API key, external data feed or paid compute is required.</p><h3>Validation contract</h3><p>At close t, returns, momentum, realized volatility and drawdown use only observations through t. Models fit on earlier rows, then calibrate and select on a later block. A one-row embargo separates each boundary. Initial training uses 500 rows, calibration 150 and outer test blocks 200. Never tune using the outer test charts.</p><p>The target is the next observed close’s log return. Downside is below −0.02 log return, approximately −1.98% simple return; the middle event includes both boundaries, and the final event is a positive return. Probabilities sum to one.</p><h3>Two distinct execution modes</h3><p><b>Browser experiment:</b> empirical frequencies, ridge with Gaussian residual probabilities, and multinomial logistic regression are fitted to the selected data. Synthetic JavaScript draws differ from Python even with the same seed.</p><p><b>Precomputed Python benchmark:</b> a saved 900-observation synthetic run actually fitted scikit-learn, XGBoost and LightGBM, completed three training-only Optuna trials, computed SHAP and recorded MLflow metrics. Loading it does not execute those libraries. Download the full Python/Gradio project to run them locally.</p><h3>Implementation limits</h3><p>Calibration reuses data for temperatures and model choice. Financial tails and nonstationarity can invalidate normal residual assumptions. Tiny test samples and sparse reliability bins are especially unreliable. SHAP explains uncalibrated raw class margins, not causal effects. Close-based information does not imply executable same-close fills. No costs, live trading or economic backtest is included.</p><p>TFT, DeepSurv, PPO, calibrated rough-volatility models, SPDE solvers and quantum algorithms remain unimplemented. Qiskit has no defined task here; TensorFlow would duplicate the optional PyTorch backend. The downloadable project records all requested books and access limits; full books were not read.</p><p><a href="METHODS.md">Detailed method & provenance notes</a> · <a href="python-project.zip" download>Full Python source and tests</a></p></section></main><footer><span>QuantLab · research estimates, explicit assumptions.</span><span>Browser-local modeling / no paid compute</span></footer></body></html>4 unmodified lines56789101112131415161 unmodified line181920212223241 unmodified line262728293031323334353637383940414 unmodified lines<meta name="theme-color" content="#f2f4f7"><meta name="description" content="Browser-local probability research with chronological validation and a reproducible Python benchmark."><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css"><script src="labs.js" defer></script><script src="scenarios.js" defer></script><script src="app.js" defer></script></head><body><a class="skip" href="#results">Skip to results</a><header><div><h1>QuantLab <span>/ probability research</span></h1><p>Forecast the next observed close. Inspect calibration before trusting conviction.</p></div><a class="source-link" href="python-project.zip" download>Download Python project ↗</a></header><nav aria-label="Research views"><button class="tab active" data-view="workbench" aria-pressed="true">Forecast workbench</button><button class="tab" data-view="mathematics" aria-pressed="false">Mathematics lab</button><button class="tab" data-view="distributions" aria-pressed="false">Distribution lab</button><button class="tab" data-view="methods" aria-pressed="false">Methods & limits</button></nav><main><section id="workbench" class="view"><aside><form id="experiment"><h2>Experiment setup</h2><p class="small">No paid compute. CSV data stays in your browser.</p>1 unmodified line<label for="csv-file">CSV · date,close</label><input id="csv-file" type="file" accept=".csv,text/csv"><p class="hint">714–2,500 rows · 2 MiB maximum · adjusted closes · ascending ISO dates</p><label for="observations">Synthetic observations</label><input id="observations" type="number" min="850" max="2500" step="50" value="1200" required><label for="seed">Random seed</label><input id="seed" type="number" min="0" max="100000" step="1" value="42" required><div class="model-list"><h3>Browser models</h3><p>Empirical frequency<br>Ridge + Gaussian residuals<br>EWMA residual volatility<br>Multinomial logistic</p><span class="hint">Train → calibrate → unseen test.<br>Selection uses calibration scores only.</span></div><button id="run" class="primary" type="submit">Run chronological experiment</button></form><div class="benchmark-control"><h2>Python benchmark</h2><p class="small">Inspect a saved, verified run with scikit-learn, XGBoost, LightGBM, Optuna and SHAP.</p><button id="benchmark" class="secondary">Load precomputed benchmark</button><p class="hint">Synthetic data · 900 observations.<br>Python libraries do not run on this static host.</p></div>1 unmodified line<div id="results" tabindex="-1"><div id="status" role="status" aria-live="polite">Preparing a browser-local synthetic experiment…</div><div class="stats" id="stats"><div><span>P(downside)</span><strong>—</strong></div><div><span>P(positive)</span><strong>—</strong></div><div><span>Test log loss</span><strong>—</strong></div><div><span>Unseen observations</span><strong>—</strong></div></div><p class="small" id="volatility-note"></p><div class="charts"><section class="plot"><h2>Next observed close</h2><p>Mutually exclusive log-return events</p><div id="probability-chart" class="chart"></div></section><section class="plot"><h2>Downside through time</h2><p>Probabilities on unseen observations</p><div id="timeline-chart" class="chart"></div></section><section class="plot"><h2>Calibration</h2><p>Sample counts matter; sparse bins are noisy</p><div id="calibration-chart" class="chart"></div></section><section class="plot"><h2>Candidate comparison</h2><p>Outer-test log loss · lower is better</p><div id="score-chart" class="chart"></div></section></div><section class="scores"><h2>Same-history evidence</h2><p id="score-note" class="small">Comparative test scores appear after a run.</p><div class="table-scroll"><table><caption class="sr-only">Candidate test scores</caption><thead><tr><th scope="col">Model</th><th scope="col">Scored rows</th><th scope="col">Log loss</th><th scope="col">Brier</th><th scope="col">Up Brier</th><th scope="col">Downside Brier</th></tr></thead><tbody id="scores-body"></tbody></table></div></section><div class="audit-grid"><details><summary>Chronology & run audit</summary><pre id="audit">No completed run.</pre></details><details><summary>Distribution diagnostics</summary><pre id="diagnostics">No completed run.</pre></details><details><summary>SHAP & Python provenance</summary><pre id="explanations">Load the precomputed Python benchmark to inspect its tree explanation.</pre></details></div><button id="download" class="secondary" disabled>Download current report JSON</button><p class="hint">A probability forecast is not an executable trade. No historical investment edge is established.</p></div></section><section id="mathematics" class="view" hidden><h2>Incentives, prices & sizing</h2><p>Separate mathematical examples. These assumptions do not establish a market forecasting edge.</p><div class="lab-grid"><section class="plot"><h3>Two-player games</h3><label for="game">Game</label><select id="game"><option value="prisoner">Prisoner’s dilemma</option><option value="matching">Matching pennies</option></select><pre id="game-output"></pre></section><section class="plot"><h3>Option prices & binary Kelly</h3><form id="risk-form"><div class="input-grid"><label>Spot<input name="spot" type="number" min="1" step="1" value="100" required></label><label>Strike<input name="strike" type="number" min="1" step="1" value="100" required></label><label>Years<input name="years" type="number" min="0.01" max="10" step="0.01" value="1" required></label><label>Annual volatility<input name="vol" type="number" min="0.01" max="3" step="0.01" value="0.2" required></label><label>Binary win probability<input name="probability" type="number" min="0" max="1" step="0.01" value="0.55" required></label><label>Net binary payoff odds<input name="odds" type="number" min="0.1" max="10" step="0.1" value="1" required></label></div><button class="secondary">Calculate</button></form><pre id="risk-output" aria-live="polite"></pre><p class="hint">Black–Scholes: European, no dividends, constant volatility and 3% rate. Kelly: capped quarter-Kelly for a fixed-payoff binary bet, not an equity allocation.</p></section></div><section class="plot iv-lab"><h3>Implied volatility from an option premium</h3><p>European Black–Scholes inversion; no dividends. Risk-neutral pricing inputs stay separate from historical forecast probabilities.</p><form id="iv-form"><div class="input-grid"><label>Spot<input name="spot" type="number" min="0.01" value="100" step="0.01" required></label><label>Strike<input name="strike" type="number" min="0.01" value="100" step="0.01" required></label><label>Maturity · years<input name="years" type="number" min="0.001" max="10" value="1" step="0.001" required></label><label>Annual continuously compounded rate<input name="rate" type="number" min="-1" max="1" value="0.03" step="0.01" required></label><label>Observed premium · same units as spot<input name="premium" type="number" min="0" value="9.4134" step="0.0001" required></label><label>Option type<select name="type"><option value="call">Call</option><option value="put">Put</option></select></label></div><button class="secondary">Solve implied volatility</button></form><pre id="iv-output" aria-live="polite"></pre></section></section><section id="distributions" class="view" hidden><h2>Jump-diffusion distribution explorer</h2><p class="scenario-note">User-specified scenarios, separate from the forecast workbench. No parameters are fitted to uploaded prices. These are not option-implied or calibrated market probabilities.</p><div class="scenario-layout"><form id="jump-form"><h3>Annual parameters</h3><label>Expected simple-return drift<input name="mu" type="number" min="-1" max="1" step="0.01" value="0.06" required></label><label>Diffusion volatility<input name="sigma" type="number" min="0.01" max="2" step="0.01" value="0.2" required></label><label>Expected jumps per year<input name="intensity" type="number" min="0" max="50" step="0.5" value="2" required></label><label>Mean log jump size<input name="jumpMean" type="number" min="-1" max="1" step="0.01" value="-0.08" required></label><label>Log jump standard deviation<input name="jumpStd" type="number" min="0" max="1" step="0.01" value="0.1" required></label><label>Horizon · observations<input name="horizon" type="number" min="1" max="252" step="1" value="21" required></label><label>Downside log-return threshold<input name="threshold" type="number" min="-2" max="2" step="0.01" value="-0.02" required></label><button class="primary">Calculate scenario distribution</button><p class="hint">252 equal-length observations per year assumed. All return parameters are decimals. Jump compensation preserves the chosen expected simple-return drift.</p></form><div><div id="jump-status" role="status" aria-live="polite"></div><div class="stats" id="jump-stats"></div><div class="charts"><section class="plot"><h3>Probability density · PDF</h3><p>Density can exceed one; area gives probability.</p><div id="jump-pdf" class="chart"></div></section><section class="plot"><h3>Cumulative probability · CDF</h3><p>Blue: jump mixture. Gray: moment-matched normal.</p><div id="jump-cdf" class="chart"></div></section></div><details><summary>Scenario assumptions & numerical mass audit</summary><pre id="jump-audit"></pre></details></div></div></section><section id="methods" class="view prose" hidden><h2>What runs here</h2><p>This is a free Static Hugging Face Space. Browser models fit locally in a web worker. CSV contents are read by your browser; they are not uploaded to a modeling server. No API key, external data feed or paid compute is required.</p><h3>Validation contract</h3><p>At close t, returns, momentum, realized volatility and drawdown use only observations through t. Models fit on earlier rows, then calibrate and select on a later block. A one-row embargo separates each boundary. Initial training uses 500 rows, calibration 150 and outer test blocks 200. Never tune using the outer test charts.</p><p>The target is the next observed close’s log return. Downside is below −0.02 log return, approximately −1.98% simple return; the middle event includes both boundaries, and the final event is a positive return. Probabilities sum to one.</p><h3>EWMA challenger</h3><p>The ridge mean stays frozen within each fold. Residual variance updates online with a fixed 20-observation half-life, using only outcomes already known before each forecast. Its own target never updates its own variance. The audit records volatility and timing; annualization assumes 252 equal-length observations and is only illustrative for gapped CSVs.</p><h3>Two distinct execution modes</h3><p><b>Browser experiment:</b> empirical frequencies, ridge with Gaussian residual probabilities, EWMA residual-volatility probabilities, and multinomial logistic regression are fitted to the selected data. Synthetic JavaScript draws differ from Python even with the same seed.</p><p><b>Precomputed Python benchmark:</b> a saved 900-observation synthetic run actually fitted scikit-learn, XGBoost and LightGBM, completed three training-only Optuna trials, computed SHAP and recorded MLflow metrics. Loading it does not execute those libraries. Download the full Python/Gradio project to run them locally.</p><h3>Implementation limits</h3><p>Calibration reuses data for temperatures and model choice. Financial tails and nonstationarity can invalidate normal residual assumptions. Tiny test samples and sparse reliability bins are especially unreliable. SHAP explains uncalibrated raw class margins, not causal effects. Close-based information does not imply executable same-close fills. No costs, live trading or economic backtest is included.</p><p>TFT, DeepSurv, PPO, calibrated rough-volatility models, SPDE solvers and quantum algorithms remain unimplemented. Qiskit has no defined task here; TensorFlow would duplicate the optional PyTorch backend. The downloadable project records all requested books and access limits; full books were not read.</p><p>The implied-volatility solver and jump-mixture PDF/CDF explorer are independently implemented standard methods inspired by <a href="https://github.com/quantmind/quantflow">Quantflow</a>. No upstream source is copied and the Python package is not installed in this static host.</p><p><a href="METHODS.md">Detailed method & provenance notes</a> · <a href="python-project.zip" download>Full Python source and tests</a></p></section></main><footer><span>QuantLab · research estimates, explicit assumptions.</span><span>Browser-local modeling / no paid compute</span></footer></body></html>
26 unmodified lines27282930313233343536373826 unmodified linesconst a=Array.from({length:p+1},()=>Array(p+1).fill(0)),b=Array(p+1).fill(0);for(let i=0;i<n;i++)for(let j=0;j<=p;j++){b[j]+=z[i][j]*y[i]/n;for(let k=0;k<=p;k++)a[j][k]+=z[i][j]*z[i][k]/n;}for(let j=1;j<=p;j++)a[j][j]+=1;const beta=solve(a,b);const residual=y.map((v,i)=>v-z[i].reduce((s,u,j)=>s+u*beta[j],0)),mu=mean(residual),sigma=Math.max(1e-6,Math.sqrt(residual.reduce((s,v)=>s+(v-mu)**2,0)/(n-1)));const weights=Array.from({length:p+1},()=>[0,0,0]);let squared=0;for(const row of z)for(const v of row)squared+=v*v;const step=1/(.5*squared/n+.03);for(let iter=0;iter<100;iter++){const grad=Array.from({length:p+1},()=>[0,0,0]);for(let i=0;i<n;i++){const logits=[0,0,0];for(let j=0;j<=p;j++)for(let k=0;k<3;k++)logits[k]+=z[i][j]*weights[j][k];const prob=softmax(logits);for(let j=0;j<=p;j++)for(let k=0;k<3;k++)grad[j][k]+=z[i][j]*(prob[k]-(cls(y[i])===k?1:0))/n;}for(let j=0;j<=p;j++)for(let k=0;k<3;k++)weights[j][k]-=step*(grad[j][k]+(j?.03*weights[j][k]:0));}return{m,scale,beta,sigma,weights,empirical:counts.map(v=>v/(n+3))};}function probabilities(model,x,name){if(name==='empirical')return model.empirical.slice();const z=[1,...x.map((v,j)=>(v-model.m[j])/model.scale[j])];if(name==='softmax'){const v=[0,0,0];for(let j=0;j<z.length;j++)for(let k=0;k<3;k++)v[k]+=z[j]*model.weights[j][k];return softmax(v);}const mu=z.reduce((s,v,j)=>s+v*model.beta[j],0),lo=cdf((-.02-mu)/model.sigma),hi=cdf(-mu/model.sigma);return[lo,Math.max(0,hi-lo),1-hi];}function run(close){validate(close,714);if(close.length>2500)throw Error('Maximum 2500 closes');const{x,y,indices}=features(close),names=['empirical','ridge','softmax'],predictions=[],folds=[],allQ={empirical:[],ridge:[],softmax:[]},allY=[],selectedQ=[];function train(calStop){const calStart=calStop-150,trainStop=calStart-1,model=fit(x.slice(0,trainStop),y.slice(0,trainStop)),temps={},scores={};for(const name of names){const q=x.slice(calStart,calStop).map(row=>probabilities(model,row,name));let best=Infinity;for(const t of [.5,.75,1,1.5,2,3]){const score=metrics(y.slice(calStart,calStop),q.map(p=>temperature(p,t))).log_loss;if(score<best){best=score;temps[name]=t;}}scores[name]=best;}const chosen=names.reduce((a,b)=>scores[a]<=scores[b]?a:b);return{model,temps,scores,chosen,calStart,trainStop};}for(let start=652;start<y.length;start+=200){const stop=Math.min(start+200,y.length),calStop=start-1,t=train(calStop);folds.push({train_feature_start:indices[0],train_feature_end:indices[t.trainStop-1],train_label_end:indices[t.trainStop-1]+1,calibration_feature_start:indices[t.calStart],calibration_label_end:indices[calStop-1]+1,test_feature_start:indices[start],test_feature_end:indices[stop-1],selected:t.chosen,calibration_log_loss:t.scores,temperatures:t.temps});for(let i=start;i<stop;i++){const qs={};for(const name of names){qs[name]=temperature(probabilities(t.model,x[i],name),t.temps[name]);allQ[name].push(qs[name]);}allY.push(y[i]);selectedQ.push(qs[t.chosen]);predictions.push({feature_index:indices[i],target_index:indices[i]+1,probabilities:qs[t.chosen],actual_log_return:y[i],model:t.chosen});}}const t=train(y.length-1),latestX=features([...close,close.at(-1)]).x.at(-1),candidate={};for(const name of names)candidate[name]=temperature(probabilities(t.model,latestX,name),t.temps[name]);return{target:'next observed-close log return',threshold:-.02,classes:['r < -0.02','-0.02 <= r <= 0','r > 0'],test_observations:allY.length,predictions,folds,candidate_metrics:Object.fromEntries(names.map(name=>[name,metrics(allY,allQ[name])])),selected_metrics:metrics(allY,selectedQ),latest_forecast:{probabilities:candidate[t.chosen],model:t.chosen,candidate_probabilities:candidate,feature_index:close.length-1,target_index:close.length,train_label_end:indices[t.trainStop-1]+1,calibration_feature_start:indices[t.calStart],calibration_label_end:indices[y.length-2]+1,calibration_log_loss:t.scores,temperatures:t.temps},limitations:['Synthetic data demonstrate software only.','Next observed close may span calendar gaps.','Normal ridge errors and stationary calibration can fail under regime shifts.','Temperature and model selection reuse calibration; test blocks remain untouched.','No transaction costs, execution model, or established economic edge.']};}const api={synthetic,features,run};if(typeof module!=='undefined'&&module.exports)module.exports=api;root.QuantModel=api;})(typeof globalThis!=='undefined'?globalThis:this);26 unmodified lines27282930313233343536373839404142434445464726 unmodified linesconst a=Array.from({length:p+1},()=>Array(p+1).fill(0)),b=Array(p+1).fill(0);for(let i=0;i<n;i++)for(let j=0;j<=p;j++){b[j]+=z[i][j]*y[i]/n;for(let k=0;k<=p;k++)a[j][k]+=z[i][j]*z[i][k]/n;}for(let j=1;j<=p;j++)a[j][j]+=1;const beta=solve(a,b);const residual=y.map((v,i)=>v-z[i].reduce((s,u,j)=>s+u*beta[j],0)),mu=mean(residual),sigma=Math.max(1e-6,Math.sqrt(residual.reduce((s,v)=>s+(v-mu)**2,0)/(n-1)));const weights=Array.from({length:p+1},()=>[0,0,0]);let squared=0;for(const row of z)for(const v of row)squared+=v*v;const step=1/(.5*squared/n+.03);for(let iter=0;iter<100;iter++){const grad=Array.from({length:p+1},()=>[0,0,0]);for(let i=0;i<n;i++){const logits=[0,0,0];for(let j=0;j<=p;j++)for(let k=0;k<3;k++)logits[k]+=z[i][j]*weights[j][k];const prob=softmax(logits);for(let j=0;j<=p;j++)for(let k=0;k<3;k++)grad[j][k]+=z[i][j]*(prob[k]-(cls(y[i])===k?1:0))/n;}for(let j=0;j<=p;j++)for(let k=0;k<3;k++)weights[j][k]-=step*(grad[j][k]+(j?.03*weights[j][k]:0));}return{m,scale,beta,sigma,training_residual_mse:mean(residual.map(v=>v*v)),weights,empirical:counts.map(v=>v/(n+3))};}function ridgeMean(model,x){return model.beta[0]+x.reduce((sum,v,j)=>sum+(v-model.m[j])/model.scale[j]*model.beta[j+1],0);}function probabilities(model,x,name,sigmaOverride){if(name==='empirical')return model.empirical.slice();const z=[1,...x.map((v,j)=>(v-model.m[j])/model.scale[j])];if(name==='softmax'){const v=[0,0,0];for(let j=0;j<z.length;j++)for(let k=0;k<3;k++)v[k]+=z[j]*model.weights[j][k];return softmax(v);}const mu=z.reduce((s,v,j)=>s+v*model.beta[j],0),sigma=sigmaOverride??model.sigma,lo=cdf((-.02-mu)/sigma),hi=cdf(-mu/sigma);return[lo,Math.max(0,hi-lo),1-hi];}function run(close){validate(close,714);if(close.length>2500)throw Error('Maximum 2500 closes');const{x,y,indices}=features(close),names=['empirical','ridge','softmax','ewma'],predictions=[],folds=[],allQ={empirical:[],ridge:[],softmax:[],ewma:[]},allY=[],selectedQ=[];function train(calStop){const calStart=calStop-150,trainStop=calStart-1,model=fit(x.slice(0,trainStop),y.slice(0,trainStop)),temps={},scores={},ewmaSigmas=[];// A row i forecasts y[i] before observing it. Only residuals j<i enter sigma[i].// Start from training-only MSE, then process embargo/calibration/test labels in order.const alpha=1-Math.exp(-Math.log(2)/20);let variance=Math.max(1e-12,model.training_residual_mse);for(let i=trainStop;i<=y.length;i++){ewmaSigmas[i]=Math.sqrt(Math.max(1e-12,variance));if(i<y.length){const residual=y[i]-ridgeMean(model,x[i]);variance=(1-alpha)*variance+alpha*residual*residual;}}for(const name of names){const q=x.slice(calStart,calStop).map((row,j)=>probabilities(model,row,name,name==='ewma'?ewmaSigmas[calStart+j]:undefined));let best=Infinity;for(const t of [.5,.75,1,1.5,2,3]){const score=metrics(y.slice(calStart,calStop),q.map(p=>temperature(p,t))).log_loss;if(score<best){best=score;temps[name]=t;}}scores[name]=best;}const chosen=names.reduce((a,b)=>scores[a]<=scores[b]?a:b);return{model,temps,scores,chosen,calStart,trainStop,ewmaSigmas};}for(let start=652;start<y.length;start+=200){const stop=Math.min(start+200,y.length),calStop=start-1,t=train(calStop);folds.push({train_feature_start:indices[0],train_feature_end:indices[t.trainStop-1],train_label_end:indices[t.trainStop-1]+1,calibration_feature_start:indices[t.calStart],calibration_label_end:indices[calStop-1]+1,test_feature_start:indices[start],test_feature_end:indices[stop-1],selected:t.chosen,calibration_log_loss:t.scores,temperatures:t.temps});for(let i=start;i<stop;i++){const qs={};for(const name of names){qs[name]=temperature(probabilities(t.model,x[i],name,name==='ewma'?t.ewmaSigmas[i]:undefined),t.temps[name]);allQ[name].push(qs[name]);}allY.push(y[i]);selectedQ.push(qs[t.chosen]);predictions.push({feature_index:indices[i],target_index:indices[i]+1,probabilities:qs[t.chosen],actual_log_return:y[i],model:t.chosen,ewma_sigma:t.ewmaSigmas[i],ridge_mean:ridgeMean(t.model,x[i])});}}const t=train(y.length-1),latestX=features([...close,close.at(-1)]).x.at(-1),candidate={};for(const name of names)candidate[name]=temperature(probabilities(t.model,latestX,name,name==='ewma'?t.ewmaSigmas[y.length]:undefined),t.temps[name]);return{target:'next observed-close log return',threshold:-.02,classes:['r < -0.02','-0.02 <= r <= 0','r > 0'],test_observations:allY.length,predictions,folds,candidate_metrics:Object.fromEntries(names.map(name=>[name,metrics(allY,allQ[name])])),selected_metrics:metrics(allY,selectedQ),model_details:{ewma:{half_life_observations:20,alpha:1-Math.exp(-Math.log(2)/20),mean_model:'ridge',initialization:'training residual mean square',variance_convention:'next-observation conditional residual second moment; daily sigma floor 1e-6',update:'online after each observed label, with frozen fold ridge coefficients; own forecast label excluded',annualization:'sigma times sqrt(252); assumes equally spaced trading-day observations',probabilities:'normal residual probabilities, then calibration-selected temperature'},ridge:{variance:'constant training residual sample variance'}},latest_forecast:{candidate_volatility_annualized:{ewma:t.ewmaSigmas[y.length]*Math.sqrt(252),ridge:t.model.sigma*Math.sqrt(252)},ewma_sigma:t.ewmaSigmas[y.length],probabilities:candidate[t.chosen],model:t.chosen,candidate_probabilities:candidate,feature_index:close.length-1,target_index:close.length,train_label_end:indices[t.trainStop-1]+1,calibration_feature_start:indices[t.calStart],calibration_label_end:indices[y.length-2]+1,calibration_log_loss:t.scores,temperatures:t.temps},limitations:['Synthetic data demonstrate software only.','Next observed close may span calendar gaps.','Normal ridge/EWMA errors and stationary calibration can fail under regime shifts.','EWMA volatility updates from prior observed outcomes inside test blocks; mean coefficients stay frozen.','Annualized volatility assumes 252 equally spaced trading observations; calendar gaps can invalidate this convention.','Temperature and model selection reuse calibration; test blocks remain untouched.','No transaction costs, execution model, or established economic edge.']};}const api={synthetic,features,run};if(typeof module!=='undefined'&&module.exports)module.exports=api;root.QuantModel=api;})(typeof globalThis!=='undefined'?globalThis:this);
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495/* Conceptual references: Black & Scholes (1973), European option bounds; * Merton (1976), compound-Poisson lognormal jump diffusion. Independent * implementation of finite Poisson mixtures; no calibration or copied code. */(function(root,factory){ const api=factory(typeof module!=='undefined'&&module.exports?require('./labs.js'):root.QuantLabs); if(typeof module!=='undefined'&&module.exports) module.exports=api; if(root) root.QuantScenarios=api;})(typeof globalThis!=='undefined'?globalThis:this,function(labs){ 'use strict'; const finite=x=>typeof x==='number'&&Number.isFinite(x); const check=(condition,message)=>{if(!condition) throw new Error(message);}; function impliedVolatility({spot,strike,years,rate,premium,type='call'}={}) { check([spot,strike,years,rate,premium].every(finite)&&Math.min(spot,strike,years)>0,'Finite inputs and positive spot, strike, years required.'); check(type==='call'||type==='put','Option type must be call or put.'); check(labs&&typeof labs.blackScholes==='function','Load QuantLabs before QuantScenarios.'); const discount=strike*Math.exp(-rate*years); check(finite(discount)&&discount>0,'Discounted strike exceeds numerical range.'); const lower=type==='call'?Math.max(spot-discount,0):Math.max(discount-spot,0); const upper=type==='call'?spot:discount,bounds={lower,upper}; check(premium>=lower&&premium<upper,'Premium violates European no-dividend bounds or has no finite-volatility solution.'); if(premium===lower) return {volatility:0,converged:true,iterations:0,repriced:lower,error:0,bounds}; const tolerance=1e-8*Math.max(1,spot); const price=vol=>labs.blackScholes(spot,strike,years,rate,vol)[type]; let lo=0,hi=.5,highPrice=price(hi); while(highPrice<premium&&hi<10){hi=Math.min(10,hi*2);highPrice=price(hi);} check(highPrice>=premium,'Required volatility exceeds supported bracket [0, 10].'); let volatility=hi,repriced=highPrice,iterations=0; for(iterations=1;iterations<=200;iterations++){ volatility=(lo+hi)/2;repriced=price(volatility); if(Math.abs(repriced-premium)<=tolerance) break; if(repriced<premium)lo=volatility;else hi=volatility; } return {volatility,converged:Math.abs(repriced-premium)<=tolerance,iterations:Math.min(iterations,200),repriced,error:repriced-premium,bounds}; } const normPDF=z=>Math.exp(-z*z/2)/Math.sqrt(2*Math.PI); function normCDF(z){ if(z===0)return .5; const t=1/(1+.2316419*Math.abs(z)); const tail=normPDF(z)*t*(.319381530+t*(-.356563782+t*(1.781477937+t*(-1.821255978+t*1.330274429)))); return Math.max(0,Math.min(1,z>0?1-tail:tail)); } function jumpDistribution({mu=.06,sigma=.2,intensity=1,jumpMean=-.05,jumpStd=.1,years=1/252,threshold=-.02}={}) { check([mu,sigma,intensity,jumpMean,jumpStd,years,threshold].every(finite),'All scenario parameters must be finite numbers.'); check(mu>=-1&&mu<=1&&sigma>=.01&&sigma<=2&&intensity>=0&&intensity<=50&&jumpMean>=-1&&jumpMean<=1&&jumpStd>=0&&jumpStd<=1&&years>=1/252&&years<=2&&intensity*years<=50,'Scenario parameters exceed supported bounds; intensity × years must be ≤ 50.'); const poissonMean=intensity*years,kappa=Math.expm1(jumpMean+jumpStd*jumpStd/2); const drift=(mu-.5*sigma*sigma-intensity*kappa)*years; const mean=drift+poissonMean*jumpMean; const variance=sigma*sigma*years+poissonMean*(jumpStd*jumpStd+jumpMean*jumpMean),sd=Math.sqrt(variance); const components=[];let weight=Math.exp(-poissonMean),retainedMass=0,n=0; while(true){ components.push({weight,mean:drift+n*jumpMean,sd:Math.sqrt(sigma*sigma*years+n*jumpStd*jumpStd)}); retainedMass+=weight; if(Math.max(0,1-retainedMass)<1e-12)break; n++;weight*=poissonMean/n; check(n<1000,'Poisson truncation failed to converge.'); } const omittedPoissonMass=Math.max(0,1-retainedMass); const cdf=x=>components.reduce((sum,c)=>sum+c.weight*normCDF((x-c.mean)/c.sd),0); const pdf=x=>components.reduce((sum,c)=>sum+c.weight*normPDF((x-c.mean)/c.sd)/c.sd,0); // Search within component six-sigma bounds, then use mixture quantiles to // avoid a plot dominated by extraordinarily improbable far-tail components. const lower=Math.min(...components.map(c=>c.mean-8*c.sd)); const upper=Math.max(...components.map(c=>c.mean+8*c.sd)); function quantile(probability){ let left=lower,right=upper; for(let i=0;i<100;i++){const mid=(left+right)/2;if(cdf(mid)<probability)left=mid;else right=mid;} return (left+right)/2; } const left=quantile(1e-7),right=quantile(retainedMass-1e-7); const points=new Set(Array.from({length:401},(_,i)=>left+(right-left)*i/400)); const resolvedComponents=components.filter(c=>c.weight>1e-12); // A global grid misses narrow separated modes. Resolve each material // component locally at quarter-sigma spacing, including eight-sigma tails. for(const c of resolvedComponents) for(let i=0;i<=64;i++) { const point=c.mean+(i/4-8)*c.sd; if(point>left&&point<right) points.add(point); } check(points.size<=10000,'Adaptive plotting grid exceeds numerical budget.'); const grid=Array.from(points).sort((a,b)=>a-b).map(x=>{ const z=(x-mean)/sd; return {x,pdf:pdf(x),cdf:cdf(x),gaussianPdf:normPDF(z)/sd,gaussianCdf:normCDF(z)}; }); const gridCDFMass=grid[grid.length-1].cdf-grid[0].cdf; const gridPdfMass=grid.slice(1).reduce((sum,p,i)=>sum+(p.x-grid[i].x)*(p.pdf+grid[i].pdf)/2,0); return {grid,downsideProbability:cdf(threshold),gaussianDownsideProbability:normCDF((threshold-mean)/sd),mean,variance, retainedMass,omittedPoissonMass,gridCDFMass,gridPdfMass,gridPointCount:grid.length, gridAudit:{basePoints:401,componentCount:components.length,resolvedComponents:resolvedComponents.length, localStepStandardDeviations:.25,localTailStandardDeviations:8, absoluteMassError:Math.abs(gridPdfMass-gridCDFMass),maxPoints:10000}, parameters:{mu,sigma,intensity,jumpMean,jumpStd,years,threshold,kappa}, measure:'user-specified scenario, not calibrated physical forecast or risk-neutral pricing', comparison:'Gaussian has the same total log-return mean and variance; only distribution shape differs.', gridNote:'Adaptive nonuniform grid combines 401 mixture-quantile-span points with quarter-sigma local grids over ±8 standard deviations for every component with weight >1e-12. Local points are clipped to mixture quantiles 1e-7 and retainedMass-1e-7, so plotted tails omit about 2e-7 mass without renormalization. CDF probabilities use the mixture directly; gridAudit reports trapezoidal density integration error.', driftDefinition:'mu is annual expected simple-return drift in the compensated exponential model; mean reports the log-return mean. Normal CDF uses an approximation with absolute error about 8e-8.'}; } return {impliedVolatility,jumpDistribution};});1:root{font-family:Arial,Helvetica,sans-serif;color:#141414;background:#f2f4f7;font-size:14px;line-height:1.5;color-scheme:light}*{box-sizing:border-box}body{margin:0;padding:24px 32px}header{display:flex;align-items:center;justify-content:space-between;gap:24px;max-width:1400px;margin:auto}h1{font-size:25px;letter-spacing:-.7px;font-weight:600;margin:0}h1 span{font-weight:400;color:#505864}header p{margin:6px 0 0;color:#505864}a{color:#174f9d;text-underline-offset:3px}.source-link{white-space:nowrap;font-size:13px}nav{display:flex;gap:24px;border-bottom:1px solid #d6dce4;margin:24px auto;max-width:1400px}button,input,select{font:inherit}button{cursor:pointer;touch-action:manipulation}button:disabled{opacity:.55;cursor:progress}.tab{border:0;background:none;padding:10px 0;color:#505864;border-bottom:2px solid transparent;white-space:nowrap}.tab.active{border-color:#141414;color:#141414}.primary,.secondary{min-height:44px;padding:9px 16px;border-radius:5px;border:1px solid #c3cad5;background:white;color:#141414}.primary{background:#141414;color:white;border-color:#141414;width:100%}.primary:hover{background:#333}.secondary:hover{background:#e8ecf1}:focus-visible{outline:3px solid #1d5fbf;outline-offset:3px}main{max-width:1400px;margin:auto}#workbench{display:grid;grid-template-columns:265px minmax(0,1fr);gap:28px}aside{min-width:0}h2{font-size:16px;font-weight:600;margin:0 0 6px}h3{font-size:14px;font-weight:600;margin:20px 0 6px}p{margin:8px 0 16px}.small,.hint{color:#505864;font-size:13px}.hint{font-size:12px;margin:7px 0 14px}form label{display:block;margin:14px 0 6px}input,select{display:block;width:100%;background:white;color:#141414;border:1px solid #c3cad5;border-radius:4px;min-height:40px;padding:8px;font-size:16px}input[type=file]{font-size:12px;max-width:100%}input[type=file]::file-selector-button{border:0;padding:5px;margin-right:5px;background:#e8ecf1;cursor:pointer}.model-list{margin:22px 0;padding:15px 0;border-top:1px solid #d6dce4}.model-list h3{margin:0}.model-list p{line-height:1.8;margin:8px 0}.benchmark-control{margin-top:26px;padding-top:20px;border-top:1px solid #d6dce4}.benchmark-control button{width:100%}#results{min-width:0;outline-offset:8px}#status{font-size:13px;color:#444c58;min-height:45px;padding:0 0 8px}#status.error{color:#a82222}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:18px;margin:12px 0 26px}.stats span{font-size:12px;display:block;color:#505864;margin-bottom:5px}.stats strong{font-size:29px;font-weight:500;font-variant-numeric:tabular-nums}.charts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.plot{background:#fff;padding:18px 18px 10px;min-width:0;border-radius:5px}.plot h2{font-size:15px}.plot>p{font-size:12px;color:#505864;margin:0 0 8px}.chart{height:220px;width:100%}.chart svg{width:100%;height:100%;overflow:visible}.chart text{font-family:Arial,sans-serif;font-size:11px;fill:#505864}.chart line.grid{stroke:#e7ebf0;stroke-width:1}.chart path,.chart line{vector-effect:non-scaling-stroke}.scores{margin-top:26px}.scores p{margin-top:0}.table-scroll{overflow:auto;background:white;border-radius:5px}table{border-collapse:collapse;width:100%;font-size:13px;white-space:nowrap;font-variant-numeric:tabular-nums}th,td{text-align:right;padding:12px;border-bottom:1px solid #edf0f4}th:first-child,td:first-child{text-align:left}th{font-weight:500;color:#505864}.audit-grid{display:grid;gap:10px;margin:20px 0}details{background:#fff;border-radius:5px;padding:12px 16px}summary{cursor:pointer;min-height:24px}pre{font-size:12px;line-height:1.6;max-height:360px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.lab-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-top:24px}.input-grid{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}.prose{max-width:800px}.prose h3{margin-top:28px}.prose p{line-height:1.8}footer{max-width:1400px;margin:36px auto 0;padding-top:18px;border-top:1px solid #d6dce4;font-size:12px;color:#505864;display:flex;justify-content:space-between;gap:16px}.skip{position:absolute;left:16px;top:-100px;background:white;padding:12px;z-index:10}.skip:focus{top:5px}.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}[hidden]{display:none!important}@media(max-width:960px){body{padding:20px}#workbench{grid-template-columns:230px minmax(0,1fr);gap:20px}.charts{grid-template-columns:1fr}.stats{grid-template-columns:1fr 1fr}.source-link{max-width:150px;white-space:normal;text-align:right}}@media(max-width:640px){body{padding:18px 16px}header{display:block}h1{font-size:22px}h1 span{display:block;font-size:18px;letter-spacing:-.3px;margin-top:3px}header p{font-size:13px}.source-link{display:inline-block;max-width:none;margin-top:12px;text-align:left}nav{gap:20px;overflow:auto;margin:18px 0}#workbench{display:flex;flex-direction:column}aside{display:grid;grid-template-columns:1fr;gap:12px}.model-list{margin:15px 0}.benchmark-control{margin-top:12px;padding-top:16px}#results{margin-top:14px}.stats{gap:16px}.stats strong{font-size:27px}.charts,.lab-grid{grid-template-columns:1fr}.plot{padding:16px 12px}.chart{height:210px}.input-grid{gap:0 12px}footer{display:block}footer span{display:block;margin:6px 0}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}}123:root{font-family:Arial,Helvetica,sans-serif;color:#141414;background:#f2f4f7;font-size:14px;line-height:1.5;color-scheme:light}*{box-sizing:border-box}body{margin:0;padding:24px 32px}header{display:flex;align-items:center;justify-content:space-between;gap:24px;max-width:1400px;margin:auto}h1{font-size:25px;letter-spacing:-.7px;font-weight:600;margin:0}h1 span{font-weight:400;color:#505864}header p{margin:6px 0 0;color:#505864}a{color:#174f9d;text-underline-offset:3px}.source-link{white-space:nowrap;font-size:13px}nav{display:flex;gap:24px;border-bottom:1px solid #d6dce4;margin:24px auto;max-width:1400px}button,input,select{font:inherit}button{cursor:pointer;touch-action:manipulation}button:disabled{opacity:.55;cursor:progress}.tab{border:0;background:none;padding:10px 0;color:#505864;border-bottom:2px solid transparent;white-space:nowrap}.tab.active{border-color:#141414;color:#141414}.primary,.secondary{min-height:44px;padding:9px 16px;border-radius:5px;border:1px solid #c3cad5;background:white;color:#141414}.primary{background:#141414;color:white;border-color:#141414;width:100%}.primary:hover{background:#333}.secondary:hover{background:#e8ecf1}:focus-visible{outline:3px solid #1d5fbf;outline-offset:3px}main{max-width:1400px;margin:auto}#workbench{display:grid;grid-template-columns:265px minmax(0,1fr);gap:28px}aside{min-width:0}h2{font-size:16px;font-weight:600;margin:0 0 6px}h3{font-size:14px;font-weight:600;margin:20px 0 6px}p{margin:8px 0 16px}.small,.hint{color:#505864;font-size:13px}.hint{font-size:12px;margin:7px 0 14px}form label{display:block;margin:14px 0 6px}input,select{display:block;width:100%;background:white;color:#141414;border:1px solid #c3cad5;border-radius:4px;min-height:40px;padding:8px;font-size:16px}input[type=file]{font-size:12px;max-width:100%}input[type=file]::file-selector-button{border:0;padding:5px;margin-right:5px;background:#e8ecf1;cursor:pointer}.model-list{margin:22px 0;padding:15px 0;border-top:1px solid #d6dce4}.model-list h3{margin:0}.model-list p{line-height:1.8;margin:8px 0}.benchmark-control{margin-top:26px;padding-top:20px;border-top:1px solid #d6dce4}.benchmark-control button{width:100%}#results{min-width:0;outline-offset:8px}#status{font-size:13px;color:#444c58;min-height:45px;padding:0 0 8px}#status.error{color:#a82222}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:18px;margin:12px 0 26px}.stats span{font-size:12px;display:block;color:#505864;margin-bottom:5px}.stats strong{font-size:29px;font-weight:500;font-variant-numeric:tabular-nums}.charts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.plot{background:#fff;padding:18px 18px 10px;min-width:0;border-radius:5px}.plot h2{font-size:15px}.plot>p{font-size:12px;color:#505864;margin:0 0 8px}.chart{height:220px;width:100%}.chart svg{width:100%;height:100%;overflow:visible}.chart text{font-family:Arial,sans-serif;font-size:11px;fill:#505864}.chart line.grid{stroke:#e7ebf0;stroke-width:1}.chart path,.chart line{vector-effect:non-scaling-stroke}.scores{margin-top:26px}.scores p{margin-top:0}.table-scroll{overflow:auto;background:white;border-radius:5px}table{border-collapse:collapse;width:100%;font-size:13px;white-space:nowrap;font-variant-numeric:tabular-nums}th,td{text-align:right;padding:12px;border-bottom:1px solid #edf0f4}th:first-child,td:first-child{text-align:left}th{font-weight:500;color:#505864}.audit-grid{display:grid;gap:10px;margin:20px 0}details{background:#fff;border-radius:5px;padding:12px 16px}summary{cursor:pointer;min-height:24px}pre{font-size:12px;line-height:1.6;max-height:360px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.lab-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-top:24px}.input-grid{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}.prose{max-width:800px}.prose h3{margin-top:28px}.prose p{line-height:1.8}footer{max-width:1400px;margin:36px auto 0;padding-top:18px;border-top:1px solid #d6dce4;font-size:12px;color:#505864;display:flex;justify-content:space-between;gap:16px}.skip{position:absolute;left:16px;top:-100px;background:white;padding:12px;z-index:10}.skip:focus{top:5px}.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}[hidden]{display:none!important}@media(max-width:960px){body{padding:20px}#workbench{grid-template-columns:230px minmax(0,1fr);gap:20px}.charts{grid-template-columns:1fr}.stats{grid-template-columns:1fr 1fr}.source-link{max-width:150px;white-space:normal;text-align:right}}@media(max-width:640px){body{padding:18px 16px}header{display:block}h1{font-size:22px}h1 span{display:block;font-size:18px;letter-spacing:-.3px;margin-top:3px}header p{font-size:13px}.source-link{display:inline-block;max-width:none;margin-top:12px;text-align:left}nav{gap:20px;overflow:auto;margin:18px 0}#workbench{display:flex;flex-direction:column}aside{display:grid;grid-template-columns:1fr;gap:12px}.model-list{margin:15px 0}.benchmark-control{margin-top:12px;padding-top:16px}#results{margin-top:14px}.stats{gap:16px}.stats strong{font-size:27px}.charts,.lab-grid{grid-template-columns:1fr}.plot{padding:16px 12px}.chart{height:210px}.input-grid{gap:0 12px}footer{display:block}footer span{display:block;margin:6px 0}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}}.scenario-layout{display:grid;grid-template-columns:265px minmax(0,1fr);gap:28px;margin-top:24px}.scenario-layout form{min-width:0}.scenario-layout .stats{grid-template-columns:repeat(3,minmax(0,1fr))}.scenario-layout details{margin-top:18px}.scenario-layout .plot h3,.iv-lab h3{margin-top:0}.iv-lab{margin-top:24px;max-width:850px;padding:24px}.iv-lab>p{font-size:14px}.scenario-note{max-width:850px}.lab-error{color:#a82222}.input-grid select{width:100%}@media(max-width:800px){.scenario-layout{grid-template-columns:1fr}.scenario-layout .stats{grid-template-columns:1fr 1fr}}
13 unmodified lines14151613 unmodified linesfor(const x of [[1,2],Array(900).fill(NaN),Array(900).fill(0),Array(2501).fill(1)])assert.throws(()=>Q.run(x));for(const metrics of [...Object.values(a.candidate_metrics),a.selected_metrics]){assert(Number.isFinite(metrics.up_brier));assert(Number.isFinite(metrics.downside_brier));assert(metrics.up_brier>=0&&metrics.up_brier<=1);assert(metrics.downside_brier>=0&&metrics.downside_brier<=1);}console.log('All model tests passed');13 unmodified lines1415161718192021222324252627282930313213 unmodified linesfor(const x of [[1,2],Array(900).fill(NaN),Array(900).fill(0),Array(2501).fill(1)])assert.throws(()=>Q.run(x));for(const metrics of [...Object.values(a.candidate_metrics),a.selected_metrics]){assert(Number.isFinite(metrics.up_brier));assert(Number.isFinite(metrics.downside_brier));assert(metrics.up_brier>=0&&metrics.up_brier<=1);assert(metrics.downside_brier>=0&&metrics.downside_brier<=1);}console.log('All model tests passed');assert(a.candidate_metrics.ewma,'EWMA challenger must be scored');assert(Number.isFinite(a.latest_forecast.candidate_volatility_annualized.ewma));const shock=prices.slice();for(let i=801;i<shock.length;i++)shock[i]*=Math.exp(.4);const stressed=Q.run(shock);const at=(r,t)=>r.predictions.find(p=>p.feature_index===t);assert.equal(at(a,800).ewma_sigma,at(stressed,800).ewma_sigma,'own target label cannot alter forecast variance');assert.deepEqual(at(a,800).probabilities,at(stressed,800).probabilities,'own target cannot change its probability forecast');for(const q of Object.values(a.latest_forecast.candidate_probabilities))assert(Math.abs(q.reduce((sum,p)=>sum+p,0)-1)<1e-12);assert.deepEqual(Object.keys(a.candidate_metrics).sort(),['empirical','ewma','ridge','softmax']);assert(at(stressed,801).ewma_sigma>at(a,801).ewma_sigma,'variance must react after observed shock');const alpha=1-Math.exp(-Math.log(2)/20),before=at(stressed,800),after=at(stressed,801);const expected=(1-alpha)*before.ewma_sigma**2+alpha*(before.actual_log_return-before.ridge_mean)**2;assert(Math.abs(after.ewma_sigma**2-expected)<1e-14,'EWMA must implement exact causal recursion');for(let i=0;i<a.predictions.length;i++)if(a.predictions[i].feature_index<820)assert.equal(a.predictions[i].ewma_sigma,b.predictions[i].ewma_sigma);assert.equal(a.model_details.ewma.half_life_observations,20);console.log('EWMA causal variance tests passed');
123456789101112131415161718192021222324252627282930313233343536373839const assert=require('node:assert/strict');const labs=require('./labs.js'), s=require('./scenarios.js');for(const rate of [.05,-.03]) for(const type of ['call','put']) { const premium=labs.blackScholes(100,105,.75,rate,.35)[type]; const result=s.impliedVolatility({spot:100,strike:105,years:.75,rate,premium,type}); assert.ok(result.converged); assert.ok(Math.abs(result.volatility-.35)<1e-6); assert.ok(Math.abs(result.error)<1e-6);}assert.equal(s.impliedVolatility({spot:110,strike:100,years:1,rate:0,premium:10}).volatility,0);assert.throws(()=>s.impliedVolatility({spot:100,strike:100,years:1,rate:0,premium:100}));assert.throws(()=>s.impliedVolatility({spot:100,strike:100,years:1,rate:0,premium:-1}));const beyond=labs.blackScholes(100,100,.01,0,11).call;assert.throws(()=>s.impliedVolatility({spot:100,strike:100,years:.01,rate:0,premium:beyond}));const d=s.jumpDistribution({});assert.ok(d.omittedPoissonMass<1e-12);assert.ok(Math.abs(d.retainedMass+d.omittedPoissonMass-1)<1e-14);assert.ok(d.downsideProbability>=0&&d.downsideProbability<=1);for(let i=1;i<d.grid.length;i++) assert.ok(d.grid[i].cdf>=d.grid[i-1].cdf);const integrated=d.grid.slice(1).reduce((v,p,i)=>v+(p.x-d.grid[i].x)*(p.pdf+d.grid[i].pdf)/2,0);assert.ok(Math.abs(integrated-d.gridCDFMass)<.002);const normal=s.jumpDistribution({intensity:0});for(const p of normal.grid) {assert.ok(Math.abs(p.pdf-p.gaussianPdf)<1e-10);assert.ok(Math.abs(p.cdf-p.gaussianCdf)<1e-12);}const p={mu:.1,sigma:.3,intensity:2,jumpMean:-.1,jumpStd:.2,years:.5};const t=s.jumpDistribution(p), k=Math.exp(p.jumpMean+p.jumpStd**2/2)-1;assert.ok(Math.abs(t.mean-(p.mu-.5*p.sigma**2-p.intensity*k+p.intensity*p.jumpMean)*p.years)<1e-14);assert.ok(Math.abs(t.variance-(p.sigma**2+p.intensity*(p.jumpStd**2+p.jumpMean**2))*p.years)<1e-14);const high=s.jumpDistribution({intensity:25,years:2});assert.ok(high.omittedPoissonMass<1e-12);assert.ok(high.grid.length>=401&&high.grid.length<=10000);const narrow=s.jumpDistribution({sigma:.01,intensity:1,jumpMean:-1,jumpStd:0,years:1/252});assert.ok(Math.abs(narrow.gridPdfMass-narrow.gridCDFMass)<.005,'Adaptive grid must resolve narrow separated mixture modes');assert.throws(()=>s.jumpDistribution({intensity:50,years:2}));assert.throws(()=>s.jumpDistribution({sigma:0}));const vm=require('node:vm'),fs=require('node:fs');const context=vm.createContext({QuantLabs:labs});vm.runInContext(fs.readFileSync(require.resolve('./scenarios.js'),'utf8'),context);assert.equal(typeof context.QuantScenarios.jumpDistribution,'function');console.log('scenarios tests passed: IV bounds/roundtrips; mixture mass, moments, CDF, normal limit, worker export');const plotted=s.jumpDistribution();assert(Math.abs(plotted.grid[0].cdf-1e-7)<1e-9,'plot starts at the requested lower mixture quantile');assert(Math.abs(plotted.grid.at(-1).cdf-(plotted.retainedMass-1e-7))<1e-9,'plot ends at upper mixture quantile');IMPLEMENTATION.mdAdded+10
METHODS.md+18
README.md+8
VERIFICATION.mdAdded+7
app.js+9-2
index.html+7-6
model.js+16-7
scenarios.jsAdded+95
style.css+2
test_model.cjs+16
test_scenarios.cjsAdded+39