app: background cache refresh, per-benchmark stats, correlation tab, global date range

- data.py: non-blocking load_bundle(); background watcher thread refreshes
  the parquet cache (5s scan, 30s min rebuild cadence); refresh()/
  up_to_date()/generation()
- statistics tab: one table per benchmark (vs <label>), plain column names
  (beta/alpha/return/vol...), selectable+reorderable stat list in
  settings.json
- correlation tab: per-portfolio components-vs-benchmarks +
  all-portfolios-vs-benchmarks; numbered columns
- global date range (window radio + start/end boxes) applied to all tabs;
  metrics.xcorr(); equity window radio gains YTD/3M/1M
This commit is contained in:
gmp
2026-08-25 18:15:47 -04:00
parent cba7291676
commit 4f36bc7aea
6 changed files with 403 additions and 81 deletions
+85 -14
View File
@@ -104,25 +104,91 @@ def _run() -> None:
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))
blocks = [d.value for d in app().main.tabs[0].dataframe]
check("one stats block per benchmark", not app().exception
and len(blocks) == 2, f"{len(blocks)} blocks")
check("each block lists its own benchmark",
"benchmark: v" in list(blocks[0].index)
and "benchmark: googl, amzn" in list(blocks[1].index))
check("per-block beta columns (no suffix)",
"beta" in blocks[0].columns and "beta" in blocks[1].columns
and not any("[" in c for c in blocks[0].columns))
corr_blocks = [d.value for d in app().main.tabs[4].dataframe]
check("single-component portfolio: no components table",
len(corr_blocks) == 1,
f"{len(corr_blocks)} blocks")
check("all-portfolios cross-correlation table",
"Current" in corr_blocks[0].index and "benchmark: v" in corr_blocks[0].index
and list(corr_blocks[0].columns) == [1, 2, 3]
and abs(float(corr_blocks[0].loc["Current", 1]) - 1.0) < 1e-9)
run_app("MSFT:0.5,goog:0.5", "V")
corr_blocks = [d.value for d in app().main.tabs[4].dataframe]
corr, allcorr = corr_blocks[0], corr_blocks[-1]
check("multi-component portfolio gets a components table",
len(corr_blocks) == 2
and "msft" in corr.index and "goog" in corr.index
and "benchmark: v" in corr.index
and list(corr.columns) == [1, 2, 3]
and abs(float(corr.loc["msft", 1]) - 1.0) < 1e-9)
run_app("MSFT", "V zzzznope")
rows = list(app().main.tabs[0].dataframe[0].value.index)
blocks = [d.value for d in app().main.tabs[0].dataframe]
rows = list(blocks[0].index) if blocks else []
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)
and len(blocks) == 1 and "benchmark: v" in rows)
run_app("MSFT:0.6,V:0.4", "V")
rows = list(app().main.tabs[0].dataframe[0].value.index)
blocks = [d.value for d in app().main.tabs[0].dataframe]
rows = list(blocks[0].index) if blocks else []
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("statistics order", flush=True)
run_app("MSFT", "V", stats_order="sharpe,calmar")
cols = list(app().main.tabs[0].dataframe[0].value.columns)
check("stats columns follow configured order",
not app().exception and cols == ["sharpe", "calmar"], str(cols))
run_app("MSFT", "V", stats_order="sharpe,nonsense")
cols = list(app().main.tabs[0].dataframe[0].value.columns)
check("unknown statistic warned and ignored",
cols == ["sharpe"]
and any("nonsense" in w.value for w in app().sidebar.warning), str(cols))
run_app("MSFT", "V", stats_order="")
cols = list(app().main.tabs[0].dataframe[0].value.columns)
check("empty field shows all in default order",
len(cols) == 10 and cols[0] == "total_return" and "beta" in cols
and "return" in cols and "vol" in cols and "alpha" in cols
and "ann_return" not in cols and "ann_vol" not in cols,
str(cols))
run_app("MSFT", "V", stats_order="ann_return,ann_vol,alpha_ann")
cols = list(app().main.tabs[0].dataframe[0].value.columns)
check("old statistic names migrated", cols == ["return", "vol", "alpha"],
str(cols))
print("date range", flush=True)
# total_return (cumulative) is range-sensitive; the annualized 'return'
# can coincidentally match at 1-decimal precision
_so = "total_return" # pin: earlier tests persist other selections
run_app("MSFT", "V", stats_order=_so)
full_ret = app().main.tabs[0].dataframe[0].value.loc["Current", "total_return"]
run_app("MSFT", "V", stats_order=_so, range_end="20151231")
ret = app().main.tabs[0].dataframe[0].value.loc["Current", "total_return"]
check("end date limits the statistics", not app().exception
and ret != full_ret, f"{ret} vs {full_ret}")
run_app("MSFT", "V", stats_order=_so, range_start="20120102")
ret = app().main.tabs[0].dataframe[0].value.loc["Current", "total_return"]
check("start date overrides the window", not app().exception
and ret != full_ret, f"{ret} vs {full_ret}")
run_app("MSFT", "V", stats_order=_so, date_window="1Y")
ret = app().main.tabs[0].dataframe[0].value.loc["Current", "total_return"]
check("window applies to the statistics", not app().exception
and ret != full_ret, f"{ret} vs {full_ret}")
run_app("MSFT", "V", stats_order=_so, range_start="notadate")
check("invalid start date warns and is ignored",
not app().exception
and any("Invalid start date" in w.value for w in app().sidebar.warning))
print("curve mode", flush=True)
for mode, suffixed in (("Pre-tax", False), ("After-tax", False),
("Pre-tax + after-tax", True)):
@@ -163,15 +229,20 @@ def _run() -> None:
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")
curve_mode="After-tax", date_window="5Y",
range_start="20120102", range_end="", stats_order="sharpe,vol")
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))
s.get("curve_mode") == "After-tax" and s.get("date_window") == "5Y" and
s.get("range_start") == "20120102" and s.get("stats_order") == "sharpe,vol",
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")}
ti = {t.key: t.value for t in app().sidebar.text_input
if t.key in ("spec", "bench_spec", "range_start")}
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))
ti == {"spec": "MSFT:0.6,V:0.4", "bench_spec": "googl:0.5,amzn:0.5 v",
"range_start": "20120102"}, str(ti))
if __name__ == "__main__":
+22 -1
View File
@@ -11,6 +11,7 @@ import pathlib
import shutil
import sys
import tempfile
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
@@ -49,10 +50,13 @@ def touch(p: pathlib.Path) -> None:
def reload(d: pathlib.Path) -> D.Bundle:
return D.load_bundle(root=d["root"], cache=d["cache"])
# refresh() is the synchronous path: deterministic for these assertions
return D.refresh(root=d["root"], cache=d["cache"])
def main() -> int:
# fast watcher for the background-refresh test below
D.WATCH_INTERVAL, D.REFRESH_CADENCE = 0.2, 0.0
tmp = pathlib.Path(tempfile.mkdtemp(prefix="fdatatest-"))
root, cache = tmp / "stocks", tmp / "cache"
root.mkdir()
@@ -107,6 +111,23 @@ def main() -> int:
after = (cache / "panel_adj.parquet").stat().st_mtime_ns
check("no-op reload does not rewrite parquet", before == after)
# --- background refresh: load_bundle never blocks on changed data;
# it serves the current bundle and a background thread catches up
f = write_history(root, "aaa", last_price=300.0)
touch(f)
t0 = time.monotonic()
b = D.load_bundle(root=root, cache=cache)
check("load_bundle returns immediately on changed data",
time.monotonic() - t0 < 2.0)
deadline = time.monotonic() + 15.0
while time.monotonic() < deadline:
b = D.load_bundle(root=root, cache=cache)
if b.adj["aaa"].iloc[-1] == 300.0:
break
time.sleep(0.2)
check("background thread picks up the change", b.adj["aaa"].iloc[-1] == 300.0)
check("generation counter advances", D.generation(root=root, cache=cache) >= 1)
# --- forced full rebuild still works
b = D.load_bundle(root=root, cache=cache, rebuild=True)
check("forced full rebuild", list(b.adj.columns) == ["aaa", "bbb", "ddd"])