Make navigation and results easier to understand with plain-language guidance
Browse filesFiles changed (6)
- DESIGN.md+6
- README.md+3
- VERIFICATION.md+6
- app.js+28-26
- index.html+30-31
- style.css+13
10 unmodified lines11121310 unmodified linesData quality is a disclosure next to forecast evidence. Warning counts appear in its summary. Cleaning changes and retained anomalies are auditable. The sidebar explains the bounded temporary cache and provides Clear forecast data. Preserve strict input validation and explicit cache-hit labels.Validation uses a single white evidence surface within Forecast, with a neutral conclusion and paired baseline table. Main uncertainty is accompanied by its block length and replicate count; detailed folds, stage event counts and sensitivity are disclosures. Strict is the browser UI default, classic is explicitly selectable; minimum-history errors never silently change protocol. Show that the latest strict forecast retains the evaluated fit, while classic scores describe historical selection. Sidebar controls scroll within the viewport on desktop; mobile remains ordinary document flow.10 unmodified lines11121314151617181910 unmodified linesData quality is a disclosure next to forecast evidence. Warning counts appear in its summary. Cleaning changes and retained anomalies are auditable. The sidebar explains the bounded temporary cache and provides Clear forecast data. Preserve strict input validation and explicit cache-hit labels.Validation uses a single white evidence surface within Forecast, with a neutral conclusion and paired baseline table. Main uncertainty is accompanied by its block length and replicate count; detailed folds, stage event counts and sensitivity are disclosures. Strict is the browser UI default, classic is explicitly selectable; minimum-history errors never silently change protocol. Show that the latest strict forecast retains the evaluated fit, while classic scores describe historical selection. Sidebar controls scroll within the viewport on desktop; mobile remains ordinary document flow.## Beginner navigation and languageThe default path is Price explorer → choose prices → Show my guess → three outcome chances → Did the guesses help? Use everyday language and explain percentages as chances out of 100. Made-up data stays clearly labeled. Preserve exact cutoff definitions under What counts as a big fall. Three top outcomes replace technical score/count metrics; exact scores remain available under checking/technical disclosures.Number games, What if? and Help name the other destinations. Help starts with three steps and a short glossary. Keep model names, statistical assumptions, JSON audits and saved Python tooling available on request. Preserve numerical behavior, privacy, error recovery and the existing Apple-inspired visual system. Avoid claiming this has been tested with children.
48 unmodified lines49505148 unmodified linesBrowser JSON exports include normalized-input SHA-256, model/configuration and split metadata, plus the latest 25 successful result views in the current tab (cache hits included). Clear/reload reset this local history. This records inspection, not independent validation or vendor provenance. Run `node test_provenance.cjs` for fingerprint/history checks.48 unmodified lines49505152535448 unmodified linesBrowser JSON exports include normalized-input SHA-256, model/configuration and split metadata, plus the latest 25 successful result views in the current tab (cache hits included). Clear/reload reset this local history. This records inspection, not independent validation or vendor provenance. Run `node test_provenance.cjs` for fingerprint/history checks.The interface starts with plain-language Price explorer, Number games, What if? and Help. Main results show three chances and a short explanation; exact scores, checking methods and audit reports remain available in optional details. This changes presentation, not the forecasting models or the strength of their evidence.
28 unmodified lines29303128 unmodified lines## Provenance release — 26 October 2026Added SHA-256 normalized-input manifests and bounded successful-result inspection history. Provenance tests verify deterministic identity, date/value sensitivity, cloned bounded history and clearing. App-state tests exercise export serialization with validation, manifests and cache-hit history; export is disabled after clear. Pending-digest clear regression prevents stale worker creation. Independent source review found no concrete shipping defect. No market-predictive claim follows from these implementation checks. Browser download-file capture remains unverified; JSON Blob construction and download-handler invocation are now directly tested.28 unmodified lines29303132333435363728 unmodified lines## Provenance release — 26 October 2026Added SHA-256 normalized-input manifests and bounded successful-result inspection history. Provenance tests verify deterministic identity, date/value sensitivity, cloned bounded history and clearing. App-state tests exercise export serialization with validation, manifests and cache-hit history; export is disabled after clear. Pending-digest clear regression prevents stale worker creation. Independent source review found no concrete shipping defect. No market-predictive claim follows from these implementation checks. Browser download-file capture remains unverified; JSON Blob construction and download-handler invocation are now directly tested.## Beginner interface release — 27 October 2026Simplified navigation, main result labels and explanations; placed checking controls, detailed evidence, extra charts and technical audits behind native disclosures. Main figures are the three existing outcome probabilities; models and split logic were not changed. The checks link explicitly opens its containing disclosure. Existing export/state regression remains passing. Phone preview at 390px had document width 390px, and all four views were inspected. This is developer usability review, not child user testing. Mechanical copy/layout detector raised two cramped-padding warnings on inherited statistic separators; rendered spacing was inspected.All eleven existing verification suites passed for this release, including export/state and multi-fold causality. Browser checked the missing-file recovery message, checks-link disclosure opening, and save disable after clearing. Independent source review prompted rounding and growth-parameter wording corrections. No formal accessibility certification or child user study was performed.
6 unmodified lines789101112131415161718192021222324252627282930313233346 unmodified lines4142434445464748491 unmodified line5152535455565724 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281296 unmodified linesfunction escapeXML(value){return String(value).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}function svg(content,label){return `<svg viewBox="0 0 440 220" role="img" aria-label="${escapeXML(label)}">${content}</svg>`;}function grids(max=1){let s='';for(let i=0;i<=4;i++){let y=175-150*i/4;s+=`<line class="grid" x1="40" x2="430" y1="${y}" y2="${y}"/><text x="32" y="${y+4}" text-anchor="end">${(max*i/4*100).toFixed(0)}%</text>`;}return s;}function drawProbabilities(q){const labels=['Below −0.02','−0.02 to zero','Above zero'];let s=grids();q.forEach((v,i)=>{const x=65+i*130,y=175-v*150;s+=`<rect x="${x}" y="${y}" width="95" height="${175-y}" fill="${[GRAY,INK,BLUE][i]}"/><text x="${x+47}" y="${Math.max(15,y-7)}" text-anchor="middle">${percent(v)}</text><text x="${x+47}" y="197" text-anchor="middle">${labels[i]}</text>`;});$('probability-chart').innerHTML=svg(s,'Next-close probabilities: '+q.map(percent).join(', '));}function drawTimeline(rows,dates){const ys=rows.map(r=>r.probabilities[0]),max=Math.max(.1,...ys)*1.1;let s=grids(max);const path=ys.map((v,i)=>`${i?'L':'M'}${40+i*390/Math.max(1,ys.length-1)},${175-v/max*150}`).join(' ');s+=`<path d="${path}" fill="none" stroke="${BLUE}" stroke-width="1.5"/>`;const first=rows[0],last=rows.at(-1);const a=first.target_date||(dates&&dates[first.target_index])||String(first.target_index),b=last.target_date||(dates&&dates[last.target_index])||String(last.target_index);s+=`<text x="40" y="200">${escapeXML(a)}</text><text x="430" y="200" text-anchor="end">${escapeXML(b)}</text>`;$('timeline-chart').innerHTML=svg(s,'Predicted downside probability across '+rows.length+' unseen observations');}function drawCalibration(rows){let s=grids();s+=`<line x1="40" y1="175" x2="430" y2="25" stroke="#a9afb8" stroke-dasharray="4 4"/>`;for(const [cls,color,label]of [[0,BLUE,'Downside'],[2,INK,'Up']]){const bins=Array.from({length:10},()=>[]);rows.forEach(row=>bins[Math.min(9,Math.floor(row.probabilities[cls]*10))].push(row));let points=[];bins.forEach(bin=>{if(!bin.length)return;const p=bin.reduce((a,r)=>a+r.probabilities[cls],0)/bin.length,o=bin.reduce((a,r)=>a+(cls===0?r.actual_log_return<-.02:r.actual_log_return>0),0)/bin.length;const x=40+p*390,y=175-o*150;points.push([x,y]);s+=`<circle cx="${x}" cy="${y}" r="${Math.min(8,3+Math.sqrt(bin.length)/3)}" fill="${color}" opacity=".8"><title>${label}: predicted ${percent(p)}, observed ${percent(o)}, n=${bin.length}</title></circle>`;});if(points.length>1)s+=`<path d="${points.map(([x,y],i)=>`${i?'L':'M'}${x},${y}`).join(' ')}" fill="none" stroke="${color}" stroke-width="1"/>`;}s+='<text x="40" y="199">0%</text><text x="430" y="199" text-anchor="end">100% predicted</text><text x="125" y="219" fill="#1d5fbf">Downside</text><text x="255" y="219">Up</text>';$('calibration-chart').innerHTML=svg(s,'Reliability bins: mean predicted probability versus observed event frequency');}function drawScores(metrics){const names=Object.keys(metrics).sort((a,b)=>metrics[a].log_loss-metrics[b].log_loss),max=Math.max(...names.map(n=>metrics[n].log_loss))*1.13;let s='';names.forEach((name,i)=>{const step=150/names.length,y=20+i*step,w=metrics[name].log_loss/max*275;s+=`<text x="100" y="${y+15}" text-anchor="end">${escapeXML(name)}</text><rect x="112" y="${y}" height="${Math.min(25,step-6)}" width="${w}" fill="${name==='empirical'?BLUE:INK}"/><text x="${118+w}" y="${y+15}">${fmt(metrics[name].log_loss)}</text>`;});s+='<text x="112" y="202">0</text><text x="430" y="202" text-anchor="end">Multiclass log loss</text>';$('score-chart').innerHTML=svg(s,'Out-of-sample log loss for each model, lower is better');}function setBusy(value,message){busy=value;$('run').disabled=value;$('benchmark').disabled=value;$('run').textContent=value?'Calculating…':'Update forecast';$('results').setAttribute('aria-busy',String(value));document.querySelectorAll('#experiment input,#experiment select').forEach(input=>input.disabled=value);if(!value)syncSource();$('status').classList.remove('error');if(message)$('status').textContent=message;}function fail(message){if(worker){worker.terminate();worker=null;}setBusy(false);focusResults=false;$('status').textContent=message+(currentReport?' Previous results remain below.':'');$('status').classList.add('error');}function render(report,source,dates,diagnostics,cacheHit=false,identity=null){currentReport={...report,source,diagnostics,execution:{model_revision:report.precomputed?'saved-python-benchmark':MODEL_REVISION,cache_hit:cacheHit,cache_policy:'Tab memory only; at most 3 runs; ten-minute TTL from computation'}};const view=inspectionJournal.record({data_sha256:identity?.sha256||null,protocol:report.validation_protocol?.name||'historical-python',model_revision:currentReport.execution.model_revision,cache_hit:cacheHit,observations:report.test_observations,selected_log_loss:report.selected_metrics.log_loss,latest_model:report.latest_forecast.model});currentReport.experiment_manifest={schema_version:1,view,inputs:identity||{sha256:null,reason:'Original normalized input series unavailable for this historical artifact.'},provenance:{source_metadata:source,source:source.name||'Saved Python benchmark',adjustments:source.synthetic?'Synthetic generator; no market adjustments.':'Unknown. Dates and closing prices alone do not establish vendor, corporate-action adjustment or point-in-time availability.'},configuration:{model_revision:currentReport.execution.model_revision,protocol:report.validation_protocol,target:report.target,threshold:report.threshold,model_details:report.model_details},split_boundaries:report.folds,inspection_history:inspectionJournal.snapshot(),limitations:'Fingerprint is computed from normalized dates and prices, not original file bytes. History is tab-local, bounded and resettable; it does not prove independent evaluation or prevent research overfitting.'};const q=report.latest_forecast.probabilities;$('stats').replaceChildren();for(const [label,value]of [['Downside · log return < −0.02',percent(q[0])],['Positive return',percent(q[2])],['Prediction error²',fmt(report.selected_metrics.log_loss)],['Evaluation 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?'Saved Python example':source.synthetic?'Simulated example':'Your CSV';$('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.'}`;if(cacheHit)$('status').textContent+=' Reused a matching in-tab run (less than 10 minutes old).';$('status').textContent+=` Result view ${view.sequence} in this tab. Export includes input fingerprint and inspection history.`;renderQuality(source);renderValidation(report);$('forecast-context').textContent=report.validation_protocol?.name==='strict'?'Latest forecast uses the same coefficients, temperatures and model choice as the reserved evaluation. Features and EWMA volatility advance with known observations.':'Historical test scores describe a fold-by-fold selection procedure; the latest forecast may use a different model and training period.';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.';$('outcome-summary').textContent=`Downside ${percent(q[0])} · Middle ${percent(q[1])} · Positive ${percent(q[2])}`;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.';6 unmodified linesfunction signed(value){return(value>0?'+':'')+Number(value).toFixed(4);}function intervalText(interval){return interval?.estimable&&interval.percentile95?`[${signed(interval.percentile95[0])}, ${signed(interval.percentile95[1])}]`:'Not estimable';}function renderValidation(report){const validation=report.validation;$('validation-link').hidden=!validation?.available;for(const id of ['validation-baselines','validation-folds','validation-support','validation-intervals','validation-movement','rolling-chart','validation-policy','validation-interval-note','movement-note','rolling-description','validation-support-note','validation-interpretation'])$(id).replaceChildren();if(!validation?.available){$('validation-content').hidden=true;$('validation-verdict').textContent='Matched validation unavailable.';$('validation-scope').textContent=report.precomputed?'This saved Python benchmark predates row-matched baseline diagnostics. Run a browser experiment for the new validation panel.':validation?.reason||'This report does not contain matched baseline diagnostics.';$('validation-audit').textContent='No matched validation available.';return;}$('validation-content').hidden=false;const strict=report.validation_protocol?.name==='strict';$('validation-scope').textContent=(strict?'Strict split: final 200 outcomes reserved from coefficient fitting, temperature tuning and model choice. EWMA uses only earlier known outcomes.':'Classic expanding windows: temperature and model choice share calibration; historical tests evaluate the sequential selection procedure.')+' Repeatedly inspecting these results can still overfit the evaluation.';1 unmodified line$('validation-policy').textContent=`Selected procedure log loss: ${fmt(report.selected_metrics.log_loss)} on ${validation.observations.toLocaleString()} matched ${validation.observations===1?'observation':'observations'}. Event counts: ${validation.class_counts[0]} downside, ${validation.class_counts[1]} middle, ${validation.class_counts[2]} positive.`;const intervalReference=validation.comparisons.empirical_raw.intervals.find(i=>i.block===20)||validation.comparisons.empirical_raw.intervals[0];$('validation-interval-note').textContent=intervalReference.estimable?`Main interval: ${intervalReference.block}-observation blocks, ${intervalReference.reps} resamples. Inspect sensitivity below.`:'No resampling interval is estimable for this evaluation sample and block length.';const comparisons=Object.values(validation.comparisons),validAll=comparisons.every(c=>c.intervals.length>=3&&c.intervals.every(i=>i.estimable&&i.percentile95));$('validation-verdict').textContent=validation.observations<100?'Too little test data to assess advantage.':validAll&&comparisons.every(c=>c.intervals.every(i=>i.percentile95[1]<0))?'Lower loss in this run. Validate prospectively.':validAll&&validation.comparisons.empirical_raw.intervals.every(i=>i.percentile95[0]>0)?'Untuned frequency performs better in this run.':'Advantage not established.';for(const [key,label]of[['empirical_raw','Untuned frequency'],['empirical_calibrated','Calibrated frequency']]){const comparison=validation.comparisons[key],main=comparison.intervals.find(i=>i.block===20)||comparison.intervals[0];appendEvidenceRow('validation-baselines',[label,fmt(report.baseline_metrics[key].log_loss),signed(comparison.mean_difference),intervalText(main)]);24 unmodified linesfunction renderQuality(source){const quality=source.data_quality;$('quality-warnings').replaceChildren();$('quality-summary').textContent=quality?`${quality.rows.toLocaleString()} validated prices. ${quality.normalizedHeaderFields} header fields normalized; ${quality.trimmedValues} date/price values trimmed${quality.bomRemoved?'; initial byte-order mark removed':''}. No rows dropped or values filled.`:source.synthetic?'Simulated example: generated finite positive prices with weekday placeholder dates. This does not establish real-market data quality.':'Saved benchmark: no new CSV cleaning was performed.';for(const warning of quality?.warnings||[]){const item=document.createElement('li');item.textContent=warning;$('quality-warnings').append(item);}$('quality-audit').textContent=JSON.stringify(quality||{source:source.name||'Saved benchmark',note:'No uploaded CSV cleaning audit available for this mode.'},null,2);document.querySelector('.quality-panel').classList.toggle('has-warnings',Boolean(quality?.warnings.length));document.querySelector('.quality-panel summary').textContent=quality?.warnings.length?`Data quality · ${quality.warnings.length} ${quality.warnings.length===1?'check':'checks'} to review`:'Data quality & cleaning';}$('clear-data').addEventListener('click',()=>{operation++;if(worker){worker.terminate();worker=null;}runCache.clear();inspectionJournal.clear();currentReport=null;focusResults=false;$('csv-file').value='';setBusy(false);$('download').disabled=true;$('setup-note').hidden=true;for(const id of ['stats','probability-chart','timeline-chart','calibration-chart','score-chart','outcome-summary','scores-body','volatility-note','quality-warnings','forecast-context','validation-baselines','validation-folds','validation-support','validation-intervals','validation-movement','rolling-chart','validation-policy','validation-interval-note','movement-note','rolling-description','validation-support-note','validation-interpretation'])$(id).replaceChildren();for(const id of ['audit','diagnostics','explanations','quality-audit'])$(id).textContent='No forecast data retained by this app. Start a new run.';$('quality-summary').textContent='No active data. Choose a source and update the forecast.';document.querySelector('.quality-panel').classList.remove('has-warnings');document.querySelector('.quality-panel summary').textContent='Data quality & cleaning';$('status').textContent='Forecast data and cached runs cleared. Choose a source and update the forecast to start again.';$('score-note').textContent='No current model scores.';$('validation-content').hidden=true;$('validation-link').hidden=true;$('validation-support-note').hidden=true;$('validation-verdict').textContent='No active validation. Start a new run.';$('validation-scope').textContent='';$('validation-audit').textContent='No validation data retained.';});function syntheticDates(n){const dates=[],day=new Date('2010-01-04T00:00:00Z');while(dates.length<n){if(day.getUTCDay()!==0&&day.getUTCDay()!==6)dates.push(day.toISOString().slice(0,10));day.setUTCDate(day.getUTCDate()+1);}return dates;}async function run(){if(busy)return;const token=++operation;setBusy(true,'Fitting browser models on past data, calibrating, then testing on later observations…');try{let closes,dates,source;const mode=$('data-source').value,protocol=$('validation-protocol').value;if(!['classic','strict'].includes(protocol))throw Error('Choose a validation approach.');if(mode==='csv'){const file=$('csv-file').files[0];if(!file)throw Error('Choose a date,close CSV, or select Synthetic demo.');if(file.size>2*1024*1024)throw Error('CSV must be no larger than 2 MiB.');const buffer=await file.arrayBuffer();if(token!==operation)return;let text;try{text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(buffer);}catch{throw Error('CSV must use valid UTF-8 encoding. Export it as UTF-8 and try again.');}const data=QuantLabs.parseCSV(text);closes=data.closes;dates=data.dates;source={synthetic:false,rows:closes.length,name:'Local CSV',calendar_gap_max_days:data.calendarGapMaxDays,data_quality:data.quality};}else{const n=Number($('observations').value),seed=Number($('seed').value);if(!Number.isInteger(n)||n<850||n>2500||!Number.isInteger(seed)||seed<0||seed>100000)throw Error('Use 850–2,500 observations and an integer seed from 0 to 100,000.');const model=await import('./model.js?v=20261026validation4');if(token!==operation)return;closes=globalThis.QuantModel.synthetic(n,seed);dates=syntheticDates(n);source={synthetic:true,rows:n,seed,name:'Browser synthetic generator',calendar:'Weekday placeholders, not exchange dates'};}if(protocol==='strict'&&closes.length<1064)throw Error('Strict validation needs at least 1,064 prices. Add history or choose Classic expanding windows.');const sha256=await QuantProvenance.fingerprint({dates,closes});if(token!==operation)return;const identity={sha256,canonical_format:'quantlab-normalized-prices-v1: JSON array of format tag, ISO dates, finite positive numeric closes',rows:closes.length,first_date:dates[0],last_date:dates.at(-1)};const key=JSON.stringify([MODEL_REVISION,protocol,dates,closes]);const cached=runCache.get(key);if(cached){render(cached.report,source,dates,cached.diagnostics,true,identity);return;}if(worker)worker.terminate();worker=new Worker('worker.js?v=20261026validation4');worker.onmessage=event=>{if(token!==operation)return;if(event.data.error){fail(event.data.error);return;}const report=event.data.report;report.predictions.forEach(r=>{r.feature_date=dates[r.feature_index];r.target_date=dates[r.target_index];});report.latest_forecast.feature_date=dates.at(-1);runCache.set(key,{report,diagnostics:event.data.diagnostics});render(report,source,dates,event.data.diagnostics,false,identity);worker.terminate();worker=null;};worker.onerror=()=>{if(token!==operation)return;fail('Browser calculation could not finish. Try fewer observations or download the Python project.');};worker.postMessage({closes,protocol});}catch(error){if(token===operation)fail(error.message);}}$('experiment').addEventListener('submit',event=>{event.preventDefault();focusResults=true;run();});function syncSource(){const csv=$('data-source').value==='csv';$('csv-controls').hidden=!csv;$('demo-settings').hidden=csv;$('observations').required=!csv;$('seed').required=!csv;$('observations').disabled=busy||csv;$('seed').disabled=busy||csv;$('csv-file').disabled=busy||!csv;$('observations').min=$('validation-protocol').value==='strict'?'1064':'850';if(!csv&&Number($('observations').value)<Number($('observations').min))$('demo-settings').open=true;$('protocol-help').textContent=$('validation-protocol').value==='strict'?'Separate 150-row temperature and selection blocks, then a reserved final 200-outcome evaluation. Requires 1,064 prices.':'Expanding tests with shared calibration and model choice. CSV needs at least 714 prices; the synthetic demo starts at 850.';}$('data-source').addEventListener('change',syncSource);$('validation-protocol').addEventListener('change',syncSource);$('experiment').addEventListener('input',()=>{$('setup-note').hidden=false;});$('experiment').addEventListener('change',()=>{$('setup-note').hidden=false;});$('csv-file').addEventListener('change',()=>{if($('csv-file').files.length)$('data-source').value='csv';syncSource();});syncSource();$('benchmark').addEventListener('click',async()=>{if(busy)return;const token=++operation;setBusy(true,'Loading a saved Python benchmark; no Python models are executing…');try{const response=await fetch('benchmark.json',{cache:'no-cache'});if(token!==operation)return;if(!response.ok)throw Error('The benchmark file could not be loaded.');const report=await response.json();if(token!==operation)return;render(report,report.source,null,report.diagnostics);}catch(error){if(token===operation)fail(error.message);}});$('download').addEventListener('click',()=>{if(!currentReport)return;const blob=new Blob([JSON.stringify(currentReport,null,2)],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='quantlab-report.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});document.querySelectorAll('[data-view]').forEach(button=>button.addEventListener('click',()=>{document.querySelectorAll('[data-view]').forEach(b=>{const active=b===button;b.classList.toggle('active',active);b.setAttribute('aria-pressed',String(active));});document.querySelectorAll('.view').forEach(section=>section.hidden=section.id!==button.dataset.view);}));function updateGame(){try{const g=QuantLabs.game($('game').value);$('game-output').textContent=g.mixed?'A balanced mixed strategy\n\nEach player chooses either action with 50% probability. Neither can improve by changing strategy alone. The expected payoff is zero: one player’s gain is the other’s loss.':'Individual incentives, shared cost\n\nDefect is each player’s dominant strategy. Both defecting is the Nash equilibrium, with a payoff of 1 each. Both cooperating gives 3 each, so the equilibrium is not Pareto efficient.';}catch(error){$('game-output').textContent=error.message;}}$('game').addEventListener('change',updateGame);function updateRisk(){try{const data=new FormData($('risk-form')),value=name=>Number(data.get(name));const price=QuantLabs.blackScholes(value('spot'),value('strike'),value('years'),.03,value('vol'));$('risk-output').textContent=`European call ${price.call.toFixed(4)}\nEuropean put ${price.put.toFixed(4)}\n\nQuarter-Kelly fraction ${percent(QuantLabs.kelly(value('probability'),value('odds')))}\n\nOption values use the same price units as spot. Kelly applies only to the specified fixed-payoff binary bet.`;}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=`Implied annual volatility ${percent(result.volatility)}\n\nThe volatility that reproduces your premium under European, no-dividend Black–Scholes pricing. This is a risk-neutral pricing input, not a real-world return probability.`;$('iv-details').textContent=JSON.stringify(result,null,2);}catch(error){out.classList.add('lab-error');out.textContent=error.message;$('iv-details').textContent='No valid solution. Correct the premium or pricing inputs and solve again.';}}$('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();6 unmodified lines78910111213141516171819202122232425262728293031323334356 unmodified lines4243444546474849501 unmodified line5253545556575824 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301316 unmodified linesfunction escapeXML(value){return String(value).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}function svg(content,label){return `<svg viewBox="0 0 440 220" role="img" aria-label="${escapeXML(label)}">${content}</svg>`;}function grids(max=1){let s='';for(let i=0;i<=4;i++){let y=175-150*i/4;s+=`<line class="grid" x1="40" x2="430" y1="${y}" y2="${y}"/><text x="32" y="${y+4}" text-anchor="end">${(max*i/4*100).toFixed(0)}%</text>`;}return s;}function drawProbabilities(q){const labels=['Big fall','Small fall / same','Rise'];let s=grids();q.forEach((v,i)=>{const x=65+i*130,y=175-v*150;s+=`<rect x="${x}" y="${y}" width="95" height="${175-y}" fill="${[GRAY,INK,BLUE][i]}"/><text x="${x+47}" y="${Math.max(15,y-7)}" text-anchor="middle">${percent(v)}</text><text x="${x+47}" y="197" text-anchor="middle">${labels[i]}</text>`;});$('probability-chart').innerHTML=svg(s,'Next-close probabilities: '+q.map(percent).join(', '));}function drawTimeline(rows,dates){const ys=rows.map(r=>r.probabilities[0]),max=Math.max(.1,...ys)*1.1;let s=grids(max);const path=ys.map((v,i)=>`${i?'L':'M'}${40+i*390/Math.max(1,ys.length-1)},${175-v/max*150}`).join(' ');s+=`<path d="${path}" fill="none" stroke="${BLUE}" stroke-width="1.5"/>`;const first=rows[0],last=rows.at(-1);const a=first.target_date||(dates&&dates[first.target_index])||String(first.target_index),b=last.target_date||(dates&&dates[last.target_index])||String(last.target_index);s+=`<text x="40" y="200">${escapeXML(a)}</text><text x="430" y="200" text-anchor="end">${escapeXML(b)}</text>`;$('timeline-chart').innerHTML=svg(s,'Predicted downside probability across '+rows.length+' unseen observations');}function drawCalibration(rows){let s=grids();s+=`<line x1="40" y1="175" x2="430" y2="25" stroke="#a9afb8" stroke-dasharray="4 4"/>`;for(const [cls,color,label]of [[0,BLUE,'Downside'],[2,INK,'Up']]){const bins=Array.from({length:10},()=>[]);rows.forEach(row=>bins[Math.min(9,Math.floor(row.probabilities[cls]*10))].push(row));let points=[];bins.forEach(bin=>{if(!bin.length)return;const p=bin.reduce((a,r)=>a+r.probabilities[cls],0)/bin.length,o=bin.reduce((a,r)=>a+(cls===0?r.actual_log_return<-.02:r.actual_log_return>0),0)/bin.length;const x=40+p*390,y=175-o*150;points.push([x,y]);s+=`<circle cx="${x}" cy="${y}" r="${Math.min(8,3+Math.sqrt(bin.length)/3)}" fill="${color}" opacity=".8"><title>${label}: predicted ${percent(p)}, observed ${percent(o)}, n=${bin.length}</title></circle>`;});if(points.length>1)s+=`<path d="${points.map(([x,y],i)=>`${i?'L':'M'}${x},${y}`).join(' ')}" fill="none" stroke="${color}" stroke-width="1"/>`;}s+='<text x="40" y="199">0%</text><text x="430" y="199" text-anchor="end">100% predicted</text><text x="125" y="219" fill="#1d5fbf">Downside</text><text x="255" y="219">Up</text>';$('calibration-chart').innerHTML=svg(s,'Reliability bins: mean predicted probability versus observed event frequency');}function drawScores(metrics){const names=Object.keys(metrics).sort((a,b)=>metrics[a].log_loss-metrics[b].log_loss),max=Math.max(...names.map(n=>metrics[n].log_loss))*1.13;let s='';names.forEach((name,i)=>{const step=150/names.length,y=20+i*step,w=metrics[name].log_loss/max*275;s+=`<text x="100" y="${y+15}" text-anchor="end">${escapeXML(name)}</text><rect x="112" y="${y}" height="${Math.min(25,step-6)}" width="${w}" fill="${name==='empirical'?BLUE:INK}"/><text x="${118+w}" y="${y+15}">${fmt(metrics[name].log_loss)}</text>`;});s+='<text x="112" y="202">0</text><text x="430" y="202" text-anchor="end">Multiclass log loss</text>';$('score-chart').innerHTML=svg(s,'Out-of-sample log loss for each model, lower is better');}function setBusy(value,message){busy=value;$('run').disabled=value;$('benchmark').disabled=value;$('run').textContent=value?'Making a guess…':'Show my guess';$('results').setAttribute('aria-busy',String(value));document.querySelectorAll('#experiment input,#experiment select').forEach(input=>input.disabled=value);if(!value)syncSource();$('status').classList.remove('error');if(message)$('status').textContent=message;}function fail(message){if(worker){worker.terminate();worker=null;}setBusy(false);focusResults=false;$('status').textContent=message+(currentReport?' Previous results remain below.':'');$('status').classList.add('error');}function render(report,source,dates,diagnostics,cacheHit=false,identity=null){currentReport={...report,source,diagnostics,execution:{model_revision:report.precomputed?'saved-python-benchmark':MODEL_REVISION,cache_hit:cacheHit,cache_policy:'Tab memory only; at most 3 runs; ten-minute TTL from computation'}};const view=inspectionJournal.record({data_sha256:identity?.sha256||null,protocol:report.validation_protocol?.name||'historical-python',model_revision:currentReport.execution.model_revision,cache_hit:cacheHit,observations:report.test_observations,selected_log_loss:report.selected_metrics.log_loss,latest_model:report.latest_forecast.model});currentReport.experiment_manifest={schema_version:1,view,inputs:identity||{sha256:null,reason:'Original normalized input series unavailable for this historical artifact.'},provenance:{source_metadata:source,source:source.name||'Saved Python benchmark',adjustments:source.synthetic?'Synthetic generator; no market adjustments.':'Unknown. Dates and closing prices alone do not establish vendor, corporate-action adjustment or point-in-time availability.'},configuration:{model_revision:currentReport.execution.model_revision,protocol:report.validation_protocol,target:report.target,threshold:report.threshold,model_details:report.model_details},split_boundaries:report.folds,inspection_history:inspectionJournal.snapshot(),limitations:'Fingerprint is computed from normalized dates and prices, not original file bytes. History is tab-local, bounded and resettable; it does not prove independent evaluation or prevent research overfitting.'};const q=report.latest_forecast.probabilities;$('stats').replaceChildren();for(const [label,value]of [['Big fall',percent(q[0])],['Small fall or no change',percent(q[1])],['Rise',percent(q[2])]]){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);}$('plain-explanation').textContent=`These are three possible outcomes for the next price. A ${percent(q[2])} chance of a rise means the model gives that outcome about ${Math.round(q[2]*100)} chances out of 100. It can still be wrong.`;const kind=report.precomputed?'Saved example':source.synthetic?'Made-up prices for learning':'Your price file';$('status').textContent=`${kind} · ${source.rows.toLocaleString()} prices. ${report.precomputed?'You are viewing a saved result.':'Your prices stay in this browser.'}`;if(cacheHit)$('status').textContent+=' Same settings: reused the earlier calculation.';$('status').textContent+=` Result ${view.sequence} in this tab. Save the report to keep its details.`;renderQuality(source);renderValidation(report);$('forecast-context').textContent=report.validation_protocol?.name==='strict'?'Latest forecast uses the same coefficients, temperatures and model choice as the reserved evaluation. Features and EWMA volatility advance with known observations.':'Historical test scores describe a fold-by-fold selection procedure; the latest forecast may use a different model and training period.';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.';$('outcome-summary').textContent=`Big fall ${percent(q[0])} · Small fall or no change ${percent(q[1])} · Rise ${percent(q[2])}`;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.';6 unmodified linesfunction signed(value){return(value>0?'+':'')+Number(value).toFixed(4);}function intervalText(interval){return interval?.estimable&&interval.percentile95?`[${signed(interval.percentile95[0])}, ${signed(interval.percentile95[1])}]`:'Not estimable';}function renderValidation(report){const validation=report.validation;$('validation-link').hidden=!validation?.available;$('check-details').hidden=!validation?.available;for(const id of ['validation-baselines','validation-folds','validation-support','validation-intervals','validation-movement','rolling-chart','validation-policy','validation-interval-note','movement-note','rolling-description','validation-support-note','validation-interpretation'])$(id).replaceChildren();if(!validation?.available){$('validation-content').hidden=true;$('validation-verdict').textContent='This saved result does not have the newer checks.';$('validation-scope').textContent=report.precomputed?'This saved Python benchmark predates row-matched baseline diagnostics. Run a browser experiment for the new validation panel.':validation?.reason||'This report does not contain matched baseline diagnostics.';$('validation-audit').textContent='No matched validation available.';return;}$('validation-content').hidden=false;const strict=report.validation_protocol?.name==='strict';$('validation-scope').textContent=(strict?'Strict split: final 200 outcomes reserved from coefficient fitting, temperature tuning and model choice. EWMA uses only earlier known outcomes.':'Classic expanding windows: temperature and model choice share calibration; historical tests evaluate the sequential selection procedure.')+' Repeatedly inspecting these results can still overfit the evaluation.';1 unmodified line$('validation-policy').textContent=`Selected procedure log loss: ${fmt(report.selected_metrics.log_loss)} on ${validation.observations.toLocaleString()} matched ${validation.observations===1?'observation':'observations'}. Event counts: ${validation.class_counts[0]} downside, ${validation.class_counts[1]} middle, ${validation.class_counts[2]} positive.`;const intervalReference=validation.comparisons.empirical_raw.intervals.find(i=>i.block===20)||validation.comparisons.empirical_raw.intervals[0];$('validation-interval-note').textContent=intervalReference.estimable?`Main interval: ${intervalReference.block}-observation blocks, ${intervalReference.reps} resamples. Inspect sensitivity below.`:'No resampling interval is estimable for this evaluation sample and block length.';const comparisons=Object.values(validation.comparisons),validAll=comparisons.every(c=>c.intervals.length>=3&&c.intervals.every(i=>i.estimable&&i.percentile95));$('validation-verdict').textContent=validation.observations<100?'We need more examples to judge this guess.':validAll&&comparisons.every(c=>c.intervals.every(i=>i.percentile95[1]<0))?'This did better in this check. Try fresh data next.':validAll&&validation.comparisons.empirical_raw.intervals.every(i=>i.percentile95[0]>0)?'Simply counting past outcomes did better in this check.':'We cannot tell if this beats simply counting past outcomes.';for(const [key,label]of[['empirical_raw','Untuned frequency'],['empirical_calibrated','Calibrated frequency']]){const comparison=validation.comparisons[key],main=comparison.intervals.find(i=>i.block===20)||comparison.intervals[0];appendEvidenceRow('validation-baselines',[label,fmt(report.baseline_metrics[key].log_loss),signed(comparison.mean_difference),intervalText(main)]);24 unmodified linesfunction renderQuality(source){const quality=source.data_quality;$('quality-warnings').replaceChildren();$('quality-summary').textContent=quality?`${quality.rows.toLocaleString()} validated prices. ${quality.normalizedHeaderFields} header fields normalized; ${quality.trimmedValues} date/price values trimmed${quality.bomRemoved?'; initial byte-order mark removed':''}. No rows dropped or values filled.`:source.synthetic?'These prices are made up for learning. The dates are example weekdays, not a real market calendar.':'Saved benchmark: no new CSV cleaning was performed.';for(const warning of quality?.warnings||[]){const item=document.createElement('li');item.textContent=warning;$('quality-warnings').append(item);}$('quality-audit').textContent=JSON.stringify(quality||{source:source.name||'Saved benchmark',note:'No uploaded CSV cleaning audit available for this mode.'},null,2);document.querySelector('.quality-panel').classList.toggle('has-warnings',Boolean(quality?.warnings.length));document.querySelector('.quality-panel summary').textContent=quality?.warnings.length?`Price checks · ${quality.warnings.length} ${quality.warnings.length===1?'thing':'things'} to review`:'Check my prices';}$('clear-data').addEventListener('click',()=>{operation++;if(worker){worker.terminate();worker=null;}runCache.clear();inspectionJournal.clear();currentReport=null;focusResults=false;$('csv-file').value='';setBusy(false);$('download').disabled=true;$('setup-note').hidden=true;for(const id of ['plain-explanation','stats','probability-chart','timeline-chart','calibration-chart','score-chart','outcome-summary','scores-body','volatility-note','quality-warnings','forecast-context','validation-baselines','validation-folds','validation-support','validation-intervals','validation-movement','rolling-chart','validation-policy','validation-interval-note','movement-note','rolling-description','validation-support-note','validation-interpretation'])$(id).replaceChildren();for(const id of ['audit','diagnostics','explanations','quality-audit'])$(id).textContent='No forecast data retained by this app. Start a new run.';$('quality-summary').textContent='No active data. Choose a source and update the forecast.';document.querySelector('.quality-panel').classList.remove('has-warnings');document.querySelector('.quality-panel summary').textContent='Check my prices';$('status').textContent='Your results and saved calculations in this tab are cleared. Choose prices and press Show my guess to start again.';$('score-note').textContent='No current model scores.';$('validation-content').hidden=true;$('check-details').hidden=true;$('validation-link').hidden=true;$('validation-support-note').hidden=true;$('validation-verdict').textContent='Make a guess to see how we checked it.';$('validation-scope').textContent='';$('validation-audit').textContent='No validation data retained.';});function syntheticDates(n){const dates=[],day=new Date('2010-01-04T00:00:00Z');while(dates.length<n){if(day.getUTCDay()!==0&&day.getUTCDay()!==6)dates.push(day.toISOString().slice(0,10));day.setUTCDate(day.getUTCDate()+1);}return dates;}async function run(){if(busy)return;const token=++operation;setBusy(true,'Learning from earlier prices, then checking guesses against later prices…');try{let closes,dates,source;const mode=$('data-source').value,protocol=$('validation-protocol').value;if(!['classic','strict'].includes(protocol))throw Error('Choose how to check the guesses.');if(mode==='csv'){const file=$('csv-file').files[0];if(!file)throw Error('Choose a price file with date and close columns, or select Made-up prices.');if(file.size>2*1024*1024)throw Error('CSV must be no larger than 2 MiB.');const buffer=await file.arrayBuffer();if(token!==operation)return;let text;try{text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(buffer);}catch{throw Error('CSV must use valid UTF-8 encoding. Export it as UTF-8 and try again.');}const data=QuantLabs.parseCSV(text);closes=data.closes;dates=data.dates;source={synthetic:false,rows:closes.length,name:'Local CSV',calendar_gap_max_days:data.calendarGapMaxDays,data_quality:data.quality};}else{const n=Number($('observations').value),seed=Number($('seed').value);if(!Number.isInteger(n)||n<850||n>2500||!Number.isInteger(seed)||seed<0||seed>100000)throw Error('Use 850–2,500 observations and an integer seed from 0 to 100,000.');const model=await import('./model.js?v=20261026validation4');if(token!==operation)return;closes=globalThis.QuantModel.synthetic(n,seed);dates=syntheticDates(n);source={synthetic:true,rows:n,seed,name:'Browser synthetic generator',calendar:'Weekday placeholders, not exchange dates'};}if(protocol==='strict'&&closes.length<1064)throw Error('The separate test needs at least 1,064 prices. Add more prices, or open How we check the guesses and choose Repeated checks.');const sha256=await QuantProvenance.fingerprint({dates,closes});if(token!==operation)return;const identity={sha256,canonical_format:'quantlab-normalized-prices-v1: JSON array of format tag, ISO dates, finite positive numeric closes',rows:closes.length,first_date:dates[0],last_date:dates.at(-1)};const key=JSON.stringify([MODEL_REVISION,protocol,dates,closes]);const cached=runCache.get(key);if(cached){render(cached.report,source,dates,cached.diagnostics,true,identity);return;}if(worker)worker.terminate();worker=new Worker('worker.js?v=20261026validation4');worker.onmessage=event=>{if(token!==operation)return;if(event.data.error){fail(event.data.error);return;}const report=event.data.report;report.predictions.forEach(r=>{r.feature_date=dates[r.feature_index];r.target_date=dates[r.target_index];});report.latest_forecast.feature_date=dates.at(-1);runCache.set(key,{report,diagnostics:event.data.diagnostics});render(report,source,dates,event.data.diagnostics,false,identity);worker.terminate();worker=null;};worker.onerror=()=>{if(token!==operation)return;fail('Browser calculation could not finish. Try fewer observations or download the Python project.');};worker.postMessage({closes,protocol});}catch(error){if(token===operation)fail(error.message);}}$('experiment').addEventListener('submit',event=>{event.preventDefault();focusResults=true;run();});function syncSource(){const csv=$('data-source').value==='csv';$('csv-controls').hidden=!csv;$('demo-settings').hidden=csv;$('observations').required=!csv;$('seed').required=!csv;$('observations').disabled=busy||csv;$('seed').disabled=busy||csv;$('csv-file').disabled=busy||!csv;$('observations').min=$('validation-protocol').value==='strict'?'1064':'850';if(!csv&&Number($('observations').value)<Number($('observations').min))$('demo-settings').open=true;$('protocol-help').textContent=$('validation-protocol').value==='strict'?'Learn, adjust, choose, then check on 200 later outcomes. Each step uses a separate set of prices. Needs at least 1,064 prices.':'Run several checks as more prices become available. Adjusting and choosing share the same examples, so this is easier to overfit. Files need 714 prices; made-up examples need 850.';}$('data-source').addEventListener('change',syncSource);$('validation-protocol').addEventListener('change',syncSource);$('experiment').addEventListener('input',()=>{$('setup-note').hidden=false;});$('experiment').addEventListener('change',()=>{$('setup-note').hidden=false;});$('csv-file').addEventListener('change',()=>{if($('csv-file').files.length)$('data-source').value='csv';syncSource();});syncSource();$('benchmark').addEventListener('click',async()=>{if(busy)return;const token=++operation;setBusy(true,'Opening a saved example. No new models are running…');try{const response=await fetch('benchmark.json',{cache:'no-cache'});if(token!==operation)return;if(!response.ok)throw Error('The benchmark file could not be loaded.');const report=await response.json();if(token!==operation)return;render(report,report.source,null,report.diagnostics);}catch(error){if(token===operation)fail(error.message);}});$('validation-link').addEventListener('click',()=>{$('check-details').open=true;});$('download').addEventListener('click',()=>{if(!currentReport)return;const blob=new Blob([JSON.stringify(currentReport,null,2)],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='quantlab-report.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});document.querySelectorAll('[data-view]').forEach(button=>button.addEventListener('click',()=>{document.querySelectorAll('[data-view]').forEach(b=>{const active=b===button;b.classList.toggle('active',active);b.setAttribute('aria-pressed',String(active));});document.querySelectorAll('.view').forEach(section=>section.hidden=section.id!==button.dataset.view);}));function updateGame(){try{const g=QuantLabs.game($('game').value);$('game-output').textContent=g.mixed?'Keep your choice a surprise\n\nEach player picks heads or tails with a 50% chance. One wins what the other loses. If both choose at random this way, neither can do better by changing only their own plan. This is called a mixed-strategy balance.':'A choice that hurts the team\n\nEach player can cooperate or act selfishly. Acting selfishly gives more points whatever the other person does. But if both do it, they get only 1 point each. If both cooperate, they get 3 each. The best choice for one person can leave everyone worse off.';}catch(error){$('game-output').textContent=error.message;}}$('game').addEventListener('change',updateGame);function updateRisk(){try{const data=new FormData($('risk-form')),value=name=>Number(data.get(name));const price=QuantLabs.blackScholes(value('spot'),value('strike'),value('years'),.03,value('vol'));$('risk-output').textContent=`Right to buy · estimated price ${price.call.toFixed(4)}\nRight to sell · estimated price ${price.put.toFixed(4)}\n\nSmall-bet example · fraction of a pretend pot ${percent(QuantLabs.kelly(value('probability'),value('odds')))}\n\nThese are separate math examples. Option prices use the same money units as the starting price. The bet rule assumes only a win or a loss with fixed payouts; it is not a rule for buying shares.`;}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=`Yearly wiggle size that matches this option price ${percent(result.volatility)}\n\nThis finds the amount of price wiggle that makes the Black–Scholes formula match the option price you entered. It does not tell you the chance a real price will rise.`;$('iv-details').textContent=JSON.stringify(result,null,2);}catch(error){out.classList.add('lab-error');out.textContent=error.message;$('iv-details').textContent='No valid solution. Correct the premium or pricing inputs and solve again.';}}$('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.':'This is a made-up what-if story. Its chances come from the numbers you chose, not from learning real prices.';if(error>.005)status.classList.add('lab-error');$('jump-stats').replaceChildren();for(const [label,text]of [['Chance of falling past your limit',percent(result.downsideProbability)],['Bell-shaped comparison',percent(result.gaussianDownsideProbability)],['Tiny part left out of the calculation',result.omittedPoissonMass<1e-8?'<0.000001%':percent(result.omittedPoissonMass)]]){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();
3 unmodified lines45678910111213141516171819202122232425262728293031323334353637381 unmodified line40414243444546474849505152535455563 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f5f5f7"><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?v=20261026validation4"><script src="labs.js?v=20261026validation4" defer></script><script src="cache.js?v=20261026validation4" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="app.js?v=20261026provenance1" defer></script></head><body><a class="skip" href="#results">Skip to results</a><header><div><h1>QuantLab<span>Probability, made clearer.</span></h1><p>Explore what could happen next. Understand the evidence behind every estimate.</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</button><button class="tab" data-view="mathematics" aria-pressed="false">Calculators</button><button class="tab" data-view="distributions" aria-pressed="false">Scenarios</button><button class="tab" data-view="methods" aria-pressed="false">How it works</button></nav><main><section id="workbench" class="view"><aside><form id="experiment"><h2>Start with your data.</h2><p class="small">Try the example, or explore your own closing prices. Everything runs in your browser.</p><label for="data-source">Data source</label><select id="data-source"><option value="synthetic">Synthetic demo</option><option value="csv">Local CSV</option></select><label for="validation-protocol">Validation approach</label><select id="validation-protocol" aria-describedby="protocol-help"><option value="strict">Strict split</option><option value="classic">Classic expanding</option></select><p class="hint" id="protocol-help">Strict reserves the final 200 outcomes and separates temperature fitting from model choice. Requires 1,064 prices.</p><div id="csv-controls" hidden><label for="csv-file">CSV · date,close</label><input id="csv-file" type="file" accept=".csv,text/csv"><p class="hint">UTF-8 · 714–2,500 rows · 2 MiB maximum · adjusted closes · ascending ISO dates. Header case and surrounding spaces are normalized; prices and dates are never filled or reordered.</p></div><details id="demo-settings"><summary>Example settings</summary><label for="observations">Synthetic observations</label><input id="observations" type="number" min="850" max="2500" step="1" value="1200" required><label for="seed">Random seed</label><input id="seed" type="number" min="0" max="100000" step="1" value="42" required></details><details class="model-list"><summary>Models & validation</summary><h3>Browser models</h3><p>Empirical frequency<br>Ridge + Gaussian residuals<br>EWMA residual volatility<br>Multinomial logistic</p><span class="hint">Strict: train → temperature → model choice → reserved evaluation.<br>Classic: train → shared calibration/choice → expanding tests.</span></details><p id="setup-note" class="hint" role="status" hidden>Settings changed. Update the forecast to apply them.</p><button id="run" class="primary" type="submit">Update forecast</button></form><a class="results-shortcut" href="#results">View current results</a><details class="benchmark-control"><summary>Explore the Python benchmark</summary><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></details><div class="data-controls"><p id="cache-note" class="hint">Up to 3 runs cached in this tab for 10 minutes. Reloading clears the cache.</p><button id="clear-data" class="secondary" type="button">Clear forecast data</button></div></aside><div id="results" tabindex="-1"><div class="results-heading"><h2>Your forecast.</h2><p>Three possible outcomes for the next closing price.</p></div><div id="status" role="status" aria-live="polite">Preparing a browser-local synthetic experiment…</div><div class="stats" id="stats"><div><span>Downside · log return < −0.02</span><strong>—</strong></div><div><span>Positive return</span><strong>—</strong></div><div><span>Prediction error²</span><strong>—</strong></div><div><span>Evaluation observations</span><strong>—</strong></div></div><p class="hint">¹ Below −0.02 log return (about −1.98% price change). ² Multiclass log loss; lower is better.</p><details class="quality-panel"><summary>Data quality & cleaning</summary><p id="quality-summary" class="small">A data-quality summary appears after a run.</p><ul id="quality-warnings"></ul><pre id="quality-audit"></pre></details><p class="small" id="volatility-note"></p><p id="forecast-context" class="small"></p><section class="validation-panel" aria-labelledby="validation-title"><div class="evidence-heading"><h2 id="validation-title">Check the evidence.</h2><a id="validation-link" href="#validation-details" hidden>Inspect the validation</a></div><p id="validation-verdict" class="evidence-verdict">Validation appears after a completed run.</p><p id="validation-scope" class="small"></p><div id="validation-content" hidden><p id="validation-policy" class="small"></p><p id="validation-support-note" class="hint" hidden></p><div class="table-scroll"><table id="validation-baseline-table"><caption class="sr-only">Paired comparison against empirical frequency on identical test rows</caption><thead><tr><th scope="col">Baseline</th><th scope="col">Log loss</th><th scope="col">Loss difference</th><th scope="col">95% interval¹</th></tr></thead><tbody id="validation-baselines"></tbody></table></div><p id="validation-interval-note" class="hint"></p><p class="hint">Negative differences favor the selected procedure. Intervals spanning zero leave advantage unresolved; they do not establish equality.</p>1 unmodified line<details><summary>Rolling performance & shifts</summary><p id="rolling-description" class="small">Rolling windows · blue selected procedure / gray untuned empirical.</p><div id="rolling-chart" class="chart"></div><div class="table-scroll"><table id="validation-movement-table"><caption class="sr-only">Disjoint early and recent evaluation windows</caption><thead><tr><th scope="col">Window</th><th scope="col">Log loss</th><th scope="col">Untuned loss</th><th scope="col">Brier</th><th scope="col">Untuned Brier</th><th scope="col">Downside events</th><th scope="col">Entropy</th></tr></thead><tbody id="validation-movement"></tbody></table></div><p id="movement-note" class="hint"></p></details><details><summary>Interval sensitivity & assumptions</summary><p class="small">¹ Paired moving-block percentile intervals use 400 deterministic resamples. These condition on the existing predictions, omit refitting uncertainty, assume sufficient stationarity, and do not adjust for repeated research or multiple comparisons. Block lengths are sensitivity checks, not independent confirmations.</p><div class="table-scroll"><table><caption class="sr-only">Block-length sensitivity for paired loss differences</caption><thead><tr><th scope="col">Baseline</th><th scope="col">Block length</th><th scope="col">95% interval</th></tr></thead><tbody id="validation-intervals"></tbody></table></div><p id="validation-interpretation" class="small"></p></details><details><summary>Validation audit · JSON</summary><pre id="validation-audit"></pre></details></div></section><div class="charts"><section class="plot"><h2>What could happen next?</h2><p>Three outcomes. One complete probability distribution.</p><div id="probability-chart" class="chart"></div><p id="outcome-summary" class="outcome-summary"></p></section><section class="plot"><h2>Risk over time</h2><p>Estimated downside on data the model had not seen</p><div id="timeline-chart" class="chart"></div></section><section class="plot"><h2>Do estimates match reality?</h2><p>Closer to the dashed line is better. Small samples are noisy.</p><div id="calibration-chart" class="chart"></div></section><section class="plot"><h2>How the models compare</h2><p>Prediction error on unseen data · lower is better</p><div id="score-chart" class="chart"></div></section></div><details class="scores"><summary>Compare detailed model scores</summary><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></details><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>Export research 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>Explore the mathematics.</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><div id="game-output" class="calculation-result" aria-live="polite"></div></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><div id="risk-output" class="calculation-result" aria-live="polite"></div><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><div id="iv-output" class="calculation-result" aria-live="polite"></div><details><summary>Solver precision & bounds</summary><pre id="iv-details"></pre></details></section></section><section id="distributions" class="view" hidden><h2>Explore a different scenario.</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">Update scenario</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>Understand your results.</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>Data cleaning & privacy</h3><p>CSV parsing is bounded to 2 MiB, 2,500 price rows, 64 columns and 16,384 characters per field. We normalize header case, trim surrounding date/price whitespace and accept an initial byte-order mark. Every change is counted in the report. Duplicate dates, missing values and invalid prices are rejected with row numbers. Large moves, unchanged prices and calendar gaps are flagged and retained. We cannot verify whether prices are adjusted from two columns alone.</p><h3>Temporary caching</h3><p>Identical validated dates, prices, validation approach and model revision can reuse one of up to three fitted runs in this tab for ten minutes from computation. Cache hits are labeled. No uploaded prices or reports are written to localStorage, IndexedDB or a service-worker cache. Reloading or Clear forecast data removes application-held data; browser and operating-system memory reclamation is outside the app’s control. Public app assets may be cached by your browser or Hugging Face. The saved Python benchmark is fetched with revalidation.</p><h3>Validation contract</h3><p>At close t, returns, momentum, realized volatility and drawdown use only observations through t. Strict mode fits at least 500 training rows, temperatures on 150 later rows, and model choice on another 150 rows. A one-row embargo separates each boundary, followed by a reserved final 200-outcome evaluation. The coefficients, temperatures and model choice remain frozen for the latest forecast; features and EWMA state advance causally. Classic mode uses expanding training, a shared 150-row calibration/selection block and test blocks of up to 200. Repeatedly inspecting a reserved evaluation can still overfit it. This is not a permanently sealed holdout. Never tune using the 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>Classic calibration reuses data for temperatures and model choice. Strict mode separates these stages but cannot prevent repeated human inspection. Financial tails and nonstationarity can invalidate normal residual assumptions. Tiny test samples and sparse reliability bins are especially unreliable. The validation panel shows matched untuned and calibrated empirical baselines, fold populations, support warnings and descriptive paired uncertainty. It shows rolling loss, Brier score, entropy and event counts; it does not implement feature-drift testing or an automatic fallback strategy. The saved Python benchmark predates this panel and does not have row-matched baseline probabilities, so its new comparisons remain unavailable. 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="CACHING.md">Caching design</a> · <a href="SECURITY-REVIEW.md">Data & cache security review</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>3 unmodified lines456789101112131415161718192021222324252627282930313233343536371 unmodified line39404142434445464748495051525354553 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f5f5f7"><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?v=20261027simple1"><script src="labs.js?v=20261026validation4" defer></script><script src="cache.js?v=20261026validation4" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="app.js?v=20261027simple1" defer></script></head><body><a class="skip" href="#results">Skip to results</a><header><div><h1>QuantLab<span>What might happen next?</span></h1><p>Try made-up prices. See three guesses about the next recorded price, then learn how we checked them.</p></div></header><nav aria-label="Research views"><button class="tab active" data-view="workbench" aria-pressed="true">Price explorer</button><button class="tab" data-view="mathematics" aria-pressed="false">Number games</button><button class="tab" data-view="distributions" aria-pressed="false">What if?</button><button class="tab" data-view="methods" aria-pressed="false">Help</button></nav><main><section id="workbench" class="view"><aside><form id="experiment"><h2>Start here.</h2><p class="small">Press the blue button to try made-up prices. You can also use your own price file. The calculations happen in this browser.</p><label for="data-source">Choose your prices</label><select id="data-source"><option value="synthetic">Made-up prices</option><option value="csv">My price file</option></select><button id="run" class="primary" type="submit">Show my guess</button><details><summary>How we check the guesses</summary><label for="validation-protocol">Checking method</label><select id="validation-protocol" aria-describedby="protocol-help"><option value="strict">Separate practice and check</option><option value="classic">Repeated checks over time</option></select><p class="hint" id="protocol-help">The first method saves the last 200 answers for checking. It needs at least 1,064 prices. The other method checks several periods in order.</p></details><div id="csv-controls" hidden><label for="csv-file">Choose a CSV file · date,close</label><input id="csv-file" type="file" accept=".csv,text/csv"><p class="hint">Use a CSV text file with date and close columns, oldest date first (for example 2026-01-01). It needs 1,064–2,500 prices with the usual checking method, or at least 714 with repeated checks. Maximum file size: 2 MiB. Use prices adjusted for splits and dividends. Missing prices and dates are not filled in.</p></div><details id="demo-settings"><summary>Change the example</summary><label for="observations">Number of made-up prices</label><input id="observations" type="number" min="850" max="2500" step="1" value="1200" required><label for="seed">Example number</label><input id="seed" type="number" min="0" max="100000" step="1" value="42" required><p class="hint">The same example number makes the same pretend prices. Change it to try a different story.</p></details><details class="model-list"><summary>Meet the guessing methods</summary><h3>Four ways to make a guess</h3><p>Count earlier outcomes<br>Look for price patterns<br>Watch changing wiggles<br>Learn three outcome chances</p><span class="hint">Each method learns from earlier prices. The checking method decides which later answers are saved to check it.</span></details><p id="setup-note" class="hint" role="status" hidden>Settings changed. Press Show my guess to use them.</p></form><a class="results-shortcut" href="#results">Go to my results</a><details class="benchmark-control"><summary>Try a saved research example</summary><p class="small">See a saved example made with extra Python tools. Opening it does not run those tools.</p><button id="benchmark" class="secondary">Open saved example</button><p class="hint">Made-up prices · 900 price steps.<br>This opens saved results, not a new calculation.</p></details><div class="data-controls"><p id="cache-note" class="hint">This tab remembers up to 3 calculations for 10 minutes so repeats are quicker. Reload to forget them.</p><button id="clear-data" class="secondary" type="button">Clear my results</button></div></aside><div id="results" tabindex="-1"><div class="results-heading"><h2>Your price guess.</h2><p>Which of these three things might happen at the next recorded closing price?</p></div><div id="status" role="status" aria-live="polite">Getting the made-up price example ready…</div><p id="plain-explanation" class="small"></p><div class="stats" id="stats"><div><span>Big fall</span><strong>—</strong></div><div><span>Small fall or no change</span><strong>—</strong></div><div><span>Rise</span><strong>—</strong></div></div><details><summary>What counts as a big fall?</summary><p class="hint">A big fall is a drop greater than about 1.98%. The exact cutoff is a log return below −0.02. The middle group includes both cutoff boundaries, and a rise means any positive return.</p></details><details class="quality-panel"><summary>Check my prices</summary><p id="quality-summary" class="small">A data-quality summary appears after a run.</p><ul id="quality-warnings"></ul><pre id="quality-audit"></pre></details><details><summary>More about this guess</summary><p class="small" id="volatility-note"></p><p id="forecast-context" class="small"></p></details><section class="validation-panel" aria-labelledby="validation-title"><div class="evidence-heading"><h2 id="validation-title">Did the guesses help?</h2><a id="validation-link" href="#check-details" hidden>See the checks</a></div><p id="validation-verdict" class="evidence-verdict">Make a guess to see how we checked it.</p><details id="check-details" hidden><summary>See how we checked</summary><div id="validation-content" hidden><p id="validation-scope" class="small"></p><p id="validation-policy" class="small"></p><p id="validation-support-note" class="hint" hidden></p><div class="table-scroll"><table id="validation-baseline-table"><caption class="sr-only">Paired comparison against empirical frequency on identical test rows</caption><thead><tr><th scope="col">Baseline</th><th scope="col">Log loss</th><th scope="col">Loss difference</th><th scope="col">95% interval¹</th></tr></thead><tbody id="validation-baselines"></tbody></table></div><p id="validation-interval-note" class="hint"></p><p class="hint">Negative differences favor the selected procedure. Intervals spanning zero leave advantage unresolved; they do not establish equality.</p>1 unmodified line<details><summary>Rolling performance & shifts</summary><p id="rolling-description" class="small">Rolling windows · blue selected procedure / gray untuned empirical.</p><div id="rolling-chart" class="chart"></div><div class="table-scroll"><table id="validation-movement-table"><caption class="sr-only">Disjoint early and recent evaluation windows</caption><thead><tr><th scope="col">Window</th><th scope="col">Log loss</th><th scope="col">Untuned loss</th><th scope="col">Brier</th><th scope="col">Untuned Brier</th><th scope="col">Downside events</th><th scope="col">Entropy</th></tr></thead><tbody id="validation-movement"></tbody></table></div><p id="movement-note" class="hint"></p></details><details><summary>Interval sensitivity & assumptions</summary><p class="small">¹ Paired moving-block percentile intervals use 400 deterministic resamples. These condition on the existing predictions, omit refitting uncertainty, assume sufficient stationarity, and do not adjust for repeated research or multiple comparisons. Block lengths are sensitivity checks, not independent confirmations.</p><div class="table-scroll"><table><caption class="sr-only">Block-length sensitivity for paired loss differences</caption><thead><tr><th scope="col">Baseline</th><th scope="col">Block length</th><th scope="col">95% interval</th></tr></thead><tbody id="validation-intervals"></tbody></table></div><p id="validation-interpretation" class="small"></p></details><details><summary>Validation audit · JSON</summary><pre id="validation-audit"></pre></details></div></details></section><div class="charts"><section class="plot"><h2>What could happen next?</h2><p>Each bar shows a chance out of 100. Together they cover every outcome. Rounding may put the total just above or below 100%.</p><div id="probability-chart" class="chart"></div><p id="outcome-summary" class="outcome-summary"></p></section></div><details><summary>Explore more charts</summary><div class="charts"><section class="plot"><h2>How the chance of a drop changed</h2><p>Earlier guesses about a drop, checked against later answers.</p><div id="timeline-chart" class="chart"></div></section><section class="plot"><h2>Did the chances match what happened?</h2><p>Closer to the dashed line is better. A few answers cannot tell us much.</p><div id="calibration-chart" class="chart"></div></section><section class="plot"><h2>Which guessing method did better?</h2><p>Guessing errors on check data. Lower is better.</p><div id="score-chart" class="chart"></div></section></div></details><details><summary>For curious explorers · technical details</summary><details class="scores"><summary>Compare the exact scores</summary><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></details><div class="audit-grid"><details><summary>What happened in this run?</summary><pre id="audit">No completed run.</pre></details><details><summary>Extra number checks</summary><pre id="diagnostics">No completed run.</pre></details><details><summary>Saved Python example details</summary><pre id="explanations">Load the precomputed Python benchmark to inspect its tree explanation.</pre></details></div></details><button id="download" class="secondary" disabled>Save my results · JSON file</button><p class="hint">These are uncertain guesses for learning, not instructions to buy or sell. We have not shown that they can make money.</p></div></section><section id="mathematics" class="view" hidden><h2>Play with numbers.</h2><p>Try a game or explore a pretend deal. These examples are separate from the price guesses and do not show how to make money.</p><div class="lab-grid"><section class="plot"><h3>What happens when two people choose?</h3><label for="game">Choose a game</label><select id="game"><option value="prisoner">Teamwork trap · prisoner’s dilemma</option><option value="matching">Coin guessing · matching pennies</option></select><div id="game-output" class="calculation-result" aria-live="polite"></div></section><section class="plot"><h3>A price deal and a two-outcome bet</h3><p>A pretend option gives you a right to buy or sell later at an agreed price. The bet example has only two answers: win or lose. It is a math example, not a suggestion to bet.</p><form id="risk-form"><div class="input-grid"><label>Price today<input name="spot" type="number" min="1" step="1" value="100" required></label><label>Agreed deal price<input name="strike" type="number" min="1" step="1" value="100" required></label><label>Time left · years<input name="years" type="number" min="0.01" max="10" step="0.01" value="1" required></label><label>Yearly wiggle size · 0.20 means 20%<input name="vol" type="number" min="0.01" max="3" step="0.01" value="0.2" required></label><label>Chance of winning · 0.55 means 55%<input name="probability" type="number" min="0" max="1" step="0.01" value="0.55" required></label><label>Profit per 1 unit bet · if you win<input name="odds" type="number" min="0.1" max="10" step="0.1" value="1" required></label></div><button class="secondary">Calculate</button></form><div id="risk-output" class="calculation-result" aria-live="polite"></div><details><summary>Rules behind these examples</summary><p class="hint">Black–Scholes assumes a European option, no dividends, constant volatility and a 3% interest rate. The separate Kelly example uses capped quarter-Kelly for a bet with fixed win and loss payoffs. It is not a stock allocation.</p></details></section></div><section class="plot iv-lab"><h3>What wiggle size fits this deal price?</h3><p>An option is a right to buy or sell later at an agreed price. This calculator finds the yearly wiggle size that fits its price, using the Black–Scholes formula. It is separate from the price explorer.</p><form id="iv-form"><div class="input-grid"><label>Price today<input name="spot" type="number" min="0.01" value="100" step="0.01" required></label><label>Agreed deal price<input name="strike" type="number" min="0.01" value="100" step="0.01" required></label><label>Time left · years<input name="years" type="number" min="0.001" max="10" value="1" step="0.001" required></label><label>Yearly interest rate · 0.03 means 3%<input name="rate" type="number" min="-1" max="1" value="0.03" step="0.01" required></label><label>Option price · same units as price today<input name="premium" type="number" min="0" value="9.4134" step="0.0001" required></label><label>Kind of deal<select name="type"><option value="call">Right to buy · call</option><option value="put">Right to sell · put</option></select></label></div><button class="secondary">Find the wiggle size</button></form><div id="iv-output" class="calculation-result" aria-live="polite"></div><details><summary>How the answer was found</summary><pre id="iv-details"></pre></details></section></section><section id="distributions" class="view" hidden><h2>What if prices took surprise jumps?</h2><p class="scenario-note">Make a pretend world: prices wiggle and sometimes jump. You choose all the settings. This does not learn from your price file or predict real markets.</p><div class="scenario-layout"><form id="jump-form"><h3>Build a pretend year</h3><label>Yearly growth setting · 0.06 is about 6%<input name="mu" type="number" min="-1" max="1" step="0.01" value="0.06" required></label><label>Yearly wiggle size · 0.20 means 20%<input name="sigma" type="number" min="0.01" max="2" step="0.01" value="0.2" required></label><label>Average surprise jumps per year<input name="intensity" type="number" min="0" max="50" step="0.5" value="2" required></label><label>Average jump · log units<input name="jumpMean" type="number" min="-1" max="1" step="0.01" value="-0.08" required></label><label>How much jumps vary · log units<input name="jumpStd" type="number" min="0" max="1" step="0.01" value="0.1" required></label><label>How many price steps ahead?<input name="horizon" type="number" min="1" max="252" step="1" value="21" required></label><label>Drop cutoff · log units<input name="threshold" type="number" min="-2" max="2" step="0.01" value="-0.02" required></label><button class="primary">Show this pretend world</button><p class="hint">This pretend year has 252 equal price steps. For the log inputs, −0.02 is about a 1.98% drop and −0.08 is about a 7.69% drop. The growth setting includes the jumps. Over one year the average price change is exp(growth setting) − 1; 0.06 gives about 6.18%.</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>Where might the price change land?</h3><p>Taller parts show where changes cluster. The area under a part of the curve gives its chance. Technical name: probability density (PDF).</p><div id="jump-pdf" class="chart"></div></section><section class="plot"><h3>What is the chance of this change or less?</h3><p>Read the blue curve for the world with jumps. Gray is a smooth bell-shaped comparison with the same mean and variance. Technical name: cumulative probability (CDF).</p><div id="jump-cdf" class="chart"></div></section></div><details><summary>Rules and calculation checks</summary><pre id="jump-audit"></pre></details></div></div></section><section id="methods" class="view prose" hidden><h2>A quick guide.</h2><p>QuantLab is a learning tool. It makes uncertain guesses about the next price, then checks earlier guesses against answers.</p><h3>Try it in three steps</h3><ol><li>Open <b>Price explorer</b>. Keep <b>Made-up prices</b> selected.</li><li>Press <b>Show my guess</b>. The three bars show the chances of all three outcomes.</li><li>Read <b>Did the guesses help?</b> A clever method is only useful if it beats a simple comparison.</li></ol><h3>What do the words mean?</h3><p><b>Chance:</b> how often something might happen in many similar situations. A 20% chance means about 20 out of 100, not a promise about one outcome.</p><p><b>Guessing method:</b> a set of rules that learns from earlier prices. Researchers call it a model.</p><p><b>Practice and check:</b> learn from earlier answers, then check on later answers that were kept apart. Looking at the check answers again and again can still make the test unfair.</p><p><b>Made-up prices:</b> a repeatable example, not real market data. Doing well on it does not show that a method works in real markets.</p><h3>Find your way around</h3><p><b>Price explorer</b> makes the three guesses. <b>Number games</b> has separate calculators. <b>What if?</b> lets you invent a world with surprise price jumps. The arrows beside extra details open them when you want to learn more.</p><h3>Your file stays in this browser</h3><p>Your CSV is read here and is not sent to a modeling server. A few recent calculations are kept temporarily in this tab. Use <b>Clear my results</b> or reload to remove the app’s saved data. The browser controls when memory is actually reclaimed.</p><p>These guesses can be wrong. They are not instructions to buy, sell or place a bet. This app has not shown that its guesses can make money.</p><details><summary>More detail · methods, privacy and limits</summary><h3>Data cleaning & privacy</h3><p>CSV parsing is bounded to 2 MiB, 2,500 price rows, 64 columns and 16,384 characters per field. We normalize header case, trim surrounding date/price whitespace and accept an initial byte-order mark. Every change is counted in the report. Duplicate dates, missing values and invalid prices are rejected with row numbers. Large moves, unchanged prices and calendar gaps are flagged and retained. We cannot verify whether prices are adjusted from two columns alone.</p><h3>Temporary caching</h3><p>Identical validated dates, prices, validation approach and model revision can reuse one of up to three fitted runs in this tab for ten minutes from computation. Cache hits are labeled. No uploaded prices or reports are written to localStorage, IndexedDB or a service-worker cache. Reloading or Clear my results removes application-held data; browser and operating-system memory reclamation is outside the app’s control. Public app assets may be cached by your browser or Hugging Face. The saved Python benchmark is fetched with revalidation.</p><h3>Validation contract</h3><p>At close t, returns, momentum, realized volatility and drawdown use only observations through t. Strict mode fits at least 500 training rows, temperatures on 150 later rows, and model choice on another 150 rows. A one-row embargo separates each boundary, followed by a reserved final 200-outcome evaluation. The coefficients, temperatures and model choice remain frozen for the latest forecast; features and EWMA state advance causally. Classic mode uses expanding training, a shared 150-row calibration/selection block and test blocks of up to 200. Repeatedly inspecting a reserved evaluation can still overfit it. This is not a permanently sealed holdout. Never tune using the 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>Classic calibration reuses data for temperatures and model choice. Strict mode separates these stages but cannot prevent repeated human inspection. Financial tails and nonstationarity can invalidate normal residual assumptions. Tiny test samples and sparse reliability bins are especially unreliable. The validation panel shows matched untuned and calibrated empirical baselines, fold populations, support warnings and descriptive paired uncertainty. It shows rolling loss, Brier score, entropy and event counts; it does not implement feature-drift testing or an automatic fallback strategy. The saved Python benchmark predates this panel and does not have row-matched baseline probabilities, so its new comparisons remain unavailable. 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="CACHING.md">Caching design</a> · <a href="SECURITY-REVIEW.md">Data & cache security review</a> · <a href="python-project.zip" download>Full Python source and tests</a></p></details></section></main><footer><span>QuantLab · explore, ask, check.</span><span>Runs in your browser · free to use</span></footer></body></html>
10 unmodified lines11121310 unmodified lines@media(min-width:701px){aside{max-height:calc(100vh - 48px);max-height:calc(100dvh - 48px);overflow-y:auto}}#results,.validation-panel{min-width:0}@media(max-width:700px){#workbench{grid-template-columns:minmax(0,1fr)}#validation-baseline-table{table-layout:fixed;width:100%;font-size:11px}#validation-baseline-table th,#validation-baseline-table td{white-space:normal;overflow-wrap:anywhere;padding:12px 5px;vertical-align:top}#validation-baseline-table th:first-child{width:29%}#validation-baseline-table th:nth-child(2){width:18%}#validation-baseline-table th:nth-child(3){width:23%}#validation-baseline-table th:nth-child(4){width:30%}}10 unmodified lines1112131415161718192021222324252610 unmodified lines@media(min-width:701px){aside{max-height:calc(100vh - 48px);max-height:calc(100dvh - 48px);overflow-y:auto}}#results,.validation-panel{min-width:0}@media(max-width:700px){#workbench{grid-template-columns:minmax(0,1fr)}#validation-baseline-table{table-layout:fixed;width:100%;font-size:11px}#validation-baseline-table th,#validation-baseline-table td{white-space:normal;overflow-wrap:anywhere;padding:12px 5px;vertical-align:top}#validation-baseline-table th:first-child{width:29%}#validation-baseline-table th:nth-child(2){width:18%}#validation-baseline-table th:nth-child(3){width:23%}#validation-baseline-table th:nth-child(4){width:30%}}/* Beginner reading path: outcomes first, methods on request. */#plain-explanation{font-size:17px;line-height:1.65;max-width:64ch;margin:12px 0 24px;color:var(--ink,#1d1d1f)}#stats{grid-template-columns:repeat(3,minmax(0,1fr));margin-bottom:20px}#stats span{font-size:14px;line-height:1.5}#stats strong{font-size:32px}#results>details,.beginner-details{margin:18px 0}#results>.charts{margin:24px 0}.charts>.plot:only-child{grid-column:1/-1}#results>details .charts{margin-top:20px}#results summary{font-size:15px;min-height:44px;display:list-item;padding:10px 0}#results .validation-panel .evidence-verdict{font-size:20px;line-height:1.45;max-width:50ch}.prose li{margin:12px 0;line-height:1.7}.prose ol,.prose ul{padding-left:24px}@media(max-width:700px){#stats{grid-template-columns:1fr;gap:12px}#stats>div{border:0;border-bottom:1px solid var(--line);padding:0 0 12px;display:flex;justify-content:space-between;align-items:center;gap:20px}#stats>div:last-child{border:0}#stats strong{font-size:28px}#plain-explanation{font-size:16px}.tab{font-size:12px;white-space:normal}#status{margin-bottom:16px}}h1,h2,h3{text-wrap:balance}button,a,summary{touch-action:manipulation}
DESIGN.md+6
README.md+3
VERIFICATION.md+6
app.js+28-26
index.html+30-31
style.css+13