Every chart widget rendered only the baked-in 250-bar demo series: no set_series existed in Python despite the docstring naming it, so there was no way to plot real data at all. Now StockWidget holds up to three series slots (primary + two extra for the multi-symbol charts) via set_series (the C API), get_series, add_point, clear / populate, item_count, and load_csv; all 37 draw paths read the widget series through _bars(widget) instead of module DEMO_SERIES, so derived series (Heikin-Ashi, Renko, VWAP, OBV, ...) rebuild from the loaded data and the drawing tools inherit it as background. load_csv reads date,open,high,low,close,volume with the stdlib csv module: header optional (matched by name, any order, extra columns ignored), dates YYYY-MM-DD / YYYY/MM/DD / DD-MM-YYYY / ISO datetime / epoch seconds (validated, not stored -- the x-axis is bar index), ValueError naming the row on bad data. A cleared series draws a no-data placeholder; a one-bar series draws (Price: flat change). Tests: tests/test_stock_csv.py, 27 tests (parsing, API, headless renders of all 24 chart kinds incl. CSV-vs-template pixel diff). Fixture tests/data/ohlcv_30.csv (30 weekday bars). Full suite 311 tests pass; visreg 24/24 stock charts pixel-identical to template goldens. Docs: docs/stock-charts-data.md. Screenshots: tools/stock_csv_shots.py (Xvfb, RMSE 9-35% vs template goldens).
235 lines
8.6 KiB
Python
235 lines
8.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Screenshot every in-scope stock chart widget with CSV data loaded.
|
|
|
|
Takes each committed example in examples/<slug>.py, injects a
|
|
``widget.load_csv(...)`` call (plus slot 2/3 for the multi-symbol
|
|
charts) into its _build_widgets(), runs it under Xvfb, and screenshots
|
|
the root window cropped to the example window size -- the same render
|
|
path as the pythondoc sweep (drive.py run_one) and the visreg harness,
|
|
so the shots are directly comparable to the template-data goldens in
|
|
tools/visreg/goldens/.
|
|
|
|
Usage (on hot_newyork, from the repo root):
|
|
python3 tools/stock_csv_shots.py [--out-dir DIR] [--workers N]
|
|
[--csv PATH] [Kind ...]
|
|
|
|
Writes <slug>.png per widget into the out dir (default
|
|
/opt/lightgui-docs/pythondoc/work/csv-shots), plus report.json with
|
|
the ImageMagick RMSE of each CSV shot against its template golden
|
|
(large = the CSV data really is what is plotted).
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
sys.path.insert(0, REPO)
|
|
|
|
from lightgui.xframe import stock as stock_mod # noqa: E402
|
|
|
|
TOOL_KINDS = frozenset((
|
|
"Arrow", "Brush", "Ellipse", "FibExtension", "FibRetracement",
|
|
"HorizontalLine", "MeasureTool", "ParallelChannel", "Pitchfork",
|
|
"Rectangle", "TextAnnotation", "Trendline", "VerticalLine",
|
|
))
|
|
CHART_KINDS = sorted(stock_mod.STOCK_KINDS - TOOL_KINDS)
|
|
MULTI_KINDS = ("CorrelationView", "IndexedComparison",
|
|
"MultiSymbolChart", "OverlayChart", "RatioChart",
|
|
"RelativePerformance", "SectorComparison", "SpreadChart")
|
|
THREE_KINDS = ("MultiSymbolChart", "RelativePerformance",
|
|
"SectorComparison")
|
|
NAME_FOR_KIND = {"Price": "StockPriceLabel"}
|
|
DEFAULT_OUT = "/opt/lightgui-docs/pythondoc/work/csv-shots"
|
|
DEFAULT_CSV = os.path.join(REPO, "tests", "data", "ohlcv_30.csv")
|
|
|
|
|
|
def name_for(kind):
|
|
return NAME_FOR_KIND.get(kind, "Stock" + kind)
|
|
|
|
|
|
def win_size(kind):
|
|
from lightgui.xframe.palette import PALETTE
|
|
entry = next(e for e in PALETTE if e.name == name_for(kind))
|
|
return (max(entry.default_w + 32, 220),
|
|
max(entry.default_h + 32, 120))
|
|
|
|
|
|
def patched_example(kind, csv_path, tmpdir):
|
|
"""Copy the committed example, inject load_csv calls, return path."""
|
|
name = name_for(kind)
|
|
slug = name.lower()
|
|
src = os.path.join(REPO, "examples", slug + ".py")
|
|
with open(src, encoding="utf-8") as f:
|
|
code = f.read()
|
|
lines = [" widget.load_csv(%r)" % csv_path]
|
|
if kind in MULTI_KINDS:
|
|
lines.append(" widget.load_csv(%r, which=2)" % csv_path)
|
|
if kind in THREE_KINDS:
|
|
lines.append(" widget.load_csv(%r, which=3)" % csv_path)
|
|
anchor = " widget = create('%s', " % name
|
|
out_lines = []
|
|
injected = False
|
|
for line in code.split("\n"):
|
|
out_lines.append(line)
|
|
if not injected and line.startswith(anchor):
|
|
out_lines.extend(lines)
|
|
injected = True
|
|
if not injected:
|
|
raise RuntimeError("create() line not found in %s" % src)
|
|
path = os.path.join(tmpdir, slug + "_csv.py")
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
f.write("\n".join(out_lines))
|
|
return path
|
|
|
|
|
|
def wait_for_x(display, timeout=15):
|
|
sock = "/tmp/.X11-unix/X%d" % display
|
|
t0 = time.time()
|
|
while time.time() - t0 < timeout:
|
|
if os.path.exists(sock):
|
|
return True
|
|
time.sleep(0.2)
|
|
return False
|
|
|
|
|
|
def crop_to_window(path, kind):
|
|
from PIL import Image
|
|
w, h = win_size(kind)
|
|
im = Image.open(path)
|
|
im.crop((0, 0, min(w, im.width), min(h, im.height))).save(path)
|
|
|
|
|
|
def rmse_pct(golden, shot):
|
|
"""Normalised RMSE % between two PNGs (ImageMagick compare)."""
|
|
proc = subprocess.run(
|
|
["compare", "-metric", "RMSE", golden, shot, "null:"],
|
|
capture_output=True, text=True, timeout=60)
|
|
text = (proc.stderr or proc.stdout).strip()
|
|
m = re.search(r"\(([\d.]+)\)", text)
|
|
if not m:
|
|
return None
|
|
return round(float(m.group(1)) * 100, 2)
|
|
|
|
|
|
def run_one(kind, display, csv_path, outdir, tmpdir):
|
|
name = name_for(kind)
|
|
slug = name.lower()
|
|
result = {"kind": kind, "name": name, "slug": slug, "ok": False,
|
|
"reason": "", "shot": os.path.join(outdir, slug + ".png"),
|
|
"rmse_vs_template_pct": None}
|
|
try:
|
|
ex = patched_example(kind, csv_path, tmpdir)
|
|
except Exception as exc: # noqa: BLE001
|
|
result["reason"] = "patch failed: %r" % (exc,)
|
|
return result
|
|
chk = subprocess.run([sys.executable, "-m", "py_compile", ex],
|
|
capture_output=True, text=True, timeout=60)
|
|
if chk.returncode != 0:
|
|
result["reason"] = "py_compile failed: " + chk.stderr.strip()[:300]
|
|
return result
|
|
env = dict(os.environ)
|
|
env["DISPLAY"] = ":%d" % display
|
|
env["PYTHONPATH"] = REPO + os.pathsep + env.get("PYTHONPATH", "")
|
|
logp = os.path.join(tmpdir, slug + ".log")
|
|
png = result["shot"]
|
|
with open(logp, "w", encoding="utf-8") as logf:
|
|
proc = subprocess.Popen(
|
|
[sys.executable, ex], env=env,
|
|
stdout=logf, stderr=subprocess.STDOUT,
|
|
start_new_session=True)
|
|
try:
|
|
time.sleep(2.5)
|
|
if proc.poll() is not None:
|
|
result["reason"] = "exited early rc=%s; log: %s" % (
|
|
proc.returncode,
|
|
open(logp, encoding="utf-8",
|
|
errors="replace").read()[-400:])
|
|
return result
|
|
shot = subprocess.run(
|
|
["import", "-window", "root", png], env=env,
|
|
capture_output=True, text=True, timeout=30)
|
|
if shot.returncode != 0 or not os.path.exists(png):
|
|
result["reason"] = "screenshot failed: " + shot.stderr[:300]
|
|
return result
|
|
crop_to_window(png, kind)
|
|
finally:
|
|
try:
|
|
os.killpg(proc.pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
pass
|
|
golden = os.path.join(REPO, "tools", "visreg", "goldens",
|
|
slug + ".png")
|
|
if os.path.exists(golden):
|
|
result["rmse_vs_template_pct"] = rmse_pct(golden, png)
|
|
result["ok"] = True
|
|
return result
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--out-dir", default=DEFAULT_OUT)
|
|
parser.add_argument("--workers", type=int, default=6)
|
|
parser.add_argument("--csv", default=DEFAULT_CSV)
|
|
parser.add_argument("kinds", nargs="*", default=CHART_KINDS)
|
|
args = parser.parse_args()
|
|
wanted = []
|
|
registry_to_kind = {name_for(k): k for k in CHART_KINDS}
|
|
for k in args.kinds:
|
|
kind = registry_to_kind.get(k, k[5:] if k.startswith("Stock")
|
|
else k)
|
|
if kind in CHART_KINDS and kind not in wanted:
|
|
wanted.append(kind)
|
|
kinds = wanted
|
|
if not kinds:
|
|
print("no in-scope kinds requested")
|
|
return 1
|
|
os.makedirs(args.out_dir, exist_ok=True)
|
|
tmpdir = os.path.join(args.out_dir, ".tmp")
|
|
os.makedirs(tmpdir, exist_ok=True)
|
|
displays = [131 + i for i in range(args.workers)]
|
|
procs = []
|
|
for d in displays:
|
|
procs.append(subprocess.Popen(
|
|
["Xvfb", ":%d" % d, "-screen", "0", "1280x900x24"],
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
|
|
try:
|
|
for d in displays:
|
|
if not wait_for_x(d):
|
|
print("Xvfb :%d did not come up" % d)
|
|
return 1
|
|
# Round-robin the kinds over the displays, sequentially per
|
|
# display (each run needs its own display; 2.5 s settle each).
|
|
results = []
|
|
for i, kind in enumerate(kinds):
|
|
display = displays[i % len(displays)]
|
|
print("[%d/%d] %s on :%d" % (i + 1, len(kinds), kind, display),
|
|
flush=True)
|
|
results.append(run_one(kind, display, args.csv,
|
|
args.out_dir, tmpdir))
|
|
finally:
|
|
for p in procs:
|
|
p.terminate()
|
|
ok = [r for r in results if r["ok"]]
|
|
print("shots: ok=%d fail=%d" % (len(ok), len(results) - len(ok)))
|
|
for r in results:
|
|
if r["ok"]:
|
|
print(" OK %-28s RMSE vs template: %s%%" % (
|
|
r["kind"],
|
|
r["rmse_vs_template_pct"] if r["rmse_vs_template_pct"]
|
|
is not None else "?"))
|
|
else:
|
|
print(" FAIL %-28s %s" % (r["kind"], r["reason"]))
|
|
with open(os.path.join(args.out_dir, "report.json"), "w",
|
|
encoding="utf-8") as f:
|
|
json.dump(results, f, indent=1)
|
|
return 0 if len(ok) == len(results) else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|