Add animated investment charts and ticker ROI explorer
Browse filesAdd historical ROI, drawdown and conditional future return scenarios for eight tickers, with dated adjusted market snapshots, local CSV support, accessible interactive SVG charts and JSON export. Preserve the existing forecast models. Verified with all 16 Node test files and 18 Chrome browser checks.
Files changed (12)
- DESIGN.md+10
- INVESTMENT-VERIFICATION.mdAdded+49
- MARKET-DATA.mdAdded+46
- README.md+48
- index.html+36-1
- investment-ui.jsAdded+191
- investment.cssAdded+8
- investment.jsAdded+155
- market-data.jsonAdded
- scripts/check-investment-browser.cjsAdded+46
- scripts/refresh-market-data.pyAdded+155
- test_investment.cjsAdded+34
27 unmodified lines2829303132333435363738394027 unmodified lines
## 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.
## Investment explorerA separate navigation view preserves the Price explorer and its original models. A whitesettings surface sits beside the investment result on desktop and stacks on mobile.USD value is the primary figure; ROI, gain/loss, drawdown or scenario outcomes follow.Solid blue means mean/value, dashed purple means median, and the pale blue band spansmodeled 10th–90th outcomes. Source dates, conditional assumptions and historical/livedistinction 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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Investment explorer verification
## Changes
Added investment.js, investment-ui.js, investment.css, market-data.json, test_investment.cjs,MARKET-DATA.md and an explicit Python snapshot refresh script; index.html loads the modulesand adds a navigation view. Existing forecasting, validation, caching, next-observationchecking and cost-calculator source files are unchanged. Original downloadable researcharchives 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.
## Evidence
- All existing Node assertion files plus test_investment.cjs pass. Investment assertions were written and observed failing before the calculation module existed.- The first browser regression run reproduced three failures: initial ticker incorrectly defaulted to CSV; typing during the market-data request discarded the eventual catalog; hidden invalid historical dates blocked future-mode form submission. All three were repaired, and the regression checks pass.- Chrome headless real-browser checks: default view; all eight tickers in both modes; invalid hidden dates; analytic manual scenario ($10,000, 10% annual expected growth, 20% volatility, 24 months → $12,100 mean, 21% mean ROI); keyboard chart inspection; layer toggles; empty amount invalidation; JSON export; local CSV and weekend effective dates; malformed CSV; 390px mobile overflow and responsive chart sizing; reduced motion; zero JavaScript page errors; typing during a slow catalog load; preserving an uploaded CSV during catalog loading; stale file-read cancellation on ticker switch; clear during catalog load; local CSV fallback when the market snapshot returns HTTP 503.- Snapshot validation: eight USD series, 1,254 observations each, 2021-10-29–2026-10-28; positive finite adjusted values, increasing unique dates, no missing/dropped provider bars.- Existing fail-closed CSP remains: script-src/connect-src self, form-action none.- Desktop and mobile screenshots inspected. Mobile chart uses a smaller coordinate space to keep axis labels readable; date spacing reflects elapsed calendar time.- Current Vercel Web Interface Guidelines were consulted for the touched controls, focus, reduced motion, responsive layout, labels, contrast and native keyboard interactions.
## Limits
Chrome desktop and an emulated 390px viewport were tested; physical touch hardware,Safari, Firefox and screen-reader behavior were not directly tested. The table and nativerange controls provide non-pointer alternatives. Data is a dated, manually refreshedsnapshot, and Yahoo's unofficial endpoint may change or rate-limit. Historical adjustmentcan be revised by the provider. Scenario ranges do not capture parameter uncertainty,regime change, all tail risks or execution costs. User CSVs may have irregular spacing orunverified adjustments; 252-observation annualization assumes daily data.
Source relationships were inspected directly with rg and bounded source reads; Graphify,SearXNG and Crawl4AI were not run. Known public source URLs were retrieved directly.12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Market data provenance
Generated: 2026-10-29T22:44:55Z. Requested inclusive start: 2021-10-29; exclusive end: 2026-10-29.These are dated historical observations, never live quotes. The current day's session is excluded.
Source: Yahoo Finance public chart endpoint, `indicators.adjclose[0].adjclose`.Each security in `market-data.json` retains its exact request URL and UTC retrieval timestamp.Dates use the America/New_York exchange timezone. Values retain provider precision.[Yahoo's adjustment documentation](https://in.help.yahoo.com/kb/adjusted-close-sln28256.html) describes split and cash-dividend adjustment.Ratios of these adjusted prices approximate dividend-reinvested growth; no separate dividends are added.Provider adjustments and corrections can revise historical values. This is not a full accounting oftaxes, commissions, slippage, dividend reinvestment execution, or inflation. Symbols are a curatedselection of current securities and are not an unbiased historical universe.
| Ticker | First session | Last session | Kept | Missing dropped | Outside range excluded | Provider bars | Retrieved UTC || --- | --- | --- | ---: | ---: | ---: | ---: | --- || AAPL | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:53Z || MSFT | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:54Z || NVDA | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:54Z || AMZN | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:54Z || GOOGL | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:54Z || TSLA | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:54Z || SPY | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:54Z || QQQ | 2021-10-29 | 2026-10-28 | 1254 | 0 | 0 | 1254 | 2026-10-29T22:44:55Z |
Integrity checks: aligned price/date arrays; positive finite adjusted values; strictly increasing,unique dates; USD and requested symbol verified against provider metadata; at least 1,000 barsper security. Null adjusted values are omitted and counted above. Unexpected non-null prices,provider errors, or missing adjusted-price fields fail the entire refresh before replacement.No synthetic prices, forward filling, or substitution with unadjusted closes is performed.
Refresh manually, using Python 3.9+ and its standard library (network required):
```shpython3 scripts/refresh-market-data.py --online --as-of 2026-10-29```
If a macOS Python installation lacks configured CA certificates, use its certificate setup orexplicitly select the system trust store with `SSL_CERT_FILE=/etc/ssl/cert.pem` before the command.Certificate verification remains enabled; the snapshot here was retrieved using that trust store.
The end date is exclusive; choose today's New York date or an earlier date to omit incompletesessions. All eight requests must succeed before the snapshot is replaced atomically. Yahoo canrate-limit or change this unofficial chart endpoint. A failed refresh leaves the previous snapshotintact. The static browser app reads only its bundled same-origin JSON. Personal CSV files stayin the browser and are not sent by this maintenance script.68 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811968 unmodified linesThe 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.
Strict mode now lets unadjusted training counts compete alongside the four existing candidates. A [leakage and overfitting audit](LEAK-AUDIT.md) records the conditional form-submission privacy fix, chronological probes and synthetic-only improvement evidence. [Reproducible evidence](leakage-audit.zip) includes pinned before/current model source.
## Investment explorer
The **Investment explorer** tab adds a searchable catalog of AAPL, MSFT, NVDA, AMZN,GOOGL, TSLA, SPY and QQQ, an initial USD investment, and two calculation modes:
- **A past investment:** choose dates and inspect historical value, total ROI, dollar gain/loss, annualized return and maximum drawdown. Non-trading dates snap inward; effective dates are displayed. Adjusted-price ratios approximate dividend-reinvested growth, with fractional shares and no costs, taxes or inflation.- **A future scenario:** choose 1–120 months and estimate annual return/volatility from 1, 3 or 5 years of daily prices, or enter your own assumptions. The calculator shows mean value/ROI, median value, 10th–90th percentile outcomes and modeled loss probability. These are conditional lognormal scenarios, separate from the next-close forecast models; they are not evidence of a trading edge.
Both modes have animated SVG charts, pointer/touch inspection, a keyboard-operated pointslider, a table alternative and a JSON export. Reduced motion disables animations.Inactive settings are disabled, and changing invalid inputs clears stale results.Other tickers can use a browser-local CSV with `date,adj_close` or `date,close` columns(maximum 2 MiB and 2,500 observations). Input adjustment and currency cannot be independentlyverified from those two columns. Estimation assumes daily observations and needs at least60 returns; it does not reconstruct missing sessions or account for irregular spacing.
Bundled market history is a dated snapshot through **2026-10-28**, not a live quote feed.See [MARKET-DATA.md](MARKET-DATA.md) for source URLs, adjustment details and the optionalexplicit online refresh command. The browser only reads the same-origin JSON asset;no finance endpoint, credentials, analytics service or new runtime package is required.
For a scenario with starting amount A, expected annual simple growth r, annual volatilitys and horizon t years, `mean = A × (1+r)^t` and`median = A × exp((log(1+r) − s²/2)t)`. The 10th/90th outcomes add ±1.2815515655 × s × √tto the median's exponent. Historical estimates use the sample variance of daily logreturns, annualized by 252, and `r = exp(252 × meanLogReturn + annualVariance/2) − 1`.The outcome band excludes parameter-estimation uncertainty and assumes constant,independent normally distributed log returns. Long horizons magnify these assumptions.
Run `node test_investment.cjs` for the numerical/CSV assertions, or the existing full testloop above for regression checks. To preview locally, serve this directory using`python3 -m http.server 8765 --bind 127.0.0.1`, open the resulting localhost URL and choose**Investment explorer**. Hosting remains `sdk: static` with `index.html` as its entry point.
Optional browser regression runner (requires an existing Playwright installation and GoogleChrome): while the local server is running, use`node scripts/check-investment-browser.cjs`. If Playwright is outside this directory, set`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.5 unmodified lines678910111213121415161743 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798995 unmodified lines<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><body><a class="skip" href="#results">Skip to results</a><header class="masthead"><div class="masthead-inner"><a class="wordmark" href="index.html" aria-label="QuantLab home">QuantLab</a><nav aria-label="Research views"><button class="tab active" data-view="workbench" aria-pressed="true">Price explorer</button><button class="tab" data-view="mathematics" aria-pressed="false">Number games</button><button class="tab" data-view="distributions" aria-pressed="false">What if?</button><button class="tab" data-view="methods" aria-pressed="false">Help</button></nav></div></header><header class="masthead"><div class="masthead-inner"><a class="wordmark" href="index.html" aria-label="QuantLab home">QuantLab</a><nav aria-label="Research views"><button class="tab active" data-view="workbench" aria-pressed="true">Price explorer</button><button class="tab" data-view="investment" aria-pressed="false">Investment explorer</button><button class="tab" data-view="mathematics" aria-pressed="false">Number games</button><button class="tab" data-view="distributions" aria-pressed="false">What if?</button><button class="tab" data-view="methods" aria-pressed="false">Help</button></nav></div></header><main><div class="introduction"><h1>Make sense of chance.</h1><p>Explore three possibilities for the next price.</p></div><section id="workbench" class="view">43 unmodified lines<p class="hint">These are uncertain guesses for learning, not instructions to buy or sell. We have not shown that they can make money.</p></div></section><section id="investment" class="view" hidden aria-labelledby="investment-title"> <div class="inv-heading"><div><p class="inv-eyebrow">Investment explorer</p><h2 id="investment-title">Put a number to “what if?”</h2><p>Pick a stock, an amount, and a time. Explore its past or model a possible future.</p></div><span class="inv-badge">Historical snapshots · browser-local calculations</span></div> <div class="inv-layout"> <form id="inv-form" class="inv-controls" aria-label="Investment settings"> <label for="inv-search">Find a stock or ETF</label><input id="inv-search" name="inv-search" autocomplete="off" type="search" placeholder="e.g. AAPL or Apple…" spellcheck="false"> <label for="inv-ticker">Ticker</label><select id="inv-ticker" name="inv-ticker" autocomplete="off"><option value="__loading__">Loading historical prices…</option></select> <div id="inv-csv-controls" hidden><label for="inv-csv-ticker">Your ticker label</label><input id="inv-csv-ticker" name="inv-csv-ticker" autocomplete="off" type="text" value="MY CSV" maxlength="30"><label for="inv-csv">Adjusted daily prices · CSV</label><input id="inv-csv" name="inv-csv" autocomplete="off" type="file" accept=".csv,text/csv"><p class="hint">Columns: date and adj_close (or close). USD, oldest first; up to 2,500 rows and 2 MiB. Use prices consistently adjusted for splits and dividends. Future estimation needs at least 61 daily prices. Your file stays in this browser.</p></div> <label for="inv-amount">Initial investment · USD</label><input id="inv-amount" name="inv-amount" autocomplete="off" type="number" inputmode="decimal" min="0.01" max="1000000000" step="any" value="10000" required> <label for="inv-mode">Explore</label><select id="inv-mode" name="inv-mode" autocomplete="off"><option value="past">A past investment</option><option value="future">A future scenario</option></select> <fieldset id="inv-past-controls"><legend>Holding period</legend><label for="inv-start">Start date</label><input id="inv-start" name="inv-start" autocomplete="off" type="date" required><label for="inv-end">End date</label><input id="inv-end" name="inv-end" autocomplete="off" type="date" required><div class="inv-preset" role="group" aria-label="Historical range presets"><button type="button" data-investment-range="1">1 year</button><button type="button" data-investment-range="3">3 years</button><button type="button" data-investment-range="0">All data</button></div><p class="hint">Non-trading dates move inward to the next available start and previous available end. Effective dates appear with the result.</p></fieldset> <fieldset id="inv-future-controls" hidden><legend>Scenario assumptions</legend><label for="inv-months">How long would you hold?</label><input id="inv-months" name="inv-months" autocomplete="off" type="range" min="1" max="120" step="1" value="12" aria-describedby="inv-duration"><output id="inv-duration" for="inv-months">12 months · 1 year</output><label for="inv-window">Estimate from the last</label><select id="inv-window" name="inv-window" autocomplete="off"><option value="1">1 year of daily prices</option><option value="3" selected>3 years of daily prices</option><option value="5">5 years of daily prices</option></select><label class="inv-check" for="inv-override"><input id="inv-override" name="inv-override" autocomplete="off" type="checkbox">Use my own assumptions</label><div id="inv-overrides" hidden><label for="inv-return">Annual mean return · %</label><input id="inv-return" name="inv-return" autocomplete="off" type="number" min="-95" max="200" step="any" value="8" disabled><label for="inv-vol">Annual volatility · %</label><input id="inv-vol" name="inv-vol" autocomplete="off" type="number" min="0" max="200" step="any" value="20" disabled></div><p class="hint">The past is an estimation input. A constant-return model cannot capture every market outcome.</p></fieldset> <button class="primary" type="submit">Calculate investment</button><button id="inv-reset" class="inv-reset" type="button">Reset investment settings</button> </form> <div class="inv-contents"> <div class="inv-source-panel"><p id="inv-source">Loading dated historical snapshots…</p><a id="inv-source-link" href="MARKET-DATA.md" target="_blank" rel="noopener noreferrer" hidden>Inspect provider data (opens a new tab)</a><p class="inv-data-warning">Historical data, not live quotes. <a href="MARKET-DATA.md">Data sources & adjustment details</a></p></div> <p id="inv-status" role="status" aria-live="polite">Preparing the investment explorer…</p> <div id="inv-results" hidden> <h3 id="inv-result-title">Investment result</h3><p id="inv-result-note"></p> <div id="inv-stats" class="inv-stats" aria-label="Investment results"></div> <div class="inv-chart-heading"><h3 id="inv-chart-title">Investment value</h3><p id="inv-chart-caption"></p></div> <div id="inv-layers" class="inv-layers" role="group" aria-label="Projection chart layers" hidden><label class="inv-mean-label"><input id="inv-show-mean" name="inv-show-mean" autocomplete="off" type="checkbox" checked>Mean · solid blue</label><label class="inv-median-label"><input id="inv-show-median" name="inv-show-median" autocomplete="off" type="checkbox" checked>Median · dashed purple</label><label><input id="inv-show-band" name="inv-show-band" autocomplete="off" type="checkbox" checked>10th–90th band</label></div> <div id="inv-main-chart" class="inv-chart" role="img" aria-labelledby="inv-chart-title" aria-describedby="inv-chart-caption inv-readout"></div> <div class="inv-inspect"><label for="inv-point">Explore chart points · drag, tap, or use arrow keys</label><input id="inv-point" name="inv-point" autocomplete="off" type="range" min="0" max="1" step="1" value="1"><output id="inv-readout" for="inv-point" aria-live="polite"></output></div> <section id="inv-drawdown-panel" aria-labelledby="inv-drawdown-title"><h3 id="inv-drawdown-title">The falls along the way</h3><p>Percentage below the highest investment value reached so far. The point slider also explores this chart.</p><div id="inv-drawdown-chart" class="inv-chart" role="img" aria-labelledby="inv-drawdown-title" aria-describedby="inv-readout"></div></section> <details class="inv-details" open><summary>Assumptions behind this result</summary><p id="inv-assumptions"></p></details> <details><summary>View chart values as a table</summary><div class="table-scroll inv-table-wrap" tabindex="0" role="region" aria-label="Scrollable investment chart values"><table><caption class="sr-only">Exact values represented in the investment charts</caption><thead id="inv-table-head"></thead><tbody id="inv-table-body"></tbody></table></div></details> <button id="inv-export" class="secondary" type="button" disabled>Save investment result · JSON</button> </div> <p class="inv-fine-print">For exploration and learning. Future projections depend on assumptions and do not establish an ability to predict profitable investments. All values use USD and fractional shares.</p> </div> </div></section>
<section id="mathematics" class="view" hidden><h2>Play with numbers.</h2><p>Try a game or explore a pretend deal. These examples are separate from the price guesses and do not show how to make money.</p><div class="lab-grid"><section class="plot"><h3>What happens when two people choose?</h3><label for="game">Choose a game</label><select id="game"><option value="prisoner">Teamwork trap · prisoner’s dilemma</option><option value="matching">Coin guessing · matching pennies</option></select><div id="game-output" class="calculation-result" aria-live="polite"></div></section><section class="plot"><h3>A price deal and a two-outcome bet</h3><p>A pretend option gives you a right to buy or sell later at an agreed price. The bet example has only two answers: win or lose. It is a math example, not a suggestion to bet.</p><form id="risk-form"><div class="input-grid"><label>Price today<input name="spot" type="number" min="1" step="1" value="100" required></label><label>Agreed deal price<input name="strike" type="number" min="1" step="1" value="100" required></label><label>Time left · years<input name="years" type="number" min="0.01" max="10" step="0.01" value="1" required></label><label>Yearly wiggle size · 0.20 means 20%<input name="vol" type="number" min="0.01" max="3" step="0.01" value="0.2" required></label><label>Chance of winning · 0.55 means 55%<input name="probability" type="number" min="0" max="1" step="0.01" value="0.55" required></label><label>Profit per 1 unit bet · if you win<input name="odds" type="number" min="0.1" max="10" step="0.1" value="1" required></label></div><button class="secondary">Calculate</button></form><div id="risk-output" class="calculation-result" aria-live="polite"></div><details><summary>Rules behind these examples</summary><p class="hint">Black–Scholes assumes a European option, no dividends, constant volatility and a 3% interest rate. The separate Kelly example uses capped quarter-Kelly for a bet with fixed win and loss payoffs. It is not a stock allocation.</p></details></section></div><section class="plot iv-lab"><h3>What wiggle size fits this deal price?</h3><p>An option is a right to buy or sell later at an agreed price. This calculator finds the yearly wiggle size that fits its price, using the Black–Scholes formula. It is separate from the price explorer.</p><form id="iv-form"><div class="input-grid"><label>Price today<input name="spot" type="number" min="0.01" value="100" step="0.01" required></label><label>Agreed deal price<input name="strike" type="number" min="0.01" value="100" step="0.01" required></label><label>Time left · years<input name="years" type="number" min="0.001" max="10" value="1" step="0.001" required></label><label>Yearly interest rate · 0.03 means 3%<input name="rate" type="number" min="-1" max="1" value="0.03" step="0.01" required></label><label>Option price · same units as price today<input name="premium" type="number" min="0" value="9.4134" step="0.0001" required></label><label>Kind of deal<select name="type"><option value="call">Right to buy · call</option><option value="put">Right to sell · put</option></select></label></div><button class="secondary">Find the wiggle size</button></form><div id="iv-output" class="calculation-result" aria-live="polite"></div><details><summary>How the answer was found</summary><pre id="iv-details"></pre></details></section><section class="plot cost-lab" aria-labelledby="cost-title"><h3 id="cost-title">Would trading costs change the result?</h3><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>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191/* Investment view is independent of the next-close forecast and its uploaded data. */(() => {'use strict';const $ = id => document.getElementById(id), Q = globalThis.QuantInvestment;const money = n => new Intl.NumberFormat('en-US', {style:'currency',currency:'USD',maximumFractionDigits:Math.abs(n)<1?4:2}).format(n);const pct = n => new Intl.NumberFormat('en-US',{style:'percent',maximumFractionDigits:2}).format(n);const probability = n => n>0&&n<.0001?'<0.01%':n<1&&n>.9999?'>99.99%':pct(n);const esc = value => String(value).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));let catalog = [], selected = null, result = null, charts = [], revision = 0, csvSeries = null, explicitCustom = false, cleared = false;const form = $('inv-form');function invalidate(message) { result = null; charts = []; $('inv-results').hidden = true; $('inv-stats').replaceChildren(); $('inv-main-chart').replaceChildren(); $('inv-drawdown-chart').replaceChildren(); $('inv-table-body').replaceChildren(); $('inv-readout').textContent = ''; $('inv-export').disabled = true; $('inv-status').textContent = message; $('inv-status').classList.remove('lab-error');}function fail(error) { invalidate(error.message); $('inv-status').classList.add('lab-error'); }function finiteInput(id, name) { const input = $(id); if (!input.value.trim() || !input.validity.valid || !Number.isFinite(Number(input.value))) throw Error(`Enter a valid ${name}.`); return Number(input.value);}function sourceNote() { if (!selected) return; const dates = selected.dates; $('inv-source').textContent = `${selected.ticker} · ${selected.name} · USD · ${dates.length.toLocaleString()} prices · ${dates[0]} to ${dates.at(-1)}. ${selected.adjustment || 'Adjustment not independently verified.'} ${selected.retrievedAt ? 'Snapshot retrieved '+selected.retrievedAt+'.' : 'Your file stays in this tab.'}`; $('inv-source-link').hidden = !selected.sourceUrl; if (selected.sourceUrl) $('inv-source-link').href = selected.sourceUrl;}function modeControls() { const future = $('inv-mode').value === 'future'; $('inv-past-controls').hidden = future; $('inv-past-controls').disabled = future; $('inv-future-controls').hidden = !future; $('inv-future-controls').disabled = !future; $('inv-start').required = !future; $('inv-end').required = !future; $('inv-overrides').hidden = !$('inv-override').checked; $('inv-return').disabled = !$('inv-override').checked || !future; $('inv-vol').disabled = !$('inv-override').checked || !future; $('inv-duration').textContent = `${$('inv-months').value} months · ${(Number($('inv-months').value)/12).toFixed(2)} years`;}function setDates() { const first = selected.dates[0], last = selected.dates.at(-1); for (const id of ['inv-start','inv-end']) { $(id).min = first; $(id).max = last; } $('inv-end').value = last; const start = new Date(last+'T00:00:00Z'); start.setUTCFullYear(start.getUTCFullYear()-1); $('inv-start').value = start.toISOString().slice(0,10) < first ? first : start.toISOString().slice(0,10);}function selectTicker() { cleared=false; revision++; invalidate('Choose prices to calculate an investment.'); const custom = $('inv-ticker').value === '__csv__'; $('inv-csv-controls').hidden = !custom; selected = custom ? csvSeries : catalog.find(s=>s.ticker===$('inv-ticker').value) || null; $('inv-source').textContent = ''; $('inv-source-link').hidden = true; if (selected) { setDates(); sourceNote(); calculate(); } else if (custom) $('inv-status').textContent = 'Choose an adjusted-price CSV and enter its ticker label. No file is uploaded.';}function filterTickers({preserve=false}={}) { const search = $('inv-search').value.trim().toUpperCase(), previous = $('inv-ticker').value; $('inv-ticker').replaceChildren(); for (const s of catalog.filter(s=>(s.ticker+' '+s.name).toUpperCase().includes(search))) { const option = document.createElement('option'); option.value=s.ticker; option.textContent=`${s.ticker} · ${s.name}`; $('inv-ticker').append(option); } const custom = document.createElement('option');custom.value='__csv__';custom.textContent='Other ticker · use my CSV';$('inv-ticker').append(custom); if ([...$('inv-ticker').options].some(o=>o.value===previous) && (previous!=='__csv__'||explicitCustom)) $('inv-ticker').value=previous; if(!preserve) selectTicker();}function stat(label, value) { const div=document.createElement('div'),small=document.createElement('span'),strong=document.createElement('strong');small.textContent=label;strong.textContent=value;div.append(small,strong);$('inv-stats').append(div); }function calculate() { invalidate('Updating investment…'); modeControls(); if (!selected) { $('inv-status').textContent='Choose a ticker or import your adjusted-price CSV.'; return; } try { const amount=finiteInput('inv-amount','investment amount between $0.01 and $1 billion'); if ($('inv-mode').value==='past') { result=Q.historical(selected,{amount,start:$('inv-start').value,end:$('inv-end').value}); result.mode='past'; stat('Investment value',money(result.finalValue));stat('Total ROI',pct(result.roi));stat('Gain / loss',money(result.gain));stat('Annualized return',pct(result.annualizedReturn));stat('Maximum drawdown',pct(result.maxDrawdown)); $('inv-result-title').textContent='What your investment would have become.'; $('inv-result-note').textContent=`${selected.ticker} · ${money(amount)} invested · effective dates ${result.start} → ${result.end}. Fractional shares; buy and hold. Based on the adjustment stated above; no fees, taxes or inflation.`; $('inv-assumptions').textContent='Historical performance describes this selected period. It does not predict a future return. Drawdown measures the largest peak-to-trough fall within this period.'; $('inv-chart-title').textContent='Your investment over time'; $('inv-chart-caption').textContent='Investment value from the selected adjusted-price series. Use the chart or point slider to inspect a date.'; } else { let annualReturn,volatility, estimate=null; if ($('inv-override').checked) { annualReturn=finiteInput('inv-return','annual return')/100;volatility=finiteInput('inv-vol','annual volatility')/100; } else { estimate=Q.estimate(selected,{windowYears:Number($('inv-window').value)});annualReturn=estimate.annualReturn;volatility=estimate.volatility; } const years=finiteInput('inv-months','horizon')/12; result=Q.project({amount,years,annualReturn,volatility});result.mode='future';result.estimate=estimate;result.annualReturn=annualReturn;result.volatility=volatility; stat('Mean projected value',money(result.mean));stat('Mean projected ROI',pct(result.roi));stat('Median projected value',money(result.median));stat('10th–90th outcomes',money(result.p10)+' – '+money(result.p90));stat('Modeled chance of loss',probability(result.lossProbability)); $('inv-result-title').textContent='A range of possible futures.'; $('inv-result-note').textContent=`${selected.ticker} · ${money(amount)} invested for ${$('inv-months').value} months from the latest snapshot (${selected.dates.at(-1)}). Conditional scenario; no fees, taxes or inflation. Future dividends, if any, are assumed to follow the same return process.`; $('inv-assumptions').textContent=`Annual mean return ${pct(annualReturn)} · annual volatility ${pct(volatility)}. ${estimate ? `Estimated from ${estimate.observations} daily returns, ${estimate.start} to ${estimate.end}; 252 observations per year.` : 'Uses the annual return and volatility you entered.'} Lognormal model with constant independent returns. The shaded 10th–90th percentile band describes modeled outcomes, not confidence in the estimated return. Parameter uncertainty, market changes and extreme events are not captured. This is separate from the next-close forecast.`; $('inv-chart-title').textContent='How your investment could grow'; $('inv-chart-caption').textContent='Mean is the average across modeled outcomes; median divides outcomes in half. Large upside outcomes can pull the mean above the median.'; } $('inv-status').textContent=result.mode==='past'?'Historical calculation ready.':'Scenario ready. This is an assumption-based estimate, not a promised return.'; $('inv-results').hidden=false;$('inv-export').disabled=false;$('inv-layers').hidden=result.mode==='past';$('inv-drawdown-panel').hidden=result.mode!=='past'; drawCharts(); renderTable(); } catch(error) { fail(error); }}function path(points, key, x, y) {return points.map((p,i)=>(i?'L':'M')+x(i).toFixed(2)+','+y(p[key]).toFixed(2)).join(' ');}function makeChart(id,points,layers,{drawdown=false,band=false}={}) { const mobile=matchMedia('(max-width:650px)').matches; const W=mobile?440:900,H=mobile?300:330,L=mobile?76:88,R=mobile?16:24,T=24,B=48, innerW=W-L-R, innerH=H-T-B; let values=layers.flatMap(layer=>points.map(p=>p[layer.key])); if(band) values=values.concat(points.flatMap(p=>[p.p10,p.p90])); let min=drawdown?Math.min(...values):Math.min(...values,result.amount),max=drawdown?0:Math.max(...values,result.amount); if(max===min){max+=Math.max(1,Math.abs(max)*.05);min-=Math.max(1,Math.abs(min)*.05);} const padding=(max-min)*.07; if(!drawdown){min=Math.max(0,min-padding);max+=padding;} const times=points.map(p=>result.mode==='past'?Date.parse(p.date+'T00:00:00Z'):p.years),firstTime=times[0],span=times.at(-1)-firstTime; const x=i=>L+(times[i]-firstTime)/span*innerW,y=v=>T+(max-v)/(max-min)*innerH; let content=''; for(let i=0;i<=4;i++) {const v=min+(max-min)*i/4,py=y(v);let label=drawdown?pct(v):new Intl.NumberFormat('en-US',{style:'currency',currency:'USD',notation:Math.abs(v)>=1e6?'compact':'standard',maximumFractionDigits:0}).format(v);content+=`<line class="grid" x1="${L}" x2="${W-R}" y1="${py}" y2="${py}"/><text x="${L-12}" y="${py+4}" text-anchor="end">${esc(label)}</text>`;} if(band) {const area=path(points,'p90',x,y)+points.slice().reverse().map((p,j)=>`L${x(points.length-1-j).toFixed(2)},${y(p.p10).toFixed(2)}`).join(' ')+'Z';content+=`<path d="${area}" class="inv-band"/>`;} if(!drawdown) content+=`<line class="inv-principal" x1="${L}" x2="${W-R}" y1="${y(result.amount)}" y2="${y(result.amount)}"/>`; for(const layer of layers) content+=`<path d="${path(points,layer.key,x,y)}" class="inv-series ${layer.css}"/>`; const label=i=>result.mode==='past'?points[i].date:`${(points[i].years*12).toFixed(0)} mo`; content+=`<text x="${L}" y="${H-14}">${esc(label(0))}</text><text x="${W-R}" y="${H-14}" text-anchor="end">${esc(label(points.length-1))}</text><line class="inv-cursor" x1="${x(points.length-1)}" x2="${x(points.length-1)}" y1="${T}" y2="${H-B}"/>`; $(id).innerHTML=`<svg viewBox="0 0 ${W} ${H}" aria-hidden="true">${content}</svg>`; const svg=$(id).querySelector('svg'); const updatePointer=event=>{const box=svg.getBoundingClientRect(),vx=(event.clientX-box.left)/box.width*W;const time=firstTime+Math.max(0,Math.min(1,(vx-L)/innerW))*span;let nearest=0;for(let i=1;i<times.length;i++)if(Math.abs(times[i]-time)<Math.abs(times[nearest]-time))nearest=i;setPoint(nearest);}; svg.addEventListener('pointermove',event=>{if(event.pointerType==='mouse'||event.buttons)updatePointer(event);}); svg.addEventListener('pointerdown',event=>{svg.setPointerCapture(event.pointerId);updatePointer(event);}); charts.push({svg,x,points});}function drawCharts() { if(!result)return; charts=[]; if(result.mode==='past') {makeChart('inv-main-chart',result.points,[{key:'value',css:'inv-mean'}]);makeChart('inv-drawdown-chart',result.points,[{key:'drawdown',css:'inv-drawdown'}],{drawdown:true});} else { const layers=[]; if($('inv-show-mean').checked) layers.push({key:'mean',css:'inv-mean'}); if($('inv-show-median').checked) layers.push({key:'median',css:'inv-median'}); if(!layers.length&&!$('inv-show-band').checked){$('inv-show-mean').checked=true;layers.push({key:'mean',css:'inv-mean'});} makeChart('inv-main-chart',result.points,layers,{band:$('inv-show-band').checked}); } $('inv-point').max=String(result.points.length-1);setPoint(result.points.length-1);}function setPoint(index) { if(!result)return; index=Math.max(0,Math.min(result.points.length-1,index));const p=result.points[index];$('inv-point').value=String(index); for(const chart of charts){const line=chart.svg.querySelector('.inv-cursor');line.setAttribute('x1',chart.x(index));line.setAttribute('x2',chart.x(index));} const text=result.mode==='past'?`${p.date} · value ${money(p.value)} · drawdown ${pct(p.drawdown)}`:`Month ${Math.round(p.years*12)} · mean ${money(p.mean)} · median ${money(p.median)} · 10th–90th ${money(p.p10)} – ${money(p.p90)}`; $('inv-readout').textContent=text;$('inv-point').setAttribute('aria-valuetext',text);}function renderTable() { const future=result.mode==='future'; $('inv-table-head').innerHTML=future?'<tr><th scope="col">Month</th><th scope="col">Mean value</th><th scope="col">Median value</th><th scope="col">10th percentile</th><th scope="col">90th percentile</th></tr>':'<tr><th scope="col">Date</th><th scope="col">Value</th><th scope="col">Drawdown</th></tr>'; const fragment=document.createDocumentFragment(); for(const p of result.points){const row=document.createElement('tr');const values=future?[Math.round(p.years*12),money(p.mean),money(p.median),money(p.p10),money(p.p90)]:[p.date,money(p.value),pct(p.drawdown)];for(const value of values){const td=document.createElement('td');td.textContent=value;row.append(td);}fragment.append(row);} $('inv-table-body').append(fragment);}form.addEventListener('submit',event=>{event.preventDefault();calculate();});form.addEventListener('input',event=>{ const id=event.target.id; if(['inv-search','inv-ticker','inv-csv'].includes(id))return; if(id==='inv-csv-ticker'){if(csvSeries){csvSeries.ticker=event.target.value.trim().toUpperCase()||'MY CSV';sourceNote();calculate();}return;} calculate();});$('inv-mode').addEventListener('change',calculate);$('inv-ticker').addEventListener('change',()=>{explicitCustom=$('inv-ticker').value==='__csv__';selectTicker();});$('inv-search').addEventListener('input',()=>{explicitCustom=false;filterTickers();});$('inv-csv').addEventListener('change',async()=>{ const token=++revision;csvSeries=null;selected=null;invalidate('Reading your price file locally…');$('inv-source').textContent='';$('inv-source-link').hidden=true; try {const file=$('inv-csv').files[0];if(!file)throw Error('Choose an adjusted-price CSV.');if(file.size>2*1024*1024)throw Error('CSV must be no larger than 2 MiB.');const buffer=await file.arrayBuffer();if(token!==revision)return;const text=new TextDecoder('utf-8',{fatal:true}).decode(buffer);const parsed=Q.parseCSV(text);csvSeries={...parsed,ticker:$('inv-csv-ticker').value.trim().toUpperCase()||'MY CSV',name:'Your local prices',currency:'USD',adjustment:'User-supplied adjustment and USD currency are not independently verified.'};selected=csvSeries;setDates();sourceNote();calculate();}catch(error){if(token===revision)fail(error);}});$('inv-point').addEventListener('input',()=>setPoint(Number($('inv-point').value)));for(const id of ['inv-show-mean','inv-show-median','inv-show-band'])$(id).addEventListener('change',drawCharts);for(const button of document.querySelectorAll('[data-investment-range]'))button.addEventListener('click',()=>{ if(!selected)return;const years=Number(button.dataset.investmentRange),last=selected.dates.at(-1),date=new Date(last+'T00:00:00Z');date.setUTCFullYear(date.getUTCFullYear()-years);$('inv-start').value=years===0?selected.dates[0]:[selected.dates[0],date.toISOString().slice(0,10)].sort().at(-1);$('inv-end').value=last;calculate();});$('inv-reset').addEventListener('click',()=>{revision++;csvSeries=null;explicitCustom=false;form.reset();$('inv-search').value='';filterTickers();});$('inv-export').addEventListener('click',()=>{ if(!result)return; const report={schemaVersion:1,ticker:selected.ticker,name:selected.name,currency:'USD',source:{url:selected.sourceUrl||null,adjustment:selected.adjustment,firstDate:selected.dates[0],lastDate:selected.dates.at(-1),retrievedAt:selected.retrievedAt||null},assumptions:$('inv-assumptions').textContent,result}; const url=URL.createObjectURL(new Blob([JSON.stringify(report,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=url;a.download='quantlab-investment.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});$('clear-data').addEventListener('click',()=>{revision++;cleared=true;csvSeries=null;selected=null;$('inv-csv').value='';$('inv-source').textContent='';$('inv-source-link').hidden=true;invalidate('Investment results and local file cleared. Select a ticker to start again.');});async function loadCatalog() { try { const response=await fetch('market-data.json',{cache:'no-cache'});if(!response.ok)throw Error('Historical snapshots are unavailable. Use your adjusted-price CSV.'); const data=await response.json(); if(data.schemaVersion!==1||!Array.isArray(data.securities)||!data.securities.length)throw Error('The historical snapshot format is invalid. Use your adjusted-price CSV.'); catalog=data.securities.map(s=>{Q.validateSeries(s);if(!/^[A-Z0-9.^-]{1,15}$/.test(s.ticker)||s.currency!=='USD')throw Error('Unsupported snapshot ticker or currency.');if(s.sourceUrl&&!/^https:\/\//.test(s.sourceUrl))throw Error('Invalid data source link.');return s;}); filterTickers({preserve:explicitCustom||cleared}); } catch(error){catalog=[];filterTickers({preserve:explicitCustom||cleared});if(!selected&&!cleared)$('inv-status').textContent=error.message;}}matchMedia('(max-width:650px)').addEventListener('change',drawCharts);document.querySelectorAll('[data-view]').forEach(button=>button.addEventListener('click',()=>{if(button.dataset.view==='investment')history.replaceState(null,'','#investment');else if(location.hash==='#investment')history.replaceState(null,'',location.pathname+location.search);}));modeControls();loadCatalog();if(location.hash==='#investment')document.querySelector('[data-view="investment"]').click();})();12345678/* Match the existing QuantLab light workspace. */#investment{padding-top:36px;scroll-margin-top:90px}.inv-heading{display:flex;align-items:end;justify-content:space-between;gap:24px;margin:8px 0 28px}.inv-eyebrow{font-size:12px;letter-spacing:.09em;text-transform:uppercase;color:var(--blue);font-weight:650;margin-bottom:10px}.inv-heading h2{font-size:clamp(32px,4vw,44px);letter-spacing:-.04em;line-height:1.1;margin-bottom:12px}.inv-heading p:last-child{margin:0;color:var(--secondary);max-width:57ch}.inv-badge{display:inline-block;border:1px solid var(--line);border-radius:20px;padding:6px 12px;color:var(--secondary);font-size:12px;white-space:nowrap}.inv-layout{display:grid;grid-template-columns:280px minmax(0,1fr);gap:24px;align-items:start}.inv-controls{background:white;border-radius:16px;padding:24px;min-width:0}.inv-controls label:first-child{margin-top:0}.inv-controls label{margin-top:18px}.inv-controls input,.inv-controls select{min-width:0}.inv-controls input[type=checkbox]{width:18px;height:18px;min-height:18px;margin:0;flex-shrink:0;accent-color:var(--blue)}.inv-controls fieldset{margin:20px 0 0;padding:0;border:0;min-width:0}.inv-controls legend{font-weight:600;font-size:14px;margin-bottom:6px}.inv-controls .inv-check{display:flex;gap:10px;align-items:center;font-weight:450}.inv-controls .primary{width:100%;margin-top:24px}.inv-controls .inv-reset{width:100%;margin-top:8px;min-height:44px;border:0;background:transparent;color:var(--blue);font-size:13px}.inv-controls input[type=range],#inv-point{accent-color:var(--blue);padding:0;border:0;min-height:36px;background:transparent}.inv-preset{display:flex;gap:6px;margin:14px 0 0}.inv-preset button{border:0;border-radius:8px;min-height:40px;flex:1;background:#eeeef2;font-size:12px;color:#1d1d1f}.inv-contents{min-width:0}.inv-source-panel{border-bottom:1px solid var(--line);margin-bottom:20px;padding-bottom:16px}.inv-source-panel p{margin:0;font-size:12px;line-height:1.7;color:var(--secondary);overflow-wrap:anywhere}.inv-source-panel a{font-size:12px;display:inline-block;margin-top:8px;min-height:28px}.inv-source-panel .inv-data-warning{color:#775000;margin-top:8px}#inv-status{font-size:14px;line-height:1.6;margin:0 0 20px}#inv-status.lab-error{color:#a12525;background:#fff0ef;padding:14px;border-radius:10px}#inv-results{background:#fff;border-radius:16px;padding:28px}#inv-result-title{font-size:25px;margin-bottom:12px}#inv-result-note{color:var(--secondary);font-size:13px;line-height:1.65}.inv-stats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:22px 20px;padding:12px 0 24px;border-bottom:1px solid var(--line);margin-bottom:24px}.inv-stats>div:first-child{grid-column:1/-1}.inv-stats span{display:block;font-size:12px;color:var(--secondary)}.inv-stats strong{display:block;font-size:23px;line-height:1.3;font-weight:600;letter-spacing:-.025em;font-variant-numeric:tabular-nums;margin-top:6px;overflow-wrap:anywhere}.inv-stats>div:first-child strong{font-size:clamp(32px,4vw,48px);color:var(--blue);letter-spacing:-.04em}.inv-chart-heading h3{font-size:19px;margin-bottom:8px}.inv-chart-heading p{font-size:13px;line-height:1.6;color:var(--secondary);margin-bottom:12px}.inv-layers{display:flex;align-items:center;flex-wrap:wrap;gap:6px 14px;margin-bottom:8px}.inv-layers label{display:flex;align-items:center;gap:7px;font-size:12px;min-height:40px;margin:0}.inv-layers input{width:16px;min-height:16px;height:16px;accent-color:var(--blue)}.inv-chart svg{width:100%;display:block;touch-action:pan-y}.inv-chart text{font:14px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;fill:#626268;font-variant-numeric:tabular-nums}.inv-chart .grid{stroke:#e9e9ed;stroke-width:1}.inv-series{fill:none;stroke-width:2.5;vector-effect:non-scaling-stroke;stroke-linejoin:round;stroke-linecap:round}.inv-mean{stroke:#0066cc}.inv-median{stroke:#76509d;stroke-dasharray:7 5}.inv-drawdown{stroke:#a04b2b}.inv-band{fill:#0066cc;fill-opacity:.12}.inv-principal{stroke:#92929b;stroke-dasharray:3 5;vector-effect:non-scaling-stroke}.inv-cursor{stroke:#626268;stroke-width:1;stroke-dasharray:3 4;vector-effect:non-scaling-stroke}.inv-inspect{background:#f5f5f7;border-radius:10px;padding:14px 16px;margin-top:8px}.inv-inspect label{margin:0;font-size:12px}.inv-inspect output{display:block;font-size:12px;line-height:1.7;font-variant-numeric:tabular-nums;min-height:42px;color:#34343a}#inv-drawdown-panel{margin-top:28px}#inv-drawdown-panel h3{font-size:16px;margin-bottom:4px}#inv-drawdown-panel p{font-size:12px;color:var(--secondary)}.inv-details{margin-top:24px}.inv-details p{font-size:13px;line-height:1.7;color:var(--secondary)}.inv-table-wrap{max-height:400px;overflow:auto}.inv-table-wrap table{font-size:12px}.inv-table-wrap thead{position:sticky;top:0;background:#fff}#inv-export{margin-top:24px}.inv-mean-label{color:#0066cc}.inv-median-label{color:#76509d}.inv-fine-print{font-size:12px;line-height:1.7;color:var(--secondary);margin:20px 0 0}#inv-duration{display:block;font-size:13px;font-variant-numeric:tabular-nums;color:var(--secondary)}@media(prefers-reduced-motion:no-preference){#inv-results{animation:inv-appear .2s ease-out}.inv-series,.inv-band{animation:inv-appear .25s ease-out}@keyframes inv-appear{from{opacity:.15;transform:translateY(3px)}to{opacity:1;transform:none}}}@media(min-width:851px){.masthead-inner{gap:20px}.tab{padding-inline:11px}}@media(max-width:850px){.inv-layout{grid-template-columns:240px minmax(0,1fr);gap:18px}.inv-controls{padding:20px}#inv-results{padding:22px}.inv-stats{grid-template-columns:1fr}.inv-stats>div:first-child{grid-column:auto}.inv-heading{align-items:start}.inv-badge{white-space:normal}.masthead-inner{flex-wrap:wrap;gap:8px}.masthead-inner nav{flex-wrap:wrap}.tab{padding:9px}#investment{scroll-margin-top:145px}}@media(max-width:650px){.inv-layout{grid-template-columns:minmax(0,1fr)}.inv-heading{display:block}.inv-heading h2{font-size:34px}.inv-heading .inv-badge{margin-top:14px}.inv-controls{padding:24px}.inv-stats{grid-template-columns:repeat(2,minmax(0,1fr))}.inv-stats>div:first-child{grid-column:1/-1}.inv-chart{margin-inline:-12px}.inv-chart text{font-size:16px}.inv-heading{margin-bottom:22px}#investment{padding-top:24px}.masthead-inner nav{justify-content:flex-start;gap:2px}.tab{font-size:11px;padding:9px 8px}.inv-layers{gap:4px 10px}#inv-results{padding:24px}.inv-controls .inv-preset button{min-height:44px}}@media(max-width:360px){.inv-stats{grid-template-columns:1fr}.inv-stats>div:first-child{grid-column:auto}.tab{padding-inline:6px}}@media(prefers-reduced-motion:reduce){#inv-results,.inv-series,.inv-band{animation:none;transition:none}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155/* Independent USD fractional-share historical and conditional lognormal calculations. */(function (root, factory) { const api = factory(); if (typeof module === 'object' && module.exports) module.exports = api; else root.QuantInvestment = api;})(typeof globalThis !== 'undefined' ? globalThis : this, function () { 'use strict'; const DAY = 86400000; const Z90 = 1.2815515655446004; function dateTime(value) { if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new Error('Dates must use YYYY-MM-DD.'); const time = Date.parse(value + 'T00:00:00Z'); if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== value) throw new Error('Choose a real calendar date.'); return time; } function bounded(value, min, max, label) { if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) throw new Error(label + ' must be a finite number from ' + min + ' to ' + max + '.'); return value; } function finitePositive(value) { if (!Number.isFinite(value) || value <= 0) throw new Error('These prices or assumptions produce an unsupported numerical result.'); return value; } function validateSeries(series) { if (!series || !Array.isArray(series.dates) || !Array.isArray(series.closes) || series.dates.length !== series.closes.length || series.dates.length < 2) throw new Error('Provide at least two matching dates and closing prices.'); let previous = -Infinity; for (let i = 0; i < series.dates.length; i++) { const date = series.dates[i]; const time = dateTime(date); if (time <= previous) throw new Error('Dates must be unique and sorted from oldest to newest.'); previous = time; if (typeof series.closes[i] !== 'number' || !Number.isFinite(series.closes[i]) || series.closes[i] <= 0) throw new Error('Every closing price must be a positive finite number.'); } return series; } function historical(series, options) { validateSeries(series); if (!options) throw new Error('Choose an amount and date range.'); const amount = bounded(options.amount, .01, 1e9, 'Investment amount'); const startTime = dateTime(options.start), endTime = dateTime(options.end); const {dates, closes} = series; if (startTime >= endTime) throw new Error('The end date must follow the start date.'); if (options.start < dates[0] || options.end > dates[dates.length - 1]) throw new Error('Choose dates within the available price history.'); const first = dates.findIndex(date => date >= options.start); let last = dates.length - 1; while (last >= 0 && dates[last] > options.end) last--; if (last <= first) throw new Error('Choose a range containing at least two trading observations.'); let peak = amount, maxDrawdown = 0; const points = []; for (let i = first; i <= last; i++) { const value = finitePositive(amount * (closes[i] / closes[first])); peak = Math.max(peak, value); const drawdown = value / peak - 1; maxDrawdown = Math.max(maxDrawdown, -drawdown); points.push({date: dates[i], value, drawdown}); } const finalValue = points[points.length - 1].value; const roi = finalValue / amount - 1; const annualizedReturn = Math.expm1(Math.log(finalValue / amount) * 365.25 * DAY / (dateTime(dates[last]) - dateTime(dates[first]))); if (![roi, annualizedReturn, finalValue - amount].every(Number.isFinite)) throw new Error('This date range produces an unsupported numerical result.'); return {amount, finalValue, gain: finalValue - amount, roi, annualizedReturn, maxDrawdown, start: dates[first], end: dates[last], points}; } function estimate(series, options) { validateSeries(series); const windowYears = options && options.windowYears; if (![1, 3, 5].includes(windowYears)) throw new Error('Choose a 1, 3, or 5 year estimation window.'); const {dates, closes} = series; const end = dates[dates.length - 1]; // Calendar window anchored at the final observation, including the boundary price. const boundary = new Date(dateTime(end)); boundary.setUTCFullYear(boundary.getUTCFullYear() - windowYears); const first = dates.findIndex(date => dateTime(date) >= boundary.getTime()); const count = dates.length - first - 1; if (count < 60) throw new Error('At least 60 daily returns are required in the selected window.'); let mean = 0, m2 = 0, n = 0; for (let i = first + 1; i < closes.length; i++) { const value = Math.log(closes[i]) - Math.log(closes[i - 1]); n++; const delta = value - mean; mean += delta / n; m2 += delta * (value - mean); } const varianceAnnual = Math.max(0, m2 / (n - 1)) * 252; const annualReturn = Math.expm1(mean * 252 + varianceAnnual / 2); const volatility = Math.sqrt(varianceAnnual); if (![annualReturn, volatility].every(Number.isFinite)) throw new Error('Price history produces nonfinite annual assumptions.'); return {annualReturn, volatility, start: dates[first], end, observations: count}; } function normalCDF(x) { // Abramowitz–Stegun normal approximation: absolute error below 8e-8. if (x === 0) return .5; const t = 1 / (1 + .2316419 * Math.abs(x)); const tail = Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI) * t * (.319381530 + t * (-.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429)))); return Math.max(0, Math.min(1, x >= 0 ? 1 - tail : tail)); } function project(options) { if (!options) throw new Error('Provide future scenario assumptions.'); const amount = bounded(options.amount, .01, 1e9, 'Investment amount'); const years = bounded(options.years, 1 / 12, 10, 'Years'); const annualReturn = bounded(options.annualReturn, -.95, 2, 'Annual return'); const volatility = bounded(options.volatility, 0, 2, 'Annual volatility'); const growth = Math.log1p(annualReturn), drift = growth - volatility * volatility / 2; function point(time) { const center = drift * time, width = Z90 * volatility * Math.sqrt(time); return {years: time, mean: finitePositive(amount * Math.exp(growth * time)), median: finitePositive(amount * Math.exp(center)), p10: finitePositive(amount * Math.exp(center - width)), p90: finitePositive(amount * Math.exp(center + width))}; } const result = point(years); const steps = Math.min(120, Math.max(1, Math.ceil(years * 12))); const points = Array.from({length: steps + 1}, (_, i) => point(years * i / steps)); const lossProbability = volatility === 0 ? (annualReturn < 0 ? 1 : 0) : normalCDF(-drift * Math.sqrt(years) / volatility); return {amount, years, mean: result.mean, median: result.median, p10: result.p10, p90: result.p90, roi: result.mean / amount - 1, lossProbability, points}; } function parseCSV(text) { if (typeof text !== 'string' || new TextEncoder().encode(text).length > 2 * 1024 * 1024) throw new Error('CSV must be text no larger than 2 MiB.'); text = text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n'); const rows = []; let row = [], field = '', quoted = false, closed = false; function pushRow() { row.push(field); if (row.some(value => value.trim() !== '')) rows.push(row); if (rows.length > 2501) throw new Error('CSV supports at most 2,500 price rows.'); row = []; field = ''; closed = false; } for (let i = 0; i < text.length; i++) { const c = text[i]; if (quoted) { if (c === '"' && text[i + 1] === '"') { field += '"'; i++; } else if (c === '"') { quoted = false; closed = true; } else field += c; } else if (c === ',') { row.push(field); field = ''; closed = false; } else if (c === '\n') pushRow(); else if (c === '"' && !field && !closed) quoted = true; else if (c === '"' || (closed && !/\s/.test(c))) throw new Error('CSV contains malformed quoting.'); else field += c; } if (quoted) throw new Error('CSV contains an unclosed quoted field.'); pushRow(); if (rows.length < 3) throw new Error('CSV needs a header and at least two price rows.'); const headers = rows.shift().map(value => value.trim().toLowerCase()); if (new Set(headers).size !== headers.length) throw new Error('CSV headers must be unique.'); const dateIndex = headers.indexOf('date'); const priceIndex = headers.includes('adj_close') ? headers.indexOf('adj_close') : headers.indexOf('close'); if (dateIndex < 0 || priceIndex < 0) throw new Error('CSV requires date and adj_close (or close) columns.'); const series = {dates: [], closes: []}; rows.forEach((values, i) => { if (values.length !== headers.length) throw new Error('CSV row ' + (i + 2) + ' has the wrong number of fields.'); const price = values[priceIndex].trim(); if (!/^[+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(price)) throw new Error('CSV row ' + (i + 2) + ' needs a positive numeric closing price.'); series.dates.push(values[dateIndex].trim()); series.closes.push(Number(price)); }); return validateSeries(series); } return {validateSeries, historical, estimate, project, parseCSV};});12345678910111213141516171819202122232425262728293031323334353637383940414243444546'use strict';const {chromium}=require(process.env.PLAYWRIGHT_MODULE || 'playwright');const path=require('node:path');const ROOT=path.resolve(__dirname,'..'), ARTIFACT_DIR=path.join(ROOT,'browser-artifacts'), BASE_URL=process.env.BASE_URL||'http://127.0.0.1:8765';const assert=require('node:assert/strict'),fs=require('node:fs');fs.mkdirSync(ARTIFACT_DIR,{recursive:true});const snapshot=JSON.parse(fs.readFileSync(path.join(ROOT,'market-data.json'),'utf8'));const Q=require(path.join(ROOT,'investment.js'));(async()=>{ const browser=await chromium.launch({channel:'chrome',headless:true});let failed=0;const checks=[]; const test=async(name,fn)=>{try{await fn();checks.push({name,pass:true});console.log('PASS',name);}catch(error){failed++;checks.push({name,pass:false,error:error.message});console.error('FAIL',name,error.message);}}; const page=await browser.newPage({viewport:{width:1440,height:1100},acceptDownloads:true}); const errors=[];page.on('pageerror',e=>errors.push(e.message)); try { await page.goto(BASE_URL);await page.getByRole('button',{name:'Investment explorer',exact:true}).click();await page.waitForFunction(()=>document.querySelector('#inv-ticker').options.length>1); await test('default ticker shows a historical calculation',async()=>{assert.equal(await page.locator('#inv-ticker').inputValue(),'AAPL');assert(await page.locator('#inv-results').isVisible());}); await page.locator('#inv-ticker').selectOption('AAPL'); await test('all eight tickers calculate historical and future values',async()=>{for(const s of snapshot.securities){await page.locator('#inv-ticker').selectOption(s.ticker);await page.locator('#inv-mode').selectOption('past');const start=await page.locator('#inv-start').inputValue(),end=await page.locator('#inv-end').inputValue();const h=Q.historical(s,{amount:10000,start,end});assert((await page.locator('#inv-stats').textContent()).includes(h.finalValue.toLocaleString('en-US',{style:'currency',currency:'USD'})));await page.locator('#inv-mode').selectOption('future');assert(await page.locator('#inv-results').isVisible(),s.ticker+' scenario');}}); await test('hidden invalid historical inputs do not block future submission',async()=>{await page.locator('#inv-mode').selectOption('past');await page.locator('#inv-start').fill('1900-01-01');await page.locator('#inv-mode').selectOption('future');assert(await page.locator('#inv-form').evaluate(el=>el.checkValidity()));}); await page.locator('#inv-ticker').selectOption('AAPL');await page.locator('#inv-mode').selectOption('future');await page.locator('#inv-override').check();await page.locator('#inv-return').fill('10');await page.locator('#inv-vol').fill('20');await page.locator('#inv-months').fill('24'); await test('future manual assumptions produce analytic ROI',async()=>{assert((await page.locator('#inv-stats').textContent()).includes('$12,100.00'));assert((await page.locator('#inv-stats').textContent()).includes('21%'));}); await test('keyboard chart exploration and layer toggles work',async()=>{await page.locator('#inv-point').focus();const before=await page.locator('#inv-readout').textContent();await page.keyboard.press('ArrowLeft');assert.notEqual(await page.locator('#inv-readout').textContent(),before);await page.locator('#inv-show-mean').uncheck();await page.locator('#inv-show-median').uncheck();await page.locator('#inv-show-band').uncheck();assert.equal(await page.locator('#inv-main-chart .inv-series').count(),1);}); await test('empty investment invalidates stale results and export',async()=>{await page.locator('#inv-amount').fill('');assert(await page.locator('#inv-results').isHidden());assert(await page.locator('#inv-export').isDisabled());}); await page.locator('#inv-amount').fill('10000');await page.locator('#inv-show-median').check();await page.locator('#inv-show-band').check(); await test('result export includes ticker and current assumptions',async()=>{const downloadPromise=page.waitForEvent('download');await page.locator('#inv-export').click();const download=await downloadPromise;const report=JSON.parse(fs.readFileSync(await download.path(),'utf8'));assert.equal(report.ticker,'AAPL');assert.equal(report.result.annualReturn,.1);assert.equal(report.result.years,2);}); await page.evaluate(()=>scrollTo(0,0));await page.waitForTimeout(120);await page.screenshot({path:path.join(ARTIFACT_DIR,'investment-desktop.png'),fullPage:true}); await test('CSV remains local and historical weekend dates snap inward',async()=>{await page.locator('#inv-ticker').selectOption('__csv__');await page.locator('#inv-csv-ticker').fill('TEST');await page.locator('#inv-mode').selectOption('past');await page.locator('#inv-csv').setInputFiles({name:'prices.csv',mimeType:'text/csv',buffer:Buffer.from('date,close\n2026-10-02,100\n2026-10-05,110\n2026-10-06,120\n2026-10-09,90\n2026-10-12,130\n')});await page.waitForFunction(()=>!document.querySelector('#inv-results').hidden);await page.locator('#inv-start').fill('2026-10-03');await page.locator('#inv-end').fill('2026-10-11');assert((await page.locator('#inv-result-note').textContent()).includes('2026-10-05 → 2026-10-09'));assert((await page.locator('#inv-stats').textContent()).includes('$8,181.82'));}); await test('invalid CSV clears previous values',async()=>{await page.locator('#inv-csv').setInputFiles({name:'bad.csv',mimeType:'text/csv',buffer:Buffer.from('date,close\n2026-10-01,100\n2026-10-01,110')});await page.waitForFunction(()=>document.querySelector('#inv-status').classList.contains('lab-error'));assert(await page.locator('#inv-results').isHidden());}); await page.locator('#inv-ticker').selectOption('MSFT');await page.locator('#inv-mode').selectOption('future'); await test('mobile has no horizontal document overflow',async()=>{await page.setViewportSize({width:390,height:844});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await page.evaluate(()=>scrollTo(0,0));await page.waitForTimeout(120);await page.screenshot({path:path.join(ARTIFACT_DIR,'investment-mobile.png'),fullPage:true});assert.equal(await page.locator('#inv-main-chart svg').getAttribute('viewBox'),'0 0 440 300');await page.locator('#inv-results').screenshot({path:path.join(ARTIFACT_DIR,'investment-mobile-results.png')});}); await test('reduced motion disables result and chart animations',async()=>{await page.emulateMedia({reducedMotion:'reduce'});await page.locator('#inv-amount').fill('5000');assert.equal(await page.locator('#inv-results').evaluate(el=>getComputedStyle(el).animationName),'none');assert.equal(await page.locator('.inv-series').first().evaluate(el=>getComputedStyle(el).animationName),'none');}); await test('no browser JavaScript errors',async()=>assert.deepEqual(errors,[])); const race=await browser.newPage();let release;const gate=new Promise(r=>release=r); await race.route('**/market-data.json',async route=>{await gate;await route.fulfill({json:snapshot});}); await race.goto(BASE_URL);await race.getByRole('button',{name:'Investment explorer',exact:true}).click();await race.locator('#inv-search').fill('NVDA');release(); await test('typing during snapshot load preserves and completes ticker search',async()=>{await race.waitForFunction(()=>[...document.querySelector('#inv-ticker').options].some(o=>o.value==='NVDA'),{},{timeout:2500});assert.equal(await race.locator('#inv-ticker').inputValue(),'NVDA');assert(await race.locator('#inv-results').isVisible());}); await race.close(); await test('investment view supports a direct preview link',async()=>{const p=await browser.newPage();await p.goto(BASE_URL+'/#investment');assert(await p.locator('#investment').isVisible());await p.getByRole('button',{name:'Price explorer',exact:true}).click();assert(!p.url().endsWith('#investment'));await p.close();}); await test('CSV selected during a slow catalog load remains selected',async()=>{const p=await browser.newPage();let release;const gate=new Promise(r=>release=r);await p.route('**/market-data.json',async route=>{await gate;await route.fulfill({json:snapshot});});await p.goto(BASE_URL);await p.getByRole('button',{name:'Investment explorer',exact:true}).click();await p.locator('#inv-search').fill('OTHER');await p.locator('#inv-ticker').selectOption('__csv__');await p.locator('#inv-csv').setInputFiles({name:'test.csv',mimeType:'text/csv',buffer:Buffer.from('date,close\n2026-10-01,100\n2026-10-02,110')});await p.waitForFunction(()=>!document.querySelector('#inv-results').hidden);release();await p.waitForFunction(()=>document.querySelector('#inv-ticker').options.length===1);await p.waitForTimeout(150);assert.equal(await p.locator('#inv-ticker').inputValue(),'__csv__');assert((await p.locator('#inv-stats').textContent()).includes('$11,000.00'));await p.close();}); await test('switching ticker cancels a pending local file read',async()=>{await page.locator('#inv-mode').selectOption('past');await page.locator('#inv-ticker').selectOption('__csv__');await page.evaluate(()=>{window.originalArrayBuffer=File.prototype.arrayBuffer;File.prototype.arrayBuffer=function(){return new Promise(resolve=>window.finishCSV=()=>resolve(new TextEncoder().encode('date,close\n2026-10-01,1\n2026-10-02,9').buffer));};});await page.locator('#inv-csv').setInputFiles({name:'delayed.csv',mimeType:'text/csv',buffer:Buffer.from('date,close')});await page.waitForFunction(()=>typeof window.finishCSV==='function');await page.locator('#inv-ticker').selectOption('AAPL');const before=await page.locator('#inv-stats').textContent();await page.evaluate(()=>{window.finishCSV();File.prototype.arrayBuffer=window.originalArrayBuffer;});await page.waitForTimeout(50);assert.equal(await page.locator('#inv-stats').textContent(),before);assert((await page.locator('#inv-result-note').textContent()).startsWith('AAPL'));}); await test('clear during snapshot load does not restore cleared results',async()=>{const p=await browser.newPage();let release;const gate=new Promise(r=>release=r);await p.route('**/market-data.json',async route=>{await gate;await route.fulfill({json:snapshot});});await p.goto(BASE_URL);await p.locator('#clear-data').evaluate(el=>el.click());release();await p.waitForFunction(()=>document.querySelector('#inv-ticker').options.length>1);assert(await p.locator('#inv-results').isHidden());assert((await p.locator('#inv-status').textContent()).includes('cleared'));await p.close();}); await test('failed snapshot load leaves local CSV usable',async()=>{const p=await browser.newPage();await p.route('**/market-data.json',route=>route.fulfill({status:503,body:'Unavailable'}));await p.goto(BASE_URL);await p.getByRole('button',{name:'Investment explorer',exact:true}).click();await p.waitForFunction(()=>document.querySelector('#inv-status').textContent.includes('unavailable'));await p.locator('#inv-csv').setInputFiles({name:'test.csv',mimeType:'text/csv',buffer:Buffer.from('date,close\n2026-10-01,100\n2026-10-02,110')});await p.waitForFunction(()=>!document.querySelector('#inv-results').hidden);assert((await p.locator('#inv-stats').textContent()).includes('$11,000.00'));await p.close();});
} finally {await browser.close();fs.writeFileSync(path.join(ARTIFACT_DIR,'browser-checks.json'),JSON.stringify({checks,failed},null,2));} if(failed)process.exitCode=1;})().catch(error=>{console.error(error);process.exit(1)});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155#!/usr/bin/env python3"""Explicit maintenance task; the browser app never calls this network script."""
import argparseimport calendarimport datetime as dtimport jsonimport mathimport osfrom pathlib import Pathimport tempfileimport urllib.parseimport urllib.requestfrom zoneinfo import ZoneInfo
TICKERS = ("AAPL", "MSFT", "NVDA", "AMZN", "GOOGL", "TSLA", "SPY", "QQQ")ADJUSTMENT = "Yahoo Finance adjusted close: adjusted for stock splits and cash dividends"ADJUSTMENT_URL = "https://in.help.yahoo.com/kb/adjusted-close-sln28256.html"NY = ZoneInfo("America/New_York")
def now(): return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def epoch(day): return int(dt.datetime.combine(day, dt.time(), dt.timezone.utc).timestamp())
def retrieve(ticker, start, end): query = urllib.parse.urlencode({"period1": epoch(start), "period2": epoch(end), "interval": "1d", "events": "div,splits"}) url = f"https://query2.finance.yahoo.com/v8/finance/chart/{ticker}?{query}" request = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"}) with urllib.request.urlopen(request, timeout=40) as response: payload = json.load(response) retrieved_at = now() chart = payload["chart"] if chart.get("error") or not chart.get("result"): raise ValueError(f"{ticker}: provider did not return chart data") data = chart["result"][0] if data["meta"].get("symbol") != ticker or data["meta"].get("currency") != "USD": raise ValueError(f"{ticker}: unexpected symbol or currency") timestamps = data["timestamp"] adjusted = data["indicators"]["adjclose"][0]["adjclose"] if len(timestamps) != len(adjusted): raise ValueError(f"{ticker}: unaligned observations") dates, closes = [], [] missing, excluded = 0, 0 for timestamp, close in zip(timestamps, adjusted): day = dt.datetime.fromtimestamp(timestamp, NY).date() if not start <= day < end: excluded += 1 continue if close is None: missing += 1 continue if isinstance(close, bool) or not isinstance(close, (int, float)) or not math.isfinite(close) or close <= 0: raise ValueError(f"{ticker}: invalid adjusted price on {day}") label = day.isoformat() if dates and label <= dates[-1]: raise ValueError(f"{ticker}: dates are not strictly increasing") dates.append(label) closes.append(close) if len(dates) < 1000: raise ValueError(f"{ticker}: insufficient observations ({len(dates)})") result = {"ticker": ticker, "name": data["meta"].get("longName", ticker), "currency": "USD", "sourceUrl": url, "adjustment": ADJUSTMENT, "retrievedAt": retrieved_at, "dates": dates, "closes": closes} return result, missing, excluded, len(timestamps)
def atomic_write(path, text): handle, temporary = tempfile.mkstemp(prefix=path.name + ".", dir=path.parent) try: with os.fdopen(handle, "w") as stream: stream.write(text) os.replace(temporary, path) finally: if os.path.exists(temporary): os.unlink(temporary)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--online", action="store_true", help="explicitly permit requests to Yahoo Finance") parser.add_argument("--as-of", required=True, type=dt.date.fromisoformat, help="exclusive ISO date; only earlier daily sessions are included") args = parser.parse_args() if not args.online: parser.error("network retrieval requires --online") if args.as_of > dt.datetime.now(NY).date(): parser.error("--as-of cannot be later than today's New York date") # Five calendar years; February 29 maps to February 28 when necessary. start_year = args.as_of.year - 5 start = args.as_of.replace(year=start_year, day=min(args.as_of.day, calendar.monthrange(start_year, args.as_of.month)[1])) securities, rows = [], [] for ticker in TICKERS: series, missing, excluded, returned = retrieve(ticker, start, args.as_of) securities.append(series) rows.append(f"| {ticker} | {series['dates'][0]} | {series['dates'][-1]} | {len(series['dates'])} | {missing} | {excluded} | {returned} | {series['retrievedAt']} |") print(f"{ticker}: {len(series['dates'])} observations; {series['dates'][0]} to {series['dates'][-1]}; missing {missing}; excluded {excluded}") generated = now() result = {"schemaVersion": 1, "generatedAt": generated, "source": {"name": "Yahoo Finance chart API (dated daily snapshot)", "url": "https://finance.yahoo.com/", "adjustment": ADJUSTMENT, "currency": "USD"}, "securities": securities} root = Path(__file__).resolve().parent.parent report = f"""# Market data provenance
Generated: {generated}. Requested inclusive start: {start}; exclusive end: {args.as_of}.These are dated historical observations, never live quotes. The current day's session is excluded.
Source: Yahoo Finance public chart endpoint, `indicators.adjclose[0].adjclose`.Each security in `market-data.json` retains its exact request URL and UTC retrieval timestamp.Dates use the America/New_York exchange timezone. Values retain provider precision.[Yahoo's adjustment documentation]({ADJUSTMENT_URL}) describes split and cash-dividend adjustment.Ratios of these adjusted prices approximate dividend-reinvested growth; no separate dividends are added.Provider adjustments and corrections can revise historical values. This is not a full accounting oftaxes, commissions, slippage, dividend reinvestment execution, or inflation. Symbols are a curatedselection of current securities and are not an unbiased historical universe.
| Ticker | First session | Last session | Kept | Missing dropped | Outside range excluded | Provider bars | Retrieved UTC || --- | --- | --- | ---: | ---: | ---: | ---: | --- |{chr(10).join(rows)}
Integrity checks: aligned price/date arrays; positive finite adjusted values; strictly increasing,unique dates; USD and requested symbol verified against provider metadata; at least 1,000 barsper security. Null adjusted values are omitted and counted above. Unexpected non-null prices,provider errors, or missing adjusted-price fields fail the entire refresh before replacement.No synthetic prices, forward filling, or substitution with unadjusted closes is performed.
Refresh manually, using Python 3.9+ and its standard library (network required):
```shpython3 scripts/refresh-market-data.py --online --as-of {args.as_of}```
If a macOS Python installation lacks configured CA certificates, use its certificate setup orexplicitly select the system trust store with `SSL_CERT_FILE=/etc/ssl/cert.pem` before the command.Certificate verification remains enabled; the snapshot here was retrieved using that trust store.
The end date is exclusive; choose today's New York date or an earlier date to omit incompletesessions. All eight requests must succeed before the snapshot is replaced atomically. Yahoo canrate-limit or change this unofficial chart endpoint. A failed refresh leaves the previous snapshotintact. The static browser app reads only its bundled same-origin JSON. Personal CSV files stayin the browser and are not sent by this maintenance script.""" atomic_write(root / "market-data.json", json.dumps(result, separators=(",", ":"), allow_nan=False) + "\n") atomic_write(root / "MARKET-DATA.md", report)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334'use strict';const assert = require('node:assert/strict');const Q = require('./investment.js');const near = (a,b,t=1e-10) => assert.ok(Math.abs(a-b)<=t*Math.max(1,Math.abs(b)), `${a} != ${b}`);const series = {dates:['2020-01-01','2020-01-03','2020-07-01','2021-01-01'],closes:[100,120,90,150]};const h=Q.historical(series,{amount:1000,start:'2020-01-02',end:'2021-01-01'});assert.equal(h.start,'2020-01-03'); assert.equal(h.end,'2021-01-01');near(h.finalValue,1250); near(h.gain,250); near(h.roi,.25); near(h.maxDrawdown,.25);near(h.annualizedReturn,Math.pow(1.25,365.25/364)-1);assert.equal(h.points.length,3); near(h.points[1].value,750); near(h.points[1].drawdown,-.25);for(const bad of [{dates:['2020-02-30','2021-01-01'],closes:[1,2]}, {dates:['2020-01-01','2020-01-01'],closes:[1,2]}, {dates:['2020-01-01','2021-01-01'],closes:[1,Infinity]}, {dates:['2020-01-01'],closes:[1]}]) assert.throws(()=>Q.validateSeries(bad));assert.throws(()=>Q.historical(series,{amount:100,start:'2019-12-31',end:'2020-07-01'}));assert.throws(()=>Q.historical(series,{amount:100,start:'2020-01-02',end:'2020-01-02'}));assert.throws(()=>Q.historical(series,{amount:'100',start:'2020-01-01',end:'2021-01-01'}));const p=Q.project({amount:1000,years:2,annualReturn:.1,volatility:.2});near(p.mean,1210); near(p.roi,.21); near(p.median,1000*Math.exp((Math.log(1.1)-.02)*2));near(p.p10,1000*Math.exp((Math.log(1.1)-.02)*2-1.2815515655446004*.2*Math.sqrt(2)));near(p.p90,1000*Math.exp((Math.log(1.1)-.02)*2+1.2815515655446004*.2*Math.sqrt(2)));near(Q.project({amount:100,years:1,annualReturn:Math.exp(.02)-1,volatility:.2}).lossProbability,.5,1e-7);for(const r of [-.1,0,.1]) {const d=Q.project({amount:100,years:1/12,annualReturn:r,volatility:0}); near(d.mean,d.median); near(d.p10,d.p90); assert.equal(d.lossProbability,r<0?1:0);}assert.ok(p.points.length<=241); near(p.points[0].mean,1000); near(p.points.at(-1).mean,p.mean);for(const patch of [{amount:NaN},{amount:0},{amount:1e10},{years:0},{years:11},{annualReturn:-1},{annualReturn:3},{volatility:-1},{volatility:3}]) assert.throws(()=>Q.project({amount:1000,years:1,annualReturn:.1,volatility:.2,...patch}));const daily={dates:[],closes:[]}; for(let i=0;i<800;i++){daily.dates.push(new Date(Date.UTC(2021,0,1+i)).toISOString().slice(0,10));daily.closes.push(100*Math.exp(i*.001));}const e=Q.estimate(daily,{windowYears:1}); near(e.annualReturn,Math.expm1(.252)); near(e.volatility,0,1e-12); assert.equal(e.end,daily.dates.at(-1)); assert.ok(e.observations>=365&&e.observations<=367);assert.throws(()=>Q.estimate(series,{windowYears:1})); assert.throws(()=>Q.estimate(daily,{windowYears:2}));assert.deepEqual(Q.parseCSV('\ufeffdate,adj_close\r\n"2020-01-01","10"\r\n2020-01-02,11\r\n'),{dates:['2020-01-01','2020-01-02'],closes:[10,11]});assert.deepEqual(Q.parseCSV('Date,Close,Volume\n2020-01-01,10,"1,000"\n2020-01-02,11,2000'),{dates:['2020-01-01','2020-01-02'],closes:[10,11]});for(const csv of ['date,close\n2020-01-01,\n2020-01-02,2','date,close\n2020-01-01,1foo\n2020-01-02,2','date,close\n2020-02-30,1\n2020-03-01,2','date,close\n"2020-01-01,1\n2020-01-02,2','date,close,close\n2020-01-01,1,2\n2020-01-02,2,3']) assert.throws(()=>Q.parseCSV(csv));assert.throws(()=>Q.parseCSV(' '.repeat(2*1024*1024+1)));assert.throws(()=>Q.validateSeries({dates:new Array(2),closes:new Array(2)}));assert.throws(()=>Q.parseCSV('date,close\n'+Array.from({length:2501},(_,i)=>new Date(Date.UTC(2010,0,i+1)).toISOString().slice(0,10)+',1').join('\n')));const mixed={dates:daily.dates.slice(0,100),closes:Array.from({length:100},(_,i)=>100*Math.exp(.001*i+(i%2)*.01))};const logs=mixed.closes.slice(1).map((v,i)=>Math.log(v/mixed.closes[i])); const avg=logs.reduce((a,b)=>a+b,0)/logs.length; const variance=logs.reduce((a,b)=>a+(b-avg)**2,0)/(logs.length-1); const est=Q.estimate(mixed,{windowYears:1}); near(est.volatility,Math.sqrt(variance*252)); near(est.annualReturn,Math.expm1(avg*252+variance*126));console.log('Investment calculations: all assertions passed');DESIGN.md+10
INVESTMENT-VERIFICATION.mdAdded+49
MARKET-DATA.mdAdded+46
README.md+48
index.html+36-1
investment-ui.jsAdded+191
investment.cssAdded+8
investment.jsAdded+155
market-data.jsonAdded
scripts/check-investment-browser.cjsAdded+46
scripts/refresh-market-data.pyAdded+155
test_investment.cjsAdded+34