Treat numerical baseline ties as equality in validation
Browse filesFiles changed (11)
13 unmodified lines14151617181913 unmodified lines
## ReproduceUse Node.js with no new packages. In this directory run `node study.cjs development`, then `node study.cjs confirmation` (the latter refuses a failed development gate). The study pins model-before.js and instruments its sole challenger. Run `node causality.cjs` and `node scaling.cjs` against model-current.js. Study scripts overwrite corresponding results; preserve supplied files before rerunning if needed. Prior and current source snapshots are included. No private uploaded series are packaged.
## Numerical comparison correctionLive testing found that temperature(raw,1) can differ from raw probabilities at floating-point precision. Negative differences around5e-16 made the UI incorrectly call identical probabilities better. Validation now treats paired loss differences within1e-12 as numerical equality. A matches flag also requires all probability components within1e-12 and every paired loss difference numerically zero; tiny probabilities with material log-loss differences are not called equivalent. The UI explicitly says the selected method used the same chances as counting when that condition holds. Regression tests reproduce seed71005 and a material rare-probability counterexample. This changes diagnostics and wording, not model forecasts or study scores.107 unmodified lines108109110111112113107 unmodified lines
## Strict untuned comparison and leakage auditStrict mode now includes empirical_raw as a fifth candidate with temperature fixed at1. Selection uses its existing earlier selection block, and frozen latest inference follows that choice. Classic forecasting is unchanged. Promotion followed written development/confirmation gates on72 constructed synthetic runs; no market-accuracy claim follows. See [audit and evidence](LEAK-AUDIT.md). The page blocks native form submission through form-action none to protect inputs when JavaScript is unavailable.
## Numerical comparison correctionLive testing found that temperature(raw,1) can differ from raw probabilities at floating-point precision. Negative differences around5e-16 made the UI incorrectly call identical probabilities better. Validation now treats paired loss differences within1e-12 as numerical equality. A matches flag also requires all probability components within1e-12 and every paired loss difference numerically zero; tiny probabilities with material log-loss differences are not called equivalent. The UI explicitly says the selected method used the same chances as counting when that condition holds. Regression tests reproduce seed71005 and a material rare-probability counterexample. This changes diagnostics and wording, not model forecasts or study scores.66 unmodified lines67686970717266 unmodified lines
## Leakage and strict accuracy challenger — 27 October2026All fifteen static suites passed. New policy test first failed for missing form-action, then passed after the source fix. New strict candidate test first failed for missing raw candidate, then passed: fixed temperature1 and independently recomputed earlier selection score.72 constructed experiments passed the written development/confirmation gates. New strict report matched the tested challenger exactly and complete classic reports matched prior source for seeds42/61002/71004. Independent post-change causal probes preserved6,778 earlier forecasts over24 suffix mutations;48 strict scaler cells match training-only recomputation. See LEAK-AUDIT.md and leakage-audit.zip.
## Numerical comparison correctionLive testing found that temperature(raw,1) can differ from raw probabilities at floating-point precision. Negative differences around5e-16 made the UI incorrectly call identical probabilities better. Validation now treats paired loss differences within1e-12 as numerical equality. A matches flag also requires all probability components within1e-12 and every paired loss difference numerically zero; tiny probabilities with material log-loss differences are not called equivalent. The UI explicitly says the selected method used the same chances as counting when that condition holds. Regression tests reproduce seed71005 and a material rare-probability counterexample. This changes diagnostics and wording, not model forecasts or study scores.54 unmodified lines555657585859606143 unmodified lines10510610710810810911011111211311311411511654 unmodified lines $('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.'; $('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)]);43 unmodified linesfunction 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=20261027audit1');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{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'};} 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=20261027audit1');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}); if(worker)worker.terminate();worker=new Worker('worker.js?v=20261027audit2');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();});3 unmodified lines4567878910113 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="Explore price possibilities with simple examples and clear checks. Runs in your browser."><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'; form-action 'none'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261027audit1"><script src="labs.js?v=20261027audit1" defer></script><script src="cache.js?v=20261027audit1" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="forward.js?v=20261027audit1" defer></script><script src="execution.js?v=20261027audit1" defer></script><script src="app.js?v=20261027audit1" defer></script><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261027audit2"><script src="labs.js?v=20261027audit2" defer></script><script src="cache.js?v=20261027audit2" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="forward.js?v=20261027audit2" defer></script><script src="execution.js?v=20261027audit2" defer></script><script src="app.js?v=20261027audit2" defer></script></head><body><a class="skip" href="#results">Skip to results</a>12323version https://git-lfs.github.com/spec/v1oid sha256:f3aa743975bdd1947dfa6ebdbac474812f897703c5d4307b05744e10071c2047size 26575oid sha256:7191bb314474392b945b021de4f76ef64966fd62b9b58a9488847fe412780b95size 3117839 unmodified lines4041424343444546474839 unmodified lines assert.equal(vm.runInContext('currentReport',sandbox),null);assert.equal(vm.runInContext('runCache.size()',sandbox),0); node('observations').value='850';vm.runInContext('syncSource()',sandbox);assert.equal(node('setup-options').open,true,'Invalid hidden example settings must be revealed');assert.equal(node('demo-settings').open,true);node('observations').value='1200'; const digest=deferred();sandbox.QuantProvenance.fingerprint=()=>digest.promise;const beforeDigest=workerCount;const hashing=vm.runInContext('run()',sandbox);await Promise.resolve();node('clear-data').listeners.click();digest.resolve('stale-hash');await hashing;assert.equal(workerCount,beforeDigest,'Clearing a pending digest must prevent worker creation'); const Q=require('./model.js'),V=require('./validation.js');const report=Q.run(Q.synthetic(1200,42),{protocol:'strict'});report.validation=V.analyze(report);sandbox.fixtureReport=report; const Q=require('./model.js'),V=require('./validation.js');const report=Q.run(Q.synthetic(1200,71005),{protocol:'strict'});report.validation=V.analyze(report);sandbox.fixtureReport=report; vm.runInContext("render(fixtureReport,{synthetic:true,rows:1200,name:'Fixture'},null,{},false,{sha256:'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',rows:1200,last_date:'2014-08-08',last_close:100})",sandbox); assert.match(node('validation-verdict').textContent,/same chances/); node('download').listeners.click();assert.equal(downloadClicks,1);let exported=JSON.parse(await exportedBlob.text());assert.equal(exported.experiment_manifest.inputs.sha256,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');assert.equal(exported.experiment_manifest.inspection_history.total_views,1);assert.equal(exported.experiment_manifest.split_boundaries.length,1);assert(exported.validation.available);assert(exported.feature_support);assert.equal(Boolean(node('support-warning').textContent),exported.feature_support.warnings.length>0); vm.runInContext("render(fixtureReport,{synthetic:true,rows:1200,name:'Fixture'},null,{},true,{sha256:'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',rows:1200,last_date:'2014-08-08',last_close:100})",sandbox); node('download').listeners.click();exported=JSON.parse(await exportedBlob.text());assert.equal(exported.experiment_manifest.view.cache_hit,true);assert.equal(exported.experiment_manifest.inspection_history.total_views,2);13 unmodified lines1415161718192021222313 unmodified linesassert.throws(()=>analyze({predictions:[]}));assert.throws(()=>analyze(fixture(2501)));const shift=fixture(200);shift.predictions.forEach((row,i)=>{row.actual_log_return=i<100?.01:-.03;row.probabilities=[.05,.05,.9];});const s=analyze(shift,{reps:10});assert(s.movement.recent.log_loss>s.movement.early.log_loss);assert.equal(s.movement.early.downside_count,0);assert.equal(s.movement.recent.downside_count,100);assert.equal(s.rolling.at(-1).end_target_index,200);console.log('Validation diagnostics tests passed: paired identity, fixed losses, deterministic bootstrap, bounds, unavailable baseline, shift and support warnings');const Q=require('./model.js'),same=analyze(Q.run(Q.synthetic(1200,71005),{protocol:'strict'}),{reps:20});assert.equal(same.comparisons.empirical_raw.matches_probabilities,true);assert.equal(same.comparisons.empirical_raw.mean_difference,0,'Roundoff must not create apparent skill against the identical raw baseline');for(const interval of same.comparisons.empirical_raw.intervals)assert.deepEqual(interval.percentile95,[0,0]);assert.equal(s.comparisons.empirical_raw.matches_probabilities,false,'A shifted forecast must not be called equivalent');
const rare=fixture(1);rare.predictions[0].probabilities=[1.1e-12,.3,.7-1.1e-12];rare.predictions[0].baseline_probabilities.empirical_raw=[2e-12,.3,.7-2e-12];assert.equal(analyze(rare,{reps:5}).comparisons.empirical_raw.matches_probabilities,false,'Tiny probability differences with material log-loss effects must not be called equivalent');12344567const assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs');const Q=require('./model.js'),labs=require('./labs.js'),validation=require('./validation.js');const messages=[],loaded=[];const context={QuantModel:Q,QuantLabs:labs,QuantValidation:validation,self:{postMessage:value=>messages.push(value)},importScripts:(...names)=>{for(const name of names){assert.match(name,/^(model|labs|validation)\.js\?v=20261027audit1$/);loaded.push(name);}}};const context={QuantModel:Q,QuantLabs:labs,QuantValidation:validation,self:{postMessage:value=>messages.push(value)},importScripts:(...names)=>{for(const name of names){assert.match(name,/^(model|labs|validation)\.js\?v=20261027audit2$/);loaded.push(name);}}};vm.runInNewContext(fs.readFileSync(require.resolve('./worker.js'),'utf8'),context);assert.equal(loaded.length,3);for(const protocol of ['strict','classic']){14 unmodified lines1516171818192021222223242514 unmodified lines for(const r of rows){if(!Number.isFinite(r.actual_log_return)||!Number.isSafeInteger(r.target_index)||!Number.isSafeInteger(r.feature_index)||r.target_index<=r.feature_index||r.target_index<=previous||!probability(r.probabilities)||!probability(r.baseline_probabilities.empirical_raw)||!probability(r.baseline_probabilities.empirical_calibrated))throw Error('Prediction rows require ordered unique targets, finite returns and valid matched probability vectors.');previous=r.target_index;} const values=rows.map(r=>{const c=category(r.actual_log_return),q=r.probabilities,raw=r.baseline_probabilities.empirical_raw,cal=r.baseline_probabilities.empirical_calibrated;return{c,loss:-Math.log(Math.max(q[c],1e-12)),raw:-Math.log(Math.max(raw[c],1e-12)),cal:-Math.log(Math.max(cal[c],1e-12)),brier:q.reduce((s,p,k)=>s+(p-(k===c?1:0))**2,0),rawBrier:raw.reduce((s,p,k)=>s+(p-(k===c?1:0))**2,0),entropy:-q.reduce((s,p)=>s+(p?p*Math.log(p):0),0)};}); const lengths=[...new Set(blocks.map(b=>Math.min(b,n)))]; function compare(key){const diffs=values.map(v=>v.loss-v[key]);return{mean_difference:average(diffs),intervals:lengths.map(block=>{if(block===n)return{block,reps,percentile95:null,estimable:false,reason:'Block length spans entire evaluation sample; resampling cannot estimate uncertainty.'};const random=rng(seed+block),means=[];for(let rep=0;rep<reps;rep++){let sum=0,count=0;while(count<n){const start=Math.floor(random()*(n-block+1)),take=Math.min(block,n-count);for(let j=0;j<take;j++)sum+=diffs[start+j];count+=take;}means.push(sum/n);}means.sort((a,b)=>a-b);return{block,reps,percentile95:[quantile(means,.025),quantile(means,.975)],estimable:true};})};} function compare(key){const tolerance=1e-12,diffs=values.map(v=>Math.abs(v.loss-v[key])<=tolerance?0:v.loss-v[key]),field=key==='raw'?'empirical_raw':'empirical_calibrated';return{numerical_tolerance:tolerance,matches_probabilities:diffs.every(d=>d===0)&&rows.every(r=>r.probabilities.every((p,k)=>Math.abs(p-r.baseline_probabilities[field][k])<=tolerance)),mean_difference:average(diffs),intervals:lengths.map(block=>{if(block===n)return{block,reps,percentile95:null,estimable:false,reason:'Block length spans entire evaluation sample; resampling cannot estimate uncertainty.'};const random=rng(seed+block),means=[];for(let rep=0;rep<reps;rep++){let sum=0,count=0;while(count<n){const start=Math.floor(random()*(n-block+1)),take=Math.min(block,n-count);for(let j=0;j<take;j++)sum+=diffs[start+j];count+=take;}means.push(sum/n);}means.sort((a,b)=>a-b);return{block,reps,percentile95:[quantile(means,.025),quantile(means,.975)],estimable:true};})};} function summary(start,end){const slice=values.slice(start,end);return{end_target_index:rows[end-1].target_index,observations:slice.length,log_loss:average(slice.map(v=>v.loss)),raw_log_loss:average(slice.map(v=>v.raw)),brier:average(slice.map(v=>v.brier)),raw_brier:average(slice.map(v=>v.rawBrier)),downside_count:slice.filter(v=>v.c===0).length,mean_entropy:average(slice.map(v=>v.entropy))};} const rolling=[];if(n<100)rolling.push(summary(0,n));else{for(let end=100;end<=n;end+=20)rolling.push(summary(end-100,end));if(rolling.at(-1).end_target_index!==rows[n-1].target_index)rolling.push(summary(n-100,n));} const class_counts=[0,0,0];values.forEach(v=>class_counts[v.c]++); const warnings=['Intervals condition on fixed out-of-sample predictions; refitting and model-selection uncertainty are omitted.','Moving-block intervals assume sufficient local stationarity; regime shifts and block boundaries can limit interpretation.','Repeated research and multiple comparisons are not adjusted for.']; const warnings=['Paired log-loss differences within 1e-12 are treated as numerical equality; probability matches use absolute tolerance 1e-12.','Intervals condition on fixed out-of-sample predictions; refitting and model-selection uncertainty are omitted.','Moving-block intervals assume sufficient local stationarity; regime shifts and block boundaries can limit interpretation.','Repeated research and multiple comparisons are not adjusted for.']; if(lengths.includes(n))warnings.push('A block length spans the entire evaluation sample; its uncertainty interval is unavailable because resampling cannot estimate uncertainty.'); for(const [i,fold]of(report.folds||[]).entries())for(const [field,label]of[['temperature_class_counts','temperature'],['selection_class_counts','selection'],['test_class_counts','test']]){const counts=fold[field];if(counts===null||counts===undefined)continue;if(!Array.isArray(counts)||counts.length!==3||!counts.every(c=>Number.isSafeInteger(c)&&c>=0))throw Error('Fold class counts must contain three nonnegative integers.');for(let c=0;c<3;c++)if(counts[c]<10)warnings.push(`Fold ${i+1} ${label}: ${['downside','middle','positive'][c]} has ${counts[c]} ${counts[c]===1?'event':'events'}, below the heuristic minimum support of 10; this is not a statistical guarantee.`);} if(n<200)warnings.push('Fewer than 200 observations: disjoint early/recent movement summaries are unavailable.');122345'use strict';importScripts('model.js?v=20261027audit1','labs.js?v=20261027audit1','validation.js?v=20261027audit1');importScripts('model.js?v=20261027audit2','labs.js?v=20261027audit2','validation.js?v=20261027audit2');self.onmessage=event=>{ try { const closes=event.data.closes; const report=QuantModel.run(closes,{protocol:event.data.protocol||'classic'});report.validation=QuantValidation.analyze(report);self.postMessage({report,diagnostics:QuantLabs.diagnostics(closes)}); } catch(error){self.postMessage({error:error.message});}LEAK-AUDIT.md+3
METHODS.md+3
VERIFICATION.md+3
app.js+3-3
index.html+2-2
leakage-audit.zip+2-2
test_app_state.cjs+2-1
test_validation.cjs+7
test_worker.cjs+1-1
validation.js+2-2
worker.js+1-1