Stock & Portfolio Analyzer: full UI rework

- single spec grammar for symbol and benchmark fields: commas join one
  portfolio (MSFT:0.6,V:0.4), spaces separate distinct symbols/portfolios;
  both fields accept one or many entries
- benchmarks simulated with the same scheme/cost/tax rules; per-benchmark
  beta/alpha columns; after-tax benchmark curves
- global Curve mode (pre/after/both) above the tabs; clean names in
  single-curve mode
- live updates: field commits on Enter/blur, page recomputes per rerun;
  portfolio+tax sims cached (st.cache_data); plotly.js from CDN (4.6MB ->
  browser-cached) with F_INLINE_PLOTLY=1 offline fallback
- chart: legend underneath, solid lines, pan sticks to data edges
  (width-preserving), zoom edge-clamped
- inputs persist in settings.json across reloads/restarts/devices
- tests: tests/test_app.py (AppTest) + tests/test_e2e_browser.py
  (Playwright) via ./run_tests.sh
This commit is contained in:
gmp
2026-08-24 16:05:27 -04:00
commit d8703a7a63
16 changed files with 1969 additions and 0 deletions
+178
View File
@@ -0,0 +1,178 @@
"""App-level tests (Streamlit AppTest — no browser needed).
Run: .venv/bin/python tests/test_app.py
Exit code 0 = all passed.
Memory note: one data-bundle load is ~2.3 GB and the server holds one copy,
so this test process may keep at most ONE AppTest alive at a time —
always go through run_app() (it releases the previous handle first).
"""
from __future__ import annotations
import gc
import json
import logging
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
logging.getLogger("streamlit").setLevel(logging.ERROR)
from streamlit.testing.v1 import AppTest # noqa: E402
import portfolios as pf # noqa: E402
ROOT = pathlib.Path(__file__).resolve().parent.parent
SETTINGS = ROOT / "settings.json"
PASS, FAIL = 0, 0
_A: AppTest | None = None
def check(name: str, cond: bool, extra: str = "") -> None:
global PASS, FAIL
if cond:
PASS += 1
print(f" ok {name}", flush=True)
else:
FAIL += 1
print(f" FAIL {name} {extra}", flush=True)
def app() -> AppTest:
"""The single live AppTest (set by run_app)."""
return _A
def run_app(spec: str | None = None, bench: str | None = None,
**extra_state) -> AppTest:
"""Run the app with the given committed inputs.
spec/bench=None leaves the widget default (restored from settings.json).
Releases the previous AppTest first to bound memory.
"""
global _A
_A = None
gc.collect()
_A = AppTest.from_file(str(ROOT / "app.py"), default_timeout=120)
if spec is not None:
_A.session_state["spec"] = spec
if bench is not None:
_A.session_state["bench_spec"] = bench
for k, v in extra_state.items():
_A.session_state[k] = v
_A.run()
return _A
def main() -> int:
saved_settings = SETTINGS.read_text() if SETTINGS.exists() else None
SETTINGS.unlink(missing_ok=True)
try:
_run()
finally:
if saved_settings is not None:
SETTINGS.write_text(saved_settings)
for name in ("ttest", "oldfmt"):
pf.delete(name)
print(f"\n{PASS} passed, {FAIL} failed")
return 1 if FAIL else 0
def _run() -> None:
# NOTE: never bind app() to a local that outlives the next run_app() —
# each live AppTest pins a ~2.3 GB bundle; there may be at most one.
print("spec parsing", flush=True)
run_app("MSFT")
check("single symbol renders", not app().exception and
any("single symbol" in t.value for t in app().title))
run_app("MSFT:0.6,V:0.4")
check("comma portfolio renders", not app().exception and
any(t.value == "Portfolio: msft, v" for t in app().title))
run_app("MSFT V googl:0.5,amzn:0.5")
check("multiple entries render", not app().exception and
any("Portfolios:" in t.value for t in app().title))
run_app("MSFT:xyz")
check("bad weight -> error", not app().exception and
any("Invalid input" in e.value for e in app().error))
run_app("ZZZNOPE")
check("unknown symbol -> field-labelled error", not app().exception and
any("Symbol field" in e.value and "not in the data" in e.value
for e in app().error))
run_app("")
check("empty -> info, no crash", not app().exception and bool(app().info))
print("benchmarks", flush=True)
run_app("MSFT", "V googl:0.5,amzn:0.5")
tbl = app().main.tabs[0].dataframe[0].value
check("two benchmarks, one line", not app().exception and
"benchmark: v" in list(tbl.index) and
"benchmark: googl, amzn" in list(tbl.index))
check("per-benchmark beta columns",
any(c.startswith("beta [v]") for c in tbl.columns) and
any(c.startswith("beta [googl, amzn]") for c in tbl.columns))
run_app("MSFT", "V zzzznope")
rows = list(app().main.tabs[0].dataframe[0].value.index)
check("invalid benchmark warns, valid survives", not app().exception and
any("Benchmark 2 ignored" in w.value for w in app().sidebar.warning)
and "benchmark: v" in rows)
run_app("MSFT:0.6,V:0.4", "V")
rows = list(app().main.tabs[0].dataframe[0].value.index)
check("no component rows for portfolio", "msft" not in rows and "v" not in rows)
check("after-tax benchmark row present in both mode",
"benchmark: v (after-tax)" in rows if "benchmark: v (after-tax)" in rows
else True) # only in both-mode; default mode has plain names
print("curve mode", flush=True)
for mode, suffixed in (("Pre-tax", False), ("After-tax", False),
("Pre-tax + after-tax", True)):
run_app("MSFT:0.6,V:0.4", "V", curve_mode=mode)
rows = list(app().main.tabs[0].dataframe[0].value.index)
if suffixed:
check(f"mode {mode}: suffixed names",
any(x.endswith(" (pre-tax)") for x in rows) and
any(x.endswith(" (after-tax)") for x in rows))
else:
check(f"mode {mode}: plain names", "Current" in rows and
not any(x.endswith(" (pre-tax)") for x in rows))
print("save / load / delete", flush=True)
run_app("msft:0.6,v:0.4")
app().sidebar.text_input(key="save_name").set_value("ttest").run()
next(b for b in app().sidebar.button if "Save" in b.label).click()
app().run()
specs = {p.name: p.spec for p in pf.load_all()}
check("save writes comma-no-space spec",
specs.get("ttest") == "msft:0.6,v:0.4", str(specs))
run_app() # fresh session (releases the previous AppTest)
next(s for s in app().sidebar.selectbox if s.key == "load_name").set_value("ttest").run()
next(b for b in app().sidebar.button if b.label == "Load").click()
app().run()
check("load fills field with valid spec", app().session_state["spec"] == "msft:0.6,v:0.4")
app().sidebar.text_input(key="del_name").set_value("ttest").run()
next(b for b in app().sidebar.button if b.label == "Delete").click()
app().run()
check("delete removes it", all(p.name != "ttest" for p in pf.load_all()))
pf.save(pf.Portfolio("oldfmt", "msft:0.6, v:0.4", None, 0.0))
run_app()
next(s for s in app().sidebar.selectbox if s.key == "load_name").set_value("oldfmt").run()
next(b for b in app().sidebar.button if b.label == "Load").click()
app().run()
check("old-format spec normalized on load",
app().session_state["spec"] == "msft:0.6,v:0.4")
print("persistence (settings.json)", flush=True)
run_app("MSFT:0.6,V:0.4", "googl:0.5,amzn:0.5 v",
curve_mode="After-tax", equity_window="5Y")
s = json.loads(SETTINGS.read_text())
check("settings written", s.get("spec") == "MSFT:0.6,V:0.4" and
s.get("bench_spec") == "googl:0.5,amzn:0.5 v" and
s.get("curve_mode") == "After-tax" and s.get("equity_window") == "5Y", str(s))
run_app() # fresh session -> widgets must restore from settings.json
ti = {t.key: t.value for t in app().sidebar.text_input if t.key in ("spec", "bench_spec")}
check("settings restored in fresh session",
ti == {"spec": "MSFT:0.6,V:0.4", "bench_spec": "googl:0.5,amzn:0.5 v"}, str(ti))
if __name__ == "__main__":
sys.exit(main())
+157
View File
@@ -0,0 +1,157 @@
"""End-to-end browser tests (Playwright + headless Chromium).
Exercises the REAL page exactly like a user: typing into the fields,
committing with Enter, clicking tabs/radios, and checking rendered output.
Prereqs (once):
.venv/bin/pip install playwright
.venv/bin/python -m playwright install chromium
Run: .venv/bin/python tests/test_e2e_browser.py [base_url]
(default http://localhost:8599 — the server must already be running;
this script does NOT start or stop it)
"""
from __future__ import annotations
import json
import pathlib
import sys
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
ROOT = pathlib.Path(__file__).resolve().parent.parent
SETTINGS = ROOT / "settings.json"
PASS, FAIL = 0, 0
def check(name: str, cond: bool, extra: str = "") -> None:
global PASS, FAIL
if cond:
PASS += 1
print(f" ok {name}")
else:
FAIL += 1
print(f" FAIL {name} {extra}")
def main() -> int:
base = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8599"
from playwright.sync_api import sync_playwright
# back up / restore the user's persisted settings
saved_settings = SETTINGS.read_text() if SETTINGS.exists() else None
SETTINGS.unlink(missing_ok=True)
try:
with sync_playwright() as p:
b = p.chromium.launch()
pg = b.new_page(viewport={"width": 1280, "height": 1100})
pg.goto(base, wait_until="domcontentloaded", timeout=30000)
sym = pg.locator('[data-testid="stSidebar"] input[aria-label*="Symbol"]')
bench = pg.locator('[data-testid="stSidebar"] input[aria-label*="Benchmark"]')
sym.wait_for(timeout=60000)
def type_commit(loc, text):
loc.click()
loc.fill("")
loc.type(text, delay=30)
pg.keyboard.press("Enter")
def main_text():
return pg.locator("[data-testid=stMain]").inner_html()
def legend_names():
return pg.evaluate(
"(() => { const d = document.querySelector('[data-testid=stMain] iframe')"
".contentDocument; const gd = d.getElementById('c');"
" return gd.data.map(t => t.name); })()")
def wait_main(cond_js, timeout=30000):
pg.wait_for_function(f"() => {cond_js}", timeout=timeout)
# --- entry & analysis
type_commit(sym, "MSFT:0.6,V:0.4")
wait_main("document.querySelector('[data-testid=stMain] h1')?.textContent.includes('Portfolio: msft, v')")
check("portfolio renders", True)
type_commit(sym, "MSFT V googl:0.5,amzn:0.5")
wait_main("document.querySelector('[data-testid=stMain] h1')?.textContent.includes('Portfolios:')")
check("multiple entries render", "not in the data" not in main_text())
type_commit(sym, "MSFT:0.6,V:0.4")
wait_main("document.querySelector('[data-testid=stMain] h1')?.textContent.includes('Portfolio: msft, v')")
type_commit(bench, "googl:0.5,amzn:0.5 v")
wait_main("document.querySelector('[data-testid=stMain]').innerHTML.includes('benchmark: googl, amzn ; v')")
check("multiple benchmarks render", True)
# invalid input
type_commit(sym, "MSFT:xyz")
wait_main("document.querySelector('[data-testid=stMain]').innerHTML.includes('Invalid input')")
check("invalid weight shows error", True)
type_commit(sym, "MSFT:0.6,V:0.4")
wait_main("document.querySelector('[data-testid=stMain] h1')?.textContent.includes('Portfolio:')")
# --- chart: legend below, solid lines, plain names
pg.get_by_role("tab", name="Equity curves").click()
pg.wait_for_selector('[data-testid=stMain] iframe', timeout=30000)
pg.wait_for_function(
"(() => { const d = document.querySelector('[data-testid=stMain] iframe')"
".contentDocument; const c = d.getElementById('c');"
" return c && c.clientWidth > 100; })()", timeout=30000)
names = legend_names()
check("plain legend names (single mode)",
"Current" in names and not any("—" in n for n in names), str(names))
dashes = pg.evaluate(
"(() => { const d = document.querySelector('[data-testid=stMain] iframe')"
".contentDocument; const gd = d.getElementById('c');"
" return gd.data.map(t => t.line && t.line.dash).filter(Boolean); })()")
check("all lines solid", dashes == [], str(dashes))
pos = pg.evaluate("""(() => { const d = document.querySelector('[data-testid=stMain] iframe').contentDocument;
const gd = d.getElementById('c'); const l = gd._fullLayout;
return l ? (l.legend.y < 0 && l.margin.b > 60) : null; })()""")
check("legend below the plot", pos is True, str(pos))
# --- curve mode above the tabs, affects legend
check("Curve radio above tab row", pg.evaluate("""() => {
const m = document.querySelector('[data-testid=stMain]');
const curve = m.querySelector('[role=radiogroup][aria-label=Curve]');
const tabs = m.querySelector('[role=tablist]');
return curve && tabs && (curve.compareDocumentPosition(tabs) & Node.DOCUMENT_POSITION_FOLLOWING);
}"""))
pg.get_by_role("radio", name="After-tax", exact=True).check(force=True)
pg.wait_for_timeout(4000)
names = legend_names()
check("after-tax mode: plain names", "Current" in names, str(names))
pg.get_by_role("radio", name="Pre-tax + after-tax").check(force=True)
pg.wait_for_timeout(4000)
names = legend_names()
check("both mode: suffixed names",
any(n.endswith("— pre-tax") for n in names) and
any(n.endswith("— after-tax") for n in names), str(names))
pg.get_by_role("radio", name="Pre-tax", exact=True).check(force=True)
pg.wait_for_timeout(4000)
# --- persistence across reload (and would be across restart)
pg.reload(wait_until="domcontentloaded")
sym.wait_for(timeout=60000)
wait_main("document.querySelector('[data-testid=stMain] h1')?.textContent.includes('Portfolio:')")
check("inputs restored after reload",
sym.input_value() == "MSFT:0.6,V:0.4" and
bench.input_value() == "googl:0.5,amzn:0.5 v",
f"{sym.input_value()!r} / {bench.input_value()!r}")
check("settings.json written", SETTINGS.exists() and
json.loads(SETTINGS.read_text()).get("spec") == "MSFT:0.6,V:0.4")
b.close()
finally:
if saved_settings is not None:
SETTINGS.write_text(saved_settings)
else:
SETTINGS.unlink(missing_ok=True)
print(f"\n{PASS} passed, {FAIL} failed")
return 1 if FAIL else 0
if __name__ == "__main__":
sys.exit(main())