Add ticker forecasts and transparent evaluation support
Browse filesFit existing next-close forecasts to eight dated ticker snapshots; retain source identity in reports and saved guesses; expose evaluation outcome counts, mean predicted probabilities and observed rates; invalidate stale results on input changes. All 18 Node test files and real-browser flows passed. One fixed Student-t4 challenger failed development, so the forecasting policy remains unchanged and confirmation remains unopened. Include reproducible study evidence and verification notes.
Files changed (18)
- DESIGN.md+8
- FORECAST-STUDY.mdAdded+45
- FORECAST-VERIFICATION.mdAdded+58
- INVESTMENT-VERIFICATION.md+1-1
- README.md+26
- app.js+32-11
- forecast-study.zipAdded+3
- forward.js+1-1
- index.html+8-7
- market.jsAdded+29
- style.css+4
- test_app_state.cjs+13-2
- test_forward.cjs+5
- test_market.cjsAdded+16
- test_outcome_reliability.cjsAdded+32
- test_worker.cjs+1-1
- validation.js+2-1
- worker.js+1-1
37 unmodified lines38394037 unmodified linesdistinction stay visible. SVG charts support pointer inspection and a native range slider;a bounded-height table provides the same values. Motion is a short opacity/position revealand is disabled by reduced-motion preference. No new runtime dependency is introduced.37 unmodified lines383940414243444546474837 unmodified linesdistinction stay visible. SVG charts support pointer inspection and a native range slider;a bounded-height table provides the same values. Motion is a short opacity/position revealand is disabled by reduced-motion preference. No new runtime dependency is introduced.## Forecast source and evaluation supportPrice explorer adds a native ticker selector for dated public snapshots. Ticker, adjustmentand final-date context accompany results and survive exports. A compact table below theprobabilities separates historical outcome counts, average predicted chances and observedrates. Sparse evaluation support is visible there with its heuristic limitation. Changinginputs removes stale results; inactive controls are disabled. The forecasting policy wasretained after the single heavy-tail challenger failed its development gate.
123456789101112131415161718192021222324252627282930313233343536373839404142434445# Fixed Student-t4 challenger study
**Decision: do not promote. Keep the production selection policy unchanged.** Both development cohorts failed their prespecified primary log-loss gate. Neither synthetic nor market confirmation was scored.
One fixed candidate was appended to the current strict-mode selection policy: Student-t with 4 degrees of freedom, unchanged ridge conditional mean and causal EWMA20 standard deviation, t scale = sigma / sqrt(2). Existing temperature grid, fitting partitions, purges, candidate-selection rule, and target rows were preserved. Classic mode was tested byte-for-byte at the returned-object level against the pinned baseline. No additional candidate was searched.
## Development results
All differences are expanded policy minus unchanged current policy; negative is better. Each run contains the same 200 target observations for both policies.
| Cohort | Paired runs | Log loss difference | Multiclass Brier difference | Downside Brier difference | Gate ||---|---:|---:|---:|---:|---|| Synthetic development | 72 | +0.0000498782 | -0.0005159654 | -0.0000213257 | FAIL || Market development pooled | 16 | +0.0008513347 | +0.0004568167 | -0.0001670688 | FAIL || Market cutoff N-400 | 8 | +0.0009542709 | +0.0002080773 | +0.0001389146 | FAIL || Market cutoff N-200 | 8 | +0.0007483985 | +0.0007055562 | -0.0004730522 | FAIL |
Synthetic mechanisms: built_in_regimes, iid_gaussian, heavy_tail, autocorrelated, volatility_up, volatility_down. The same 12 new fixed development seeds (63001–63012) are paired across mechanisms; they do not create 72 independent market replications. Synthetic generation length and mechanism definitions exactly match the archived study (1,200 prices; volatility-change index 900). Market runs use eight tickers and two cutoffs, each with the latest 1,254 prices.
The largest mechanism mean log-loss degradation was +0.0015554341; the largest ticker mean degradation was +0.0099131920. Both stay below the +0.02 guard, but that cannot override primary gate failure. Requiring each market window to pass was a conservative interpretation frozen before scoring; the pooled market gate also fails, so that interpretation does not change the decision.
## Freeze and reproducibility
- Baseline revision: `6fcb807cedde4dc6bfa7253316a5aba31ffd3632`. `baseline.js` comes from `git show` at that exact revision.- Research data SHA-256: `65274ad093af61057fe71e70f9aea647d68e756aecb67a2c4ab4507abb2ebbbe`.- Manifest SHA-256: `3802bed270aec8dc1b0068463e32f573592ae9ebf8af3489d6eb503230547dc4`.- `manifest.json` froze the baseline, candidate, runner, archived mechanisms, numerical/causal tests and data hashes before any candidate scores were computed. New fixed confirmation seeds 73001–73012 and bootstrap settings were frozen but not evaluated.- Run `node test-candidate.cjs`, `node test-study.cjs`, then `node study.cjs development` from this directory. Every scoring stage validates frozen hashes. `node study.cjs freeze` refuses to overwrite the existing manifest.- Detailed paired scores, class counts, mean predictions/observed rates and per-date prediction rows are in `development.json`. `development-summary.log` contains compact summaries.
## Verification
- Tests were written first; the initial run failed with `Cannot find module ./candidate.js` before implementation.- Independent Simpson integration against the t4 density, reference CDF point, symmetry, normalization, finite-tail asymptotics through z=1e50, and integrated second moment validate the t4 construction and variance scaling.- Own-label and future-suffix mutations at three evaluation positions preserve the earlier t4 forecasts and causal sigma; fit coefficients, selection choice and temperatures remain frozen. Latest forecast reuses the evaluated fit and temperature.- Classic return objects equal the baseline. Additional harness tests prove exact equality to all six archived generators, score arithmetic, zero-improvement gate rejection, synchronized bootstrap behavior, deterministic resamples and rejection of mismatched dates.- Explicit attempts to execute both confirmation stages exited 1 with prerequisite-gate errors before scoring. See `confirmation-guard.log` and `market-confirmation-guard.log`. No confirmation result file exists.- Bootstrap implementation is present and tested but no market-confirmation intervals were computed. The frozen method uses 2,000 fixed-seed synchronized moving calendar-date blocks (20 primary; 5/60 sensitivity), equal-weight ticker mean loss differences and the empirical one-sided 98.3333rd percentile for each of three comparisons.
## Limits
This is a failed historical development experiment, not evidence of improved forecasting or investment returns. The securities are a selected correlated universe. Public past data are not sealed prospective validation. Synthetic mechanisms are controlled software checks. Fixed-prediction bootstrap would omit refitting and research-selection uncertainty; it was not invoked for confirmation because development failed. This study changed no production files.
Download [the reproducible study](forecast-study.zip) and run the commands above from its extracted directory. The production forecasting policy was retained.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# Forecast reliability release verification
Base: published commit 6fcb807cedde4dc6bfa7253316a5aba31ffd3632.
## What changed
Price explorer can fit the existing forecast policy to eight dated stock/ETF snapshots.Market input validation checks schema, unique tickers, USD metadata, adjustment/source,714–2,500 aligned prices/dates, valid increasing calendar dates, finite positive values,and a 2 MiB read limit. Files are read from the same-origin public JSON asset. User CSVsremain browser-local. Synthetic settings and CSV/ticker fields are disabled outside theiractive mode.
Input edits and fresh calculations invalidate old percentages, evaluation support andexports. Existing operation guards cancel late module, CSV, market, digest and workerresults. Exported manifests and new saved-guess records retain ticker/source context;legacy saved guesses remain scoreable. Evaluation summaries use validated matched rowsand report events, average probabilities and observed fractions. Fewer than ten eventsis explicitly a descriptive support heuristic. Legacy Python reports do not fabricateunavailable summaries. Same-origin CSP and fail-closed form-action remain in place.
## Forecast decision
The fixed Student-t4 challenger failed development. Do not promote. No confirmationscores or bootstrap confirmation intervals were computed. Production model.js remainsidentical to the frozen baseline, SHA-256b2751c8907a9da4ddc5351715152c1c1f401948aa9f19f83df2f9c4882984c7a.See FORECAST-STUDY.md and forecast-study.zip for the manifest, tests, inputs and results.
## Checks performed
- All 18 test_*.cjs files pass, including new market-input and same-row outcome-summary assertions. New logic and source-record changes were tested red before implementation.- Market tests reject invalid/duplicate tickers, wrong currency, zero/nonfinite prices, invalid/duplicate dates, misaligned arrays, missing metadata, invalid source links, failed fetches, malformed JSON and oversized input.- Source state tests reproduce late market reads followed by clear, fresh ticker fitting, and edited inputs invalidating report/export/reliability. Existing delayed CSV, module, digest, worker and benchmark guards still pass.- CUA real-browser checks: all eight ticker forecasts; stale export disabled on selection; correct source labels and three outcome rows; sparse-event warnings for SPY/QQQ; ticker retained in report, saved guess and manifest; switch back to synthetic; legacy Python report without fabricated outcomes; local CSV fit with unverified source label; native Enter-key submission; cache-hit labeling; investment future scenario still renders.- A 390px viewport had document width 390px. Reliability table and warning were visually inspected, and the temporary viewport was reset. Default desktop view was inspected.- Independent integration review found no actionable material defect; independent study verification confirmed frozen hashes, paired rows, failed gates and unopened confirmation.- git diff --check and JavaScript syntax checks pass.
## Limits
Browser checks used the available in-app browser and an emulated narrow viewport, notphysical touch devices or a screen reader. No new Safari/Firefox certification is claimed.Market snapshots remain historical, not live quotes; the next recorded date is not knownfrom this data alone. Historical validation and descriptive outcome summaries do not provecalibration, prospective forecast usefulness, accuracy improvement or profitability.Source was inspected directly with rg and bounded reads; Graphify/SearXNG/Crawl4AI did not run.8 unmodified lines91011121314158 unmodified linesarchives were hydrated from the pinned upstream revision for the complete source bundle.Source baseline: Hugging Face Space commit 65c82db2e8bfd1ab251906136da0e0902a1ff3cb.No remote repository was modified and no public deployment was performed.## Evidence8 unmodified lines91011121314158 unmodified linesarchives were hydrated from the pinned upstream revision for the complete source bundle.Source baseline: Hugging Face Space commit 65c82db2e8bfd1ab251906136da0e0902a1ff3cb.This document records the local checks before the investment release. That release was subsequently published as commit 6fcb807cedde4dc6bfa7253316a5aba31ffd3632.## Evidence
116 unmodified lines117118119116 unmodified lines`PLAYWRIGHT_MODULE` to its installed module path; `BASE_URL` defaults to`http://127.0.0.1:8765`. The runner saves screenshots and a check report under`browser-artifacts/`. These development tools are not needed by the deployed static app.116 unmodified lines117118119120121122123124125126127128129130131132133134135136137138139140141142143144145116 unmodified lines`PLAYWRIGHT_MODULE` to its installed module path; `BASE_URL` defaults to`http://127.0.0.1:8765`. The runner saves screenshots and a check report under`browser-artifacts/`. These development tools are not needed by the deployed static app.## Ticker forecasts and reliability reportingPrice explorer now accepts the same eight public stock/ETF snapshots as Investment explorer.Choose **Stock or ETF snapshot**, select a ticker and press **Show my guess**. The resultidentifies the ticker and final observation date: it concerns the next recorded close afterthat snapshot, not a live market forecast. Source adjustment and retrieval metadata remainin JSON exports and newly saved guesses. CSVs and synthetic examples remain available.Changing settings invalidates old percentages, reliability summaries and exports immediately.A visible evaluation panel shows each outcome’s count, its mean predicted probability andits observed rate on exactly the same check rows. Fewer than ten observed events raises aplain-language support warning. This threshold is a heuristic; matching aggregate ratesdoes not establish calibration or individual-forecast accuracy. Legacy saved Python resultswithout matched validation retain their unavailable state rather than fabricated summaries.One fixed, variance-matched Student-t(4) EWMA challenger was tested under the approvedchronological gates. It failed both synthetic and market development log-loss gates. Neitherconfirmation stage was scored, no additional challenger was searched, and model.js remainsbyte-identical to the published selection policy. No accuracy gain or investment edge isclaimed. See [FORECAST-STUDY.md](FORECAST-STUDY.md) and [source/results](forecast-study.zip).All 18 Node assertion files pass. Additional study checks validate distribution arithmetic,causality, frozen parameters, unchanged classic outputs, generators, scoring and synchronizedbootstrap behavior. The existing full Node test loop includes market-input and outcome-summarychecks. [FORECAST-VERIFICATION.md](FORECAST-VERIFICATION.md) records browser checks and limits.
18 unmodified lines19202122232425262728293031328 unmodified lines41424344454639 unmodified lines86878889909192939495969798991002 unmodified lines10310410510610710810911011111211311411511611711811912012112218 unmodified linesfunction render(report,source,dates,diagnostics,cacheHit=false,identity=null){currentReport={...report,source,diagnostics,execution:{model_revision:report.precomputed?'saved-python-benchmark':MODEL_REVISION,cache_hit:cacheHit,cache_policy:'Tab memory only; at most 3 runs; ten-minute TTL from computation'}};const view=inspectionJournal.record({data_sha256:identity?.sha256||null,protocol:report.validation_protocol?.name||'historical-python',model_revision:currentReport.execution.model_revision,cache_hit:cacheHit,observations:report.test_observations,selected_log_loss:report.selected_metrics.log_loss,latest_model:report.latest_forecast.model});currentReport.experiment_manifest={schema_version:1,view,inputs:identity||{sha256:null,reason:'Original normalized input series unavailable for this historical artifact.'},provenance:{source_metadata:source,source:source.name||'Saved Python benchmark',adjustments:source.synthetic?'Synthetic generator; no market adjustments.':'Unknown. Dates and closing prices alone do not establish vendor, corporate-action adjustment or point-in-time availability.'},configuration:{model_revision:currentReport.execution.model_revision,protocol:report.validation_protocol,target:report.target,threshold:report.threshold,model_details:report.model_details},split_boundaries:report.folds,inspection_history:inspectionJournal.snapshot(),limitations:'Fingerprint is computed from normalized dates and prices, not original file bytes. History is tab-local, bounded and resettable; it does not prove independent evaluation or prevent research overfitting.'};currentReport.forward_check=identity&&!report.precomputed?QuantForward.createRecord(currentReport,identity,source):null;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';$('status').textContent=`${kind} · ${source.rows.toLocaleString()} prices. ${report.precomputed?'You are viewing a saved result.':'Your prices stay in this browser.'}`;if(cacheHit)$('status').textContent+=' Same settings: reused the earlier calculation.';$('status').textContent+=` Result ${view.sequence} in this tab. Save the report to keep its details.`;renderQuality(source);renderValidation(report);8 unmodified lines$('explanations').textContent=report.precomputed?JSON.stringify({mode:'PRECOMPUTED; no Python executes on this host',tuning_trials:report.tuning_trials,shap_explanation:report.shap_explanation,mlflow:report.mlflow,benchmark_date:report.benchmark_date},null,2):'Browser run: no SHAP, Optuna, XGBoost, LightGBM or MLflow execution. Load the precomputed Python benchmark to inspect its saved results, or download the Python project.';$('download').disabled=false;setBusy(false);$('setup-note').hidden=true;if(focusResults&&!$('workbench').hidden){$('results').focus();}focusResults=false;}function appendEvidenceRow(id,values){const row=document.createElement('tr');for(const value of values){const cell=document.createElement('td');cell.textContent=String(value);row.append(cell);}$(id).append(row);}function signed(value){return(value>0?'+':'')+Number(value).toFixed(4);}function intervalText(interval){return interval?.estimable&&interval.percentile95?`[${signed(interval.percentile95[0])}, ${signed(interval.percentile95[1])}]`:'Not estimable';}39 unmodified linesfunction renderQuality(source){const quality=source.data_quality;$('quality-warnings').replaceChildren();$('quality-summary').textContent=quality?`${quality.rows.toLocaleString()} validated prices. ${quality.normalizedHeaderFields} header fields normalized; ${quality.trimmedValues} date/price values trimmed${quality.bomRemoved?'; initial byte-order mark removed':''}. No rows dropped or values filled.`:source.synthetic?'These prices are made up for learning. The dates are example weekdays, not a real market calendar.':'Saved benchmark: no new CSV cleaning was performed.';for(const warning of quality?.warnings||[]){const item=document.createElement('li');item.textContent=warning;$('quality-warnings').append(item);}$('quality-audit').textContent=JSON.stringify(quality||{source:source.name||'Saved benchmark',note:'No uploaded CSV cleaning audit available for this mode.'},null,2);document.querySelector('.quality-panel').classList.toggle('has-warnings',Boolean(quality?.warnings.length));document.querySelector('.quality-panel summary').textContent=quality?.warnings.length?`Price checks · ${quality.warnings.length} ${quality.warnings.length===1?'thing':'things'} to review`:'Check my prices';}$('clear-data').addEventListener('click',()=>{operation++;resetForward();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.';2 unmodified lines$('score-note').textContent='No current model scores.';$('validation-content').hidden=true;$('check-details').hidden=true;$('validation-link').hidden=true;$('validation-support-note').hidden=true;$('validation-verdict').textContent='Make a guess to see how we checked it.';$('validation-scope').textContent='';$('validation-audit').textContent='No validation data retained.';});function syntheticDates(n){const dates=[],day=new Date('2010-01-04T00:00:00Z');while(dates.length<n){if(day.getUTCDay()!==0&&day.getUTCDay()!==6)dates.push(day.toISOString().slice(0,10));day.setUTCDate(day.getUTCDate()+1);}return dates;}async function run(){if(busy)return;const token=++operation;setBusy(true,'Learning from earlier prices, then checking guesses against later prices…');try{let closes,dates,source;const mode=$('data-source').value,protocol=$('validation-protocol').value;if(!['classic','strict'].includes(protocol))throw Error('Choose how to check the guesses.');if(mode==='csv'){const file=$('csv-file').files[0];if(!file)throw Error('Choose a price file with date and close columns, or select Made-up prices.');if(file.size>2*1024*1024)throw Error('CSV must be no larger than 2 MiB.');const buffer=await file.arrayBuffer();if(token!==operation)return;let text;try{text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(buffer);}catch{throw Error('CSV must use valid UTF-8 encoding. Export it as UTF-8 and try again.');}const data=QuantLabs.parseCSV(text);closes=data.closes;dates=data.dates;source={synthetic:false,rows:closes.length,name:'Local CSV',calendar_gap_max_days:data.calendarGapMaxDays,data_quality:data.quality};}else{const n=Number($('observations').value),seed=Number($('seed').value);if(!Number.isInteger(n)||n<850||n>2500||!Number.isInteger(seed)||seed<0||seed>100000)throw Error('Use 850–2,500 observations and an integer seed from 0 to 100,000.');const model=await import('./model.js?v=20261027audit2');if(token!==operation)return;closes=globalThis.QuantModel.synthetic(n,seed);dates=syntheticDates(n);source={synthetic:true,rows:n,seed,name:'Browser synthetic generator',calendar:'Weekday placeholders, not exchange dates'};}if(protocol==='strict'&&closes.length<1064)throw Error('The separate test needs at least 1,064 prices. Add more prices, or open How we check the guesses and choose Repeated checks.');const sha256=await QuantProvenance.fingerprint({dates,closes});if(token!==operation)return;const identity={sha256,canonical_format:'quantlab-normalized-prices-v1: JSON array of format tag, ISO dates, finite positive numeric closes',rows:closes.length,first_date:dates[0],last_date:dates.at(-1),last_close:closes.at(-1)};const key=JSON.stringify([MODEL_REVISION,protocol,dates,closes]);const cached=runCache.get(key);if(cached){render(cached.report,source,dates,cached.diagnostics,true,identity);return;}if(worker)worker.terminate();worker=new Worker('worker.js?v=20261027audit2');worker.onmessage=event=>{if(token!==operation)return;if(event.data.error){fail(event.data.error);return;}const report=event.data.report;report.predictions.forEach(r=>{r.feature_date=dates[r.feature_index];r.target_date=dates[r.target_index];});report.latest_forecast.feature_date=dates.at(-1);runCache.set(key,{report,diagnostics:event.data.diagnostics});render(report,source,dates,event.data.diagnostics,false,identity);worker.terminate();worker=null;};worker.onerror=()=>{if(token!==operation)return;fail('Browser calculation could not finish. Try fewer observations or download the Python project.');};worker.postMessage({closes,protocol});}catch(error){if(token===operation)fail(error.message);}}$('experiment').addEventListener('invalid',event=>{for(let parent=event.target.parentElement;parent;parent=parent.parentElement){if(parent.tagName==='DETAILS')parent.open=true;}},true);$('experiment').addEventListener('submit',event=>{event.preventDefault();focusResults=true;run();});function syncSource(){const csv=$('data-source').value==='csv';$('csv-controls').hidden=!csv;$('demo-settings').hidden=csv;$('observations').required=!csv;$('seed').required=!csv;$('observations').disabled=busy||csv;$('seed').disabled=busy||csv;$('csv-file').disabled=busy||!csv;$('observations').min=$('validation-protocol').value==='strict'?'1064':'850';if(!csv&&Number($('observations').value)<Number($('observations').min)){$('demo-settings').open=true;$('setup-options').open=true;}$('protocol-help').textContent=$('validation-protocol').value==='strict'?'Learn, adjust, choose, then check on 200 later outcomes. Each step uses a separate set of prices. Needs at least 1,064 prices.':'Run several checks as more prices become available. Adjusting and choosing share the same examples, so this is easier to overfit. Files need 714 prices; made-up examples need 850.';}$('data-source').addEventListener('change',syncSource);$('validation-protocol').addEventListener('change',syncSource);$('experiment').addEventListener('input',()=>{$('setup-note').hidden=false;});$('experiment').addEventListener('change',()=>{$('setup-note').hidden=false;});$('csv-file').addEventListener('change',()=>{if($('csv-file').files.length)$('data-source').value='csv';syncSource();});syncSource();$('benchmark').addEventListener('click',async()=>{if(busy)return;const token=++operation;setBusy(true,'Opening a saved example. No new models are running…');try{const response=await fetch('benchmark.json',{cache:'no-cache'});if(token!==operation)return;if(!response.ok)throw Error('The benchmark file could not be loaded.');const report=await response.json();if(token!==operation)return;render(report,report.source,null,report.diagnostics);}catch(error){if(token===operation)fail(error.message);}});18 unmodified lines192021222324252627282930313233348 unmodified lines434445464748495051525354555657585960616263646539 unmodified lines1051061071081091101111121131141151161171181192 unmodified lines12212312412512612712812913013113213313413513613713813914014114214318 unmodified linesfunction render(report,source,dates,diagnostics,cacheHit=false,identity=null){currentReport={...report,source,diagnostics,execution:{model_revision:report.precomputed?'saved-python-benchmark':MODEL_REVISION,cache_hit:cacheHit,cache_policy:'Tab memory only; at most 3 runs; ten-minute TTL from computation'}};const view=inspectionJournal.record({data_sha256:identity?.sha256||null,protocol:report.validation_protocol?.name||'historical-python',model_revision:currentReport.execution.model_revision,cache_hit:cacheHit,observations:report.test_observations,selected_log_loss:report.selected_metrics.log_loss,latest_model:report.latest_forecast.model});currentReport.experiment_manifest={schema_version:1,view,inputs:identity||{sha256:null,reason:'Original normalized input series unavailable for this historical artifact.'},provenance:{source_metadata:source,source:source.name||'Saved Python benchmark',adjustments:source.synthetic?'Synthetic generator; no market adjustments.':source.adjustment_basis||'Unknown. Dates and closing prices alone do not establish vendor, corporate-action adjustment or point-in-time availability.'},configuration:{model_revision:currentReport.execution.model_revision,protocol:report.validation_protocol,target:report.target,threshold:report.threshold,model_details:report.model_details},split_boundaries:report.folds,inspection_history:inspectionJournal.snapshot(),limitations:'Fingerprint is computed from normalized dates and prices, not original file bytes. History is tab-local, bounded and resettable; it does not prove independent evaluation or prevent research overfitting.'};currentReport.forward_check=identity&&!report.precomputed?QuantForward.createRecord(currentReport,identity,source):null;const q=report.latest_forecast.probabilities;$('forecast-source').textContent=source.kind==='market_snapshot'?`${source.name} · historical snapshot through ${source.last_observation_date}. These chances concern the next recorded close after that date, not a live quote or today’s forecast.`:source.synthetic?'Practice forecast from made-up prices.':report.precomputed?'Saved historical research example.':`Your price file${identity?.last_date?' · through '+identity.last_date:''}. Vendor and adjustment are not independently verified.`;renderOutcomeSupport(report);const supportMessages=report.feature_support?.warnings?.map(w=>w.message)||[];$('support-warning').textContent=supportMessages.join(' ');$('support-warning').hidden=!supportMessages.length;$('stats').replaceChildren();for(const [label,value]of [['Big fall',percent(q[0])],['Small fall or no change',percent(q[1])],['Rise',percent(q[2])]]){const div=document.createElement('div'),span=document.createElement('span'),strong=document.createElement('strong');span.textContent=label;strong.textContent=value;div.append(span,strong);$('stats').append(div);}$('plain-explanation').textContent=`A ${percent(q[2])} chance of a rise means about ${Math.round(q[2]*100)} out of 100 similar next steps, according to this model. It is a guess, not a promise.`;const kind=report.precomputed?'Saved example':source.synthetic?'Made-up prices for learning':source.kind==='market_snapshot'?source.name+' · dated snapshot':'Your price file';$('status').textContent=`${kind} · ${source.rows.toLocaleString()} prices. ${report.precomputed?'You are viewing a saved result.':source.kind==='market_snapshot'?'Public dated prices; calculations run in this browser.':'Your prices stay in this browser.'}`;if(cacheHit)$('status').textContent+=' Same settings: reused the earlier calculation.';$('status').textContent+=` Result ${view.sequence} in this tab. Save the report to keep its details.`;renderQuality(source);renderValidation(report);8 unmodified lines$('explanations').textContent=report.precomputed?JSON.stringify({mode:'PRECOMPUTED; no Python executes on this host',tuning_trials:report.tuning_trials,shap_explanation:report.shap_explanation,mlflow:report.mlflow,benchmark_date:report.benchmark_date},null,2):'Browser run: no SHAP, Optuna, XGBoost, LightGBM or MLflow execution. Load the precomputed Python benchmark to inspect its saved results, or download the Python project.';$('download').disabled=false;setBusy(false);$('setup-note').hidden=true;if(focusResults&&!$('workbench').hidden){$('results').focus();}focusResults=false;}function renderOutcomeSupport(report){const outcomes=report.validation?.outcomes;$('evaluation-support').hidden=!outcomes?.length;$('evaluation-outcomes').replaceChildren();$('evaluation-warning').textContent='';$('evaluation-warning').hidden=true;if(!outcomes?.length)return;for(const row of outcomes)appendEvidenceRow('evaluation-outcomes',[row.label,`${row.events} / ${row.observations}`,percent(row.mean_predicted),percent(row.observed_rate)]);const rows=report.predictions,first=rows?.[0]?.target_date,last=rows?.at(-1)?.target_date;$('evaluation-scope').textContent=`${outcomes[0].observations} earlier outcomes${first&&last?' · '+first+' to '+last:''}. Average predicted chances and observed rates use the same evaluation rows.`;const sparse=outcomes.filter(row=>row.low_support);if(sparse.length){$('evaluation-warning').hidden=false;$('evaluation-warning').textContent=sparse.map(row=>`${row.label}: only ${row.events} evaluation ${row.events===1?'event':'events'}.`).join(' ')+' Fewer than 10 is a support warning, not a calibrated confidence threshold; accuracy for these outcomes is not well established.';}}function invalidateForecast(message='Settings changed. Press Show my guess to calculate for these inputs.'){operation++;if(worker){worker.terminate();worker=null;}currentReport=null;focusResults=false;setBusy(false);$('download').disabled=true;for(const id of ['stats','support-warning','forecast-source','plain-explanation','probability-chart','timeline-chart','calibration-chart','score-chart','rolling-chart','outcome-summary','scores-body','volatility-note','forecast-context','evaluation-outcomes','evaluation-warning','evaluation-scope','quality-warnings','validation-baselines','validation-folds','validation-support','validation-intervals','validation-movement'])$(id).replaceChildren();for(const id of ['audit','diagnostics','explanations','quality-audit','validation-audit'])$(id).textContent='No current forecast. Calculate with the selected inputs.';$('evaluation-support').hidden=true;$('evaluation-warning').hidden=true;$('support-warning').hidden=true;$('validation-content').hidden=true;$('check-details').hidden=true;$('validation-link').hidden=true;$('validation-verdict').textContent='Make a guess to see how we checked it.';$('quality-summary').textContent='No current price checks.';$('validation-scope').textContent='';$('status').textContent=message;}function appendEvidenceRow(id,values){const row=document.createElement('tr');for(const value of values){const cell=document.createElement('td');cell.textContent=String(value);row.append(cell);}$(id).append(row);}function signed(value){return(value>0?'+':'')+Number(value).toFixed(4);}function intervalText(interval){return interval?.estimable&&interval.percentile95?`[${signed(interval.percentile95[0])}, ${signed(interval.percentile95[1])}]`:'Not estimable';}39 unmodified linesfunction renderQuality(source){const quality=source.data_quality;$('quality-warnings').replaceChildren();$('quality-summary').textContent=source.kind==='market_snapshot'?`${source.rows.toLocaleString()} validated public adjusted prices for ${source.ticker}; observed dates are unique and increasing. No gaps filled. Vendor adjustment is declared, not independently reconstructed.`:quality?`${quality.rows.toLocaleString()} validated prices. ${quality.normalizedHeaderFields} header fields normalized; ${quality.trimmedValues} date/price values trimmed${quality.bomRemoved?'; initial byte-order mark removed':''}. No rows dropped or values filled.`:source.synthetic?'These prices are made up for learning. The dates are example weekdays, not a real market calendar.':'Saved benchmark: no new CSV cleaning was performed.';for(const warning of quality?.warnings||[]){const item=document.createElement('li');item.textContent=warning;$('quality-warnings').append(item);}$('quality-audit').textContent=JSON.stringify(quality||{source:source.name||'Saved benchmark',source_metadata:source,note:'No uploaded CSV cleaning audit available for this mode.'},null,2);document.querySelector('.quality-panel').classList.toggle('has-warnings',Boolean(quality?.warnings.length));document.querySelector('.quality-panel summary').textContent=quality?.warnings.length?`Price checks · ${quality.warnings.length} ${quality.warnings.length===1?'thing':'things'} to review`:'Check my prices';}$('clear-data').addEventListener('click',()=>{operation++;resetForward();if(worker){worker.terminate();worker=null;}runCache.clear();inspectionJournal.clear();currentReport=null;focusResults=false;$('csv-file').value='';$('support-warning').hidden=true;$('evaluation-support').hidden=true;$('evaluation-warning').hidden=true;$('forecast-source').textContent='';$('evaluation-outcomes').replaceChildren();$('evaluation-warning').textContent='';$('evaluation-scope').textContent='';setBusy(false);$('download').disabled=true;$('setup-note').hidden=true;for(const id of ['support-warning','plain-explanation','stats','probability-chart','timeline-chart','calibration-chart','score-chart','outcome-summary','scores-body','volatility-note','quality-warnings','forecast-context','validation-baselines','validation-folds','validation-support','validation-intervals','validation-movement','rolling-chart','validation-policy','validation-interval-note','movement-note','rolling-description','validation-support-note','validation-interpretation'])$(id).replaceChildren();for(const id of ['audit','diagnostics','explanations','quality-audit'])$(id).textContent='No forecast data retained by this app. Start a new run.';$('quality-summary').textContent='No active data. Choose a source and update the forecast.';2 unmodified lines$('score-note').textContent='No current model scores.';$('validation-content').hidden=true;$('check-details').hidden=true;$('validation-link').hidden=true;$('validation-support-note').hidden=true;$('validation-verdict').textContent='Make a guess to see how we checked it.';$('validation-scope').textContent='';$('validation-audit').textContent='No validation data retained.';});function syntheticDates(n){const dates=[],day=new Date('2010-01-04T00:00:00Z');while(dates.length<n){if(day.getUTCDay()!==0&&day.getUTCDay()!==6)dates.push(day.toISOString().slice(0,10));day.setUTCDate(day.getUTCDate()+1);}return dates;}async function run(){if(busy)return;const requestedFocus=focusResults;invalidateForecast('Preparing the selected prices…');focusResults=requestedFocus;const token=++operation;setBusy(true,'Learning from earlier prices, then checking guesses against later prices…');try{let closes,dates,source;const mode=$('data-source').value,protocol=$('validation-protocol').value;if(!['classic','strict'].includes(protocol))throw Error('Choose how to check the guesses.');if(mode==='csv'){const file=$('csv-file').files[0];if(!file)throw Error('Choose a price file with date and close columns, or select Made-up prices.');if(file.size>2*1024*1024)throw Error('CSV must be no larger than 2 MiB.');const buffer=await file.arrayBuffer();if(token!==operation)return;let text;try{text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(buffer);}catch{throw Error('CSV must use valid UTF-8 encoding. Export it as UTF-8 and try again.');}const data=QuantLabs.parseCSV(text);closes=data.closes;dates=data.dates;source={synthetic:false,rows:closes.length,name:'Local CSV',calendar_gap_max_days:data.calendarGapMaxDays,data_quality:data.quality};}else if(mode==='market'){const ticker=$('market-ticker').value;const catalog=await QuantMarket.loadSnapshot();if(token!==operation)return;const selected=catalog.find(s=>s.ticker===ticker);if(!selected)throw Error('Choose a ticker available in the dated snapshot.');closes=selected.closes;dates=selected.dates;source=QuantMarket.source(selected);}else if(mode==='synthetic'){const n=Number($('observations').value),seed=Number($('seed').value);if(!Number.isInteger(n)||n<850||n>2500||!Number.isInteger(seed)||seed<0||seed>100000)throw Error('Use 850–2,500 observations and an integer seed from 0 to 100,000.');const model=await import('./model.js?v=20261027audit2');if(token!==operation)return;closes=globalThis.QuantModel.synthetic(n,seed);dates=syntheticDates(n);source={synthetic:true,rows:n,seed,name:'Browser synthetic generator',calendar:'Weekday placeholders, not exchange dates'};}else throw Error('Choose a valid price source.');if(protocol==='strict'&&closes.length<1064)throw Error('The separate test needs at least 1,064 prices. Add more prices, or open How we check the guesses and choose Repeated checks.');const sha256=await QuantProvenance.fingerprint({dates,closes});if(token!==operation)return;const identity={sha256,canonical_format:'quantlab-normalized-prices-v1: JSON array of format tag, ISO dates, finite positive numeric closes',rows:closes.length,first_date:dates[0],last_date:dates.at(-1),last_close:closes.at(-1)};const key=JSON.stringify([MODEL_REVISION,protocol,dates,closes]);const cached=runCache.get(key);if(cached){render(cached.report,source,dates,cached.diagnostics,true,identity);return;}if(worker)worker.terminate();worker=new Worker('worker.js?v=20261029forecast1');worker.onmessage=event=>{if(token!==operation)return;if(event.data.error){fail(event.data.error);return;}const report=event.data.report;report.predictions.forEach(r=>{r.feature_date=dates[r.feature_index];r.target_date=dates[r.target_index];});report.latest_forecast.feature_date=dates.at(-1);runCache.set(key,{report,diagnostics:event.data.diagnostics});render(report,source,dates,event.data.diagnostics,false,identity);worker.terminate();worker=null;};worker.onerror=()=>{if(token!==operation)return;fail('Browser calculation could not finish. Try fewer observations or download the Python project.');};worker.postMessage({closes,protocol});}catch(error){if(token===operation)fail(error.message);}}$('experiment').addEventListener('invalid',event=>{for(let parent=event.target.parentElement;parent;parent=parent.parentElement){if(parent.tagName==='DETAILS')parent.open=true;}},true);$('experiment').addEventListener('submit',event=>{event.preventDefault();focusResults=true;run();});function syncSource(){const mode=$('data-source').value,csv=mode==='csv',market=mode==='market',synthetic=mode==='synthetic';$('csv-controls').hidden=!csv;$('market-controls').hidden=!market;$('demo-settings').hidden=!synthetic;$('observations').required=synthetic;$('seed').required=synthetic;$('observations').disabled=busy||!synthetic;$('seed').disabled=busy||!synthetic;$('csv-file').disabled=busy||!csv;$('market-ticker').disabled=busy||!market;$('observations').min=$('validation-protocol').value==='strict'?'1064':'850';if(synthetic&&Number($('observations').value)<Number($('observations').min)){$('demo-settings').open=true;$('setup-options').open=true;}$('protocol-help').textContent=$('validation-protocol').value==='strict'?'Learn, adjust, choose, then check on 200 later outcomes. Each step uses a separate set of prices. Needs at least 1,064 prices.':'Run several checks as more prices become available. Adjusting and choosing share the same examples, so this is easier to overfit. Files need 714 prices; made-up examples need 850.';}$('data-source').addEventListener('change',syncSource);$('validation-protocol').addEventListener('change',syncSource);$('experiment').addEventListener('input',()=>{invalidateForecast();$('setup-note').hidden=false;});$('experiment').addEventListener('change',()=>{$('setup-note').hidden=false;});$('csv-file').addEventListener('change',()=>{if($('csv-file').files.length)$('data-source').value='csv';syncSource();});syncSource();$('benchmark').addEventListener('click',async()=>{if(busy)return;const token=++operation;setBusy(true,'Opening a saved example. No new models are running…');try{const response=await fetch('benchmark.json',{cache:'no-cache'});if(token!==operation)return;if(!response.ok)throw Error('The benchmark file could not be loaded.');const report=await response.json();if(token!==operation)return;render(report,report.source,null,report.diagnostics);}catch(error){if(token===operation)fail(error.message);}});
123version https://git-lfs.github.com/spec/v1oid sha256:ed0d3bbd59addeb451e06af86af05891d37aa84c3a9aea367ae0e9f6b2983067size 120995929 unmodified lines3031323334353629 unmodified linesif(!Array.isArray(counts)||counts.length!==3||Array.from(counts).some(v=>!Number.isSafeInteger(v)||v<0)||!Number.isSafeInteger(n)||n<1||n>2500||counts.reduce((a,b)=>a+b,0)!==n)throw Error('Training class counts must match the training sample size.');if(typeof savedAt!=='string'||!Number.isFinite(Date.parse(savedAt))||new Date(savedAt).toISOString()!==savedAt)throw Error('Use a valid ISO saved timestamp.');const revision=report.execution?.model_revision;return{schema_version:1,target:TARGET,threshold:-.02,saved_at:savedAt,model_revision:typeof revision==='string'?revision:'unrecorded-browser-model',model:typeof report.latest_forecast.model==='string'?report.latest_forecast.model:'unknown',synthetic:source.synthetic===true,anchor:anchor(identity),probabilities:probabilities(report.latest_forecast.probabilities),baseline_probabilities:counts.map(v=>(v+1)/(n+3)),baseline:'Untuned training class frequencies with Laplace smoothing of one per class.',note:NOTE};}function scoreRecord(record,observation={}){validRecord(record);29 unmodified lines3031323334353629 unmodified linesif(!Array.isArray(counts)||counts.length!==3||Array.from(counts).some(v=>!Number.isSafeInteger(v)||v<0)||!Number.isSafeInteger(n)||n<1||n>2500||counts.reduce((a,b)=>a+b,0)!==n)throw Error('Training class counts must match the training sample size.');if(typeof savedAt!=='string'||!Number.isFinite(Date.parse(savedAt))||new Date(savedAt).toISOString()!==savedAt)throw Error('Use a valid ISO saved timestamp.');const revision=report.execution?.model_revision;return{schema_version:1,target:TARGET,threshold:-.02,saved_at:savedAt,model_revision:typeof revision==='string'?revision:'unrecorded-browser-model',model:typeof report.latest_forecast.model==='string'?report.latest_forecast.model:'unknown',synthetic:source.synthetic===true,source:Object.fromEntries(['kind','name','ticker','currency','adjustment_basis','source_url','snapshot_retrieved_at','last_observation_date'].filter(key=>typeof source[key]==='string').map(key=>[key,source[key]])),anchor:anchor(identity),probabilities:probabilities(report.latest_forecast.probabilities),baseline_probabilities:counts.map(v=>(v+1)/(n+3)),baseline:'Untuned training class frequencies with Laplace smoothing of one per class.',note:NOTE};}function scoreRecord(record,observation={}){validRecord(record);
3 unmodified lines45678910114 unmodified lines161718192021222324252627282930313269 unmodified lines1021031041051061071083 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f5f5f7"><meta name="description" content="Explore price possibilities with simple examples and clear checks. Runs in your browser."><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'none'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261027audit2"><script src="labs.js?v=20261027audit2" defer></script><script src="cache.js?v=20261027audit2" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="forward.js?v=20261027audit2" defer></script><script src="execution.js?v=20261027audit2" defer></script><script src="app.js?v=20261027audit2" defer></script><link rel="stylesheet" href="investment.css?v=20261029investment1"><script src="investment.js?v=20261029investment1" defer></script><script src="investment-ui.js?v=20261029investment1" defer></script></head>4 unmodified lines<div class="introduction"><h1>Make sense of chance.</h1><p>Explore three possibilities for the next price.</p></div><section id="workbench" class="view"><aside class="experiment-tools" aria-label="Price choices"><form id="experiment"><div class="experiment-row"><div class="price-picker"><label for="data-source">Choose your prices</label><select id="data-source"><option value="synthetic">Made-up prices</option><option value="csv">My price file</option></select></div><button id="run" class="primary" type="submit">Show my guess</button></div><div id="csv-controls" hidden><label for="csv-file">Choose a CSV file · date,close</label><input id="csv-file" type="file" accept=".csv,text/csv"><p class="hint">Use a CSV text file with date and close columns, oldest date first (for example 2026-01-01). It needs 1,064–2,500 prices with the usual checking method, or at least 714 with repeated checks. Maximum file size: 2 MiB. Use prices adjusted for splits and dividends. Missing prices and dates are not filled in.</p></div><details class="setup-options" id="setup-options"><summary>Change the example or checking method</summary><div class="settings-grid"><details id="demo-settings"><summary>Change the example</summary><label for="observations">Number of made-up prices</label><input id="observations" type="number" min="850" max="2500" step="1" value="1200" required><label for="seed">Example number</label><input id="seed" type="number" min="0" max="100000" step="1" value="42" required><p class="hint">The same example number makes the same pretend prices. Change it to try a different story.</p></details><details><summary>How we check the guesses</summary><label for="validation-protocol">Checking method</label><select id="validation-protocol" aria-describedby="protocol-help"><option value="strict">Separate practice and check</option><option value="classic">Repeated checks over time</option></select><p class="hint" id="protocol-help">The first method saves the last 200 answers for checking. It needs at least 1,064 prices. The other method checks several periods in order.</p></details><details class="model-list"><summary>Meet the guessing methods</summary><h2>Four ways to make a guess</h2><p>Count earlier outcomes<br>Look for price patterns<br>Watch changing wiggles<br>Learn three outcome chances</p><span class="hint">Each method learns from earlier prices. The checking method decides which later answers are saved to check it.</span></details></div></details><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><details id="check-details" hidden><summary>See how we checked</summary><div id="validation-content" hidden>69 unmodified lines<p id="cost-threshold" class="cost-threshold" aria-live="polite"></p><div id="cost-output" class="calculation-result" role="status" aria-live="polite"></div><details><summary>How this story works</summary><p class="hint">Each trade uses the same starting amount. Every finished trade buys and sells once, with the same price change and costs. Unfinished trades are assumed never to fill, so they cost nothing here. All percentages are applied to the starting amount; money is not reinvested. Skipping a losing trade can help. Real orders can fill only partly, and their timing and price can differ.</p><p class="hint">This is arithmetic, not a historical trading test, order-book replay or estimate of future profit. HftBacktest, NautilusTrader and KalshiMarketMaker are not running here.</p><pre id="cost-audit"></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, including a pretend trading-cost story. <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. Strict mode also lets unadjusted past-outcome counts compete during selection, with no temperature fitted for that candidate.</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 (untuned and temperature-adjusted in strict mode), 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">Model tests and rejected changes</a> · <a href="LEAK-AUDIT.md">Data leakage and overfitting checks</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. The separate trading-cost story uses chosen assumptions; it is not an economic backtest. No live trading 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 lines45678910114 unmodified lines16171819202122232425262728293031323369 unmodified lines1031041051061071081093 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f5f5f7"><meta name="description" content="Explore price possibilities with simple examples and clear checks. Runs in your browser."><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'none'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261029forecast1"><script src="labs.js?v=20261027audit2" defer></script><script src="cache.js?v=20261027audit2" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="forward.js?v=20261029forecast1" defer></script><script src="execution.js?v=20261027audit2" defer></script><script src="market.js?v=20261029forecast1" defer></script><script src="app.js?v=20261029forecast1" defer></script><link rel="stylesheet" href="investment.css?v=20261029investment1"><script src="investment.js?v=20261029investment1" defer></script><script src="investment-ui.js?v=20261029investment1" defer></script></head>4 unmodified lines<div class="introduction"><h1>Make sense of chance.</h1><p>Explore three possibilities for the next price.</p></div><section id="workbench" class="view"><aside class="experiment-tools" aria-label="Price choices"><form id="experiment"><div class="experiment-row"><div class="price-picker"><label for="data-source">Choose your prices</label><select id="data-source"><option value="synthetic">Made-up prices</option><option value="market">Stock or ETF snapshot</option><option value="csv">My price file</option></select></div><button id="run" class="primary" type="submit">Show my guess</button></div><div id="market-controls" hidden><label for="market-ticker">Stock or ETF ticker</label><select id="market-ticker" name="ticker" autocomplete="off" disabled><option value="AAPL">AAPL · Apple Inc.</option><option value="MSFT">MSFT · Microsoft Corporation</option><option value="NVDA">NVDA · NVIDIA Corporation</option><option value="AMZN">AMZN · Amazon.com, Inc.</option><option value="GOOGL">GOOGL · Alphabet Inc.</option><option value="TSLA">TSLA · Tesla, Inc.</option><option value="SPY">SPY · State Street SPDR S&P 500 ETF Trust</option><option value="QQQ">QQQ · Invesco QQQ Trust</option></select><p class="hint">Dated, adjusted USD prices. The forecast concerns the next recorded close after the snapshot’s final date. This is not a live market forecast. <a href="MARKET-DATA.md">Sources & adjustment details</a></p></div><div id="csv-controls" hidden><label for="csv-file">Choose a CSV file · date,close</label><input id="csv-file" type="file" accept=".csv,text/csv"><p class="hint">Use a CSV text file with date and close columns, oldest date first (for example 2026-01-01). It needs 1,064–2,500 prices with the usual checking method, or at least 714 with repeated checks. Maximum file size: 2 MiB. Use prices adjusted for splits and dividends. Missing prices and dates are not filled in.</p></div><details class="setup-options" id="setup-options"><summary>Change the example or checking method</summary><div class="settings-grid"><details id="demo-settings"><summary>Change the example</summary><label for="observations">Number of made-up prices</label><input id="observations" type="number" min="850" max="2500" step="1" value="1200" required><label for="seed">Example number</label><input id="seed" type="number" min="0" max="100000" step="1" value="42" required><p class="hint">The same example number makes the same pretend prices. Change it to try a different story.</p></details><details><summary>How we check the guesses</summary><label for="validation-protocol">Checking method</label><select id="validation-protocol" aria-describedby="protocol-help"><option value="strict">Separate practice and check</option><option value="classic">Repeated checks over time</option></select><p class="hint" id="protocol-help">The first method saves the last 200 answers for checking. It needs at least 1,064 prices. The other method checks several periods in order.</p></details><details class="model-list"><summary>Meet the guessing methods</summary><h2>Ways to make a guess</h2><p>Count earlier outcomes, with or without calibration<br>Look for price patterns<br>Watch changing wiggles<br>Learn three outcome chances</p><span class="hint">Each method learns from earlier prices. The checking method decides which later answers are saved to check it.</span></details></div></details><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><p id="forecast-source" class="forecast-source"></p><div class="stats" id="stats"><div><span>Big fall</span><strong>—</strong></div><div><span>Small fall or no change</span><strong>—</strong></div><div><span>Rise</span><strong>—</strong></div></div><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 id="evaluation-support" class="evaluation-support" aria-labelledby="evaluation-title" hidden><h2 id="evaluation-title">What the check data actually showed.</h2><p id="evaluation-scope" class="small"></p><div class="table-scroll"><table><caption class="sr-only">Evaluation outcome counts, average predicted probabilities and observed rates on identical rows</caption><thead><tr><th scope="col">Outcome</th><th scope="col">Events / checked</th><th scope="col">Average chance</th><th scope="col">Observed rate</th></tr></thead><tbody id="evaluation-outcomes"></tbody></table></div><p id="evaluation-warning" class="support-warning" role="status" hidden></p><p class="hint">Similar averages do not prove calibration or forecast accuracy. These are historical checks, not confidence bounds for the next price.</p></section><section class="validation-panel" aria-labelledby="validation-title"><div class="evidence-heading"><h2 id="validation-title">Did the guesses help?</h2><a id="validation-link" href="#check-details" hidden>See the checks</a></div><p id="validation-verdict" class="evidence-verdict">Make a guess to see how we checked it.</p><details id="check-details" hidden><summary>See how we checked</summary><div id="validation-content" hidden>69 unmodified lines<p id="cost-threshold" class="cost-threshold" aria-live="polite"></p><div id="cost-output" class="calculation-result" role="status" aria-live="polite"></div><details><summary>How this story works</summary><p class="hint">Each trade uses the same starting amount. Every finished trade buys and sells once, with the same price change and costs. Unfinished trades are assumed never to fill, so they cost nothing here. All percentages are applied to the starting amount; money is not reinvested. Skipping a losing trade can help. Real orders can fill only partly, and their timing and price can differ.</p><p class="hint">This is arithmetic, not a historical trading test, order-book replay or estimate of future profit. HftBacktest, NautilusTrader and KalshiMarketMaker are not running here.</p><pre id="cost-audit"></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, including a pretend trading-cost story. <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. Strict mode also lets unadjusted past-outcome counts compete during selection, with no temperature fitted for that candidate.</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 (untuned and temperature-adjusted in strict mode), 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="FORECAST-STUDY.md">Heavy-tail challenger study and decision</a> · <a href="MODEL-STUDY.md">Earlier model tests and rejected changes</a> · <a href="LEAK-AUDIT.md">Data leakage and overfitting checks</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. The separate trading-cost story uses chosen assumptions; it is not an economic backtest. No live trading 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>
1234567891011121314151617181920212223242526272829/* Dated public snapshots only; no uploaded input is transmitted by this module. */(function(root){'use strict';function validateSnapshot(data){ if(!data||data.schemaVersion!==1||!Array.isArray(data.securities)||!data.securities.length||data.securities.length>32)throw Error('Invalid market snapshot catalog. Use a CSV or made-up example.'); const seen=new Set(); return data.securities.map(s=>{ if(!s||typeof s.ticker!=='string'||!/^[A-Z0-9.^-]{1,15}$/.test(s.ticker)||seen.has(s.ticker))throw Error('Invalid or duplicate snapshot ticker.');seen.add(s.ticker); if(s.currency!=='USD'||typeof s.name!=='string'||!s.name.trim()||s.name.length>200||typeof s.adjustment!=='string'||!s.adjustment.trim()||s.adjustment.length>1000||typeof s.sourceUrl!=='string'||!/^https:\/\//.test(s.sourceUrl)||typeof s.retrievedAt!=='string'||!Number.isFinite(Date.parse(s.retrievedAt)))throw Error('Snapshot source, adjustment or USD metadata is invalid.'); if(!Array.isArray(s.dates)||!Array.isArray(s.closes)||s.dates.length!==s.closes.length||s.dates.length<714||s.dates.length>2500)throw Error('Market snapshots need 714–2,500 matching daily dates and prices.'); let previous=''; for(let i=0;i<s.dates.length;i++){ const date=s.dates[i],value=s.closes[i]; if(typeof date!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(date)||date.slice(0,4)==='0000'||!Number.isFinite(Date.parse(date+'T00:00:00Z'))||new Date(date+'T00:00:00Z').toISOString().slice(0,10)!==date||date<=previous)throw Error('Snapshot dates must be valid, unique and increasing.'); if(typeof value!=='number'||!Number.isFinite(value)||value<=0)throw Error('Snapshot prices must be finite and positive.');previous=date; } return{...s,dates:s.dates.slice(),closes:s.closes.slice()}; });}async function loadSnapshot(fetcher=fetch){ const response=await fetcher('market-data.json',{cache:'no-cache'}); if(!response.ok)throw Error('Market snapshots are unavailable. Use your CSV or the made-up example.'); const text=await response.text();if(new TextEncoder().encode(text).length>2*1024*1024)throw Error('Market snapshot exceeds the 2 MiB limit.'); let data;try{data=JSON.parse(text);}catch{throw Error('Market snapshot is not valid JSON. Use a CSV or made-up example.');} return validateSnapshot(data);}function source(s){return{kind:'market_snapshot',synthetic:false,ticker:s.ticker,currency:s.currency,rows:s.closes.length,name:s.ticker+' · '+s.name,adjustment_basis:s.adjustment,source_url:s.sourceUrl,snapshot_retrieved_at:s.retrievedAt,first_observation_date:s.dates[0],last_observation_date:s.dates.at(-1),calendar:'Observed exchange sessions; no gaps filled.'};}const api={validateSnapshot,loadSnapshot,source};if(typeof module!=='undefined'&&module.exports)module.exports=api;root.QuantMarket=api;})(globalThis);32 unmodified lines33343532 unmodified lines@media(max-width:420px){.cost-lab .input-grid{grid-template-columns:1fr}}.cost-threshold{font-size:16px;line-height:1.65;font-weight:500;max-width:65ch;margin-top:24px}.cost-threshold:empty{display:none}32 unmodified lines3334353637383932 unmodified lines@media(max-width:420px){.cost-lab .input-grid{grid-template-columns:1fr}}.cost-threshold{font-size:16px;line-height:1.65;font-weight:500;max-width:65ch;margin-top:24px}.cost-threshold:empty{display:none}/* Forecast source and support stay next to the actual outcome chances. */#market-controls{max-width:640px;margin:16px auto}.forecast-source{font-size:14px;line-height:1.65;color:#515158;max-width:72ch;margin:16px auto 24px;text-align:center}.forecast-source:empty{display:none}.evaluation-support{border:1px solid var(--line);border-radius:12px;padding:22px 24px;margin:24px 0}.evaluation-support h2{font-size:19px;line-height:1.3;margin-bottom:10px}.evaluation-support .small{margin-bottom:12px}.evaluation-support table{font-size:12px}.evaluation-support .support-warning{margin:16px 0 0;padding:14px}.evaluation-support>.hint{margin-bottom:0}.evaluation-support td:first-child,.evaluation-support th:first-child{white-space:normal}.evaluation-support th{vertical-align:bottom}@media(max-width:600px){.forecast-source{text-align:left;font-size:13px}.evaluation-support{padding:18px 14px}.evaluation-support table{font-size:11px;table-layout:fixed}.evaluation-support td,.evaluation-support th{white-space:normal;overflow-wrap:anywhere;padding:12px 5px}.evaluation-support th:first-child{width:30%}}
1 unmodified line23456781 unmodified line10111213141516171819202137 unmodified lines5960616263641 unmodified lineconst {createRunCache}=require('./cache.js');const nodes=new Map();function node(id){if(!nodes.has(id))nodes.set(id,{id,value:id==='validation-protocol'?'strict':id==='data-source'?'synthetic':id==='observations'?'1200':'42',files:[],textContent:'',hidden:false,disabled:false,listeners:{},classList:{remove(){},add(){},toggle(){}},addEventListener(type,fn){this.listeners[type]=fn;},setAttribute(){},replaceChildren(){this.textContent='';},append(){},focus(){this.focused=true;},scrollIntoView(){this.scrolled=true;},click(){downloadClicks++;}});return nodes.get(id);}const tabs=[node('forecast-tab'),node('help-tab')];tabs[0].dataset={view:'workbench'};tabs[1].dataset={view:'methods'};let workerCount=0,parseCount=0,cacheWrites=0,exportedBlob=null,downloadClicks=0;const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};let network=deferred();const sandbox={URL:{createObjectURL(blob){exportedBlob=blob;return 'blob:fixture';},revokeObjectURL(){}},console,TextEncoder,TextDecoder,structuredClone,setTimeout,clearTimeout,Date,JSON,Math,Number,Blob,1 unmodified lineQuantProvenance:{...require('./provenance.js'),fingerprint:async()=> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'},QuantCache:{createRunCache(){const cache=createRunCache();return{...cache,set(...args){cacheWrites++;cache.set(...args);}};}},QuantForward:require('./forward.js'),QuantExecution:{costs:input=>require('./execution.js').costs(input)},QuantModel:{synthetic:()=>Array(1200).fill(100)},QuantLabs:{game:()=>({}),blackScholes:()=>({call:1,put:1}),kelly:()=>0,parseCSV(){parseCount++;return{closes:Array(1200).fill(100),dates:Array(714).fill('2020-01-01'),quality:{}};}},QuantScenarios:{impliedVolatility(){throw Error('stub');},jumpDistribution(){throw Error('stub');}},FormData:class{get(){return '1';}},fetch:()=>network.promise,Worker:class{constructor(){workerCount++;}postMessage(){}terminate(){}}};sandbox.globalThis=sandbox;const source=fs.readFileSync(require.resolve('./app.js'),'utf8').replace(/import\('\.\/model\.js[^']*'\)/,"Promise.resolve({})");vm.createContext(sandbox);vm.runInContext(source,sandbox);37 unmodified linesnode('forward-file').files=[{size:2,arrayBuffer:async()=>new TextEncoder().encode('{}').buffer}];await node('forward-form').listeners.submit({preventDefault(){}});assert.match(node('forward-status').textContent,/new browser guess/);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');console.log('Export integration passed: current manifest, validation, cache-hit history and clear');console.log('App state tests passed: clear invalidates delayed module, CSV read, benchmark response and JSON; fresh runs still work');})().catch(error=>{console.error(error);process.exitCode=1;});1 unmodified line23456781 unmodified line1011121314151617181920212237 unmodified lines606162636465666768697071727374751 unmodified lineconst {createRunCache}=require('./cache.js');const nodes=new Map();function node(id){if(!nodes.has(id))nodes.set(id,{id,value:id==='validation-protocol'?'strict':id==='data-source'?'synthetic':id==='observations'?'1200':'42',files:[],textContent:'',hidden:false,disabled:false,listeners:{},classList:{remove(){},add(){},toggle(){}},addEventListener(type,fn){this.listeners[type]=fn;},setAttribute(){},replaceChildren(){this.textContent='';},append(){},focus(){this.focused=true;},scrollIntoView(){this.scrolled=true;},click(){downloadClicks++;}});return nodes.get(id);}const tabs=[node('forecast-tab'),node('help-tab')];tabs[0].dataset={view:'workbench'};tabs[1].dataset={view:'methods'};let lastWorkerData=null;let workerCount=0,parseCount=0,cacheWrites=0,exportedBlob=null,downloadClicks=0;const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};let network=deferred();const sandbox={URL:{createObjectURL(blob){exportedBlob=blob;return 'blob:fixture';},revokeObjectURL(){}},console,TextEncoder,TextDecoder,structuredClone,setTimeout,clearTimeout,Date,JSON,Math,Number,Blob,1 unmodified lineQuantProvenance:{...require('./provenance.js'),fingerprint:async()=> 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'},QuantCache:{createRunCache(){const cache=createRunCache();return{...cache,set(...args){cacheWrites++;cache.set(...args);}};}},QuantForward:require('./forward.js'),QuantMarket:{source:require('./market.js').source,loadSnapshot:async()=>require('./market-data.json').securities},QuantExecution:{costs:input=>require('./execution.js').costs(input)},QuantModel:{synthetic:()=>Array(1200).fill(100)},QuantLabs:{game:()=>({}),blackScholes:()=>({call:1,put:1}),kelly:()=>0,parseCSV(){parseCount++;return{closes:Array(1200).fill(100),dates:Array(714).fill('2020-01-01'),quality:{}};}},QuantScenarios:{impliedVolatility(){throw Error('stub');},jumpDistribution(){throw Error('stub');}},FormData:class{get(){return '1';}},fetch:()=>network.promise,Worker:class{constructor(){workerCount++;}postMessage(data){lastWorkerData=data;}terminate(){}}};sandbox.globalThis=sandbox;const source=fs.readFileSync(require.resolve('./app.js'),'utf8').replace(/import\('\.\/model\.js[^']*'\)/,"Promise.resolve({})");vm.createContext(sandbox);vm.runInContext(source,sandbox);37 unmodified linesnode('forward-file').files=[{size:2,arrayBuffer:async()=>new TextEncoder().encode('{}').buffer}];await node('forward-form').listeners.submit({preventDefault(){}});assert.match(node('forward-status').textContent,/new browser guess/);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');// A pending market read must not create a worker after clear or source changes.const marketPending=deferred();sandbox.QuantMarket.loadSnapshot=()=>marketPending.promise;node('data-source').value='market';node('market-ticker').value='AAPL';const beforeMarket=workerCount;const marketRun=vm.runInContext('run()',sandbox);node('clear-data').listeners.click();marketPending.resolve(require('./market-data.json').securities);await marketRun;assert.equal(workerCount,beforeMarket);assert.equal(vm.runInContext('currentReport',sandbox),null);sandbox.QuantMarket.loadSnapshot=async()=>require('./market-data.json').securities;await vm.runInContext('run()',sandbox);assert.equal(workerCount,beforeMarket+1);assert.equal(lastWorkerData.closes.length,1254);node('clear-data').listeners.click();node('data-source').value='synthetic';node('seed').value='42';node('observations').value='1200';vm.runInContext("render(fixtureReport,{synthetic:true,rows:1200,name:'Fixture'},null,{},false,{sha256:'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',rows:1200,last_date:'2014-08-08',last_close:100})",sandbox);node('experiment').listeners.input();assert.equal(vm.runInContext('currentReport',sandbox),null);assert.equal(node('download').disabled,true);assert.equal(node('evaluation-support').hidden,true,'Edited inputs must hide stale reliability');console.log('Ticker/source state passed: late market read canceled; fresh snapshot fits; edits invalidate export and reliability.');console.log('Export integration passed: current manifest, validation, cache-hit history and clear');console.log('App state tests passed: clear invalidates delayed module, CSV read, benchmark response and JSON; fresh runs still work');})().catch(error=>{console.error(error);process.exitCode=1;});
23 unmodified lines24252623 unmodified linesconst zeroQ={...r,probabilities:[0,1,0]};assert.equal(F.scoreRecord(zeroQ,{date:'2026-01-02',close:r.anchor.close*2,confirmedNext:true}).log_loss,-Math.log(1e-12));const mutable=F.createRecord(report,identity,source);mutable.probabilities[0]=999;assert.notEqual(report.latest_forecast.probabilities[0],999);console.log('Forward tests passed: frozen strict-model record, independent observed outcome, scoring, dates, validation, no mutation');23 unmodified lines242526272829303123 unmodified linesconst zeroQ={...r,probabilities:[0,1,0]};assert.equal(F.scoreRecord(zeroQ,{date:'2026-01-02',close:r.anchor.close*2,confirmedNext:true}).log_loss,-Math.log(1e-12));const mutable=F.createRecord(report,identity,source);mutable.probabilities[0]=999;assert.notEqual(report.latest_forecast.probabilities[0],999);console.log('Forward tests passed: frozen strict-model record, independent observed outcome, scoring, dates, validation, no mutation');const snapshotSource={kind:'market_snapshot',synthetic:false,ticker:'AAPL',currency:'USD',name:'AAPL · Apple Inc.',adjustment_basis:'Adjusted for splits and dividends',source_url:'https://finance.yahoo.com/quote/AAPL/',snapshot_retrieved_at:'2026-01-01T00:00:00Z',last_observation_date:'2026-01-01'};const labeled=F.createRecord(report,identity,snapshotSource,'2026-01-01T10:00:00.000Z');assert.equal(labeled.source.ticker,'AAPL');assert.equal(labeled.source.kind,'market_snapshot');assert.equal(labeled.source.last_observation_date,identity.last_date);assert.equal(labeled.source.adjustment_basis,snapshotSource.adjustment_basis);snapshotSource.ticker='MSFT';assert.equal(labeled.source.ticker,'AAPL','Record source must be a snapshot of the identity at creation');const old={...r};delete old.source;assert(Number.isFinite(F.scoreRecord(old,{date:'2026-01-02',close:100,confirmedNext:true}).log_loss),'Legacy saved records stay scoreable');
12345678910111213141516'use strict';const assert=require('node:assert/strict');const Q=require('./market.js');const raw=require('./market-data.json');const clone=()=>structuredClone(raw);const list=Q.validateSnapshot(raw);assert.equal(list.length,8);assert.equal(list[0].ticker,'AAPL');assert.equal(list[0].closes.length,1254);assert.notEqual(list[0].closes,raw.securities[0].closes,'Validated input must not share mutable price arrays');for(const mutate of [d=>d.schemaVersion=2,d=>d.securities[0].currency='EUR',d=>d.securities[0].closes[0]=0,d=>d.securities[0].closes[0]=Infinity,d=>d.securities[0].dates[0]='2021-02-30',d=>d.securities[0].dates[1]=d.securities[0].dates[0],d=>d.securities[0].dates.pop(),d=>d.securities[0].sourceUrl='javascript:alert(1)',d=>d.securities[0].ticker='<img>',d=>d.securities.push(d.securities[0]),d=>d.securities[0].adjustment='']){const data=clone();mutate(data);assert.throws(()=>Q.validateSnapshot(data));}assert.throws(()=>Q.validateSnapshot({schemaVersion:1,securities:[]}));(async()=>{let call;const items=await Q.loadSnapshot(async(url,options)=>{call={url,options};return{ok:true,text:async()=>JSON.stringify(raw)}});assert.equal(items.length,8);assert.equal(call.url,'market-data.json');assert(!call.options.body);assert.equal(call.options.cache,'no-cache');await assert.rejects(()=>Q.loadSnapshot(async()=>({ok:false,status:503})),/unavailable/i);await assert.rejects(()=>Q.loadSnapshot(async()=>({ok:true,text:async()=>'{bad'})),/snapshot/i);await assert.rejects(()=>Q.loadSnapshot(async()=>({ok:true,text:async()=>' '.repeat(2*1024*1024+1)})),/2 MiB/);const source=Q.source(items[0]);assert.equal(source.ticker,'AAPL');assert.equal(source.kind,'market_snapshot');assert.equal(source.last_observation_date,'2026-10-28');assert.equal(source.rows,1254);assert.match(source.adjustment_basis,/adjusted/i);assert.equal(source.synthetic,false);console.log('Market snapshot tests passed: eight verified series, invalid inputs, bounded read, source provenance, failed fetch.');})().catch(e=>{console.error(e);process.exitCode=1});1234567891011121314151617181920212223242526272829303132const assert=require('node:assert/strict');const {analyze}=require('./validation.js');const options={reps:1,blocks:[1]};function fixture(returns,probabilities){return{predictions:returns.map((actual_log_return,i)=>({actual_log_return,probabilities:probabilities?.[i]||[.2,.3,.5],baseline_probabilities:{empirical_raw:[.2,.3,.5],empirical_calibrated:[.2,.3,.5]},feature_index:i,target_index:i+1}))};}// All means use the identical validated evaluation rows, including boundary values.const report=fixture([-.020001,-.02,0,.000001],[[.1,.2,.7],[.2,.4,.4],[.3,.5,.2],[.4,.1,.5]]);const result=analyze(report,options);assert(Array.isArray(result.outcomes),'Outcome summaries must be available for matched evaluation rows');assert.deepEqual(result.outcomes.map(({class_index,label,events,observations,observed_rate,low_support})=>({class_index,label,events,observations,observed_rate,low_support})),[ {class_index:0,label:'Big fall',events:1,observations:4,observed_rate:.25,low_support:true}, {class_index:1,label:'Small fall or no change',events:2,observations:4,observed_rate:.5,low_support:true}, {class_index:2,label:'Rise',events:1,observations:4,observed_rate:.25,low_support:true}]);for(const [i,expected]of[.25,.3,.45].entries())assert(Math.abs(result.outcomes[i].mean_predicted-expected)<1e-12);assert.equal(result.outcomes.reduce((sum,o)=>sum+o.events,0),report.predictions.length);assert.deepEqual(result.outcomes.map(o=>o.events),result.class_counts);const support=analyze(fixture([...Array(9).fill(-.03),...Array(10).fill(-.01)]),options);assert.deepEqual(support.outcomes.map(o=>o.events),[9,10,0]);assert.deepEqual(support.outcomes.map(o=>o.low_support),[true,false,true]);assert.deepEqual(support.outcomes.map(o=>o.observed_rate),[9/19,10/19,0]);const legacy=fixture([.01]);delete legacy.predictions[0].baseline_probabilities;assert.equal(analyze(legacy,options).available,false);assert.equal(analyze(legacy,options).outcomes,undefined,'Unavailable legacy diagnostics must not fabricate outcome summaries');for(const mutate of[ r=>r.predictions[0].actual_log_return=NaN, r=>r.predictions[0].probabilities=[.2,.3,.6], r=>r.predictions[0].probabilities=[-.1,.5,.6], r=>r.predictions[1].target_index=1, r=>r.predictions[0].baseline_probabilities.empirical_calibrated=[Infinity,0,0]]){const invalid=fixture([-.03,.01]);mutate(invalid);assert.throws(()=>analyze(invalid,options));}assert.throws(()=>analyze({predictions:[]},options));console.log('Outcome reliability tests passed: boundaries, exact counts, same-row means, support threshold, unavailable legacy and invalid rows');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=20261027audit2$/);loaded.push(name);}}};vm.runInNewContext(fs.readFileSync(require.resolve('./worker.js'),'utf8'),context);assert.equal(loaded.length,3);for(const protocol of ['strict','classic']){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)\.js\?v=20261027audit2|validation\.js\?v=20261029forecast1)$/);loaded.push(name);}}};vm.runInNewContext(fs.readFileSync(require.resolve('./worker.js'),'utf8'),context);assert.equal(loaded.length,3);for(const protocol of ['strict','classic']){
18 unmodified lines192021222324252627282918 unmodified linesfunction summary(start,end){const slice=values.slice(start,end);return{end_target_index:rows[end-1].target_index,observations:slice.length,log_loss:average(slice.map(v=>v.loss)),raw_log_loss:average(slice.map(v=>v.raw)),brier:average(slice.map(v=>v.brier)),raw_brier:average(slice.map(v=>v.rawBrier)),downside_count:slice.filter(v=>v.c===0).length,mean_entropy:average(slice.map(v=>v.entropy))};}const rolling=[];if(n<100)rolling.push(summary(0,n));else{for(let end=100;end<=n;end+=20)rolling.push(summary(end-100,end));if(rolling.at(-1).end_target_index!==rows[n-1].target_index)rolling.push(summary(n-100,n));}const class_counts=[0,0,0];values.forEach(v=>class_counts[v.c]++);const warnings=['Paired log-loss differences within 1e-12 are treated as numerical equality; probability matches use absolute tolerance 1e-12.','Intervals condition on fixed out-of-sample predictions; refitting and model-selection uncertainty are omitted.','Moving-block intervals assume sufficient local stationarity; regime shifts and block boundaries can limit interpretation.','Repeated research and multiple comparisons are not adjusted for.'];if(lengths.includes(n))warnings.push('A block length spans the entire evaluation sample; its uncertainty interval is unavailable because resampling cannot estimate uncertainty.');for(const [i,fold]of(report.folds||[]).entries())for(const [field,label]of[['temperature_class_counts','temperature'],['selection_class_counts','selection'],['test_class_counts','test']]){const counts=fold[field];if(counts===null||counts===undefined)continue;if(!Array.isArray(counts)||counts.length!==3||!counts.every(c=>Number.isSafeInteger(c)&&c>=0))throw Error('Fold class counts must contain three nonnegative integers.');for(let c=0;c<3;c++)if(counts[c]<10)warnings.push(`Fold ${i+1} ${label}: ${['downside','middle','positive'][c]} has ${counts[c]} ${counts[c]===1?'event':'events'}, below the heuristic minimum support of 10; this is not a statistical guarantee.`);}if(n<200)warnings.push('Fewer than 200 observations: disjoint early/recent movement summaries are unavailable.');return{available:true,observations:n,class_counts,comparisons:{empirical_raw:compare('raw'),empirical_calibrated:compare('cal')},rolling,movement:n>=200?{window:100,early:summary(0,100),recent:summary(n-100,n)}:null,warnings,interpretation:'Negative paired loss differences favor the selected policy. Intervals are descriptive; crossing zero leaves advantage unresolved and does not establish equality. These diagnostics do not establish market edge or trigger trading or retraining.'};}const api={analyze};if(typeof module!=='undefined'&&module.exports)module.exports=api;root.QuantValidation=api;})(typeof globalThis!=='undefined'?globalThis:this);18 unmodified lines19202122232425262728293018 unmodified linesfunction summary(start,end){const slice=values.slice(start,end);return{end_target_index:rows[end-1].target_index,observations:slice.length,log_loss:average(slice.map(v=>v.loss)),raw_log_loss:average(slice.map(v=>v.raw)),brier:average(slice.map(v=>v.brier)),raw_brier:average(slice.map(v=>v.rawBrier)),downside_count:slice.filter(v=>v.c===0).length,mean_entropy:average(slice.map(v=>v.entropy))};}const rolling=[];if(n<100)rolling.push(summary(0,n));else{for(let end=100;end<=n;end+=20)rolling.push(summary(end-100,end));if(rolling.at(-1).end_target_index!==rows[n-1].target_index)rolling.push(summary(n-100,n));}const class_counts=[0,0,0];values.forEach(v=>class_counts[v.c]++);const outcomes=['Big fall','Small fall or no change','Rise'].map((label,class_index)=>({class_index,label,events:class_counts[class_index],observations:n,mean_predicted:average(rows.map(r=>r.probabilities[class_index])),observed_rate:class_counts[class_index]/n,low_support:class_counts[class_index]<10}));const warnings=['Paired log-loss differences within 1e-12 are treated as numerical equality; probability matches use absolute tolerance 1e-12.','Intervals condition on fixed out-of-sample predictions; refitting and model-selection uncertainty are omitted.','Moving-block intervals assume sufficient local stationarity; regime shifts and block boundaries can limit interpretation.','Repeated research and multiple comparisons are not adjusted for.'];if(lengths.includes(n))warnings.push('A block length spans the entire evaluation sample; its uncertainty interval is unavailable because resampling cannot estimate uncertainty.');for(const [i,fold]of(report.folds||[]).entries())for(const [field,label]of[['temperature_class_counts','temperature'],['selection_class_counts','selection'],['test_class_counts','test']]){const counts=fold[field];if(counts===null||counts===undefined)continue;if(!Array.isArray(counts)||counts.length!==3||!counts.every(c=>Number.isSafeInteger(c)&&c>=0))throw Error('Fold class counts must contain three nonnegative integers.');for(let c=0;c<3;c++)if(counts[c]<10)warnings.push(`Fold ${i+1} ${label}: ${['downside','middle','positive'][c]} has ${counts[c]} ${counts[c]===1?'event':'events'}, below the heuristic minimum support of 10; this is not a statistical guarantee.`);}if(n<200)warnings.push('Fewer than 200 observations: disjoint early/recent movement summaries are unavailable.');return{available:true,observations:n,class_counts,outcomes,comparisons:{empirical_raw:compare('raw'),empirical_calibrated:compare('cal')},rolling,movement:n>=200?{window:100,early:summary(0,100),recent:summary(n-100,n)}:null,warnings,interpretation:'Negative paired loss differences favor the selected policy. Intervals are descriptive; crossing zero leaves advantage unresolved and does not establish equality. These diagnostics do not establish market edge or trigger trading or retraining.'};}const api={analyze};if(typeof module!=='undefined'&&module.exports)module.exports=api;root.QuantValidation=api;})(typeof globalThis!=='undefined'?globalThis:this);
12345'use strict';importScripts('model.js?v=20261027audit2','labs.js?v=20261027audit2','validation.js?v=20261027audit2');self.onmessage=event=>{try { const closes=event.data.closes; const report=QuantModel.run(closes,{protocol:event.data.protocol||'classic'});report.validation=QuantValidation.analyze(report);self.postMessage({report,diagnostics:QuantLabs.diagnostics(closes)}); }catch(error){self.postMessage({error:error.message});}12345'use strict';importScripts('model.js?v=20261027audit2','labs.js?v=20261027audit2','validation.js?v=20261029forecast1');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+8
FORECAST-STUDY.mdAdded+45
FORECAST-VERIFICATION.mdAdded+58
INVESTMENT-VERIFICATION.md+1-1
README.md+26
app.js+32-11
forecast-study.zipAdded+3
forward.js+1-1
index.html+8-7
market.jsAdded+29
style.css+4
test_app_state.cjs+13-2
test_forward.cjs+5
test_market.cjsAdded+16
test_outcome_reliability.cjsAdded+32
test_worker.cjs+1-1
validation.js+2-1
worker.js+1-1