Clarify cost comparisons and show the cost-covering price change
Browse filesFiles changed (10)
24 unmodified lines25262724 unmodified lines## Cost storyNumber games gains a separate cost exercise with four primary inputs and optional cost settings. Percent inputs use plain percentage units throughout this exercise; exact basis-point conversion stays in the audit. Results explicitly describe gains/losses rather than an account balance. Native forms and disclosures preserve existing navigation and keyboard behavior. At390px the new form uses one column; mobile document width was measured without horizontal overflow.24 unmodified lines25262728293024 unmodified lines## Cost storyNumber games gains a separate cost exercise with four primary inputs and optional cost settings. Percent inputs use plain percentage units throughout this exercise; exact basis-point conversion stays in the audit. Results explicitly describe gains/losses rather than an account balance. Native forms and disclosures preserve existing navigation and keyboard behavior. At390px the new form uses one column; mobile document width was measured without horizontal overflow.## Cost comparison refinementAdded a plain cost-covering price-change sentence and an intermediate completed-before-costs result. Excess completed counts explain the correction and focus the relevant input. Editing inputs removes the old threshold and error styling so stale results are not mistaken for the new calculation.
101 unmodified lines102103104101 unmodified linesEach completed long trade assumes both buy and sell filled. Uncompleted attempts assume neither leg fills and no exposure/cost. All charges apply to the same initial notional, including sell-side charges; this is an educational convention, not an exchange fee calculation. No reinvestment, financing, inventory path, market impact, partial fills or endogenous latency/fill prediction is modeled. Delay is a chosen adverse price allowance, not elapsed time. It must not double-count effects already included in slippage. Inputs are bounded (notional <=1e9, <=10000 planned trades, move −100%..100%, each charge 0..100%). Extreme combinations can imply losses exceeding the starting amount; no account solvency model is implied.HftBacktest and NautilusTrader were assessed as separate local execution-research options; KalshiMarketMaker was assessed as an operational/quotation reference. None is installed or executed by this Space, and no upstream source was copied for this arithmetic. None of these calculations measures forecasting accuracy or establishes trading profitability.101 unmodified lines102103104105106107101 unmodified linesEach completed long trade assumes both buy and sell filled. Uncompleted attempts assume neither leg fills and no exposure/cost. All charges apply to the same initial notional, including sell-side charges; this is an educational convention, not an exchange fee calculation. No reinvestment, financing, inventory path, market impact, partial fills or endogenous latency/fill prediction is modeled. Delay is a chosen adverse price allowance, not elapsed time. It must not double-count effects already included in slippage. Inputs are bounded (notional <=1e9, <=10000 planned trades, move −100%..100%, each charge 0..100%). Extreme combinations can imply losses exceeding the starting amount; no account solvency model is implied.HftBacktest and NautilusTrader were assessed as separate local execution-research options; KalshiMarketMaker was assessed as an operational/quotation reference. None is installed or executed by this Space, and no upstream source was copied for this arithmetic. None of these calculations measures forecasting accuracy or establishes trading profitability.## Cost-covering price changeThe cost exercise now reports breakEvenMovePercent=(spreadBps+2*feeBps+2*slippageBps+delayBps)/100 for at least one completed trade. Substitution into the fixed-notional gain/loss equation gives zero net (up to floating-point precision). With no completed trades it reports null and no comparison. This is the completed-trade threshold under chosen assumptions, not a forecast or a threshold for recovering a hypothetical missed opportunity. It is independent of notional and completed count when that count is positive. Values above100% exceed the exercise’s allowed move range and are labeled. Exact values remain in the audit; the display rounds to at most six decimals with a nonzero tiny-value label.
64 unmodified lines65666764 unmodified lines## Trading-cost learning exerciseUnder **Number games**, “Would trading costs change the result?” compares hypothetical gains/losses before costs with a fixed-notional example after assumed missed trades, spread, two-sided fees/slippage and an adverse-delay charge. All inputs are chosen by the user. It does not use forecast probabilities or simulate order-book fills. No third-party execution engine or account connection was added.64 unmodified lines656667686964 unmodified lines## Trading-cost learning exerciseUnder **Number games**, “Would trading costs change the result?” compares hypothetical gains/losses before costs with a fixed-notional example after assumed missed trades, spread, two-sided fees/slippage and an adverse-delay charge. All inputs are chosen by the user. It does not use forecast probabilities or simulate order-book fills. No third-party execution engine or account connection was added.The cost exercise also shows the price change needed for each finished trade to cover the entered costs. The default is0.27%; this is a hypothetical cost threshold, not an expected return.
60 unmodified lines61626360 unmodified lines## Trading-cost exercise — 27 October 2026Added pure QuantExecution.costs with test-first arithmetic and browser/CommonJS export. Integration test first failed on missing submit handler. All fourteen static test files passed after integration. Core covers exact 100-to-58.4 fixture, signed missed losses, zero fills, zero friction, input bounds, accounting identity, copied inputs and browser export. App integration covers percent-to-bps conversion, invalid completed count, recovery and audit replacement. Independent read-only review found no concrete integration defect. Browser verified the default result, invalid completed count, signed missed-loss explanation and phone layout at measured width390/scrollWidth390. Existing forecast model and worker files are untouched. These are software checks, not economic backtest evidence. Graphify did not run; familiar code was inspected directly.60 unmodified lines61626364656660 unmodified lines## Trading-cost exercise — 27 October 2026Added pure QuantExecution.costs with test-first arithmetic and browser/CommonJS export. Integration test first failed on missing submit handler. All fourteen static test files passed after integration. Core covers exact 100-to-58.4 fixture, signed missed losses, zero fills, zero friction, input bounds, accounting identity, copied inputs and browser export. App integration covers percent-to-bps conversion, invalid completed count, recovery and audit replacement. Independent read-only review found no concrete integration defect. Browser verified the default result, invalid completed count, signed missed-loss explanation and phone layout at measured width390/scrollWidth390. Existing forecast model and worker files are untouched. These are software checks, not economic backtest evidence. Graphify did not run; familiar code was inspected directly.## Cost comparison refinement — 27 October 2026All fourteen static test files passed. New test-first checks verify the0.27% default threshold, zero net when substituted into the arithmetic, zero-friction0%, and no-completion null. Integration checks threshold display, removal on error and focus on excess completed count. Independent review ran extra zero/tiny/extreme probes and found no concrete defect. Local browser verified normal threshold, focused count error and zero-completion message. Local preview initially failed to attach; retry succeeded. No model/worker calculation changed. Graphify did not run; source was inspected directly.
162 unmodified lines163164165166167168169170171172173174175176177162 unmodified linesfunction updateCosts(){const output=$('cost-output');try{const value=name=>{const raw=$('cost-'+name).value;if(!raw.trim())throw Error('Fill in every amount, count and percentage, then try again.');return Number(raw);};const result=QuantExecution.costs({notional:value('notional'),attempts:value('attempts'),completed:value('completed'),movePercent:value('movePercent'),spreadBps:100*value('spreadPercent'),feeBps:100*value('feePercent'),slippageBps:100*value('slippagePercent'),delayBps:100*value('delayPercent')});const number=x=>new Intl.NumberFormat('en-US',{minimumFractionDigits:2,maximumFractionDigits:2}).format(x);const missed=result.missedEffect<0?`Skipping losing trades helped by ${number(-result.missedEffect)} units.`:`Trades that never filled left out ${number(result.missedEffect)} units of the imagined result.`;output.classList.remove('lab-error');output.textContent=`Gain or loss before costs, if all trades finished: ${number(result.ideal)} units.\nGain or loss after missed trades and costs: ${number(result.net)} units.\n\n${result.completed} of ${result.attempts} trades finished. ${missed}\n\nCosts on finished trades\nWaiting: ${number(result.delayCost)}\nBuy–sell gap: ${number(result.spreadCost)}\nFees for buying and selling: ${number(result.feeCost)}\nExtra price cost: ${number(result.slippageCost)}\nTotal costs: ${number(result.totalCosts)} units.\n\nThese are the results of your pretend story, not a forecast.`;$('cost-audit').textContent=JSON.stringify(result,null,2);}catch(error){output.classList.add('lab-error');output.textContent=error.message;$('cost-audit').textContent='No valid cost exercise. Correct the inputs and try again.';}}$('cost-form').addEventListener('submit',event=>{event.preventDefault();updateCosts();});$('cost-form').addEventListener('invalid',event=>{for(let parent=event.target.parentElement;parent;parent=parent.parentElement)if(parent.tagName==='DETAILS')parent.open=true;},true);$('cost-form').addEventListener('input',()=>{$('cost-output').textContent='Numbers changed. Press See what is left to update the story.';$('cost-audit').textContent='Inputs changed; calculate again for current details.';});updateCosts();162 unmodified lines163164165166167168169170171172173174175176177178179180181162 unmodified linesfunction updateCosts(){const output=$('cost-output');try{const value=name=>{const raw=$('cost-'+name).value;if(!raw.trim()){$('cost-'+name).focus();throw Error('Fill in every amount, count and percentage, then try again.');}return Number(raw);};if(value('completed')>value('attempts')){$('cost-completed').focus();throw Error('Finished trades cannot be more than planned trades. Reduce the finished count or increase the plan.');}const result=QuantExecution.costs({notional:value('notional'),attempts:value('attempts'),completed:value('completed'),movePercent:value('movePercent'),spreadBps:100*value('spreadPercent'),feeBps:100*value('feePercent'),slippageBps:100*value('slippagePercent'),delayBps:100*value('delayPercent')});const number=x=>new Intl.NumberFormat('en-US',{minimumFractionDigits:2,maximumFractionDigits:2}).format(x);const missed=result.missedEffect<0?`Skipping losing trades helped by ${number(-result.missedEffect)} units.`:`Trades that never filled left out ${number(result.missedEffect)} units of the imagined result.`;output.classList.remove('lab-error');output.textContent=`Gain or loss before costs, if all trades finished: ${number(result.ideal)} units.\nAfter missed trades, before costs: ${number(result.filledGross)} units.\nGain or loss after missed trades and costs: ${number(result.net)} units.\n\n${result.completed} of ${result.attempts} trades finished. ${missed}\n\nCosts on finished trades\nWaiting: ${number(result.delayCost)}\nBuy–sell gap: ${number(result.spreadCost)}\nFees for buying and selling: ${number(result.feeCost)}\nExtra price cost: ${number(result.slippageCost)}\nTotal costs: ${number(result.totalCosts)} units.\n\nThese are the results of your pretend story, not a forecast.`;const threshold=result.breakEvenMovePercent;const display=threshold!==null&&threshold>0&&threshold<.000001?'less than 0.000001':new Intl.NumberFormat('en-US',{maximumFractionDigits:6}).format(threshold??0);$('cost-threshold').textContent=threshold===null?'No trades finished, so there is no cost-covering price change to compare.':`Each finished trade needs a price change of about ${display}% to cover these costs. This is a cost threshold, not a prediction.${threshold>100?' That is beyond the price-change range allowed in this exercise.':''}`;$('cost-audit').textContent=JSON.stringify(result,null,2);}catch(error){$('cost-threshold').textContent='';output.classList.add('lab-error');output.textContent=error.message;$('cost-audit').textContent='No valid cost exercise. Correct the inputs and try again.';}}$('cost-form').addEventListener('submit',event=>{event.preventDefault();updateCosts();});$('cost-form').addEventListener('invalid',event=>{for(let parent=event.target.parentElement;parent;parent=parent.parentElement)if(parent.tagName==='DETAILS')parent.open=true;},true);$('cost-form').addEventListener('input',()=>{$('cost-threshold').textContent='';$('cost-output').classList.remove('lab-error');$('cost-output').textContent='Numbers changed. Press See what is left to update the story.';$('cost-audit').textContent='Inputs changed; calculate again for current details.';});updateCosts();
12 unmodified lines1314151617181912 unmodified linesfor(const name of ['spreadBps','feeBps','slippageBps','delayBps'])if(values[name]<0||values[name]>10000)throw Error(`${name} must be between zero and 10,000 basis points.`);const ideal=notional*attempts*movePercent/100,filledGross=notional*completed*movePercent/100,missedEffect=ideal-filledGross,batch=notional*completed;const delayCost=batch*delayBps/10000,spreadCost=batch*spreadBps/10000,feeCost=2*batch*feeBps/10000,slippageCost=2*batch*slippageBps/10000,totalCosts=delayCost+spreadCost+feeCost+slippageCost,net=filledGross-totalCosts;return{schema_version:1,inputs:values,assumptions:['Independent same-notional long round trips; every completed trade has both entry and exit filled.','Uncompleted attempts have no fills, costs or exposure. Missing a losing trade can improve the result.','Every completed trade has the same assumed percentage move. All charges use the fixed entered notional.',12 unmodified lines131415161718192012 unmodified linesfor(const name of ['spreadBps','feeBps','slippageBps','delayBps'])if(values[name]<0||values[name]>10000)throw Error(`${name} must be between zero and 10,000 basis points.`);const ideal=notional*attempts*movePercent/100,filledGross=notional*completed*movePercent/100,missedEffect=ideal-filledGross,batch=notional*completed;const delayCost=batch*delayBps/10000,spreadCost=batch*spreadBps/10000,feeCost=2*batch*feeBps/10000,slippageCost=2*batch*slippageBps/10000,totalCosts=delayCost+spreadCost+feeCost+slippageCost,net=filledGross-totalCosts;const breakEvenMovePercent=completed>0?(spreadBps+2*feeBps+2*slippageBps+delayBps)/100:null;return{schema_version:1,breakEvenMovePercent,inputs:values,assumptions:['Independent same-notional long round trips; every completed trade has both entry and exit filled.','Uncompleted attempts have no fills, costs or exposure. Missing a losing trade can improve the result.','Every completed trade has the same assumed percentage move. All charges use the fixed entered notional.',
3 unmodified lines456789101152 unmodified lines646566676869703 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f5f5f7"><meta name="description" content="Explore price possibilities with simple examples and clear checks. Runs in your browser."><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261027costs1"><script src="labs.js?v=20261027support1" defer></script><script src="cache.js?v=20261027support1" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="forward.js?v=20261027costs1" defer></script><script src="execution.js?v=20261027costs1" defer></script><script src="app.js?v=20261027costs1" defer></script></head><body><a class="skip" href="#results">Skip to results</a>52 unmodified lines<p>Imagine buying, then selling. A price rise can leave you with less than you expected once costs are paid. Try it with pretend money.</p><p class="hint">This is a separate math story. It does not use your forecasts or price file. You choose how many trades finish; the app does not predict fills. Results show gains or losses, not your account balance.</p><form id="cost-form"><div class="input-grid"><label for="cost-notional">Amount for each pretend trade<input id="cost-notional" name="notional" autocomplete="off" type="number" value="1000" min="0.01" max="1000000000.0" step="any" required></label><label for="cost-attempts">Trades you planned<input id="cost-attempts" name="attempts" autocomplete="off" type="number" value="10" min="1" max="10000" step="1" required></label><label for="cost-completed">Trades that finished both steps<input id="cost-completed" name="completed" autocomplete="off" type="number" value="8" min="0" max="10000" step="1" required></label><label for="cost-movePercent">Price change assumed for every trade · %<input id="cost-movePercent" name="movePercent" autocomplete="off" type="number" value="1" min="-100" max="100" step="any" required></label></div><details><summary>Change the costs</summary><p class="hint">All amounts use the same pretend units. The price gap is charged once per finished trade. Fees and extra price costs are charged twice: once to buy and once to sell. Waiting only makes the price worse in this story. Keep its cost separate from the extra price cost so you do not count the same effect twice. For every percentage here, 0.10 means 0.10%.</p><div class="input-grid"><label for="cost-spreadPercent">Buy–sell price gap · % per full trade<input id="cost-spreadPercent" name="spreadPercent" autocomplete="off" type="number" value="0.1" min="0" max="100" step="any" required></label><label for="cost-feePercent">Fee · % each time you buy or sell<input id="cost-feePercent" name="feePercent" autocomplete="off" type="number" value="0.05" min="0" max="100" step="any" required></label><label for="cost-slippagePercent">Extra price cost · % each time you buy or sell<input id="cost-slippagePercent" name="slippagePercent" autocomplete="off" type="number" value="0.02" min="0" max="100" step="any" required></label><label for="cost-delayPercent">Price lost while waiting · % per full trade<input id="cost-delayPercent" name="delayPercent" autocomplete="off" type="number" value="0.03" min="0" max="100" step="any" required></label></div></details><button class="secondary">See what is left</button></form><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.</p><p>The target is the next observed close’s log return. Downside is below −0.02 log return, approximately −1.98% simple return; the middle event includes both boundaries, and the final event is a positive return. Probabilities sum to one.</p><h3>EWMA challenger</h3><p>The ridge mean stays frozen within each fold. Residual variance updates online with a fixed 20-observation half-life, using only outcomes already known before each forecast. Its own target never updates its own variance. The audit records volatility and timing; annualization assumes 252 equal-length observations and is only illustrative for gapped CSVs.</p><h3>Two distinct execution modes</h3><p><b>Browser experiment:</b> empirical frequencies, ridge with Gaussian residual probabilities, EWMA residual-volatility probabilities, and multinomial logistic regression are fitted to the selected data. Synthetic JavaScript draws differ from Python even with the same seed.</p><p><b>Precomputed Python benchmark:</b> a saved 900-observation synthetic run actually fitted scikit-learn, XGBoost and LightGBM, completed three training-only Optuna trials, computed SHAP and recorded MLflow metrics. Loading it does not execute those libraries. Download the full Python/Gradio project to run them locally.</p><h3>When the learning examples may not be enough</h3><p>A note appears when an outcome has fewer than 10 training examples, or when recent price patterns are unusual compared with training. These are simple checks, not a guarantee of reliability. The absence of a note does not prove a guess is safe or accurate.</p><p><a href="MODEL-STUDY.md">Latest model tests and rejected changes</a></p><h3>Implementation limits</h3><p>Classic calibration reuses data for temperatures and model choice. Strict mode separates these stages but cannot prevent repeated human inspection. Financial tails and nonstationarity can invalidate normal residual assumptions. Tiny test samples and sparse reliability bins are especially unreliable. The validation panel shows matched untuned and calibrated empirical baselines, fold populations, support warnings and descriptive paired uncertainty. It shows rolling loss, Brier score, entropy and event counts; it does not implement feature-drift testing or an automatic fallback strategy. The saved Python benchmark predates this panel and does not have row-matched baseline probabilities, so its new comparisons remain unavailable. SHAP explains uncalibrated raw class margins, not causal effects. Close-based information does not imply executable same-close fills. 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>3 unmodified lines456789101152 unmodified lines646566676869703 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f5f5f7"><meta name="description" content="Explore price possibilities with simple examples and clear checks. Runs in your browser."><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; worker-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'"><title>QuantLab · probability research</title><link rel="stylesheet" href="style.css?v=20261027costs2"><script src="labs.js?v=20261027support1" defer></script><script src="cache.js?v=20261027support1" defer></script><script src="scenarios.js" defer></script><script src="provenance.js?v=20261026provenance1" defer></script><script src="forward.js?v=20261027costs2" defer></script><script src="execution.js?v=20261027costs2" defer></script><script src="app.js?v=20261027costs2" defer></script></head><body><a class="skip" href="#results">Skip to results</a>52 unmodified lines<p>Imagine buying, then selling. A price rise can leave you with less than you expected once costs are paid. Try it with pretend money.</p><p class="hint">This is a separate math story. It does not use your forecasts or price file. You choose how many trades finish; the app does not predict fills. Results show gains or losses, not your account balance.</p><form id="cost-form"><div class="input-grid"><label for="cost-notional">Amount for each pretend trade<input id="cost-notional" name="notional" autocomplete="off" type="number" value="1000" min="0.01" max="1000000000.0" step="any" required></label><label for="cost-attempts">Trades you planned<input id="cost-attempts" name="attempts" autocomplete="off" type="number" value="10" min="1" max="10000" step="1" required></label><label for="cost-completed">Trades that finished both steps<input id="cost-completed" name="completed" autocomplete="off" type="number" value="8" min="0" max="10000" step="1" required></label><label for="cost-movePercent">Price change assumed for every trade · %<input id="cost-movePercent" name="movePercent" autocomplete="off" type="number" value="1" min="-100" max="100" step="any" required></label></div><details><summary>Change the costs</summary><p class="hint">All amounts use the same pretend units. The price gap is charged once per finished trade. Fees and extra price costs are charged twice: once to buy and once to sell. Waiting only makes the price worse in this story. Keep its cost separate from the extra price cost so you do not count the same effect twice. For every percentage here, 0.10 means 0.10%.</p><div class="input-grid"><label for="cost-spreadPercent">Buy–sell price gap · % per full trade<input id="cost-spreadPercent" name="spreadPercent" autocomplete="off" type="number" value="0.1" min="0" max="100" step="any" required></label><label for="cost-feePercent">Fee · % each time you buy or sell<input id="cost-feePercent" name="feePercent" autocomplete="off" type="number" value="0.05" min="0" max="100" step="any" required></label><label for="cost-slippagePercent">Extra price cost · % each time you buy or sell<input id="cost-slippagePercent" name="slippagePercent" autocomplete="off" type="number" value="0.02" min="0" max="100" step="any" required></label><label for="cost-delayPercent">Price lost while waiting · % per full trade<input id="cost-delayPercent" name="delayPercent" autocomplete="off" type="number" value="0.03" min="0" max="100" step="any" required></label></div></details><button class="secondary">See what is left</button></form><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.</p><p>The target is the next observed close’s log return. Downside is below −0.02 log return, approximately −1.98% simple return; the middle event includes both boundaries, and the final event is a positive return. Probabilities sum to one.</p><h3>EWMA challenger</h3><p>The ridge mean stays frozen within each fold. Residual variance updates online with a fixed 20-observation half-life, using only outcomes already known before each forecast. Its own target never updates its own variance. The audit records volatility and timing; annualization assumes 252 equal-length observations and is only illustrative for gapped CSVs.</p><h3>Two distinct execution modes</h3><p><b>Browser experiment:</b> empirical frequencies, ridge with Gaussian residual probabilities, EWMA residual-volatility probabilities, and multinomial logistic regression are fitted to the selected data. Synthetic JavaScript draws differ from Python even with the same seed.</p><p><b>Precomputed Python benchmark:</b> a saved 900-observation synthetic run actually fitted scikit-learn, XGBoost and LightGBM, completed three training-only Optuna trials, computed SHAP and recorded MLflow metrics. Loading it does not execute those libraries. Download the full Python/Gradio project to run them locally.</p><h3>When the learning examples may not be enough</h3><p>A note appears when an outcome has fewer than 10 training examples, or when recent price patterns are unusual compared with training. These are simple checks, not a guarantee of reliability. The absence of a note does not prove a guess is safe or accurate.</p><p><a href="MODEL-STUDY.md">Latest model tests and rejected changes</a></p><h3>Implementation limits</h3><p>Classic calibration reuses data for temperatures and model choice. Strict mode separates these stages but cannot prevent repeated human inspection. Financial tails and nonstationarity can invalidate normal residual assumptions. Tiny test samples and sparse reliability bins are especially unreliable. The validation panel shows matched untuned and calibrated empirical baselines, fold populations, support warnings and descriptive paired uncertainty. It shows rolling loss, Brier score, entropy and event counts; it does not implement feature-drift testing or an automatic fallback strategy. The saved Python benchmark predates this panel and does not have row-matched baseline probabilities, so its new comparisons remain unavailable. SHAP explains uncalibrated raw class margins, not causal effects. Close-based information does not imply executable same-close fills. 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>
30 unmodified lines31323330 unmodified lines.cost-lab{margin-top:24px}.cost-lab>p{max-width:70ch}.cost-lab form{max-width:720px}.cost-lab input{min-width:0}.cost-lab form>button{margin-top:20px}.cost-lab pre{max-height:400px;overflow:auto}.cost-lab .calculation-result{max-width:720px}@media(max-width:420px){.cost-lab .input-grid{grid-template-columns:1fr}}30 unmodified lines313233343530 unmodified lines.cost-lab{margin-top:24px}.cost-lab>p{max-width:70ch}.cost-lab form{max-width:720px}.cost-lab input{min-width:0}.cost-lab form>button{margin-top:20px}.cost-lab pre{max-height:400px;overflow:auto}.cost-lab .calculation-result{max-width:720px}@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}
21 unmodified lines222324252627282921 unmodified lines(async()=>{for(const [key,value]of Object.entries({notional:1000,attempts:10,completed:8,movePercent:1,spreadPercent:.1,feePercent:.05,slippagePercent:.02,delayPercent:.03}))node('cost-'+key).value=String(value);node('cost-form').listeners.submit({preventDefault(){}});assert.match(node('cost-output').textContent,/58.40/);assert.match(node('cost-audit').textContent,/58.4/);node('cost-completed').value='11';node('cost-form').listeners.submit({preventDefault(){}});assert.match(node('cost-output').textContent,/completed/i);assert.equal(node('cost-audit').textContent,'No valid cost exercise. Correct the inputs and try again.');node('cost-completed').value='8';node('cost-form').listeners.submit({preventDefault(){}});assert.match(node('cost-output').textContent,/58.40/);assert.equal(vm.runInContext('percent(1e-9)',sandbox),'<0.01%');assert.equal(vm.runInContext('percent(1-1e-9)',sandbox),'>99.99%');assert.equal(vm.runInContext('percent(0)',sandbox),'0.00%');assert.equal(vm.runInContext('percent(1)',sandbox),'100.00%');vm.runInContext('drawProbabilities([1e-9,.5,.5-1e-9])',sandbox);assert(node('probability-chart').innerHTML.includes('<0.01%'),'Tiny nonzero probabilities must stay readable in valid SVG text');21 unmodified lines222324252627282921 unmodified lines(async()=>{for(const [key,value]of Object.entries({notional:1000,attempts:10,completed:8,movePercent:1,spreadPercent:.1,feePercent:.05,slippagePercent:.02,delayPercent:.03}))node('cost-'+key).value=String(value);node('cost-form').listeners.submit({preventDefault(){}});assert.match(node('cost-output').textContent,/58.40/);assert.match(node('cost-audit').textContent,/58.4/);assert.match(node('cost-threshold').textContent,/0.27%/);node('cost-completed').value='11';node('cost-form').listeners.submit({preventDefault(){}});assert.match(node('cost-output').textContent,/finished|completed/i);assert.equal(node('cost-completed').focused,true);assert.equal(node('cost-threshold').textContent,'');assert.equal(node('cost-audit').textContent,'No valid cost exercise. Correct the inputs and try again.');node('cost-completed').value='8';node('cost-form').listeners.submit({preventDefault(){}});assert.match(node('cost-output').textContent,/58.40/);assert.equal(vm.runInContext('percent(1e-9)',sandbox),'<0.01%');assert.equal(vm.runInContext('percent(1-1e-9)',sandbox),'>99.99%');assert.equal(vm.runInContext('percent(0)',sandbox),'0.00%');assert.equal(vm.runInContext('percent(1)',sandbox),'100.00%');vm.runInContext('drawProbabilities([1e-9,.5,.5-1e-9])',sandbox);assert(node('probability-chart').innerHTML.includes('<0.01%'),'Tiny nonzero probabilities must stay readable in valid SVG text');
5 unmodified lines678910115 unmodified linesconst near=(a,b)=>assert(Math.abs(a-b)<1e-9,`${a} differs from ${b}`);assert.equal(r.schema_version,1);assert.deepEqual(r.inputs,input);assert.equal(r.ideal,100);assert.equal(r.filledGross,80);assert.equal(r.missedEffect,20);assert.equal(r.delayCost,2.4);assert.equal(r.spreadCost,8);assert.equal(r.feeCost,8);assert.equal(r.slippageCost,3.2);near(r.totalCosts,21.6);near(r.net,58.4);assert.equal(r.completed,8);assert.equal(r.attempts,10);assert.equal(JSON.stringify(input),original);near(r.ideal,r.net+r.totalCosts+r.missedEffect);const loss=E.costs({...input,movePercent:-1});assert.equal(loss.missedEffect,-20);near(loss.net,-101.6);const none=E.costs({...input,completed:0});for(const key of ['filledGross','delayCost','spreadCost','feeCost','slippageCost','totalCosts','net'])assert.equal(none[key],0);assert.equal(none.missedEffect,none.ideal);const free=E.costs({...input,spreadBps:0,feeBps:0,slippageBps:0,delayBps:0});assert.equal(free.totalCosts,0);assert.equal(free.net,free.filledGross);5 unmodified lines67891011121314155 unmodified linesconst near=(a,b)=>assert(Math.abs(a-b)<1e-9,`${a} differs from ${b}`);assert.equal(r.schema_version,1);assert.deepEqual(r.inputs,input);assert.equal(r.ideal,100);assert.equal(r.filledGross,80);assert.equal(r.missedEffect,20);assert.equal(r.delayCost,2.4);assert.equal(r.spreadCost,8);assert.equal(r.feeCost,8);assert.equal(r.slippageCost,3.2);near(r.totalCosts,21.6);near(r.net,58.4);assert.equal(r.completed,8);assert.equal(r.attempts,10);assert.equal(JSON.stringify(input),original);near(r.ideal,r.net+r.totalCosts+r.missedEffect);near(r.breakEvenMovePercent,.27);near(E.costs({...input,movePercent:r.breakEvenMovePercent}).net,0);assert.equal(E.costs({...input,completed:0}).breakEvenMovePercent,null);assert.equal(E.costs({...input,spreadBps:0,feeBps:0,slippageBps:0,delayBps:0}).breakEvenMovePercent,0);const loss=E.costs({...input,movePercent:-1});assert.equal(loss.missedEffect,-20);near(loss.net,-101.6);const none=E.costs({...input,completed:0});for(const key of ['filledGross','delayCost','spreadCost','feeCost','slippageCost','totalCosts','net'])assert.equal(none[key],0);assert.equal(none.missedEffect,none.ideal);const free=E.costs({...input,spreadBps:0,feeBps:0,slippageBps:0,delayBps:0});assert.equal(free.totalCosts,0);assert.equal(free.net,free.filledGross);
DESIGN.md+3
METHODS.md+3
README.md+2
VERIFICATION.md+3
app.js+8-4
execution.js+2-1
index.html+3-3
style.css+2
test_app_state.cjs+2-2
test_execution.cjs+4