PabloRod11's picture
Add ticker forecasts and transparent evaluation support
95ca804 verified
Raw History Blame Contribute Delete
43.7 kB
'use strict';
const $=id=>document.getElementById(id),percent=x=>x>0&&x<.0001?'<0.01%':x<1&&x>.9999?'>99.99%':(100*x).toFixed(2)+'%',fmt=x=>Number(x).toFixed(4);
let currentReport=null,busy=false,worker=null,focusResults=false,operation=0;
let forwardOperation=0,forwardCheck=null;
const runCache=QuantCache.createRunCache(),MODEL_REVISION='browser-untuned-20261027-v6';
const inspectionJournal=QuantProvenance.createJournal();
const INK='#34343a',BLUE='#0066cc',GRAY='#767680';
function escapeXML(value){return String(value).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&apos;'}[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">${escapeXML(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 ${escapeXML(percent(p))}, observed ${escapeXML(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.':source.adjustment_basis||'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.'};
currentReport.forward_check=identity&&!report.precomputed?QuantForward.createRecord(currentReport,identity,source):null;
const q=report.latest_forecast.probabilities;
$('forecast-source').textContent=source.kind==='market_snapshot'?`${source.name} · historical snapshot through ${source.last_observation_date}. These chances concern the next recorded close after that date, not a live quote or today’s forecast.`:source.synthetic?'Practice forecast from made-up prices.':report.precomputed?'Saved historical research example.':`Your price file${identity?.last_date?' · through '+identity.last_date:''}. Vendor and adjustment are not independently verified.`;
renderOutcomeSupport(report);
const supportMessages=report.feature_support?.warnings?.map(w=>w.message)||[];$('support-warning').textContent=supportMessages.join(' ');$('support-warning').hidden=!supportMessages.length;
$('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=`A ${percent(q[2])} chance of a rise means about ${Math.round(q[2]*100)} out of 100 similar next steps, according to this model. It is a guess, not a promise.`;
const kind=report.precomputed?'Saved example':source.synthetic?'Made-up prices for learning':source.kind==='market_snapshot'?source.name+' · dated snapshot':'Your price file';
$('status').textContent=`${kind} · ${source.rows.toLocaleString()} prices. ${report.precomputed?'You are viewing a saved result.':source.kind==='market_snapshot'?'Public dated prices; calculations run in this browser.':'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.';
$('audit').textContent=JSON.stringify({experiment_manifest:currentReport.experiment_manifest,feature_support:report.feature_support,source,validation_protocol:report.validation_protocol,target:report.target,threshold:report.threshold,latest_forecast:report.latest_forecast,model_details:report.model_details,folds:report.folds,model_status:report.model_status||'Browser baselines only',limitations:report.limitations},null,2);
$('diagnostics').textContent=JSON.stringify(diagnostics||{},null,2);
$('explanations').textContent=report.precomputed?JSON.stringify({mode:'PRECOMPUTED; no Python executes on this host',tuning_trials:report.tuning_trials,shap_explanation:report.shap_explanation,mlflow:report.mlflow,benchmark_date:report.benchmark_date},null,2):'Browser run: no SHAP, Optuna, XGBoost, LightGBM or MLflow execution. Load the precomputed Python benchmark to inspect its saved results, or download the Python project.';
$('download').disabled=false;setBusy(false);$('setup-note').hidden=true;if(focusResults&&!$('workbench').hidden){$('results').focus();}focusResults=false;
}
function renderOutcomeSupport(report){
const outcomes=report.validation?.outcomes;
$('evaluation-support').hidden=!outcomes?.length;$('evaluation-outcomes').replaceChildren();$('evaluation-warning').textContent='';$('evaluation-warning').hidden=true;
if(!outcomes?.length)return;
for(const row of outcomes)appendEvidenceRow('evaluation-outcomes',[row.label,`${row.events} / ${row.observations}`,percent(row.mean_predicted),percent(row.observed_rate)]);
const rows=report.predictions,first=rows?.[0]?.target_date,last=rows?.at(-1)?.target_date;
$('evaluation-scope').textContent=`${outcomes[0].observations} earlier outcomes${first&&last?' · '+first+' to '+last:''}. Average predicted chances and observed rates use the same evaluation rows.`;
const sparse=outcomes.filter(row=>row.low_support);
if(sparse.length){$('evaluation-warning').hidden=false;$('evaluation-warning').textContent=sparse.map(row=>`${row.label}: only ${row.events} evaluation ${row.events===1?'event':'events'}.`).join(' ')+' Fewer than 10 is a support warning, not a calibrated confidence threshold; accuracy for these outcomes is not well established.';}
}
function invalidateForecast(message='Settings changed. Press Show my guess to calculate for these inputs.'){
operation++;if(worker){worker.terminate();worker=null;}currentReport=null;focusResults=false;setBusy(false);$('download').disabled=true;
for(const id of ['stats','support-warning','forecast-source','plain-explanation','probability-chart','timeline-chart','calibration-chart','score-chart','rolling-chart','outcome-summary','scores-body','volatility-note','forecast-context','evaluation-outcomes','evaluation-warning','evaluation-scope','quality-warnings','validation-baselines','validation-folds','validation-support','validation-intervals','validation-movement'])$(id).replaceChildren();
for(const id of ['audit','diagnostics','explanations','quality-audit','validation-audit'])$(id).textContent='No current forecast. Calculate with the selected inputs.';
$('evaluation-support').hidden=true;$('evaluation-warning').hidden=true;$('support-warning').hidden=true;$('validation-content').hidden=true;$('check-details').hidden=true;$('validation-link').hidden=true;
$('validation-verdict').textContent='Make a guess to see how we checked it.';$('quality-summary').textContent='No current price checks.';$('validation-scope').textContent='';$('status').textContent=message;
}
function appendEvidenceRow(id,values){const row=document.createElement('tr');for(const value of values){const cell=document.createElement('td');cell.textContent=String(value);row.append(cell);}$(id).append(row);}
function 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.';
const lowSupport=validation.warnings.filter(w=>w.startsWith('Fold ')).length;$('validation-support-note').hidden=!lowSupport;$('validation-support-note').textContent=`Low event support in ${lowSupport} stage/class checks. Inspect fold results; the 10-event warning threshold is a heuristic.`;
$('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.comparisons.empirical_raw.matches_probabilities?'This used the same chances as simply counting past outcomes.':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)]);
for(const interval of comparison.intervals)appendEvidenceRow('validation-intervals',[label,interval.block,intervalText(interval)]);
}
for(const [index,fold]of report.folds.entries()){
const total=counts=>counts?.reduce((sum,n)=>sum+n,0),down=counts=>counts?counts[0]:'shared';
appendEvidenceRow('validation-folds',[`${index+1} · ${fold.selected}`,total(fold.training_class_counts),fold.temperature_class_counts?total(fold.temperature_class_counts):'shared',total(fold.selection_class_counts),fold.test_observations,fmt(fold.test_metrics.log_loss),fmt(fold.raw_empirical_metrics.log_loss),`${down(fold.temperature_class_counts)} / ${down(fold.selection_class_counts)} / ${down(fold.test_class_counts)}`]);
}
const support=validation.warnings.filter(w=>w.startsWith('Fold ')||w.includes('degenerate')||w.includes('resampling')||w.includes('uncertainty cannot'));
for(const warning of support){const item=document.createElement('li');item.textContent=warning;$('validation-support').append(item);}
$('rolling-description').textContent=(validation.observations>=100?'100-observation rolling windows.':`Only ${validation.observations} evaluation ${validation.observations===1?'observation':'observations'}; a full 100-observation window is unavailable.`)+' Blue: selected procedure. Gray: untuned empirical. Movement is descriptive and does not trigger trading or retraining.';
$('validation-movement-table').hidden=!validation.movement;drawRolling(validation.rolling,report.predictions);
if(validation.movement){for(const [key,label]of[['early','First 100'],['recent','Latest 100']]){const window=validation.movement[key];appendEvidenceRow('validation-movement',[label,fmt(window.log_loss),fmt(window.raw_log_loss),fmt(window.brier),fmt(window.raw_brier),window.downside_count,fmt(window.mean_entropy)]);}$('movement-note').textContent=`Two disjoint 100-observation windows. Recent-minus-early loss: ${signed(validation.movement.recent.log_loss-validation.movement.early.log_loss)}. Entropy uses natural-log units; Brier is the three-class probability error. Differences can reflect chance, changing event mix or regime shifts; they are not a formal drift test.`;}
else $('movement-note').textContent='At least 200 test observations are needed for disjoint first/recent 100-observation windows.';
$('validation-interpretation').textContent=validation.interpretation+' '+validation.warnings.filter(w=>!w.startsWith('Fold ')).join(' ');
$('validation-audit').textContent=JSON.stringify({protocol:report.validation_protocol,baseline_metrics:report.baseline_metrics,validation,folds:report.folds},null,2);
}
function drawRolling(rows,predictions){
if(!rows.length)return;const max=Math.max(.01,...rows.flatMap(r=>[r.log_loss,r.raw_log_loss]))*1.1;let content='';
for(let i=0;i<=4;i++){const y=175-i*150/4;content+=`<line class="grid" x1="45" x2="425" y1="${y}" y2="${y}"/><text x="38" y="${y+4}" text-anchor="end">${(max*i/4).toFixed(2)}</text>`;}
for(const [key,color,dash]of[['raw_log_loss',GRAY,'4 3'],['log_loss',BLUE,'']]){const coords=rows.map((r,i)=>[45+i*380/Math.max(1,rows.length-1),175-r[key]/max*150]);content+=`<path d="${coords.map(([x,y],i)=>`${i?'L':'M'}${x},${y}`).join(' ')}" fill="none" stroke="${color}" stroke-width="1.7" stroke-dasharray="${dash}"/>`;if(rows.length===1)content+=`<circle cx="${coords[0][0]}" cy="${coords[0][1]}" r="3" fill="${color}"/>`;}
const label=index=>predictions.find(p=>p.target_index===index)?.target_date||`Price row ${index+1}`;
content+=`<text x="45" y="200">${escapeXML(label(rows[0].end_target_index))}</text><text x="425" y="200" text-anchor="end">${escapeXML(label(rows.at(-1).end_target_index))}</text><text x="235" y="219" text-anchor="middle">Rolling log loss · lower is better</text>`;
$('rolling-chart').innerHTML=svg(content,'Rolling selected and untuned empirical log loss on the same test observations');
}
function renderQuality(source){
const quality=source.data_quality;
$('quality-warnings').replaceChildren();
$('quality-summary').textContent=source.kind==='market_snapshot'?`${source.rows.toLocaleString()} validated public adjusted prices for ${source.ticker}; observed dates are unique and increasing. No gaps filled. Vendor adjustment is declared, not independently reconstructed.`: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',source_metadata:source,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++;resetForward();
if(worker){worker.terminate();worker=null;}runCache.clear();inspectionJournal.clear();currentReport=null;focusResults=false;
$('csv-file').value='';$('support-warning').hidden=true;$('evaluation-support').hidden=true;$('evaluation-warning').hidden=true;$('forecast-source').textContent='';$('evaluation-outcomes').replaceChildren();$('evaluation-warning').textContent='';$('evaluation-scope').textContent='';setBusy(false);$('download').disabled=true;$('setup-note').hidden=true;
for(const id of ['support-warning','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 requestedFocus=focusResults;invalidateForecast('Preparing the selected prices…');focusResults=requestedFocus;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 if(mode==='market'){const ticker=$('market-ticker').value;const catalog=await QuantMarket.loadSnapshot();if(token!==operation)return;const selected=catalog.find(s=>s.ticker===ticker);if(!selected)throw Error('Choose a ticker available in the dated snapshot.');closes=selected.closes;dates=selected.dates;source=QuantMarket.source(selected);}
else if(mode==='synthetic'){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=20261027audit2');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'};}
else throw Error('Choose a valid price source.');
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),last_close:closes.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=20261029forecast1');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('invalid',event=>{for(let parent=event.target.parentElement;parent;parent=parent.parentElement){if(parent.tagName==='DETAILS')parent.open=true;}},true);
$('experiment').addEventListener('submit',event=>{event.preventDefault();focusResults=true;run();});
function syncSource(){const mode=$('data-source').value,csv=mode==='csv',market=mode==='market',synthetic=mode==='synthetic';$('csv-controls').hidden=!csv;$('market-controls').hidden=!market;$('demo-settings').hidden=!synthetic;$('observations').required=synthetic;$('seed').required=synthetic;$('observations').disabled=busy||!synthetic;$('seed').disabled=busy||!synthetic;$('csv-file').disabled=busy||!csv;$('market-ticker').disabled=busy||!market;$('observations').min=$('validation-protocol').value==='strict'?'1064':'850';if(synthetic&&Number($('observations').value)<Number($('observations').min)){$('demo-settings').open=true;$('setup-options').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',()=>{invalidateForecast();$('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);const destination=$(button.dataset.view);destination.setAttribute('tabindex','-1');destination.focus({preventScroll:true});destination.scrollIntoView({block:'start'});}));
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();
function resetForward(){
forwardOperation++;forwardCheck=null;
for(const id of ['forward-file','forward-date','forward-close'])$(id).value='';
$('forward-next').checked=false;$('forward-download').disabled=true;$('forward-run').disabled=false;
for(const id of ['forward-status','forward-result','forward-audit'])$(id).textContent='';
}
$('forward-form').addEventListener('input',()=>{forwardOperation++;forwardCheck=null;$('forward-download').disabled=true;$('forward-run').disabled=false;for(const id of ['forward-result','forward-audit','forward-status'])$(id).textContent='';});
$('forward-form').addEventListener('submit',async event=>{
event.preventDefault();const token=++forwardOperation;forwardCheck=null;$('forward-download').disabled=true;$('forward-result').textContent='';$('forward-audit').textContent='';$('forward-run').disabled=true;
$('forward-status').textContent='Reading the saved guess…';
const observation={date:$('forward-date').value,close:Number($('forward-close').value),confirmedNext:$('forward-next').checked};
try{
const file=$('forward-file').files[0];if(!file)throw Error('Choose your saved JSON results file first.');
if(file.size>4*1024*1024)throw Error('Choose a JSON report smaller than 4 MiB.');
const bytes=await file.arrayBuffer();if(token!==forwardOperation)return;
const report=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes));
if(!report?.forward_check)throw Error('This report does not contain a saved guess record. Make and save a new browser guess.');
const record=report.forward_check,result=QuantForward.scoreRecord(record,observation);
forwardCheck={schema_version:1,record,result};
$('forward-result').textContent=`${record.synthetic===true?'Practice with made-up prices.\n\n':''}What happened: ${result.outcome}. Your saved guess gave that outcome a ${percent(result.assigned_probability)} chance.\n\nFrom ${record.anchor.date} to ${result.date}. This is one result, not proof that the method works.`;
$('forward-audit').textContent=JSON.stringify(forwardCheck,null,2);$('forward-status').textContent='Checked the saved probabilities. No model was trained.';$('forward-download').disabled=false;
}catch(error){if(token===forwardOperation)$('forward-status').textContent=error.message;}
finally{if(token===forwardOperation)$('forward-run').disabled=false;}
});
$('forward-download').addEventListener('click',()=>{if(!forwardCheck)return;const url=URL.createObjectURL(new Blob([JSON.stringify(forwardCheck,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=url;a.download='quantlab-saved-check.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});
function updateCosts(){
const output=$('cost-output');
try{
const value=name=>{const raw=$('cost-'+name).value;if(!raw.trim()){$('cost-'+name).focus();throw Error('Fill in every amount, count and percentage, then try again.');}return Number(raw);};
if(value('completed')>value('attempts')){$('cost-completed').focus();throw Error('Finished trades cannot be more than planned trades. Reduce the finished count or increase the plan.');}
const result=QuantExecution.costs({notional:value('notional'),attempts:value('attempts'),completed:value('completed'),movePercent:value('movePercent'),spreadBps:100*value('spreadPercent'),feeBps:100*value('feePercent'),slippageBps:100*value('slippagePercent'),delayBps:100*value('delayPercent')});
const number=x=>new Intl.NumberFormat('en-US',{minimumFractionDigits:2,maximumFractionDigits:2}).format(x);
const missed=result.missedEffect<0?`Skipping losing trades helped by ${number(-result.missedEffect)} units.`:`Trades that never filled left out ${number(result.missedEffect)} units of the imagined result.`;
output.classList.remove('lab-error');output.textContent=`Gain or loss before costs, if all trades finished: ${number(result.ideal)} units.\nAfter missed trades, before costs: ${number(result.filledGross)} units.\nGain or loss after missed trades and costs: ${number(result.net)} units.\n\n${result.completed} of ${result.attempts} trades finished. ${missed}\n\nCosts on finished trades\nWaiting: ${number(result.delayCost)}\nBuy–sell gap: ${number(result.spreadCost)}\nFees for buying and selling: ${number(result.feeCost)}\nExtra price cost: ${number(result.slippageCost)}\nTotal costs: ${number(result.totalCosts)} units.\n\nThese are the results of your pretend story, not a forecast.`;
const threshold=result.breakEvenMovePercent;
const display=threshold!==null&&threshold>0&&threshold<.000001?'less than 0.000001':new Intl.NumberFormat('en-US',{maximumFractionDigits:6}).format(threshold??0);
$('cost-threshold').textContent=threshold===null?'No trades finished, so there is no cost-covering price change to compare.':`Each finished trade needs a price change of about ${display}% to cover these costs. This is a cost threshold, not a prediction.${threshold>100?' That is beyond the price-change range allowed in this exercise.':''}`;
$('cost-audit').textContent=JSON.stringify(result,null,2);
}catch(error){$('cost-threshold').textContent='';output.classList.add('lab-error');output.textContent=error.message;$('cost-audit').textContent='No valid cost exercise. Correct the inputs and try again.';}
}
$('cost-form').addEventListener('submit',event=>{event.preventDefault();updateCosts();});
$('cost-form').addEventListener('invalid',event=>{for(let parent=event.target.parentElement;parent;parent=parent.parentElement)if(parent.tagName==='DETAILS')parent.open=true;},true);
$('cost-form').addEventListener('input',()=>{$('cost-threshold').textContent='';$('cost-output').classList.remove('lab-error');$('cost-output').textContent='Numbers changed. Press See what is left to update the story.';$('cost-audit').textContent='Inputs changed; calculate again for current details.';});
updateCosts();