quantlab-probability-research / scripts /check-investment-browser.cjs
PabloRod11's picture
Add animated investment charts and ticker ROI explorer
6fcb807 verified
Raw History Blame Contribute Delete
11.3 kB
'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)});