Add training-support checks, numerical stress tests and documented challenger results
Browse filesFiles changed (16)
- DESIGN.md+3
- METHODS.md+4
- MODEL-STUDY.mdAdded+56
- README.md+3
- SECURITY-REVIEW.md+4
- VERIFICATION.md+10
- app.js+10-9
- index.html+4-4
- model-study.zipAdded+3
- model.js+11-1
- style.css+2
- test_app_state.cjs+5-3
- test_model_support.cjsAdded+18
- test_numerical.cjsAdded+6
- test_worker.cjs+1-1
- worker.js+1-1
15 unmodified lines16171815 unmodified lines## Reference studyReviewed official Apple homepage, iPhone and iOS pages, MacBook Air presentation, Human Interface Guidelines for typography/layout/materials and the One Night on iPhone campaign. Applied hierarchy, purposeful spacing, product-first presentation and controlled disclosure. This is an adaptation for a web learning tool, not Apple certification or an exhaustive study of every product. See APPLE-REFERENCES.md for sources and review scope.15 unmodified lines16171819202115 unmodified lines## Reference studyReviewed official Apple homepage, iPhone and iOS pages, MacBook Air presentation, Human Interface Guidelines for typography/layout/materials and the One Night on iPhone campaign. Applied hierarchy, purposeful spacing, product-first presentation and controlled disclosure. This is an adaptation for a web learning tool, not Apple certification or an exhaustive study of every product. See APPLE-REFERENCES.md for sources and review scope.Training-support notes sit directly below the three probabilities in a restrained warm surface. Keep them plain and factual: few learning examples or unfamiliar recent patterns. They are not a formal confidence/drift claim. Hidden notes must be cleared when changing to an older saved report or clearing data. Never round a tiny nonzero chance into an apparent zero.
85 unmodified lines86878885 unmodified linesEach successful browser result export includes a SHA-256 fingerprint of UTF-8 JSON `["quantlab-normalized-prices-v1", dates, closes]`, preserving normalized chronological ISO dates and numeric prices. It identifies model inputs, not original CSV bytes, vendor accuracy, corporate-action adjustment or point-in-time availability. CSV adjustment provenance is explicitly unknown. Source metadata, model revision/settings and split boundaries accompany the fingerprint. Historical Python artifacts have no reconstructed fingerprint because their full input series is unavailable.The tab records successful result views, including cache hits, with sequence, time, fingerprint, protocol, revision, score and latest model. Only the most recent 25 records are retained; total and omitted counts are exported. It records neither failures nor other tabs or prior sessions. Clear and reload reset it. This is a transparent inspection log, not preregistration, tamper-proof evidence, a complete experiment registry or protection against repeated-research overfitting. Exported reports retain their own snapshots after tab history is cleared.85 unmodified lines8687888990919285 unmodified linesEach successful browser result export includes a SHA-256 fingerprint of UTF-8 JSON `["quantlab-normalized-prices-v1", dates, closes]`, preserving normalized chronological ISO dates and numeric prices. It identifies model inputs, not original CSV bytes, vendor accuracy, corporate-action adjustment or point-in-time availability. CSV adjustment provenance is explicitly unknown. Source metadata, model revision/settings and split boundaries accompany the fingerprint. Historical Python artifacts have no reconstructed fingerprint because their full input series is unavailable.The tab records successful result views, including cache hits, with sequence, time, fingerprint, protocol, revision, score and latest model. Only the most recent 25 records are retained; total and omitted counts are exported. It records neither failures nor other tabs or prior sessions. Clear and reload reset it. This is a transparent inspection log, not preregistration, tamper-proof evidence, a complete experiment registry or protection against repeated-research overfitting. Exported reports retain their own snapshots after tab history is cleared.## Latest-input and class supportReport feature_support records the latest fit's training-only feature minima/maxima, standardized latest feature values and training class counts. Warnings use two descriptive heuristics: any feature outside its observed training range or absolute standardized value above3, and any training class count below10. They do not estimate predictive confidence or formally test drift; absent flags do not certify forecasts. Classic latest refits may include observations previously evaluated in earlier folds. Strict training excludes the reserved evaluation. Probability calculations and model selection are unchanged. Small nonzero percentages display <0.01% and near-one percentages >99.99%; JSON keeps exact numbers. See MODEL-STUDY.md for the frozen challenger evaluations and their rejection.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# QuantLab model study
Neither tested forecasting replacement earned promotion. The current forecasting policy remains in place. The software improvement is a training-support diagnostic: it warns when outcomes are scarcely represented in the learning data or when the latest features are unusual relative to the fitted training reference.
## Study design and decision
The initial written plan fixed 12 development seeds and 12 different confirmation seeds for six synthetic mechanisms: built-in regimes, independent Gaussian returns, occasional symmetric heavy-tail jumps, autocorrelated returns, rising volatility and falling volatility. Each series has 1,200 prices and the strict 200-outcome evaluation. This gives 144 constructed fixtures. Seeds reused across mechanisms are paired; these are not 144 independent market replications.
The promotion rule required a nonpositive cohort-average log-loss difference against the existing policy in both stages, with no cohort worse by more than 0.02. This was a development heuristic, not a significance test or an investment criterion. Differences below are challenger minus current; negative favors the challenger.
The first challenger fixed 50% weight on the selected forecast and 50% on raw training frequency. It failed development: mean difference +0.025180. It helped quiet/no-signal cases but diluted the useful response to volatility changes. It was rejected without opening confirmation results for that challenger.
A second development attempt used an online combination of five existing forecasts: raw frequency, calibrated frequency, ridge, softmax and EWMA. Weights started equal, then updated by realized log loss only after each outcome was known. No weight or forgetting-rate search was performed. The second attempt was informed by development evidence; this is disclosed rather than treated as an untouched first hypothesis.
The adaptive combination passed development by a tiny margin (mean −0.000304), then failed confirmation (mean +0.000145). Confirmation cohort differences were:
- Built-in regimes: −0.007968.- Independent Gaussian returns: −0.001224.- Heavy-tail jumps: −0.005837.- Autocorrelated returns: −0.000193.- Rising volatility: +0.008047.- Falling volatility: +0.008047.
Full per-seed log loss, multiclass Brier, downside Brier and worst-row loss are retained in the JSON files. Some Brier comparisons disagree with loss comparisons. No test result was used to optimize the weights after confirmation. Both challengers remain research artifacts, not app defaults.
## Primary-source real-data sanity check
Used the latest 2,500 USD-per-EUR reference observations from the European Central Bank's history archive, from 2017-01-18 through 2026-10-26. Data are sorted chronologically; no missing prices are filled and no outliers are deleted. Source selection and filtering are recorded in ecb-source.json with archive and normalized-file hashes. This is one historical slice inspected after the synthetic policies were fixed, not prospective validation across markets.
Strict evaluation covers 2026-01-15 through 2026-10-26, 200 outcomes:
- Current selected policy log loss: 0.689329.- Raw training frequency: 0.693356.- Calibrated frequency log loss: 0.692537.- Rejected online combination: 0.689210.
For the current policy versus raw frequency, the block-20 paired fixed-prediction 95% interval for the loss difference is [−0.008374, −0.000501]. Against calibrated frequency it is [−0.007328, +0.000242], which spans zero. Block lengths 5/20/60 are all retained in ecb-results.json. These intervals omit refitting/research-selection uncertainty and depend on block/stationarity assumptions; the app therefore does not establish an advantage over both comparisons.
The small improvement for the rejected combination on this one slice does not override its failed confirmation gate. There are zero big-fall events in both the 1,936 training labels and the 200 evaluation labels. These data cannot validate big-fall forecasting. The middle/positive evaluation counts are 115/85.
ECB reference rates are published for information; the ECB discourages using them for transactions. They are neither adjusted equity closing prices nor executable fills. No costs, investment returns or trading strategy were tested. Source: https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html
## Implemented support checks
For the latest forecast, the app records training-only feature minima/maxima and standardized feature values. It flags a feature outside its training range or with absolute standardized value greater than 3. It separately flags training classes with fewer than 10 observations. These thresholds are descriptive heuristics, not calibrated confidence bounds or a formal drift test. An absent warning does not prove reliability. In classic mode the latest refit's training can legitimately include earlier expanding-test observations; strict mode excludes its reserved evaluation from the training reference.
The forecast probabilities, fitted coefficients, model selection and evaluation metrics remain identical to the pinned model in this study. Source review and regression tests check that the diagnostics do not read later labels into a training reference. No automatic fallback, abstention or trading rule was added. Tiny nonzero chances now display as <0.01% rather than rounding to 0.00%; values just below one display as >99.99%. Exact exported probabilities are unchanged.
## Numerical and causal probes
Both protocols were probed with flat prices, extremely small/large finite positive prices, alternating extremes, monotonic trends and an isolated large shock. Outputs stayed finite and probabilities normalized. Price scaling from 1e-300 through 1e300 changed probabilities by no more than about 1.3e-12 in the tested seeded series. Future suffix changes preserved 1,861 earlier prediction records across three boundaries in the new probes. The earlier multi-fold regression remains separate coverage.
These are bounded software checks, not a proof for every possible numeric input or for market forecasting usefulness. No numerical/leakage defect was found in this pass. Graphify did not run; the small familiar model source was inspected directly.
Reproduction files, the dated public FX snapshot and per-seed results are in [model-study.zip](model-study.zip). The app does not fetch a live market feed.53 unmodified lines54555653 unmodified linesThe 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.The Apple-inspired refinement centers the actual outcome chances, consolidates optional controls, and uses an opaque result surface beneath lightweight navigation. See APPLE-REFERENCES.md for the bounded design study.53 unmodified lines54555657585953 unmodified linesThe 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.The Apple-inspired refinement centers the actual outcome chances, consolidates optional controls, and uses an opaque result surface beneath lightweight navigation. See APPLE-REFERENCES.md for the bounded design study.The latest run also checks whether some outcomes have too few learning examples or recent patterns are unusual. These are warning heuristics, not confidence guarantees. Both newly tested forecast combinations failed promotion, so the forecasting policy remains unchanged. See MODEL-STUDY.md and model-study.zip for synthetic and ECB reference-data evidence. New tests: `node test_model_support.cjs` and `node test_numerical.cjs`.
36 unmodified lines37383936 unmodified lines## Provenance release scope — 26 October 2026SHA-256 uses browser Web Crypto locally; no data is transmitted. The bounded tab history stores metadata, including data fingerprints and scores, not additional copies of raw inputs. Reports already contain prediction data; exports now also contain source metadata and inspection history. Fingerprints are identifiers, not anonymization guarantees. Clear removes current reports/history and invalidates pending digest completion. No new dependency, permission, account credential or persistent storage was added. Scoped source review and regression tests completed; infrastructure and scanner exclusions remain.36 unmodified lines3738394041424336 unmodified lines## Provenance release scope — 26 October 2026SHA-256 uses browser Web Crypto locally; no data is transmitted. The bounded tab history stores metadata, including data fingerprints and scores, not additional copies of raw inputs. Reports already contain prediction data; exports now also contain source metadata and inspection history. Fingerprints are identifiers, not anonymization guarantees. Clear removes current reports/history and invalidates pending digest completion. No new dependency, permission, account credential or persistent storage was added. Scoped source review and regression tests completed; infrastructure and scanner exclusions remain.## Training-support release scopeNew diagnostics run locally on the existing worker inputs and fitted training reference. Warning messages use textContent; percentage threshold symbols inserted into SVG labels are escaped. No new network request, dependency, credential, persistent storage or private-data destination was introduced. Clear wipes the support warning and exported/current reports retain the existing operation invalidation rules. The bundled research archive contains only public ECB rates, synthetic experiments and project source. Scanner/infrastructure exclusions from earlier sections remain.
44 unmodified lines45464744 unmodified linesMechanical detector found a skipped heading, corrected to h2, and two inherited separator-padding warnings. Desktop and mobile probability separators were visually inspected with sufficient spacing.All eleven regression suites passed. At 768px tablet width, scrollWidth also equaled768px. Reduced motion/transparency and increased-contrast alternatives were reviewed in source; preference emulation was not run.44 unmodified lines4546474849505152535455565744 unmodified linesMechanical detector found a skipped heading, corrected to h2, and two inherited separator-padding warnings. Desktop and mobile probability separators were visually inspected with sufficient spacing.All eleven regression suites passed. At 768px tablet width, scrollWidth also equaled768px. Reduced motion/transparency and increased-contrast alternatives were reviewed in source; preference emulation was not run.## Model support and stress testing — 27 October 2026Two challengers were tested on a written development/confirmation design; neither earned promotion. 144 synthetic fixtures and one primary-source ECB USD/EUR reference slice are recorded in MODEL-STUDY.md. No current-policy probabilities or fitted parameters were changed. Independent complete-report comparison (excluding new support metadata) matched the pinned old model exactly in strict/classic for seeds42/313.New support tests verify training reference isolation, low-class support, latest-shock flagging and causal invariance. Numerical tests assert finite outputs and normalized probabilities on12 extreme-input protocol runs, plus price-scale invariance to2e-11; observed maximum difference approximately1.2044e-12. Additional future-suffix probes preserved1861 earlier records. App state/export tests cover support clearing and exact exports; tiny nonzero percentage formatting is tested with escaped SVG text. Browser processed the 2500-row public FX sample and displayed the zero-training-tail warning.Independent review corrected classic reference wording: a latest refit may legitimately use earlier evaluated observations. No numerical or leakage defect was found in bounded probes. Graphify did not run; source was inspected directly. These are software checks and historical experiments, not demonstrated market alpha.All thirteen verification suites passed (12 static suites plus the historical causal boundary suite). Browser reran the public FX CSV, confirmed <0.01% rather than0.00%, observed the support warning, and recorded no console errors.
123456789101112131415163 unmodified lines2021222324257 unmodified lines3334353637383951 unmodified lines91929394959697983 unmodified lines102103104105106107108109110111112113'use strict';const $=id=>document.getElementById(id),percent=x=>(100*x).toFixed(2)+'%',fmt=x=>Number(x).toFixed(4);let currentReport=null,busy=false,worker=null,focusResults=false,operation=0;const runCache=QuantCache.createRunCache(),MODEL_REVISION='browser-validation-20261026-v4';const inspectionJournal=QuantProvenance.createJournal();const INK='#34343a',BLUE='#0066cc',GRAY='#767680';function 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;}3 unmodified linesconst 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=`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':'Your price file';7 unmodified linesdrawProbabilities(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,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;51 unmodified lines$('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';3 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=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('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();});123456789101112131415163 unmodified lines202122232425267 unmodified lines3435363738394051 unmodified lines92939495969798993 unmodified lines103104105106107108109110111112113114'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;const runCache=QuantCache.createRunCache(),MODEL_REVISION='browser-support-20261027-v5';const inspectionJournal=QuantProvenance.createJournal();const INK='#34343a',BLUE='#0066cc',GRAY='#767680';function 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">${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;}3 unmodified linesconst 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;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':'Your price file';7 unmodified linesdrawProbabilities(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;51 unmodified lines$('clear-data').addEventListener('click',()=>{operation++;if(worker){worker.terminate();worker=null;}runCache.clear();inspectionJournal.clear();currentReport=null;focusResults=false;$('csv-file').value='';$('support-warning').hidden=true;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';3 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=20261027support1');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=20261027support1');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 lines456789101111 unmodified lines2324252627282917 unmodified lines474849505152533 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'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261027apple1"><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=20261027apple1" defer></script></head><body><a class="skip" href="#results">Skip to results</a>11 unmodified lines<p id="setup-note" class="hint" role="status" hidden>Settings changed. Press Show my guess to use them.</p></form><details class="session-options"><summary>Saved examples & privacy</summary><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></details></aside><div id="results" tabindex="-1"><div class="results-heading"><h2>Three ways it could go.</h2><p>Chances for the next recorded price. Each outcome is uncertain.</p></div><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><div id="status" role="status" aria-live="polite">Getting the made-up price example ready…</div><p id="plain-explanation" class="small"></p><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>17 unmodified lines</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 numbers 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>3 unmodified lines456789101111 unmodified lines2324252627282917 unmodified lines474849505152533 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'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261027support1"><script src="labs.js?v=20261027support1" defer></script><script src="cache.js?v=20261027support1" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="app.js?v=20261027support1" defer></script></head><body><a class="skip" href="#results">Skip to results</a>11 unmodified lines<p id="setup-note" class="hint" role="status" hidden>Settings changed. Press Show my guess to use them.</p></form><details class="session-options"><summary>Saved examples & privacy</summary><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></details></aside><div id="results" tabindex="-1"><div class="results-heading"><h2>Three ways it could go.</h2><p>Chances for the next recorded price. Each outcome is uncertain.</p></div><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><p id="support-warning" class="support-warning" role="status" hidden></p><div id="status" role="status" aria-live="polite">Getting the made-up price example ready…</div><p id="plain-explanation" class="small"></p><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>17 unmodified lines</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 numbers 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>When the learning examples may not be enough</h3><p>A note appears when an outcome has fewer than 10 training examples, or when recent price patterns are unusual compared with training. These are simple checks, not a guarantee of reliability. The absence of a note does not prove a guess is safe or accurate.</p><p><a href="MODEL-STUDY.md">Latest model tests and rejected changes</a></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>
123version https://git-lfs.github.com/spec/v1oid sha256:2fb301e00eb5539916f2587b924feaa5c0c5edd3cef45ae71aa01f391ddc5ddbsize 7178364 unmodified lines6566676869707164 unmodified lines// Strict freezes the evaluated fit/choice; only causal EWMA state and features advance.const t=strict?frozen:train(y.length-1),latestX=features([...close,close.at(-1)]).x.at(-1),candidate={};for(const name of names)candidate[name]=temperature(probabilities(t.model,latestX,name,name==='ewma'?t.ewmaSigmas[y.length]:undefined),t.temps[name]);const candidateMetrics=Object.fromEntries(names.map(name=>[name,metrics(allY,allQ[name])]));return{target:'next observed-close log return',threshold:-.02,classes:['r < -0.02','-0.02 <= r <= 0','r > 0'],validation_protocol:{name:protocol,scope:strict?'single reserved final 200 labeled feature rows':'expanding chronological test blocks',note:strict?'Training, temperature fitting and candidate selection use separate earlier blocks; evaluated coefficients, temperatures and choice stay frozen for latest forecast. EWMA updates causally. Repeated inspection can still overfit this reservation.':'Temperature and candidate selection reuse calibration; latest forecast refits on its own earlier training block.',reserved_test_rows:strict?200:0},test_observations:allY.length,predictions,folds,candidate_metrics:candidateMetrics,baseline_metrics:{empirical_raw:metrics(allY,rawQ),empirical_calibrated:candidateMetrics.empirical},selected_metrics:metrics(allY,selectedQ),model_details:{ewma:{half_life_observations:20,alpha:1-Math.exp(-Math.log(2)/20),mean_model:'ridge',initialization:'training residual mean square',variance_convention:'next-observation conditional residual second moment; daily sigma floor 1e-6',update:'online after each observed label, with frozen fold ridge coefficients; own forecast label excluded',annualization:'sigma times sqrt(252); assumes equally spaced trading-day observations',probabilities:'normal residual probabilities, then calibration-selected temperature'},ridge:{variance:'constant training residual sample variance'}},latest_forecast:{...boundaries(t),...(strict?{fit_metadata:snapshot(t),fit_frozen_from_fold:0}:{}),candidate_volatility_annualized:{ewma:t.ewmaSigmas[y.length]*Math.sqrt(252),ridge:t.model.sigma*Math.sqrt(252)},ewma_sigma:t.ewmaSigmas[y.length],probabilities:candidate[t.chosen],model:t.chosen,candidate_probabilities:candidate,feature_index:close.length-1,target_index:close.length,calibration_log_loss:t.scores,temperatures:t.temps},limitations:['Synthetic data demonstrate software only.','Next observed close may span calendar gaps.','Normal ridge/EWMA errors and stationary calibration can fail under regime shifts.','EWMA volatility updates from prior observed outcomes inside test blocks; mean coefficients stay frozen.','Annualized volatility assumes 252 equally spaced trading observations; calendar gaps can invalidate this convention.',strict?'Reserved labels are excluded from coefficient/temperature/choice fitting; EWMA updates using only earlier observed labels. Repeated inspection is not controlled.':'Temperature and model selection reuse calibration; test blocks remain untouched.','No transaction costs, execution model, or established economic edge.']};}const api={synthetic,features,run};if(typeof module!=='undefined'&&module.exports)module.exports=api;root.QuantModel=api;})(typeof globalThis!=='undefined'?globalThis:this);64 unmodified lines656667686970717273747576777879808164 unmodified lines// Strict freezes the evaluated fit/choice; only causal EWMA state and features advance.const t=strict?frozen:train(y.length-1),latestX=features([...close,close.at(-1)]).x.at(-1),candidate={};for(const name of names)candidate[name]=temperature(probabilities(t.model,latestX,name,name==='ewma'?t.ewmaSigmas[y.length]:undefined),t.temps[name]);const candidateMetrics=Object.fromEntries(names.map(name=>[name,metrics(allY,allQ[name])]));// Support describes the frozen training reference; it does not certify calibration or detect drift formally.const featureNames=['last_return','return_5','return_20','volatility_5','volatility_20','drawdown_60'];const trainingRanges=featureNames.map((name,j)=>({name,min:Math.min(...x.slice(0,t.trainStop).map(row=>row[j])),max:Math.max(...x.slice(0,t.trainStop).map(row=>row[j]))}));const standardized=latestX.map((value,j)=>(value-t.model.m[j])/t.model.scale[j]);const outside=trainingRanges.filter((range,j)=>latestX[j]<range.min||latestX[j]>range.max).map(range=>range.name),extreme=featureNames.filter((name,j)=>Math.abs(standardized[j])>3),trainingCounts=counts(0,t.trainStop),supportWarnings=[];const classNames=['big falls','small falls or no change','rises'],lowClasses=classNames.filter((name,j)=>trainingCounts[j]<10);if(lowClasses.length)supportWarnings.push({code:'LOW_CLASS_SUPPORT',classes:lowClasses,message:'The learning examples include fewer than 10 cases for: '+lowClasses.join(', ')+'. These chances have little supporting data.'});if(outside.length||extreme.length)supportWarnings.push({code:'UNFAMILIAR_INPUT',message:'Some recent price patterns are unusual compared with the learning examples. Treat this guess with extra care.'});const featureSupport={reference:strict?'Frozen coefficient-training rows only; temperature, selection and reserved evaluation rows are excluded.':'Training rows of the latest refit; later calibration/selection rows are excluded. Classic refits may include observations evaluated in earlier expanding folds.',training_observations:t.trainStop,training_class_counts:trainingCounts,training_ranges:trainingRanges,latest:{feature_index:close.length-1,standardized_values:standardized,max_abs_standardized_value:Math.max(...standardized.map(Math.abs)),outside_training_range:outside,extreme_features:extreme},thresholds:{absolute_standardized_value:3,minimum_class_count:10,note:'Descriptive heuristics, not calibrated confidence, a formal drift test, or evidence that unflagged forecasts are reliable.'},warnings:supportWarnings};return{feature_support:featureSupport,target:'next observed-close log return',threshold:-.02,classes:['r < -0.02','-0.02 <= r <= 0','r > 0'],validation_protocol:{name:protocol,scope:strict?'single reserved final 200 labeled feature rows':'expanding chronological test blocks',note:strict?'Training, temperature fitting and candidate selection use separate earlier blocks; evaluated coefficients, temperatures and choice stay frozen for latest forecast. EWMA updates causally. Repeated inspection can still overfit this reservation.':'Temperature and candidate selection reuse calibration; latest forecast refits on its own earlier training block.',reserved_test_rows:strict?200:0},test_observations:allY.length,predictions,folds,candidate_metrics:candidateMetrics,baseline_metrics:{empirical_raw:metrics(allY,rawQ),empirical_calibrated:candidateMetrics.empirical},selected_metrics:metrics(allY,selectedQ),model_details:{ewma:{half_life_observations:20,alpha:1-Math.exp(-Math.log(2)/20),mean_model:'ridge',initialization:'training residual mean square',variance_convention:'next-observation conditional residual second moment; daily sigma floor 1e-6',update:'online after each observed label, with frozen fold ridge coefficients; own forecast label excluded',annualization:'sigma times sqrt(252); assumes equally spaced trading-day observations',probabilities:'normal residual probabilities, then calibration-selected temperature'},ridge:{variance:'constant training residual sample variance'}},latest_forecast:{...boundaries(t),...(strict?{fit_metadata:snapshot(t),fit_frozen_from_fold:0}:{}),candidate_volatility_annualized:{ewma:t.ewmaSigmas[y.length]*Math.sqrt(252),ridge:t.model.sigma*Math.sqrt(252)},ewma_sigma:t.ewmaSigmas[y.length],probabilities:candidate[t.chosen],model:t.chosen,candidate_probabilities:candidate,feature_index:close.length-1,target_index:close.length,calibration_log_loss:t.scores,temperatures:t.temps},limitations:['Synthetic data demonstrate software only.','Next observed close may span calendar gaps.','Normal ridge/EWMA errors and stationary calibration can fail under regime shifts.','EWMA volatility updates from prior observed outcomes inside test blocks; mean coefficients stay frozen.','Annualized volatility assumes 252 equally spaced trading observations; calendar gaps can invalidate this convention.',strict?'Reserved labels are excluded from coefficient/temperature/choice fitting; EWMA updates using only earlier observed labels. Repeated inspection is not controlled.':'Temperature and model selection reuse calibration; test blocks remain untouched.','No transaction costs, execution model, or established economic edge.']};}const api={synthetic,features,run};if(typeof module!=='undefined'&&module.exports)module.exports=api;root.QuantModel=api;})(typeof globalThis!=='undefined'?globalThis:this);
23 unmodified lines24252623 unmodified lines@media(prefers-contrast:more){:root{--secondary:#414145;--line:#8b8b91}.masthead{background:#fff;backdrop-filter:none;-webkit-backdrop-filter:none}.hint,.small{color:#414145}}.settings-grid h2{font-size:18px;line-height:1.3;letter-spacing:-.015em}23 unmodified lines242526272823 unmodified lines@media(prefers-contrast:more){:root{--secondary:#414145;--line:#8b8b91}.masthead{background:#fff;backdrop-filter:none;-webkit-backdrop-filter:none}.hint,.small{color:#414145}}.settings-grid h2{font-size:18px;line-height:1.3;letter-spacing:-.015em}.support-warning{background:#fff7df;color:#775000;border-radius:10px;padding:16px 20px;margin:24px auto;font-size:14px;line-height:1.65;max-width:70ch}
17 unmodified lines181920212223242526275 unmodified lines3334353637383917 unmodified linesconst source=fs.readFileSync(require.resolve('./app.js'),'utf8').replace(/import\('\.\/model\.js[^']*'\)/,"Promise.resolve({})");vm.createContext(sandbox);vm.runInContext(source,sandbox);(async()=>{tabs[1].listeners.click();assert.equal(node('workbench').hidden,true);assert.equal(node('methods').hidden,false);assert.equal(node('methods').scrolled,true,'Navigation must show the start of the newly selected view');tabs[0].listeners.click();const outer={tagName:'DETAILS',open:false,parentElement:null},inner={tagName:'DETAILS',open:false,parentElement:outer};node('experiment').listeners.invalid({target:{parentElement:inner}});assert(inner.open&&outer.open,'Native validation must reveal closed ancestor details');for(const id of ['validation-policy','movement-note','validation-audit'])node(id).textContent='private derived fixture';node('clear-data').listeners.click();assert.equal(node('validation-policy').textContent,'');assert.equal(node('movement-note').textContent,'');assert.match(node('validation-audit').textContent,/No validation/);await Promise.resolve();assert.equal(workerCount,0,'Clearing pending module load must prevent worker creation');const file=deferred();node('data-source').value='csv';node('csv-file').files=[{size:100,arrayBuffer:()=>file.promise}];const pending=vm.runInContext('run()',sandbox);node('clear-data').listeners.click();file.resolve(new TextEncoder().encode('date,close').buffer);await pending;assert.equal(parseCount,0);assert.equal(workerCount,0);assert.equal(cacheWrites,0);assert.match(node('status').textContent,/cleared/);5 unmodified linesconst 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;vm.runInContext("render(fixtureReport,{synthetic:true,rows:1200,name:'Fixture'},null,{},false,{sha256:'fixture-hash'})",sandbox);node('download').listeners.click();assert.equal(downloadClicks,1);let exported=JSON.parse(await exportedBlob.text());assert.equal(exported.experiment_manifest.inputs.sha256,'fixture-hash');assert.equal(exported.experiment_manifest.inspection_history.total_views,1);assert.equal(exported.experiment_manifest.split_boundaries.length,1);assert(exported.validation.available);vm.runInContext("render(fixtureReport,{synthetic:true,rows:1200,name:'Fixture'},null,{},true,{sha256:'fixture-hash'})",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);node('clear-data').listeners.click();assert.equal(vm.runInContext('inspectionJournal.snapshot().total_views',sandbox),0);const clicks=downloadClicks;node('download').listeners.click();assert.equal(downloadClicks,clicks,'No export after clearing');17 unmodified lines1819202122232425262728295 unmodified lines3536373839404117 unmodified linesconst source=fs.readFileSync(require.resolve('./app.js'),'utf8').replace(/import\('\.\/model\.js[^']*'\)/,"Promise.resolve({})");vm.createContext(sandbox);vm.runInContext(source,sandbox);(async()=>{assert.equal(vm.runInContext('percent(1e-9)',sandbox),'<0.01%');assert.equal(vm.runInContext('percent(1-1e-9)',sandbox),'>99.99%');assert.equal(vm.runInContext('percent(0)',sandbox),'0.00%');assert.equal(vm.runInContext('percent(1)',sandbox),'100.00%');vm.runInContext('drawProbabilities([1e-9,.5,.5-1e-9])',sandbox);assert(node('probability-chart').innerHTML.includes('<0.01%'),'Tiny nonzero probabilities must stay readable in valid SVG text');tabs[1].listeners.click();assert.equal(node('workbench').hidden,true);assert.equal(node('methods').hidden,false);assert.equal(node('methods').scrolled,true,'Navigation must show the start of the newly selected view');tabs[0].listeners.click();const outer={tagName:'DETAILS',open:false,parentElement:null},inner={tagName:'DETAILS',open:false,parentElement:outer};node('experiment').listeners.invalid({target:{parentElement:inner}});assert(inner.open&&outer.open,'Native validation must reveal closed ancestor details');for(const id of ['support-warning','validation-policy','movement-note','validation-audit'])node(id).textContent='private derived fixture';node('clear-data').listeners.click();assert.equal(node('support-warning').textContent,'');assert.equal(node('support-warning').hidden,true);assert.equal(node('validation-policy').textContent,'');assert.equal(node('movement-note').textContent,'');assert.match(node('validation-audit').textContent,/No validation/);await Promise.resolve();assert.equal(workerCount,0,'Clearing pending module load must prevent worker creation');const file=deferred();node('data-source').value='csv';node('csv-file').files=[{size:100,arrayBuffer:()=>file.promise}];const pending=vm.runInContext('run()',sandbox);node('clear-data').listeners.click();file.resolve(new TextEncoder().encode('date,close').buffer);await pending;assert.equal(parseCount,0);assert.equal(workerCount,0);assert.equal(cacheWrites,0);assert.match(node('status').textContent,/cleared/);5 unmodified linesconst 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;vm.runInContext("render(fixtureReport,{synthetic:true,rows:1200,name:'Fixture'},null,{},false,{sha256:'fixture-hash'})",sandbox);node('download').listeners.click();assert.equal(downloadClicks,1);let exported=JSON.parse(await exportedBlob.text());assert.equal(exported.experiment_manifest.inputs.sha256,'fixture-hash');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:'fixture-hash'})",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);node('clear-data').listeners.click();assert.equal(vm.runInContext('inspectionJournal.snapshot().total_views',sandbox),0);const clicks=downloadClicks;node('download').listeners.click();assert.equal(downloadClicks,clicks,'No export after clearing');
123456789101112131415161718const assert=require('node:assert/strict'),Q=require('./model.js');const flat=Q.run(Array(1200).fill(100),{protocol:'strict'});assert(flat.feature_support,'Run must report training support for latest input');assert.deepEqual(flat.feature_support.training_class_counts,flat.folds[0].training_class_counts);assert.equal(flat.feature_support.latest.max_abs_standardized_value,0);assert.deepEqual(flat.feature_support.latest.outside_training_range,[]);assert(flat.feature_support.warnings.some(w=>w.code==='LOW_CLASS_SUPPORT'));const normal=Q.synthetic(1200,42),shock=normal.slice();shock[1199]*=1.5;const a=Q.run(normal,{protocol:'strict'}),b=Q.run(shock,{protocol:'strict'});assert.deepEqual(a.feature_support.training_ranges,b.feature_support.training_ranges,'Latest shock must not change training reference');assert.deepEqual(a.predictions.map(({actual_log_return,...row})=>row),b.predictions.map(({actual_log_return,...row})=>row),'Changing the last close must not change forecasts made before it');assert(b.feature_support.latest.extreme_features.includes('last_return'));assert(b.feature_support.latest.outside_training_range.includes('last_return'));assert(b.feature_support.warnings.some(w=>w.code==='UNFAMILIAR_INPUT'));assert.equal(b.feature_support.thresholds.absolute_standardized_value,3);assert.equal(b.feature_support.thresholds.minimum_class_count,10);for(const protocol of ['classic','strict']){const report=Q.run(normal,{protocol});assert.equal(report.feature_support.latest.feature_index,1199);assert.equal(report.feature_support.training_observations,report.latest_forecast.train_label_end-60);assert.equal(report.feature_support.latest.standardized_values.length,6);}console.log('Model support tests passed: training-only reference, low-support warnings, extreme-input flag and label-causal invariance');123456const assert=require('node:assert/strict'),Q=require('./model.js');const fixtures={flat:Array(1200).fill(100),tiny:Array(1200).fill(Number.MIN_VALUE),huge:Array(1200).fill(Number.MAX_VALUE),alternating:Array.from({length:1200},(_,i)=>i%2?Number.MAX_VALUE:Number.MIN_VALUE),trend:Array.from({length:1200},(_,i)=>100*Math.exp(i*.001)),shock:Array.from({length:1200},(_,i)=>i===1000?Number.MAX_VALUE:100)};let cases=0;function finite(value){if(typeof value==='number')assert(Number.isFinite(value));else if(value&&typeof value==='object')Object.values(value).forEach(finite);}for(const prices of Object.values(fixtures))for(const protocol of ['strict','classic']){const report=Q.run(prices,{protocol});finite(report);for(const q of [...report.predictions.map(r=>r.probabilities),report.latest_forecast.probabilities]){assert(q.every(p=>p>=0&&p<=1));assert(Math.abs(q.reduce((a,b)=>a+b,0)-1)<1e-12);}cases++;}const x=Q.synthetic(1200,42),base=Q.run(x,{protocol:'strict'});let maxDifference=0;for(const factor of [1e-300,1e-200,1e200,1e300]){const report=Q.run(x.map(v=>v*factor),{protocol:'strict'});assert.equal(report.latest_forecast.model,base.latest_forecast.model);for(let i=0;i<report.predictions.length;i++)for(let k=0;k<3;k++)maxDifference=Math.max(maxDifference,Math.abs(report.predictions[i].probabilities[k]-base.predictions[i].probabilities[k]));}assert(maxDifference<2e-11);console.log(`Numerical tests passed: ${cases} extreme-input runs, normalized finite reports, scale difference ${maxDifference}`);1234567const 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=20261026validation4$/);loaded.push(name);}}};vm.runInNewContext(fs.readFileSync(require.resolve('./worker.js'),'utf8'),context);assert.equal(loaded.length,3);for(const protocol of ['strict','classic']){1234567const 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=20261027support1$/);loaded.push(name);}}};vm.runInNewContext(fs.readFileSync(require.resolve('./worker.js'),'utf8'),context);assert.equal(loaded.length,3);for(const protocol of ['strict','classic']){
12345'use strict';importScripts('model.js?v=20261026validation4','labs.js?v=20261026validation4','validation.js?v=20261026validation4');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});}12345'use strict';importScripts('model.js?v=20261027support1','labs.js?v=20261027support1','validation.js?v=20261027support1');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});}
DESIGN.md+3
METHODS.md+4
MODEL-STUDY.mdAdded+56
README.md+3
SECURITY-REVIEW.md+4
VERIFICATION.md+10
app.js+10-9
index.html+4-4
model-study.zipAdded+3
model.js+11-1
style.css+2
test_app_state.cjs+5-3
test_model_support.cjsAdded+18
test_numerical.cjsAdded+6
test_worker.cjs+1-1
worker.js+1-1